public async Task Invoke(IGrainCallContext ctx)
        {
            //
            // NOTE: this grain demonstrates incorrect usage of grain call interceptors and should not be used
            // as an example of proper usage. Specifically, storing the context for later execution is invalid.
            //

            this.context = ctx;
            if (string.Equals(ctx.Method.Name, nameof(CallWithBadInterceptors)) && (bool)ctx.Arguments[0])
            {
                await ctx.Invoke();
            }

            if (RequestContext.Get(Key) is string value)
            {
                RequestContext.Set(Key, value + '3');
            }
            await ctx.Invoke();

            if (string.Equals(ctx.Method?.Name, nameof(CallWithBadInterceptors)) && (bool)ctx.Arguments[1])
            {
                await ctx.Invoke();
            }

            this.context = null;
        }
        public async Task Invoke(IGrainCallContext context)
        {
            if (context.Method.Name == nameof(GetInputAsString))
            {
                context.Result = $"Hah! You wanted {context.Arguments[0]}, but you got me!";
                return;
            }

            await context.Invoke();
        }
Example #3
0
            public Task Invoke(IGrainCallContext context)
            {
                if (string.Equals(context.Method.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext)))
                {
                    if (RequestContext.Get(GrainCallFilterTestConstants.Key) is string value)
                    {
                        RequestContext.Set(GrainCallFilterTestConstants.Key, value + '2');
                    }
                }

                return(context.Invoke());
            }
Example #4
0
        public async Task Invoke(IGrainCallContext context)
        {
            var initialLastStreamValue = this.lastStreamValue;
            await context.Invoke();

            // If the last stream value changed after the invoke, then the stream must have produced a value, double
            // it for testing purposes.
            if (this.lastStreamValue != initialLastStreamValue)
            {
                this.lastStreamValue *= 2;
            }
        }
Example #5
0
        public async Task <object> Invoke(MethodInfo method, InvokeMethodRequest request, IGrainMethodInvoker invoker)
        {
            var value = RequestContext.Get(Key) as string;

            if (value != null)
            {
                RequestContext.Set(Key, value + '5');
            }

            if (string.Equals(method?.Name, nameof(CallWithBadInterceptors)) && (bool)request.Arguments[0])
            {
                await context.Invoke();
            }

            var result = await invoker.Invoke(this, request);

            if (string.Equals(method?.Name, nameof(CallWithBadInterceptors)) && (bool)request.Arguments[1])
            {
                await context.Invoke();
            }

            return(result);
        }
Example #6
0
        async Task IGrainCallFilter.Invoke(IGrainCallContext context)
        {
            var methodInfo = context.Method;

            if (methodInfo.Name == nameof(One) && methodInfo.GetParameters().Length == 0)
            {
                // Short-circuit the request and return to the caller without actually invoking the grain method.
                context.Result = "intercepted one with no args";
                return;
            }

            if (methodInfo.Name == nameof(IncorrectResultType))
            {
                // This method has a string return type, but we are setting the result to a Guid.
                // This should result in an invalid cast exception.
                context.Result = Guid.NewGuid();
                return;
            }

            if (methodInfo.Name == nameof(FilterThrows))
            {
                throw new MyDomainSpecificException("Filter THROW!");
            }

            // Invoke the request.
            try
            {
                await context.Invoke();
            }
            catch (MyDomainSpecificException e)
            {
                context.Result = "EXCEPTION! " + e.Message;
                return;
            }

            // To prove that the MethodInfo is from the implementation and not the interface,
            // we check for this attribute which is only present on the implementation. This could be
            // done in a simpler fashion, but this demonstrates a potential usage scenario.
            var shouldMessWithResult = methodInfo.GetCustomAttribute <MessWithResultAttribute>();
            var resultString         = context.Result as string;

            if (shouldMessWithResult != null && resultString != null)
            {
                context.Result = string.Concat(resultString.Reverse());
            }
        }
Example #7
0
        public async Task Invoke(IGrainCallContext ctx)
        {
            //
            // NOTE: this grain demonstrates incorrect usage of grain call interceptors and should not be used
            // as an example of proper usage. Specifically, storing the context for later execution is invalid.
            //

            this.context = ctx;
            var value = RequestContext.Get(Key) as string;

            if (value != null)
            {
                RequestContext.Set(Key, value + '4');
            }
            await ctx.Invoke();

            this.context = null;
        }
        public async Task Invoke(IGrainCallContext context)
        {
            var timerInfo    = context.Method.GetCustomAttribute <LogElapsedTimeAttribute>();
            var globalMillis = _runtimeConfiguration.LogGrainCallsExceedingMilliseconds;

            if (context.Grain is IGrain grain && (timerInfo != null || globalMillis > 0))
            {
                var sw        = Stopwatch.StartNew();
                var logMillis = timerInfo?.IfExceedsMilliseconds ?? globalMillis;

                try {
                    await context.Invoke();
                } finally {
                    sw.Stop();
                    if (sw.ElapsedMilliseconds > logMillis)
                    {
                        grain.Info($"GRAIN_ELAPSED_TIME {grain.GetType().Name}.{context.Method.Name}: {sw.Elapsed}", "", "", 0);
                    }
                }
            }
Example #9
0
        protected static async Task Process(IGrainCallContext context, Activity activity)
        {
            if (activity is not null)
            {
                // rpc attributes from https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/rpc.md
                activity.SetTag("rpc.service", context.InterfaceMethod?.DeclaringType?.FullName);
                activity.SetTag("rpc.method", context.InterfaceMethod?.Name);
                activity.SetTag("net.peer.name", context.Grain?.ToString());
                activity.SetTag("rpc.system", "orleans");
            }

            try
            {
                await context.Invoke();

                if (activity is not null && activity.IsAllDataRequested)
                {
                    activity.SetTag("status", "Ok");
                }
            }
            catch (Exception e)
            {
                if (activity is not null && activity.IsAllDataRequested)
                {
                    // exception attributes from https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/exceptions.md
                    activity.SetTag("exception.type", e.GetType().FullName);
                    activity.SetTag("exception.message", e.Message);
                    activity.SetTag("exception.stacktrace", e.StackTrace);
                    activity.SetTag("exception.escaped", true);
                    activity.SetTag("status", "Error");
                }
                throw;
            }
            finally
            {
                activity?.Stop();
            }
        }
Example #10
0
        public async Task Invoke(IGrainCallContext context)
        {
            Activity activity = null;

            // export requestcontext once
            IDictionary <string, object> requestContext = RequestContext.Export(_serializationManager);;

            if (requestContext != null && requestContext.ContainsKey(DiagnosticsLoggingStrings.RequestIdHeaderName))
            {
                // flow activity from request headers
                activity = StartActivity(context, requestContext);
            }

            try
            {
                await context.Invoke().ConfigureAwait(false);

                if (activity != null)
                {
                    // is set when diagnosticslistener is enabled
                    // requestcontext dictionary is also not null
                    StopActivity(context, activity, requestContext);
                }
            }
            catch (Exception ex)
            {
                //capture failed method...
                if (_listener.IsEnabled(DiagnosticsLoggingStrings.DiagnosticsUnhandledExceptionName))
                {
                    var timestamp = Stopwatch.GetTimestamp();
                    // Diagnostics is enabled for UnhandledException, but it may not be for BeginRequest
                    // so call GetTimestamp if currentTimestamp is zero (from above)
                    RecordUnhandledExceptionDiagnostics(context, timestamp, ex);
                }
                throw;
            }
        }
Example #11
0
        public async Task Invoke(IGrainCallContext context)
        {
            if (siloAddress == null)
            {
                var providerRuntime = services.GetRequiredService <IProviderRuntime>();

                siloAddress = providerRuntime.SiloIdentity.ToSiloAddress();
            }

            var stopwatch = Stopwatch.StartNew();

            var isException = false;

            try
            {
                await context.Invoke();
            }
            catch (Exception)
            {
                isException = true;
                throw;
            }
            finally
            {
                try
                {
                    stopwatch.Stop();

                    var elapsedMs  = (double)stopwatch.ElapsedTicks / TimeSpan.TicksPerMillisecond;
                    var grainName  = context.Grain.GetType().FullName;
                    var methodName = formatMethodName(context);

                    var key = string.Format("{0}.{1}", grainName, methodName);

                    grainTrace.AddOrUpdate(key, _ =>
                                           new GrainTraceEntry
                    {
                        Count          = 1,
                        ExceptionCount = (isException ? 1 : 0),
                        SiloAddress    = siloAddress,
                        ElapsedTime    = elapsedMs,
                        Grain          = grainName,
                        Method         = methodName,
                        Period         = DateTime.UtcNow
                    },
                                           (_, last) =>
                    {
                        last.Count       += 1;
                        last.ElapsedTime += elapsedMs;

                        if (isException)
                        {
                            last.ExceptionCount += 1;
                        }

                        return(last);
                    });
                }
                catch (Exception ex)
                {
                    logger.LogError(100002, "error recording results for grain", ex);
                }
            }
        }