public void GlobalSetup() { var memoryBufferWriter = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteRequestMessage(new HandshakeRequestMessage("json", 1), memoryBufferWriter); _handshakeRequestResult = new ReadResult(new ReadOnlySequence <byte>(memoryBufferWriter.ToArray()), false, false); } finally { MemoryBufferWriter.Return(memoryBufferWriter); } _pipe = new TestDuplexPipe(); var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), _pipe, _pipe); var contextOptions = new HubConnectionContextOptions() { KeepAliveInterval = Timeout.InfiniteTimeSpan, }; _hubConnectionContext = new HubConnectionContext(connection, contextOptions, NullLoggerFactory.Instance); _successHubProtocolResolver = new TestHubProtocolResolver(new NewtonsoftJsonHubProtocol()); _failureHubProtocolResolver = new TestHubProtocolResolver(null); _userIdProvider = new TestUserIdProvider(); _supportedProtocols = new List <string> { "json" }; }
public async Task TransportFailsOnTimeoutWithErrorWhenApplicationFailsAndClientDoesNotSendCloseFrame() { using (StartLog(out var loggerFactory, LogLevel.Debug)) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions { CloseTimeout = TimeSpan.FromSeconds(1) }; var connectionContext = new DefaultConnectionContext(string.Empty, null, null); var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // fail the client to server channel connection.Transport.Output.Complete(new Exception()); await transport.OrTimeout(); Assert.Equal(WebSocketState.Aborted, serverSocket.State); } } }
public void GlobalSetup() { var serviceCollection = new ServiceCollection(); serviceCollection.AddSignalRCore(); var provider = serviceCollection.BuildServiceProvider(); var serviceScopeFactory = provider.GetService <IServiceScopeFactory>(); _dispatcher = new DefaultHubDispatcher <TestHub>( serviceScopeFactory, new HubContext <TestHub>(new DefaultHubLifetimeManager <TestHub>(NullLogger <DefaultHubLifetimeManager <TestHub> > .Instance)), enableDetailedErrors: false, new Logger <DefaultHubDispatcher <TestHub> >(NullLoggerFactory.Instance), hubFilters: null); var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Application, pair.Transport); var contextOptions = new HubConnectionContextOptions() { KeepAliveInterval = TimeSpan.Zero, StreamBufferCapacity = 10, }; _connectionContext = new NoErrorHubConnectionContext(connection, contextOptions, NullLoggerFactory.Instance); _connectionContext.Protocol = new FakeHubProtocol(); }
public async Task ClientReceivesInternalServerErrorWhenTheApplicationFails() { using (StartLog(out var loggerFactory, LogLevel.Debug)) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); using (var feature = new TestWebSocketConnectionFeature()) { var connectionContext = new DefaultConnectionContext(string.Empty, null, null); var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // Fail in the app connection.Transport.Output.Complete(new InvalidOperationException("Catastrophic failure.")); var clientSummary = await client.OrTimeout(); Assert.Equal(WebSocketCloseStatus.InternalServerError, clientSummary.CloseResult.CloseStatus); // Close from the client await feature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); await transport.OrTimeout(); } } }
public async Task TransportClosesOnCloseTimeoutIfClientDoesNotSendCloseFrame() { using (StartLog(out var loggerFactory, LogLevel.Debug)) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); using (var feature = new TestWebSocketConnectionFeature()) { var options = new WebSocketOptions() { CloseTimeout = TimeSpan.FromSeconds(1) }; var connectionContext = new DefaultConnectionContext(string.Empty, null, null); var ws = new WebSocketsTransport(options, connection.Application, connectionContext, loggerFactory); var serverSocket = await feature.AcceptAsync(); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(serverSocket); // End the app connection.Transport.Output.Complete(); await transport.OrTimeout(TimeSpan.FromSeconds(10)); // Now we're closed Assert.Equal(WebSocketState.Aborted, serverSocket.State); serverSocket.Dispose(); } } }
public async Task MultipleFramesSentAsSingleResponse() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, LoggerFactory); var ms = new MemoryStream(); context.Response.Body = ms; await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello")); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes(" ")); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("World")); connection.Transport.Output.Complete(); await poll.ProcessRequestAsync(context, context.RequestAborted).OrTimeout(); Assert.Equal(200, context.Response.StatusCode); var payload = ms.ToArray(); Assert.Equal("Hello World", Encoding.UTF8.GetString(payload)); } }
public TestClient(bool synchronousCallbacks = false, IHubProtocol protocol = null, IInvocationBinder invocationBinder = null, bool addClaimId = false) { var options = new PipeOptions(readerScheduler: synchronousCallbacks ? PipeScheduler.Inline : null); var pair = DuplexPipe.CreateConnectionPair(options, options); Connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application); var claimValue = Interlocked.Increment(ref _id).ToString(); var claims = new List <Claim> { new Claim(ClaimTypes.Name, claimValue) }; if (addClaimId) { claims.Add(new Claim(ClaimTypes.NameIdentifier, claimValue)); } Connection.User = new ClaimsPrincipal(new ClaimsIdentity(claims)); Connection.Items["ConnectedTask"] = new TaskCompletionSource <bool>(); _protocol = protocol ?? new JsonHubProtocol(); _invocationBinder = invocationBinder ?? new DefaultInvocationBinder(); _cts = new CancellationTokenSource(); }
public void GlobalSetup() { _hubLifetimeManager = new DefaultHubLifetimeManager <Hub>(NullLogger <DefaultHubLifetimeManager <Hub> > .Instance); IHubProtocol protocol; if (Protocol == "json") { protocol = new JsonHubProtocol(); } else { protocol = new MessagePackHubProtocol(); } var options = new PipeOptions(); for (var i = 0; i < Connections; ++i) { var pair = DuplexPipe.CreateConnectionPair(options, options); var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Application, pair.Transport); var hubConnection = new HubConnectionContext(connection, Timeout.InfiniteTimeSpan, NullLoggerFactory.Instance); hubConnection.Protocol = protocol; _hubLifetimeManager.OnConnectedAsync(hubConnection).GetAwaiter().GetResult(); _ = ConsumeAsync(connection.Application); } _hubContext = new HubContext <Hub>(_hubLifetimeManager); }
public TestClient(bool synchronousCallbacks = false, IHubProtocol protocol = null, IInvocationBinder invocationBinder = null, bool addClaimId = false) { var options = new PipeOptions(readerScheduler: synchronousCallbacks ? PipeScheduler.Inline : null); var pair = DuplexPipe.CreateConnectionPair(options, options); Connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application); var claimValue = Interlocked.Increment(ref _id).ToString(); var claims = new List <Claim> { new Claim(ClaimTypes.Name, claimValue) }; if (addClaimId) { claims.Add(new Claim(ClaimTypes.NameIdentifier, claimValue)); } Connection.User = new ClaimsPrincipal(new ClaimsIdentity(claims)); Connection.Metadata["ConnectedTask"] = new TaskCompletionSource <bool>(); protocol = protocol ?? new JsonHubProtocol(); _protocolReaderWriter = new HubProtocolReaderWriter(protocol, new PassThroughEncoder()); _invocationBinder = invocationBinder ?? new DefaultInvocationBinder(); _cts = new CancellationTokenSource(); using (var memoryStream = new MemoryStream()) { NegotiationProtocol.WriteMessage(new NegotiationMessage(protocol.Name), memoryStream); Connection.Application.Output.WriteAsync(memoryStream.ToArray()); } }
public async Task SSEWritesVeryLargeMessages() { using (StartVerifiableLog()) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, new PipeOptions(readerScheduler: PipeScheduler.Inline)); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); var ms = new MemoryStream(); context.Response.Body = ms; var sse = new ServerSentEventsServerTransport(connection.Application.Input, connectionId: string.Empty, LoggerFactory); var task = sse.ProcessRequestAsync(context, context.RequestAborted); string hText = new string('H', 60000); string wText = new string('W', 60000); await connection.Transport.Output.WriteAsync(Encoding.ASCII.GetBytes(hText + wText)); connection.Transport.Output.Complete(); await task.OrTimeout(); Assert.Equal(":\r\ndata: " + hText + wText + "\r\n\r\n", Encoding.ASCII.GetString(ms.ToArray())); } }
public void GlobalSetup() { var arguments = new object[ArgumentCount]; for (var i = 0; i < arguments.Length; i++) { arguments[i] = "Hello world!"; } var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); _pipe = new TestDuplexPipe(); _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult)); } finally { MemoryBufferWriter.Return(writer); } _nextReadTcs = new TaskCompletionSource <ReadResult>(); _pipe.AddReadResult(new ValueTask <ReadResult>(_nextReadTcs.Task)); IHubProtocol hubProtocol; var hubConnectionBuilder = new HubConnectionBuilder(); if (Protocol == "json") { hubProtocol = new NewtonsoftJsonHubProtocol(); } else { hubProtocol = new MessagePackHubProtocol(); } hubConnectionBuilder.Services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHubProtocol), hubProtocol)); _invocationMessageBytes = hubProtocol.GetMessageBytes(new InvocationMessage(MethodName, arguments)); var delegateConnectionFactory = new DelegateConnectionFactory(endPoint => { var connection = new DefaultConnectionContext(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; return(new ValueTask <ConnectionContext>(connection)); }); hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); _hubConnection = hubConnectionBuilder.Build(); _hubConnection.On(MethodName, arguments.Select(v => v.GetType()).ToArray(), OnInvoke); _hubConnection.StartAsync().GetAwaiter().GetResult(); }
public void GlobalSetup() { var writer = MemoryBufferWriter.Get(); try { HandshakeProtocol.WriteResponseMessage(HandshakeResponseMessage.Empty, writer); var handshakeResponseResult = new ReadResult(new ReadOnlySequence <byte>(writer.ToArray()), false, false); _pipe = new TestDuplexPipe(); _pipe.AddReadResult(new ValueTask <ReadResult>(handshakeResponseResult)); } finally { MemoryBufferWriter.Return(writer); } _tcs = new TaskCompletionSource <ReadResult>(); _pipe.AddReadResult(new ValueTask <ReadResult>(_tcs.Task)); var hubConnectionBuilder = new HubConnectionBuilder(); if (Protocol == "json") { // JSON protocol added by default } else { hubConnectionBuilder.AddMessagePackProtocol(); } var delegateConnectionFactory = new DelegateConnectionFactory(format => { var connection = new DefaultConnectionContext(); // prevents keep alive time being activated connection.Features.Set <IConnectionInherentKeepAliveFeature>(new TestConnectionInherentKeepAliveFeature()); connection.Transport = _pipe; return(Task.FromResult <ConnectionContext>(connection)); }, connection => { connection.Transport.Output.Complete(); connection.Transport.Input.Complete(); return(Task.CompletedTask); }); hubConnectionBuilder.Services.AddSingleton <IConnectionFactory>(delegateConnectionFactory); _hubConnection = hubConnectionBuilder.Build(); _hubConnection.StartAsync().GetAwaiter().GetResult(); _arguments = new object[ArgumentCount]; for (var i = 0; i < _arguments.Length; i++) { _arguments[i] = "Hello world!"; } }
public async Task ReadMessagesAsynchronouslyWorks() { var options = new PipeOptions(useSynchronizationContext: false, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline); var pair = DuplexPipe.CreateConnectionPair(options, options); await using var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application); var data = Encoding.UTF8.GetBytes("Hello World"); var protocol = new TestProtocol(); async Task WritingTask() { var writer = connection.Application.Output; for (var i = 0; i < 3; i++) { protocol.WriteMessage(data, writer); await writer.FlushAsync().ConfigureAwait(false); } await writer.CompleteAsync().ConfigureAwait(false); } async Task ReadingTask() { var reader = connection.CreatePipeReader(protocol); while (true) { var result = await reader.ReadAsync().ConfigureAwait(false); var buffer = result.Buffer; if (buffer.Length < 3 * data.Length) { reader.AdvanceTo(buffer.Start, buffer.End); continue; } Assert.Equal(Enumerable.Repeat(data, 3).SelectMany(a => a).ToArray(), buffer.ToArray()); reader.AdvanceTo(buffer.End); result = await reader.ReadAsync().ConfigureAwait(false); Assert.True(result.IsCompleted); break; } await reader.CompleteAsync(); } var readingTask = ReadingTask(); var writingTask = WritingTask(); await writingTask; await readingTask; }
public async Task TestLargePacket() { var serializer = new MqttPacketFormatterAdapter(MqttProtocolVersion.V311); var pipe = new DuplexPipeMockup(); var connection = new DefaultConnectionContext(); connection.Transport = pipe; var ctx = new MqttConnectionContext(serializer, connection); await ctx.SendPacketAsync(new MqttPublishPacket { Payload = new byte[20_000] }, CancellationToken.None).ConfigureAwait(false);
/// <summary> /// アクションが実行される直前に呼び出されます。 /// </summary> /// <param name="actionContext"> /// アクションに関する情報を格納する <see cref="System.Web.Http.Controllers.HttpActionContext"/>。 /// </param> public override void OnActionExecuting(HttpActionContext actionContext) { try { var value = actionContext.Request.Headers.Authorization; if (value == null) { throw new UnauthorizedAccessException(); } if (string.Equals(value.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) != true) { throw new UnauthorizedAccessException(); } var parameter = value.Parameter; if (string.IsNullOrEmpty(parameter) == true) { throw new UnauthorizedAccessException(); } var bytes = Convert.FromBase64String(parameter); var encoding = Encoding.GetEncoding("iso-8859-1"); var credentials = encoding.GetString(bytes); var separator = credentials.IndexOf(':'); var deviceId = Guid.Parse(credentials.Substring(0, separator)); var deviceKey = credentials.Substring(separator + 1); using (var dbContext = new DefaultConnectionContext()) { var device = dbContext.Devices .Where(x => x.DeviceId == deviceId) .Where(x => x.DeviceKey == deviceKey) .SingleOrDefault(); if (device == null) { throw new UnauthorizedAccessException(); } dbContext.AccessLogs.Add(new AccessLog() { LogId = Guid.NewGuid(), DeviceId = deviceId, Url = actionContext.Request.RequestUri.AbsolutePath.ToString(), CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow, }); dbContext.SaveChanges(); } } catch (UnauthorizedAccessException) { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Unauthorized; response.Headers.Add("WWW-Authenticate", "Basic Realm=Kanpuchi"); actionContext.Response = response; } catch (Exception ex) { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.InternalServerError; response.Content = new StringContent(ex.Message); actionContext.Response = response; } }
public static Mock <HubConnectionContext> CreateMock(DefaultConnectionContext connection) { var mock = new Mock <HubConnectionContext>(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance) { CallBase = true }; var protocol = new JsonHubProtocol(); mock.SetupGet(m => m.Protocol).Returns(protocol); return(mock); }
public static Mock <HubConnectionContext> CreateMock(DefaultConnectionContext connection) { var mock = new Mock <HubConnectionContext>(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance) { CallBase = true }; var readerWriter = new HubProtocolReaderWriter(new JsonHubProtocol(), new PassThroughEncoder()); mock.SetupGet(m => m.ProtocolReaderWriter).Returns(readerWriter); return(mock); }
public void OnConnection(IFeatureCollection features) { var connectionContext = new DefaultConnectionContext(features); Input = connectionContext.PipeFactory.Create(InputOptions ?? new PipeOptions()); Output = connectionContext.PipeFactory.Create(OutputOptions ?? new PipeOptions()); var feature = connectionContext.Features.Get <IConnectionTransportFeature>(); connectionContext.Transport = new PipeConnection(Input.Reader, Output.Writer); feature.Application = new PipeConnection(Output.Reader, Input.Writer); }
public void OnConnection(IFeatureCollection features) { var connectionContext = new DefaultConnectionContext(features); var feature = connectionContext.Features.Get <IConnectionTransportFeature>(); Input = new Pipe(InputOptions(feature.MemoryPool)); Output = new Pipe(OutputOptions(feature.MemoryPool)); connectionContext.Transport = new DuplexPipe(Input.Reader, Output.Writer); feature.Application = new DuplexPipe(Output.Reader, Input.Writer); }
public async Task TransportCommunicatesErrorToApplicationWhenClientDisconnectsAbnormally() { using (StartLog(out var loggerFactory, LogLevel.Debug)) { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); using (var feature = new TestWebSocketConnectionFeature()) { async Task CompleteApplicationAfterTransportCompletes() { try { // Wait until the transport completes so that we can end the application var result = await connection.Transport.Input.ReadAsync(); connection.Transport.Input.AdvanceTo(result.Buffer.End); } catch (Exception ex) { Assert.IsType <WebSocketError>(ex); } finally { // Complete the application so that the connection unwinds without aborting connection.Transport.Output.Complete(); } } var connectionContext = new DefaultConnectionContext(string.Empty, null, null); var ws = new WebSocketsTransport(new WebSocketOptions(), connection.Application, connectionContext, loggerFactory); // Give the server socket to the transport and run it var transport = ws.ProcessSocketAsync(await feature.AcceptAsync()); // Run the client socket var client = feature.Client.ExecuteAndCaptureFramesAsync(); // When the close frame is received, we complete the application so the send // loop unwinds _ = CompleteApplicationAfterTransportCompletes(); // Terminate the client to server channel with an exception feature.Client.SendAbort(); // Wait for the transport await transport.OrTimeout(); await client.OrTimeout(); } } }
public async Task TestReceivePacketAsyncThrowsWhenReaderCompleted() { var serializer = new MqttPacketFormatterAdapter(MqttProtocolVersion.V311); var pipe = new DuplexPipeMockup(); var connection = new DefaultConnectionContext(); connection.Transport = pipe; var ctx = new MqttConnectionContext(serializer, connection); pipe.Receive.Writer.Complete(); await Assert.ThrowsExceptionAsync <MqttCommunicationException>(() => ctx.ReceivePacketAsync(CancellationToken.None)); }
public async Task Set204StatusCodeWhenChannelComplete() { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); var poll = new LongPollingTransport(CancellationToken.None, connection.Application.Input, connectionId: string.Empty, loggerFactory: new LoggerFactory()); connection.Transport.Output.Complete(); await poll.ProcessRequestAsync(context, context.RequestAborted).OrTimeout(); Assert.Equal(204, context.Response.StatusCode); }
public static HubConnectionContext Create(DefaultConnectionContext connection, Channel <HubMessage> replacementOutput = null) { var context = new HubConnectionContext(connection, TimeSpan.FromSeconds(15), NullLoggerFactory.Instance); if (replacementOutput != null) { context.Output = replacementOutput; } context.ProtocolReaderWriter = new HubProtocolReaderWriter(new JsonHubProtocol(), new PassThroughEncoder()); _ = context.StartAsync(); return(context); }
public async Task TestReceivePacketAsyncThrowsWhenReaderCompleted() { var serializer = new MqttPacketSerializer { }; var pipe = new DuplexPipeMockup(); var connection = new DefaultConnectionContext(); connection.Transport = pipe; var ctx = new MqttConnectionContext(serializer, connection); pipe.Receive.Writer.Complete(); await Assert.ThrowsExceptionAsync <MqttCommunicationException>(() => ctx.ReceivePacketAsync(TimeSpan.FromSeconds(1), CancellationToken.None)); }
public async Task SSESetsContentType() { var pair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default); var connection = new DefaultConnectionContext("foo", pair.Transport, pair.Application); var context = new DefaultHttpContext(); var sse = new ServerSentEventsTransport(connection.Application.Input, connectionId: string.Empty, loggerFactory: new LoggerFactory()); connection.Transport.Output.Complete(); await sse.ProcessRequestAsync(context, context.RequestAborted); Assert.Equal("text/event-stream", context.Response.ContentType); Assert.Equal("no-cache", context.Response.Headers["Cache-Control"]); }
public async Task Set204StatusCodeWhenChannelComplete() { var toApplication = Channel.CreateUnbounded <byte[]>(); var toTransport = Channel.CreateUnbounded <byte[]>(); var context = new DefaultHttpContext(); var connection = new DefaultConnectionContext("foo", toTransport, toApplication); var poll = new LongPollingTransport(CancellationToken.None, toTransport.Reader, connectionId: string.Empty, loggerFactory: new LoggerFactory()); Assert.True(toTransport.Writer.TryComplete()); await poll.ProcessRequestAsync(context, context.RequestAborted).OrTimeout(); Assert.Equal(204, context.Response.StatusCode); }
public async Task MessageBiggerThanMaxMessageSizeThrows() { var options = new PipeOptions(useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); await using var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application); var data = Encoding.UTF8.GetBytes("Hello World"); var protocol = new TestProtocol(data.Length); var reader = connection.CreateReader(); var resultTask = reader.ReadAsync(protocol, maximumMessageSize: 5); await connection.Application.Output.WriteAsync(data); await Assert.ThrowsAsync <InvalidDataException>(async() => await resultTask); }
public async Task ReadMessagesAsynchronouslyWorks() { var options = new PipeOptions(useSynchronizationContext: false, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline); var pair = DuplexPipe.CreateConnectionPair(options, options); await using var connection = new DefaultConnectionContext(Guid.NewGuid().ToString(), pair.Transport, pair.Application); var data = Encoding.UTF8.GetBytes("Hello World"); var protocol = new TestProtocol(data.Length); async Task WritingTask() { for (int i = 0; i < 3; i++) { await connection.Application.Output.WriteAsync(data); } connection.Application.Output.Complete(); } async Task ReadingTask() { var reader = connection.CreateReader(); var count = 0; while (true) { var result = await reader.ReadAsync(protocol); if (result.IsCompleted) { break; } count++; Assert.Equal(data, result.Message); reader.Advance(); } Assert.Equal(3, count); } var readingTask = ReadingTask(); var writingTask = WritingTask(); await writingTask; await readingTask; }
public async Task SSESetsContentType() { var toApplication = Channel.CreateUnbounded <byte[]>(); var toTransport = Channel.CreateUnbounded <byte[]>(); var context = new DefaultHttpContext(); var connection = new DefaultConnectionContext("foo", toTransport, toApplication); var sse = new ServerSentEventsTransport(toTransport.Reader, connectionId: string.Empty, loggerFactory: new LoggerFactory()); Assert.True(toTransport.Writer.TryComplete()); await sse.ProcessRequestAsync(context, context.RequestAborted); Assert.Equal("text/event-stream", context.Response.ContentType); Assert.Equal("no-cache", context.Response.Headers["Cache-Control"]); }
private DefaultConnectionContext CreateConnectionContext(HubInvocationMessage message) { var connectionId = message.GetConnectionId(); // TODO: // No physical pipeline for logical ConnectionContext. These pipelines won't be used in current context. // So no exception or error will be thrown. // We should have a cleaner approach to reuse DefaultConnectionContext for Azure SignalR. var connectionContext = new DefaultConnectionContext(connectionId, null, null); if (message.TryGetClaims(out var claims)) { connectionContext.User = new ClaimsPrincipal(); connectionContext.User.AddIdentity(new ClaimsIdentity(claims, "Bearer")); } return(connectionContext); }