-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathTestSseEventStreamStore.cs
More file actions
290 lines (246 loc) · 9.73 KB
/
TestSseEventStreamStore.cs
File metadata and controls
290 lines (246 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Collections.Concurrent;
using System.Net.ServerSentEvents;
using System.Runtime.CompilerServices;
namespace ModelContextProtocol.AspNetCore.Tests.Utils;
/// <summary>
/// In-memory event store for testing resumability.
/// This is a simple implementation intended for testing, not for production use.
/// </summary>
public sealed class TestSseEventStreamStore : ISseEventStreamStore
{
private readonly ConcurrentDictionary<string, StreamState> _streams = new();
private readonly ConcurrentDictionary<string, (StreamState Stream, long Sequence)> _eventLookup = new();
private readonly List<string> _storedEventIds = [];
private readonly List<TimeSpan> _storedReconnectionIntervals = [];
private readonly object _storedEventIdsLock = new();
private int _storeEventCallCount;
private long _globalSequence;
/// <summary>
/// Gets the number of times events have been stored.
/// </summary>
public int StoreEventCallCount => _storeEventCallCount;
/// <summary>
/// Gets the list of stored event IDs in order.
/// </summary>
public IReadOnlyList<string> StoredEventIds
{
get
{
lock (_storedEventIdsLock)
{
return [.. _storedEventIds];
}
}
}
/// <summary>
/// Gets the list of stored reconnection intervals in order.
/// </summary>
public IReadOnlyList<TimeSpan> StoredReconnectionIntervals
{
get
{
lock (_storedEventIdsLock)
{
return [.. _storedReconnectionIntervals];
}
}
}
/// <inheritdoc />
public ValueTask<ISseEventStreamWriter> CreateStreamAsync(SseEventStreamOptions options, CancellationToken cancellationToken = default)
{
var streamKey = GetStreamKey(options.SessionId, options.StreamId);
var state = new StreamState(options.SessionId, options.StreamId, options.Mode);
if (!_streams.TryAdd(streamKey, state))
{
throw new InvalidOperationException($"A stream with key '{streamKey}' has already been created.");
}
var writer = new InMemoryEventStreamWriter(this, state);
return new ValueTask<ISseEventStreamWriter>(writer);
}
/// <inheritdoc />
public ValueTask<ISseEventStreamReader?> GetStreamReaderAsync(string lastEventId, CancellationToken cancellationToken = default)
{
// Look up the event by its ID to find which stream it belongs to
if (!_eventLookup.TryGetValue(lastEventId, out var lookup))
{
return new ValueTask<ISseEventStreamReader?>((ISseEventStreamReader?)null);
}
var reader = new InMemoryEventStreamReader(lookup.Stream, lookup.Sequence);
return new ValueTask<ISseEventStreamReader?>(reader);
}
private string GenerateEventId() => Interlocked.Increment(ref _globalSequence).ToString();
private void TrackEvent(string eventId, StreamState stream, long sequence, TimeSpan? reconnectionInterval = null)
{
_eventLookup[eventId] = (stream, sequence);
lock (_storedEventIdsLock)
{
_storedEventIds.Add(eventId);
if (reconnectionInterval.HasValue)
{
_storedReconnectionIntervals.Add(reconnectionInterval.Value);
}
}
Interlocked.Increment(ref _storeEventCallCount);
}
/// <inheritdoc />
public ValueTask DeleteStreamsForSessionAsync(string sessionId, CancellationToken cancellationToken = default)
{
// Find all streams belonging to this session
var keysToRemove = _streams.Keys.Where(k => k.StartsWith($"{sessionId}:", StringComparison.Ordinal)).ToList();
foreach (var key in keysToRemove)
{
if (_streams.TryRemove(key, out var state))
{
// Remove all events belonging to this stream from the event lookup
var eventKeysToRemove = _eventLookup.Where(kvp => kvp.Value.Stream == state).Select(kvp => kvp.Key).ToList();
foreach (var eventKey in eventKeysToRemove)
{
_eventLookup.TryRemove(eventKey, out _);
}
}
}
return default;
}
private static string GetStreamKey(string sessionId, string streamId) => $"{sessionId}:{streamId}";
/// <summary>
/// Holds the state for a single stream.
/// </summary>
private sealed class StreamState
{
private readonly List<(SseItem<JsonRpcMessage?> Item, long Sequence)> _events = [];
private readonly object _lock = new();
private TaskCompletionSource _newEventSignal = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
public StreamState(string sessionId, string streamId, SseEventStreamMode mode)
{
SessionId = sessionId;
StreamId = streamId;
Mode = mode;
}
public string SessionId { get; }
public string StreamId { get; }
public SseEventStreamMode Mode { get; set; }
public bool IsCompleted { get; private set; }
public long NextSequence() => Interlocked.Increment(ref _sequence);
public void AddEvent(SseItem<JsonRpcMessage?> item, long sequence)
{
lock (_lock)
{
if (IsCompleted)
{
throw new InvalidOperationException("Cannot add events to a completed stream.");
}
_events.Add((item, sequence));
var oldSignal = _newEventSignal;
_newEventSignal = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
oldSignal.TrySetResult();
}
}
public (List<SseItem<JsonRpcMessage?>> Events, long LastSequence, Task NewEventSignal) GetEventsAfter(long sequence)
{
lock (_lock)
{
var result = new List<SseItem<JsonRpcMessage?>>();
long lastSequence = sequence;
foreach (var (item, seq) in _events)
{
if (seq > sequence)
{
result.Add(item);
lastSequence = seq;
}
}
return (result, lastSequence, _newEventSignal.Task);
}
}
public void Complete()
{
lock (_lock)
{
IsCompleted = true;
_newEventSignal.TrySetResult();
}
}
}
private sealed class InMemoryEventStreamWriter : ISseEventStreamWriter
{
private readonly TestSseEventStreamStore _store;
private readonly StreamState _state;
private bool _disposed;
public InMemoryEventStreamWriter(TestSseEventStreamStore store, StreamState state)
{
_store = store;
_state = state;
}
public ValueTask SetModeAsync(SseEventStreamMode mode, CancellationToken cancellationToken = default)
{
_state.Mode = mode;
return default;
}
public ValueTask<SseItem<JsonRpcMessage?>> WriteEventAsync(SseItem<JsonRpcMessage?> sseItem, CancellationToken cancellationToken = default)
{
// Skip if already has an event ID
if (sseItem.EventId is not null)
{
return new ValueTask<SseItem<JsonRpcMessage?>>(sseItem);
}
var sequence = _state.NextSequence();
var eventId = _store.GenerateEventId();
var newItem = sseItem with { EventId = eventId };
_state.AddEvent(newItem, sequence);
_store.TrackEvent(eventId, _state, sequence, sseItem.ReconnectionInterval);
return new ValueTask<SseItem<JsonRpcMessage?>>(newItem);
}
public ValueTask DisposeAsync()
{
if (_disposed)
{
return default;
}
_disposed = true;
_state.Complete();
return default;
}
}
private sealed class InMemoryEventStreamReader : ISseEventStreamReader
{
private readonly StreamState _state;
private readonly long _startSequence;
public InMemoryEventStreamReader(StreamState state, long startSequence)
{
_state = state;
_startSequence = startSequence;
}
public string SessionId => _state.SessionId;
public string StreamId => _state.StreamId;
public async IAsyncEnumerable<SseItem<JsonRpcMessage?>> ReadEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
long lastSeenSequence = _startSequence;
while (true)
{
// Get events after the last seen sequence
var (events, lastSequence, newEventSignal) = _state.GetEventsAfter(lastSeenSequence);
foreach (var evt in events)
{
yield return evt;
}
// Update to the sequence we actually retrieved
lastSeenSequence = lastSequence;
// If in polling mode, stop after returning currently available events
if (_state.Mode == SseEventStreamMode.Polling)
{
yield break;
}
// If the stream is completed, stop
if (_state.IsCompleted)
{
yield break;
}
// Wait for new events or cancellation
await newEventSignal.WaitAsync(cancellationToken).ConfigureAwait(false);
}
}
}
}