public async Task ReceiveAsync( PipeWriter writer, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && !Incoming.Any()) { await Task.Delay(100, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } GenericOperationMessage message = Incoming.Dequeue(); string json = JsonConvert.SerializeObject(message); byte[] buffer = Encoding.UTF8.GetBytes(json); Memory <byte> memory = writer.GetMemory(buffer.Length); for (int i = 0; i < buffer.Length; i++) { memory.Span[i] = buffer[i]; } writer.Advance(buffer.Length); await writer .FlushAsync(cancellationToken) .ConfigureAwait(false); }
public async Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { await context.CloseAsync().ConfigureAwait(false); }
public async Task Handle_InitializeMessage_True() { // arrange (WebSocketContext context, WebSocketMock socket) = WebSocketContextHelper.Create(); var handler = new ConnectionInitializeHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Initialize }; // act await handler.HandleAsync( context, message, CancellationToken.None); // assert Assert.Collection(socket.Outgoing, t => { Assert.Equal(MessageTypes.Connection.Accept, t.Type); }, t => { Assert.Equal(MessageTypes.Connection.KeepAlive, t.Type); }); }
public async Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { QueryRequest request = message.Payload.ToObject <QueryRequest>(); IExecutionResult result = await context.QueryExecuter.ExecuteAsync( new Execution.QueryRequest(request.Query, request.OperationName) { VariableValues = QueryMiddlewareUtilities .DeserializeVariables(request.Variables), Services = QueryMiddlewareUtilities .CreateRequestServices(context.HttpContext) }, cancellationToken).ConfigureAwait(false); if (result is IResponseStream responseStream) { context.RegisterSubscription( new Subscription(context, responseStream, message.Id)); } else if (result is IQueryExecutionResult queryResult) { await context.SendSubscriptionDataMessageAsync( message.Id, queryResult, cancellationToken); await context.SendSubscriptionCompleteMessageAsync( message.Id, cancellationToken); } }
public async Task Send_Start_ReceiveDataOnMutation() { // arrange TestServer testServer = CreateTestServer(); WebSocketClient client = CreateWebSocketClient(testServer); WebSocket webSocket = await client .ConnectAsync(SubscriptionUri, CancellationToken.None); await ConnectAsync(webSocket); var query = new SubscriptionQuery { Query = "subscription { foo }" }; // act string id = await webSocket.SendSubscriptionStartAsync(query); // assert await testServer.SendRequestAsync(new ClientQueryRequest { Query = "mutation { sendFoo }" }); GenericOperationMessage message = await WaitForMessage(webSocket, MessageTypes.Subscription.Data); Assert.NotNull(message); Assert.Equal(MessageTypes.Subscription.Data, message.Type); Dictionary <string, object> result = message.Payload .ToObject <Dictionary <string, object> >(); Assert.True(result.ContainsKey("data")); }
public async Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { ConnectionStatus connectionStatus = await context.OpenAsync(message.Payload.ToDictionary()) .ConfigureAwait(false); if (connectionStatus.Accepted) { await context.SendConnectionAcceptMessageAsync( cancellationToken).ConfigureAwait(false); await context.SendConnectionKeepAliveMessageAsync( cancellationToken).ConfigureAwait(false); } else { await context.SendConnectionErrorMessageAsync( connectionStatus.Response, cancellationToken) .ConfigureAwait(false); await context.CloseAsync().ConfigureAwait(false); } }
private async Task ReceiveMessagesAsync( CancellationToken cancellationToken) { using (var combined = CancellationTokenSource .CreateLinkedTokenSource(cancellationToken, _cts.Token)) { while (!_context.CloseStatus.HasValue || !combined.IsCancellationRequested) { GenericOperationMessage message = await _context .ReceiveMessageAsync(combined.Token); if (message == null) { await _context.SendConnectionKeepAliveMessageAsync( combined.Token).ConfigureAwait(false); } else { await HandleMessage(message, combined.Token) .ConfigureAwait(false); } } } }
public async Task Can_AcceptMessage_False() { // arrange var webSocketContext = new InMemoryWebSocketContext(); var handler = new ConnectionInitializeHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Initialize }; // act await handler.HandleAsync( webSocketContext, message, CancellationToken.None); // assert Assert.Collection(webSocketContext.Outgoing, t => { Assert.Equal(MessageTypes.Connection.Accept, t.Type); }, t => { Assert.Equal(MessageTypes.Connection.KeepAlive, t.Type); }); }
private async Task <GenericOperationMessage> WaitForMessage( WebSocket webSocket, string messageType, TimeSpan timeout) { Stopwatch timer = Stopwatch.StartNew(); try { while (timer.Elapsed <= timeout) { GenericOperationMessage message = await webSocket.ReceiveServerMessageAsync(); if (messageType.Equals(message?.Type)) { return(message); } if (message != null && !MessageTypes.Connection.KeepAlive.Equals( message.Type)) { throw new Exception( $"Unexpected message type: {message.Type}"); } } } finally { timer.Stop(); } return(null); }
public Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { context.UnregisterSubscription(message.Id); return(Task.CompletedTask); }
public Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { context.Dispose(); return(Task.CompletedTask); }
public async Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { await context.SendConnectionAcceptMessageAsync( cancellationToken); await context.SendConnectionKeepAliveMessageAsync( cancellationToken); }
public void CanHandle_AcceptMessage_False() { // arrange var handler = new ConnectionTerminateHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Accept }; // act bool result = handler.CanHandle(message); // assert Assert.False(result); }
public void CanHandle_SubscriptionStart_True() { // arrange var handler = new SubscriptionStartHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Subscription.Start }; // act bool result = handler.CanHandle(message); // assert Assert.True(result); }
public void CanHandle_InitializeMessage_True() { // arrange var handler = new ConnectionInitializeHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Initialize }; // act bool result = handler.CanHandle(message); // assert Assert.True(result); }
private async Task ConnectAsync(WebSocket webSocket) { // act await webSocket.SendConnectionInitializeAsync(); // assert GenericOperationMessage message = await webSocket.ReceiveServerMessageAsync(); Assert.NotNull(message); Assert.Equal(MessageTypes.Connection.Accept, message.Type); message = await webSocket.ReceiveServerMessageAsync(); Assert.NotNull(message); Assert.Equal(MessageTypes.Connection.KeepAlive, message.Type); }
private Task HandleMessage( GenericOperationMessage message, CancellationToken cancellationToken) { foreach (IRequestHandler requestHandler in _requestHandlers) { if (requestHandler.CanHandle(message)) { return(requestHandler.HandleAsync( _context, message, cancellationToken)); } } throw new NotSupportedException( "The specified message type is not supported."); }
public async Task Handle_TerminateMessage_True() { // arrange (WebSocketContext context, WebSocketMock socket) = WebSocketContextHelper.Create(); var handler = new ConnectionTerminateHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Terminate }; // act await handler.HandleAsync( context, message, CancellationToken.None); // assert Assert.True(socket.Closed); }
private async Task <GenericOperationMessage> WaitForMessage( WebSocket webSocket, string messageType) { for (var i = 0; i < 10; i++) { GenericOperationMessage message = await webSocket.ReceiveServerMessageAsync(); if (message?.Type == messageType) { return(message); } if (message?.Type != MessageTypes.Connection.KeepAlive) { break; } } return(null); }
public async Task Can_AcceptMessage_False() { // arrange var webSocketContext = new InMemoryWebSocketContext(); var handler = new ConnectionTerminateHandler(); var message = new GenericOperationMessage { Type = MessageTypes.Connection.Terminate }; // act await handler.HandleAsync( webSocketContext, message, CancellationToken.None); // assert Assert.True(webSocketContext.IsDisposed); }
public async Task ReceiveMessageAsync( Stream messageStream, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && !Incoming.Any()) { await Task.Delay(100, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } GenericOperationMessage message = Incoming.Dequeue(); string json = JsonConvert.SerializeObject(message); byte[] buffer = Encoding.UTF8.GetBytes(json); messageStream.Write(buffer, 0, buffer.Length); }
public async Task HandleAsync( IWebSocketContext context, GenericOperationMessage message, CancellationToken cancellationToken) { QueryRequestDto payload = message.Payload.ToObject <QueryRequestDto>(); IQueryRequestBuilder requestBuilder = QueryRequestBuilder.New() .SetQuery(payload.Query) .SetOperation(payload.OperationName) .SetVariableValues(QueryMiddlewareUtilities .ToDictionary(payload.Variables)) .SetServices(context.HttpContext.CreateRequestServices()); await context.PrepareRequestAsync(requestBuilder) .ConfigureAwait(false); IExecutionResult result = await context.QueryExecutor.ExecuteAsync( requestBuilder.Create(), cancellationToken) .ConfigureAwait(false); if (result is IResponseStream responseStream) { context.RegisterSubscription( new Subscription(context, responseStream, message.Id)); } else if (result is IReadOnlyQueryResult queryResult) { await context.SendSubscriptionDataMessageAsync( message.Id, queryResult, cancellationToken) .ConfigureAwait(false); await context.SendSubscriptionCompleteMessageAsync( message.Id, cancellationToken) .ConfigureAwait(false); } }
private async Task HandleMessageAsync( string content, CancellationToken cancellationToken) { GenericOperationMessage message = JsonConvert .DeserializeObject <GenericOperationMessage>(content); foreach (IRequestHandler handler in RequestHandlers) { if (handler.CanHandle(message)) { await handler.HandleAsync( _context, message, cancellationToken) .ConfigureAwait(false); return; } } throw new NotSupportedException( "The specified message type is not supported."); }
public bool CanHandle(GenericOperationMessage message) { return(message.Type == MessageTypes.Connection.Initialize); }
public bool CanHandle(GenericOperationMessage message) { return(message.Type == MessageTypes.Subscription.Start); }
public bool CanHandle(GenericOperationMessage message) { return(message.Type == MessageTypes.Connection.Terminate); }