openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Utility/ServerSentEventEnumerable.cs
81lines · modecode
| 1 | using System; |
| 2 | using System.Collections; |
| 3 | using System.Collections.Generic; |
| 4 | using System.IO; |
| 5 | using System.Threading; |
| 6 | |
| 7 | #nullable enable |
| 8 | |
| 9 | namespace OpenAI; |
| 10 | |
| 11 | /// <summary> |
| 12 | /// Represents a collection of SSE events that can be enumerated as a C# collection. |
| 13 | /// </summary> |
| 14 | internal class ServerSentEventEnumerable : IEnumerable<ServerSentEvent> |
| 15 | { |
| 16 | private readonly Stream _contentStream; |
| 17 | |
| 18 | public ServerSentEventEnumerable(Stream contentStream) |
| 19 | { |
| 20 | Argument.AssertNotNull(contentStream, nameof(contentStream)); |
| 21 | |
| 22 | _contentStream = contentStream; |
| 23 | |
| 24 | LastEventId = string.Empty; |
| 25 | ReconnectionInterval = Timeout.InfiniteTimeSpan; |
| 26 | } |
| 27 | |
| 28 | public string LastEventId { get; private set; } |
| 29 | |
| 30 | public TimeSpan ReconnectionInterval { get; private set; } |
| 31 | |
| 32 | public IEnumerator<ServerSentEvent> GetEnumerator() |
| 33 | { |
| 34 | return new ServerSentEventEnumerator(_contentStream, this); |
| 35 | } |
| 36 | |
| 37 | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| 38 | |
| 39 | private sealed class ServerSentEventEnumerator : IEnumerator<ServerSentEvent> |
| 40 | { |
| 41 | private readonly ServerSentEventReader _reader; |
| 42 | private readonly ServerSentEventEnumerable _enumerable; |
| 43 | |
| 44 | public ServerSentEventEnumerator(Stream contentStream, ServerSentEventEnumerable enumerable) |
| 45 | { |
| 46 | _reader = new(contentStream); |
| 47 | _enumerable = enumerable; |
| 48 | } |
| 49 | |
| 50 | public ServerSentEvent Current { get; private set; } |
| 51 | |
| 52 | object IEnumerator.Current => Current; |
| 53 | |
| 54 | public bool MoveNext() |
| 55 | { |
| 56 | ServerSentEvent? nextEvent = _reader.TryGetNextEvent(); |
| 57 | _enumerable.LastEventId = _reader.LastEventId; |
| 58 | _enumerable.ReconnectionInterval = _reader.ReconnectionInterval; |
| 59 | |
| 60 | if (nextEvent.HasValue) |
| 61 | { |
| 62 | Current = nextEvent.Value; |
| 63 | return true; |
| 64 | } |
| 65 | |
| 66 | Current = default; |
| 67 | return false; |
| 68 | } |
| 69 | |
| 70 | public void Reset() |
| 71 | { |
| 72 | throw new NotSupportedException("Cannot seek back in an SSE stream."); |
| 73 | } |
| 74 | |
| 75 | public void Dispose() |
| 76 | { |
| 77 | // The creator of the enumerable has responsibility for disposing |
| 78 | // the content stream passed to the enumerable constructor. |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |