Example #1
0
        public async Task <Profile> Profile(string name)
        {
            var profileGrain = _clusterClient
                               .GetGrain <IProfileGrain>(name);
            var cancellationTokenSource = new GrainCancellationTokenSource();

            return(await profileGrain.GetProfile(cancellationTokenSource.Token));
        }
        public async Task PreCancelledTokenPassing()
        {
            var grain = this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
            var tcs   = new GrainCancellationTokenSource();
            await tcs.Cancel();

            var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10));
            await Assert.ThrowsAsync <TaskCanceledException>(() => grainTask);
        }
Example #3
0
        public async Task <bool> CallOtherCancellationTokenCallbackResolve(ILongRunningTaskGrain <T> target)
        {
            var tc        = new GrainCancellationTokenSource();
            var grainTask = target.CancellationTokenCallbackResolve(tc.Token);
            await Task.Delay(300);

            await tc.Cancel();

            return(await grainTask);
        }
Example #4
0
        public Task SendAddressedMessageAsync(AddressedMessage msg, CancellationToken cancellationToken = default)
        {
            var token = new GrainCancellationTokenSource();

            if (cancellationToken != default)
            {
                cancellationToken.Register(() => token.Cancel());
            }
            return(grainFactory.GetGrain <IClientGrain>($"{hubName}::{msg.ConnectionId}").AcceptMessageAsync(msg.Payload, token.Token));
        }
Example #5
0
        public async Task <int> Index()
        {
            var wikiFetchGrain = _clusterClient
                                 .GetGrain <IWikiFetcherGrain>("AnatolyKulakov/SpbDotNet.wiki.git");
            var cancellationTokenSource = new GrainCancellationTokenSource();

            await wikiFetchGrain.StartFetchWikiJob(cancellationTokenSource.Token);

            return(1);
        }
Example #6
0
        public async Task CallOtherLongRunningTaskWithLocalToken(ILongRunningTaskGrain <T> target, TimeSpan delay, TimeSpan delayBeforeCancel)
        {
            var tcs  = new GrainCancellationTokenSource();
            var task = target.LongWait(tcs.Token, delay);
            await Task.Delay(delayBeforeCancel);

            await tcs.Cancel();

            await task;
        }
Example #7
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Starting Benoit Client...");
            var client = await StartClient();

            var options = new RenderingOptions()
                          .WithFrameWidth(700)
                          .WithFrameHeight(400)
                          .WithMaxIteration(10000)
                          .WithBailoutValue(1 << 8)
                          .WithBatchSize(4000);

            PrintOptions(options);

            // Frame options
            var center = new Complex(-0.743643887037158d, 0.131825904205311d);
            var scale  = 0.01d;

            // Zoom options
            var frames          = 400;
            var scaleMultiplier = 0.90d; // < 1 will magnify, > 1 will zoom out.

            var observer = new RenderObserver();

            observer.OnReceivedRenderedMovie += (guid, movie) =>
            {
                SaveMovie($"{guid.ToString()}.gif", options, movie.Value);
            };

            observer.OnReceivedRenderedFrame += (guid, frame) =>
            {
                SaveFrame($"{guid.ToString()}.png", options, frame.Value);
            };

            var cTokenSource = new GrainCancellationTokenSource();
            var cToken       = cTokenSource.Token;

            var dispatcher = client.GetGrain <IRenderingDispatcher <int> >(Guid.NewGuid());
            await dispatcher.SetOptions(options);

            var observerRef = await client.CreateObjectReference <IRenderObserver <int> >(observer);

            await dispatcher.Subscribe(observerRef);

            await dispatcher.BeginRenderMovie(Guid.NewGuid(), center, scale, scaleMultiplier, frames, cToken);

            //await dispatcher.BeginRenderFrame(Guid.NewGuid(), center, scale, cToken);

            Console.WriteLine("Awaiting response from the server... (Enter to cancel)");
            Console.ReadLine();

            await cTokenSource.Cancel();

            await client.Close();
        }
        public async Task GrainTaskCancellation(int delay)
        {
            var grain     = GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
            var tcs       = new GrainCancellationTokenSource();
            var grainTask = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10));
            await Task.Delay(TimeSpan.FromMilliseconds(delay));

            await tcs.Cancel();

            await Assert.ThrowsAsync <TaskCanceledException>(() => grainTask);
        }
Example #9
0
        private static async Task Run1()
        {
            var tcs       = new GrainCancellationTokenSource();
            var testGrain = _client.GetGrain <ICancellationTokensGrain>(1);

            await Task.WhenAny(
                testGrain.LongIoWork(tcs.Token, TimeSpan.FromSeconds(5)),
                Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith(t => tcs.Cancel())
                );

            tcs.Dispose();
        }
Example #10
0
        public Task RemoveFromGroupAsync(string connectionId, CancellationToken cancellationToken = default)
        {
            connectionId = $"{hubName}::{connectionId}";
            var token = new GrainCancellationTokenSource();

            if (cancellationToken != default)
            {
                cancellationToken.Register(() => token.Cancel());
            }

            return(groupActorGrain.RemoveFromGroupAsync(connectionId, token.Token));
        }
Example #11
0
        public Task AcceptMessageAsync(AnonymousMessage message, CancellationToken cancellationToken = default)
        {
            message = new AnonymousMessage(message.Excluding.Select(x => $"{hubName}::{x}").ToSet(), message.Payload);
            var token = new GrainCancellationTokenSource();

            if (cancellationToken != default)
            {
                cancellationToken.Register(() => token.Cancel());
            }

            return(groupActorGrain.AcceptMessageAsync(message, token.Token));
        }
        public async Task CancellationTokenCallbacksTaskSchedulerContext()
        {
            var grains = await GetGrains <bool>(false);

            var tcs       = new GrainCancellationTokenSource();
            var grainTask = grains.Item1.CallOtherCancellationTokenCallbackResolve(grains.Item2);
            await tcs.Cancel();

            var result = await grainTask;

            Assert.True(result);
        }
Example #13
0
        public async Task Callchain_Reentrancy_InterleavingSecondCall_Enabled()
        {
            var grain  = fixture.GrainFactory.GetGrain <INonReentrantGrain>(0);
            var target = fixture.GrainFactory.GetGrain <INonReentrantGrain>(1);
            var gcts   = new GrainCancellationTokenSource();

            grain.DoAsyncWork(TimeSpan.FromHours(1), gcts.Token).Ignore();
            var i          = 1;
            var pingResult = await grain.PingSelfThroughOtherInterleaving(target, i);

            Assert.Equal(i, pingResult);
            await gcts.Cancel();
        }
        public async Task MultipleGrainsTaskCancellation(int delay)
        {
            var tcs        = new GrainCancellationTokenSource();
            var grainTasks = Enumerable.Range(0, 5)
                             .Select(i => this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid())
                                     .LongWait(tcs.Token, TimeSpan.FromSeconds(10)))
                             .Select(task => Assert.ThrowsAsync <TaskCanceledException>(() => task)).ToList();
            await Task.Delay(TimeSpan.FromMilliseconds(delay));

            await tcs.Cancel();

            await Task.WhenAll(grainTasks);
        }
        public async Task CancellationTokenCallbacksExecutionContext()
        {
            var grain     = this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
            var tcs       = new GrainCancellationTokenSource();
            var grainTask = grain.CancellationTokenCallbackResolve(tcs.Token);
            await Task.Delay(TimeSpan.FromMilliseconds(100));

            await tcs.Cancel();

            var result = await grainTask;

            Assert.True(result);
        }
        public async Task TokenPassingWithoutCancellation_NoExceptionShouldBeThrown()
        {
            var grain = this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
            var tcs   = new GrainCancellationTokenSource();

            try
            {
                await grain.LongWait(tcs.Token, TimeSpan.FromMilliseconds(1));
            }
            catch (Exception ex)
            {
                Assert.True(false, "Expected no exception, but got: " + ex.Message);
            }
        }
        public async Task InjectedDependencyCanBeVerified()
        {
            //This creates a mock and injects it into the tested grain.
            var featureManagementService = Silo.AddServiceProbe <IFeatureManagerSnapshot>();

            featureManagementService.Setup(x => x.IsEnabledAsync("FeatureA"))
            .ReturnsAsync(true);
            var token = new GrainCancellationTokenSource().Token;
            var sut   = await Silo.CreateGrainAsync <HelloWorld>(1);

            await sut.SayHello("Mike", token);

            featureManagementService.Verify(x => x.IsEnabledAsync("FeatureA"), Times.Once);
        }
        private async Task ClientGrainGrainTokenPassing(int delay, bool interSilo)
        {
            var grains = await GetGrains <bool>(interSilo);

            var grain     = grains.Item1;
            var target    = grains.Item2;
            var tcs       = new GrainCancellationTokenSource();
            var grainTask = grain.CallOtherLongRunningTask(target, tcs.Token, TimeSpan.FromSeconds(10));
            await Task.Delay(TimeSpan.FromMilliseconds(delay));

            await tcs.Cancel();

            await Assert.ThrowsAsync <TaskCanceledException>(() => grainTask);
        }
Example #19
0
        public Task SendAllMessageAsync(AnonymousMessage allMessage, CancellationToken cancellationToken = default)
        {
            var token = new GrainCancellationTokenSource();

            if (cancellationToken != default)
            {
                cancellationToken.Register(() => token.Cancel());
            }
            var hubNamespacesAllMessage = new AnonymousMessage(
                allMessage.Excluding.Select(id => $"{hubName}::{id}").ToSet(),
                allMessage.Payload
                );

            return(grainFactory.GetGrain <IAnonymousMessageGrain>(hubName).AcceptMessageAsync(allMessage, token.Token));
        }
Example #20
0
        public async Task <string> Get(string name, CancellationToken cancellationToken)
        {
            string result = null;

            if (!cancellationToken.IsCancellationRequested)
            {
                var grainCancellationTokenSource = new GrainCancellationTokenSource();

                //A random integer is generated to allow for a new hello world grain to be created per client creation.
                return(await _clusterClient.GetGrain <IHelloWorld>(_generator.Next(int.MaxValue))
                       .SayHello(name, grainCancellationTokenSource.Token));
            }

            return(result);
        }
Example #21
0
        public async Task Execute(CancellationToken cancellationToken)
        {
            var tcs = new GrainCancellationTokenSource();

            cancellationToken.Register(() => tcs.Cancel());

            var dataProjectionGrain = _grainFactory.GetGrain <IDataProjectionDispatchingGrain>(Guid.NewGuid().ToString());
            await dataProjectionGrain.StartExecutingAsync(tcs.Token);

            var flowKaleidoscopeConsumerGrain = _grainFactory.GetGrain <IFlowKaleidoscopeConsumerGrain>(Guid.NewGuid().ToString());
            await flowKaleidoscopeConsumerGrain.StartExecutingAsync(tcs.Token);

            var flowGeoClassifierConsumerGrain = _grainFactory.GetGrain <IFlowGeoClassifierConsumerGrain>(Guid.NewGuid().ToString());
            await flowGeoClassifierConsumerGrain.StartExecutingAsync(tcs.Token);

            var flowCardForErmConsumerGrain = _grainFactory.GetGrain <IFlowCardForErmConsumerGrain>(Guid.NewGuid().ToString());
            await flowCardForErmConsumerGrain.StartExecutingAsync(tcs.Token);
        }
        public async Task <IActionResult> Get(string name, CancellationToken cancellationToken)
        {
            IActionResult result = null;

            if (!cancellationToken.IsCancellationRequested)
            {
                var grainCancellationTokenSource = new GrainCancellationTokenSource();
                //A random integer (1 - 50) is generated to allow for a new hello world grain to be created or reused per client.
                var response = await _clusterClient.GetGrain <IHelloWorld>(_generator.Next(1, 51))
                               .SayHello(name, grainCancellationTokenSource.Token);

                result = string.IsNullOrEmpty(response)
                    ? NoContent()
                    : Ok(response);
            }

            return(result);
        }
Example #23
0
        public async Task CancellationTokenCallbacksThrow_ExceptionShouldBePropagated()
        {
            var grain     = this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
            var tcs       = new GrainCancellationTokenSource();
            var grainTask = grain.CancellationTokenCallbackThrow(tcs.Token);
            await Task.Delay(TimeSpan.FromMilliseconds(100));

            try
            {
                await tcs.Cancel();
            }
            catch (AggregateException ex)
            {
                Assert.True(ex.InnerException is InvalidOperationException, "Exception thrown has wrong type");
                return;
            }

            Assert.True(false, "No exception was thrown");
        }
 public async Task GrainTaskMultipleCancellations(int delay)
 {
     var grain      = this.fixture.GrainFactory.GetGrain <ILongRunningTaskGrain <bool> >(Guid.NewGuid());
     var grainTasks = Enumerable.Range(0, 5)
                      .Select(async i =>
     {
         var tcs  = new GrainCancellationTokenSource();
         var task = grain.LongWait(tcs.Token, TimeSpan.FromSeconds(10));
         await Task.WhenAny(task, Task.Delay(TimeSpan.FromMilliseconds(delay)));
         await tcs.Cancel();
         try
         {
             await task;
             Assert.True(false, "Expected TaskCancelledException, but message completed");
         }
         catch (TaskCanceledException) { }
     })
                      .ToList();
     await Task.WhenAll(grainTasks);
 }
        public async Task Should_fail_with_task_canceled()
        {
            // Arrange
            var grain = _fixture.Cluster !.Client.GetGrain <IBackgroundWorkload <int, string> >(nameof(Should_fail_with_task_canceled));

            // Act
            var cancellationTokenSource = new GrainCancellationTokenSource();
            var startResult             = await grain.StartAsync(10, cancellationTokenSource.Token);

            await Task.Delay(1000);

            await cancellationTokenSource.Cancel();

            var result = await WaitForResultAsync(grain);

            // Assert
            startResult.Should().BeTrue();
            result.Should().BeOfType <Failed>()
            .Which.Exception.Should().BeOfType <TaskCanceledException>();
        }
Example #26
0
        private static void Main(string[] args)
        {
            var env           = Environment.GetEnvironmentVariable("ROADS_ENVIRONMENT") ?? "Production";
            var basePath      = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(basePath)
                                .AddJsonFile("appsettings.json")
                                .AddJsonFile($"appsettings.{env.ToLower()}.json")
                                .AddEnvironmentVariables("ROADS_")
                                .Build();

            var serilogLogger = CreateLogger(configuration);

            var serviceProvider = new ServiceCollection()
                                  .AddLogging(x => x.AddSerilog(serilogLogger, true))
                                  .BuildServiceProvider();

            var logger = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <Program>();

            var cts = new GrainCancellationTokenSource();

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                logger.LogInformation("Application is shutting down...");
                cts.Cancel();
                serviceProvider.Dispose();

                eventArgs.Cancel = true;
            };

            var app = new CommandLineApplication {
                Name = "Broadway.Worker"
            };

            app.HelpOption(CommandLine.HelpOptionTemplate);
            app.OnExecute(
                () =>
            {
                Console.WriteLine("Broadway worker host.");
                app.ShowHelp();

                return(0);
            });

            var clusterClient = CreateClusterClient(env, basePath, logger, serilogLogger);

            app.Command(
                CommandLine.Commands.Import,
                config =>
            {
                config.Description = "Run import worker. See available arguments for details.";
                config.HelpOption(CommandLine.HelpOptionTemplate);
                config.Command(
                    CommandLine.CommandTypes.FlowCardsForERM,
                    commandConfig =>
                {
                    commandConfig.Description = "Import objects from flowCardsForERM.";
                    commandConfig.HelpOption(CommandLine.HelpOptionTemplate);
                    commandConfig.OnExecute(() => Run(commandConfig, logger, clusterClient, cts));
                });

                config.Command(
                    CommandLine.CommandTypes.FlowKaleidoscope,
                    commandConfig =>
                {
                    commandConfig.Description = "Import objects from flowKaleidoscope.";
                    commandConfig.HelpOption(CommandLine.HelpOptionTemplate);
                    commandConfig.OnExecute(() => Run(commandConfig, logger, clusterClient, cts));
                });

                config.Command(
                    CommandLine.CommandTypes.FlowGeoClassifier,
                    commandConfig =>
                {
                    commandConfig.Description = "Import objects from flowGeoClassifier.";
                    commandConfig.HelpOption(CommandLine.HelpOptionTemplate);
                    commandConfig.OnExecute(() => Run(commandConfig, logger, clusterClient, cts));
                });

                config.OnExecute(
                    () =>
                {
                    config.ShowHelp();

                    return(0);
                });
            });

            var exitCode = 0;

            try
            {
                logger.LogInformation("Broadway Worker started with options: {workerOptions}.", args.Length != 0 ? string.Join(" ", args) : "N/A");
                exitCode = app.Execute(args);
            }
            catch (CommandParsingException ex)
            {
                ex.Command.ShowHelp();
                exitCode = 1;
            }
            catch (WorkerGrainNotFoundExeption)
            {
                exitCode = 2;
            }
            catch (Exception ex)
            {
                logger.LogCritical(default, ex, "Unexpected error occured. See logs for details.");