/// <summary> /// LockAsync acquires a distributed shared lock on a given named lock. /// On success, it will return a unique key that exists so long as the /// lock is held by the caller. This key can be used in conjunction with /// transactions to safely ensure updates to etcd only occur while holding /// lock ownership. The lock is held until Unlock is called on the key or the /// lease associate with the owner expires. /// </summary> /// <param name="name">is the identifier for the distributed shared lock to be acquired.</param> /// <returns></returns> public async Task <LockResponse> LockAsync(string name, Grpc.Core.Metadata headers = null) { return(await LockAsync(new LockRequest() { Name = ByteString.CopyFromUtf8(name), }, headers)); }
/// <summary> /// Lock acquires a distributed shared lock on a given named lock. /// On success, it will return a unique key that exists so long as the /// lock is held by the caller. This key can be used in conjunction with /// transactions to safely ensure updates to etcd only occur while holding /// lock ownership. The lock is held until Unlock is called on the key or the /// lease associate with the owner expires. /// </summary> /// <param name="name">is the identifier for the distributed shared lock to be acquired.</param> /// <returns></returns> public LockResponse Lock(string name, Grpc.Core.Metadata headers = null) { return(Lock(new LockRequest() { Name = ByteString.CopyFromUtf8(name), }, headers)); }
/// <summary> /// UnlockAsync takes a key returned by Lock and releases the hold on lock. The /// next Lock caller waiting for the lock will then be woken up and given /// ownership of the lock. /// </summary> /// <param name="key">the lock ownership key granted by Lock.</param> /// <returns></returns> public async Task <UnlockResponse> UnlockAsync(string key, Grpc.Core.Metadata headers = null) { return(await UnlockAsync(new UnlockRequest() { Key = ByteString.CopyFromUtf8(key), }, headers)); }
/// <summary> /// Unlock takes a key returned by Lock and releases the hold on lock. The /// next Lock caller waiting for the lock will then be woken up and given /// ownership of the lock. /// </summary> /// <param name="key">the lock ownership key granted by Lock.</param> /// <returns></returns> public UnlockResponse Unlock(string key, Grpc.Core.Metadata headers = null) { return(Unlock(new UnlockRequest() { Key = ByteString.CopyFromUtf8(key), }, headers)); }
/// <summary> /// Get the value for a specified key in async /// </summary> /// <param name="key">Key for which value need to be fetched</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The value for the specified key</returns> public async Task <string> GetValAsync(string key, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { RangeResponse rangeResponse = await GetAsync(key, headers, deadline, cancellationToken); return(rangeResponse.Count != 0 ? rangeResponse.Kvs[0].Value.ToStringUtf8().Trim() : string.Empty); }
/// <summary> /// Get the etcd response for a specified key in async /// </summary> /// <param name="request"></param> /// <returns>The etcd response for the specified request</returns> public async Task <RangeResponse> GetAsync(RangeRequest request, Grpc.Core.Metadata headers = null) { RangeResponse rangeResponse = new RangeResponse(); bool success = false; int retryCount = 0; while (!success) { try { rangeResponse = await _balancer.GetConnection().kvClient.RangeAsync(request, headers); success = true; } catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable) { retryCount++; if (retryCount >= _balancer._numNodes) { throw ex; } } } return(rangeResponse); }
/// <summary> /// LeaseKeepAlive keeps the lease alive by streaming keep alive requests from the client /// to the server and streaming keep alive responses from the server to the client. /// </summary> /// <param name="requests"></param> /// <param name="methods"></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 LeaseKeepAlive(LeaseKeepAliveRequest[] requests, Action <LeaseKeepAliveResponse>[] methods, CancellationToken cancellationToken, Grpc.Core.Metadata headers = null, DateTime?deadline = null) { await CallEtcdAsync(async (connection) => { using (AsyncDuplexStreamingCall <LeaseKeepAliveRequest, LeaseKeepAliveResponse> leaser = connection.leaseClient .LeaseKeepAlive(headers, deadline, cancellationToken)) { Task leaserTask = Task.Run(async() => { while (await leaser.ResponseStream.MoveNext(cancellationToken)) { LeaseKeepAliveResponse update = leaser.ResponseStream.Current; foreach (Action <LeaseKeepAliveResponse> method in methods) { method(update); } } }, cancellationToken); foreach (LeaseKeepAliveRequest request in requests) { await leaser.RequestStream.WriteAsync(request); } await leaser.RequestStream.CompleteAsync(); await leaserTask; } }); }
/// <summary> /// LeaseKeepAlive keeps the lease alive by streaming keep alive requests from the client /// to the server and streaming keep alive responses from the server to the client. /// </summary> /// <param name="requests"></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> public async Task LeaseKeepAlive(LeaseKeepAliveRequest[] requests, Action <LeaseKeepAliveResponse> method, CancellationToken cancellationToken, Grpc.Core.Metadata headers = null) => await CallEtcdAsync(async (connection) => { using (AsyncDuplexStreamingCall <LeaseKeepAliveRequest, LeaseKeepAliveResponse> leaser = connection._leaseClient .LeaseKeepAlive(headers, cancellationToken: cancellationToken)) { Task leaserTask = Task.Run(async() => { while (await leaser.ResponseStream.MoveNext(cancellationToken).ConfigureAwait(false)) { LeaseKeepAliveResponse update = leaser.ResponseStream.Current; method(update); } }, cancellationToken); foreach (LeaseKeepAliveRequest request in requests) { await leaser.RequestStream.WriteAsync(request).ConfigureAwait(false); } await leaser.RequestStream.CompleteAsync().ConfigureAwait(false); await leaserTask.ConfigureAwait(false); } }).ConfigureAwait(false);
/// <summary> /// Status gets the status of the member. /// </summary> /// <param name="request">Status Request</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>Status response</returns> public StatusResponse Status(StatusRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { StatusResponse response = new StatusResponse(); bool success = false; int retryCount = 0; while (!success) { try { response = _balancer.GetConnection().maintenanceClient .Status(request, headers, deadline, cancellationToken); success = true; } catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable) { retryCount++; if (retryCount >= _balancer._numNodes) { throw; } } } return(response); }
/// <summary> /// LeaseGrant creates a lease in async which expires if the server does not receive a keepAlive /// within a given time to live period. All keys attached to the lease will be expired and /// deleted if the lease expires. Each expired key generates a delete event in the event history. /// </summary> /// <param name="request">The request to send to the server.</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public async Task <LeaseGrantResponse> LeaseGrantAsync(LeaseGrantRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { LeaseGrantResponse response = new LeaseGrantResponse(); bool success = false; int retryCount = 0; while (!success) { try { response = await _balancer.GetConnection().leaseClient .LeaseGrantAsync(request, headers, deadline, cancellationToken); success = true; } catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable) { retryCount++; if (retryCount >= _balancer._numNodes) { throw; } } } return(response); }
/// <summary> /// RoleGet gets detailed role information /// </summary> /// <param name="request"></param> /// <returns></returns> public AuthRoleGetResponse RoleGet(AuthRoleGetRequest request, Grpc.Core.Metadata headers = null) { AuthRoleGetResponse response = new AuthRoleGetResponse(); bool success = false; int retryCount = 0; while (!success) { try { response = _balancer.GetConnection().authClient.RoleGet(request, headers); success = true; } catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable) { retryCount++; if (retryCount >= _balancer._numNodes) { throw ex; } } } return(response); }
/// <summary> /// Get the etcd response for a specified key in async /// </summary> /// <returns>The etcd response for the specified key</returns> /// <param name="key">Key for which value need to be fetched</param> public async Task <RangeResponse> GetAsync(string key, Grpc.Core.Metadata headers = null) { return(await GetAsync(new RangeRequest { Key = ByteString.CopyFromUtf8(key) }, headers)); }
public void WithMethods() { var options = new CallOptions(); var metadata = new Metadata(); Assert.AreSame(metadata, options.WithHeaders(metadata).Headers); var deadline = DateTime.UtcNow; Assert.AreEqual(deadline, options.WithDeadline(deadline).Deadline.Value); var cancellationToken = new CancellationTokenSource().Token; Assert.AreEqual(cancellationToken, options.WithCancellationToken(cancellationToken).CancellationToken); var writeOptions = new WriteOptions(); Assert.AreSame(writeOptions, options.WithWriteOptions(writeOptions).WriteOptions); var propagationToken = new ContextPropagationToken(CallSafeHandle.NullInstance, DateTime.UtcNow, CancellationToken.None, ContextPropagationOptions.Default); Assert.AreSame(propagationToken, options.WithPropagationToken(propagationToken).PropagationToken); var credentials = new FakeCallCredentials(); Assert.AreSame(credentials, options.WithCredentials(credentials).Credentials); // Check that the original instance is unchanged. Assert.IsNull(options.Headers); Assert.IsNull(options.Deadline); Assert.AreEqual(CancellationToken.None, options.CancellationToken); Assert.IsNull(options.WriteOptions); Assert.IsNull(options.PropagationToken); Assert.IsNull(options.Credentials); }
private Grpc.Core.Metadata GetDefaultHeaders() { var metadata = new Grpc.Core.Metadata(); metadata.Add("x-helm-api-client", Version); return(metadata); }
protected override void HandleCallException(Exception exception, IRpcSerializer?serializer) { var rpcError = RpcError.TryCreate(exception, serializer); if (rpcError != null) { if (serializer != null) { var serializedError = serializer.Serialize(rpcError); throw new GrpcCore.RpcException(new GrpcCore.Status(GrpcCore.StatusCode.Unknown, rpcError.Message), new GrpcCore.Metadata { { WellKnownHeaderKeys.ErrorInfo, serializedError } }); } else { var metadata = new GrpcCore.Metadata { { WellKnownHeaderKeys.ErrorType, rpcError.ErrorType }, { WellKnownHeaderKeys.ErrorMessage, rpcError.Message }, { WellKnownHeaderKeys.ErrorCode, rpcError.ErrorCode } }; if (rpcError.ErrorDetails != null) { metadata.Add(new GrpcCore.Metadata.Entry(WellKnownHeaderKeys.ErrorDetails, rpcError.ErrorDetails)); } throw new GrpcCore.RpcException(new GrpcCore.Status(GrpcCore.StatusCode.Unknown, rpcError.Message), metadata); } } }
/// <summary> /// Defragment defragments a member's backend database to recover storage space in async. /// </summary> /// <param name="request">Defragment Request</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>Defragment Response</returns> public async Task <DefragmentResponse> DefragmentAsync(DefragmentRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await CallEtcdAsync(async (connection) => await connection._maintenanceClient .DefragmentAsync(request, headers, deadline, cancellationToken)).ConfigureAwait(false)); }
/// <summary> /// LeaseRevoke revokes a lease. All keys attached to the lease will expire and be deleted. /// </summary> /// <param name="request">The request to send to the server.</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public LeaseRevokeResponse LeaseRevoke(LeaseRevokeRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(CallEtcd((connection) => connection.leaseClient .LeaseRevoke(request, headers, deadline, cancellationToken))); }
/// <summary> /// Creates a new instance of <c>CallOptions</c>. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { // TODO(jtattermusch): consider only creating metadata object once it's really needed. this.headers = headers != null ? headers : new Metadata(); this.deadline = deadline.HasValue ? deadline.Value : DateTime.MaxValue; this.cancellationToken = cancellationToken; }
/// <summary> /// Status gets the status of the member in async. /// </summary> /// <param name="request">Status Request</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>Status response</returns> public async Task <StatusResponse> StatusASync(StatusRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await CallEtcdAsync(async (connection) => await connection.maintenanceClient .StatusAsync(request, headers, deadline, cancellationToken))); }
/// <summary> /// Defragment defragments a member's backend database to recover storage space. /// </summary> /// <param name="request">Defragment Request</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>Defragment Response</returns> public DefragmentResponse Defragment(DefragmentRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(CallEtcd((connection) => connection._maintenanceClient .Defragment(request, headers, deadline, cancellationToken))); }
/// <summary> /// Status gets the status of the member. /// </summary> /// <param name="request">Status Request</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>Status response</returns> public StatusResponse Status(StatusRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(CallEtcd((connection) => connection.maintenanceClient .Status(request, headers, deadline, cancellationToken))); }
/// <summary> /// LeaseRevoke revokes a lease in async. All keys attached to the lease will expire and be deleted. /// </summary> /// <param name="request">The request to send to the server.</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public async Task <LeaseRevokeResponse> LeaseRevokeAsync(LeaseRevokeRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await CallEtcdAsync(async (connection) => await connection.leaseClient .LeaseRevokeAsync(request, headers, deadline, cancellationToken))); }
public async Task <Comment> RemoveAsync(int id) { var tokenResult = await tokenProvider.RequestAccessToken(new AccessTokenRequestOptions() { Scopes = new string[] { "commentsgrpc" } }); if (tokenResult.TryGetToken(out var token)) { GrpCore.Metadata headers = new GrpCore.Metadata(); headers.Add("Authorization", $"Bearer {token.Value}"); RemoveReply c = await serviceClient.RemoveAsync(new RemoveRequest() { Id = id }, headers); return(new Comment { Id = c.Id, PhotoId = c.PhotoId, UserName = c.UserName, Subject = c.Subject, Body = c.Body, SubmittedOn = c.SubmittedOn.ToDateTime() }); } else { throw new UnauthorizedDeleteAttemptException <Comment>(); } }
/// <summary> /// Get the etcd response for a specified key /// </summary> /// <returns>The etcd response for the specified key</returns> /// <param name="key">Key for which value need to be fetched</param> public RangeResponse Get(string key, Grpc.Core.Metadata headers = null) { return(Get(new RangeRequest { Key = ByteString.CopyFromUtf8(key) }, headers)); }
/// <summary> /// Delete the specified key in etcd /// </summary> /// <param name="key">Key which needs to be deleted</param> public DeleteRangeResponse Delete(string key, Grpc.Core.Metadata headers = null) { return(Delete(new DeleteRangeRequest { Key = ByteString.CopyFromUtf8(key) }, headers)); }
/// <summary> /// Get the etcd response for a specified key /// </summary> /// <param name="key">Key for which value need to be fetched</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The etcd response for the specified key</returns> public RangeResponse Get(string key, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(Get(new RangeRequest { Key = ByteString.CopyFromUtf8(key) }, headers, deadline, cancellationToken)); }
public ServerCallContext(string method, string host, DateTime deadline, Metadata requestHeaders, CancellationToken cancellationToken) { this.method = method; this.host = host; this.deadline = deadline; this.requestHeaders = requestHeaders; this.cancellationToken = cancellationToken; }
/// <summary> /// LockAsync acquires a distributed shared lock on a given named lock. /// On success, it will return a unique key that exists so long as the /// lock is held by the caller. This key can be used in conjunction with /// transactions to safely ensure updates to etcd only occur while holding /// lock ownership. The lock is held until Unlock is called on the key or the /// lease associate with the owner expires. /// </summary> /// <param name="name">is the identifier for the distributed shared lock to be acquired.</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public async Task <LockResponse> LockAsync(string name, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await LockAsync(new LockRequest() { Name = ByteString.CopyFromUtf8(name), }, headers, deadline, cancellationToken)); }
/// <summary> /// UnlockAsync takes a key returned by Lock and releases the hold on lock. The /// next Lock caller waiting for the lock will then be woken up and given /// ownership of the lock. /// </summary> /// <param name="key">the lock ownership key granted by Lock.</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public async Task <UnlockResponse> UnlockAsync(string key, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await UnlockAsync(new UnlockRequest() { Key = ByteString.CopyFromUtf8(key), }, headers, deadline, cancellationToken)); }
/// <summary> /// Sets the key value in etcd /// </summary> /// <param name="key">Key for which value need to be set</param> /// <param name="val">Value corresponding the key</param> /// <returns></returns> public PutResponse Put(string key, string val, Grpc.Core.Metadata headers = null) { return(Put(new PutRequest { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(val) }, headers)); }
/// <summary> /// Sets the key value in etcd in async /// </summary> /// <param name="key">Key for which value need to be set</param> /// <param name="val">Value corresponding the key</param> /// <returns></returns> public async Task <PutResponse> PutAsync(string key, string val, Grpc.Core.Metadata headers = null) { return(await PutAsync(new PutRequest { Key = ByteString.CopyFromUtf8(key), Value = ByteString.CopyFromUtf8(val) }, headers)); }
/// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; }
public void CreateAndDestroy() { var metadata = new Metadata { new Metadata.Entry("host", "somehost"), new Metadata.Entry("header2", "header value"), }; var nativeMetadata = MetadataArraySafeHandle.Create(metadata); nativeMetadata.Dispose(); }
public ServerRpcNew(Server server, CallSafeHandle call, string method, string host, Timespec deadline, Metadata requestMetadata) { this.server = server; this.call = call; this.method = method; this.host = host; this.deadline = deadline; this.requestMetadata = requestMetadata; }
/// <summary> /// Delete the specified key in etcd in async /// </summary> /// <param name="key">Key which needs to be deleted</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> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public async Task <DeleteRangeResponse> DeleteAsync(string key, Grpc.Core.Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default) { return(await DeleteAsync(new DeleteRangeRequest { Key = ByteString.CopyFromUtf8(key) }, headers, deadline, cancellationToken)); }
public CallGrpcClientJob( ILoggerFactory loggerFactory) { Logger = loggerFactory.CreateLogger("CallGrpcClientJob"); channel = new Channel("localhost:828", ChannelCredentials.Insecure); AuthMetadata = new Grpc.Core.Metadata(); AuthMetadata.Add("token", "smallchi518"); }
/// <summary> /// Creates a new instance of <c>CallOptions</c>. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken? cancellationToken = null, WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null) { // TODO(jtattermusch): consider only creating metadata object once it's really needed. this.headers = headers ?? new Metadata(); this.deadline = deadline ?? (propagationToken != null ? propagationToken.Deadline : DateTime.MaxValue); this.cancellationToken = cancellationToken ?? (propagationToken != null ? propagationToken.CancellationToken : CancellationToken.None); this.writeOptions = writeOptions; this.propagationToken = propagationToken; }
public void Init() { helper = new MockServiceHelper(); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); headers = new Metadata { { "ascii-header", "abcdefg" } }; }
internal ServerCallContext(CallSafeHandle callHandle, string method, string host, DateTime deadline, Metadata requestHeaders, CancellationToken cancellationToken, Func<Metadata, Task> writeHeadersFunc, IHasWriteOptions writeOptionsHolder) { this.callHandle = callHandle; this.method = method; this.host = host; this.deadline = deadline; this.requestHeaders = requestHeaders; this.cancellationToken = cancellationToken; this.writeHeadersFunc = writeHeadersFunc; this.writeOptionsHolder = writeOptionsHolder; }
public void ReadMetadataFromPtrUnsafe() { var metadata = new Metadata { new Metadata.Entry("host", "somehost"), new Metadata.Entry("header2", "header value"), }; var nativeMetadata = MetadataArraySafeHandle.Create(metadata); var copy = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(nativeMetadata.Handle); Assert.AreEqual(2, copy.Count); Assert.AreEqual("host", copy[0].Key); Assert.AreEqual("somehost", copy[0].Value); Assert.AreEqual("header2", copy[1].Key); Assert.AreEqual("header value", copy[1].Value); nativeMetadata.Dispose(); }
public void WithMethods() { var options = new CallOptions(); var metadata = new Metadata(); Assert.AreSame(metadata, options.WithHeaders(metadata).Headers); var deadline = DateTime.UtcNow; Assert.AreEqual(deadline, options.WithDeadline(deadline).Deadline.Value); var token = new CancellationTokenSource().Token; Assert.AreEqual(token, options.WithCancellationToken(token).CancellationToken); // Change original instance is unchanged. Assert.IsNull(options.Headers); Assert.IsNull(options.Deadline); Assert.AreEqual(CancellationToken.None, options.CancellationToken); Assert.IsNull(options.WriteOptions); Assert.IsNull(options.PropagationToken); Assert.IsNull(options.Credentials); }
public void Merge_HeaderMutationOrdering() { Action<Metadata> clearAndAddFoo = m => { m.Clear(); m.Add("foo", "bar"); }; Action<Metadata> addSample = m => m.Add("sample", "value"); CallSettings clearAndAddFooSettings = new CallSettings(null, null, null, clearAndAddFoo, null, null); CallSettings addSampleSettings = new CallSettings(null, null, null, addSample, null, null); var merged1 = CallSettings.Merge(clearAndAddFooSettings, addSampleSettings); var merged2 = CallSettings.Merge(addSampleSettings, clearAndAddFooSettings); // Original should be called first, so merged1 should end up with foo and sample; // merged2 should end up with just foo. var metadata = new Metadata(); merged1.HeaderMutation(metadata); Assert.Equal(2, metadata.Count); metadata = new Metadata(); merged2.HeaderMutation(metadata); Assert.Equal(1, metadata.Count); }
public AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RunClient, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); }
public void AsyncUnaryCall_EchoMetadata() { var headers = new Metadata { new Metadata.Entry("asciiHeader", "abcdefg"), new Metadata.Entry("binaryHeader-bin", new byte[] { 1, 2, 3, 0, 0xff }), }; var internalCall = new Call<string, string>(ServiceName, EchoMethod, channel, headers); var call = Calls.AsyncUnaryCall(internalCall, "ABC", CancellationToken.None); Assert.AreEqual("ABC", call.ResponseAsync.Result); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); }
/// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; }
public static void RunPerRpcCreds(TestService.TestServiceClient client) { Console.WriteLine("running per_rpc_creds"); var credential = GoogleCredential.GetApplicationDefault().CreateScoped(new[] { AuthScope }); Assert.IsTrue(credential.RequestAccessTokenAsync(CancellationToken.None).Result); string oauth2Token = credential.Token.AccessToken; var headerInterceptor = OAuth2Interceptors.FromAccessToken(oauth2Token); var request = SimpleRequest.CreateBuilder() .SetFillUsername(true) .SetFillOauthScope(true) .Build(); var headers = new Metadata(); headerInterceptor(headers); var response = client.UnaryCall(request, headers: headers); Assert.AreEqual(AuthScopeResponse, response.OauthScope); Assert.AreEqual(ServiceAccountUser, response.Username); Console.WriteLine("Passed!"); }
public AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); }
public global::grpc.testing.Empty EmptyCall(global::grpc.testing.Empty request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_EmptyCall, headers, deadline); return Calls.BlockingUnaryCall(call, request, cancellationToken); }
public AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_Sum, headers); return Calls.AsyncClientStreamingCall(call, cancellationToken); }
public AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_Div, headers); return Calls.AsyncUnaryCall(call, request, cancellationToken); }
public AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_DivMany, headers); return Calls.AsyncDuplexStreamingCall(call, cancellationToken); }
public global::Walletrpc.CloseWalletResponse CloseWallet(global::Walletrpc.CloseWalletRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CloseWallet, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); }
public AsyncUnaryCall<global::Walletrpc.StartBtcdRpcResponse> StartBtcdRpcAsync(global::Walletrpc.StartBtcdRpcRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_StartBtcdRpc, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); }
public AsyncServerStreamingCall<global::Walletrpc.AccountNotificationsResponse> AccountNotifications(global::Walletrpc.AccountNotificationsRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_AccountNotifications, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncServerStreamingCall(call, request); }
public AsyncUnaryCall<global::grpc.testing.SimpleResponse> UnaryCallAsync(global::grpc.testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_UnaryCall, headers, deadline); return Calls.AsyncUnaryCall(call, request, cancellationToken); }
public AsyncServerStreamingCall<global::grpc.testing.StreamingOutputCallResponse> StreamingOutputCall(global::grpc.testing.StreamingOutputCallRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_StreamingOutputCall, headers, deadline); return Calls.AsyncServerStreamingCall(call, request, cancellationToken); }
public AsyncUnaryCall<global::Grpc.Health.V1Alpha.HealthCheckResponse> CheckAsync(global::Grpc.Health.V1Alpha.HealthCheckRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_Check, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); }
public AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__ServiceName, __Method_Fib, headers); return Calls.AsyncServerStreamingCall(call, request, cancellationToken); }
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 AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_StreamingCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); }