Exemple #1
0
        public static CallOptions GetCallOptions(this double timeOut)
        {
            var callOption = new CallOptions();

            callOption.WithDeadline(DateTime.Now.AddMilliseconds(timeOut));
            return(callOption);
        }
Exemple #2
0
 private CallOptions SetDeadline(CallOptions callOptions)
 {
     if (callOptions.Deadline == null)
     {
         callOptions = callOptions.WithDeadline(DateTime.UtcNow.AddSeconds(_callTimeOut));
     }
     return(callOptions);
 }
Exemple #3
0
        protected override async Task <IResult <T> > HandleInvoke <T>(IInvocation invocation)
        {
            var paraTypes = new Type[invocation.Arguments.Length + 1];
            var parasPlus = new object[invocation.Arguments.Length + 1];

            for (var i = 0; i < invocation.Arguments.Length; i++)
            {
                paraTypes[i] = invocation.Arguments[i].GetType();
                parasPlus[i] = invocation.Arguments[i];
            }
            paraTypes[invocation.Arguments.Length] = typeof(CallOptions);

            var callOption = new CallOptions();

            if (_clientTimeout > 0)
            {
                callOption.WithDeadline(DateTime.Now.AddMilliseconds(_clientTimeout));
            }
            parasPlus[invocation.Arguments.Length] = callOption;

            var method = _instance.GetType().GetMethod(invocation.MethodInfo.Name, paraTypes);

            var watch = Stopwatch.StartNew();

            try
            {
                var taskResult = method.Invoke(_instance, parasPlus);
                if (taskResult.GetType().GetTypeInfo().IsGenericType&&
                    taskResult.GetType().GetGenericTypeDefinition() == typeof(AsyncUnaryCall <>))
                {
                    var resultData = await(AsyncUnaryCall <T>) taskResult;
                    watch.Stop();
                    var result = new RpcResult <T>(resultData, watch.ElapsedMilliseconds);
                    return(result);
                }
                else
                {
                    watch.Stop();
                    var result = new RpcResult <T>((T)taskResult.ChangeType(typeof(T)), watch.ElapsedMilliseconds);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.StackTrace);
                throw ex;
            }
            finally
            {
                if (watch.IsRunning)
                {
                    watch.Stop();
                }
                Logger().LogInformation($"Grpc Invoke {watch.ElapsedMilliseconds} ms");
            }
        }
Exemple #4
0
        public CallOptions GetGrpcCallOptions(CancellationToken?cancellationToken)
        {
            CallOptions callOptions = new CallOptions();

            if (_callTimeout > 0)
            {
                callOptions = callOptions.WithDeadline(DateTime.Now.AddMilliseconds(_callTimeout));
            }

            return(callOptions);
        }
 private CallOptions OverrideCallOptions(CallOptions options)
 {
     if (!_timeout.HasValue)
     {
         return(options);
     }
     else
     {
         return(options.WithDeadline(DateTime.UtcNow.AddMilliseconds(_timeout.Value.TotalMilliseconds)));
     }
 }
Exemple #6
0
        private (DgraphConnection, CallOptions) AnyConnection()
        {
            Random rand       = new Random();
            var    connection = _pool.Connections[rand.Next(0, _pool.Connections.Count)];

            var callOptions = new CallOptions();

            var deadline = GetDeadline();

            if (deadline.HasValue)
            {
                callOptions = callOptions.WithDeadline(deadline.Value);
            }

            return(connection, callOptions);
        }
        private GrpcCall <TRequest, TResponse> CreateGrpcCall <TRequest, TResponse>(
            Method <TRequest, TResponse> method,
            CallOptions options,
            out Action disposeAction)
            where TRequest : class
            where TResponse : class
        {
            if (_client.BaseAddress == null)
            {
                throw new InvalidOperationException("Unable to send the gRPC call because no server address has been configured. " +
                                                    "Set HttpClient.BaseAddress on the HttpClient used to created to gRPC client.");
            }

            CancellationTokenSource?linkedCts = null;

            // Use propagated deadline if it is small than the specified deadline
            if (Deadline < options.Deadline)
            {
                options = options.WithDeadline(Deadline);
            }

            if (CancellationToken.CanBeCanceled)
            {
                if (options.CancellationToken.CanBeCanceled)
                {
                    // If both propagated and options cancellation token can be canceled
                    // then set a new linked token of both
                    linkedCts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, options.CancellationToken);
                    options   = options.WithCancellationToken(linkedCts.Token);
                }
                else
                {
                    options = options.WithCancellationToken(CancellationToken);
                }
            }

            var call = new GrpcCall <TRequest, TResponse>(method, options, Clock, _loggerFactory);

            // Clean up linked cancellation token
            disposeAction = linkedCts != null
                ? () => { call.Dispose(); linkedCts !.Dispose(); }
                : (Action)call.Dispose;

            return(call);
        }
Exemple #8
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 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);

            var flags = CallFlags.WaitForReady | CallFlags.CacheableRequest;

            Assert.AreEqual(flags, options.WithFlags(flags).Flags);

            // 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);
            Assert.AreEqual(default(CallFlags), options.Flags);
        }
Exemple #9
0
        private CallOptions GetCallOptions(bool isConnectToServer = false, bool addAuth = false, bool noDeadline = false)
        {
            int         deadlineSec;
            CallOptions calloptions;

            if (isConnectToServer)
            {
                deadlineSec = _coreComOptions.GrpcOptions.ConnectToServerDeadlineSec;
            }
            else if (noDeadline || _coreComOptions.GrpcOptions.ConnectToServerDeadlineSec == -1)
            {
                deadlineSec = 0;
                Console.WriteLine("deadlineSec=NoDeadLine");
            }
            else
            {
                deadlineSec = _coreComOptions.GrpcOptions.MessageDeadlineSec * _coreComOptions.GrpcOptions.MessageDeadlineSecMultiplay;
                Console.WriteLine("deadlineSec=" + deadlineSec.ToString());
            }
            if (addAuth && !string.IsNullOrEmpty(_coreComOptions.ClientToken))
            {
                var headers = new Metadata();
                headers.Add("Authorization", $"Bearer {_coreComOptions.ClientToken}");
                calloptions = new CallOptions(headers);//.WithWaitForReady(true)
                if (!noDeadline)
                {
                    calloptions = calloptions.WithDeadline(DateTime.UtcNow.AddSeconds(deadlineSec));
                }
            }
            else
            {
                calloptions = new CallOptions();//.WithWaitForReady(true)
                if (!noDeadline)
                {
                    calloptions = calloptions.WithDeadline(DateTime.UtcNow.AddSeconds(deadlineSec));
                }
            }
            return(calloptions);
        }
Exemple #10
0
        private GrpcCall <TRequest, TResponse> CreateGrpcCall <TRequest, TResponse>(
            Method <TRequest, TResponse> method,
            CallOptions options,
            out Action disposeAction)
            where TRequest : class
            where TResponse : class
        {
            CancellationTokenSource?linkedCts = null;

            // Use propagated deadline if it is small than the specified deadline
            if (Deadline < options.Deadline)
            {
                options = options.WithDeadline(Deadline);
            }

            if (CancellationToken.CanBeCanceled)
            {
                if (options.CancellationToken.CanBeCanceled)
                {
                    // If both propagated and options cancellation token can be canceled
                    // then set a new linked token of both
                    linkedCts = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken, options.CancellationToken);
                    options   = options.WithCancellationToken(linkedCts.Token);
                }
                else
                {
                    options = options.WithCancellationToken(CancellationToken);
                }
            }

            var call = new GrpcCall <TRequest, TResponse>(method, options, Clock, _loggerFactory);

            // Clean up linked cancellation token
            disposeAction = linkedCts != null
                ? () => { call.Dispose(); linkedCts !.Dispose(); }
                : (Action)call.Dispose;

            return(call);
        }
        private CallOptions PrepareCallOptions(CancellationToken cancellationToken)
        {
            var callOptions = new CallOptions().WithCancellationToken(cancellationToken);

            if (callCredentials != null)
            {
                callOptions.WithCredentials(callCredentials);
            }

            if (deadlineOnMessages.HasValue)
            {
                var date = clock.GetUtcNow();
                date = date + deadlineOnMessages.Value;
                callOptions.WithDeadline(date);
            }

            if (writeOptions != null)
            {
                callOptions.WithWriteOptions(writeOptions);
            }

            return(callOptions);
        }
Exemple #12
0
        /// <summary>
        /// Creates a populated call options instance based on the provided parameters
        /// </summary>
        /// <param name="metadata">The metadata to be added for the call.</param>
        /// <param name="credentials">The credentials associated with the call</param>
        /// <param name="timeout">The timespan to add to the current UTC time to act as the call deadline</param>
        /// <param name="cancellationToken">A best effort cancellation token</param>
        /// <returns>A call options instace</returns>
        public static CallOptions GetCallOptions(Metadata metadata = null, CallCredentials credentials = null, TimeSpan?timeout = null, CancellationToken cancellationToken = default)
        {
            var options = new CallOptions();

            if (metadata != null)
            {
                options = options.WithHeaders(metadata);
            }
            if (cancellationToken != default)
            {
                options = options.WithCancellationToken(cancellationToken);
            }
            if (timeout.HasValue)
            {
                options = options.WithDeadline(DateTime.UtcNow.Add(timeout.Value));
            }
            if (credentials != null)
            {
                options = options.WithCredentials(credentials);
            }

            return(options);
        }
Exemple #13
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);
        }