Beispiel #1
0
        protected async Task Reset()
        {
            await Over(OverType.DeleteAll);
            await RecoverySnapshot();

            await ObserverUnit.Reset(Snapshot.Base.StateId);
        }
Beispiel #2
0
        /// <summary>
        /// 依赖注入统一方法
        /// </summary>
        protected async virtual ValueTask DependencyInjection()
        {
            CoreOptions       = ServiceProvider.GetOptionsByName <CoreOptions>(GrainType.FullName);
            ArchiveOptions    = ServiceProvider.GetOptionsByName <ArchiveOptions>(GrainType.FullName);
            Logger            = (ILogger)ServiceProvider.GetService(typeof(ILogger <>).MakeGenericType(GrainType));
            ProducerContainer = ServiceProvider.GetService <IProducerContainer>();
            Serializer        = ServiceProvider.GetService <ISerializer>();
            TypeFinder        = ServiceProvider.GetService <ITypeFinder>();
            SnapshotHandler   = ServiceProvider.GetService <ISnapshotHandler <PrimaryKey, StateType> >();
            if (SnapshotHandler == default)
            {
                throw new UnfindSnapshotHandlerException(GrainType);
            }
            ObserverUnit          = ServiceProvider.GetService <IObserverUnitContainer>().GetUnit <PrimaryKey>(GrainType);
            ObserverEventHandlers = ObserverUnit.GetAllEventHandlers();
            var configureBuilder  = (IConfigureBuilder <PrimaryKey>)ServiceProvider.GetService(typeof(IConfigureBuilder <,>).MakeGenericType(typeof(PrimaryKey), GrainType));
            var storageConfigTask = configureBuilder.GetConfig(ServiceProvider, GrainId);

            if (!storageConfigTask.IsCompletedSuccessfully)
            {
                await storageConfigTask;
            }
            var storageFactory = ServiceProvider.GetService(configureBuilder.StorageFactory) as IStorageFactory;

            //创建归档存储器
            if (ArchiveOptions.On)
            {
                var archiveStorageTask = storageFactory.CreateArchiveStorage <PrimaryKey, StateType>(storageConfigTask.Result, GrainId);
                if (!archiveStorageTask.IsCompletedSuccessfully)
                {
                    await archiveStorageTask;
                }
                ArchiveStorage = archiveStorageTask.Result;
            }
            //创建事件存储器
            var eventStorageTask = storageFactory.CreateEventStorage(storageConfigTask.Result, GrainId);

            if (!eventStorageTask.IsCompletedSuccessfully)
            {
                await eventStorageTask;
            }
            EventStorage = eventStorageTask.Result;
            //创建状态存储器
            var stateStorageTask = storageFactory.CreateSnapshotStorage <PrimaryKey, StateType>(storageConfigTask.Result, GrainId);

            if (!stateStorageTask.IsCompletedSuccessfully)
            {
                await stateStorageTask;
            }
            SnapshotStorage = stateStorageTask.Result;
            //创建事件发布器
            var producerTask = ProducerContainer.GetProducer(GrainType);

            if (!producerTask.IsCompletedSuccessfully)
            {
                await producerTask;
            }
            EventBusProducer = producerTask.Result;
        }
Beispiel #3
0
        protected async Task Over()
        {
            if (Snapshot.Base.IsOver)
            {
                throw new StateIsOverException(Snapshot.Base.StateId.ToString(), GrainType);
            }
            if (Snapshot.Base.Version != Snapshot.Base.DoingVersion)
            {
                throw new StateInsecurityException(Snapshot.Base.StateId.ToString(), GrainType, Snapshot.Base.DoingVersion, Snapshot.Base.Version);
            }
            if (ArchiveOptions.On && ArchiveOptions.ArchiveEventOnOver)
            {
                var versions = await ObserverUnit.GetAndSaveVersion(Snapshot.Base.StateId, Snapshot.Base.Version);

                if (versions.Any(v => v < Snapshot.Base.Version))
                {
                    throw new ObserverNotCompletedException(GrainType.FullName, Snapshot.Base.StateId.ToString());
                }
            }
            Snapshot.Base.IsOver   = true;
            Snapshot.Base.IsLatest = true;
            if (SnapshotEventVersion != Snapshot.Base.Version)
            {
                var saveTask = SaveSnapshotAsync(true, true);
                if (!saveTask.IsCompletedSuccessfully)
                {
                    await saveTask;
                }
            }
            else
            {
                await SnapshotStorage.Over(Snapshot.Base.StateId, true);
            }
            if (ArchiveOptions.On && ArchiveOptions.ArchiveEventOnOver)
            {
                await ArchiveStorage.DeleteAll(Snapshot.Base.StateId);

                if (ArchiveOptions.EventArchiveType == EventArchiveType.Delete)
                {
                    await EventStorage.DeleteStart(Snapshot.Base.StateId, Snapshot.Base.Version, Snapshot.Base.StartTimestamp);
                }
                else
                {
                    await ArchiveStorage.EventArichive(Snapshot.Base.StateId, Snapshot.Base.Version, Snapshot.Base.StartTimestamp);
                }
            }
            else
            {
                await ArchiveStorage.Over(Snapshot.Base.StateId, true);
            }
        }
Beispiel #4
0
 public async Task FinishTransaction(long transactionId)
 {
     if (CurrentTransactionId == transactionId)
     {
         //如果副本快照没有更新,则更新副本集
         foreach (var transport in WaitingForTransactionTransports)
         {
             var task = OnRaised(transport.FullyEvent, transport.BytesTransport);
             if (!task.IsCompletedSuccessfully)
             {
                 await task;
             }
         }
         var onFinishTask = OnFinshTransaction(transactionId);
         if (!onFinishTask.IsCompletedSuccessfully)
         {
             await onFinishTask;
         }
         var saveSnapshotTask = SaveSnapshotAsync();
         if (!saveSnapshotTask.IsCompletedSuccessfully)
         {
             await saveSnapshotTask;
         }
         var handlers = ObserverUnit.GetAllEventHandlers();
         if (handlers.Count > 0)
         {
             try
             {
                 foreach (var transport in WaitingForTransactionTransports)
                 {
                     await PublishToEventBus(transport.BytesTransport.GetBytes(), transport.HashKey);
                 }
             }
             catch (Exception ex)
             {
                 Logger.LogError(ex, ex.Message);
             }
         }
         WaitingForTransactionTransports.Clear();
         RestoreTransactionTemporaryState();
         TransactionSemaphore.Release();
     }
 }
Beispiel #5
0
        protected async Task Over(OverType overType)
        {
            if (Snapshot.Base.IsOver)
            {
                throw new StateIsOverException(Snapshot.Base.StateId.ToString(), GrainType);
            }
            if (Snapshot.Base.Version != Snapshot.Base.DoingVersion)
            {
                throw new StateInsecurityException(Snapshot.Base.StateId.ToString(), GrainType, Snapshot.Base.DoingVersion, Snapshot.Base.Version);
            }
            if (overType != OverType.None)
            {
                var versions = await ObserverUnit.GetAndSaveVersion(Snapshot.Base.StateId, Snapshot.Base.Version);

                if (versions.Any(v => v < Snapshot.Base.Version))
                {
                    throw new ObserverNotCompletedException(GrainType.FullName, Snapshot.Base.StateId.ToString());
                }
            }
            Snapshot.Base.IsOver   = true;
            Snapshot.Base.IsLatest = true;
            if (SnapshotEventVersion != Snapshot.Base.Version)
            {
                var saveTask = SaveSnapshotAsync(true, true);
                if (!saveTask.IsCompletedSuccessfully)
                {
                    await saveTask;
                }
            }
            else
            {
                await SnapshotStorage.Over(Snapshot.Base.StateId, true);
            }
            if (overType == OverType.ArchivingEvent)
            {
                if (ArchiveOptions.On)
                {
                    await DeleteAllArchive();
                }
                await ArchiveStorage.EventArichive(Snapshot.Base.StateId, Snapshot.Base.Version, Snapshot.Base.StartTimestamp);
            }
            else if (overType == OverType.DeleteEvent)
            {
                if (ArchiveOptions.On)
                {
                    await DeleteAllArchive();
                }
                await EventStorage.DeletePrevious(Snapshot.Base.StateId, Snapshot.Base.Version, Snapshot.Base.StartTimestamp);
            }
            else if (overType == OverType.DeleteAll)
            {
                if (ArchiveOptions.On)
                {
                    await DeleteAllArchive();
                }
                await EventStorage.DeletePrevious(Snapshot.Base.StateId, Snapshot.Base.Version, Snapshot.Base.StartTimestamp);

                if (SnapshotEventVersion > 0)
                {
                    await SnapshotStorage.Delete(GrainId);

                    SnapshotEventVersion = 0;
                }
            }
            else if (ArchiveOptions.On && BriefArchiveList.Count > 0)
            {
                await ArchiveStorage.Over(Snapshot.Base.StateId, true);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Grain激活时调用用来初始化的方法(禁止在子类重写)
        /// </summary>
        /// <returns></returns>
        public override async Task OnActivateAsync()
        {
            var dITask = DependencyInjection();

            if (!dITask.IsCompletedSuccessfully)
            {
                await dITask;
            }
            try
            {
                if (ArchiveOptions.On)
                {
                    //加载归档信息
                    BriefArchiveList = (await ArchiveStorage.GetBriefList(GrainId)).OrderBy(a => a.Index).ToList();
                    LastArchive      = BriefArchiveList.LastOrDefault();
                    ClearedArchive   = BriefArchiveList.Where(a => a.EventIsCleared).OrderByDescending(a => a.Index).FirstOrDefault();
                    var secondLastArchive = BriefArchiveList.Count > 1 ? BriefArchiveList.SkipLast(1).Last() : default;
                    if (LastArchive != null && !LastArchive.IsCompletedArchive(ArchiveOptions, secondLastArchive) && !LastArchive.EventIsCleared)
                    {
                        await DeleteArchive(LastArchive.Id);

                        BriefArchiveList.Remove(LastArchive);
                        NewArchive  = LastArchive;
                        LastArchive = BriefArchiveList.LastOrDefault();
                    }
                }
                //修复状态
                await RecoverySnapshot();

                if (ArchiveOptions.On)
                {
                    if (Snapshot.Base.Version != 0 &&
                        (LastArchive is null || LastArchive.EndVersion < Snapshot.Base.Version) &&
                        (NewArchive is null || NewArchive.EndVersion < Snapshot.Base.Version))
                    {
                        //归档恢复
                        while (true)
                        {
                            var  startTimestamp = Snapshot.Base.StartTimestamp;
                            long startVersion   = 0;
                            if (NewArchive != null)
                            {
                                startVersion   = NewArchive.EndVersion;
                                startTimestamp = NewArchive.StartTimestamp;
                            }
                            else if (NewArchive is null && LastArchive != null)
                            {
                                startVersion   = LastArchive.EndVersion;
                                startTimestamp = LastArchive.EndTimestamp;
                            }
                            var eventList = await EventStorage.GetList(GrainId, startTimestamp, startVersion + 1, startVersion + CoreOptions.NumberOfEventsPerRead);

                            foreach (var @event in eventList)
                            {
                                var task = EventArchive(@event);
                                if (!task.IsCompletedSuccessfully)
                                {
                                    await task;
                                }
                            }
                            if (eventList.Count < CoreOptions.NumberOfEventsPerRead)
                            {
                                break;
                            }
                        }
                        ;
                    }
                }
                if (CoreOptions.SyncAllObserversOnActivate)
                {
                    var syncResults = await ObserverUnit.SyncAllObservers(GrainId, Snapshot.Base.Version);

                    if (syncResults.Any(r => !r))
                    {
                        throw new SyncAllObserversException(GrainId.ToString(), GrainType);
                    }
                }
                var onActivatedTask = OnActivationCompleted();
                if (!onActivatedTask.IsCompletedSuccessfully)
                {
                    await onActivatedTask;
                }
                if (Logger.IsEnabled(LogLevel.Trace))
                {
                    Logger.LogTrace("Activation completed: {0}->{1}", GrainType.FullName, Serializer.Serialize(Snapshot));
                }
            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex, "Activation failed: {0}->{1}", GrainType.FullName, GrainId.ToString());
                throw;
            }
        }
Beispiel #7
0
        public async Task FinishTransaction(long transactionId)
        {
            if (CurrentTransactionId == transactionId)
            {
                //如果副本快照没有更新,则更新副本集
                foreach (var transport in WaitingForTransactionTransports)
                {
                    var task = OnRaiseSuccessed(transport.FullyEvent, transport.BytesTransport);
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }
                }
                var onFinishTask = OnFinshTransaction(transactionId);
                if (!onFinishTask.IsCompletedSuccessfully)
                {
                    await onFinishTask;
                }
                var saveSnapshotTask = SaveSnapshotAsync();
                if (!saveSnapshotTask.IsCompletedSuccessfully)
                {
                    await saveSnapshotTask;
                }
                var handlers = ObserverUnit.GetAllEventHandlers();
                if (handlers.Count > 0)
                {
                    try
                    {
                        foreach (var transport in WaitingForTransactionTransports)
                        {
                            if (CoreOptions.PriorityAsyncEventBus)
                            {
                                try
                                {
                                    var publishTask = EventBusProducer.Publish(transport.BytesTransport.GetBytes(), transport.HashKey);
                                    if (!publishTask.IsCompletedSuccessfully)
                                    {
                                        await publishTask;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogError(ex, ex.Message);

                                    //当消息队列出现问题的时候同步推送
                                    await Task.WhenAll(handlers.Select(func => func(transport.BytesTransport.GetBytes())));
                                }
                            }
                            else
                            {
                                try
                                {
                                    await Task.WhenAll(handlers.Select(func => func(transport.BytesTransport.GetBytes())));
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogError(ex, ex.Message);
                                    //当消息队列出现问题的时候异步推送
                                    var publishTask = EventBusProducer.Publish(transport.BytesTransport.GetBytes(), transport.HashKey);
                                    if (!publishTask.IsCompletedSuccessfully)
                                    {
                                        await publishTask;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex, ex.Message);
                    }
                }
                WaitingForTransactionTransports.Clear();
                RestoreTransactionTemporaryState();
                TransactionSemaphore.Release();
            }
        }