public async Task Invoke(IIncomingGrainCallContext context) { if (!context.InterfaceMethod.Name.Equals("DeliverBatch")) { await context.Invoke(); return; } var spanContext = RequestContext.Get("SpanContext") as ISpanContext; if (spanContext != null) { using (GlobalTracer.Instance.BuildSpan(context.ImplementationMethod.Name).AsChildOf(spanContext) .WithTag("grain-id", context.Grain.GetPrimaryKeyString()) .WithTag("grain-name", context.Grain.GetType().Name) .StartActive(true)) { await context.Invoke(); } } else { await context.Invoke(); } }
public async Task Invoke(IIncomingGrainCallContext context) { var tracer = _oneAgentSdk.TraceIncomingMessageProcess( _oneAgentSdk.CreateMessagingSystemInfo("Orleans Incoming", context?.Grain?.ToString(), MessageDestinationType.QUEUE, ChannelType.IN_PROCESS, "")); if (RequestContext.Get("TraceId") != null) { tracer.SetCorrelationId(RequestContext.Get("TraceId").ToString()); tracer.SetDynatraceByteTag((byte[])RequestContext.Get(OneAgentSdkConstants.DYNATRACE_MESSAGE_PROPERTYNAME)); //_logger.LogDebug("Incoming Dyntrace Byte Tag : {byte_tag}", RequestContext.Get(OneAgentSdkConstants.DYNATRACE_MESSAGE_PROPERTYNAME)); _logger.LogDebug("Tracing Incoming {grainType} Correlation Id {traceId}", context.Grain.GetType().FullName, RequestContext.Get("TraceId")); await tracer.TraceAsync(async() => { await context.Invoke(); }); } else { await context.Invoke(); } }
public async Task Invoke(IIncomingGrainCallContext 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.ImplementationMethod.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.ImplementationMethod?.Name, nameof(CallWithBadInterceptors)) && (bool)ctx.Arguments[1]) { await ctx.Invoke(); } this.context = null; }
public async Task Should_not_log_domain_exceptions() { A.CallTo(() => context.Invoke()) .Throws(new ValidationException("Failed")); await Assert.ThrowsAsync <ValidationException>(() => sut.Invoke(context)); A.CallTo(() => log.Log(A <SemanticLogLevel> ._, A <Exception?> ._, A <LogFormatter> ._ !)) .MustNotHaveHappened(); }
public async Task Should_not_log_domain_exceptions() { A.CallTo(() => context.Invoke()) .Throws(new ValidationException("Failed")); await Assert.ThrowsAsync <ValidationException>(() => sut.Invoke(context)); A.CallTo(() => log.Log(A <SemanticLogLevel> .Ignored, A <None> .Ignored, A <Action <None, IObjectWriter> > .Ignored)) .MustNotHaveHappened(); }
public async Task Should_not_log_domain_exceptions() { A.CallTo(() => context.Invoke()) .Throws(new ValidationException("Failed")); await Assert.ThrowsAsync <ValidationException>(() => sut.Invoke(context)); A.CallTo(() => logFactory.CreateLogger(A <string> ._)) .MustNotHaveHappened(); }
public async Task Should_just_forward_serializable_exception() { var original = new InvalidOperationException(); A.CallTo(() => context.Invoke()) .Throws(original); var ex = await Assert.ThrowsAnyAsync <Exception>(() => sut.Invoke(context)); Assert.Same(ex, original); }
public async Task Invoke(IIncomingGrainCallContext context) { AuthorizeAttribute authAttr = this.FindAuthorizeAttribute(context); if (authAttr == null) { await context.Invoke(); return; } //已经授权无需再次授权 if (RequestContext.Get(UserPrincipalKey) != null) { var UserPrincipal = RequestContext.Get(UserPrincipalKey); if (UserPrincipal.GetType() == typeof(ClaimsPrincipal)) { if (this.VerifyPolicy(context, (ClaimsPrincipal)UserPrincipal, authAttr)) { await context.Invoke(); return; } } } //获取授权的方案 var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate == null) { await context.Invoke(); return; } //授权处理 var authContext = new AuthenticateContext(ServiceProvider); var result = await authContext.AuthenticateAsync(defaultAuthenticate.Name); if (result?.Succeeded != true) { this.Logger.LogError(result.Failure, result.Failure.Message); throw new AuthenticationException("Authorization Token is invalid"); } //验证 Policy if (this.VerifyPolicy(context, result.Principal, authAttr)) { RequestContext.Set(UserPrincipalKey, result.Principal); } await context.Invoke(); }
public async Task Invoke(IIncomingGrainCallContext context) { var grainType = context.Grain.GetType(); var grainName = grainType.GetDemystifiedName(); var shouldHaveDetailedTrace = grainType.Namespace.Contains("Heroes"); // todo: Create log filter mechanism if (!shouldHaveDetailedTrace) { await context.Invoke(); return; } string primaryKey = null; if (context.Grain is Grain grain) { primaryKey = grain.GetPrimaryKeyAny(); } var stopwatch = Stopwatch.StartNew(); try { await context.Invoke(); stopwatch.Stop(); //if (stopwatch.Elapsed > WarnThreshold) //{ _logger.LogDebug( "Executed grain method {grain}.{grainMethod} ({primaryKey}) in {duration:n0}ms", grainName, context.ImplementationMethod.Name, primaryKey, stopwatch.ElapsedMilliseconds ); //} } catch (Exception ex) { _logger.LogError( ex, "Execution failed for grain method {grain}.{grainMethod} ({primaryKey}) in {duration:n0}ms.", primaryKey, grainName, context.ImplementationMethod.Name, stopwatch.ElapsedMilliseconds ) ; throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { if (!context.Grain.GetType().Namespace.StartsWith("Orleans", StringComparison.OrdinalIgnoreCase)) { using (localCache.StartContext()) { await context.Invoke(); } } else { await context.Invoke(); } }
public async Task Invoke(IIncomingGrainCallContext context) { try { await context.Invoke(); var msg = string.Format( "{0}.{1}({2}) returned value {3}", context.Grain.GetType(), context.InterfaceMethod.Name, string.Join(", ", context.Arguments), context.Result); _log.LogInformation(msg); } catch (Exception e) { var msg = string.Format( "{0}.{1}({2}) threw an exception: {3}", context.Grain.GetType(), context.InterfaceMethod.Name, string.Join(", ", context.Arguments), e); _log.LogInformation(msg); throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { try { if (!(context.Grain is IHelloGrain)) { var grain = _grainFactory.GetGrain <IHelloGrain>(new Guid()); // Perform some grain call here. await grain.Other(); } await context.Invoke(); if (context.InterfaceMethod.Name == "GetFavoriteNumber") { var msg = $"调用方法为: {context.Grain.GetType()}.{context.InterfaceMethod.Name}({(context.Arguments != null ? string.Join(", ", context.Arguments) : "")}) 返回值为: {context.Result}"; Console.WriteLine(msg); } } catch (Exception exception) { var msg = $"{context.Grain.GetType()}.{context.InterfaceMethod.Name}({(context.Arguments != null ? string.Join(", ", context.Arguments) : "")}) 抛出了一个异常: {exception.Message}"; Console.WriteLine(msg); throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { if (context.Arguments?.FirstOrDefault() is string phrase && string.Equals("please", phrase)) { _throttleScore = 0; } // Work out how long it's been since the last call var elapsedSeconds = _stopwatch.Elapsed.TotalSeconds; _stopwatch.Restart(); // Calculate a new score based on a constant rate of score decay and the time which elapsed since the last call. _throttleScore = Math.Max(0, _throttleScore - elapsedSeconds * DecayRate) + 1; // If the user has exceeded the threshold, deny their request and give them a helpful warning. if (_throttleScore > ThrottleThreshold) { var remainingSeconds = Math.Max(0, (int)Math.Ceiling((_throttleScore - (ThrottleThreshold - 1)) / DecayRate)); _logger.LogError("Throttling"); throw new ThrottlingException($"Request rate exceeded, wait {remainingSeconds}s before retrying"); } await context.Invoke(); }
public async Task Invoke(IIncomingGrainCallContext context) { try { if (ShowLog(context.ImplementationMethod.Name)) { var arguments = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); _logger.LogInformation($"LOGGINGFILTER TraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}:arguments{arguments} request"); } await context.Invoke(); if (ShowLog(context.ImplementationMethod.Name)) { var result = JsonConvert.SerializeObject(context.Result, _serializerSettings); _logger.LogInformation($"LOGGINGFILTERTraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}:arguments{result} request"); _logger.LogInformation($""); } } catch (Exception ex) { var arguments = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); var result = JsonConvert.SerializeObject(context.Result, _serializerSettings); _logger.LogError($"LOGGINGFILTERTraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}: threw exception: {nameof(ex)} request", ex); throw; } }
public async Task Invoke(IIncomingGrainCallContext ctx) { var attemptsRemaining = 2; while (attemptsRemaining > 0) { try { if (RequestContext.Get(Key) is string value) { RequestContext.Set(Key, value + '3'); } await ctx.Invoke(); return; } catch (ArgumentOutOfRangeException) when(attemptsRemaining > 1) { if (string.Equals(ctx.ImplementationMethod?.Name, nameof(ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value) { ctx.Arguments[0] = value - 1; } --attemptsRemaining; } } }
public async Task Invoke(IIncomingGrainCallContext context) { await context.Invoke(); var grainType = context.Grain.GetType(); var bufferIdObj = RequestContext.Get(Constants.BufferIdKey); if (bufferIdObj != null && grainType.GetCustomAttributes(typeof(BufferInMemAttribute), true).Length > 0) { var bufferId = (Guid)bufferIdObj; var grainTypeEnum = grainType.Name switch { nameof(JobGrainInMem) => BufferedGrainInterfaceType.JobGrain, nameof(DescendantsRefGrainInMem) => BufferedGrainInterfaceType.DescendantsRefGrain, nameof(JobTreeStatisticsGrainInMem) => BufferedGrainInterfaceType.JobTreeStatisticsGrain, _ => BufferedGrainInterfaceType.JobGrain }; await _client.GetGrain <IBufferManagerGrain>(bufferId) .AddToBufferAsync(new AddToBufferDto(context.Grain.GetPrimaryKeyLong(), grainTypeEnum)); } } }
public async Task Invoke(IIncomingGrainCallContext context) { var name = $"Grain/{context.Grain?.GetType().Name}/{context.ImplementationMethod?.Name}"; using (Telemetry.Activities.StartActivity(name)) { try { await context.Invoke(); } catch (DomainException ex) { if (ex.InnerException != null) { Log(context, ex.InnerException); } throw; } catch (Exception ex) { Log(context, ex); throw; } } }
/// <summary> /// 拦截器记录日志 /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(IIncomingGrainCallContext context) { string sw8 = RequestContext.Get(IdentityServerConsts.ClaimTypes.SkyWalking) as string; string OperId = this.GrainId.ToString(); var tracingTimestamp = _diagnosticListener.OrleansInvokeBefore(context.Grain.GetType(), context.InterfaceMethod, OperId, this.RuntimeIdentity, sw8); try { await context.Invoke(); _diagnosticListener.OrleansInvokeAfter(tracingTimestamp); } catch (Exception exception) { Logger.LogError($"Grain执行异常", exception); if (FuncExceptionHandler != null) { await FuncExceptionHandler(exception); } _diagnosticListener.OrleansInvokeError(tracingTimestamp, exception); throw exception; } }
public async Task Invoke(IIncomingGrainCallContext context) { Console.WriteLine("Hello! Start to invoke our grain."); await context.Invoke(); Console.WriteLine(" I am done with invoking"); }
public async Task Invoke(IIncomingGrainCallContext context) { try { await context.Invoke(); } catch (DomainObjectNotFoundException) { TryDeactivate(context); throw; } catch (WrongEventVersionException) { TryDeactivate(context); throw; } catch (InconsistentStateException) { TryDeactivate(context); throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { //调用方法前获取参数,调用方法后修改返回值 //if (context.Arguments != null) //{ // foreach (var arg in context.Arguments) // { // Console.WriteLine($"参数:{arg}"); // } // if (context.Arguments.Length > 0) // { // context.Arguments[0] = "桂素伟加一"; // } //} //await context.Invoke(); //// Change the result of the call from 7 to 38. //if (string.Equals(context.InterfaceMethod.Name, nameof(this.GetFavoriteNumber))) //{ // context.Result = 38; //} //用特性的方式控制访问 var isAdminMethod = context.ImplementationMethod.GetCustomAttribute <AdminOnlyAttribute>() != null; if (isAdminMethod && !(bool)RequestContext.Get("isAdmin")) { throw new Exception($"只有 admins 能访问 {context.ImplementationMethod.Name}!"); } await context.Invoke(); }
public async Task Invoke(IIncomingGrainCallContext context) { LogWrite(context, () => { Console.WriteLine($"{this.GetType().Name} Grain Before Invoke"); Console.WriteLine($"{this.GetType().Name} Grain Name: {context.Grain.GetType().FullName}"); Console.WriteLine($"{this.GetType().Name} Grain Interface Type: {context.InterfaceMethod.DeclaringType?.FullName}"); Console.WriteLine($"{this.GetType().Name} Grain Implementation Type: {context.ImplementationMethod.DeclaringType?.FullName}"); Console.WriteLine($"{this.GetType().Name} Grain PrimaryKey: {context.Grain.GetPrimaryKeyLong()}"); Console.WriteLine($"{this.GetType().Name} Grain Method Arguments: {string.Join(",", context.Arguments)}"); }); try { await context.Invoke(); LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain After Invoke")); } catch (Exception e) { LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain Exception: {e}")); throw; } finally { LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain Result: {context.Result}")); } }
public async Task Invoke(IIncomingGrainCallContext context) { Console.WriteLine("Before Method Invoke, incoming call filter"); await context.Invoke(); Console.WriteLine("After Method Invoke, incoming call filter"); }
Task IIncomingGrainCallFilter.Invoke(IIncomingGrainCallContext ctx) { if (ctx.InterfaceMethod is null) { throw new Exception("InterfaceMethod is null"); } if (!ctx.InterfaceMethod.DeclaringType.IsInterface) { throw new Exception("InterfaceMethod is not an interface method"); } if (ctx.ImplementationMethod is null) { throw new Exception("ImplementationMethod is null"); } if (ctx.ImplementationMethod.DeclaringType.IsInterface) { throw new Exception("ImplementationMethod is an interface method"); } if (RequestContext.Get("tag") is string tag) { var ifaceTag = ctx.InterfaceMethod.GetCustomAttribute <TestMethodTagAttribute>()?.Tag; var implTag = ctx.ImplementationMethod.GetCustomAttribute <TestMethodTagAttribute>()?.Tag; if (!string.Equals(tag, ifaceTag, StringComparison.Ordinal) || !string.Equals(tag, implTag, StringComparison.Ordinal)) { throw new Exception($"Expected method tags to be equal to request context tag: RequestContext: {tag} Interface: {ifaceTag} Implementation: {implTag}"); } } return(ctx.Invoke()); }
public async Task Invoke(IIncomingGrainCallContext ctx) { var attemptsRemaining = 2; while (attemptsRemaining > 0) { try { var interfaceMethod = ctx.InterfaceMethod ?? throw new ArgumentException("InterfaceMethod is null!"); var implementationMethod = ctx.ImplementationMethod ?? throw new ArgumentException("ImplementationMethod is null!"); if (!string.Equals(implementationMethod.Name, interfaceMethod.Name)) { throw new ArgumentException("InterfaceMethod.Name != ImplementationMethod.Name"); } if (RequestContext.Get(Key) is string value) { RequestContext.Set(Key, value + '3'); } await ctx.Invoke(); return; } catch (ArgumentOutOfRangeException) when(attemptsRemaining > 1) { if (string.Equals(ctx.ImplementationMethod?.Name, nameof(ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value) { ctx.Arguments[0] = (object)(value - 1); } --attemptsRemaining; } } }
public async Task Invoke(IIncomingGrainCallContext context) { try { if (ShouldLod(context.InterfaceMethod.Name)) { var arguments = JsonConvert.SerializeObject(context.Arguments, _jsonSerializerSettings); _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: arguments: {arguments} request"); } await context.Invoke(); if (ShouldLod(context.InterfaceMethod.Name)) { var result = JsonConvert.SerializeObject(context.Result, _jsonSerializerSettings); _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: result: {result} request"); } } catch (Exception ex) { var arguments = JsonConvert.SerializeObject(context.Arguments, _jsonSerializerSettings); var result = JsonConvert.SerializeObject(context.Result, _jsonSerializerSettings); _logger.LogError($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: threw an exception: {nameof(ex)} request", ex); throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { try { if (ShouldLog(context.InterfaceMethod.Name)) { var args = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: arguments: {args} REQUEST"); } // triggers called method await context.Invoke(); if (ShouldLog(context.InterfaceMethod.Name)) { var result = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: result: {result} RESULT"); } } catch (Exception e) { var args = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); var result = JsonConvert.SerializeObject(context.Arguments, _serializerSettings); _logger.LogError($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: threw an exception: {nameof(e)} RESULT", e); throw; } }
public async Task Invoke(IIncomingGrainCallContext context) { bool isOrleansGrain = context.InterfaceMethod == null || context.InterfaceMethod.DeclaringType == null || context.InterfaceMethod.Module.Assembly.FullName.StartsWith("Orleans"); //TODO add test that validate that we are not introducing new grain in micro dot bool isMicrodotGrain = isOrleansGrain == false && context.InterfaceMethod.DeclaringType.Name == nameof(IRequestProcessingGrain); bool isServiceGrain = isOrleansGrain == false && isMicrodotGrain == false; var grainTags = new Lazy <GrainTags>(() => new GrainTags(context)); // Drop the request if we're overloaded var loadSheddingConfig = _loadSheddingConfig(); if ( (loadSheddingConfig.ApplyToMicrodotGrains && isMicrodotGrain) || (loadSheddingConfig.ApplyToServiceGrains && isServiceGrain) ) { //Can brake the flow by throwing Overloaded RejectRequestIfLateOrOverloaded(grainTags); } var loggingConfig = _grainLoggingConfig(); bool shouldLog = (loggingConfig.LogOrleansGrains && isOrleansGrain) || (loggingConfig.LogMicrodotGrains && isMicrodotGrain) || (loggingConfig.LogServiceGrains && isServiceGrain); shouldLog = shouldLog && !ShouldSkipLoggingUnderRatio(loggingConfig, TracingContext.TryGetRequestID()); GrainCallEvent grainEvent = null; if (shouldLog) { RequestTimings.GetOrCreate(); // Ensure request timings is created here and not in the grain call. RequestTimings.Current.Request.Start(); grainEvent = _eventPublisher.CreateEvent(); grainEvent.ParentSpanId = TracingContext.TryGetParentSpanID(); grainEvent.SpanId = Guid.NewGuid().ToString("N"); TracingContext.SetParentSpan(grainEvent.SpanId); } Exception ex = null; try { await context.Invoke(); } catch (Exception e) { ex = e; throw; } finally { if (shouldLog) { RequestTimings.Current.Request.Stop(); PublishEvent(ex, grainTags, grainEvent); } } }
public async Task Should_update_iam_alive_for_grain_base() { var limit = A.Fake <IActivationLimit>(); var grain = new MyGrain(limit); A.CallTo(() => context.Grain) .Returns(grain); await sut.Invoke(context); A.CallTo(() => limit.ReportIAmAlive()) .MustHaveHappened(); A.CallTo(() => context.Invoke()) .MustHaveHappened(); }
public Task Invoke(IIncomingGrainCallContext context) { if (context.Grain is GrainBase grainBase) { grainBase.ReportIAmAlive(); } return(context.Invoke()); }