private async Task StreamContentAsync(Stream input, byte[] buffer, IClientStreamWriter <PushFileRequest> requestStream, CancellationToken ct) { Contract.Requires(!(input is null)); Contract.Requires(!(requestStream is null)); int chunkSize = 0; // Pre-fill buffer with the file's first chunk await readNextChunk(); while (true) { ct.ThrowIfCancellationRequested(); if (chunkSize == 0) { break; } ByteString content = ByteString.CopyFrom(buffer, 0, chunkSize); var request = new PushFileRequest() { Content = content }; // Read the next chunk while waiting for the response await Task.WhenAll(readNextChunk(), requestStream.WriteAsync(request)); } async Task <int> readNextChunk() { chunkSize = await input.ReadAsync(buffer, 0, buffer.Length, ct); return(chunkSize); } }
public async Task RunSample() { AsyncClientStreamingCall <GatherRequest, GatherResponse> streaming = client.Gather(); IClientStreamWriter <GatherRequest> streamWriter = streaming.RequestStream; while (true) { Console.WriteLine("Write a name to add to the list (press Enter to finish)"); string input = Console.ReadLine(); if (!string.IsNullOrEmpty(input)) { Console.WriteLine($"Streaming name '{input}' to server"); await streamWriter.WriteAsync(new() { Msg = input }); Console.WriteLine("Name successfully streamed to server"); Console.WriteLine(); } else { break; } } await streamWriter.CompleteAsync(); Console.WriteLine("Submitting data to server..."); GatherResponse response = await streaming.ResponseAsync; Console.WriteLine("Server responded: "); Console.WriteLine(response.Result); }
/// <summary> /// Creates a test double for <c>AsyncDuplexStreamingCall</c>. Only for testing. /// Note: experimental API that can change or be removed without any prior notice. /// </summary> public static AsyncDuplexStreamingCall <TRequest, TResponse> AsyncDuplexStreamingCall <TResponse, TRequest>( IClientStreamWriter <TRequest> requestStream, IAsyncStreamReader <TResponse> responseStream, Task <Metadata> responseHeadersAsync, Func <Status> getStatusFunc, Func <Metadata> getTrailersFunc, Action disposeAction) { return(new AsyncDuplexStreamingCall <TRequest, TResponse>(requestStream, responseStream, responseHeadersAsync, getStatusFunc, getTrailersFunc, disposeAction)); }
private static bool SatisfyDataRequest( [NotNull] DataVerificationResponse arg, [NotNull] IVerificationDataProvider verificationDataProvider, [NotNull] IClientStreamWriter <DataVerificationRequest> callRequestStream) { DataVerificationRequest result = new DataVerificationRequest(); try { if (arg.SchemaRequest != null) { result.Schema = verificationDataProvider.GetGdbSchema(arg.SchemaRequest); } else if (arg.DataRequest != null) { result.Data = verificationDataProvider .GetData(arg.DataRequest).FirstOrDefault(); } callRequestStream.WriteAsync(result); return(true); } catch (Exception e) { _msg.Debug("Error handling data request", e); // Send an empty message to make sure the server does not wait forever: callRequestStream.WriteAsync(result); throw; } }
private async Task <bool> ProvideDataToServer( [NotNull] DataVerificationResponse serverResponseMsg, [NotNull] IClientStreamWriter <DataVerificationRequest> dataStream, [NotNull] CancellationTokenSource cancellationSource) { if (_msg.IsVerboseDebugEnabled) { _msg.DebugFormat("Sending verification data for {0}...", serverResponseMsg); } Assert.NotNull(VerificationDataProvider, "No verification data provider available."); Func <bool> getDataFunc = () => SatisfyDataRequest( serverResponseMsg, VerificationDataProvider, dataStream); bool result = await Task.Factory.StartNew( () => TryExecute(getDataFunc, cancellationSource.Token, "SatisfyDataRequest"), cancellationSource.Token, TaskCreationOptions.LongRunning, StaTaskScheduler); if (result) { _msg.DebugFormat("Successfully provided verification data for to the server."); } return(result); }
public async Task StartWriterAsync(IClientStreamWriter <StreamingMessage> requestStream) { await foreach (StreamingMessage rpcWriteMsg in _outputChannel.Channel.Reader.ReadAllAsync()) { await requestStream.WriteAsync(rpcWriteMsg); } }
public TracingClientStreamWriter(IClientStreamWriter <T> writer, ClientInterceptorContext <T, TResponse> context, Action <T, ClientInterceptorContext <T, TResponse> > onWrite, Action onComplete = null) { _writer = writer; _context = context; _onWrite = onWrite; _onComplete = onComplete; }
private Task StartedAsync() { Console.WriteLine("[REMOTING] Started EndpointWriter for address {0}", _address); Console.WriteLine("[REMOTING] EndpointWriter connecting to address {0}", _address); _channel = new Channel(_address, ChannelCredentials.Insecure); _client = new Remoting.RemotingClient(_channel); _stream = _client.Receive(); Task.Factory.StartNew(async() => { try { await _stream.ResponseStream.ForEachAsync(i => Actor.Done); } catch (Exception x) { Console.WriteLine( $"[REMOTING] EndpointWriter lost connection to address {_address}, reason {x.Message}"); var terminated = new EndpointTerminatedEvent { Address = _address }; Actor.EventStream.Publish(terminated); } }); _streamWriter = _stream.RequestStream; Console.WriteLine("[REMOTING] EndpointWriter connected to address {0}", _address); return(Actor.Done); }
/// <summary> /// Constructs an instance which writes to the specified writer, and with the given capacity. /// </summary> /// <param name="writer">The writer to delegate to.</param> /// <param name="capacity">The maximum number of messages to buffer.</param> public BufferedClientStreamWriter(IClientStreamWriter <T> writer, int capacity) { _writer = GaxPreconditions.CheckNotNull(writer, nameof(writer)); _queue = new LinkedList <Request>(); Capacity = capacity; GaxPreconditions.CheckArgument(capacity >= 1, nameof(capacity), "Capacity cannot be less than 1."); }
/// <summary> /// Writes the specified requests. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <param name="streamWriter"></param> /// <param name="requests">The requests.</param> /// <returns></returns> public static async Task WriteRequestsAsync <TRequest>(this IClientStreamWriter <TRequest> streamWriter, IEnumerable <Task <TRequest> > requests) { foreach (Task <TRequest> request in requests) { await streamWriter.WriteAsync(await request.ConfigureAwait(false)).ConfigureAwait(false); } }
public CalculatorDuplexCallbackStreamHandler(ICalculatorDuplexClientCallback callback, IClientStreamWriter <Protos.CalculatorDuplexAction> requestStream, IAsyncStreamReader <Protos.CalculatorDuplexCallback> responseStream) { _callback = callback; _requestStream = requestStream; _responseStream = responseStream; _pendingCompletions = new PendingCompletionStore(TimeSpan.FromMinutes(1)); }
private Task StartedAsync() { _logger.LogDebug($"Connecting to address {_address}"); _channel = new Channel(_address, _channelCredentials, _channelOptions); _client = new Remoting.RemotingClient(_channel); _stream = _client.Receive(_callOptions); Task.Factory.StartNew(async() => { try { await _stream.ResponseStream.ForEachAsync(i => Actor.Done); } catch (Exception x) { _logger.LogError($"Lost connection to address {_address}, reason {x.Message}"); var terminated = new EndpointTerminatedEvent { Address = _address }; Actor.EventStream.Publish(terminated); } }); _streamWriter = _stream.RequestStream; _logger.LogDebug($"Connected to address {_address}"); return(Actor.Done); }
public ClientStreamWriterWrapper(IClientStreamWriter <TRequest> wrapped, ILogger logger, CancellationToken token) { _wrapped = wrapped; _logger = logger; _token = token; }
public bool TrySendData(IClientStreamWriter <TRequest> requestStream, TRequest item, int sendTimeoutMs, CancellationToken cancellationToken) { try { //If there is no channel, return if (cancellationToken.IsCancellationRequested) { return(false); } return(requestStream.WriteAsync(item).Wait(sendTimeoutMs, cancellationToken)); } catch (Exception ex) { const string errorMessage = "Unable to create gRPC Request/Response Streams"; var invalidOperEx = ex as InvalidOperationException; if (invalidOperEx != null && invalidOperEx.Message == "Request stream has already been completed.") { throw new GrpcWrapperStreamNotAvailableException(errorMessage, invalidOperEx); } var grpcEx = ex as RpcException ?? ex.InnerException as RpcException; if (grpcEx != null) { throw new GrpcWrapperException(grpcEx.StatusCode, errorMessage, grpcEx); } throw new GrpcWrapperException(errorMessage, ex); } }
/// <summary> /// Initializes a new instance of the <see cref="ClientStreamWriterProxy{T}"/> class. /// </summary> /// <param name="writer">The writer.</param> /// <param name="onWrite">The on write action if any.</param> /// <param name="onComplete">The on complete action, if any.</param> /// <param name="onException">The on exception action, if any.</param> public ClientStreamWriterProxy(IClientStreamWriter <T> writer, Action <T> onWrite = null, Action onComplete = null, Action <Exception> onException = null) { this.writer = writer; this.onWrite = onWrite; this.onComplete = onComplete; this.onException = onException; }
public ClientStreamingResult(AsyncClientStreamingCall <byte[], byte[]> inner, IClientStreamWriter <TRequest> requestStream, MessagePackSerializerOptions serializerOptions) { this.hasRawValue = false; this.rawValue = default(TResponse); this.inner = inner; this.requestStream = requestStream; this.serializerOptions = serializerOptions; }
public AsyncClientStreamingCall(IClientStreamWriter <TRequest> requestStream, Task <TResponse> responseAsync, Func <Status> getStatusFunc, Func <Metadata> getTrailersFunc, Action disposeAction) { this.requestStream = requestStream; this.responseAsync = responseAsync; this.getStatusFunc = getStatusFunc; this.getTrailersFunc = getTrailersFunc; this.disposeAction = disposeAction; }
private Task StartedAsync() { _channel = new Channel(_host, ChannelCredentials.Insecure); _client = new Remoting.RemotingClient(_channel); _stream = _client.Receive(); _streamWriter = _stream.RequestStream; return(Actor.Done); }
public ClientStreamingResponse(TResponse rawValue) { this.hasRawValue = true; this.rawValue = rawValue; this.inner = null; this.requestStream = null; //this.resolver = null; }
public static IDisposable Write <T>(this IObservable <T> source, IClientStreamWriter <T> writer) { return(SubscribeAsync(source, onNext: writer.WriteAsync, onError: ex => { }, onCompleted: () => writer.CompleteAsync())); }
public ClientStreamingResult(TResponse rawValue) { this.hasRawValue = true; this.rawValue = rawValue; this.inner = null; this.requestStream = null; this.serializerOptions = null; }
/// <summary> /// Writes the specified requests and send a completion. /// </summary> /// <typeparam name="TRequest">The type of the request.</typeparam> /// <param name="streamWriter"></param> /// <param name="requests">The requests.</param> /// <returns></returns> public static async Task WriteRequestsAndCompleteAsync <TRequest>(this IClientStreamWriter <TRequest> streamWriter, IEnumerable <TRequest> requests) { foreach (TRequest request in requests) { await streamWriter.WriteAsync(request).ConfigureAwait(false); } await streamWriter.CompleteAsync().ConfigureAwait(false); }
internal AsyncDuplexStreamingCall(IClientStreamWriter <TRequest> requestStream, IAsyncStreamReader <TResponse> responseStream, Task <Metadata> responseHeadersAsync, Func <Status> getStatusFunc, Func <Metadata> getTrailersFunc, Action disposeAction) { this.requestStream = requestStream; this.responseStream = responseStream; this.responseHeadersAsync = responseHeadersAsync; this.getStatusFunc = getStatusFunc; this.getTrailersFunc = getTrailersFunc; this.disposeAction = disposeAction; }
private static AsyncDuplexStreamingCall <string, string> BuildDuplexCall(IAsyncStreamReader <string> reader, IClientStreamWriter <string> writer) { var metadataTask = Task.Run(() => new Metadata()); return(new AsyncDuplexStreamingCall <string, string>(writer, reader, metadataTask, () => new Status(), () => new Metadata(), () => { })); }
internal Subscriber(Grpc.Core.AsyncDuplexStreamingCall <FastQueueService.CompleteRequest, FastQueueService.Messages> duplexStream, Action <ISubscriber, IEnumerable <Message> > messagesHandler) { this.duplexStream = duplexStream; this.messagesHandler = messagesHandler; requestStream = duplexStream.RequestStream; responseStream = duplexStream.ResponseStream; cancellationTokenSource = new CancellationTokenSource(); }
/// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="method"></param> /// <param name="host"></param> /// <param name="options"></param> /// <param name="onCompleted"></param> /// <param name="performanceListener"></param> internal RequestStreamWriter(IClientStreamWriter <TRequest> target, IMethod method, string host, CallOptions options, Action onCompleted, GrpcClientPerformanceListener performanceListener) { m_Target = target; m_Method = method; m_Host = host; m_Options = options; m_OnCompleted = onCompleted; m_PerformanceListener = performanceListener; }
public ClientStreamWriterInterceptor( IClientStreamWriter <TRequest> original, ClientCallInterceptorContext context, IClientCallInterceptor interceptor) { _original = original; _context = context; _interceptor = interceptor; }
public AgonesSDK(int healthInterval = 5, bool healthEnabled = true, double requestTimeout = 15) { this.HealthInterval = healthInterval; this.HealthEnabled = healthEnabled; this.RequestTimeout = requestTimeout; this.channel = new Channel(Host, Port, ChannelCredentials.Insecure); this.client = new SDK.SDKClient(channel); this.healthStream = client.Health().RequestStream; }
/// <inheritdoc/> public void Connect(IClientStreamWriter <PlayerResponse> stream) { if (State == ManagerConnectionState.Connected) { throw new InvalidOperationException("Already connected. This should never happen!"); } PlayerResponseStream = stream; }
public DrawService(GrpcChannel channel) { _channel = channel; _client = new Draw.DrawClient(channel); id = _client.ReceiveId(new IdRequest()).Id; _stream = _client.DrawPoints(); _requestStream = _stream.RequestStream; _responseStream = _stream.ResponseStream; }