-
Notifications
You must be signed in to change notification settings - Fork 689
Streamable HTTP resumability + redelivery + SSE polling via server-side disconnect #1077
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 24 commits
Commits
Show all changes
38 commits
Select commit
Hold shift + click to select a range
1e407ce
Client-side polling via `Last-Event-ID`
MackinnonBuck 677d9ea
`ISseEventStreamStore` and test implementation
MackinnonBuck 63fb022
Server-side resumability via `Last-Event-ID`
MackinnonBuck 11494e1
Server-side disconnect
MackinnonBuck 493062a
Integration tests
MackinnonBuck fe71286
Make `EnablePollingAsync` no-op in stateless mode
MackinnonBuck 2065c0e
Merge remote-tracking branch 'origin/main' into mbuck/resumability-re…
MackinnonBuck 66fcdb1
Update src/ModelContextProtocol.Core/Client/HttpClientTransportOption…
MackinnonBuck c9044c8
PR feedback: Don't dispose `_sseWriter` on final message
MackinnonBuck 2f19044
PR feedback: Use `SseEventStreamMode.Default` for unsolicited messages
MackinnonBuck f6858ab
Return 405 on GET in statless mode
MackinnonBuck 8e617bd
Make completing POST responses more robust
MackinnonBuck 1fdec43
Fix `TestSseEventStreamStore` and make tests more robust
MackinnonBuck ef6dd62
Allow tests to configure their own `HttpClient`
MackinnonBuck 58ee59e
Add test: Using an event ID for a different session
MackinnonBuck 4dd7383
Require negotiated protocol version for priming
MackinnonBuck 7262e5d
Improve `StreamableHttpPostTransport` thread safety
MackinnonBuck 2f7a923
Acquire lock before writing to parent transport
MackinnonBuck 7804475
PR feedback
MackinnonBuck c2bffd9
Simplify SSE message writing
MackinnonBuck 45b7382
PR feedback
MackinnonBuck b221f37
PR feedback: Throw in `EnablePollingAsync`
MackinnonBuck 0f9c09f
PR feedback: Delete `SseEventStreamStoreTests`
MackinnonBuck e589876
Make client default reconnection interval configurable
MackinnonBuck 1376430
Update src/ModelContextProtocol.Core/Client/StreamableHttpClientSessi…
MackinnonBuck f467015
PR feedback
MackinnonBuck fe1264c
Drop messages rather than throwing
MackinnonBuck 1b1a368
PR feedback: use `init` over `set`
MackinnonBuck e531a92
PR feedback: Attempt reconnection on 500 responses
MackinnonBuck d0cbd05
PR feedback: Rename `_diposed` variable
MackinnonBuck b627cba
PR feedback: Make stream completion more reliable
MackinnonBuck b6d4398
Remove `RetryInterval` from `HttpServerTransportOptions`
MackinnonBuck cb78114
Only fallback to parent transport after final message
MackinnonBuck e8c3032
Fix flaky test
MackinnonBuck 5502522
PR feedback
MackinnonBuck 4da6dca
Pin `@modelcontextprotocol/server-everything` version
MackinnonBuck 3bbc0d1
Add missing `CancellationToken` in tests and add diagnostics
MackinnonBuck 8ab1d82
Pin `@modelcontextprotocol/server-everything` version in CI
MackinnonBuck File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| // Copied from https://github.com/dotnet/runtime/blob/main/src/libraries/Common/src/System/Net/ArrayBuffer.cs | ||
|
|
||
| using System.Buffers; | ||
| using System.Diagnostics; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Runtime.InteropServices; | ||
|
|
||
| namespace System.Net.ServerSentEvents; | ||
|
|
||
| // Warning: Mutable struct! | ||
| // The purpose of this struct is to simplify buffer management. | ||
| // It manages a sliding buffer where bytes can be added at the end and removed at the beginning. | ||
| // [ActiveSpan/Memory] contains the current buffer contents; these bytes will be preserved | ||
| // (copied, if necessary) on any call to EnsureAvailableBytes. | ||
| // [AvailableSpan/Memory] contains the available bytes past the end of the current content, | ||
| // and can be written to in order to add data to the end of the buffer. | ||
| // Commit(byteCount) will extend the ActiveSpan by [byteCount] bytes into the AvailableSpan. | ||
| // Discard(byteCount) will discard [byteCount] bytes as the beginning of the ActiveSpan. | ||
|
|
||
| [StructLayout(LayoutKind.Auto)] | ||
| internal struct ArrayBuffer : IDisposable | ||
| { | ||
| #if NET | ||
| private static int ArrayMaxLength => Array.MaxLength; | ||
| #else | ||
| private const int ArrayMaxLength = 0X7FFFFFC7; | ||
|
MackinnonBuck marked this conversation as resolved.
Outdated
|
||
| #endif | ||
|
|
||
| private readonly bool _usePool; | ||
| private byte[] _bytes; | ||
| private int _activeStart; | ||
| private int _availableStart; | ||
|
|
||
| // Invariants: | ||
| // 0 <= _activeStart <= _availableStart <= bytes.Length | ||
|
|
||
| public ArrayBuffer(int initialSize, bool usePool = false) | ||
| { | ||
| Debug.Assert(initialSize > 0 || usePool); | ||
|
|
||
| _usePool = usePool; | ||
| _bytes = initialSize == 0 | ||
| ? Array.Empty<byte>() | ||
| : usePool ? ArrayPool<byte>.Shared.Rent(initialSize) : new byte[initialSize]; | ||
| _activeStart = 0; | ||
| _availableStart = 0; | ||
| } | ||
|
|
||
| public ArrayBuffer(byte[] buffer) | ||
| { | ||
| Debug.Assert(buffer.Length > 0); | ||
|
|
||
| _usePool = false; | ||
| _bytes = buffer; | ||
| _activeStart = 0; | ||
| _availableStart = 0; | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| _activeStart = 0; | ||
| _availableStart = 0; | ||
|
|
||
| byte[] array = _bytes; | ||
| _bytes = null!; | ||
|
|
||
| if (array is not null) | ||
| { | ||
| ReturnBufferIfPooled(array); | ||
| } | ||
| } | ||
|
|
||
| // This is different from Dispose as the instance remains usable afterwards (_bytes will not be null). | ||
| public void ClearAndReturnBuffer() | ||
| { | ||
| Debug.Assert(_usePool); | ||
| Debug.Assert(_bytes is not null); | ||
|
|
||
| _activeStart = 0; | ||
| _availableStart = 0; | ||
|
|
||
| byte[] bufferToReturn = _bytes!; | ||
| _bytes = Array.Empty<byte>(); | ||
| ReturnBufferIfPooled(bufferToReturn); | ||
| } | ||
|
|
||
| public int ActiveLength => _availableStart - _activeStart; | ||
| public Span<byte> ActiveSpan => new Span<byte>(_bytes, _activeStart, _availableStart - _activeStart); | ||
| public ReadOnlySpan<byte> ActiveReadOnlySpan => new ReadOnlySpan<byte>(_bytes, _activeStart, _availableStart - _activeStart); | ||
| public Memory<byte> ActiveMemory => new Memory<byte>(_bytes, _activeStart, _availableStart - _activeStart); | ||
|
|
||
| public int AvailableLength => _bytes.Length - _availableStart; | ||
| public Span<byte> AvailableSpan => _bytes.AsSpan(_availableStart); | ||
| public Memory<byte> AvailableMemory => _bytes.AsMemory(_availableStart); | ||
| public Memory<byte> AvailableMemorySliced(int length) => new Memory<byte>(_bytes, _availableStart, length); | ||
|
|
||
| public int Capacity => _bytes.Length; | ||
| public int ActiveStartOffset => _activeStart; | ||
|
|
||
| public byte[] DangerousGetUnderlyingBuffer() => _bytes; | ||
|
|
||
| public void Discard(int byteCount) | ||
| { | ||
| Debug.Assert(byteCount <= ActiveLength, $"Expected {byteCount} <= {ActiveLength}"); | ||
| _activeStart += byteCount; | ||
|
|
||
| if (_activeStart == _availableStart) | ||
| { | ||
| _activeStart = 0; | ||
| _availableStart = 0; | ||
| } | ||
| } | ||
|
|
||
| public void Commit(int byteCount) | ||
| { | ||
| Debug.Assert(byteCount <= AvailableLength); | ||
| _availableStart += byteCount; | ||
| } | ||
|
|
||
| // Ensure at least [byteCount] bytes to write to. | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| public void EnsureAvailableSpace(int byteCount) | ||
| { | ||
| if (byteCount > AvailableLength) | ||
| { | ||
| EnsureAvailableSpaceCore(byteCount); | ||
| } | ||
| } | ||
|
|
||
| private void EnsureAvailableSpaceCore(int byteCount) | ||
| { | ||
| Debug.Assert(AvailableLength < byteCount); | ||
|
|
||
| if (_bytes.Length == 0) | ||
| { | ||
| Debug.Assert(_usePool && _activeStart == 0 && _availableStart == 0); | ||
| _bytes = ArrayPool<byte>.Shared.Rent(byteCount); | ||
| return; | ||
| } | ||
|
|
||
| int totalFree = _activeStart + AvailableLength; | ||
| if (byteCount <= totalFree) | ||
| { | ||
| // We can free up enough space by just shifting the bytes down, so do so. | ||
| Buffer.BlockCopy(_bytes, _activeStart, _bytes, 0, ActiveLength); | ||
| _availableStart = ActiveLength; | ||
| _activeStart = 0; | ||
| Debug.Assert(byteCount <= AvailableLength); | ||
| return; | ||
| } | ||
|
|
||
| int desiredSize = ActiveLength + byteCount; | ||
|
|
||
| if ((uint)desiredSize > ArrayMaxLength) | ||
| { | ||
| throw new OutOfMemoryException(); | ||
| } | ||
|
|
||
| // Double the existing buffer size (capped at Array.MaxLength). | ||
| int newSize = Math.Max(desiredSize, (int)Math.Min(ArrayMaxLength, 2 * (uint)_bytes.Length)); | ||
|
|
||
| byte[] newBytes = _usePool ? | ||
| ArrayPool<byte>.Shared.Rent(newSize) : | ||
| new byte[newSize]; | ||
| byte[] oldBytes = _bytes; | ||
|
|
||
| if (ActiveLength != 0) | ||
| { | ||
| Buffer.BlockCopy(oldBytes, _activeStart, newBytes, 0, ActiveLength); | ||
| } | ||
|
|
||
| _availableStart = ActiveLength; | ||
| _activeStart = 0; | ||
|
|
||
| _bytes = newBytes; | ||
| ReturnBufferIfPooled(oldBytes); | ||
|
|
||
| Debug.Assert(byteCount <= AvailableLength); | ||
| } | ||
|
|
||
| public void Grow() | ||
| { | ||
| EnsureAvailableSpaceCore(AvailableLength + 1); | ||
| } | ||
|
|
||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| private void ReturnBufferIfPooled(byte[] buffer) | ||
| { | ||
| // The buffer may be Array.Empty<byte>() | ||
| if (_usePool && buffer.Length > 0) | ||
| { | ||
| ArrayPool<byte>.Shared.Return(buffer); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| // Copied from https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.ServerSentEvents/src/System/Net/ServerSentEvents/PooledByteBufferWriter.cs | ||
|
|
||
| using System.Buffers; | ||
| using System.Diagnostics; | ||
|
|
||
| namespace System.Net.ServerSentEvents; | ||
|
|
||
| internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable | ||
| { | ||
| private const int MinimumBufferSize = 256; | ||
| private ArrayBuffer _buffer = new(initialSize: 256, usePool: true); | ||
|
|
||
| public void Advance(int count) => _buffer.Commit(count); | ||
|
|
||
| public Memory<byte> GetMemory(int sizeHint = 0) | ||
| { | ||
| _buffer.EnsureAvailableSpace(Math.Max(sizeHint, MinimumBufferSize)); | ||
| return _buffer.AvailableMemory; | ||
| } | ||
|
|
||
| public Span<byte> GetSpan(int sizeHint = 0) | ||
| { | ||
| _buffer.EnsureAvailableSpace(Math.Max(sizeHint, MinimumBufferSize)); | ||
| return _buffer.AvailableSpan; | ||
| } | ||
|
|
||
| public ReadOnlyMemory<byte> WrittenMemory => _buffer.ActiveMemory; | ||
| public int Capacity => _buffer.Capacity; | ||
| public int WrittenCount => _buffer.ActiveLength; | ||
| public void Reset() => _buffer.Discard(_buffer.ActiveLength); | ||
| public void Dispose() => _buffer.Dispose(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| // Based on https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.ServerSentEvents/src/System/Net/ServerSentEvents/SseFormatter.cs | ||
|
|
||
| using System.Buffers; | ||
| using System.Diagnostics; | ||
| using System.IO; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.Net.ServerSentEvents; | ||
|
|
||
| /// <summary> | ||
| /// Provides methods for writing SSE events to a stream. | ||
| /// </summary> | ||
| internal sealed class SseEventWriter : IDisposable | ||
| { | ||
| private static readonly byte[] s_newLine = "\n"u8.ToArray(); | ||
|
|
||
| private readonly Stream _destination; | ||
| private readonly PooledByteBufferWriter _bufferWriter = new(); | ||
| private readonly PooledByteBufferWriter _userDataBufferWriter = new(); | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="SseEventWriter"/> class with the specified destination stream and item formatter. | ||
| /// </summary> | ||
| /// <param name="destination">The stream to write SSE events to.</param> | ||
| /// <exception cref="ArgumentNullException"><paramref name="destination"/> is <see langword="null"/>.</exception> | ||
| public SseEventWriter(Stream destination) | ||
| { | ||
| _destination = destination ?? throw new ArgumentNullException(nameof(destination)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes an SSE item to the destination stream. | ||
| /// </summary> | ||
| /// <param name="item">The SSE item to write.</param> | ||
| /// <param name="itemFormatter"></param> | ||
| /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> | ||
| /// <returns>A task representing the asynchronous write operation.</returns> | ||
| public async ValueTask WriteAsync<T>(SseItem<T> item, Action<SseItem<T>, IBufferWriter<byte>> itemFormatter, CancellationToken cancellationToken = default) | ||
| { | ||
| itemFormatter(item, _userDataBufferWriter); | ||
|
|
||
| FormatSseEvent( | ||
| _bufferWriter, | ||
| eventType: item.EventType, | ||
| data: _userDataBufferWriter.WrittenMemory.Span, | ||
| eventId: item.EventId, | ||
| reconnectionInterval: item.ReconnectionInterval); | ||
|
|
||
| await _destination.WriteAsync(_bufferWriter.WrittenMemory, cancellationToken).ConfigureAwait(false); | ||
| await _destination.FlushAsync(cancellationToken).ConfigureAwait(false); | ||
|
|
||
| _userDataBufferWriter.Reset(); | ||
| _bufferWriter.Reset(); | ||
| } | ||
|
|
||
| private static void FormatSseEvent( | ||
| IBufferWriter<byte> bufferWriter, | ||
| string? eventType, | ||
| ReadOnlySpan<byte> data, | ||
| string? eventId, | ||
| TimeSpan? reconnectionInterval) | ||
| { | ||
| if (eventType is not null) | ||
| { | ||
| Debug.Assert(!eventType.ContainsLineBreaks()); | ||
|
|
||
| bufferWriter.WriteUtf8String("event: "u8); | ||
| bufferWriter.WriteUtf8String(eventType); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| WriteLinesWithPrefix(bufferWriter, prefix: "data: "u8, data); | ||
| bufferWriter.Write(s_newLine); | ||
|
|
||
| if (eventId is not null) | ||
| { | ||
| Debug.Assert(!eventId.ContainsLineBreaks()); | ||
|
|
||
| bufferWriter.WriteUtf8String("id: "u8); | ||
| bufferWriter.WriteUtf8String(eventId); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| if (reconnectionInterval is { } retry) | ||
| { | ||
| Debug.Assert(retry >= TimeSpan.Zero); | ||
|
|
||
| bufferWriter.WriteUtf8String("retry: "u8); | ||
| bufferWriter.WriteUtf8Number((long)retry.TotalMilliseconds); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| private static void WriteLinesWithPrefix(IBufferWriter<byte> writer, ReadOnlySpan<byte> prefix, ReadOnlySpan<byte> data) | ||
| { | ||
| // Writes a potentially multi-line string, prefixing each line with the given prefix. | ||
| // Both \n and \r\n sequences are normalized to \n. | ||
|
|
||
| while (true) | ||
| { | ||
| writer.WriteUtf8String(prefix); | ||
|
|
||
| int i = data.IndexOfAny((byte)'\r', (byte)'\n'); | ||
| if (i < 0) | ||
| { | ||
| writer.WriteUtf8String(data); | ||
| return; | ||
| } | ||
|
|
||
| int lineLength = i; | ||
| if (data[i++] == '\r' && i < data.Length && data[i] == '\n') | ||
| { | ||
| i++; | ||
| } | ||
|
|
||
| ReadOnlySpan<byte> nextLine = data.Slice(0, lineLength); | ||
| data = data.Slice(i); | ||
|
|
||
| writer.WriteUtf8String(nextLine); | ||
| writer.WriteUtf8String(s_newLine); | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public void Dispose() | ||
| { | ||
| _bufferWriter.Dispose(); | ||
| _userDataBufferWriter.Dispose(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.