| | | 1 | | namespace Nabs.ScenarioGrains; |
| | | 2 | | |
| | | 3 | | public interface IScenarioGrain : IAddressable; |
| | | 4 | | |
| | | 5 | | public abstract class ScenarioGrain<TGrainState> : Grain, IScenarioGrain |
| | | 6 | | where TGrainState : class |
| | | 7 | | { |
| | | 8 | | protected IPersistentState<TGrainState> GrainState { get; } |
| | | 9 | | protected IGrainRepository<TGrainState> GrainRepository { get; } |
| | | 10 | | |
| | 1 | 11 | | public ScenarioGrain( |
| | 1 | 12 | | IPersistentState<TGrainState> state, |
| | 1 | 13 | | IGrainRepository<TGrainState> grainRepository) |
| | | 14 | | { |
| | 1 | 15 | | GrainState = state; |
| | 1 | 16 | | GrainRepository = grainRepository; |
| | 1 | 17 | | } |
| | | 18 | | |
| | | 19 | | public override async Task OnActivateAsync( |
| | | 20 | | CancellationToken cancellationToken) |
| | | 21 | | { |
| | 1 | 22 | | await GrainState.ReadStateAsync(); |
| | | 23 | | |
| | 1 | 24 | | if (!GrainState.RecordExists) |
| | | 25 | | { |
| | 1 | 26 | | var queryResult = await GrainRepository.Query(this); |
| | | 27 | | |
| | 1 | 28 | | if (queryResult.IsSuccess) |
| | | 29 | | { |
| | 1 | 30 | | GrainState.State = queryResult.Value; |
| | 1 | 31 | | await GrainState.WriteStateAsync(); |
| | | 32 | | } |
| | | 33 | | else |
| | | 34 | | { |
| | 0 | 35 | | throw new InvalidOperationException( |
| | 0 | 36 | | $"Failed to query for {this.GetType().FullName}: {this.GetPrimaryKey()}"); |
| | | 37 | | } |
| | | 38 | | } |
| | | 39 | | |
| | 1 | 40 | | await base.OnActivateAsync(cancellationToken); |
| | 1 | 41 | | } |
| | | 42 | | |
| | | 43 | | public override async Task OnDeactivateAsync( |
| | | 44 | | DeactivationReason reason, |
| | | 45 | | CancellationToken cancellationToken) |
| | | 46 | | { |
| | 1 | 47 | | await GrainState.WriteStateAsync(); |
| | | 48 | | |
| | 1 | 49 | | var persistResult = await GrainRepository.Persist(this, GrainState.State); |
| | 1 | 50 | | if (persistResult.IsSuccess) |
| | | 51 | | { |
| | 1 | 52 | | await GrainState.ClearStateAsync(); |
| | | 53 | | } |
| | | 54 | | else |
| | | 55 | | { |
| | 0 | 56 | | throw new InvalidOperationException( |
| | 0 | 57 | | $"Failed to persist for {this.GetType().FullName}: {this.GetPrimaryKey()}"); |
| | | 58 | | } |
| | | 59 | | |
| | 1 | 60 | | await base.OnDeactivateAsync(reason, cancellationToken); |
| | 1 | 61 | | } |
| | | 62 | | } |