Example #1
0
        /// <summary>
        /// Initializes any custom actor logs.
        /// </summary>
        private void InitializeCustomActorLogging(IActorRuntime runtime)
        {
            if (this.Configuration.IsTraceVisualizationEnabled)
            {
                // Registers an activity coverage graph builder.
                runtime.RegisterLog(new ActorRuntimeLogGraphBuilder(false, false));
            }

            if (this.Configuration.IsActivityCoverageReported)
            {
                // Registers an activity coverage graph builder that collapses instances.
                runtime.RegisterLog(new ActorRuntimeLogGraphBuilder(false, true));

                // Need this additional logger to get the event coverage report correct
                runtime.RegisterLog(new ActorRuntimeLogEventCoverage());
            }

            if (this.Configuration.IsXmlLogEnabled)
            {
                this.XmlLog = new StringBuilder();
                runtime.RegisterLog(new ActorRuntimeLogXmlFormatter(XmlWriter.Create(this.XmlLog,
                                                                                     new XmlWriterSettings()
                {
                    Indent = true, IndentChars = "  ", OmitXmlDeclaration = true
                })));
            }
        }
        public ActorTaskCompletionSource(IActorRuntime r, ITypedActorRuntime typedRuntime)
        {
            runtime = r;

            Task = runtime.StartNew(() =>
            {
                TaskCompletionSourceHelper.Msg res =
                    (TaskCompletionSourceHelper.Msg)
                    runtime.CurrentMailbox().Receive();

                if (res.state == TaskStatus.Canceled)
                {
                    runtime.CancelSelf();
                }

                if (res.state == TaskStatus.Faulted)
                {
                    throw res.exception;
                }

                return((T)res.result);
            });

            source =
                typedRuntime.Create <ITaskCompletionSource>(
                    new TaskCompletionSourceHelper(runtime, runtime.MailboxFromTask(Task), Task));
        }
Example #3
0
        public async Task TestCustomActorRuntimeLogFormatter()
        {
            Configuration config = Configuration.Create().WithVerbosityEnabled();

            config.IsMonitoringEnabledInInProduction = true;

            IActorRuntime runtime = RuntimeFactory.Create(config);

            runtime.RegisterMonitor <S>();
            runtime.SetLogger(null);
            var logger = new CustomActorRuntimeLog();

            runtime.RegisterLog(logger);

            var tcs = new TaskCompletionSource <bool>();

            runtime.CreateActor(typeof(M), new SetupEvent(tcs));

            await WaitAsync(tcs.Task);

            await Task.Delay(200);

            string expected = @"CreateActor
StateTransition
CreateActor
StateTransition
StateTransition
StateTransition
";

            string actual = RemoveNonDeterministicValuesFromReport(logger.ToString());

            Assert.Equal(expected, actual);
        }
Example #4
0
        private async Task RunServer(IActorRuntime runtime, ActorId clusterManager, string subscriptionName)
        {
            if (this.Debug)
            {
                Console.WriteLine("Attach debugger");
                await Task.Delay(60000);
            }

            CancellationTokenSource cancelSource = new CancellationTokenSource();

            if (this.ClientProcessId == 0)
            {
                throw new Exception("Server should have a client process id");
            }

            MonitorClientProcess(this.ClientProcessId);

            // We create a server host that will create and wrap a Raft server instance (implemented
            // as a Coyote state machine), and execute it using the Coyote runtime.
            var host = new AzureServer(runtime, this.ConnectionString, this.TopicName, this.ServerId, this.ClusterSize, clusterManager);

            this.LocalId = host.HostedServer;
            host.Initialize();
            host.Start();

            var receiver = new AzureMessageReceiver(runtime, this.ConnectionString, this.TopicName, this.LocalId, subscriptionName);
            await receiver.RunAsync(cancelSource.Token);
        }
Example #5
0
        private async Task RunClient(IActorRuntime runtime, ActorId clusterManager, string subscriptionName)
        {
            CancellationTokenSource cancelSource = new CancellationTokenSource();

            StartRaftServers(this.ConnectionString, this.TopicName, this.ClusterSize);

            var receiver = new AzureMessageReceiver(runtime, this.ConnectionString, this.TopicName, this.LocalId, subscriptionName);
            var nowait   = receiver.RunAsync(cancelSource.Token);

            receiver.ResponseReceived += (s, e) =>
            {
                this.completed.SetResult(e);
            };

            // Now send the requested number of ClientRequestEvents to the cluster, and wait for each response.
            for (int i = 0; i < this.NumRequests; i++)
            {
                string command = $"request-{i}";
                Console.WriteLine($"<Client> sending {command}.");
                this.completed = new TaskCompletionSource <ClientResponseEvent>();
                runtime.SendEvent(clusterManager, new ClientRequestEvent(command));
                var response = await this.completed.Task;
                Console.WriteLine($"<Client> received response for {response.Command} from  {response.Server}.");
            }
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ActorId"/> class.
        /// </summary>
        internal ActorId(Type type, string name, ActorRuntime runtime, bool useNameForHashing = false)
        {
            this.Runtime  = runtime;
            this.Endpoint = string.Empty;

            if (useNameForHashing)
            {
                this.Value     = 0;
                this.NameValue = name;
                this.Runtime.Assert(!string.IsNullOrEmpty(this.NameValue), "The actor name cannot be null when used as id.");
            }
            else
            {
                this.Value     = runtime.GetNextOperationId();
                this.NameValue = string.Empty;

                // Checks for overflow.
                this.Runtime.Assert(this.Value != ulong.MaxValue, "Detected actor id overflow.");
            }

            this.Generation = runtime.Configuration.RuntimeGeneration;

            this.Type = type.FullName;
            if (this.IsNameUsedForHashing)
            {
                this.Name = this.NameValue;
            }
            else
            {
                this.Name = string.Format(CultureInfo.InvariantCulture, "{0}({1})",
                                          string.IsNullOrEmpty(name) ? this.Type : name, this.Value.ToString());
            }
        }
Example #7
0
            public static void RunTest(IActorRuntime runtime, LogEvent initEvent)
            {
                var actor = runtime.CreateActor(typeof(M8), initEvent);

                runtime.SendEvent(actor, new E1()); // should be handled by Init state, and trigger push to Ready
                runtime.SendEvent(actor, new E1()); // should pop Active and go back to Init where it will be handled.
            }
Example #8
0
 internal virtual void Initialize(IActorHost host, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher)
 {
     Path       = path;
     Runtime    = runtime;
     Dispatcher = Dispatcher ?? dispatcher;
     Host       = host;
 }
Example #9
0
        public async Task TestGraphLoggerCollapsed()
        {
            CustomLogger  logger = new CustomLogger();
            Configuration config = Configuration.Create().WithVerbosityEnabled();

            var graphBuilder = new ActorRuntimeLogGraphBuilder(false);

            graphBuilder.CollapseMachineInstances = true;

            var           tcs     = TaskCompletionSource.Create <bool>();
            IActorRuntime runtime = CreateTestRuntime(config, tcs, logger);

            runtime.RegisterLog(graphBuilder);

            ActorId serverId = runtime.CreateActor(typeof(Server));

            runtime.CreateActor(typeof(Client), new ClientSetupEvent(serverId));
            runtime.CreateActor(typeof(Client), new ClientSetupEvent(serverId));
            runtime.CreateActor(typeof(Client), new ClientSetupEvent(serverId));

            await WaitAsync(tcs.Task, 5000000);

            await Task.Delay(1000);

            string actual = graphBuilder.Graph.ToString();

            Assert.Contains("<Node Id='Microsoft.Coyote.Production.Tests.Actors.CustomActorRuntimeLogTests+Client.Client' Label='Client'/>", actual);
            Assert.Contains("<Node Id='Microsoft.Coyote.Production.Tests.Actors.CustomActorRuntimeLogTests+Server.Complete' Label='Complete'/>", actual);

            logger.Dispose();
        }
Example #10
0
            public static void RunTest(IActorRuntime r, LogEvent config)
            {
                var actor = r.CreateActor(typeof(W), config);

                r.SendEvent(actor, new E1());
                r.SendEvent(actor, new E2());
            }
Example #11
0
        /// <summary>
        /// Provided only for unit-testing purposes
        /// </summary>
        protected ActorGrain(string id = null, IActorRuntime runtime = null)
        {
            var @interface = ActorGrainImplementation.InterfaceOf(GetType());

            Path    = ActorPath.For(@interface, id ?? Guid.NewGuid().ToString("N"));
            Runtime = runtime;
        }
Example #12
0
        internal override void Initialize(IActorHost host, ActorPath path, IActorRuntime runtime, Dispatcher dispatcher)
        {
            base.Initialize(host, path, runtime, dispatcher);
            var endpoint = (StatefulActorEndpoint <TState>)host;

            storage = new StorageService <TState>(endpoint);
        }
Example #13
0
            internal static void RunTest(IActorRuntime runtime, LogEvent config)
            {
                var actor = runtime.CreateActor(typeof(X3), config);

                runtime.SendEvent(actor, new E1()); // deferred
                runtime.SendEvent(actor, new E2()); // push state Active, and allow handling of deferred event.
            }
Example #14
0
        public async Task TestCustomActorRuntimeLogFormatter()
        {
            Configuration config  = Configuration.Create().WithVerbosityEnabled();
            var           tcs     = TaskCompletionSource.Create <bool>();
            IActorRuntime runtime = CreateTestRuntime(config, tcs);

            runtime.RegisterMonitor <S>();
            runtime.SetLogger(null);

            var logger = new CustomActorRuntimeLog();

            runtime.RegisterLog(logger);

            runtime.CreateActor(typeof(M));

            await WaitAsync(tcs.Task, 5000);

            await Task.Delay(200);

            string expected = @"CreateActor
CreateStateMachine
StateTransition
StateTransition
StateTransition
";

            string actual = RemoveNonDeterministicValuesFromReport(logger.ToString());

            Assert.Equal(expected, actual);
        }
Example #15
0
        internal Actor Activate(IActorHost host, ActorPath path, IActorRuntime runtime)
        {
            var instance = Activator.Activate(actor, path.Id, runtime, dispatcher);

            instance.Initialize(host, path, runtime, dispatcher);
            return(instance);
        }
 public void IterationSetup()
 {
     if (this.Runtime == null)
     {
         var configuration = Configuration.Create();
         this.Runtime = RuntimeFactory.Create(configuration);
     }
 }
Example #17
0
        protected Actor(string id, IActorRuntime runtime)
        {
            Requires.NotNull(runtime, nameof(runtime));
            Requires.NotNullOrWhitespace(id, nameof(id));

            Id      = id;
            Runtime = runtime;
        }
Example #18
0
            internal static void RunTest(IActorRuntime runtime)
            {
                var a = runtime.CreateActor(typeof(M5a));

                runtime.SendEvent(a, new E2()); // Push(S1)
                runtime.SendEvent(a, new E1()); // Execute foo without popping
                runtime.SendEvent(a, new E3()); // Can handle it because A is still in S1
            }
Example #19
0
        /// <summary>
        /// Provided only for unit-testing purposes
        /// </summary>
        protected ActorGrain(string id = null, IActorRuntime runtime = null)
        {
            var @interface = InterfaceOf(GetType());

            Path         = ActorPath.For(@interface, id ?? Guid.NewGuid().ToString("N"));
            System       = runtime?.System;
            this.runtime = runtime;
        }
Example #20
0
            public static void RunTest(IActorRuntime r, LogEvent config)
            {
                var a = r.CreateActor(typeof(Aa), config);

                r.SendEvent(a, new E2());
                r.SendEvent(a, UnitEvent.Instance);
                r.SendEvent(a, new E1());
            }
Example #21
0
 public static void Execute(IActorRuntime runtime)
 {
     // Monitors must be registered before the first Coyote machine
     // gets created (which will kickstart the runtime).
     runtime.RegisterMonitor <Safety>();
     runtime.RegisterMonitor <Liveness>();
     runtime.CreateActor(typeof(Driver), new Driver.Config(2));
 }
Example #22
0
        protected Actor(string id, IActorRuntime runtime)
        {
            Requires.NotNull(runtime, "runtime");
            Requires.NotNullOrWhitespace(id, "id");

            Id      = id;
            Runtime = runtime;
        }
Example #23
0
            internal static void RunTest(IActorRuntime runtime, LogEvent config)
            {
                var actor = runtime.CreateActor(typeof(X3), config);

                runtime.SendEvent(actor, new E1()); // ignored (and therefore dropped)
                runtime.SendEvent(actor, new E2()); // push state Active.
                runtime.SendEvent(actor, new E1()); // Catch by wildcard (overriding inherited IgnoreEvents)
            }
Example #24
0
            internal static void RunTest(IActorRuntime runtime, LogEvent config)
            {
                var actor = runtime.CreateActor(typeof(X2), config);

                runtime.SendEvent(actor, new E1()); // handle E1 & push active
                runtime.SendEvent(actor, new E1()); // catch E1, by wildcard
                runtime.SendEvent(actor, new E2()); // handle E2, specific handler wins
            }
 public TaskCompletionSourceHelper(
     IActorRuntime runtime,
     IMailbox<object> taskMailbox,
     Task task)
 {
     this.runtime = runtime;
     this.taskMailbox = taskMailbox;
     this.task = task;
 }
Example #26
0
        /// <summary>
        /// Creates a new shared dictionary.
        /// </summary>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="runtime">The actor runtime.</param>
        public static SharedDictionary <TKey, TValue> Create <TKey, TValue>(IActorRuntime runtime)
        {
            if (runtime is ActorExecutionContext.Mock executionContext)
            {
                return(new Mock <TKey, TValue>(executionContext, null));
            }

            return(new SharedDictionary <TKey, TValue>(new ConcurrentDictionary <TKey, TValue>()));
        }
Example #27
0
        /// <summary>
        /// Creates a new shared counter.
        /// </summary>
        /// <param name="runtime">The actor runtime.</param>
        /// <param name="value">The initial value.</param>
        public static SharedCounter Create(IActorRuntime runtime, int value = 0)
        {
            if (runtime is ActorExecutionContext.Mock executionContext)
            {
                return(new Mock(value, executionContext));
            }

            return(new SharedCounter(value));
        }
Example #28
0
        public static void Main()
        {
            RunForever = true;
            IActorRuntime runtime = RuntimeFactory.Create(); // Configuration.Create().WithVerbosityEnabled());

            Execute(runtime);
            Console.ReadLine();
            Console.WriteLine("User cancelled the test by pressing ENTER");
        }
Example #29
0
 public Api(
     IObserverCollection observers,
     IApiWorker worker,
     IActorRuntime runtime = null)
     : base(runtime)
 {
     this.observers = observers;
     this.worker    = worker;
 }
 public AzureMessageReceiver(IActorRuntime runtime, string connectionString, string topicName, ActorId actorId, string subscriptionName)
 {
     this.ActorRuntime         = runtime;
     this.LocalActorId         = actorId;
     this.LocalActorName       = (actorId == null) ? "Client" : actorId.Name;
     this.SubscriptionReceiver = new MessageReceiver(connectionString,
                                                     EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName),
                                                     ReceiveMode.ReceiveAndDelete);
 }
Example #31
0
            public static void RunTest(IActorRuntime runtime, LogEvent initEvent)
            {
                var actor = runtime.CreateActor(typeof(M7), initEvent);

                runtime.SendEvent(actor, new E1()); // should be handled by Init state, and trigger push to Ready
                runtime.SendEvent(actor, new E1()); // should be handled by Ready with OnEventPushState to Active
                runtime.SendEvent(actor, new E2()); // Now OnEventGotoState(E2) should not be inherited so this should pop us back to the Init state.
                runtime.SendEvent(actor, new E3()); // just to prove we are no longer in the Active state, this should raise an unhandled event error.
            }
Example #32
0
 public DIActor(string id, IActorRuntime runtime, ISomeService service) : base(id, runtime)
 {
     this.service = service;
 }
Example #33
0
 public HumanProxy(ActorId<IHuman> id, IActorRuntime runtime)
 {
     //            this.id = id;
     this.runtime = runtime;
 }
Example #34
0
 public Topic(string id, IActorRuntime runtime, ITopicStorage storage) : base(id, runtime)
 {
     this.storage = storage;
 }