This repository was archived by the owner on Feb 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
Wait until Saga is CompletedΒ #58
Copy link
Copy link
Open
Description
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()
}zayatsRB
Metadata
Metadata
Assignees
Labels
No labels