I have some questions about Orleans Best Practices
I've already read this guide, but still have some questions. Please see the code bellow:
[StorageProvider(ProviderName = "AzureTable")]
public class OfficeOrderTransaction : Grain<OfficeOrderState>, IOfficeOrderTransaction
{
private bool _inProgress = false;
private ObserverSubscriptionManager<IOfficeOrderObserver> _subsManager;
public override async Task OnActivateAsync()
{
Console.WriteLine($"Grain {nameof(ProductsGrain)} activated.");
// We created the utility at activation time.
_subsManager = new ObserverSubscriptionManager<IOfficeOrderObserver>();
await base.OnActivateAsync();
}
public Task Continue()
{
// ReSharper disable once InvertIf
if (State.State != TransactionState.Completed && !_inProgress)
{
ExecuteTransaction();
}
return Task.CompletedTask;
}
public async Task<bool> Start(string subscriptionId)
{
if (State.State == TransactionState.Completed)
{
throw new InvalidOperationException();
}
State.SubscriptionId = subscriptionId;
await WriteStateAsync();
var client = GrainFactory.GetGrain<IInProgressTransactionsQueue>(nameof(IInProgressTransactionsQueue));
await client.Put(this.GetPrimaryKey());
ExecuteTransaction();
return true;
}
// Clients call this to subscribe.
public Task Subscribe(IOfficeOrderObserver observer)
{
_subsManager.Subscribe(observer);
return Task.CompletedTask;
}
//Also clients use this to unsubscribe themselves to no longer receive the messages.
public Task UnSubscribe(IOfficeOrderObserver observer)
{
_subsManager.Unsubscribe(observer);
return Task.CompletedTask;
}
public Task<TransactionState> GetState()
{
return Task.FromResult(State.State);
}
private async void ExecuteTransaction()
{
_inProgress = true;
// Step 1
if (string.IsNullOrEmpty(State.ActionState)
|| State.ActionState == nameof(Action1))
{
State.ActionState = nameof(Action1);
await WriteStateAsync();
await Action1();
State.ActionState = nameof(Action2);
await WriteStateAsync();
ExecuteTransaction();
}
// Step 2
else if (State.ActionState == nameof(Action2))
{
await Action2();
}
var grain = GrainFactory.GetGrain<IProductGrain>(long.Parse(State.SubscriptionId));
await grain.Save("New product", "Sucessfuly created!");
State.State = TransactionState.Completed;
await WriteStateAsync();
var streamProvider = GetStreamProvider("AzureQueueProvider");
//Get the reference to a stream
var stream = streamProvider.GetStream<string>(Guid.Empty, "Test");
await stream.OnNextAsync(State.SubscriptionId);
_subsManager.Notify(s => s.ReceiveMessage(State.SubscriptionId));
}
private async Task Action1()
{
var client = GrainFactory.GetGrain<IClient>((default(int)));
await client.IsBalanceEnought();
}
private async Task Action2()
{
var client = GrainFactory.GetGrain<IPayment>((default(int)));
await client.Pay();
}
}
I'm trying to organize long running transactional process (in the future maybe with compensating actions aka [saga/state machine/call it what you want] it doesn't matter).
- I need to do some piece of work in the Start method.
- After run some method (ExecuteTransaction) without waiting and immediately return some result (in this example value which will notify that process has been successfully started).
What is the right way to do it? Use async void method or one more additional grain? Is async void bad practice here?
Also sometimes I'm getting Orleans.Storage.TableStorageUpdateConditionNotSatisfiedException in the ExecuteTransaction() method. I put two breakpoints in this method:
- At the beginning of method.
- After block of // Step 2.
The second breakpoint hits two times without stack trace when first only once. How it is possible, magic?
What is the right way to do it? Use async void method or one more additional grain? Is async void bad practice here?
async void is a bad practice not just here but pretty much everywhere except for some UI apps.
If you want to return to the caller before execution completes, you can record the request from within Start just like you seem to be doing, and then schedule a timer and/or reminder for the actual execution. After that, Start can return to the caller a success, meaning that the request got accepted, and will be processed.
The timer/reminder combination is a popular way for implementing workflow-like computations in Orleans.
TableStorageUpdateConditionNotSatisfiedException points to an Etag violation, which is likely caused by a race between the async void method and normal grain methods.
@sergeybykov thank you very much!