Exemplo n.º 1
0
 /// <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));
 }
Exemplo n.º 2
0
 /// <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));
 }
Exemplo n.º 3
0
 /// <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));
 }
Exemplo n.º 4
0
 /// <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));
 }
Exemplo n.º 5
0
        /// <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);
        }
Exemplo n.º 6
0
        /// <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);
        }
Exemplo n.º 7
0
        /// <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;
                }
            });
        }
Exemplo n.º 8
0
        /// <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);
Exemplo n.º 9
0
        /// <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);
        }
Exemplo n.º 10
0
        /// <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);
        }
Exemplo n.º 11
0
        /// <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);
        }
Exemplo n.º 12
0
 /// <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);
        }
Exemplo n.º 14
0
        private Grpc.Core.Metadata GetDefaultHeaders()
        {
            var metadata = new Grpc.Core.Metadata();

            metadata.Add("x-helm-api-client", Version);
            return(metadata);
        }
Exemplo n.º 15
0
        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);
                }
            }
        }
Exemplo n.º 16
0
 /// <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));
 }
Exemplo n.º 17
0
 /// <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)));
 }
Exemplo n.º 18
0
 /// <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;
 }
Exemplo n.º 19
0
 /// <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)));
 }
Exemplo n.º 20
0
 /// <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)));
 }
Exemplo n.º 21
0
 /// <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)));
 }
Exemplo n.º 22
0
 /// <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)));
 }
Exemplo n.º 23
0
        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>();
            }
        }
Exemplo n.º 24
0
 /// <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));
 }
Exemplo n.º 25
0
 /// <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));
 }
Exemplo n.º 26
0
 /// <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));
 }
Exemplo n.º 27
0
 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;
 }
Exemplo n.º 28
0
 /// <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));
 }
Exemplo n.º 29
0
 /// <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));
 }
Exemplo n.º 30
0
 /// <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));
 }
Exemplo n.º 31
0
 /// <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));
 }
Exemplo n.º 32
0
 /// <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;
 }
Exemplo n.º 33
0
 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;
 }
Exemplo n.º 35
0
 /// <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));
 }
Exemplo n.º 36
0
 public CallGrpcClientJob(
     ILoggerFactory loggerFactory)
 {
     Logger  = loggerFactory.CreateLogger("CallGrpcClientJob");
     channel = new Channel("localhost:828",
                           ChannelCredentials.Insecure);
     AuthMetadata = new Grpc.Core.Metadata();
     AuthMetadata.Add("token", "smallchi518");
 }
Exemplo n.º 37
0
 /// <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" } };
        }
Exemplo n.º 39
0
 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;
 }
Exemplo n.º 40
0
        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();
        }
Exemplo n.º 41
0
        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);
        }
Exemplo n.º 42
0
        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);
        }
Exemplo n.º 43
0
 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);
 }
Exemplo n.º 44
0
        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);
        }
Exemplo n.º 45
0
 /// <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;
 }
Exemplo n.º 46
0
        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!");
        }
Exemplo n.º 47
0
 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);
 }
Exemplo n.º 48
0
 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);
 }
Exemplo n.º 49
0
 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);
 }
Exemplo n.º 50
0
 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);
 }
Exemplo n.º 51
0
 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);
 }
Exemplo n.º 52
0
 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);
 }
Exemplo n.º 53
0
 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);
 }
Exemplo n.º 54
0
 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);
 }
Exemplo n.º 55
0
 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);
 }
Exemplo n.º 56
0
 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);
 }
Exemplo n.º 57
0
 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);
 }
Exemplo n.º 58
0
 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);
 }
Exemplo n.º 59
0
        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!");
        }
Exemplo n.º 60
0
 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);
 }