/// <summary> /// This helper ensures we invalidate the _currentCall state if we want to throw canceled. /// </summary> private void ThrowIfCancellationRequested(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { _currentCall?.Dispose(); _currentCall = null; cancellationToken.ThrowIfCancellationRequested(); } }
// Example of an ongoing stream of replies from the demo heartbeat method async void HandleUpdates(AsyncServerStreamingCall <GameUpdate> updates) { IAsyncStreamReader <GameUpdate> stream = updates.ResponseStream; while (await stream.MoveNext()) { Debug.Log("Received GameUpdate: " + stream.Current.ToString()); game.HandleUpdate(stream.Current); } }
/// <summary> /// Tries to the get call trailers. /// </summary> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <param name="call">The call.</param> /// <returns>The trailing metadata, if the call has completed, an empty metadata if the /// call is ongoing.</returns> /// <remarks>There is currently no exposed method in the gRPC stack to check if an API call /// has completed.</remarks> private Metadata TryGetCallTrailers <TResponse>(AsyncServerStreamingCall <TResponse> call) { try { return(call.GetTrailers()); } catch (InvalidOperationException) { return(new Metadata()); } }
private static async Task ProcessStream(AsyncServerStreamingCall <WeatherResponse> response) { var stream = response.ResponseStream; while (await stream.MoveNext()) { var result = stream.Current; Console.WriteLine($"From Stream: {result}"); } }
/// <summary> /// ファイルダウンロード /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void FileDownloadButton_Click(object sender, RoutedEventArgs e) { string fileName = System.IO.Path.GetFileName(this.xDownloadFileNameTextBox.Text); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "txt files (*.txt)|*.txt"; saveFileDialog.FileName = fileName; if (this.xDownloadFileNameTextBox.Text.Length == 0) { return; } if (saveFileDialog.ShowDialog() == false) { return; } this.FileDownloadButton.IsEnabled = false; this.CancelButton.IsEnabled = true; this.xDownloadMessage.Text = fileName + " ダウンロード中"; FileDownloadRequest fileDownloadRequest = new FileDownloadRequest(); fileDownloadRequest.FileName = this.xDownloadFileNameTextBox.Text; // gRPC サービスを呼び出す。 //var response = this.grpcClient.GreeterClient.FileDownload(fileDownloadRequest); this._responseFileDownload = this.grpcClient.GreeterClient.FileDownload(fileDownloadRequest); try { using (var fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write)) { int offset = 0; while (await this._responseFileDownload?.ResponseStream.MoveNext()) { var reply = this._responseFileDownload.ResponseStream.Current; byte[] bin = reply.Binary.ToByteArray(); fs.Write(bin, offset, (int)reply.FileSize); } } this.xDownloadMessage.Text = ""; } catch (RpcException rpcEx) when(rpcEx.StatusCode == StatusCode.Cancelled) { this.xDownloadMessage.Text = "ダウンロードをキャンセルしました。"; } this.FileDownloadButton.IsEnabled = true; this.CancelButton.IsEnabled = false; }
public void TestServerStreamingWithException() { GoogleAdsConfig config = new GoogleAdsConfig(); LoggingHandler handler = new LoggingHandler(config); handler.WriteSummaryLogs = delegate(LogEntry logEntry) { Assert.AreEqual(config.ServerUrl, logEntry.Host); Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method); CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders); Assert.True(logEntry.IsFailure); HelloException helloException = logEntry.Exception as HelloException; Assert.NotNull(helloException); Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId); Assert.NotNull(helloException.Failure); Assert.AreEqual(1, helloException.Failure.Errors.Count); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError); }; handler.WriteDetailedLogs = delegate(LogEntry logEntry) { Assert.AreEqual(config.ServerUrl, logEntry.Host); Assert.AreEqual(TEST_METHOD_IN_LOGS, logEntry.Method); CompareMetadata(TEST_REQUEST_METADATA, logEntry.RequestHeaders); CompareMetadata(TEST_RESPONSE_METADATA, logEntry.ResponseHeaders); Assert.AreSame(TEST_REQUEST, logEntry.Request); // Response is null if there's an exception. Assert.IsNull(logEntry.Response); Assert.AreEqual(TEST_CUSTOMER_ID, logEntry.CustomerId); Assert.True(logEntry.IsFailure); HelloException helloException = logEntry.Exception as HelloException; Assert.NotNull(helloException); Assert.AreEqual(TEST_REQUEST_ID, helloException.RequestId); Assert.NotNull(helloException.Failure); Assert.AreEqual(1, helloException.Failure.Errors.Count); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode); Assert.NotNull(helloException.Failure.Errors[0].ErrorCode.RequestError); }; ClientInterceptorContext <HelloRequest, HelloResponse> context = GetClientInterceptorContext(); AsyncServerStreamingCall <HelloResponse> call = StreamingContinuationWithException <HelloResponse>(); handler.HandleAsyncServerStreamingLogging(TEST_REQUEST, null, context, new AggregateException(TEST_EXCEPTION), call); }
private Task <Metadata> ConnectAsync() { Logger.LogPerformanceCounterFn("StreamReader.ConnectCount", x => x + 1); if (_resumeToken != null) { Logger.Debug(() => $"Resuming at location:{_resumeToken}"); _request.ResumeToken = _resumeToken; } _currentCall = _spannerClient.ExecuteSqlStream(_request); return(_currentCall.ResponseHeadersAsync.WithSessionChecking(() => _session)); }
public AnalogyMessageConsumer(string address) { channel = new Channel(address, ChannelCredentials.Insecure); client = new Analogy.AnalogyClient(channel); AnalogyConsumerMessage m = new AnalogyConsumerMessage { Message = "client" }; _stream = client.SubscribeForConsumingMessages(m); consumer = Task.Factory.StartNew(GetMessages); }
public AnalogyMessageConsumer(string address) { //using var channel = GrpcChannel.ForAddress("http://localhost:6000"); channel = GrpcChannel.ForAddress(address); client = new Analogy.AnalogyClient(channel); AnalogyConsumerMessage m = new AnalogyConsumerMessage { Message = "client" }; _stream = client.SubscribeForConsumingMessages(m); }
public LoginServerClientLL( Channel channel, LoginPrivateService.LoginPrivateServiceClient client, AsyncServerStreamingCall <PrivateEvent> stream, string token) { this.channel = channel; this.client = client; call_metadata = new Metadata(); call_metadata.Add(HeaderConstants.PrivateServiceTokenHeader, token); Task.Run(() => handle_stream(stream)); }
public async Task ConnectAsync() { _channel = await _channelFactory.CreateAsync(_connectionId); _client = new BenchmarkService.BenchmarkServiceClient(_channel); var options = new CallOptions(deadline: _deadline, cancellationToken: _cts.Token); _call = _client.StreamingFromServer(new SimpleRequest { ResponseSize = 10 }, options); }
public static async Task SelectAsync <T>(this AsyncServerStreamingCall <T> streamingCall, Action <T> callback, CancellationToken token) { using (IAsyncStreamReader <T> responseStream = streamingCall.ResponseStream) { while (await responseStream .MoveNext(token) .ConfigureAwait(false)) { callback(responseStream.Current); } } }
private async System.Threading.Tasks.Task ProcessIssues(AsyncServerStreamingCall <Issue> call, string path, IIssueConsumer consumer) { var issues = new List <Issue>(); while (await call.ResponseStream.MoveNext()) { var issue = call.ResponseStream.Current; issues.Add(issue); } consumer.Accept(path, issues); }
/// <summary> /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="method"></param> /// <param name="cancellationToken"></param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> public async Task Snapshot(SnapshotRequest request, Action <SnapshotResponse> method, CancellationToken cancellationToken, Grpc.Core.Metadata headers = null, DateTime?deadline = null) => await CallEtcdAsync(async (connection) => { using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = connection ._maintenanceClient.Snapshot(request, headers, deadline, cancellationToken)) { while (await snapshotter.ResponseStream.MoveNext(cancellationToken).ConfigureAwait(false)) { SnapshotResponse update = snapshotter.ResponseStream.Current; method(update); } } }).ConfigureAwait(false);
/// <summary> /// 指定された例外を処理し、実行結果を返します。 /// </summary> /// <typeparam name="TResponse">レスポンスの型</typeparam> /// <param name="call">呼び出しオブジェクト</param> /// <param name="ex">例外</param> /// <returns>実行結果</returns> private static GrpcResult <TResponse> HandleResponseException <TResponse>(AsyncServerStreamingCall <TResponse> call, Exception ex) { Exception actual = GrpcExceptionUtility.GetActualException(ex); GrpcCallState state; if (GrpcCallInvokerContext.TryGetState(call, out state)) { GrpcExceptionListener.NotifyCatchClientException(state.Method, state.Host, state.Options, actual); } return(GrpcResult.Create <TResponse>(actual)); }
private Task <Metadata> ConnectAsync() { Logger.LogPerformanceCounterFn("StreamReader.ConnectCount", x => x + 1); if (_resumeToken != null) { Logger.Debug(() => $"Resuming at location:{_resumeToken}"); _request.ResumeToken = _resumeToken; } _currentCall = _spannerClient.ExecuteSqlStream(_request, _spannerClient.Settings.ExecuteSqlStreamSettings.WithExpiration( _spannerClient.Settings.ConvertTimeoutToExpiration(_timeoutSeconds))); return(WithTiming(_currentCall.ResponseHeadersAsync.WithSessionChecking(() => _session), "ResponseHeaders")); }
private async Task TryRecoverOnFailureAsync(CancellationToken cancellationToken, Exception exception) { _currentCall?.Dispose(); _currentCall = null; //reconnect on failure which will call reliableconnect and respect resumetoken and resumeskip cancellationToken.ThrowIfCancellationRequested(); Logger.Warn("An error occurred attemping to iterate through the sql query. Attempting to recover.", exception); // Reconnect, which will automatically skip as far as we need to using the resume token. // We don't need to call MoveNext again; we'll already be resuming *after* the result set that provided the resume token. _isReading = await ReliableConnectAsync(cancellationToken).ConfigureAwait(false); }
/// <summary> /// /// </summary> /// <typeparam name="TRequest"></typeparam> /// <typeparam name="TResponse"></typeparam> /// <param name="invoker"></param> /// <param name="method"></param> /// <param name="option"></param> /// <param name="request"></param> /// <returns></returns> private async Task <IList <TResponse> > AsyncServerStreamingCall <TRequest, TResponse>(CallInvoker invoker, Method <TRequest, TResponse> method, CallOptions option, TRequest request) where TRequest : class where TResponse : class { using (AsyncServerStreamingCall <TResponse> call = invoker.AsyncServerStreamingCall(method, null, option, request)) { List <TResponse> responses = new List <TResponse>(); while (await call.ResponseStream.MoveNext().ConfigureAwait(false)) { responses.Add(call.ResponseStream.Current); } return(responses); } }
public void RunIndefinitely() { var filter = new TransactionFilter(); filter.FiltersByParty.Add(_party, new Filters()); // we use the default filter since we don't want to filter out any contracts // assemble the request for the transaction stream GetTransactionsRequest transactionsRequest = new GetTransactionsRequest { LedgerId = _ledgerId, Begin = new LedgerOffset { Boundary = LedgerOffset.Types.LedgerBoundary.LedgerBegin }, Filter = filter, Verbose = true }; // this StreamObserver reacts to transactions and prints a message if an error occurs or the stream gets closed Console.WriteLine($"{_party} starts reading transactions."); AsyncServerStreamingCall <GetTransactionsResponse> transactionObserver = _transactionService.GetTransactions(transactionsRequest, null, null, _cancellationTokenSource.Token); Task.Run(async() => { try { while (await transactionObserver.ResponseStream.MoveNext(CancellationToken.None)) { foreach (var transaction in transactionObserver.ResponseStream.Current.Transactions) { ProcessTransaction(transaction); } } Console.WriteLine($"{_party}'s transactions stream completed."); } catch (RpcException ex) { if (ex.StatusCode != StatusCode.Cancelled) { Console.Error.WriteLine($"{_party} encountered an RpcException while processing transactions! {ex.Message}"); } } catch (Exception ex) { Console.Error.WriteLine($"{_party} encountered an error while processing transactions! {ex.Message}"); } }); }
private async void RecvMessage(AsyncServerStreamingCall <Message> ssc) { try { await foreach (var msg in ssc.ResponseStream.ReadAllAsync(cts.Token)) { ChatTB.AppendText(msg.M); } } catch (RpcException ex) when(ex.Status.StatusCode == StatusCode.Cancelled) { // Stream Cancelled! } catch (Exception ex) { LeaveChat(); MessageBox.Show(ex.Message); } }
/// <summary> /// Creates a server streaming call continuation with test results. /// </summary> /// <typeparam name="TResponse">The type of the response.</typeparam> /// <returns>The streaming continuation.</returns> private AsyncServerStreamingCall <HelloResponse> StreamingContinuationWithResult <TResponse>() where TResponse : class { Task <HelloResponse> responseTask = Task.FromResult(TEST_RESPONSE); Task <Metadata> responseHeadersTask = Task.FromResult(TEST_RESPONSE_METADATA); Func <Metadata> trailersTask = () => TEST_TRAILERS_METADATA; TestStreamReader <HelloResponse> responseStream = new TestStreamReader <HelloResponse>(new[] { TEST_RESPONSE }, null); AsyncServerStreamingCall <HelloResponse> call = new AsyncServerStreamingCall <HelloResponse>(responseStream, responseHeadersTask, null, trailersTask, null); return(call); }
private async System.Threading.Tasks.Task ProcessIssues(AsyncServerStreamingCall <Issue> call, string path, IIssueConsumer consumer) { var issues = new List <IAnalysisIssue>(); int issueCount = 0; while (await call.ResponseStream.MoveNext()) { var issue = call.ResponseStream.Current; issues.Add(ToAnalysisIssue(issue)); issueCount++; } WritelnToPane($"Found {issueCount} issue(s)"); consumer.Accept(path, issues); }
private static async Task GrpcMessageResponseStream() { GrpcChannel grpcChannel = GrpcChannel.ForAddress("https://localhost:5001"); Greeter.GreeterClient greeterClient = new Greeter.GreeterClient(grpcChannel); AsyncServerStreamingCall <HelloReply> helloReply = greeterClient.SayHelloStream(new HelloRequest { Name = "gRPC Streaming Demonstration!" }); await foreach (HelloReply item in helloReply.ResponseStream.ReadAllAsync()) { Console.WriteLine(item.Message); } }
public void StartListener() { _listenCancel = new CancellationTokenSource(); _listenTask = Task.Run(async() => { AsyncServerStreamingCall <NotificationMessage> notificationStream = Listen(new Empty(), cancellationToken: _listenCancel.Token); while (!_listenCancel.Token.IsCancellationRequested) { bool hasNotification = await notificationStream.ResponseStream.MoveNext(_listenCancel.Token); if (hasNotification) { OnNotificationReceived(notificationStream.ResponseStream.Current.Message); } } }, _listenCancel.Token); }
public async IAsyncEnumerable <int> GenerateNumbers(int count) { GenerateController.GenerateControllerClient client = _factory.CreateClient <GenerateController.GenerateControllerClient>(); GenerateNumbersRequest request = new GenerateNumbersRequest { Count = count }; using (AsyncServerStreamingCall <GetNumbersResponse> streamingCall = client.GenerateNumber(request)) { await foreach (GetNumbersResponse response in streamingCall.ResponseStream.ReadAllAsync()) { yield return(response.Number); } } }
/// <summary> /// Snapshot sends a snapshot of the entire backend from a member over a stream to a client. /// </summary> /// <param name="request"></param> /// <param name="method"></param> /// <param name="token"></param> public async void Snapshot(SnapshotRequest request, Action <SnapshotResponse> method, CancellationToken token, Metadata headers = null) { using (AsyncServerStreamingCall <SnapshotResponse> snapshotter = _balancer.GetConnection().maintenanceClient.Snapshot(request, headers)) { Task snapshotTask = Task.Run(async() => { while (await snapshotter.ResponseStream.MoveNext(token)) { SnapshotResponse update = snapshotter.ResponseStream.Current; method(update); } }); await snapshotTask; } }
/// <summary> /// Connects or reconnects to Spanner, fast forwarding to where we left off based on /// our _resumeToken and _resumeSkipCount. /// </summary> private async Task <bool> ReliableConnectAsync(CancellationToken cancellationToken) { if (_currentCall == null) { await WithTiming(ConnectAsync(), "ConnectAsync").ConfigureAwait(false); GaxPreconditions.CheckState(_currentCall != null, "Failed to connect"); bool success = false; try { for (int i = 0; i <= _resumeSkipCount; i++) { ThrowIfCancellationRequested(cancellationToken); _isReading = await WithTiming( _currentCall.ResponseStream.MoveNext(cancellationToken) .WithSessionExpiryChecking(_session), "ResponseStream.MoveNext") .ConfigureAwait(false); if (!_isReading || _currentCall.ResponseStream.Current == null) { return(false); } if (_metadata == null) { _metadata = _currentCall.ResponseStream.Current.Metadata; } } RecordResumeToken(); RecordStatistics(); success = true; } finally { // If we failed at any point, dispose the call and forget it. if (!success) { _currentCall?.Dispose(); _currentCall = null; } } } return(_isReading); }
// Use this for initialization void Start() { var client = new Example.Client("127.0.0.1", 9991); Debug.Log("Stating calling gRPC service to greet me 10 times"); // You can setup some timeout here... var ctx = new GrpcCancellationTokenSource(); AsyncServerStreamingCall <Example.HelloReply> call = client.SayHello(ctx, new Example.HelloRequest { Name = "CuriousUser!11one!one", NumGreetings = 10 }); // Schedule response parsing in async. call.ResponseStream.MoveNext().StartAsCoroutine <bool>(this.onNextFn(call)); }
private Task <Metadata> ConnectAsync() { Logger.LogPerformanceCounter("StreamReader.ConnectCount", x => x + 1); if (_resumeToken != null) { Logger.Debug($"Resuming read using a resume token"); _request.ResumeToken = _resumeToken; } // TODO: Clear the resume token in the request if we don't have one? var sqlStream = _spannerClient.ExecuteStreamingSql(_request, _spannerClient.Settings.ExecuteStreamingSqlSettings.WithExpiration( _spannerClient.Settings.ConvertTimeoutToExpiration(_timeoutSeconds))); _currentCall = sqlStream.GrpcCall; return(WithTiming(_currentCall.ResponseHeadersAsync.WithSessionExpiryChecking(_session), "ResponseHeaders")); }
public async Task ConnectAsync() { var credentials = _useClientCertificate ? GetCertificateCredentials() : ChannelCredentials.Insecure; _channel = new Channel(Target, credentials); _client = new GreetService.GreetServiceClient(_channel); await _channel.ConnectAsync(); var options = new CallOptions(deadline: _deadline, cancellationToken: _cts.Token); _call = _client.SayHellos(new HelloRequest { Name = "World" }, options); }