示例#1
0
        public void OrchestrationInstanceComparer_DifferentOrchestrationInstances()
        {
            var first = new OrchestrationInstance()
            {
                InstanceId  = "InstanceId1",
                ExecutionId = "ExecutionId1"
            };

            var second = new OrchestrationInstance()
            {
                InstanceId  = "InstanceId2",
                ExecutionId = "ExecutionId2"
            };

            Assert.IsFalse(OrchestrationInstanceComparer.Default.Equals(first, second));
        }
示例#2
0
        public void SessionNotExceededLimitTest()
        {
            taskHub.AddTaskOrchestrations(typeof(LargeSessionOrchestration))
            .AddTaskActivities(typeof(LargeSessionTaskActivity))
            .Start();

            OrchestrationInstance id = client.CreateOrchestrationInstance(typeof(LargeSessionOrchestration), 15);

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 90, true);

            Thread.Sleep(20000);

            OrchestrationState state = client.GetOrchestrationState(id);

            Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus);
        }
示例#3
0
        public void AsyncGreetingsTest()
        {
            AsyncGreetingsOrchestration.Result = null;

            taskHub.AddTaskOrchestrations(typeof(AsyncGreetingsOrchestration))
            .AddTaskActivities(typeof(AsyncGetUserTask), typeof(AsyncSendGreetingTask))
            .Start();

            OrchestrationInstance id = client.CreateOrchestrationInstance(typeof(AsyncGreetingsOrchestration), null);

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            Assert.AreEqual("Greeting send to Gabbar", AsyncGreetingsOrchestration.Result,
                            "Orchestration Result is wrong!!!");
        }
示例#4
0
        public async Task GenerationBasicNoCompressionTest()
        {
            GenerationBasicOrchestration.Result = 0;
            GenerationBasicTask.GenerationCount = 0;

            await this.taskHubNoCompression.AddTaskOrchestrations(typeof(GenerationBasicOrchestration))
            .AddTaskActivities(new GenerationBasicTask())
            .StartAsync();

            OrchestrationInstance id = await this.client.CreateOrchestrationInstanceAsync(typeof(GenerationBasicOrchestration), 4);

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(this.client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(this.client, id, 60));
            Assert.AreEqual(4, GenerationBasicOrchestration.Result, "Orchestration Result is wrong!!!");
        }
        public async Task FailingInstanceStoreTest()
        {
            await taskHub.AddTaskOrchestrations(typeof(InstanceStoreTestOrchestration))
            .AddTaskActivities(new Activity1())
            .StartAsync();

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(InstanceStoreTestOrchestration),
                                                                                     "THROW");

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            var status = await client.GetOrchestrationStateAsync(id);

            Assert.IsTrue(status.OrchestrationStatus == OrchestrationStatus.Failed);
        }
示例#6
0
        public async Task GreetingsDynamicProxyTest()
        {
            await taskHub.AddTaskOrchestrations(typeof(GreetingsOrchestration))
            .AddTaskActivities(
                new NameValueObjectCreator <TaskActivity>(GET_USER_NAME, GET_USER_VERSION, new GetUserTask()),
                new NameValueObjectCreator <TaskActivity>(SEND_GREETING_NAME, SEND_GREETING_VERSION,
                                                          new SendGreetingTask()))
            .StartAsync();

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(GreetingsOrchestration), null);

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            Assert.AreEqual("Greeting send to Gabbar", GreetingsOrchestration.Result, "Orchestration Result is wrong!!!");
        }
        public async Task MoreParamsOrchestrationTest()
        {
            await taskHub.AddTaskOrchestrations(typeof(MoreParamsOrchestration))
            .AddTaskActivitiesFromInterface <IMoreParamsActivities>(new MoreParamsActivities())
            .StartAsync();


            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(MoreParamsOrchestration),
                                                                                     new MoreParamsOrchestrationInput { Str = "Hello" });

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));

            Assert.AreEqual("Hello00Hello1015", MoreParamsOrchestration.Result);
        }
示例#8
0
        /// <summary>
        /// Starts a new execution of the specified orchestrator function.
        /// </summary>
        /// <param name="orchestratorFunctionName">The name of the orchestrator function to start.</param>
        /// <param name="instanceId">A unique ID to use for the new orchestration instance.</param>
        /// <param name="input">JSON-serializeable input value for the orchestrator function.</param>
        /// <returns>A task that completes when the start message is enqueued.</returns>
        public async Task <string> StartNewAsync(string orchestratorFunctionName, string instanceId, object input)
        {
            OrchestrationInstance instance = await this.client.CreateOrchestrationInstanceAsync(
                orchestratorFunctionName, DefaultVersion, instanceId, input);

            this.traceHelper.FunctionScheduled(
                this.hubName,
                orchestratorFunctionName,
                DefaultVersion,
                instance.InstanceId,
                reason: "NewInstance",
                isOrchestrator: true,
                isReplay: false);

            return(instance.InstanceId);
        }
示例#9
0
        public void GenerationBasicTest()
        {
            GenerationBasicOrchestration.Result = 0;
            GenerationBasicTask.GenerationCount = 0;

            taskHub.AddTaskOrchestrations(typeof(GenerationBasicOrchestration))
            .AddTaskActivities(new GenerationBasicTask())
            .Start();

            OrchestrationInstance id = client.CreateOrchestrationInstance(typeof(GenerationBasicOrchestration), 4);

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            Assert.AreEqual(4, GenerationBasicOrchestration.Result, "Orchestration Result is wrong!!!");
        }
示例#10
0
        public async Task ErrorHandlingTest()
        {
            await taskHub.AddTaskOrchestrations(typeof(ErrorHandlingOrchestration))
            .AddTaskActivities(typeof(GoodTask), typeof(BadTask), typeof(CleanupTask))
            .StartAsync();

            taskHub.TaskActivityDispatcher.IncludeDetails = true;

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(ErrorHandlingOrchestration), null);

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            Assert.AreEqual("CleanupResult", ErrorHandlingOrchestration.Result,
                            "Orchestration Result is wrong!!!");
        }
示例#11
0
        static async Task Main(string[] args)
        {
            //Use Azurite emulator
            string storageConnectionString = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;" +
                                             "BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1";
            string taskHubName = "RetryTest";

            var settings = new AzureStorageOrchestrationServiceSettings();

            settings.StorageConnectionString      = storageConnectionString;
            settings.TaskHubName                  = taskHubName;
            settings.UseDataContractSerialization = true;

            var orchestrationServiceAndClient = new AzureStorageOrchestrationService(settings);
            await orchestrationServiceAndClient.CreateIfNotExistsAsync();

            var taskHubClient = new TaskHubClient(orchestrationServiceAndClient);
            var taskHub       = new TaskHubWorker(orchestrationServiceAndClient);

            // add instance
            _ = Task.Run(async() =>
            {
                OrchestrationInstance ins = await taskHubClient.CreateOrchestrationInstanceAsync(typeof(HelloOrchestration), "b", "");
            });

            // add worker
            try
            {
                taskHub.AddTaskOrchestrations(
                    typeof(HelloOrchestration)
                    );

                taskHub.AddTaskActivitiesFromInterface <IFailedTask>(new FailedTask());


                await taskHub.StartAsync();

                //Console.WriteLine("Press any key to quit.");
                Console.ReadLine();
                taskHub.StopAsync(true).Wait();
            }
            catch (Exception e)
            {
                // silently eat any unhandled exceptions.
                Console.WriteLine($"worker exception: {e}");
            }
        }
示例#12
0
        internal void RescheduleMessages(OrchestrationContext innerContext, List <RequestMessage> messages)
        {
            if (messages != null)
            {
                foreach (var message in messages)
                {
                    var instance = new OrchestrationInstance {
                        InstanceId = this.InstanceId
                    };
                    DateTime adjustedDeliveryTime = message.GetAdjustedDeliveryTime(this.durabilityProvider);
                    var      eventName            = EntityMessageEventNames.ScheduledRequestMessageEventName(adjustedDeliveryTime);
                    innerContext.SendEvent(instance, eventName, message);
                }

                messages.Clear();
            }
        }
示例#13
0
        /// <summary>
        /// Creates a <see cref="OrchestrationInstanceEx"/> from the provided
        /// <see cref="OrchestrationRuntimeState"/>, using its extension data if available.
        /// </summary>
        /// <param name="runtimeState">The runtime state to create this instance from.</param>
        /// <returns>A new or deserialized instance.</returns>
        public static OrchestrationInstanceEx Initialize(OrchestrationRuntimeState runtimeState)
        {
            if (runtimeState == null)
            {
                throw new ArgumentNullException(nameof(runtimeState));
            }

            OrchestrationInstance instance = runtimeState.OrchestrationInstance;

            if (instance is OrchestrationInstanceEx custom)
            {
                return(custom);
            }

            custom = Get(instance);
            return(custom);
        }
示例#14
0
        public void SignalTest()
        {
            taskHub.AddTaskOrchestrations(typeof(SignalOrchestration))
            .AddTaskActivities(typeof(SendGreetingTask))
            .Start();

            OrchestrationInstance id = client.CreateOrchestrationInstance(typeof(SignalOrchestration), null);

            Thread.Sleep(2 * 1000);
            client.RaiseEvent(id, "GetUser", "Gabbar");

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 60);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 60));
            Assert.AreEqual("Greeting send to Gabbar", SignalOrchestration.Result,
                            "Orchestration Result is wrong!!!");
        }
示例#15
0
        public async Task RetryFailProxyTest()
        {
            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(3), 3);
            var retryTask    = new RetryTask(3);
            await taskHub.AddTaskOrchestrations(new TestObjectCreator <TaskOrchestration>(RETRY_NAME, RETRY_VERSION,
                                                                                          () => new RetryOrchestration(retryOptions)))
            .AddTaskActivitiesFromInterface <IRetryTask>(retryTask)
            .StartAsync();

            RetryOrchestration.Result = null;
            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(RETRY_NAME, RETRY_VERSION, null);

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 120);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 120));
            Assert.AreEqual("RetryCount is: 3", RetryOrchestration.Result, "Orchestration Result is wrong!!!");
        }
示例#16
0
        public async Task SubOrchestrationRetryExhaustedTest()
        {
            ArgumentException argumentException = null;

            try
            {
                // ReSharper disable once ObjectCreationAsStatement
                new RetryOptions(TimeSpan.Zero, 10);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            Assert.IsNotNull(argumentException);
            Assert.AreEqual(
                "Invalid interval.  Specify a TimeSpan value greater then TimeSpan.Zero.\r\nParameter name: firstRetryInterval",
                argumentException.Message);

            var parentRetryOptions = new RetryOptions(TimeSpan.FromSeconds(3), 2)
            {
                BackoffCoefficient = 2.0,
                MaxRetryInterval   = TimeSpan.FromSeconds(4),
            };
            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(3), 2);
            var retryTask    = new RetryTask(4);

            RetryOrchestration.RethrowException = true;

            await this.taskHub.AddTaskOrchestrations(new TestObjectCreator <TaskOrchestration>(RetryName, RetryVersion,
                                                                                               () => new RetryOrchestration(retryOptions)))
            .AddTaskOrchestrations(new TestObjectCreator <TaskOrchestration>(RetryParentName, RetryParentVersion,
                                                                             () => new ParentOrchestration(parentRetryOptions)))
            .AddTaskActivitiesFromInterface <IRetryTask>(retryTask)
            .StartAsync();

            ParentOrchestration.Result = null;
            RetryOrchestration.Result  = null;
            OrchestrationInstance id = await this.client.CreateOrchestrationInstanceAsync(RetryParentName, RetryParentVersion, false);

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(this.client, id, 90);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(this.client, id, 90));
            Assert.AreEqual("DoWork Failed. RetryCount is: 4", ParentOrchestration.Result,
                            "Orchestration Result is wrong!!!");
        }
示例#17
0
        internal void SendOperationMessage(OrchestrationInstance target, string eventName, object message)
        {
            lock (this.outbox)
            {
                if (message is RequestMessage requestMessage)
                {
                    this.State.MessageSorter.LabelOutgoingMessage(requestMessage, target.InstanceId, DateTime.UtcNow, this.EntityMessageReorderWindow);
                }

                this.outbox.Add(new OperationMessage()
                {
                    Target       = target,
                    EventName    = eventName,
                    EventContent = message,
                });
            }
        }
        public void TryUnlockSession(OrchestrationInstance instance, bool abandon = false, bool isComplete = false)
        {
            ServiceFabricProviderEventSource.Tracing.TraceMessage(instance.InstanceId, $"Session Unlock Begin, Abandon = {abandon}");
            if (!this.lockedSessions.TryRemove(instance.InstanceId, out LockState lockState) || lockState == LockState.InFetchQueue)
            {
                var errorMessage = $"{nameof(SessionProvider)}.{nameof(TryUnlockSession)} : Trying to unlock the session {instance.InstanceId} which was not locked.";
                ServiceFabricProviderEventSource.Tracing.UnexpectedCodeCondition(errorMessage);
                throw new Exception(errorMessage);
            }

            if (!isComplete && (abandon || lockState == LockState.NewMessagesWhileLocked))
            {
                this.TryEnqueueSession(instance);
            }

            ServiceFabricProviderEventSource.Tracing.TraceMessage(instance.InstanceId, $"Session Unlock End, Abandon = {abandon}, removed lock state = {lockState}");
        }
示例#19
0
        public void SessionExceededLimitNoCompressionTest()
        {
            taskHubNoCompression.AddTaskOrchestrations(typeof(LargeSessionOrchestration))
            .AddTaskActivities(typeof(LargeSessionTaskActivity))
            .Start();

            OrchestrationInstance id = client.CreateOrchestrationInstance(typeof(LargeSessionOrchestration), 15);

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 60, true);

            Thread.Sleep(20000);

            OrchestrationState state = client.GetOrchestrationState(id);

            Assert.AreEqual(OrchestrationStatus.Terminated, state.OrchestrationStatus);
            Assert.IsTrue(state.Output.Contains("exceeded"));
        }
        public async Task SimplestGreetingsJumpStartDelayTest()
        {
            var    sbService = (ServiceBusOrchestrationService)taskHub.orchestrationService;
            string name      = NameVersionHelper.GetDefaultName(typeof(SimplestGreetingsOrchestration));
            string version   = NameVersionHelper.GetDefaultVersion(typeof(SimplestGreetingsOrchestration));

            await taskHub.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration))
            .AddTaskActivities(typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask))
            .StartAsync();

            OrchestrationInstance id = await TestHelpers.CreateOrchestrationInstanceAsync(sbService, name, version, null, null, true, false);

            // Wait only 8 seconds, the jumptstartinterval is set to 10
            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, id, 8);

            Assert.IsFalse(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 8));
        }
示例#21
0
        public async Task WaitForOrchestration_Returns_Null_When_Orchestration_Not_Started()
        {
            var instance = new OrchestrationInstance()
            {
                InstanceId = "NonExisting", ExecutionId = "NonExisting"
            };
            OrchestrationState result = null;
            var waitTime = TimeSpan.FromMinutes(1);
            var time     = await Utilities.MeasureAsync(async() =>
            {
                result = await this.taskHubClient.WaitForOrchestrationAsync(instance, waitTime);
            });

            Assert.IsNull(result);
            Assert.IsTrue(time < waitTime + waitTime);
            Console.WriteLine($"Full WaitTime : {waitTime}, Actual time taken for Wait {time}");
        }
示例#22
0
        public void OrchestrationInstanceComparer_SameOrchestrationInstances()
        {
            var first = new OrchestrationInstance()
            {
                InstanceId  = "InstanceId",
                ExecutionId = "ExecutionId"
            };

            var second = new OrchestrationInstance()
            {
                InstanceId  = "InstanceId",
                ExecutionId = "ExecutionId"
            };

            Assert.IsTrue(OrchestrationInstanceComparer.Default.Equals(first, first));
            Assert.IsTrue(OrchestrationInstanceComparer.Default.Equals(first, second));
        }
        public void Messages_With_Different_FiredAt_Value_Are_Sorted_Based_On_FiredAt()
        {
            ImmutableSortedSet <Message <Guid, TaskMessageItem> > timerMessages = ImmutableSortedSet <Message <Guid, TaskMessageItem> > .Empty.WithComparer(TimerFiredEventComparer.Instance);

            var instance = new OrchestrationInstance()
            {
                InstanceId = "InstanceId",
            };

            var currentTime      = DateTime.UtcNow;
            var builder          = timerMessages.ToBuilder();
            int numberOfMessages = 5;

            var guids = Enumerable.Range(0, numberOfMessages).Select(x => Guid.NewGuid()).ToList();

            // Add them in reverse order to expected order just to make the test case more interesting.
            for (int i = numberOfMessages - 1; i >= 0; i--)
            {
                builder.Add(new Message <Guid, TaskMessageItem>(guids[i], new TaskMessageItem(new TaskMessage() //Let the key values be in reverse order to fired at values again to make test more interesting.
                {
                    SequenceNumber        = i,
                    OrchestrationInstance = instance,
                    Event = new TimerFiredEvent(i)
                    {
                        FireAt = currentTime + TimeSpan.FromSeconds(i)
                    }
                })));
            }

            Assert.AreEqual(numberOfMessages, builder.Count);
            timerMessages = builder.ToImmutableSortedSet(TimerFiredEventComparer.Instance);
            Assert.AreEqual(numberOfMessages, timerMessages.Count);

            // Now enumerating the items should result in right order.
            for (int i = 0; i < numberOfMessages; i++)
            {
                var min = timerMessages.Min;
                timerMessages = timerMessages.Remove(min);
                var firedAt = (min.Value.TaskMessage.Event as TimerFiredEvent)?.FireAt;
                Assert.AreEqual(currentTime + TimeSpan.FromSeconds(i), firedAt, "Ordering seems to be broken");
                Assert.AreEqual(guids[i], min.Key);
            }

            Assert.AreEqual(0, timerMessages.Count);
        }
示例#24
0
        public async Task ScheduledStart()
        {
            const int MaxSecondsToCompleteNotDelayedOrchestration = 10;

            await this.taskHub.AddTaskOrchestrations(typeof(StartAtTimeOrchestration))
            .StartAsync();

            // orchestrationId1 has delayed start
            var delay             = TimeSpan.FromSeconds(30);
            var expectedStartTime = DateTime.UtcNow.Add(delay);
            OrchestrationInstance orchestrationId1 = await this.client.CreateScheduledOrchestrationInstanceAsync(typeof(StartAtTimeOrchestration), null, expectedStartTime);

            // orchestrationId2 can start immediately
            OrchestrationInstance orchestrationId2 = await this.client.CreateOrchestrationInstanceAsync(typeof(StartAtTimeOrchestration), null);

            // Ensure that the orchestration with delay has been created properly
            var orchestration1StateAfterCreation = await this.client.GetOrchestrationStateAsync(orchestrationId1);

            Assert.AreEqual(OrchestrationStatus.Pending, orchestration1StateAfterCreation.OrchestrationStatus);

            // Ensure that the orchestration without delay has been created properly
            var orchestration2StateAfterCreation = await this.client.GetOrchestrationStateAsync(orchestrationId2);

            Assert.IsTrue(new[] { OrchestrationStatus.Pending, OrchestrationStatus.Running, OrchestrationStatus.Completed }.Contains(orchestration2StateAfterCreation.OrchestrationStatus));

            // Wait until orchestration 2 (not delayed) is complete
            bool isOrchestration2Complete = await TestHelpers.WaitForInstanceAsync(this.client, orchestrationId2, 60);

            Assert.IsTrue(isOrchestration2Complete, TestHelpers.GetInstanceNotCompletedMessage(this.client, orchestrationId2, 60));
            var orchestration2CompletedState = await client.GetOrchestrationStateAsync(orchestrationId2);

            var orchestration2TimeToCompleteInSeconds = (int)orchestration2CompletedState.CompletedTime.Subtract(orchestration2CompletedState.CreatedTime).TotalSeconds;

            Assert.IsTrue(orchestration2TimeToCompleteInSeconds < MaxSecondsToCompleteNotDelayedOrchestration, $"Expected not delayed orchestration to be complete in under {MaxSecondsToCompleteNotDelayedOrchestration} secs, but was {orchestration2TimeToCompleteInSeconds}");

            // Wait until orchestration 1 (delayed) is complete
            bool isOrchestration1Complete = await TestHelpers.WaitForInstanceAsync(this.client, orchestrationId1, 60);

            Assert.IsTrue(isOrchestration1Complete, TestHelpers.GetInstanceNotCompletedMessage(this.client, orchestrationId1, 60));
            var orchestration1CompletedState = await client.GetOrchestrationStateAsync(orchestrationId1);

            var orchestration1TimeToCompleteInSeconds = (int)orchestration1CompletedState.CompletedTime.Subtract(orchestration1CompletedState.CreatedTime).TotalSeconds;

            Assert.IsTrue(orchestration1TimeToCompleteInSeconds >= delay.TotalSeconds, $"Expected delayed orchestration to be completed after {delay.TotalSeconds} seconds or more relative to the creation time, but was {orchestration1TimeToCompleteInSeconds} seconds");
        }
示例#25
0
        public async Task NonDeterministicOrchestrationTest()
        {
            await taskHub.AddTaskOrchestrations(typeof(NonDeterministicOrchestration))
            .AddTaskActivities(typeof(FirstTask))
            .StartAsync();

            taskHub.TaskActivityDispatcher.IncludeDetails = true;

            OrchestrationInstance instance = await client.CreateOrchestrationInstanceAsync(typeof(NonDeterministicOrchestration),
                                                                                           "FAILTIMER");

            bool isCompleted = await TestHelpers.WaitForInstanceAsync(client, instance, 60);

            OrchestrationState state = await client.GetOrchestrationStateAsync(instance);

            Assert.AreEqual(OrchestrationStatus.Failed, state.OrchestrationStatus);
            Assert.IsTrue(state.Output.Contains("TimerCreatedEvent"));

            instance = await client.CreateOrchestrationInstanceAsync(typeof(NonDeterministicOrchestration), "FAILTASK");

            isCompleted = await TestHelpers.WaitForInstanceAsync(client, instance, 60);

            state = await client.GetOrchestrationStateAsync(instance);

            Assert.AreEqual(OrchestrationStatus.Failed, state.OrchestrationStatus);
            Assert.IsTrue(state.Output.Contains("TaskScheduledEvent"));

            instance = await client.CreateOrchestrationInstanceAsync(typeof(NonDeterministicOrchestration), "FAILSUBORCH");

            isCompleted = await TestHelpers.WaitForInstanceAsync(client, instance, 60);

            state = await client.GetOrchestrationStateAsync(instance);

            Assert.AreEqual(OrchestrationStatus.Failed, state.OrchestrationStatus);
            Assert.IsTrue(state.Output.Contains("SubOrchestrationInstanceCreatedEvent"));

            instance = await client.CreateOrchestrationInstanceAsync(typeof(NonDeterministicOrchestration), "PARENTORCH");

            isCompleted = await TestHelpers.WaitForInstanceAsync(client, instance, 60);

            state = await client.GetOrchestrationStateAsync(instance);

            Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus);
            Assert.IsTrue(state.Output.Contains("Non-Deterministic workflow detected"));
        }
        public async Task DispatchMiddlewareContextBuiltInProperties()
        {
            TaskOrchestration         orchestration = null;
            OrchestrationRuntimeState state         = null;
            OrchestrationInstance     instance1     = null;

            TaskActivity          activity           = null;
            TaskScheduledEvent    taskScheduledEvent = null;
            OrchestrationInstance instance2          = null;

            this.worker.AddOrchestrationDispatcherMiddleware((context, next) =>
            {
                orchestration = context.GetProperty <TaskOrchestration>();
                state         = context.GetProperty <OrchestrationRuntimeState>();
                instance1     = context.GetProperty <OrchestrationInstance>();

                return(next());
            });

            this.worker.AddActivityDispatcherMiddleware((context, next) =>
            {
                activity           = context.GetProperty <TaskActivity>();
                taskScheduledEvent = context.GetProperty <TaskScheduledEvent>();
                instance2          = context.GetProperty <OrchestrationInstance>();

                return(next());
            });

            var instance = await this.client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), null);

            TimeSpan timeout = TimeSpan.FromSeconds(Debugger.IsAttached ? 1000 : 10);

            await this.client.WaitForOrchestrationAsync(instance, timeout);

            Assert.IsNotNull(orchestration);
            Assert.IsNotNull(state);
            Assert.IsNotNull(instance1);

            Assert.IsNotNull(activity);
            Assert.IsNotNull(taskScheduledEvent);
            Assert.IsNotNull(instance2);

            Assert.AreNotSame(instance1, instance2);
            Assert.AreEqual(instance1.InstanceId, instance2.InstanceId);
        }
        private async Task SignalEntityAsyncInternal(TaskHubClient client, string hubName, EntityId entityId, DateTime?scheduledTimeUtc, string operationName, object operationInput)
        {
            if (operationName == null)
            {
                throw new ArgumentNullException(nameof(operationName));
            }

            if (this.client.Equals(client))
            {
                this.config.ThrowIfFunctionDoesNotExist(entityId.EntityName, FunctionType.Entity);
            }

            var guid       = Guid.NewGuid(); // unique id for this request
            var instanceId = EntityId.GetSchedulerIdFromEntityId(entityId);
            var instance   = new OrchestrationInstance()
            {
                InstanceId = instanceId
            };
            var request = new RequestMessage()
            {
                ParentInstanceId  = null, // means this was sent by a client
                ParentExecutionId = null,
                Id            = guid,
                IsSignal      = true,
                Operation     = operationName,
                ScheduledTime = scheduledTimeUtc,
            };

            if (operationInput != null)
            {
                request.SetInput(operationInput, this.messageDataConverter);
            }

            var jrequest  = JToken.FromObject(request, this.messageDataConverter.JsonSerializer);
            var eventName = scheduledTimeUtc.HasValue ? EntityMessageEventNames.ScheduledRequestMessageEventName(scheduledTimeUtc.Value) : EntityMessageEventNames.RequestMessageEventName;
            await client.RaiseEventAsync(instance, eventName, jrequest);

            this.traceHelper.FunctionScheduled(
                hubName,
                entityId.EntityName,
                EntityId.GetSchedulerIdFromEntityId(entityId),
                reason: $"EntitySignal:{operationName}",
                functionType: FunctionType.Entity,
                isReplay: false);
        }
示例#28
0
        protected async Task JumpStartOrchestrationAsync(OrchestrationJumpStartInstanceEntity jumpStartEntity)
        {
            OrchestrationInstance            instance    = jumpStartEntity.State.OrchestrationInstance;
            OrchestrationStateInstanceEntity stateEntity = (await this.service.InstanceStore.GetEntitiesAsync(instance.InstanceId, instance.ExecutionId))?.FirstOrDefault();

            if (stateEntity != null)
            {
                // It seems orchestration started, delete entity from JumpStart table
                await this.service.InstanceStore.DeleteJumpStartEntitiesAsync(new[] { jumpStartEntity });
            }
            else if (!jumpStartEntity.JumpStartTime.IsSet() &&
                     jumpStartEntity.State.CreatedTime + this.ignoreWindow < DateTime.UtcNow)
            {
                // JumpStart orchestration
                var startedEvent = new ExecutionStartedEvent(-1, jumpStartEntity.State.Input)
                {
                    Tags    = jumpStartEntity.State.Tags,
                    Name    = jumpStartEntity.State.Name,
                    Version = jumpStartEntity.State.Version,
                    OrchestrationInstance = jumpStartEntity.State.OrchestrationInstance
                };

                var taskMessage = new TaskMessage
                {
                    OrchestrationInstance = jumpStartEntity.State.OrchestrationInstance,
                    Event = startedEvent
                };

                await this.service.SendTaskOrchestrationMessageAsync(taskMessage);

                TraceHelper.Trace(
                    TraceEventType.Information,
                    "JumpStartManager-SendTaskOrchestrationMessage",
                    $"JumpStartManager: SendTaskOrchestrationMessageAsync({instance.InstanceId}, {instance.ExecutionId}) success!");

                // Now update the JumpStart table
                jumpStartEntity.JumpStartTime = DateTime.UtcNow;
                await this.service.InstanceStore.WriteJumpStartEntitiesAsync(new[] { jumpStartEntity });

                TraceHelper.Trace(
                    TraceEventType.Information,
                    "JumpStartManager-WriteJumpStartEntities",
                    $"JumpStartManager: WriteJumpStartEntitiesAsync({instance.InstanceId}, {instance.ExecutionId}) success!");
            }
        }
        public void SubOrchestrationRetryExhaustedTest()
        {
            ArgumentException argumentException = null;

            try
            {
                new RetryOptions(TimeSpan.Zero, 10);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            Assert.IsNotNull(argumentException);
            Assert.AreEqual(
                "Invalid interval.  Specify a TimeSpan value greater then TimeSpan.Zero.\r\nParameter name: firstRetryInterval",
                argumentException.Message);

            var parentRetryOptions = new RetryOptions(TimeSpan.FromSeconds(3), 2)
            {
                BackoffCoefficient = 2.0,
                MaxRetryInterval   = TimeSpan.FromSeconds(4),
            };
            var retryOptions = new RetryOptions(TimeSpan.FromSeconds(3), 2);
            var retryTask    = new RetryTask(4);

            RetryOrchestration.rethrowException = true;

            taskHub.AddTaskOrchestrations(new TestObjectCreator <TaskOrchestration>(RETRY_NAME, RETRY_VERSION,
                                                                                    () => new RetryOrchestration(retryOptions)))
            .AddTaskOrchestrations(new TestObjectCreator <TaskOrchestration>(RETRY_PARENT_NAME, RETRY_PARENT_VERSION,
                                                                             () => new ParentOrchestration(parentRetryOptions)))
            .AddTaskActivitiesFromInterface <IRetryTask>(retryTask)
            .Start();

            ParentOrchestration.Result = null;
            RetryOrchestration.Result  = null;
            OrchestrationInstance id = client.CreateOrchestrationInstance(RETRY_PARENT_NAME, RETRY_PARENT_VERSION, false);

            bool isCompleted = TestHelpers.WaitForInstance(client, id, 90);

            Assert.IsTrue(isCompleted, TestHelpers.GetInstanceNotCompletedMessage(client, id, 90));
            Assert.AreEqual("DoWork Failed. RetryCount is: 4", ParentOrchestration.Result,
                            "Orchestration Result is wrong!!!");
        }
        /// <summary>
        /// Starts a new execution of the specified orchestrator function.
        /// </summary>
        /// <param name="orchestratorFunctionName">The name of the orchestrator function to start.</param>
        /// <param name="instanceId">A unique ID to use for the new orchestration instance.</param>
        /// <param name="input">JSON-serializeable input value for the orchestrator function.</param>
        /// <returns>A task that completes when the start message is enqueued.</returns>
        /// <exception cref="ArgumentException">
        /// The specified function does not exist, is disabled, or is not an orchestrator function.
        /// </exception>
        public async Task <string> StartNewAsync(string orchestratorFunctionName, string instanceId, object input)
        {
            this.config.AssertOrchestratorExists(orchestratorFunctionName, DefaultVersion);

            OrchestrationInstance instance = await this.client.CreateOrchestrationInstanceAsync(
                orchestratorFunctionName, DefaultVersion, instanceId, input);

            this.traceHelper.FunctionScheduled(
                this.hubName,
                orchestratorFunctionName,
                DefaultVersion,
                instance.InstanceId,
                reason: "NewInstance",
                functionType: FunctionType.Orchestrator,
                isReplay: false);

            return(instance.InstanceId);
        }
示例#31
0
 public TaskContext(OrchestrationInstance orchestrationInstance)
 {
     OrchestrationInstance = orchestrationInstance;
 }
示例#32
0
 // have both iid and eid
 public static void TraceInstance(TraceEventType eventType, OrchestrationInstance orchestrationInstance,
     string format, params object[] args)
 {
     if (source.Switch.ShouldTrace(eventType))
     {
         ExceptionHandlingWrapper(
             () =>
                 source.TraceEvent(eventType, 0,
                     GetFormattedString(
                         orchestrationInstance == null ? string.Empty : orchestrationInstance.InstanceId,
                         orchestrationInstance == null ? string.Empty : orchestrationInstance.ExecutionId,
                         format, args)));
     }
 }
示例#33
0
 public static void TraceInstance(TraceEventType eventType, OrchestrationInstance orchestrationInstance,
     Func<string> generateMessage)
 {
     if (source.Switch.ShouldTrace(eventType))
     {
         ExceptionHandlingWrapper(
             () => source.TraceEvent(eventType, 0, GetFormattedString(
                 orchestrationInstance == null ? string.Empty : orchestrationInstance.InstanceId,
                 orchestrationInstance == null ? string.Empty : orchestrationInstance.ExecutionId,
                 generateMessage())));
     }
 }
示例#34
0
 // instance tracing methods
 public static Exception TraceExceptionInstance(TraceEventType eventType,
     OrchestrationInstance orchestrationInstance, Exception exception)
 {
     return TraceExceptionCore(eventType, orchestrationInstance.InstanceId, orchestrationInstance.ExecutionId,
         exception, string.Empty);
 }
示例#35
0
 public static Exception TraceExceptionInstance(TraceEventType eventType,
     OrchestrationInstance orchestrationInstance, Exception exception, Func<string> generateMessage)
 {
     return TraceExceptionCore(eventType, orchestrationInstance.InstanceId, orchestrationInstance.ExecutionId,
         exception, generateMessage);
 }
示例#36
0
 public static Exception TraceExceptionInstance(TraceEventType eventType,
     OrchestrationInstance orchestrationInstance, Exception exception, string format, params object[] args)
 {
     return TraceExceptionCore(eventType, orchestrationInstance.InstanceId, orchestrationInstance.ExecutionId,
         exception, format, args);
 }