openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.0.0-beta.1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Utility/ServerSentEventEnumerable.cs

81lines · modeblame

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