public static void Complete <T>(this IWritableChannel <T> channel) { if (!channel.TryComplete()) { throw new OperationCanceledException(); } }
public static async Task CopyToAsync(this Stream stream, IWritableChannel channel) { while (true) { var end = channel.BeginWrite(); var block = end.Block; try { int bytesRead = await stream.ReadAsync(block.Array, block.End, block.Data.Offset + block.Data.Count - block.End); if (bytesRead == 0) { channel.CompleteWriting(); break; } else { end.UpdateEnd(bytesRead); await channel.EndWriteAsync(end); } } catch (Exception error) { channel.CompleteWriting(error); break; } } }
public HttpConnection(IHttpApplication <TContext> application, IReadableChannel input, IWritableChannel output) { _application = application; _input = input; _output = output; _initialBody = new HttpBodyStream <TContext>(this); }
public static Task WriteAsync(this IWritableChannel channel, byte[] buffer, int offset, int count) { var writeBuffer = channel.Alloc(); writeBuffer.Write(buffer, offset, count); return(channel.WriteAsync(writeBuffer)); }
public async Task AppLaunchedEventStream(Empty request, IWritableChannel <AppLaunchedEvent> responseStream, MethodCallContext context) { Log.Debug("AppLaunchedEventStream pipe started"); await _appLaunchedEvents.PipeAsync(responseStream, context.CancellationToken).ConfigureAwait(false); Log.Debug("AppLaunchedEventStream pipe finished"); }
public async Task ContextLoadedStream(ContextDto request, IWritableChannel <ContextLoadingUpdate> responseStream, MethodCallContext callContext) { var context = _contextsSet.GetContext(request.Id); if (context == null) { throw new Exception($"There is no context with {request.Id} id"); } await Observable.Return(Unit.Default) .Merge(context.ContextUpdatedEventStream) .ObserveOn(TaskPoolScheduler.Default) .Throttle(TimeSpan.FromMilliseconds(200)) .Select(_ => new ContextLoadingUpdate { LoadedAppDescriptors = { context.GetConnectedApps().Select(ConvertToProto) }, Status = context.IsLoading ? ContextLoadingStatus.InProgress : ContextLoadingStatus.Finished, }) .DistinctUntilChanged() .Do(update => { Log.Debug( $"Sending context linkage update for context {context.Id}: LoadedAppDescriptorsCount={update.LoadedAppDescriptors.Count}"); }) .PipeAsync(responseStream, callContext.CancellationToken); }
private static async Task CopyCompletedAsync(IReadableChannel input, IWritableChannel channel) { await input; do { var fin = input.Completion.IsCompleted; var inputBuffer = input.BeginRead(); try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = channel.Alloc(); buffer.Append(inputBuffer); await channel.WriteAsync(buffer); } finally { input.EndRead(inputBuffer); } }while (input.IsCompleted); }
private static async Task CopyCompletedAsync(IReadableChannel input, IWritableChannel channel) { var inputBuffer = await input; do { var fin = input.Completion.IsCompleted; try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = channel.Alloc(); buffer.Append(inputBuffer); await buffer.FlushAsync(); } finally { inputBuffer.Consumed(); } }while (input.IsCompleted); }
public static async Task CopyToAsync(this IReadableChannel input, IWritableChannel channel) { while (true) { await input; var fin = input.Completion.IsCompleted; var inputBuffer = input.BeginRead(); try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = channel.Alloc(); buffer.Append(inputBuffer); await channel.WriteAsync(buffer); } finally { input.EndRead(inputBuffer); } } }
public static async Task CopyToAsync(this IReadableChannel input, IWritableChannel output) { while (true) { var result = await input.ReadAsync(); var inputBuffer = result.Buffer; var fin = result.IsCompleted; try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = output.Alloc(); buffer.Append(inputBuffer); await buffer.FlushAsync(); } finally { input.Advance(inputBuffer.End); } } }
/// <summary> /// Constructs a new <see cref="WebSocketConnection"/> from an <see cref="IReadableChannel"/> and an <see cref="IWritableChannel"/> that represents an established WebSocket connection (i.e. after handshaking) /// </summary> /// <param name="inbound">A <see cref="IReadableChannel"/> from which frames will be read when receiving.</param> /// <param name="outbound">A <see cref="IWritableChannel"/> to which frame will be written when sending.</param> /// <param name="subProtocol">The sub-protocol provided during handshaking</param> /// <param name="options">A <see cref="WebSocketOptions"/> which provides the configuration options for the socket.</param> public WebSocketConnection(IReadableChannel inbound, IWritableChannel outbound, string subProtocol, WebSocketOptions options) { _inbound = inbound; _outbound = outbound; _options = options; SubProtocol = subProtocol; if (_options.FixedMaskingKey != null) { // Use the fixed key directly as the buffer. _maskingKeyBuffer = _options.FixedMaskingKey; // Clear the MaskingKeyGenerator just to ensure that nobody set it. _options.MaskingKeyGenerator = null; } else if (_options.MaskingKeyGenerator != null) { // Establish a buffer for the random generator to use _maskingKeyBuffer = new byte[4]; } if (_options.PingInterval > TimeSpan.Zero) { var pingIntervalMillis = (int)_options.PingInterval.TotalMilliseconds; // Set up the pinger _pinger = new Timer(Pinger, this, pingIntervalMillis, pingIntervalMillis); } }
public static async Task CopyToAsync(this Stream stream, IWritableChannel channel) { while (true) { var buffer = channel.Alloc(2048); try { int bytesRead = await stream.ReadAsync(buffer.Memory.Array, buffer.Memory.Offset, buffer.Memory.Length); if (bytesRead == 0) { channel.CompleteWriting(); break; } else { buffer.UpdateWritten(bytesRead); await channel.WriteAsync(buffer); } } catch (Exception error) { channel.CompleteWriting(error); break; } } }
private static async Task CopyCompletedAsync(IReadableChannel input, IWritableChannel channel) { var inputBuffer = await input.ReadAsync(); while (true) { try { if (inputBuffer.IsEmpty && input.Completion.IsCompleted) { return; } var buffer = channel.Alloc(); buffer.Append(ref inputBuffer); await buffer.FlushAsync(); } finally { inputBuffer.Consumed(); } var awaiter = input.ReadAsync(); if (!awaiter.IsCompleted) { // No more data break; } inputBuffer = await awaiter; } }
public static async Task CopyToAsync(this IReadableChannel input, IWritableChannel output) { while (true) { var inputBuffer = await input.ReadAsync(); var fin = input.Completion.IsCompleted; try { if (inputBuffer.IsEmpty && fin) { return; } var buffer = output.Alloc(); buffer.Append(ref inputBuffer); await buffer.FlushAsync(); } finally { inputBuffer.Consumed(); } } }
public static Task WriteAsync(this IWritableChannel channel, byte[] buffer, int offset, int length) { var end = channel.BeginWrite(); end.CopyFrom(buffer, offset, length); return(channel.EndWriteAsync(end)); }
private static async Task WriteItems(IWritableChannel <int> channel, CancellationToken cancellationToken) { // Start generating items int counter = 0; while (!cancellationToken.IsCancellationRequested && counter < 5) { try { var value = counter++; Console.WriteLine($"Sending: {value}"); await channel.WriteAsync(value); Console.WriteLine("Waiting 0.5sec"); await Task.Delay(500); } catch (Exception ex) { Console.WriteLine($"Sender Threw: {ex}"); return; } } Console.WriteLine("Completing channel"); channel.Complete(); }
private static void Pipes_EnumerateValues() { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <int> writer = Channel.WriteToStream <int>(serverPipe); IReadableChannel <int> reader = Channel.ReadFromStream <int>(clientPipe); Task.WaitAll( Task.Run(async() => { for (int i = 0; i < 100; i++) { await writer.WriteAsync(i); } writer.Complete(); Assert.False(writer.TryWrite(100)); }), Task.Run(async() => { int i = 0; IAsyncEnumerator <int> e = reader.GetAsyncEnumerator(); while (await e.MoveNextAsync()) { Assert.Equal(i++, e.Current); } })); } }
public static Task WriteAsync(this IWritableChannel channel, Span <byte> source) { var writeBuffer = channel.Alloc(); writeBuffer.Write(source); return(writeBuffer.FlushAsync()); }
private static async Task Pipes_ReadWriteValues <T>(bool firstWaitToRead, int numItems, Func <int, T> getValue) { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <T> writer = Channel.WriteToStream <T>(serverPipe); IReadableChannel <T> reader = Channel.ReadFromStream <T>(clientPipe); for (int i = 0; i < numItems; i++) { T itemToWrite = getValue(i); Task <T> readItem = firstWaitToRead ? reader.WaitToReadAsync().ContinueWith(_ => reader.ReadAsync().AsTask()).Unwrap() : reader.ReadAsync().AsTask(); Task writeItem = writer.WriteAsync(itemToWrite); await Task.WhenAll(readItem, writeItem); Assert.Equal(itemToWrite, readItem.Result); } writer.Complete(); Assert.False(await reader.WaitToReadAsync()); await reader.Completion; } }
private static void Pipes_WaitForReadThenTryReadValues() { using (AnonymousPipeServerStream serverPipe = new AnonymousPipeServerStream(PipeDirection.Out)) using (AnonymousPipeClientStream clientPipe = new AnonymousPipeClientStream(PipeDirection.In, serverPipe.ClientSafePipeHandle)) { IWritableChannel <int> writer = Channel.WriteToStream <int>(serverPipe); IReadableChannel <int> reader = Channel.ReadFromStream <int>(clientPipe); Task.WaitAll( Task.Run(async() => { for (int i = 0; i < 100; i++) { await writer.WriteAsync(i); } writer.Complete(); Assert.False(writer.TryWrite(100)); }), Task.Run(async() => { int result; int i = 0; while (await reader.WaitToReadAsync()) { if (reader.TryRead(out result)) { Assert.Equal(i++, result); } } Assert.False(reader.TryRead(out result)); })); } }
/// <summary>Creates an observer for a writeable channel.</summary> /// <typeparam name="T">Specifies the type of data in the channel.</typeparam> /// <param name="target">The channel to be treated as an observer.</param> /// <returns>An observer that forwards to the specified channel.</returns> public static IObserver <T> AsObserver <T>(this IWritableChannel <T> target) { if (target == null) { throw new ArgumentNullException("target"); } return(new ChannelObserver <T>(target)); }
public HttpConnection(IHttpApplication <TContext> application, IReadableChannel input, IWritableChannel output) { _application = application; _input = input; _output = output; _requestBody = new HttpRequestStream <TContext>(this); _responseBody = new HttpResponseStream <TContext>(this); }
public PropagatingChannel( int bufferSize, IWritableChannel <TOut> output, Func <T, IWriteOnlyChannel <TOut>, Task> consumeAsync, Action <T> disposeRejected) : this(bufferSize, output, null, consumeAsync, null, null, disposeRejected) { }
public async Task GetConnectionsStream(GetConnectionsRequest request, IWritableChannel <GetConnectionsEvent> responseStream, MethodCallContext context) { await _appLifecycleManager.ConnectionEventsStream .Where(e => IsEventFitRequest(request, e.Connection)) .Select(e => CreateGetConnectionsEvent(request, e)) .Where(e => e != null) .StartWith(CreateInitialGetConnectionsEvent(request)) .PipeAsync(responseStream); }
public static void Terminate <T>( this IWritableChannel <T> channel, Exception error = null) { if (!channel.TryTerminate(error)) { throw new OperationCanceledException(); } }
public HttpConnection(IHttpApplication<TContext> application, IReadableChannel input, IWritableChannel output) { _application = application; _input = input; _output = output; _requestBody = new HttpRequestStream<TContext>(this); _responseBody = new HttpResponseStream<TContext>(this); _outputFormatter = _output.GetFormatter(EncodingData.InvariantUtf8); }
public void WriteToStream_Precancellation() { IWritableChannel <int> w = Channel.WriteToStream <int>(new MemoryStream()); var cts = new CancellationTokenSource(); cts.Cancel(); AssertSynchronouslyCanceled(w.WaitToWriteAsync(cts.Token), cts.Token); AssertSynchronouslyCanceled(w.WriteAsync(42, cts.Token), cts.Token); }
public static async Task WriteAsync <T>(this IWritableChannel <T> channel, T item, CancellationToken cancellationToken = default) { var result = await channel.TryWriteAsync(item, cancellationToken).ConfigureAwait(false); if (!result) { throw new OperationCanceledException(); } }
public Task AppJoinedContextStream(Empty request, IWritableChannel <AppJoinedContextEvent> responseStream, MethodCallContext callContext) { return(_contextsSet.AppContextBindingEvents .Select(ev => new AppJoinedContextEvent { AppInstanceId = ev.AppInstanceId.ToProto(), Context = ConvertContextToProto(ev.Context, ev.AppInstanceId) }) .PipeAsync(responseStream, callContext.CancellationToken)); }
public IWritableChannel MakeWriteableChannel(IWritableChannel channel, Func <IReadableChannel, IWritableChannel, Task> consume) { var newChannel = new Channel(_pool); consume(newChannel, channel).ContinueWith(t => { }); return(newChannel); }