Repository navigation
fix: reconnect agent after ELS restarts #14
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 all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
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,9 @@ | ||
| <Solution> | ||
| <Folder Name="/src/"> | ||
| <Project Path="src/Api/Api.csproj" /> | ||
| </Folder> | ||
| <Folder Name="/tests/"> | ||
| <Project Path="tests/Api.IntegrationTests/Api.IntegrationTests.csproj" /> | ||
| <Project Path="tests/Api.UnitTests/Api.UnitTests.csproj" /> | ||
| </Folder> | ||
| </Solution> |
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,4 @@ | ||
| using System.Runtime.CompilerServices; | ||
|
|
||
| [assembly: InternalsVisibleTo("Api.UnitTests")] | ||
| [assembly: InternalsVisibleTo("Api.IntegrationTests")] |
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
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,25 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| <IsPackable>false</IsPackable> | ||
| <IsTestProject>true</IsTestProject> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.5.1" /> | ||
| <PackageReference Include="xunit" Version="2.9.3" /> | ||
| <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5"> | ||
| <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
| <PrivateAssets>all</PrivateAssets> | ||
| </PackageReference> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <FrameworkReference Include="Microsoft.AspNetCore.App" /> | ||
| <ProjectReference Include="..\..\src\Api\Api.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
100 changes: 100 additions & 0 deletions
100
tests/Api.IntegrationTests/Transport/WebSocketReconnectTests.cs
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,100 @@ | ||
| using System.Net.WebSockets; | ||
| using Api.Transport; | ||
| using Microsoft.Extensions.Logging.Abstractions; | ||
| using Xunit; | ||
|
|
||
| namespace Api.IntegrationTests.Transport; | ||
|
|
||
| public class WebSocketReconnectTests | ||
| { | ||
| [Fact] | ||
| public async Task NormalClosure_ReconnectsRepeatedly() | ||
| { | ||
| await using var server = await WebSocketStubServer.StartAsync(); | ||
| var webSocket = new FbWebSocket(server.WebSocketUri, NullLoggerFactory.Instance); | ||
|
|
||
| try | ||
| { | ||
| await webSocket.ConnectAsync(); | ||
| await server.WaitForConnectionsAsync(1); | ||
|
|
||
| await server.CloseAsync(1, WebSocketCloseStatus.NormalClosure); | ||
| await server.WaitForConnectionsAsync(2); | ||
|
|
||
| await server.CloseAsync(2, WebSocketCloseStatus.NormalClosure); | ||
| await server.WaitForConnectionsAsync(3); | ||
|
|
||
| Assert.Equal(3, server.ConnectionCount); | ||
| } | ||
| finally | ||
| { | ||
| server.AbortConnections(); | ||
| await webSocket.CloseAsync(CancellationToken.None); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task InvalidRequestClose_DoesNotReconnect() | ||
| { | ||
| await using var server = await WebSocketStubServer.StartAsync( | ||
| FbWebSocket.ServerRejectedCloseStatus | ||
| ); | ||
| var webSocket = new FbWebSocket(server.WebSocketUri, NullLoggerFactory.Instance); | ||
| var closed = new TaskCompletionSource<WebSocketCloseStatus?>( | ||
| TaskCreationOptions.RunContinuationsAsynchronously | ||
| ); | ||
| webSocket.OnClosed += (_, status, _) => | ||
| { | ||
| closed.TrySetResult(status); | ||
| return Task.CompletedTask; | ||
| }; | ||
|
|
||
| try | ||
| { | ||
| await webSocket.ConnectAsync(); | ||
|
|
||
| var closeStatus = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5)); | ||
| await Task.Delay(TimeSpan.FromMilliseconds(250)); | ||
|
|
||
| Assert.Equal(FbWebSocket.ServerRejectedCloseStatus, closeStatus); | ||
| Assert.Equal(1, server.ConnectionCount); | ||
|
deleteLater marked this conversation as resolved.
|
||
| } | ||
| finally | ||
| { | ||
| server.AbortConnections(); | ||
| await webSocket.CloseAsync(CancellationToken.None); | ||
| } | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task NormalClosure_WhenStoppedDuringReconnect_DoesNotReconnect() | ||
| { | ||
| await using var server = await WebSocketStubServer.StartAsync(); | ||
| var webSocket = new FbWebSocket(server.WebSocketUri, NullLoggerFactory.Instance); | ||
| var reconnecting = new TaskCompletionSource( | ||
| TaskCreationOptions.RunContinuationsAsynchronously | ||
| ); | ||
| webSocket.OnReconnecting += _ => | ||
| { | ||
| reconnecting.TrySetResult(); | ||
| return webSocket.CloseAsync(CancellationToken.None); | ||
| }; | ||
|
|
||
| try | ||
| { | ||
| await webSocket.ConnectAsync(); | ||
| await server.WaitForConnectionsAsync(1); | ||
|
|
||
| await server.CloseAsync(1, WebSocketCloseStatus.NormalClosure); | ||
| await reconnecting.Task.WaitAsync(TimeSpan.FromSeconds(5)); | ||
| await Task.Delay(TimeSpan.FromMilliseconds(250)); | ||
|
|
||
| Assert.Equal(1, server.ConnectionCount); | ||
| } | ||
| finally | ||
| { | ||
| server.AbortConnections(); | ||
| await webSocket.CloseAsync(CancellationToken.None); | ||
| } | ||
| } | ||
| } | ||
142 changes: 142 additions & 0 deletions
142
tests/Api.IntegrationTests/Transport/WebSocketStubServer.cs
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,142 @@ | ||
| using System.Collections.Concurrent; | ||
| using System.Net; | ||
| using System.Net.WebSockets; | ||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.AspNetCore.Hosting; | ||
| using Microsoft.AspNetCore.Hosting.Server; | ||
| using Microsoft.AspNetCore.Hosting.Server.Features; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Api.IntegrationTests.Transport; | ||
|
|
||
| public sealed class WebSocketStubServer : IAsyncDisposable | ||
| { | ||
| private readonly WebApplication _application; | ||
| private readonly WebSocketCloseStatus? _closeImmediatelyWith; | ||
| private readonly ConcurrentDictionary<int, WebSocket> _connections = new(); | ||
| private readonly SemaphoreSlim _connectionSignal = new(0); | ||
| private int _connectionCount; | ||
|
|
||
| private WebSocketStubServer(WebApplication application, WebSocketCloseStatus? closeImmediatelyWith) | ||
| { | ||
| _application = application; | ||
| _closeImmediatelyWith = closeImmediatelyWith; | ||
| } | ||
|
|
||
| public int ConnectionCount => Volatile.Read(ref _connectionCount); | ||
|
|
||
| public Uri WebSocketUri { get; private set; } = null!; | ||
|
|
||
| public static async Task<WebSocketStubServer> StartAsync(WebSocketCloseStatus? closeImmediatelyWith = null) | ||
| { | ||
| var builder = WebApplication.CreateBuilder(); | ||
| builder.Logging.ClearProviders(); | ||
| builder.WebHost.ConfigureKestrel(options => options.Listen(IPAddress.Loopback, 0)); | ||
|
|
||
| var application = builder.Build(); | ||
| var server = new WebSocketStubServer(application, closeImmediatelyWith); | ||
|
|
||
| application.UseWebSockets(); | ||
| application.Map("/streaming", server.HandleConnectionAsync); | ||
|
|
||
| await application.StartAsync(); | ||
|
|
||
| var addresses = application.Services | ||
| .GetRequiredService<IServer>() | ||
| .Features | ||
| .Get<IServerAddressesFeature>()!; | ||
| var httpUri = new Uri(addresses.Addresses.Single()); | ||
| server.WebSocketUri = new UriBuilder(new Uri(httpUri, "/streaming")) { Scheme = "ws" }.Uri; | ||
|
|
||
| return server; | ||
| } | ||
|
|
||
| public async Task WaitForConnectionsAsync(int expectedCount) | ||
| { | ||
| using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | ||
| while (ConnectionCount < expectedCount) | ||
| { | ||
| await _connectionSignal.WaitAsync(timeout.Token); | ||
| } | ||
| } | ||
|
|
||
| public async Task CloseAsync(int connectionId, WebSocketCloseStatus closeStatus) | ||
| { | ||
| if (!_connections.TryGetValue(connectionId, out var connection)) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"WebSocket connection {connectionId} is no longer active." | ||
| ); | ||
| } | ||
|
|
||
| await connection.CloseOutputAsync(closeStatus, "closed by test server", CancellationToken.None); | ||
| } | ||
|
|
||
| public void AbortConnections() | ||
| { | ||
| foreach (var connection in _connections.Values) | ||
| { | ||
| connection.Abort(); | ||
| } | ||
| } | ||
|
|
||
| private async Task HandleConnectionAsync(HttpContext context) | ||
| { | ||
| if (!context.WebSockets.IsWebSocketRequest) | ||
| { | ||
| context.Response.StatusCode = StatusCodes.Status400BadRequest; | ||
| return; | ||
| } | ||
|
|
||
| using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); | ||
| var connectionId = Interlocked.Increment(ref _connectionCount); | ||
| _connections[connectionId] = webSocket; | ||
| _connectionSignal.Release(); | ||
|
|
||
| try | ||
| { | ||
| if (_closeImmediatelyWith.HasValue) | ||
| { | ||
| await webSocket.CloseOutputAsync( | ||
| _closeImmediatelyWith.Value, | ||
| "closed by test server", | ||
| CancellationToken.None | ||
| ); | ||
| } | ||
|
|
||
| var buffer = new byte[1024]; | ||
| while (webSocket.State is WebSocketState.Open or WebSocketState.CloseSent) | ||
| { | ||
| var result = await webSocket.ReceiveAsync(buffer, context.RequestAborted); | ||
| if (result.MessageType == WebSocketMessageType.Close) | ||
| { | ||
| break; | ||
| } | ||
| } | ||
| } | ||
| catch (OperationCanceledException) | ||
| { | ||
| // The test server is stopping. | ||
| } | ||
| catch (WebSocketException) | ||
| { | ||
| // The client disposed the connection after observing the close frame. | ||
| } | ||
| finally | ||
| { | ||
| _connections.TryRemove(connectionId, out _); | ||
| } | ||
| } | ||
|
|
||
| public async ValueTask DisposeAsync() | ||
| { | ||
| AbortConnections(); | ||
|
|
||
| using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | ||
| await _application.StopAsync(timeout.Token); | ||
| await _application.DisposeAsync(); | ||
| _connectionSignal.Dispose(); | ||
| } | ||
| } |
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.