Пример #1
0
        private static void VerifySnapshotCount(
            SnapshotHandler handler,
            double expectedCont)
        {
            var count = handler.SnapshotCount;

            FailTestIf(count != expectedCont, "count={0} expected={1}", count, expectedCont);
        }
Пример #2
0
        public override async Task OnActivateAsync()
        {
            await base.OnActivateAsync();

            if (!(SnapshotHandler is DTxSnapshotHandler <PrimaryKey, StateType>))
            {
                throw new SnapshotHandlerTypeException(SnapshotHandler.GetType().FullName);
            }
        }
Пример #3
0
 protected virtual ValueTask OnEventDelivered(IFullyEvent <PrimaryKey> @event)
 {
     if (Logger.IsEnabled(LogLevel.Trace))
     {
         Logger.LogTrace("OnEventDelivered: {0}({1})", @event.GetType().FullName, Serializer.Serialize(@event, @event.GetType()));
     }
     SnapshotHandler.Apply(Snapshot, @event);
     return(Consts.ValueTaskDone);
 }
Пример #4
0
    // Update is called once per frame
    void Update()
    {
        time     += Time.deltaTime;
        acumTime += Time.deltaTime;

        if (acumTime >= (1.0f / fps))
        {
            frame++;
            acumTime -= (1.0f / fps);
            Packet packet = PacketQueue.GetInstance().PollPacket();
            while (packet != null)
            {
                foreach (var gm in packet.Messages)
                {
                    handler.Handle(gm);
                }
                packet = PacketQueue.GetInstance().PollPacket();
            }

            foreach (var action in player.toSend)
            {
                outgoingMessages.Add(action);
            }
            player.toSend.Clear();

            foreach (var gm in outgoingMessages)
            {
                if (gm.isReliable())
                {
                    if (MessageType.PlayerInput.Equals(gm.type()))
                    {
                        rq.AddQueueWithOutTimeout((ReliableMessage)gm);
                    }
                    else
                    {
                        rq.AddQueueWithTimeout((ReliableMessage)gm, time);
                    }
                }
            }

            Dictionary <int, PlayerSnapshot> currentSnapshot = SnapshotHandler.GetInstance().getSnapshot(time);
            if (currentSnapshot != null)
            {
                SnapshotHandler.GetInstance().updatePlayer(currentSnapshot);
            }

            outgoingMessages.AddRange(rq.MessageToResend(time));
            Debug.Log("Outgoing messages size: " + outgoingMessages.Count);
            if (outgoingMessages.Count > 0)
            {
                Packet p     = new Packet(outgoingMessages);
                byte[] bytes = p.serialize();
                SendUdp(bytes);
                outgoingMessages.Clear();
            }
        }
    }
Пример #5
0
        public Camera()
        {
            InitializeComponent();

            _imageProvider = new DrawingImageProvider();
            videoViewerWF1.SetImageProvider(_imageProvider);

            _connector       = new MediaConnector();
            _snapshotHandler = new SnapshotHandler();
        }
Пример #6
0
        public HomeForm()
        {
            InitializeComponent();

            //camera
            globalImageProvider   = new DrawingImageProvider();
            globalMediaConnector  = new MediaConnector();
            globalSnapshotHandler = new SnapshotHandler();
            connectUsbCamera();
        }
Пример #7
0
        public ConcurrentRenderer(
            Func <Action, Task> queueDrawFunc,
            DrawDelegate drawAction,
            Action drawCompleteAction
            )
        {
            _drawAction         = drawAction;
            _drawCompleteAction = drawCompleteAction;
            _queueDrawFunc      = queueDrawFunc;

            _snapshotHandler = new SnapshotHandler(this);
        }
Пример #8
0
 protected virtual ValueTask OnEventDelivered(IFullyEvent <PrimaryKey> @event)
 {
     try
     {
         SnapshotHandler.Apply(Snapshot, @event);
     }
     catch (Exception ex)
     {
         Logger.LogCritical(ex, "Delivered failed: {0}->{1}->{2}", GrainType.FullName, GrainId.ToString(), Serializer.Serialize(@event, @event.GetType()));
     }
     return(Consts.ValueTaskDone);
 }
Пример #9
0
        public CameraConnection(XmlCamera settings)
        {
            this.active    = false;
            this.Settings  = settings;
            this.webClient = new WebClient();

            // set the variables
            this.Log = LogManager.GetLogger("Camera - " + this.Name);

            this.motionHandler   = new MotionHandler(this);
            this.snapshotHandler = new SnapshotHandler(this);
        }
Пример #10
0
        public Camera()
        {
            Detector             = new MotionDetector();
            BitmapSourceProvider = new BitmapSourceProvider();
            Connector            = new MediaConnector();
            VadFilter            = new VADFilter {
                Enabled = false, ActivationLevel = 40
            };
            Snapshot = new SnapshotHandler();

            VadFilter.VoiceDetected += VadFilterVoiceDetected;
            Duration = 10;
        }
Пример #11
0
    private void handleWorldSnapshot(WorldSnapshotMessage wm)
    {
        float time = wm._playerSnapshots[0]._TimeStamp;
        Dictionary <int, PlayerSnapshot> worldSnap = new Dictionary <int, PlayerSnapshot>();


        foreach (PlayerSnapshot wmPlayerSnapshot in wm._playerSnapshots)
        {
            worldSnap.Add(wmPlayerSnapshot.id, wmPlayerSnapshot);
        }

        SnapshotHandler.GetInstance().ReceiveSnapshot(worldSnap, time);
    }
Пример #12
0
        /// </summary>

        public UserControl_Flight()
        {
            InitializeComponent();
            getAvailablePorts();

            // Create video viewer UI control
            _imageProvider   = new DrawingImageProvider();
            _connector       = new MediaConnector();
            _snapshotHandler = new SnapshotHandler();
            _videoViewerWF1  = new VideoViewerWF();
            setVideoViewer();

            buttonDisconnect.Enabled = false;
            _points = new List <PointLatLng>();
        }
Пример #13
0
 /// <summary>
 /// 防止对象在Snapshot和BackupSnapshot中互相干扰,所以反序列化一个全新的Event对象给BackupSnapshot
 /// </summary>
 /// <param name="fullyEvent">事件本体</param>
 /// <param name="bytes">事件序列化之后的二进制数据</param>
 protected override ValueTask OnRaised(FullyEvent <PrimaryKey> fullyEvent, EventBytesTransport transport)
 {
     if (BackupSnapshot.Base.Version + 1 == fullyEvent.Base.Version)
     {
         var copiedEvent = new FullyEvent <PrimaryKey>
         {
             Event = Serializer.Deserialize(transport.EventBytes, fullyEvent.Event.GetType()) as IEvent,
             Base  = EventBase.FromBytes(transport.BaseBytes)
         };
         SnapshotHandler.Apply(BackupSnapshot, copiedEvent);
         BackupSnapshot.Base.FullUpdateVersion(copiedEvent.Base, GrainType);//更新处理完成的Version
     }
     //父级涉及状态归档
     return(base.OnRaised(fullyEvent, transport));
 }
Пример #14
0
    // Update is called once per frame
    void Update()
    {
        time     += Time.deltaTime;
        acumTime += Time.deltaTime;

        if (Input.GetKey(KeyCode.W))
        {
            frameActions.Add(PlayerAction.MoveForward);
        }
        if (Input.GetKey(KeyCode.A))
        {
            frameActions.Add(PlayerAction.MoveLeft);
        }
        if (Input.GetKey(KeyCode.S))
        {
            frameActions.Add(PlayerAction.MoveBack);
        }
        if (Input.GetKey(KeyCode.D))
        {
            frameActions.Add(PlayerAction.MoveRight);
        }

        if (Input.GetMouseButtonDown(0))
        {
            Shoot();
            toSend.Add(new PlayerInputMessage(PlayerAction.Shoot, time, true));
        }

        if (acumTime >= (1.0f / GlobalSettings.Fps))
        {
            acumTime -= (1.0f / GlobalSettings.Fps);
            foreach (var action in frameActions)
            {
                PlayerInputMessage msg = new PlayerInputMessage(action, time, true);
                toSend.Add(msg);
                if (SnapshotHandler.GetInstance().prediction)
                {
                    actions.Enqueue(msg);
                    applyAction(action);
                }
            }
            toSend.Add(new RotationMessage(this.gameObject.transform.eulerAngles));
            frameActions.Clear();
        }

        camera.transform.position = this.gameObject.transform.position;
        camera.transform.rotation = this.gameObject.transform.rotation;
    }
Пример #15
0
 public LiveView()
 {
     InitializeComponent();
     _bitmapSourceProvider1 = new DrawingImageProvider();
     _bitmapSourceProvider2 = new DrawingImageProvider();
     _bitmapSourceProvider3 = new DrawingImageProvider();
     _connector1            = new MediaConnector();
     _connector2            = new MediaConnector();
     _connector3            = new MediaConnector();
     _snapShot1             = new SnapshotHandler();
     _snapShot2             = new SnapshotHandler();
     _snapShot3             = new SnapshotHandler();
     videoViewerWF1.SetImageProvider(_bitmapSourceProvider1);
     videoViewerWF2.SetImageProvider(_bitmapSourceProvider2);
     videoViewerWF3.SetImageProvider(_bitmapSourceProvider3);
 }
Пример #16
0
    // Use this for initialization
    void Start()
    {
        player           = GameObject.Find("Player").GetComponent <Player>();
        player.name      = playerName;
        outgoingMessages = new List <GameMessage>();
        rq = new ReliableQueue(GlobalSettings.ReliableTimeout);
        rq.AddQueueWithTimeout(new ClientConnectMessage(playerName, time, true), 0);
        otherPlayers = new Dictionary <int, ServerPlayer>();
        handler      = new ClientMessageHandler(this);
        SnapshotHandler.GetInstance().otherPlayers = this.otherPlayers;
        SnapshotHandler.GetInstance().self         = this.player;
        SnapshotHandler.GetInstance().prediction   = this.prediction;
        Thread thread = new Thread(new ThreadStart(ThreadMethod));

        thread.Start();
    }
Пример #17
0
 /// <summary>
 /// 事务性事件提交
 /// 使用该函数前必须开启事务,不然会出现异常
 /// </summary>
 /// <param name="event"></param>
 /// <param name="uniqueId"></param>
 protected void TxRaiseEvent(IEvent @event, EventUID uniqueId = null)
 {
     if (Logger.IsEnabled(LogLevel.Trace))
     {
         Logger.LogTrace("Start transactionRaiseEvent, grain Id ={0} and state version = {1},event type = {2} ,event = {3},uniqueueId = {4}", GrainId.ToString(), Snapshot.Base.Version, @event.GetType().FullName, Serializer.SerializeToString(@event), uniqueId);
     }
     try
     {
         if (CurrentTransactionStartVersion == -1)
         {
             throw new UnopenedTransactionException(GrainId.ToString(), GrainType, nameof(TxRaiseEvent));
         }
         Snapshot.Base.IncrementDoingVersion(GrainType);//标记将要处理的Version
         var fullyEvent = new FullyEvent <PrimaryKey>
         {
             StateId = GrainId,
             Event   = @event,
             Base    = new EventBase
             {
                 Version = Snapshot.Base.Version + 1
             }
         };
         if (uniqueId == default)
         {
             uniqueId = EventUID.Empty;
         }
         if (string.IsNullOrEmpty(uniqueId.UID))
         {
             fullyEvent.Base.Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
         }
         else
         {
             fullyEvent.Base.Timestamp = uniqueId.Timestamp;
         }
         WaitingForTransactionTransports.Add(new EventTransport <PrimaryKey>(fullyEvent, uniqueId.UID, fullyEvent.StateId.ToString()));
         SnapshotHandler.Apply(Snapshot, fullyEvent);
         Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType);//更新处理完成的Version
     }
     catch (Exception ex)
     {
         Logger.LogCritical(ex, "Grain Id = {0},event type = {1} and event = {2}", GrainId.ToString(), @event.GetType().FullName, Serializer.SerializeToString(@event));
         Snapshot.Base.DecrementDoingVersion();//还原doing Version
         throw;
     }
 }
Пример #18
0
 /// <summary>
 /// 事务性事件提交
 /// 使用该函数前必须开启事务,不然会出现异常
 /// </summary>
 /// <param name="event"></param>
 /// <param name="eUID"></param>
 protected void TxRaiseEvent(IEvent @event, EventUID eUID = null)
 {
     try
     {
         if (CurrentTransactionStartVersion == -1)
         {
             throw new UnopenedTransactionException(GrainId.ToString(), GrainType, nameof(TxRaiseEvent));
         }
         Snapshot.Base.IncrementDoingVersion(GrainType);//标记将要处理的Version
         var fullyEvent = new FullyEvent <PrimaryKey>
         {
             StateId = GrainId,
             Event   = @event,
             Base    = new EventBase
             {
                 Version = Snapshot.Base.Version + 1
             }
         };
         string unique = default;
         if (eUID is null)
         {
             fullyEvent.Base.Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
             unique = fullyEvent.GetEventId();
         }
         else
         {
             fullyEvent.Base.Timestamp = eUID.Timestamp;
             unique = eUID.UID;
         }
         WaitingForTransactionTransports.Add(new EventTransport <PrimaryKey>(fullyEvent, unique, fullyEvent.StateId.ToString()));
         SnapshotHandler.Apply(Snapshot, fullyEvent);
         Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType);//更新处理完成的Version
         if (Logger.IsEnabled(LogLevel.Trace))
         {
             Logger.LogTrace("TxRaiseEvent completed: {0}->{1}->{2}", GrainType.FullName, Serializer.Serialize(fullyEvent), Serializer.Serialize(Snapshot));
         }
     }
     catch (Exception ex)
     {
         Logger.LogCritical(ex, "TxRaiseEvent failed: {0}->{1}->{2}", GrainType.FullName, Serializer.Serialize(@event, @event.GetType()), Serializer.Serialize(Snapshot));
         Snapshot.Base.DecrementDoingVersion();//还原doing Version
         throw;
     }
 }
Пример #19
0
        public void SnapshotTest()
        {
            TestCase("### SnapshotTest ###");

            var snapshotHandler  = new SnapshotHandler();
            var snapshotInterval = UpperBoundBuffer * 2;
            var timeManager      = new VolatileLogicalTimeManager(snapshotHandler, GetTimestamp(snapshotInterval));

            VerifySnapshotTime(timeManager, 0);
            VerifySnapshotCount(snapshotHandler, 0);

            timeManager.Start();

            WaitForSnapshotCount(snapshotHandler, 1, true, GetTimestamp(snapshotInterval + UpperBoundBuffer));

            VerifyCurrentTime(timeManager, snapshotInterval);
            VerifySnapshotTime(timeManager, snapshotInterval);

            WaitForSnapshotCount(snapshotHandler, 2, true, GetTimestamp(snapshotInterval + UpperBoundBuffer));

            VerifyCurrentTime(timeManager, snapshotInterval * 2);
            VerifySnapshotTime(timeManager, snapshotInterval * 2);

            timeManager.Stop();

            WaitForSnapshotCount(snapshotHandler, 2, false, GetTimestamp(snapshotInterval));

            VerifyCurrentTime(timeManager, snapshotInterval * 3);
            VerifySnapshotTime(timeManager, snapshotInterval * 2);

            timeManager.Start();

            WaitForSnapshotCount(snapshotHandler, 3, true, GetTimestamp(snapshotInterval + UpperBoundBuffer));

            VerifyCurrentTime(timeManager, snapshotInterval * 3);
            VerifySnapshotTime(timeManager, snapshotInterval * 3);

            timeManager.Stop();

            WaitForSnapshotCount(snapshotHandler, 3, false, GetTimestamp(snapshotInterval));

            VerifyCurrentTime(timeManager, snapshotInterval * 4);
            VerifySnapshotTime(timeManager, snapshotInterval * 3);
        }
Пример #20
0
        public void CurrentLogicalTimeTest()
        {
            TestCase("### CurrentLogicalTimeTest ###");

            var snapshotHandler  = new SnapshotHandler();
            var snapshotInterval = UpperBoundBuffer;
            var timeManager      = new VolatileLogicalTimeManager(snapshotHandler, GetTimestamp(snapshotInterval));

            VerifyCurrentTime(timeManager, 0);
            VerifySnapshotTime(timeManager, 0);

            Thread.Sleep(GetTimestamp(2));

            VerifyCurrentTime(timeManager, 2);
            VerifySnapshotTime(timeManager, 0);

            Thread.Sleep(GetTimestamp(3));

            VerifyCurrentTime(timeManager, 5);
            VerifySnapshotTime(timeManager, 0);

            Thread.Sleep(GetTimestamp(3));

            VerifyCurrentTime(timeManager, 8);
            VerifySnapshotTime(timeManager, 0);

            timeManager.CurrentLogicalTime = GetTimestamp(1);

            VerifyCurrentTime(timeManager, 1);
            VerifySnapshotTime(timeManager, 1);

            timeManager.CurrentLogicalTime = GetTimestamp(5);

            VerifyCurrentTime(timeManager, 5);
            VerifySnapshotTime(timeManager, 5);

            timeManager.CurrentLogicalTime = GetTimestamp(15);

            Thread.Sleep(GetTimestamp(1));

            VerifyCurrentTime(timeManager, 16);
            VerifySnapshotTime(timeManager, 15);
        }
Пример #21
0
        //--------------------------------------------------------------------------------
        /// <summary>
        /// This method serves as a common constructor initialization location,
        /// and serves mainly to set the desired size of the container panel in
        /// the wizard form (see WizardFormBase for more info).  I didn't want
        /// to do this here but it was the only way I could get the form to
        /// resize itself appropriately - it needed to size itself according
        /// to the size of the largest wizard page.
        /// </summary>
        public void InitPage()
        {
            InitializeComponent();
            _mediaConnector       = new MediaConnector();
            _imageProvider        = new DrawingImageProvider();
            _snapshotHandler      = new SnapshotHandler();
            _videoViewer          = new VideoViewerWF();
            timAnimation          = new System.Windows.Forms.Timer();
            timAnimation.Interval = 200;
            timAnimation.Tick    += new System.EventHandler(this.timAnimation_Tick);
            //==================

            _webCamera = WebCamera.GetDefaultDevice();
            SetVideoViewer();
            base.Size = this.Size;
            this.ParentWizardForm.DiscoverPagePanelSize(this.Size);
            this.panelVideo.Controls.Add(_videoViewer);
            clsGlobalVariables.SnapshotFilesDirectory = @"C:\iPrint\iPrintCamera\";
        }
        public Form1()
        {
            InitializeComponent();
            showPowerStatus();
            getAvailablePorts();
            buttonDisconnect.Enabled = false;

            // Create Video Viewer UI Controller
            _imageProvider   = new DrawingImageProvider();
            _connector       = new MediaConnector();
            _snapshotHandler = new SnapshotHandler();
            _videoViewerWF1  = new VideoViewerWF();
            setVideoViewer();

            _points = new List <PointLatLng>();
            _jalur  = new List <PointLatLng>();

            timer1.Start();
        }
Пример #23
0
        protected virtual async Task RecoverySnapshot()
        {
            try
            {
                await ReadSnapshotAsync();

                while (!Snapshot.Base.IsLatest)
                {
                    var eventList = await EventStorage.GetList(GrainId, Snapshot.Base.LatestMinEventTimestamp, Snapshot.Base.Version + 1, Snapshot.Base.Version + CoreOptions.NumberOfEventsPerRead);

                    foreach (var fullyEvent in eventList)
                    {
                        Snapshot.Base.IncrementDoingVersion(GrainType);          //标记将要处理的Version
                        SnapshotHandler.Apply(Snapshot, fullyEvent);
                        Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType); //更新处理完成的Version
                    }
                    if (eventList.Count < CoreOptions.NumberOfEventsPerRead)
                    {
                        break;
                    }
                }
                ;
                if (Snapshot.Base.Version - SnapshotEventVersion >= CoreOptions.MinSnapshotVersionInterval)
                {
                    var saveTask = SaveSnapshotAsync(true, true);
                    if (!saveTask.IsCompletedSuccessfully)
                    {
                        await saveTask;
                    }
                }
                if (Logger.IsEnabled(LogLevel.Trace))
                {
                    Logger.LogTrace("Recovery completed: {0}->{1}", GrainType.FullName, Serializer.Serialize(Snapshot));
                }
            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex, "Recovery failed: {0}->{1}", GrainType.FullName, GrainId.ToString());
                throw;
            }
        }
Пример #24
0
        protected virtual async Task RecoverySnapshot()
        {
            if (Logger.IsEnabled(LogLevel.Trace))
            {
                Logger.LogTrace("The state of id = {0} begin to recover", GrainId.ToString());
            }
            try
            {
                await ReadSnapshotAsync();

                while (!Snapshot.Base.IsLatest)
                {
                    var eventList = await EventStorage.GetList(GrainId, Snapshot.Base.LatestMinEventTimestamp, Snapshot.Base.Version + 1, Snapshot.Base.Version + CoreOptions.NumberOfEventsPerRead);

                    foreach (var fullyEvent in eventList)
                    {
                        Snapshot.Base.IncrementDoingVersion(GrainType);          //标记将要处理的Version
                        SnapshotHandler.Apply(Snapshot, fullyEvent);
                        Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType); //更新处理完成的Version
                    }
                    if (eventList.Count < CoreOptions.NumberOfEventsPerRead)
                    {
                        break;
                    }
                }
                ;
                if (Logger.IsEnabled(LogLevel.Trace))
                {
                    Logger.LogTrace("The state of id = {0} recovery has been completed ,state version = {1}", GrainId.ToString(), Snapshot.Base.Version);
                }
            }
            catch (Exception ex)
            {
                Logger.LogCritical(ex, "The state of id = {0} recovery has failed ,state version = {1}", GrainId.ToString(), Snapshot.Base.Version);
                throw;
            }
        }
Пример #25
0
        private static void WaitForSnapshotCount(
            SnapshotHandler handler,
            double expectedCount,
            bool breakOnMatch,
            TimeSpan timeout)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            double count = 0;

            while (stopwatch.Elapsed < timeout)
            {
                count = handler.SnapshotCount;

                if (breakOnMatch && count == expectedCount)
                {
                    break;
                }
                else
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(100));
                }
            }

            stopwatch.Stop();

            FailTestIf(
                count != expectedCount,
                "WaitForSnapshotCount(): count={0} expected={1} break={2} timeout={3}",
                count,
                expectedCount,
                breakOnMatch,
                timeout);
        }
Пример #26
0
 protected virtual ValueTask OnEventDelivered(IFullyEvent <PrimaryKey> @event)
 {
     SnapshotHandler.Apply(Snapshot, @event);
     return(Consts.ValueTaskDone);
 }
Пример #27
0
        public Camera()
        {
            Detector = new MotionDetector();
            BitmapSourceProvider = new BitmapSourceProvider();
            Connector = new MediaConnector();
            VadFilter = new VADFilter { Enabled = false, ActivationLevel = 40 };
            Snapshot = new SnapshotHandler();

            VadFilter.VoiceDetected += VadFilterVoiceDetected;
            Duration = 10;
        }
Пример #28
0
 public IpCameraHandler()
 {
     //ImageProvider = new DrawingImageProvider();
     Snapshot  = new SnapshotHandler();
     Connector = new MediaConnector();
 }
Пример #29
0
 public static SnapshotHandler GetInstance()
 {
     return(_instance ?? (_instance = new SnapshotHandler(-1, -1)));
 }
Пример #30
0
        protected virtual async Task <bool> RaiseEvent(IEvent @event, EventUID eUID = null)
        {
            if (Logger.IsEnabled(LogLevel.Trace))
            {
                Logger.LogTrace("Start raise event, grain Id ={0} and state version = {1},event type = {2} ,event ={3},uniqueueId= {4}", GrainId.ToString(), Snapshot.Base.Version, @event.GetType().FullName, Serializer.SerializeToString(@event), eUID);
            }
            if (Snapshot.Base.IsOver)
            {
                throw new StateIsOverException(Snapshot.Base.StateId.ToString(), GrainType);
            }
            try
            {
                var fullyEvent = new FullyEvent <PrimaryKey>
                {
                    Event = @event,
                    Base  = new EventBase
                    {
                        Version = Snapshot.Base.Version + 1
                    },
                    StateId = Snapshot.Base.StateId
                };
                string unique = default;
                if (eUID == default)
                {
                    fullyEvent.Base.Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    unique = fullyEvent.GetEventId();
                }
                else
                {
                    fullyEvent.Base.Timestamp = eUID.Timestamp;
                    unique = eUID.UID;
                }
                var startTask = OnRaiseStart(fullyEvent);
                if (!startTask.IsCompletedSuccessfully)
                {
                    await startTask;
                }
                Snapshot.Base.IncrementDoingVersion(GrainType);//标记将要处理的Version
                var bytesTransport = new EventBytesTransport(
                    TypeContainer.GetTypeCode(@event.GetType()),
                    Snapshot.Base.StateId,
                    fullyEvent.Base.GetBytes(),
                    Serializer.SerializeToBytes(@event)
                    );
                if (await EventStorage.Append(fullyEvent, in bytesTransport, unique))
                {
                    SnapshotHandler.Apply(Snapshot, fullyEvent);
                    Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType);//更新处理完成的Version
                    var task = OnRaised(fullyEvent, bytesTransport);
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }
                    var saveSnapshotTask = SaveSnapshotAsync();
                    if (!saveSnapshotTask.IsCompletedSuccessfully)
                    {
                        await saveSnapshotTask;
                    }
                    await PublishToEventBust(bytesTransport.GetBytes(), GrainId.ToString());

                    if (Logger.IsEnabled(LogLevel.Trace))
                    {
                        Logger.LogTrace("Raise event successfully, grain Id= {0} and state version = {1}", GrainId.ToString(), Snapshot.Base.Version);
                    }
                    return(true);
                }
                else
                {
                    Snapshot.Base.DecrementDoingVersion();//还原doing Version
                    if (Logger.IsEnabled(LogLevel.Information))
                    {
                        Logger.LogInformation("Raise event failure because of idempotency limitation, grain Id = {0},state version = {1},event type = {2} with version = {3}", GrainId.ToString(), Snapshot.Base.Version, @event.GetType().FullName, fullyEvent.Base.Version);
                    }
                    var task = OnRaiseFailed(fullyEvent);
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }
                }
            }
Пример #31
0
        protected virtual async Task <bool> RaiseEvent(IEvent @event, EventUID eUID = null)
        {
            if (Snapshot.Base.IsOver)
            {
                throw new StateIsOverException(Snapshot.Base.StateId.ToString(), GrainType);
            }
            try
            {
                var fullyEvent = new FullyEvent <PrimaryKey>
                {
                    Event = @event,
                    Base  = new EventBase
                    {
                        Version = Snapshot.Base.Version + 1
                    },
                    StateId = Snapshot.Base.StateId
                };
                string unique = default;
                if (eUID is null)
                {
                    fullyEvent.Base.Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                    unique = fullyEvent.GetEventId();
                }
                else
                {
                    fullyEvent.Base.Timestamp = eUID.Timestamp;
                    unique = eUID.UID;
                }
                var startTask = OnRaiseStart(fullyEvent);
                if (!startTask.IsCompletedSuccessfully)
                {
                    await startTask;
                }
                Snapshot.Base.IncrementDoingVersion(GrainType);//标记将要处理的Version
                var evtType        = @event.GetType();
                var bytesTransport = new EventBytesTransport(
                    TypeFinder.GetCode(evtType),
                    Snapshot.Base.StateId,
                    fullyEvent.Base.GetBytes(),
                    Serializer.SerializeToUtf8Bytes(@event, evtType)
                    );
                if (await EventStorage.Append(fullyEvent, in bytesTransport, unique))
                {
                    SnapshotHandler.Apply(Snapshot, fullyEvent);
                    Snapshot.Base.UpdateVersion(fullyEvent.Base, GrainType);//更新处理完成的Version
                    var task = OnRaised(fullyEvent, bytesTransport);
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }
                    var saveSnapshotTask = SaveSnapshotAsync();
                    if (!saveSnapshotTask.IsCompletedSuccessfully)
                    {
                        await saveSnapshotTask;
                    }
                    await PublishToEventBus(bytesTransport.GetBytes(), GrainId.ToString());

                    if (Logger.IsEnabled(LogLevel.Trace))
                    {
                        Logger.LogTrace("RaiseEvent completed: {0}->{1}->{2}", GrainType.FullName, Serializer.Serialize(fullyEvent), Serializer.Serialize(Snapshot));
                    }
                    return(true);
                }
                else
                {
                    if (Logger.IsEnabled(LogLevel.Trace))
                    {
                        Logger.LogTrace("RaiseEvent failed: {0}->{1}->{2}", GrainType.FullName, Serializer.Serialize(fullyEvent), Serializer.Serialize(Snapshot));
                    }
                    Snapshot.Base.DecrementDoingVersion();//还原doing Version
                    var task = OnRaiseFailed(fullyEvent);
                    if (!task.IsCompletedSuccessfully)
                    {
                        await task;
                    }
                }
            }