protected async ValueTask SaveSnapshotAsync(bool force = false, bool isLatest = false) { if (Snapshot.Base.Version != Snapshot.Base.DoingVersion) { throw new StateInsecurityException(Snapshot.Base.StateId.ToString(), GrainType, Snapshot.Base.DoingVersion, Snapshot.Base.Version); } if (Logger.IsEnabled(LogLevel.Trace)) { Logger.LogTrace(LogEventIds.GrainSnapshot, "Start save snapshot with Id = {0} ,state version = {1}", GrainId.ToString(), Snapshot.Base.Version); } //如果版本号差超过设置则更新快照 if (force || (Snapshot.Base.Version - SnapshotEventVersion >= CoreOptions.SnapshotIntervalVersion)) { var oldLatestMinEventTimestamp = Snapshot.Base.LatestMinEventTimestamp; try { var onSaveSnapshotTask = OnStartSaveSnapshot(); if (!onSaveSnapshotTask.IsCompletedSuccessfully) { await onSaveSnapshotTask; } Snapshot.Base.LatestMinEventTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Snapshot.Base.IsLatest = isLatest; if (SnapshotEventVersion == 0) { await SnapshotStorage.Insert(Snapshot); } else { await SnapshotStorage.Update(Snapshot); } SnapshotEventVersion = Snapshot.Base.Version; if (Logger.IsEnabled(LogLevel.Trace)) { Logger.LogTrace(LogEventIds.GrainSnapshot, "The snapshot of id={0} save completed ,state version = {1}", GrainId.ToString(), Snapshot.Base.Version); } } catch (Exception ex) { Snapshot.Base.LatestMinEventTimestamp = oldLatestMinEventTimestamp; if (Logger.IsEnabled(LogLevel.Critical)) { Logger.LogCritical(LogEventIds.GrainSnapshot, ex, "The snapshot of id= {0} save failed", GrainId.ToString()); } throw; } } }
protected async ValueTask SaveSnapshotAsync(bool force = false, bool isLatest = false) { if (Snapshot.Base.Version != Snapshot.Base.DoingVersion) { throw new StateInsecurityException(Snapshot.Base.StateId.ToString(), GrainType, Snapshot.Base.DoingVersion, Snapshot.Base.Version); } //如果版本号差超过设置则更新快照 if ((force && Snapshot.Base.Version > SnapshotEventVersion) || (Snapshot.Base.Version - SnapshotEventVersion >= CoreOptions.SnapshotVersionInterval)) { var oldLatestMinEventTimestamp = Snapshot.Base.LatestMinEventTimestamp; try { var onSaveSnapshotTask = OnStartSaveSnapshot(); if (!onSaveSnapshotTask.IsCompletedSuccessfully) { await onSaveSnapshotTask; } Snapshot.Base.LatestMinEventTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Snapshot.Base.IsLatest = isLatest; if (SnapshotEventVersion == 0) { await SnapshotStorage.Insert(Snapshot); } else { await SnapshotStorage.Update(Snapshot); } SnapshotEventVersion = Snapshot.Base.Version; if (Logger.IsEnabled(LogLevel.Trace)) { Logger.LogTrace("SaveSnapshot completed: {0}->{1}", GrainType.FullName, Serializer.Serialize(Snapshot)); } } catch (Exception ex) { Snapshot.Base.LatestMinEventTimestamp = oldLatestMinEventTimestamp; Logger.LogCritical(ex, "SaveSnapshot failed: {0}->{1}", GrainType.FullName, GrainId.ToString()); throw; } } }