示例#1
0
        public static void Main()
        {
            var runtime = RuntimeFactory.Create();
            var task    = Task.Run(() => TestBoundedBufferNoDeadlock(runtime));

            Task.WaitAll(task);
            Console.WriteLine("Test complete - no deadlocks!");
        }
示例#2
0
 protected virtual void Initialize(string methodName)
 {
     Runtime =
         RuntimeFactory.CreateRuntime()
         .InitializeWithConfigSetName(Utilities.GetConfigSetName());
     Runtime.SetEnvironment(Utilities.GetEnvironment());
     Tracer = Runtime.SetServiceName(this, ServiceName, methodName);
 }
 public void IterationSetup()
 {
     if (this.Runtime == null)
     {
         var configuration = Configuration.Create();
         this.Runtime = RuntimeFactory.Create(configuration);
     }
 }
        public async SystemTasks.Task TestAssertFailureNoEventHandler()
        {
            var runtime = RuntimeFactory.Create();
            var tcs     = TaskCompletionSource.Create <bool>();

            runtime.CreateActor(typeof(M), new SetupEvent(tcs));
            await tcs.Task;
        }
 private RequestHeader CreateRequestHeader(string operationName, RequestHeader requestHeader)
 {
     requestHeader.MethodName      = operationName;
     requestHeader.RuntimeInstance = RuntimeFactory.GetInstanceId().ToString();
     requestHeader.ServerIdentity  = Environment.MachineName;
     SetMessageValuesIfNotSetInClient(requestHeader, RuntimeFactory.Current);
     return(requestHeader);
 }
 public async Task CreateContextScopeContainer()
 {
     using (var scopeManager = RequestResponseScopefactory.CreateScope())
     {
         var runtime = RuntimeFactory.CreateRuntime();
         Assert.AreEqual(scopeManager.ContextId, runtime.InstanceId);
     }
 }
示例#7
0
 public void IterationSetup()
 {
     if (this.Runtime == null)
     {
         var configuration = Configuration.Create();
         this.Runtime = RuntimeFactory.Create(configuration);
         this.Master  = this.Runtime.CreateActor(typeof(M1), null, new SetupTcsEvent(NumMessages));
     }
 }
示例#8
0
        public static void Main()
        {
            RunForever = true;
            ICoyoteRuntime runtime = RuntimeFactory.Create();

            _ = Execute(runtime);
            Console.ReadLine();
            Console.WriteLine("User cancelled the test by pressing ENTER");
        }
示例#9
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");
        }
示例#10
0
 public ThumbprintItem GetChacedThumbprint(string issuerAddress)
 {
     using (var container = RuntimeFactory.CreateRuntime().CreateServiceProxy <IThumbprintCacheService>())
     {
         return(container.GetClient().GetThumbprint(new ThumbprintRequest {
             IsuerAddress = issuerAddress
         }).Thumbprint);
     }
 }
        public void MeasureLatencyExchangeEventViaReceive()
        {
            var tcs           = new TaskCompletionSource <bool>();
            var configuration = Configuration.Create();
            var runtime       = RuntimeFactory.Create(configuration);

            runtime.CreateActor(typeof(M3), null,
                                new SetupTcsEvent(tcs, this.NumMessages));
            tcs.Task.Wait();
        }
示例#12
0
        public void MeasurePushTransitionThroughput()
        {
            var configuration = Configuration.Create();
            var runtime       = RuntimeFactory.Create(configuration);
            var tcs           = new TaskCompletionSource <bool>();
            var e             = new SetupEvent(tcs, this.NumTransitions);

            runtime.CreateActor(typeof(M), null, e);
            tcs.Task.Wait();
        }
示例#13
0
        internal async Task RunAsync()
        {
            try
            {
                // We use the Topic/Subscription pattern which is a pub/sub model where each Server will send
                // messages to this Topic, and every other server has a Subscription to receive those messages.
                // If the Message has a "To" field then the server ignores the message as it was not meant for them.
                // Otherwise the Message is considered a "broadcast" to all servers and each server will handle it.
                // The client also has a subcription on the same topic and is how it broadcasts requests and receives
                // the final response from the elected Leader.
                var managementClient = new ManagementClient(this.ConnectionString);
                if (!await managementClient.TopicExistsAsync(this.TopicName))
                {
                    await managementClient.CreateTopicAsync(this.TopicName);
                }

                // then we need a subscription, whether we are client or server and the subscription name will be
                // the same as our local actorid.
                string subscriptionName = (this.ServerId < 0) ? "Client" : $"Server-{this.ServerId}";
                if (!await managementClient.SubscriptionExistsAsync(this.TopicName, subscriptionName))
                {
                    await managementClient.CreateSubscriptionAsync(
                        new SubscriptionDescription(this.TopicName, subscriptionName));
                }

                Console.WriteLine("Running " + subscriptionName);

                IActorRuntime runtime = RuntimeFactory.Create(Configuration.Create().WithVerbosityEnabled());

                // We create a new Coyote actor runtime instance, and pass an optional configuration
                // that increases the verbosity level to see the Coyote runtime log.
                runtime.OnFailure += RuntimeOnFailure;

                var topicClient = new TopicClient(this.ConnectionString, this.TopicName);

                // cluster manager needs the topic client in order to be able to broadcast messages using Azure Service Bus
                var clusterManager = runtime.CreateActor(typeof(AzureClusterManager), new AzureClusterManager.RegisterMessageBusEvent()
                {
                    TopicClient = topicClient
                });
                if (this.ServerId < 0)
                {
                    await this.RunClient(runtime, clusterManager, subscriptionName);
                }
                else
                {
                    await this.RunServer(runtime, clusterManager, subscriptionName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now} :: ex: {ex.ToString()}");
            }
        }
示例#14
0
        public void RuntimeFactoryInExtendedScope()
        {
            var runtime1 = RuntimeFactory.CreateRuntime(Scope.PerRequest);

            runtime1.InitializeWithConfigSetName("test");
            var runtime2 = RuntimeFactory.CreateRuntime(Scope.PerRequest);

            Assert.NotNull(runtime1);
            Assert.NotNull(runtime2);
            Assert.NotEqual(runtime1, runtime2);
        }
 public void IterationSetup()
 {
     if (this.ProducerMachine == null)
     {
         this.Runtime = RuntimeFactory.Create(Configuration.Create());
         var setuptcs = new TaskCompletionSource <bool>();
         this.ProducerMachine = this.Runtime.CreateActor(typeof(Producer), null,
                                                         new SetupProducerEvent(setuptcs, NumConsumers, NumMessages));
         setuptcs.Task.Wait();
     }
 }
示例#16
0
        public MasterDataClient(string serviceName, BootstrapContext token = null)
        {
            Tracer = TracerFactory.StartTracer(this, "ctor");
            var runtime = RuntimeFactory.CreateRuntime();

            Container = runtime.CreateServiceProxy <IMasterDataManagementService>(serviceName);
            if (token.IsInstance())
            {
                Container.Initialize(token);
            }
        }
示例#17
0
        public void IterationSetup()
        {
            var configuration = Configuration.Create();

            this.Runtime           = RuntimeFactory.Create(configuration);
            this.ExperimentAwaiter = new TaskCompletionSource <bool>();
            var tcs = new TaskCompletionSource <bool>();

            this.ProducerMachine = this.Runtime.CreateActor(typeof(Producer), null,
                                                            new SetupProducerEvent(tcs, this.ExperimentAwaiter, this.NumConsumers, NumMessages));
            tcs.Task.Wait();
        }
示例#18
0
        public void TestEventInheritanceInStateMachine()
        {
            var tcs           = new TaskCompletionSource <bool>();
            var configuration = Configuration.Create();
            var runtime       = RuntimeFactory.Create(configuration);
            var a             = runtime.CreateActor(typeof(A), null, new A.SetupEvent(tcs));

            runtime.SendEvent(a, new A.E3());
            runtime.SendEvent(a, new E1());
            runtime.SendEvent(a, new E2());
            Assert.True(tcs.Task.Wait(3000), "Test timed out");
        }
示例#19
0
 public Task <IBatchConnector <T> > ExecuteConnector(ExecutionTypes executionType)
 {
     if (IsRunning)
     {
         throw new InvalidAsynchronousStateException(string.Format("{0} is already running", Name));
     }
     ResetRunDetails();
     CheckForTerminationSignal();
     PrepareDataSet();
     Logger.SetBatchSize(RunId, ItemsToProcess, string.Format("Execution batch, type: {0}", executionType));
     CheckForTerminationSignal();
     return(RuntimeFactory.Run(() => InternalExecutor(executionType)));
 }
示例#20
0
        protected async Task RunAsync(Func <IActorRuntime, Task> test, Configuration configuration = null, bool handleFailures = true)
        {
            configuration = configuration ?? GetConfiguration();

            int iterations = Math.Max(1, configuration.TestingIterations);

            for (int i = 0; i < iterations; i++)
            {
                TextWriter logger;
                if (configuration.IsVerbose)
                {
                    logger = new TestOutputLogger(this.TestOutput, true);
                }
                else
                {
                    logger = TextWriter.Null;
                }

                try
                {
                    configuration.IsMonitoringEnabledInInProduction = true;
                    var runtime = RuntimeFactory.Create(configuration);
                    runtime.SetLogger(logger);

                    var errorTask = new TaskCompletionSource <Exception>();
                    if (handleFailures)
                    {
                        runtime.OnFailure += (e) =>
                        {
                            errorTask.SetResult(Unwrap(e));
                        };
                    }

                    await Task.WhenAny(test(runtime), errorTask.Task);

                    if (handleFailures && errorTask.Task.IsCompleted)
                    {
                        Assert.False(true, errorTask.Task.Result.Message);
                    }
                }
                catch (Exception ex)
                {
                    Exception e = Unwrap(ex);
                    Assert.False(true, e.Message + "\n" + e.StackTrace);
                }
                finally
                {
                    logger.Dispose();
                }
            }
        }
示例#21
0
        private static IActorRuntime CreateTestRuntime(Configuration config, TaskCompletionSource <bool> tcs, TextWriter logger = null)
        {
            config.IsMonitoringEnabledInInProduction = true;
            IActorRuntime runtime = RuntimeFactory.Create(config);

            runtime.RegisterMonitor <TestMonitor>();
            runtime.Monitor <TestMonitor>(new SetupEvent(tcs));
            if (logger != null)
            {
                runtime.SetLogger(logger);
            }

            return(runtime);
        }
示例#22
0
        protected async Task RunWithExceptionAsync <TException>(Func <Task> test, Configuration configuration = null)
        {
            configuration ??= GetConfiguration();

            Exception actualException = null;
            Type      exceptionType   = typeof(TException);

            Assert.True(exceptionType.IsSubclassOf(typeof(Exception)), "Please configure the test correctly. " +
                        $"Type '{exceptionType}' is not an exception type.");

            ILogger logger = this.GetLogger(configuration);

            try
            {
                configuration.IsMonitoringEnabledInInProduction = true;
                var runtime         = RuntimeFactory.Create(configuration);
                var errorCompletion = new TaskCompletionSource <Exception>();
                runtime.OnFailure += (e) =>
                {
                    errorCompletion.TrySetResult(e);
                };

                runtime.Logger = logger;
                for (int i = 0; i < configuration.TestingIterations; i++)
                {
                    await test();

                    if (configuration.TestingIterations is 1)
                    {
                        Assert.True(errorCompletion.Task.Wait(GetExceptionTimeout()), "Timeout waiting for error");
                        actualException = errorCompletion.Task.Result;
                    }
                }
            }
            catch (Exception ex)
            {
                actualException = ex;
            }
            finally
            {
                logger.Dispose();
            }

            if (actualException is null)
            {
                Assert.True(false, string.Format("Error not found after all {0} test iterations", configuration.TestingIterations));
            }

            Assert.True(actualException.GetType() == exceptionType, actualException.Message + "\n" + actualException.StackTrace);
        }
示例#23
0
        public async SystemTasks.Task TestSendNullEventInActor()
        {
            TaskCompletionSource <bool> completed = new TaskCompletionSource <bool>();
            var runtime = RuntimeFactory.Create();

            runtime.OnFailure += (e) =>
            {
                completed.SetResult(true);
            };
            var id     = runtime.CreateActor(typeof(B));
            var result = await completed.Task;

            Assert.True(result, "Sending null event didn't raise an Assert on null exception");
        }
示例#24
0
        public static void Main()
        {
            // Create a default configuration and a new Coyote runtime.
            var           config  = Configuration.Create();
            IActorRuntime runtime = RuntimeFactory.Create(config);

            Execute(runtime);

            runtime.OnFailure += OnRuntimeFailure;

            // Coyote actors run in separate Tasks, so this stops the program from terminating prematurely!
            Console.WriteLine("press ENTER to terminate...");
            Console.ReadLine();
        }
示例#25
0
        public async Task TestNullCustomLogger()
        {
            IActorRuntime runtime = RuntimeFactory.Create();

            runtime.SetLogger(null);

            var tcs = new TaskCompletionSource <bool>();

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

            await WaitAsync(tcs.Task);

            Assert.Equal("System.IO.TextWriter+NullTextWriter", runtime.Logger.ToString());
        }
示例#26
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            IStardustContext ctx = null;

            try
            {
                ctx = ContextScopeExtensions.CreateScope();
                if (request.Version.Envelope == EnvelopeVersion.None)
                {
                    runtime = RuntimeFactory.CreateRuntime();
                    runtime.GetStateStorageContainer().TryAddStorageItem((ThreadSynchronizationContext)ctx, Synccontext);
                    var httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                    if (httpRequest != null)
                    {
                        var msg = httpRequest.Headers["X-Stardust-Meta"];
                        if (msg.ContainsCharacters())
                        {
                            try
                            {
                                var item = Resolver.Activate <IReplaceableSerializer>().Deserialize <RequestHeader>(Convert.FromBase64String(msg).GetStringFromArray());
                                request.Properties.Add("autoHeader", item);
                                runtime.GetStateStorageContainer().TryAddStorageItem(true, "isRest");
                            }
                            catch
                            {
                            }
                        }
                    }

                    return(ctx);
                }
                if (request.Headers.Any(messageHeader => messageHeader.Name == "HeaderInfoIncluded"))
                {
                    runtime = RuntimeFactory.CreateRuntime();
                    runtime.GetStateStorageContainer().TryAddStorageItem((ThreadSynchronizationContext)ctx, Synccontext);
                    return(ctx);
                }
                ;
                var header = request.Headers.GetHeader <RequestHeader>("RequestHeader", RequestHeader.NS);
                request.Properties.Add("autoHeader", header);
                runtime = RuntimeFactory.CreateRuntime();
                runtime.GetStateStorageContainer().TryAddStorageItem((ThreadSynchronizationContext)ctx, Synccontext);
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            return(ctx);
        }
        public void MeasureCreationThroughput()
        {
            var configuration = Configuration.Create();
            var runtime       = RuntimeFactory.Create(configuration);

            var tcs = new TaskCompletionSource <bool>();
            var e   = new SetupEvent(tcs, this.NumMachines, this.DoHalt);

            for (int idx = 0; idx < this.NumMachines; idx++)
            {
                runtime.CreateActor(typeof(M), null, e);
            }

            tcs.Task.Wait();
        }
示例#28
0
        internal static IStardustContext CreateScope()
        {
            var id  = Guid.NewGuid();
            var ctx = ThreadSynchronizationContext.BeginContext(id);


            ContainerFactory.Current.Bind(typeof(Guid?), id, Scope.Context);
            var runtime = RuntimeFactory.CreateRuntime(Scope.PerRequest);

            ContainerFactory.Current.Bind(typeof(IRuntime), runtime, Scope.Context);
            ContainerFactory.Current.Bind(typeof(InvokationMarker), new InvokationMarker(DateTime.UtcNow), Scope.Context);
            ContainerFactory.Current.Bind(typeof(TraceHandler), new TraceHandler(), Scope.Context);
            ctx.Disposing += CurrentContextOnOperationCompleted;
            return(ctx);
        }
示例#29
0
        private static IRuntime CreateRuntime()
        {
            var runtime = RuntimeFactory.CreateRuntime(Scope.PerRequest);

            runtime.NoTrace = true;
            Logging.DebugMessage("Runtime created");
            runtime.SetEnvironment(Utilities.GetEnvironment());
            Logging.DebugMessage("Environment set");
            var serviceName = Utilities.GetServiceName();

            Logging.DebugMessage("ServiceName obtained");
            runtime.SetServiceName(new object(), serviceName, "IdentitySetup");
            Logging.DebugMessage("Service name set");
            return(runtime);
        }
示例#30
0
        public static void Main()
        {
            // Optional: increases verbosity level to see the Coyote runtime log.
            var configuration = Configuration.Create().WithVerbosityEnabled();

            // Creates a new Coyote runtime instance, and passes an optional configuration.
            var runtime = RuntimeFactory.Create(configuration);

            // Executes the Coyote program.
            Execute(runtime);

            // The Coyote runtime executes asynchronously, so we wait
            // to not terminate the process.
            Console.ReadLine();
        }