示例#1
0
 /// <summary>
 /// 发送无状态更改的消息到消息队列
 /// </summary>
 /// <returns></returns>
 protected async ValueTask Publish(IMessage msg, string hashKey = null)
 {
     if (string.IsNullOrEmpty(hashKey))
     {
         hashKey = GrainId.ToString();
     }
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, msg);
         var data = new W
         {
             TypeCode    = msg.GetType().FullName,
             BinaryBytes = ms.ToArray()
         };
         ms.Position = 0;
         ms.SetLength(0);
         Serializer.Serialize(ms, data);
         var mqServiceTask = GetMQService();
         if (!mqServiceTask.IsCompleted)
         {
             await mqServiceTask;
         }
         var pubLishTask = mqServiceTask.Result.Publish(ms.ToArray(), hashKey);
         if (!pubLishTask.IsCompleted)
         {
             await pubLishTask;
         }
     }
 }
示例#2
0
        protected virtual async ValueTask <bool> RaiseEvent(IEventBase <K> @event, string uniqueId = null, string hashKey = null)
        {
            try
            {
                State.IncrementDoingVersion();//标记将要处理的Version
                @event.StateId   = GrainId;
                @event.Version   = State.Version + 1;
                @event.Timestamp = DateTime.UtcNow;
                var serializer = GetSerializer();
                using (var ms = new PooledMemoryStream())
                {
                    serializer.Serialize(ms, @event);
                    var bytes = ms.ToArray();
                    if (await(await GetEventStorage()).SaveAsync(@event, bytes, uniqueId))
                    {
                        if (SupportAsync)
                        {
                            var data = new W
                            {
                                TypeCode    = @event.TypeCode,
                                BinaryBytes = bytes
                            };
                            ms.Position = 0;
                            ms.SetLength(0);
                            serializer.Serialize(ms, data);
                            //消息写入消息队列,以提供异步服务
                            Apply(State, @event);
                            GetMQService().Publish(ms.ToArray(), string.IsNullOrEmpty(hashKey) ? GrainId.ToString() : hashKey);
                        }
                        else
                        {
                            Apply(State, @event);
                        }
                        State.UpdateVersion(@event);//更新处理完成的Version
                        await SaveSnapshotAsync();

                        OnRaiseSuccess(@event, bytes);
                        return(true);
                    }
                    else
                    {
                        State.DecrementDoingVersion();//还原doing Version
                    }
                }
            }
            catch (Exception ex)
            {
                await RecoveryState();//还原状态

                ExceptionDispatchInfo.Capture(ex).Throw();
            }
            return(false);
        }
示例#3
0
文件: ESGrain.cs 项目: hlzhang123/Ray
        protected async ValueTask <bool> RaiseEvent(IEventBase <K> @event, string uniqueId = null, string hashKey = null)
        {
            try
            {
                State.IncrementDoingVersion();//标记将要处理的Version
                @event.StateId   = GrainId;
                @event.Version   = State.Version + 1;
                @event.Timestamp = DateTime.UtcNow;
                var serializer = GetSerializer();
                using (var ms = new PooledMemoryStream())
                {
                    serializer.Serialize(ms, @event);
                    var bytes  = ms.ToArray();
                    var result = await GetEventStorage().SaveAsync(@event, bytes, uniqueId);

                    if (result)
                    {
                        EventHandle.Apply(State, @event);
                        if (SupportAsync)
                        {
                            var data = new W
                            {
                                TypeCode    = @event.TypeCode,
                                BinaryBytes = bytes
                            };
                            ms.Position = 0;
                            ms.SetLength(0);
                            serializer.Serialize(ms, data);
                            //消息写入消息队列,以提供异步服务
                            await GetMQService().Publish(ms.ToArray(), string.IsNullOrEmpty(hashKey) ? GrainId.ToString() : hashKey);
                        }
                        State.UpdateVersion(@event);//更新处理完成的Version
                        await SaveSnapshotAsync();

                        return(true);
                    }
                    else
                    {
                        State.DecrementDoingVersion();//还原doing Version
                    }
                }
            }
            catch (Exception ex)
            {
                State.DecrementDoingVersion();//还原doing Version
                Logger.LogError(LogEventIds.EventRaiseError, ex, "Apply event {0} error, EventId={1}", @event.TypeCode, @event.Version);
                throw ex;
            }
            return(false);
        }
示例#4
0
        internal Task ProcessAndSendMessage(MessageEventArgs e, EncryptContext context)
        {
            var         message     = (ProudMessage)e.Message;
            var         data        = message.ToArray();
            CoreMessage coreMessage = new RmiMessage(data);

            if (message.Compress)
            {
                data        = coreMessage.ToArray();
                coreMessage = new CompressedMessage(data.Length, data.CompressZLib());
            }

            if (message.Encrypt)
            {
                data = coreMessage.ToArray();
                using (var w = new PooledMemoryStream(Service.ArrayPool).ToBinaryWriter(false))
                {
                    w.Write(context.EncryptCounter);
                    w.Write(data);

                    data = w.ToArray();
                }

                data        = context.Encrypt(data);
                coreMessage = new EncryptedReliableMessage(data);
            }

            e.Message = coreMessage;
            return(base.OnSendMessage(e));
        }
示例#5
0
        public byte[] GetBytes()
        {
            var eventTypeBytes = Encoding.UTF8.GetBytes(EventTypeCode);

            byte[] actorIdBytes;
            if (GrainId is long id)
            {
                actorIdBytes = BitConverter.GetBytes(id);
            }
            else if (GrainId is string strId)
            {
                actorIdBytes = Encoding.UTF8.GetBytes(strId);
            }
            else
            {
                throw new PrimaryKeyTypeException(EventTypeCode);
            }
            using var ms = new PooledMemoryStream();
            ms.WriteByte((byte)TransportType.Event);
            ms.Write(BitConverter.GetBytes((ushort)eventTypeBytes.Length));
            ms.Write(BitConverter.GetBytes((ushort)actorIdBytes.Length));
            ms.Write(BitConverter.GetBytes((ushort)BaseBytes.Length));
            ms.Write(BitConverter.GetBytes(EventBytes.Length));
            ms.Write(eventTypeBytes);
            ms.Write(actorIdBytes);
            ms.Write(BaseBytes);
            ms.Write(EventBytes);
            return(ms.ToArray());
        }
示例#6
0
 public byte[] GetBytes()
 {
     if (allBytes == default)
     {
         var    eventTypeBytes = Encoding.Default.GetBytes(EventType);
         byte[] actorIdBytes;
         if (ActorId is long id)
         {
             actorIdBytes = BitConverter.GetBytes(id);
         }
         else if (ActorId is string strId)
         {
             actorIdBytes = Encoding.Default.GetBytes(strId);
         }
         else
         {
             throw new PrimaryKeyTypeException(EventType);
         }
         using (var ms = new PooledMemoryStream())
         {
             ms.WriteByte((byte)TransportType.Event);
             ms.Write(BitConverter.GetBytes((ushort)eventTypeBytes.Length));
             ms.Write(BitConverter.GetBytes((ushort)actorIdBytes.Length));
             ms.Write(BitConverter.GetBytes((ushort)BaseBytes.Length));
             ms.Write(BitConverter.GetBytes(EventBytes.Length));
             ms.Write(eventTypeBytes);
             ms.Write(actorIdBytes);
             ms.Write(BaseBytes);
             ms.Write(EventBytes);
             allBytes = ms.ToArray();
         }
     }
     return(allBytes);
 }
示例#7
0
        public override async Task OnActivateAsync()
        {
            await ReadSnapshotAsync();

            while (true)
            {
                var eventList = await EventStorage.GetListAsync(this.GrainId, this.State.Version, this.State.Version + 1000, this.State.VersionTime);

                foreach (var @event in eventList)
                {
                    this.State.IncrementDoingVersion();//标记将要处理的Version
                    EventHandle.Apply(this.State, @event.Event);
                    if ([email protected])
                    {
                        using (var ms = new PooledMemoryStream())
                        {
                            Serializer.Serialize(ms, @event.Event);
                            await AfterEventSavedHandle(@event.Event, ms.ToArray());
                        }
                    }
                    this.State.UpdateVersion(@event.Event);//更新处理完成的Version
                }
                if (eventList.Count < 1000)
                {
                    break;
                }
            }
            ;
        }
示例#8
0
 public byte[] GetBytes()
 {
     using var ms = new PooledMemoryStream();
     ms.Write(BitConverter.GetBytes(Version));
     ms.Write(BitConverter.GetBytes(Timestamp));
     return(ms.ToArray());
 }
示例#9
0
        protected async ValueTask<bool> RaiseEvent(IEventBase<K> @event, string uniqueId = null, string hashKey = null)
        {
            try
            {
                this.State.IncrementDoingVersion();//标记将要处理的Version
                @event.StateId = GrainId;
                @event.Version = this.State.Version + 1;
                @event.Timestamp = DateTime.UtcNow;
                using (var ms = new PooledMemoryStream())
                {
                    Serializer.Serialize(ms, @event);
                    var bytes = ms.ToArray();
                    var result = await EventStorage.SaveAsync(@event, bytes, uniqueId);
                    if (result)
                    {
                        EventHandle.Apply(this.State, @event);
                        await AfterEventSavedHandle(@event, bytes, hashKey: hashKey);

                        this.State.UpdateVersion(@event);//更新处理完成的Version

                        await SaveSnapshotAsync();
                        return true;
                    }
                    else
                        this.State.DecrementDoingVersion();//还原doing Version
                }
            }
            catch (Exception ex)
            {
                this.GetLogger("Event_Raise").Log(LogCodes.EventRaiseError, Orleans.Runtime.Severity.Error, $"applay event {@event.TypeCode} error, eventId={@event.Version}", null, ex);
                await OnActivateAsync();//重新激活Actor
                throw ex;
            }
            return false;
        }
示例#10
0
 /// <summary>
 ///   Sets the given key and value in the current session. Value is serialized using given
 ///   custom serializer.
 /// </summary>
 /// <typeparam name="T">The type of the value.</typeparam>
 /// <param name="session">The session.</param>
 /// <param name="serializer">The custom serializer.</param>
 /// <param name="key">The key.</param>
 /// <param name="value">The value.</param>
 public static void SetObject <T>(this ISession session, ISerializer serializer, string key, T value)
 {
     using (var serializedStream = new PooledMemoryStream())
     {
         BlobSerializer.Serialize(serializer, serializedStream, value);
         session.Set(key, serializedStream.ToArray());
     }
 }
示例#11
0
 /// <summary>
 /// 发送消息到消息队列
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="data"></param>
 /// <param name="exchange"></param>
 /// <param name="queue"></param>
 /// <returns></returns>
 public void Publish <T>(T data, string exchange, string queue, bool persistent = true)
 {
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, data);
         Publish(ms.ToArray(), exchange, queue, persistent);
     }
 }
示例#12
0
 /// <summary>
 /// 发送无状态更改的消息到消息队列
 /// </summary>
 /// <param name="msg"></param>
 /// <returns></returns>
 public async Task Publish(IActorOwnMessage <K> msg)
 {
     msg.StateId = this.GrainId;
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, msg);
         await MQService.Publish(msg, ms.ToArray(), GrainId.ToString());
     }
 }
示例#13
0
 public void PublishByCmd <T>(UInt16 cmd, T data, string exchange, string queue, bool persistent = false)
 {
     using (var ms = new PooledMemoryStream())
     {
         ms.Write(BitConverter.GetBytes(cmd), 0, 2);
         Serializer.Serialize(ms, data);
         Publish(ms.ToArray(), exchange, queue, persistent);
     }
 }
示例#14
0
 /// <summary>
 /// 发送消息到消息队列
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="data"></param>
 /// <param name="exchange"></param>
 /// <param name="queue"></param>
 /// <returns></returns>
 public static Task Publish <T>(T data, string exchange, string queue, bool persistent = true)
 {
     byte[] msg;
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, data);
         msg = ms.ToArray();
     }
     return(Publish(msg, exchange, queue, persistent));
 }
示例#15
0
        public byte[] GetBytes()
        {
            var eventTypeBytes = Encoding.Default.GetBytes(TypeFullName);

            using var ms = new PooledMemoryStream();
            ms.WriteByte((byte)TransportType.Common);
            ms.Write(BitConverter.GetBytes((ushort)eventTypeBytes.Length));
            ms.Write(Bytes);
            return(ms.ToArray());
        }
示例#16
0
        public void TestShrink()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stm = new PooledMemoryStream())
            {
                stm.Write(data, 0, data.Length);
                stm.Shrink(2);
                Assert.Equal(data.AsSpan(0, 2).ToArray(), stm.ToArray());
            }
        }
示例#17
0
 public static Task PublishByCmd <T>(UInt16 cmd, T data, string exchange, string queue)
 {
     byte[] msg;
     using (var ms = new PooledMemoryStream())
     {
         ms.Write(BitConverter.GetBytes(cmd), 0, 2);
         Serializer.Serialize(ms, data);
         msg = ms.ToArray();
     }
     return(Publish(msg, exchange, queue, false));
 }
示例#18
0
        public void TestWriteMiddle()
        {
            var data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (var stm = new PooledMemoryStream(ArrayPool <byte> .Shared))
            {
                stm.Write(data, 0, data.Length);
                stm.Seek(4, SeekOrigin.Begin);
                stm.Write(data, 0, data.Length);
                var ar = stm.ToArray();
                Assert.Equal(data.Take(4).Concat(data), ar);
            }
        }
示例#19
0
        public void TestSetLength()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stm = new PooledMemoryStream(ArrayPool <byte> .Shared))
            {
                stm.Write(data, 0, data.Length);
                stm.SetLength(128 * 1024);
                Assert.Equal(128 * 1024, stm.Length);
                var ar = stm.ToArray();
                Assert.Equal(data, ar.Take(data.Length));
            }
        }
示例#20
0
        public void TestWriteTwice()
        {
            var data = new byte[] { 1, 2, 3, 4 };

            using (var stm = new PooledMemoryStream(ArrayPool <byte> .Shared))
            {
                Assert.True(stm.CanWrite);
                Assert.True(stm.CanRead);
                Assert.Equal(0, stm.Length);
                Assert.Equal(0, stm.Position);
                stm.Write(data, 0, data.Length);
                Assert.Equal(4, stm.Length);
                Assert.Equal(4, stm.Position);
                var ar = stm.ToArray();
                Assert.Equal(data, ar);
                stm.Write(data, 0, data.Length);
                Assert.Equal(8, stm.Length);
                Assert.Equal(8, stm.Position);
                ar = stm.ToArray();
                Assert.Equal(data.Concat(data), ar);
            }
        }
示例#21
0
        /// <summary>
        /// 发送无状态更改的消息到消息队列
        /// </summary>
        /// <returns></returns>
        public async Task Publish(IMessage msg, string hashKey = null)
        {
            if (string.IsNullOrEmpty(hashKey))
            {
                hashKey = GrainId.ToString();
            }
            var serializer = GetSerializer();

            using (var ms = new PooledMemoryStream())
            {
                serializer.Serialize(ms, msg);
                var data = new W
                {
                    TypeCode    = msg.TypeCode,
                    BinaryBytes = ms.ToArray()
                };
                ms.Position = 0;
                ms.SetLength(0);
                serializer.Serialize(ms, data);
                await GetMQService().Publish(ms.ToArray(), hashKey);
            }
        }
示例#22
0
        public async Task Go()
        {
            Data d         = new Data();
            var  mqService = mQServiceContainer.GetService(this);

            using (var ms = new PooledMemoryStream())
            {
                Serializer.Serialize(ms, d);
                var data = new MessageInfo()
                {
                    TypeCode    = d.GetType().FullName,
                    BinaryBytes = ms.ToArray()
                };
                ms.Position = 0;
                ms.SetLength(0);
                Serializer.Serialize(ms, data);
                for (int i = 0; i < 2; i++)
                {
                    await mqService.Result.Publish(ms.ToArray(), Guid.NewGuid().ToString());

                    Console.WriteLine(i);
                }
            }
        }
示例#23
0
        public byte[] GetBytes()
        {
            var eventTypeBytes = Encoding.UTF8.GetBytes(EventTypeCode);
            var eventIdBytes   = Encoding.UTF8.GetBytes(EventId);

            using var ms = new PooledMemoryStream();
            ms.WriteByte((byte)TransportType.Event);
            ms.Write(BitConverter.GetBytes((ushort)eventTypeBytes.Length));
            ms.Write(BitConverter.GetBytes((ushort)eventIdBytes.Length));
            ms.Write(BitConverter.GetBytes(EventBytes.Length));
            ms.Write(eventTypeBytes);
            ms.Write(eventIdBytes);
            ms.Write(EventBytes);
            return(ms.ToArray());
        }
示例#24
0
 protected async ValueTask CommitTransaction()
 {
     if (transactionEventList.Count > 0)
     {
         var serializer = GetSerializer();
         using (var ms = new PooledMemoryStream())
         {
             foreach (var @event in transactionEventList)
             {
                 serializer.Serialize(ms, @event.Evt);
                 @event.Bytes = ms.ToArray();
                 ms.Position  = 0;
                 ms.SetLength(0);
             }
         }
         await(await GetEventStorage()).TransactionSaveAsync(transactionEventList);
         if (SupportAsync)
         {
             var mqService = GetMQService();
             using (var ms = new PooledMemoryStream())
             {
                 foreach (var @event in transactionEventList)
                 {
                     var data = new W
                     {
                         TypeCode    = @event.Evt.TypeCode,
                         BinaryBytes = @event.Bytes
                     };
                     serializer.Serialize(ms, data);
                     mqService.Publish(ms.ToArray(), @event.HashKey);
                     OnRaiseSuccess(@event.Evt, @event.Bytes);
                     ms.Position = 0;
                     ms.SetLength(0);
                 }
             }
         }
         else
         {
             foreach (var evt in transactionEventList)
             {
                 OnRaiseSuccess(evt.Evt, evt.Bytes);
             }
         }
         transactionEventList.Clear();
         await SaveSnapshotAsync();
     }
     transactionPending = false;
 }
示例#25
0
        public async Task InsertAsync(T data)
        {
            var mState = new MongoState <K>();

            mState.StateId = data.StateId;
            mState.Id      = ObjectId.GenerateNewId().ToString();
            using (var ms = new PooledMemoryStream())
            {
                Serializer.Serialize <T>(ms, data);
                mState.Data = ms.ToArray();
            }
            if (mState.Data != null && mState.Data.Count() > 0)
            {
                await mongoStorage.GetCollection <MongoState <K> >(database, collection).InsertOneAsync(mState, null, new CancellationTokenSource(3000).Token);
            }
        }
示例#26
0
        public async Task UpdateAsync(T data)
        {
            var filterBuilder = Builders <BsonDocument> .Filter;
            var filter        = filterBuilder.Eq("StateId", data.StateId);

            byte[] bytes;
            using (var ms = new PooledMemoryStream())
            {
                Serializer.Serialize <T>(ms, data);
                bytes = ms.ToArray();
            }
            if (bytes != null && bytes.Count() > 0)
            {
                var update = Builders <BsonDocument> .Update.Set("Data", bytes);

                await mongoStorage.GetCollection <BsonDocument>(database, collection).UpdateOneAsync(filter, update, null, new CancellationTokenSource(3000).Token);
            }
        }
示例#27
0
        public async Task InsertAsync(T data)
        {
            var mState = new MongoState <K>
            {
                StateId = data.StateId,
                Id      = ObjectId.GenerateNewId().ToString(),
                Version = data.Version
            };

            using (var ms = new PooledMemoryStream())
            {
                Serializer.Serialize <T>(ms, data);
                mState.Data = ms.ToArray();
            }
            if (mState.Data != null && mState.Data.Count() > 0)
            {
                await grainConfig.Storage.GetCollection <MongoState <K> >(grainConfig.DataBase, grainConfig.SnapshotCollection).InsertOneAsync(mState, null, new CancellationTokenSource(3000).Token);
            }
        }
示例#28
0
 private byte[] GetMimeData(StoreObjectId itemId, out string[] recipients)
 {
     recipients = null;
     byte[] result;
     using (MessageItem messageItem = MessageItem.Bind(this.mailboxSession, itemId, StoreObjectSchema.ContentConversionProperties))
     {
         List <string> list = new List <string>(messageItem.Recipients.Count);
         foreach (RecipientBase recipientBase in messageItem.Recipients)
         {
             Participant participant = recipientBase.Participant;
             if (participant != null)
             {
                 string valueOrDefault = participant.GetValueOrDefault <string>(ParticipantSchema.SmtpAddress);
                 list.Add(valueOrDefault);
             }
         }
         OutboundConversionOptions options = new OutboundConversionOptions(this.mailboxSession.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid), this.mailboxSession.ServerFullyQualifiedDomainName)
         {
             IsSenderTrusted = true,
             RecipientCache  = null,
             ClearCategories = true,
             Limits          =
             {
                 MimeLimits = MimeLimits.Unlimited
             },
             AllowPartialStnefConversion = true
         };
         using (PooledMemoryStream pooledMemoryStream = new PooledMemoryStream(6))
         {
             ItemConversion.ConvertItemToMime(messageItem, pooledMemoryStream, options);
             recipients = list.ToArray();
             result     = pooledMemoryStream.ToArray();
         }
     }
     return(result);
 }
示例#29
0
 public async Task InsertAsync(T data)
 {
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, data);
         using (var connection = tableInfo.CreateConnection())
         {
             await connection.ExecuteAsync(insertSql, new { StateId = data.StateId.ToString(), Data = ms.ToArray(), data.Version });
         }
     }
 }
示例#30
0
 public async Task UpdateAsync(T data)
 {
     using (var ms = new PooledMemoryStream())
     {
         Serializer.Serialize(ms, data);
         using (var connection = tableInfo.CreateConnection())
         {
             await connection.ExecuteAsync(updateSql, new { data.StateId, Data = ms.ToArray() });
         }
     }
 }