public static IStatefulActorService GetActorServiceHandler(string appName, string serviceName, string partitionKey)
        {
            var serviceUri = $"fabric:/{appName}/{serviceName}";
            ActorProxyFactory actorProxyFactory = new ActorProxyFactory();

            return(actorProxyFactory.CreateActorServiceProxy <IStatefulActorService>(new Uri(serviceUri), long.Parse(partitionKey)));
        }
        private async Task MakeRequestAsync(IAbpMethodInvocation invocation)
        {
            // 获取Actor配置
            var actorProxyConfig    = DaprActorProxyOptions.ActorProxies.GetOrDefault(typeof(TService)) ?? throw new AbpException($"Could not get DynamicDaprActorProxyConfig for {typeof(TService).FullName}.");
            var remoteServiceConfig = DaprActorOptions.RemoteActors.GetConfigurationOrDefault(actorProxyConfig.RemoteServiceName);

            var actorProxyOptions = new ActorProxyOptions
            {
                HttpEndpoint = remoteServiceConfig.BaseUrl
            };

            // 自定义请求处理器
            // 添加请求头用于传递状态
            // TODO: Actor一次只能处理一个请求,使用状态管理来传递状态的可行性?
            var httpClientHandler = new DaprHttpClientHandler();

            // 身份认证处理
            await ActoryProxyAuthenticator.AuthenticateAsync(
                new DaprActorProxyAuthenticateContext(
                    httpClientHandler, remoteServiceConfig, actorProxyConfig.RemoteServiceName));

            AddHeaders(httpClientHandler);

            // 代理工厂
            var proxyFactory = new ActorProxyFactory(actorProxyOptions, (HttpMessageHandler)httpClientHandler);

            await MakeRequestAsync(invocation, proxyFactory, remoteServiceConfig);
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                foreach (var name in ObjectMother.Names)
                {
                    var correlationId     = Guid.NewGuid();
                    var actorProxyFactory =
                        new ActorProxyFactory(
                            callbackClient =>
                            FabricTransportActorRemotingHelpers.CreateServiceRemotingClientFactory(typeof(IPersonActorService), callbackClient, _communicationLogger,
                                                                                                   correlationId.ToString()));
                    //var actorProxyFactory = new ActorProxyFactory();
                    await actorProxyFactory.RunInContext(async factory =>
                    {
                        var title = ObjectMother.Titles[Environment.TickCount % ObjectMother.Titles.Length];

                        var proxy = actorProxyFactory.CreateActorProxy <IPersonActor>(new ActorId(name));
                        await proxy.SetTitleAsync(title, cancellationToken);

                        _logger.PersonGenerated(name, title);
                    },
                                                         _communicationLogger,
                                                         new CustomServiceRequestHeader(new Dictionary <string, string>()
                    {
                        { "name", "service itself" }, { "correlation-id", Guid.NewGuid().ToString() }
                    })
                                                         );

                    await Task.Delay(200000, cancellationToken);
                }
            }
        }
        public CorrelatingActorProxyFactory(
            Func <IServiceRemotingCallbackMessageHandler, IServiceRemotingClientFactory> createServiceRemotingClientFactory = null,
            OperationRetrySettings retrySettings = null,
            Action <CallSummary> raiseSummary    = null,
            string remoteServiceName             = null)
        {
            _defaultListenerName = ActorHelper.GetDefaultListenerName <TActorInterface>(out _providerAttribute);

            if (_providerAttribute != null)
            {
                createServiceRemotingClientFactory = _providerAttribute.CreateServiceRemotingClientFactory;
            }

            //_actorProxyFactory = new ActorProxyFactory();

            _actorProxyFactory = new ActorProxyFactory(
                (callbackClient) =>
            {
                if (createServiceRemotingClientFactory == null)
                {
                    return(new CorrelatingFabricTransportServiceRemotingClientFactory <TActorInterface>(inner: null, raiseSummary: raiseSummary, remoteServiceName: remoteServiceName));
                }

                IServiceRemotingClientFactory innerClientFactory = createServiceRemotingClientFactory(callbackClient);

                if (innerClientFactory is CorrelatingFabricTransportServiceRemotingClientFactory <TActorInterface> )
                {
                    return(innerClientFactory);
                }

                return(new CorrelatingFabricTransportServiceRemotingClientFactory <TActorInterface>(inner: innerClientFactory, raiseSummary: raiseSummary, remoteServiceName: remoteServiceName));
            },
                retrySettings);
        }
Beispiel #5
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // This line registers an Actor Service to host your actor class with the Service Fabric runtime.
                // The contents of your ServiceManifest.xml and ApplicationManifest.xml files
                // are automatically populated when you build this project.
                // For more information, see https://aka.ms/servicefabricactorsplatform


                var actorProxyFactory          = new ActorProxyFactory();
                var serviceProxyFactory        = new ServiceProxyFactory();
                IRepositoryFactories factories = null;

                ActorRuntime.RegisterActorAsync <ParticipantActor>(
                    (context, actorType) => new ActorService(context, actorType, (service, actorId) =>
                                                             new ParticipantActor(service, actorId, actorProxyFactory, serviceProxyFactory, factories))).GetAwaiter().GetResult();


                ActorRuntime.RegisterActorAsync <ApprovalActor>(
                    (context, actorType) => new ActorService(context, actorType, (service, actorId) =>
                                                             new ApprovalActor(service, actorId, actorProxyFactory, serviceProxyFactory, factories))).GetAwaiter().GetResult();

                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
Beispiel #6
0
        public async Task TestActorRemotingAsync()
        {
            var payload             = new Payload("content");
            var service             = new CustomActorService(MockStatefulServiceContextFactory.Default, ActorTypeInformation.Get(typeof(RemotingEnabledActor)));
            var factory             = new ServiceFabric.Mocks.RemotingV2.MockActorServiceRemotingClientFactory(service);
            var responseMessageBody = new MockServiceRemotingResponseMessageBody()
            {
                Response = payload
            };
            var requestMessageBody = new MockServiceRemotingRequestMessageBody();

            factory.MockServiceRemotingMessageBodyFactory = new MockServiceRemotingMessageBodyFactory()
            {
                Request  = requestMessageBody,
                Response = responseMessageBody
            };
            factory.ServiceRemotingClient = new RemotingV2.MockActorServiceRemotingClient(service)
            {
                ServiceRemotingResponseMessage = new MockServiceRemotingResponseMessage
                {
                    Body = responseMessageBody
                }
            };

            var proxyFactory = new ActorProxyFactory(callbackClient => factory);
            var proxy        = proxyFactory.CreateActorProxy <IMyStatefulActor>(ActorId.CreateRandom(), "App", "Service", "Listener");
            await proxy.InsertAsync("state", payload);

            Assert.IsInstanceOfType(proxy, typeof(IMyStatefulActor));
        }
Beispiel #7
0
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            long iterations = 0;

            var actorProxyFactory = new ActorProxyFactory();
            var readSpeakers      = new List <string>();
            var readSessions      = new List <string>();

            var scraper = new Scraper(this.Context);

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var speakers = await scraper.ScanSpeakers();

                var tasks = new List <Task>();
                foreach (var speaker in speakers)
                {
                    if (!readSpeakers.Contains(speaker.GetShortHash()))
                    {
                        ServiceEventSource.Current.SpeakerFound(this.Context, speaker);

                        var speakerActor     = actorProxyFactory.CreateActorProxy <ISpeakerActor>(new ActorId(speaker.Name));
                        var speakerInfoAsync = speakerActor.SetSpeakerInfoAsync(speaker.ToSpeakerInfo(), cancellationToken);
                        tasks.Add(speakerInfoAsync);

                        readSpeakers.Add(speaker.GetShortHash());
                    }
                }
                await Task.WhenAll(tasks);

                var sessions = await scraper.ScanSessions();

                tasks = new List <Task>();

                scraper.AddSessionsToSpeakers(speakers, sessions);

                foreach (var speaker in speakers)
                {
                    if (!readSessions.Contains(speaker.Sessions.GetShortHash()))
                    {
                        ServiceEventSource.Current.ServiceMessage(this.Context, $"Updating {speaker.Sessions.Count} sessions for speaker {speaker.Name}");

                        var speakerActor  = actorProxyFactory.CreateActorProxy <ISpeakerActor>(new ActorId(speaker.Name));
                        var sessionsAsync = speakerActor.SetSessionsAsync(speaker.Sessions.Select(session => session.ToSessionInfo()).ToArray(), cancellationToken);
                        tasks.Add(sessionsAsync);

                        readSessions.Add(speaker.Sessions.GetShortHash());
                    }
                }
                await Task.WhenAll(tasks);


                ServiceEventSource.Current.ServiceMessage(this.Context, "Scanning sessions-{0}", ++iterations);

                await Task.Delay(TimeSpan.FromSeconds(20), cancellationToken);
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            // use this to start the reproduction of the issue
            var proxyFactory = new ActorProxyFactory();
            var proxy        = proxyFactory.CreateActorProxy <IRemindMe>(new Uri("fabric:/RedundantReminderRepro/RemindMeActorService"), new ActorId(1337));

            proxy.CreateReminderAsync("get toilet paper from store").Wait();
        }
        public async Task TestActorRemotingAsync()
        {
            var service      = new CustomActorService(MockStatefulServiceContextFactory.Default, ActorTypeInformation.Get(typeof(MyStatefulActor)));
            var factory      = new MockActorServiceRemotingClientFactory(service);
            var proxyFactory = new ActorProxyFactory(callbackClient => factory);
            var proxy        = proxyFactory.CreateActorProxy <IMyStatefulActor>(ActorId.CreateRandom(), "App", "Service", "Listener");
            await proxy.InsertAsync("state", new Payload("content"));

            Assert.IsInstanceOfType(proxy, typeof(IMyStatefulActor));
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            var proxyFactory = new ActorProxyFactory((c) =>
            {
                return(new CustomActorRemotingClientFactory(c));
            });

            var actorId = new ActorId("test");
            var proxy   = proxyFactory.CreateActorProxy <IActor1>(actorId, "fabric:/ActorCustomMessageHandler");
            var res     = proxy.GetContextData(CancellationToken.None).GetAwaiter().GetResult();
        }
        /// <summary>
        /// Creates an <see cref="ActorProxy"/>
        /// </summary>
        /// <typeparam name="TActorInterface">The type of the actor to create</typeparam>
        /// <param name="actorId">The id of the actor to address</param>
        /// <param name="customHeaderProvider">A factory to create a <see cref="CustomHeaders"/> instance with data passed to the actor</param>
        /// <param name="applicationName"></param>
        /// <param name="serviceName"></param>
        /// <param name="listenerName"></param>
        /// <returns>An actor proxy object that implements IActorProxy and TActorInterface.</returns>
        public static TActorInterface Create <TActorInterface>(ActorId actorId, Func <CustomHeaders> customHeaderProvider, string applicationName = null, string serviceName = null, string listenerName = null) where TActorInterface : IActor
        {
            var methodNameProvider = new MethodNameProvider();

            var proxyFactory = new ActorProxyFactory(handler =>
                                                     new ExtendedServiceRemotingClientFactory(
                                                         new FabricTransportActorRemotingClientFactory(handler), customHeaderProvider, methodNameProvider));
            var proxy = proxyFactory.CreateActorProxy <TActorInterface>(actorId, applicationName, serviceName, listenerName);

            methodNameProvider.AddMethodsForProxyOrService(proxy.GetType().GetInterfaces(), typeof(IActor));
            return(proxy);
        }
        public async Task Alternative_TestSubscribe_Doesnt_CrashAsync()
        {
            var guid    = Guid.NewGuid();
            var service = new CustomActorService(MockStatefulServiceContextFactory.Default, ActorTypeInformation.Get(typeof(MyStatefulActor)));
            var factory = new MockActorServiceRemotingClientFactory(service);

            var mockProxyFactory = new ActorProxyFactory(callbackClient => factory);
            var exampleService   = new ExampleClient(MockStatefulServiceContextFactory.Default, new MockReliableStateManager(),
                                                     null, mockProxyFactory);
            await exampleService.DoSomething(guid, "message text");

            Assert.IsFalse(IsSuccess);             //Subscribe doesn't crash the test, but the Event is not really fired and processed at this time
        }
Beispiel #13
0
        public async Task <int[]> GetSomeNumbers()
        {
            var tasks = new List <Task <int> >();

            for (var i = 0; i < 5; ++i)
            {
                var proxy = ActorProxyFactory.CreateActorProxy <INumberActor>(new ActorId(Guid.NewGuid()));

                tasks.Add(proxy.GetANumber());
            }

            return((await Task.WhenAll(tasks)).ToArray());
        }
Beispiel #14
0
        public void CreateProxyWithNoRemoting_WithNoApiToken()
        {
            var actorId = new ActorId("abc");
            var handler = new TestHttpClientHandler();
            var factory = new ActorProxyFactory(null, handler);
            var proxy   = factory.Create(actorId, "TestActor");
            var task    = proxy.InvokeMethodAsync("SetCountAsync", 1, new CancellationToken());

            handler.Requests.TryDequeue(out var entry).Should().BeTrue();
            Action action = () => entry.Request.Headers.GetValues("dapr-api-token");

            action.Should().Throw <InvalidOperationException>();
        }
        private async Task MakeRequestAsync(
            IAbpMethodInvocation invocation,
            ActorProxyFactory proxyFactory,
            DaprActorConfiguration configuration
            )
        {
            var actorId = new ActorId(configuration.ActorId);

            var invokeType = typeof(TService);
            // 约定的 RemoteServiceAttribute 为Actor名称
            var remoteServiceAttr = invokeType.GetTypeInfo().GetCustomAttribute <RemoteServiceAttribute>();
            var actorType         = remoteServiceAttr != null
                ? remoteServiceAttr.Name
                : invokeType.Name;


            try
            {
                // 创建强类型代理
                var actorProxy = proxyFactory.CreateActorProxy <TService>(actorId, actorType);
                // 远程调用
                var   task = (Task)invocation.Method.Invoke(actorProxy, invocation.Arguments);
                await task;

                // 存在返回值
                if (!invocation.Method.ReturnType.GenericTypeArguments.IsNullOrEmpty())
                {
                    // 处理返回值
                    invocation.ReturnValue = typeof(Task <>)
                                             .MakeGenericType(invocation.Method.ReturnType.GenericTypeArguments[0])
                                             .GetProperty(nameof(Task <object> .Result), BindingFlags.Public | BindingFlags.Instance)
                                             .GetValue(task);
                }
            }
            catch (ActorMethodInvocationException amie) // 其他异常忽略交给框架处理
            {
                if (amie.InnerException != null && amie.InnerException is ActorInvokeException aie)
                {
                    // Dapr 包装了远程服务异常
                    throw new AbpDaprActorCallException(
                              new RemoteServiceErrorInfo
                    {
                        Message = aie.Message,
                        Code    = aie.ActualExceptionType
                    }
                              );
                }
                throw;
            }
        }
Beispiel #16
0
        private async Task MakeRequestAsync(IAbpMethodInvocation invocation)
        {
            // 获取Actor配置
            var actorProxyConfig    = DaprActorProxyOptions.ActorProxies.GetOrDefault(typeof(TService)) ?? throw new AbpException($"Could not get DynamicDaprActorProxyConfig for {typeof(TService).FullName}.");
            var remoteServiceConfig = DaprServiceOptions.RemoteServices.GetConfigurationOrDefault(actorProxyConfig.RemoteServiceName);

            // Actors的定义太多, 可以考虑使用默认的 BaseUrl 作为远程地址
            if (remoteServiceConfig.BaseUrl.IsNullOrWhiteSpace())
            {
                throw new AbpException($"Could not get BaseUrl for {actorProxyConfig.RemoteServiceName} Or Default.");
            }

            var actorProxyOptions = new ActorProxyOptions
            {
                HttpEndpoint = remoteServiceConfig.BaseUrl
            };

            // 自定义请求处理器
            // 添加请求头用于传递状态
            // TODO: Actor一次只能处理一个请求,使用状态管理来传递状态的可行性?
            var httpClientHandler = new DaprHttpClientHandler();

            AddHeaders(httpClientHandler);

            httpClientHandler.PreConfigure(async(requestMessage) =>
            {
                // 占位
                var httpClient = HttpClientFactory.Create(AbpDaprActorsModule.DaprHttpClient);

                await ClientAuthenticator.Authenticate(
                    new RemoteServiceHttpClientAuthenticateContext(
                        httpClient,
                        requestMessage,
                        remoteServiceConfig,
                        actorProxyConfig.RemoteServiceName));
                // 标头
                if (requestMessage.Headers.Authorization == null &&
                    httpClient.DefaultRequestHeaders.Authorization != null)
                {
                    requestMessage.Headers.Authorization = httpClient.DefaultRequestHeaders.Authorization;
                }
            });

            // 代理工厂
            var proxyFactory = new ActorProxyFactory(actorProxyOptions, (HttpMessageHandler)httpClientHandler);

            await MakeRequestAsync(invocation, proxyFactory);
        }
Beispiel #17
0
        /// <summary>
        /// Instantiates the <see cref="CorrelatingActorProxyFactory"/> with the specified remoting factory and retrysettings.
        /// </summary>
        /// <param name="serviceContext">The service context for the calling service</param>
        /// <param name="createActorRemotingClientFactory">
        /// Specifies the factory method that creates the remoting client factory. The remoting client factory got from this method
        /// is cached in the ActorProxyFactory.
        /// </param>
        /// <param name="retrySettings">Specifies the retry policy to use on exceptions seen when using the proxies created by this factory</param>
        public CorrelatingActorProxyFactory(ServiceContext serviceContext, Func <IServiceRemotingCallbackClient, IServiceRemotingClientFactory> createActorRemotingClientFactory = null, OperationRetrySettings retrySettings = null)
        {
            this.methodNameProvider = new MethodNameProvider(true /* threadSafe */);

            // Layer the factory structure so the hierarchy will look like this:
            // CorrelatingServiceProxyFactory
            //  --> ServiceProxyFactory
            //      --> CorrelatingServiceRemotingFactory
            //          --> <Factory created by createActorRemotingClientFactory>
            this.actorProxyFactory = new ActorProxyFactory(
                callbackClient => {
                IServiceRemotingClientFactory innerClientFactory = createActorRemotingClientFactory(callbackClient);
                return(new CorrelatingServiceRemotingClientFactory(innerClientFactory, this.methodNameProvider));
            },
                retrySettings);
        }
Beispiel #18
0
        // GET api/values/5
        public async Task <Person> Get(string id)
        {
            //var actorProxyFactory = new ActorProxyFactory(client =>
            //	new FabricTransportServiceRemotingClientFactory(
            //		new Microsoft.ServiceFabric.Services.Remoting.FabricTransport.Client.FabricTransportServiceRemotingClientFactory(callbackClient: client),
            //		GetRequestHeaders(true)));
            var actorProxyFactory = new ActorProxyFactory();

            var proxy = actorProxyFactory.CreateActorProxy <IPersonActor>(
                new Uri($"fabric:/{FabricRuntime.GetActivationContext().ApplicationName}/PersonActorService"),
                new ActorId(id));

            var person = await proxy.GetPersonAsync(CancellationToken.None);

            return(person);
        }
Beispiel #19
0
        public void CreateProxyWithNoRemoting_WithApiToken()
        {
            var actorId = new ActorId("abc");
            var handler = new TestHttpClientHandler();
            var options = new ActorProxyOptions
            {
                DaprApiToken = "test_token",
            };
            var factory = new ActorProxyFactory(options, handler);
            var proxy   = factory.Create(actorId, "TestActor");
            var task    = proxy.InvokeMethodAsync("SetCountAsync", 1, new CancellationToken());

            handler.Requests.TryDequeue(out var entry).Should().BeTrue();
            var headerValues = entry.Request.Headers.GetValues("dapr-api-token");

            headerValues.Should().Contain("test_token");
        }
Beispiel #20
0
        public async Task <string> SayHelloToActor()
        {
            // Read the data from the custom header
            var remotingContext =
                string.Join(", ", RemotingContext.Keys.Select(k => $"{k}: {RemotingContext.GetData(k)}"));

            ServiceEventSource.Current.ServiceMessage(Context, $"SayHelloToActor got context: {remotingContext}");

            // Call the actor using the same headers as received by this method
            var proxyFactory = new ActorProxyFactory(handler =>
                                                     new ExtendedServiceRemotingClientFactory(
                                                         new FabricTransportActorRemotingClientFactory(handler), CustomHeaders.FromRemotingContext));
            var proxy    = proxyFactory.CreateActorProxy <IDemoActor>(new ActorId(1));
            var response = await proxy.GetGreetingResponseAsync(CancellationToken.None);

            return($"DemoService passed context '{remotingContext}' to actor and got as response: {response}");
        }
        /// <summary>
        /// Adds Dapr Actors support to the service collection.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" />.</param>
        /// <param name="configure">A delegate used to configure actor options and register actor types.</param>
        public static void AddActors(this IServiceCollection services, Action <ActorRuntimeOptions> configure)
        {
            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // Routing and health checks are required dependencies.
            services.AddRouting();
            services.AddHealthChecks();

            services.TryAddSingleton <ActorActivatorFactory, DependencyInjectionActorActivatorFactory>();
            services.TryAddSingleton <ActorRuntime>(s =>
            {
                var options          = s.GetRequiredService <IOptions <ActorRuntimeOptions> >().Value;
                var loggerFactory    = s.GetRequiredService <ILoggerFactory>();
                var activatorFactory = s.GetRequiredService <ActorActivatorFactory>();
                var proxyFactory     = s.GetRequiredService <IActorProxyFactory>();
                return(new ActorRuntime(options, loggerFactory, activatorFactory, proxyFactory));
            });

            services.TryAddSingleton <IActorProxyFactory>(s =>
            {
                var options = s.GetRequiredService <IOptions <ActorRuntimeOptions> >().Value;
                var factory = new ActorProxyFactory()
                {
                    DefaultOptions =
                    {
                        JsonSerializerOptions = options.JsonSerializerOptions,
                        DaprApiToken          = options.DaprApiToken,
                        HttpEndpoint          = options.HttpEndpoint,
                    }
                };

                return(factory);
            });

            if (configure != null)
            {
                services.Configure <ActorRuntimeOptions>(configure);
            }
        }
Beispiel #22
0
        public async Task CreateProxyWithNoRemoting_WithNoApiToken()
        {
            await using var client = TestClient.CreateForMessageHandler();

            var actorId = new ActorId("abc");

            var request = await client.CaptureHttpRequestAsync(async handler =>
            {
                var factory = new ActorProxyFactory(null, handler);
                var proxy   = factory.Create(actorId, "TestActor");
                await proxy.InvokeMethodAsync("SetCountAsync", 1, new CancellationToken());
            });

            request.Dismiss();

            Assert.Throws <InvalidOperationException>(() =>
            {
                request.Request.Headers.GetValues("dapr-api-token");
            });
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            ActorId actorId = ActorId.CreateRandom();

            var proxyFactory = new ActorProxyFactory((c) =>
            {
                return(new FabricTransportActorRemotingClientFactory(
                           fabricTransportRemotingSettings: null,
                           callbackMessageHandler: c,
                           serializationProvider: new ServiceRemotingJsonSerializationProvider()));
            });

            var proxy = proxyFactory.CreateActorProxy <IActor1>(actorId, "fabric:/Application7");
            var msg   = new BaseType();

            msg.j = 15;
            proxy.SetMessageAsync(msg, CancellationToken.None).GetAwaiter().GetResult();
            var res = proxy.GetMessageAsync(CancellationToken.None).GetAwaiter().GetResult();

            Console.WriteLine(res.j);
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            var proxyFactory = new ActorProxyFactory((c) => new FabricTransportActorRemotingClientFactory(
                                                         fabricTransportRemotingSettings: null,
                                                         serializationProvider: new CustomDataContractProvider()));

            for (int i = 0; i < 200; i++)
            {
                var actorId = new ActorId(Guid.NewGuid());
                var data    = new MyData()
                {
                    Data = "TestData"
                };
                var proxy = proxyFactory.CreateActorProxy <IMyActor>(actorId, "fabric:/ActorCustomDataContractSerialization");
                proxy.SetDataAsync(data, CancellationToken.None).GetAwaiter().GetResult();
                var result = proxy.GetDataAsync(CancellationToken.None).GetAwaiter().GetResult();
            }

            // Query
            QueryAtors();
        }
Beispiel #25
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                foreach (var name in ObjectMother.Names)
                {
                    var correlationId = Guid.NewGuid().ToString();
                    using (new ServiceRequestContextWrapperX(correlationId, Environment.UserName))
                    {
                        var serviceLogger       = _serviceLoggerFactory();
                        var communicationLogger = _communicationLoggerFactory();
                        using (serviceLogger.RunAsyncLoop())
                        {
                            try
                            {
                                var serviceProxyFactory = new FG.ServiceFabric.Services.Remoting.Runtime.Client.ServiceProxyFactory(communicationLogger);
                                var serviceProxy        = serviceProxyFactory.CreateServiceProxy <ITitleService>(
                                    new Uri($"{this.Context.CodePackageActivationContext.ApplicationName}/TitleService"),
                                    new ServicePartitionKey(0));
                                var titles = await serviceProxy.GetTitlesAsync(cancellationToken);

                                var title = titles[Environment.TickCount % titles.Length];

                                var actorProxyFactory = new ActorProxyFactory(communicationLogger);
                                var proxy             = actorProxyFactory.CreateActorProxy <IPersonActor>(new ActorId(name));
                                await proxy.SetTitleAsync(title, cancellationToken);

                                serviceLogger.PersonGenerated(name, title);
                            }
                            catch (Exception ex)
                            {
                                serviceLogger.RunAsyncLoopFailed(ex);
                            }
                        }
                    }

                    await Task.Delay(10000, cancellationToken);
                }
            }
        }
Beispiel #26
0
        public async Task CreateProxyWithNoRemoting_WithApiToken()
        {
            await using var client = TestClient.CreateForMessageHandler();

            var actorId = new ActorId("abc");
            var options = new ActorProxyOptions
            {
                DaprApiToken = "test_token",
            };

            var request = await client.CaptureHttpRequestAsync(async handler =>
            {
                var factory = new ActorProxyFactory(options, handler);
                var proxy   = factory.Create(actorId, "TestActor");
                await proxy.InvokeMethodAsync("SetCountAsync", 1, new CancellationToken());
            });

            request.Dismiss();

            var headerValues = request.Request.Headers.GetValues("dapr-api-token");

            headerValues.Should().Contain("test_token");
        }
Beispiel #27
0
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var proxyFactory  = new ServiceProxyFactory(c => new FabricTransportServiceRemotingClientFactory());
            var proxyFactory2 = new ServiceProxyFactory(c => new CorrelatingFabricTransportServiceRemotingClientFactory <ISampleService>());
            var proxyFactory3 = new ActorProxyFactory();

            //ISampleService service = proxyFactory2.CreateServiceProxy<ISampleService>(
            //   new Uri("fabric:/LogMagic.FabricTestApp2/LogMagic.FabricTestApp.StatelessSimulator"));

            ISampleService service = CorrelatingProxyFactory.CreateServiceProxy <ISampleService>(
                new Uri("fabric:/LogMagic.FabricTestApp2/LogMagic.FabricTestApp.StatelessSimulator"),
                raiseSummary: RaiseSummary,
                remoteServiceName: "StatelessSimulator");

            IActorSimulator actor = CorrelatingProxyFactory.CreateActorProxy <IActorSimulator>(ActorId.CreateRandom());

            //actor = proxyFactory3.CreateActorProxy<IActorSimulator>(ActorId.CreateRandom());

            using (L.Context("param1", "value1"))
            {
                try
                {
                    string hey = await service.PingSuccessAsync("hey");

                    await actor.SetCountAsync(5, cancellationToken);

                    int count = await actor.GetCountAsync(cancellationToken);

                    hey = await service.PingFailureAsync("fail");
                }
                catch (Exception ex)
                {
                    ex = null;
                }
            }
        }
Beispiel #28
0
 public StudentsController()
 {
     _actorProxyFactory   = new ActorProxyFactory();
     _serviceProxyFactory = new ServiceProxyFactory();
     _actorServiceUri     = new Uri($@"{FabricRuntime.GetActivationContext().ApplicationName}/{"StudentActorService"}");
 }