Skip to content
This repository was archived by the owner on Feb 6, 2025. It is now read-only.

Wait until Saga is CompletedΒ #58

@vecherkin

Description

@vecherkin

Is there any "legal" way to wait until the Saga is Completed?
Sometimes need to start Saga and block, for example, UI operation until Saga is Completed or Rejected.

var coordinator = app.ApplicationServices.GetService<ISagaCoordinator>();

var context = SagaContext
    .Create()
    .WithCorrelationId(Guid.NewGuid())
    .Build();

// Sending initial Message/Event
coordinator.ProcessAsync(new Message1 { Text = "Hello" }, context);

// Desired behavior: block until Saga is Completed or Rejected and return ISagaState
var state = coordinator.WaitAsync(context);

Now I can do it with a few stupid lines of code:

// Helper extensions
public static class SagaExtensions
    {
        public static async Task<ISagaState> WaitAsync(this ISagaCoordinator coordinator, ISagaContext context, ISagaStateRepository sagaStateRepository)
        {
            var sagaState = await sagaStateRepository.GetStateAsync(context);
            while (sagaState is null || sagaState.State == SagaStates.Pending)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));
                sagaState = await sagaStateRepository.GetStateAsync(context);
            }

            return sagaState;
        }

        public static async Task<ISagaState> GetStateAsync(this ISagaStateRepository sagaStateRepo, ISagaContext context)
        {
            return await sagaStateRepo.ReadAsync(context.SagaId, (Type) context.Metadata.First(md => md.Key == "sagaType").Value);
        }
    }

// Then in some place
var coordinator = app.ApplicationServices.GetService<ISagaCoordinator>();

var context = SagaContext
    .Create()
    .WithSagaId(SagaId.NewSagaId())
    .WithOriginator("Test")
    .WithMetadata("key", "lulz")
    .WithMetadata("sagaType", typeof(SampleSaga))
    .Build();

// Sending initial Message/Event
coordinator.ProcessAsync(new Message1 { Text = "Hello" }, context);

// Block until Saga is Completed or Rejected and return ISagaState
var sagaStateRepo = app.ApplicationServices.GetService<ISagaStateRepository>();
var state = await coordinator.WaitAsync(context, sagaStateRepo);

if (sagaState.State is SagaStates.Rejected)
{
// onRejected()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions