public override async Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context) { await EnsureEchoMetadataAsync(context); EnsureEchoStatus(request.ResponseStatus, context); var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) }; return response; }
public static void RunClientCompressedUnary(TestService.TestServiceClient client) { Console.WriteLine("running client_compressed_unary"); var probeRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true // lie about compression }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var e = Assert.Throws <RpcException>(() => client.UnaryCall(probeRequest, CreateClientCompressionMetadata(false))); Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); var compressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response1 = client.UnaryCall(compressedRequest, CreateClientCompressionMetadata(true)); Assert.AreEqual(314159, response1.Payload.Body.Length); var uncompressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = false }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response2 = client.UnaryCall(uncompressedRequest, CreateClientCompressionMetadata(false)); Assert.AreEqual(314159, response2.Payload.Body.Length); Console.WriteLine("Passed!"); }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); client.HeaderInterceptor = OAuth2Interceptors.FromAccessToken(oauth2Token); var request = SimpleRequest.CreateBuilder() .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var response = client.UnaryCall(request); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public static async Task RunClientCompressedUnary(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var probeRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true // lie about compression }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var e = await ExceptionAssert.ThrowsAsync <RpcException>(async() => await client.UnaryCallAsync(probeRequest, CreateClientCompressionMetadata(false))); Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); var compressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response1 = await client.UnaryCallAsync(compressedRequest, CreateClientCompressionMetadata(true)); Assert.AreEqual(314159, response1.Payload.Body.Length); var uncompressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = false }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response2 = await client.UnaryCallAsync(uncompressedRequest, CreateClientCompressionMetadata(false)); Assert.AreEqual(314159, response2.Payload.Body.Length); }
public static void RunComputeEngineCreds(TestService.ITestServiceClient client) { Console.WriteLine("running compute_engine_creds"); var request = SimpleRequest.CreateBuilder() .SetResponseType(PayloadType.COMPRESSABLE) .SetResponseSize(314159) .SetPayload(CreateZerosPayload(271828)) .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ComputeEngineUser, response.Username); Console.WriteLine("Passed!"); }
public static void RunJwtTokenCreds(TestService.TestServiceClient client) { Console.WriteLine("running jwt_token_creds"); var request = new SimpleRequest { ResponseType = PayloadType.Compressable, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.Compressable, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
public static async Task RunOAuth2AuthTokenAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var oauthScope = options.OAuthScope !; ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); var oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = await client.UnaryCallAsync(request, new CallOptions(credentials : credentials)); Assert.IsFalse(string.IsNullOrEmpty(response.OauthScope)); Assert.IsTrue(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); }
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope) { #if !NETCOREAPP1_0 Console.WriteLine("running per_rpc_creds"); ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var credentials = googleCredential.ToCallCredentials(); var request = new SimpleRequest { FillUsername = true, }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); #else // TODO(jtattermusch): implement this throw new NotImplementedException("Not supported on CoreCLR yet"); #endif }
public static void RunComputeEngineCreds(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running compute_engine_creds"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); }
public async Task CallSettingsDeadlineIsObserved(bool async) { var callDuration = TimeSpan.FromTicks(300); var failures = 4; // Fifth call would succeed, but we won't get that far. var scheduler = new FakeScheduler(); var time0 = scheduler.Clock.GetCurrentDateTimeUtc(); var server = new Server(failures, callDuration, scheduler); var callable = server.Callable; var timeout = TimeSpan.FromTicks(2500); var retrySettings = new RetrySettings( maxAttempts: 5, initialBackoff: TimeSpan.FromTicks(1000), maxBackoff: TimeSpan.FromTicks(5000), backoffMultiplier: 2.0, retryFilter: NotFoundFilter, backoffJitter: RetrySettings.NoJitter); var task = scheduler.RunAsync(async() => { // Expiration makes it fail while waiting to make third call var callSettings = CallSettings.FromRetry(retrySettings).WithTimeout(timeout); var request = new SimpleRequest { Name = "irrelevant" }; await Call(async, scheduler, server, request, callSettings); }); await Assert.ThrowsAsync <RpcException>(() => task); var firstCall = time0; var secondCall = firstCall + callDuration + TimeSpan.FromTicks(1000); server.AssertCallTimes(firstCall, secondCall); // We use the same deadline for all calls. server.AssertDeadlines(time0 + timeout, time0 + timeout); // We fail immediately when we work out that we would time out before we make the third // call - so this is before the actual total timeout. Assert.Equal((secondCall + callDuration).Ticks, scheduler.Clock.GetCurrentDateTimeUtc().Ticks); }
public static async Task RunComputeEngineCreds(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var defaultServiceAccount = options.DefaultServiceAccount !; var oauthScope = options.OAuthScope !; var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; // not setting credentials here because they were set on channel already var response = await client.UnaryCallAsync(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.IsFalse(string.IsNullOrEmpty(response.OauthScope)); Assert.IsTrue(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); }
public async void SendMessageToDiscordChannel(string message, ulong channelId) { message = message.Replace("\\", "\\\\"); message = message.Replace("\"", "\\\""); message = message.Replace("\n", "\\n"); string json = DiscordMessageFactory.CreateTextMessage(message); string response = null; try { response = await SimpleRequest.SendJsonDataAsync($"{API_URL}/channels/{channelId}/messages", new WebHeaderCollection() { { "Authorization", $"Bot {BOT_TOKEN}" } }, json); } catch (Exception e) { if (e.Message.Contains("(401) Unauthorized")) { PrettyPrint.Log("Discord", "Unauthorized access to Discord server. Is your BOT_TOKEN correct?", ConsoleColor.Red); } else if (e.Message.Contains("(403) Forbidden")) { PrettyPrint.Log("Discord", "Forbidden access to Discord channel. Are your Channel IDs & BOT permissions correct?", ConsoleColor.Red); } else { PrettyPrint.Log("Discord", e.Message, ConsoleColor.Red); } } if (debug) { Console.WriteLine(response); } }
public static async Task RunStatusCodeAndMessageAsync(TestService.TestServiceClient client) { Console.WriteLine("running status_code_and_message"); var echoStatus = new EchoStatus { Code = 2, Message = "test status message" }; { // step 1: test unary call var request = new SimpleRequest { ResponseStatus = echoStatus }; var e = Assert.Throws <RpcException>(() => client.UnaryCall(request)); Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseStatus = echoStatus }; var call = client.FullDuplexCall(); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); var e = Assert.ThrowsAsync <RpcException>(async() => await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } Console.WriteLine("Passed!"); }
/// <summary> /// See interface docs. /// </summary> /// <param name="pathAndFile"></param> /// <returns></returns> public SimpleContent RequestSimpleContent(string pathAndFile) { if (pathAndFile == null) { throw new ArgumentNullException("pathAndFile"); } var result = new SimpleContent(); const string root = "/Root"; using (var simpleRequest = new SimpleRequest(root, pathAndFile)) { using (var memoryStream = new MemoryStream()) { var simpleResponse = new SimpleResponse(memoryStream); var args = new RequestReceivedEventArgs(simpleRequest, simpleResponse, root); RequestContent(args); result.HttpStatusCode = simpleResponse.StatusCode; result.Content = memoryStream.ToArray(); } } return(result); }
public IHttpActionResult GetItemSlsProdLines(SimpleRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } DynamicParameters parameters = new DynamicParameters(); parameters.Add("@CompID", request.CompID); var response = new List <GetItemSlsProdLineResponse>(); try { response = sqlHandler.SQLWithRetrieveList <GetItemSlsProdLineResponse>("spimGetItemSalesProdLines_RKL", System.Data.CommandType.StoredProcedure, parameters); } catch (Exception exception) { Common.LogError(request.LoginName, exception.Message, exception.StackTrace, "IMController.GetItemSlsProdLines", "E"); return(BadRequest(exception.Message)); } return(Ok(response)); }
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running per_rpc_creds"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var headerInterceptor = AuthInterceptors.FromAccessToken(oauth2Token); var request = SimpleRequest.CreateBuilder() .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var headers = new Metadata(); headerInterceptor(null, "", headers); var response = client.UnaryCall(request, headers: headers); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public async Task RetryFilter_EventualSuccess(bool async) { StatusCode failureCode = StatusCode.NotFound; StatusCode[] filterCodes = new[] { StatusCode.NotFound, StatusCode.DeadlineExceeded }; var callDuration = TimeSpan.FromTicks(100); var failures = 1; var scheduler = new FakeScheduler(); var server = new Server(failures, callDuration, scheduler, failureCode); // We're not really interested in the timing in this test. var retrySettings = ConstantBackoff(5, TimeSpan.Zero, RetrySettings.FilterForStatusCodes(filterCodes)); await scheduler.RunAsync(async() => { var callSettings = CallSettings.FromRetry(retrySettings); var request = new SimpleRequest { Name = "irrelevant" }; await Call(async, scheduler, server, request, callSettings); }); Assert.True(server.CallTimes.Count() > 1); }
public async Task MaxAttemptsObserved(bool async) { var callDuration = TimeSpan.FromTicks(300); var failures = 4; // Fifth call would succeed, but we won't get that far. var scheduler = new FakeScheduler(); var time0 = scheduler.Clock.GetCurrentDateTimeUtc(); var server = new Server(failures, callDuration, scheduler); var callable = server.Callable; var retrySettings = ConstantBackoff(failures, TimeSpan.Zero, NotFoundFilter); var task = scheduler.RunAsync(async() => { // MaxAttempts makes the overall operation fail on the 4th RPC. var callSettings = CallSettings.FromRetry(retrySettings); var request = new SimpleRequest { Name = "irrelevant" }; await Call(async, scheduler, server, request, callSettings); }); await Assert.ThrowsAsync <RpcException>(() => task); Assert.Equal(4, server.CallTimes.Count); }
public static async Task Main(string[] args) { // For local measurements, use a stopwatch and make a // request from the app itself to get an approximate // measurement. if (args.Contains("--time")) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); using (var host = CreateHostBuilder(args).Start()) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var channel = GrpcChannel.ForAddress("http://localhost:5000"); var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = new SimpleRequest { Payload = new Payload { Body = ByteString.CopyFrom(new byte[0]) }, ResponseSize = 0 }; _ = await client.UnaryCallAsync(request); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Console.WriteLine("Stopwatch startup measurement: " + ts.Milliseconds); } return; } else { var host = CreateHostBuilder(args).Build(); host.Run(); } }
public SimpleResponse POST([FromBody] SimpleRequest data) { String DynamicFileName = ""; HttpResponseMessage response = new HttpResponseMessage(); using (HostingEnvironment.Impersonate()) { try { client.Headers.Add("X-Current-User", base.User.GetUsername(true).ToString()); client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UseDefaultCredentials = true; DynamicFileName = client.UploadString(theURI, data); response.data = DynamicFileName; } catch (Exception ex) { response.ReasonPhrase = ex.InnerException.ToString(); return response } return(response); } }
public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running jwt_token_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); // check this a credential with scope support, but don't add the scope. Assert.IsTrue(credential.IsCreateScopedRequired); client.HeaderInterceptor = OAuth2Interceptors.FromCredential(credential); var request = SimpleRequest.CreateBuilder() .SetResponseType(PayloadType.COMPRESSABLE) .SetResponseSize(314159) .SetPayload(CreateZerosPayload(271828)) .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public async Task MultipleCallsEventualSuccess(bool async) { var callDuration = TimeSpan.FromTicks(300); var failures = 4; // Fifth call will succeed var name = "name"; // Copied from request to response var scheduler = new FakeScheduler(); var time0 = scheduler.Clock.GetCurrentDateTimeUtc(); var server = new Server(failures, callDuration, scheduler); var retrySettings = new RetrySettings( maxAttempts: 5, initialBackoff: TimeSpan.FromTicks(1000), maxBackoff: TimeSpan.FromTicks(5000), backoffMultiplier: 2.0, retryFilter: NotFoundFilter, backoffJitter: RetrySettings.NoJitter); await scheduler.RunAsync(async() => { var callSettings = CallSettings.FromRetry(retrySettings); var request = new SimpleRequest { Name = name }; var result = await Call(async, scheduler, server, request, callSettings); Assert.Equal(name, result.Name); }); var firstCall = time0; var secondCall = firstCall + callDuration + TimeSpan.FromTicks(1000); // Delay for 1000 ticks var thirdCall = secondCall + callDuration + TimeSpan.FromTicks(2000); // Delay for 2000 ticks var fourthCall = thirdCall + callDuration + TimeSpan.FromTicks(4000); // Delay for 4000 ticks var fifthCall = fourthCall + callDuration + TimeSpan.FromTicks(5000); // Delay for 5000 ticks, as that's the max server.AssertCallTimes(firstCall, secondCall, thirdCall, fourthCall, fifthCall); // Time of last action was when the call returned Assert.Equal(fifthCall + callDuration, scheduler.Clock.GetCurrentDateTimeUtc()); }
public static async Task RunComputeEngineCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running compute_engine_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsFalse(credential.IsCreateScopedRequired); client.HeaderInterceptor = OAuth2Interceptors.FromCredential(credential); var request = SimpleRequest.CreateBuilder() .SetResponseType(PayloadType.COMPRESSABLE) .SetResponseSize(314159) .SetPayload(CreateZerosPayload(271828)) .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ComputeEngineUser, response.Username); Console.WriteLine("Passed!"); }
public IActionResult Post([FromBody] SimpleRequest simpleRequest) { // Perform some simple input validations if (simpleRequest is null) { throw new ArgumentNullException(nameof(simpleRequest)); } if (string.IsNullOrEmpty(simpleRequest.Message)) { return(BadRequest($"The request message should not be null (Error created at: {DateTime.Now.ToString("s")})")); } // ...Let's assume that we have created an entity in a persistanct storage (e.g. in our database). var rng = new Random(); SimpleResponse simpleResponse = new SimpleResponse() { Id = rng.Next(1000, 5000), CreatedOn = DateTime.Now, Message = $"A Simple string message (as created)!" }; return(CreatedAtRoute("GetById", new { Id = simpleResponse.Id }, simpleResponse)); }
private Task <SimpleResponse> Call( bool async, bool serverStreaming, FakeScheduler scheduler, Server server, SimpleRequest request, CallSettings callSettings) { if (serverStreaming) { var retryingCallable = server.ServerStreamingCallable.WithRetry(scheduler.Clock, scheduler); return(Call(async, retryingCallable, request, callSettings)); } else { var retryingCallable = server.Callable.WithRetry(scheduler.Clock, scheduler); return(Call(async, retryingCallable, request, callSettings)); } }
public AsyncServerStreamingCall <SimpleResponse> ServerStreamingMethodSync(SimpleRequest request, CallSettings callSettings) { CallTimes.Add(_scheduler.Clock.GetCurrentDateTimeUtc()); CallSettingsReceived.Add(callSettings); var responseStream = new AsyncStreamReader <SimpleResponse>(new SimpleResponse { Name = request.Name }); var responseHeaders = Task.Run(async() => { await _scheduler.Delay(_callDuration, callSettings.CancellationToken.GetValueOrDefault()); if (_failuresToReturn > 0) { _failuresToReturn--; throw new RpcException(new Status(_failureCode, "Bang")); } return(Metadata.Empty); }); var response = new AsyncServerStreamingCall <SimpleResponse>(responseStream, responseHeaders, null, null, null); return(response); }
public static async Task RunCustomMetadataAsync(TestService.TestServiceClient client) { Console.WriteLine("running custom_metadata"); { // step 1: test unary call var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var call = client.UnaryCallAsync(request, headers: CreateTestMetadata()); await call.ResponseAsync; var responseHeaders = await call.ResponseHeadersAsync; var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseParameters = { new ResponseParameters { Size = 31415 } }, Payload = CreateZerosPayload(27182) }; var call = client.FullDuplexCall(headers: CreateTestMetadata()); var responseHeaders = await call.ResponseHeadersAsync; await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); await call.ResponseStream.ToListAsync(); var responseTrailers = call.GetTrailers(); Assert.AreEqual("test_initial_metadata_value", responseHeaders.First((entry) => entry.Key == "x-grpc-test-echo-initial").Value); CollectionAssert.AreEqual(new byte[] { 0xab, 0xab, 0xab }, responseTrailers.First((entry) => entry.Key == "x-grpc-test-echo-trailing-bin").ValueBytes); } Console.WriteLine("Passed!"); }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
public static void RunComputeEngineCreds(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running compute_engine_creds"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); }
private Task<SimpleResponse> UnaryCallHandler(SimpleRequest request, ServerCallContext context) { var authToken = context.RequestHeaders.First((entry) => entry.Key == "authorization").Value; Assert.AreEqual("SECRET_TOKEN", authToken); return Task.FromResult(new SimpleResponse()); }
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope) { #if !NETCOREAPP1_0 Console.WriteLine("running per_rpc_creds"); ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var credentials = googleCredential.ToCallCredentials(); var request = new SimpleRequest { FillUsername = true, }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); #else // TODO(jtattermusch): implement this throw new NotImplementedException("Not supported on CoreCLR yet"); #endif }
public object Get(SimpleRequest request) { return 12345; }
public override Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context) { var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) }; return Task.FromResult(response); }
internal AsyncUnaryCall<SimpleResponse> MethodAsync(SimpleRequest request, CallOptions callOptions) { throw new NotImplementedException(); }
public static async Task RunJwtTokenCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount) { Console.WriteLine("running jwt_token_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); Assert.IsTrue(credential.IsCreateScopedRequired); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); }
private void Run() { var request = new SimpleRequest { Payload = CreateZerosPayload(payloadSize) }; var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); client.UnaryCall(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); } }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { AuthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); client.HeaderInterceptor = AuthInterceptors.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public static void RunClientCompressedUnary(TestService.TestServiceClient client) { Console.WriteLine("running client_compressed_unary"); var probeRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true // lie about compression }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var e = Assert.Throws<RpcException>(() => client.UnaryCall(probeRequest, CreateClientCompressionMetadata(false))); Assert.AreEqual(StatusCode.InvalidArgument, e.Status.StatusCode); var compressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = true }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response1 = client.UnaryCall(compressedRequest, CreateClientCompressionMetadata(true)); Assert.AreEqual(314159, response1.Payload.Body.Length); var uncompressedRequest = new SimpleRequest { ExpectCompressed = new BoolValue { Value = false }, ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response2 = client.UnaryCall(uncompressedRequest, CreateClientCompressionMetadata(false)); Assert.AreEqual(314159, response2.Payload.Body.Length); Console.WriteLine("Passed!"); }
public Task <JobSummaryCollection> GetJobs() { return(_client.Execute(SimpleRequest <JobSummaryCollection> .Get($"{BASE_PATH}/jobs"))); }
public static async Task RunServiceAccountCredsAsync(TestService.TestServiceClient client) { Console.WriteLine("running service_account_creds"); var credential = await GoogleCredential.GetApplicationDefaultAsync(); credential = credential.CreateScoped(new[] { AuthScope }); client.HeaderInterceptor = AuthInterceptors.FromCredential(credential); var request = new SimpleRequest { ResponseType = PayloadType.COMPRESSABLE, ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request); Assert.AreEqual(PayloadType.COMPRESSABLE, response.Payload.Type); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public static void RunLargeUnary(TestService.TestServiceClient client) { Console.WriteLine("running large_unary"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828) }; var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Console.WriteLine("Passed!"); }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { #if !NETCOREAPP1_0 Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); #else // TODO(jtattermusch): implement this throw new NotImplementedException("Not supported on CoreCLR yet"); #endif }
public static void RunJwtTokenCreds(TestService.TestServiceClient client) { Console.WriteLine("running jwt_token_creds"); var request = new SimpleRequest { ResponseSize = 314159, Payload = CreateZerosPayload(271828), FillUsername = true, }; // not setting credentials here because they were set on channel already var response = client.UnaryCall(request); Assert.AreEqual(314159, response.Payload.Body.Length); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
public override Task <SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context) { return(Task.FromResult(CreateResponse(request))); }
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running per_rpc_creds"); ITokenAccess googleCredential = await GoogleCredential.GetApplicationDefaultAsync(); var credentials = googleCredential.ToCallCredentials(); var request = new SimpleRequest { FillUsername = true, }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
public Task <AsyncServerStreamingCall <SimpleResponse> > ServerStreamingMethodAsync(SimpleRequest request, CallSettings callSettings) => Task.FromResult(ServerStreamingMethodSync(request, callSettings));
public static async Task RunStatusCodeAndMessageAsync(TestService.TestServiceClient client) { Console.WriteLine("running status_code_and_message"); var echoStatus = new EchoStatus { Code = 2, Message = "test status message" }; { // step 1: test unary call var request = new SimpleRequest { ResponseStatus = echoStatus }; var e = Assert.Throws<RpcException>(() => client.UnaryCall(request)); Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } { // step 2: test full duplex call var request = new StreamingOutputCallRequest { ResponseStatus = echoStatus }; var call = client.FullDuplexCall(); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseStream.ToListAsync(); Assert.Fail(); } catch (RpcException e) { Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode); Assert.AreEqual(echoStatus.Message, e.Status.Detail); } } Console.WriteLine("Passed!"); }
public Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context) { var response = SimpleResponse.CreateBuilder() .SetPayload(CreateZerosPayload(request.ResponseSize)).Build(); return Task.FromResult(response); }
void Handle(IConsumeContext<SimpleRequest> context, SimpleRequest message) { context.Respond(new SimpleResponse(message.Headers)); }
internal SimpleResponse MethodSync(SimpleRequest request, CallOptions callOptions) { CallOptions = callOptions; return null; }
public Task<SimpleResponse> UnaryCallAsync(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.AsyncUnaryCall(call, request, token); }
public static async Task RunPerRpcCredsAsync(TestService.TestServiceClient client, string defaultServiceAccount, string oauthScope) { Console.WriteLine("running per_rpc_creds"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string accessToken = await credential.GetAccessTokenForRequestAsync(); var headerInterceptor = AuthInterceptors.FromAccessToken(accessToken); var request = new SimpleRequest { FillUsername = true, }; var headers = new Metadata(); headerInterceptor(null, "", headers); var response = client.UnaryCall(request, headers: headers); Assert.AreEqual(defaultServiceAccount, response.Username); Console.WriteLine("Passed!"); }
public string Any(SimpleRequest request) { return("Ok"); }
public SimpleResponse UnaryCall(SimpleRequest request, CancellationToken token = default(CancellationToken)) { var call = new Grpc.Core.Call<SimpleRequest, SimpleResponse>(unaryCallMethod, channel); return Calls.BlockingUnaryCall(call, request, token); }