| | | 1 | | using Anichron.API.Settings; |
| | | 2 | | using Anichron.Core.Work; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using NodaTime.Text; |
| | | 5 | | using System.Net.ServerSentEvents; |
| | | 6 | | using System.Runtime.CompilerServices; |
| | | 7 | | |
| | | 8 | | namespace Anichron.API.Endpoints; |
| | | 9 | | |
| | 14 | 10 | | public sealed class WorkItemEvents(IWorkItemReader reader, TimeProvider time, IOptions<WorkItemEventsSettings> settings) |
| | | 11 | | { |
| | | 12 | | internal const string EventType = "work-item"; |
| | | 13 | | |
| | 17 | 14 | | internal static Duration Lookback => Duration.FromSeconds(10); |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Every work item that changes from the cursor on, re-queried at the configured interval. Each |
| | | 18 | | /// event's id is the cursor after it, so a reconnect that sends it as Last-Event-ID resumes there. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="lastEventId">The cursor to resume from; without a readable one, the latest change.</param> |
| | | 21 | | /// <param name="ct">Ends the stream.</param> |
| | | 22 | | /// <returns>One event per changed item; an item may arrive twice, never not at all.</returns> |
| | | 23 | | public async IAsyncEnumerable<SseItem<WorkItemDto>> StreamAsync( |
| | | 24 | | string? lastEventId, [EnumeratorCancellation] CancellationToken ct) |
| | 13 | 25 | | { |
| | 13 | 26 | | var cursor = Parse(lastEventId) ?? await reader.LatestUpdateAsync(ct) ?? NodaConstants.UnixEpoch; |
| | 13 | 27 | | var interval = TimeSpan.FromSeconds(settings.Value.IntervalSeconds); |
| | 13 | 28 | | var sent = new HashSet<(Guid, Instant)>(); |
| | 17 | 29 | | while (!ct.IsCancellationRequested) |
| | 17 | 30 | | { |
| | 17 | 31 | | var changed = await reader.UpdatedSinceAsync(cursor - Lookback, ct); |
| | 73 | 32 | | foreach (var item in changed.Where(item => !sent.Contains((item.Id, item.UpdatedAt)))) |
| | 11 | 33 | | { |
| | 11 | 34 | | cursor = Instant.Max(cursor, item.UpdatedAt); |
| | 11 | 35 | | yield return new SseItem<WorkItemDto>(WorkItemDtoMapper.ToDto(item), EventType) |
| | 11 | 36 | | { |
| | 11 | 37 | | EventId = WorkItemDtoMapper.Format(cursor), |
| | 11 | 38 | | }; |
| | 11 | 39 | | } |
| | | 40 | | |
| | 17 | 41 | | sent = [.. changed.Select(item => (item.Id, item.UpdatedAt))]; |
| | 17 | 42 | | await Task.Delay(interval, time, ct); |
| | 4 | 43 | | } |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | private static Instant? Parse(string? lastEventId) |
| | 13 | 47 | | => lastEventId is not null && InstantPattern.ExtendedIso.Parse(lastEventId) is { Success: true } parsed |
| | 13 | 48 | | ? parsed.Value |
| | 13 | 49 | | : null; |
| | | 50 | | } |