Ejemplo n.º 1
0
        public async Task PublishAsync <T>(string name, T contentObj, string callbackName = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message = new PublishedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                Name       = name,
                Content    = Serialize(contentObj, callbackName),
                StatusName = StatusName.Scheduled
            };

            await PublishAsyncInternal(message);
        }
Ejemplo n.º 2
0
        public void Publish <T>(string name, T contentObj, string callbackName = null)
        {
            var message = new CapPublishedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                Name       = name,
                Content    = Serialize(contentObj, callbackName),
                StatusName = StatusName.Scheduled
            };

            PublishAsyncInternal(message).GetAwaiter().GetResult();
        }
Ejemplo n.º 3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="categoryId"></param>
 /// <param name="title"></param>
 /// <param name="remark"></param>
 /// <param name="content"></param>
 /// <param name="value"></param>
 public Article(string categoryId, string title, string remark, string content, string value)
 {
     this.Id         = SnowflakeId.Default().NextId().ToString();
     this.CategoryId = categoryId;
     this.Title      = title;
     this.Remark     = remark;
     this.Content    = content;
     this.Value      = value;
     this.ReadCount  = 0;
     this.likeCount  = 0;
     this.CreateTime = DateTime.Now;
 }
Ejemplo n.º 4
0
        public void ConcurrentNextIdTest()
        {
            var array = new long[1000];

            Parallel.For(0, 1000, i =>
            {
                var id   = SnowflakeId.Default().NextId();
                array[i] = id;
            });

            Assert.True(array.Distinct().Count() == 1000);
        }
Ejemplo n.º 5
0
        public void StoreReceivedMessageTest()
        {
            var msgId  = SnowflakeId.Default().NextId().ToString();
            var header = new Dictionary <string, string>()
            {
                [Headers.MessageId] = msgId
            };
            var message = new Message(header, null);

            var mdMessage = _storage.StoreReceivedMessage("test.name", "test.group", message);

            Assert.NotNull(mdMessage);
        }
Ejemplo n.º 6
0
        public async Task ChangeReceiveStateTest()
        {
            var msgId  = SnowflakeId.Default().NextId().ToString();
            var header = new Dictionary <string, string>()
            {
                [Headers.MessageId] = msgId
            };
            var message = new Message(header, null);

            var mdMessage = _storage.StoreMessage("test.name", message);

            await _storage.ChangeReceiveStateAsync(mdMessage, StatusName.Succeeded);
        }
Ejemplo n.º 7
0
 public ClientSocket(string name, EndPoint serverEndPoint, FregataOptions fregataOptions, IBufferPool receivedBufferPool, IBufferPool sendBufferPool, ITcpConnectionHandler tcpConnectionHandler)
 {
     Id                           = SnowflakeId.Default().NextId();
     Name                         = name ?? throw new ArgumentNullException(nameof(name));
     ServerEndPoint               = serverEndPoint ?? throw new ArgumentNullException(nameof(serverEndPoint));
     Setting                      = fregataOptions ?? throw new ArgumentNullException(nameof(fregataOptions));
     _receivedBufferPool          = receivedBufferPool ?? throw new ArgumentNullException(nameof(receivedBufferPool));
     _sendBufferPool              = sendBufferPool ?? throw new ArgumentNullException(nameof(sendBufferPool));
     _waitConnectHandle           = new ManualResetEvent(false);
     Socket                       = SocketUtil.CreateSocket(serverEndPoint, fregataOptions.SendMaxSize, fregataOptions.ReceiveMaxSize);
     _tcpConnectionHandler        = tcpConnectionHandler;
     _tcpConnectionEventListeners = new List <ITcpConnectionEventListener>();
 }
        public void OnApplicationCommand(IApplicationCommandingContext context, StartTransferApplicationCommand command)
        {
            var transactionId = SnowflakeId.Default().NextId();
            var source        = command.SourceAccount;
            var sink          = command.SinkAccount;
            var domainCommand = new StartTransferTransactionDomainCommand(
                transactionId,
                new TransferAccount(source.Id, source.Name, source.Bank, TransferAccountType.Source),
                new TransferAccount(sink.Id, sink.Name, sink.Bank, TransferAccountType.Sink),
                command.Amount);

            context.PublishDomainCommand(domainCommand);
        }
Ejemplo n.º 9
0
        public void StoreReceivedMessageAsync_TestAsync()
        {
            var messageContext = new MessageContext
            {
                Group   = "test",
                Name    = "test",
                Content = "test-content"
            };

            _connection.StoreReceivedMessage(new CapReceivedMessage(messageContext)
            {
                Id = SnowflakeId.Default().NextId()
            });
        }
Ejemplo n.º 10
0
        public void OnApplicationCommand(IApplicationCommandingContext context, StartDepositApplicationCommand appCommand)
        {
            var transactionId = SnowflakeId.Default().NextId();
            var domainCommand = new StartDepositTransactionDomainCommand(transactionId, appCommand.AccountId,
                                                                         appCommand.AccountName,
                                                                         appCommand.Amount, appCommand.Bank)
            {
                ApplicationCommandId          = appCommand.Id,
                ApplicationCommandType        = appCommand.GetType().FullName,
                ApplicationCommandReplyScheme = appCommand.ReplyScheme
            };

            context.PublishDomainCommand(domainCommand);
        }
 public ApplicationMessageProcessor(
     IStringObjectSerializer objectSerializer,
     IProcessingApplicationMessageQueueFactory queueFactory,
     IBackgroundWorker backgroundWorker,
     ILogger <ApplicationMessageProcessor> logger,
     VoguediOptions options)
 {
     this.objectSerializer = objectSerializer;
     this.queueFactory     = queueFactory;
     this.backgroundWorker = backgroundWorker;
     this.logger           = logger;
     expiration            = options.MemoryQueueExpiration;
     backgroundWorkerKey   = $"{nameof(ApplicationMessageProcessor)}_{SnowflakeId.Default().NewId()}";
     queueMapping          = new ConcurrentDictionary <string, IProcessingApplicationMessageQueue>();
 }
Ejemplo n.º 12
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            object[] sqlParams =
            {
                new OracleParameter(":P_Id",         SnowflakeId.Default().NextId().ToString()),
                new OracleParameter(":P_Name",       name),
                new OracleParameter(":P_Group",      group),
                new OracleParameter(":P_Content",    content),
                new OracleParameter(":P_Retries",    _capOptions.Value.FailedRetryCount),
                new OracleParameter(":P_Added",      DateTime.Now),
                new OracleParameter(":P_ExpiresAt",  DateTime.Now.AddDays(15)),
                new OracleParameter(":P_StatusName", nameof(StatusName.Failed))
            };

            StoreReceivedMessage(sqlParams, DateTime.Now, DateTime.Now.AddDays(15));
        }
Ejemplo n.º 13
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            object[] sqlParams =
            {
                new SqliteParameter("@Id",         SnowflakeId.Default().NextId()),
                new SqliteParameter("@Name",       name),
                new SqliteParameter("@Group",      group),
                new SqliteParameter("@Content",    content),
                new SqliteParameter("@Retries",    _capOptions.Value.FailedRetryCount),
                new SqliteParameter("@Added",      DateTime.Now),
                new SqliteParameter("@ExpiresAt",  DateTime.Now.AddDays(15)),
                new SqliteParameter("@StatusName", nameof(StatusName.Failed))
            };

            StoreReceivedMessage(sqlParams);
        }
Ejemplo n.º 14
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var id = SnowflakeId.Default().NextId().ToString();

            ReceivedMessages.Insert(new LiteDBMessage
            {
                Id         = id,
                Group      = group,
                Name       = name,
                Content    = content,
                Retries    = _capOptions.Value.FailedRetryCount,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                StatusName = StatusName.Failed
            });
        }
        public MediumMessage StoreReceivedMessage(string name, string group, Message message)
        {
            var mdMessage = new MediumMessage
            {
                DbId      = SnowflakeId.Default().NextId().ToString(),
                Origin    = message,
                Added     = DateTime.Now,
                ExpiresAt = null,
                Retries   = 0
            };

            _capRepository.InsertReceivedMessage(_recName, mdMessage.DbId, _capOptions.Value.Version, name, group,
                                                 _serializer.Serialize(mdMessage.Origin), mdMessage.Retries, mdMessage.Added, mdMessage.ExpiresAt,
                                                 nameof(StatusName.Failed));

            return(mdMessage);
        }
Ejemplo n.º 16
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var id = SnowflakeId.Default().NextId().ToString();

            ReceivedMessages[id] = new MemoryMessage
            {
                DbId       = id,
                Group      = group,
                Origin     = null,
                Name       = name,
                Content    = content,
                Retries    = _capOptions.Value.FailedRetryCount,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                StatusName = StatusName.Failed
            };
        }
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var sql = $@"INSERT INTO `{_initializer.GetReceivedTableName()}`(`Id`,`Version`,`Name`,`Group`,`Content`,`Retries`,`Added`,`ExpiresAt`,`StatusName`) VALUES(@Id,'{_options.Value.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";

            using var connection = new MySqlConnection(_options.Value.ConnectionString);
            connection.Execute(sql, new
            {
                Id         = SnowflakeId.Default().NextId().ToString(),
                Group      = @group,
                Name       = name,
                Content    = content,
                Retries    = _capOptions.Value.FailedRetryCount,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                StatusName = nameof(StatusName.Failed)
            });
        }
Ejemplo n.º 18
0
        public void StoreReceivedMessageAsync_TestAsync()
        {
            var messageContext = new MessageContext
            {
                Group   = "test",
                Name    = "test",
                Content = "test-content"
            };

            _connection.StoreReceivedMessage(new ReceivedMessage()
            {
                Id      = SnowflakeId.Default().NextId(),
                Group   = messageContext.Group,
                Content = messageContext.Content,
                Name    = messageContext.Name,
                Version = "v1"
            });
        }
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var sql =
                $"INSERT INTO {_recName}(\"Id\",\"Version\",\"Name\",\"Group\",\"Content\",\"Retries\",\"Added\",\"ExpiresAt\",\"StatusName\")" +
                $"VALUES(@Id,'{_capOptions.Value.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName) RETURNING \"Id\";";

            this.DbConnection.Execute(sql, new
            {
                Id         = SnowflakeId.Default().NextId(),
                Group      = group,
                Name       = name,
                Content    = content,
                Retries    = _capOptions.Value.FailedRetryCount,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                StatusName = nameof(StatusName.Failed)
            }, transaction: DbTransaction);
        }
Ejemplo n.º 20
0
        private void RegisterMessageProcessor(IConsumerClient client)
        {
            client.OnMessageReceived += (sender, messageContext) =>
            {
                _cts.Token.ThrowIfCancellationRequested();

                var startTime = DateTimeOffset.UtcNow;
                var stopwatch = Stopwatch.StartNew();

                var tracingResult = TracingBefore(messageContext.Name, messageContext.Content);
                var operationId   = tracingResult.Item1;
                var messageBody   = tracingResult.Item2;

                var receivedMessage = new CapReceivedMessage(messageContext)
                {
                    Id         = SnowflakeId.Default().NextId(),
                    StatusName = StatusName.Scheduled,
                    Content    = messageBody
                };

                try
                {
                    StoreMessage(receivedMessage);

                    client.Commit();

                    TracingAfter(operationId, receivedMessage.Name, receivedMessage.Content, startTime,
                                 stopwatch.Elapsed);

                    _dispatcher.EnqueueToExecute(receivedMessage);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "An exception occurred when store received message. Message:'{0}'.", messageContext);

                    client.Reject();

                    TracingError(operationId, receivedMessage.Name, receivedMessage.Content, e, startTime,
                                 stopwatch.Elapsed);
                }
            };

            client.OnLog += WriteLog;
        }
Ejemplo n.º 21
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var sql =
                $"INSERT INTO {_recName}([Id],[Version],[Name],[Group],[Content],[Retries],[Added],[ExpiresAt],[StatusName])" +
                $"VALUES(@Id,'{_capOptions.Value.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";

            using var connection = new SqlConnection(_options.Value.ConnectionString);
            connection.Execute(sql, new
            {
                Id         = SnowflakeId.Default().NextId().ToString(),
                Group      = group,
                Name       = name,
                Content    = content,
                Retries    = _capOptions.Value.FailedRetryCount,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                StatusName = nameof(StatusName.Failed)
            });
        }
Ejemplo n.º 22
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            object[] sqlParams =
            {
                new OracleParameter(":Id",         SnowflakeId.Default().NextId()),
                new OracleParameter(":Name",       name),
                new OracleParameter(":Group",      group),
                new OracleParameter(":Content",    OracleDbType.Clob)
                {
                    Value = content
                },
                new OracleParameter(":Retries",    _capOptions.Value.FailedRetryCount),
                new OracleParameter(":Added",      DateTime.Now),
                new OracleParameter(":ExpiresAt",  DateTime.Now.AddDays(15)),
                new OracleParameter(":StatusName", nameof(StatusName.Failed))
            };

            StoreReceivedMessage(sqlParams);
        }
Ejemplo n.º 23
0
        public TcpConnection(string name, Socket socket, FregataOptions fregataOptions, IBufferPool receivedBufferPool, IBufferPool sendBufferPool, ITcpConnectionHandler tcpConnectionHandler)
        {
            Id                           = SnowflakeId.Default().NextId();
            Name                         = name;
            Socket                       = socket;
            LocalEndPoint                = socket.LocalEndPoint;
            RemotingEndPoint             = socket.RemoteEndPoint;
            Setting                      = fregataOptions;
            _tcpConnectionEventListeners = new List <ITcpConnectionEventListener>();

            _tcpConnectionHandler = tcpConnectionHandler;

            _messageFramer = new LengthPrefixMessageFramer(Setting);
            _messageFramer.RegisterMessageArrivedCallback(OnMessageArrived);
            _receiveBuufferPipeline = new BufferPipeline(bufferPool: receivedBufferPool, littelEndian: fregataOptions.LittleEndian, coding: fregataOptions.Encode, writerFlushCompleted: null);

            _sendBuufferPipeline = new BufferPipeline(bufferPool: sendBufferPool, littelEndian: fregataOptions.LittleEndian, coding: fregataOptions.Encode, writerFlushCompleted: null);
            Task.Run(() => TryReceiveAsync());
        }
Ejemplo n.º 24
0
        public void StoreReceivedExceptionMessage(string name, string group, string content)
        {
            var collection = _database.GetCollection <ReceivedMessage>(_options.Value.ReceivedCollection);

            var store = new ReceivedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                Group      = group,
                Name       = name,
                Content    = content,
                Added      = DateTime.Now,
                ExpiresAt  = DateTime.Now.AddDays(15),
                Retries    = _capOptions.Value.FailedRetryCount,
                Version    = _capOptions.Value.Version,
                StatusName = nameof(StatusName.Failed)
            };

            collection.InsertOne(store);
        }
Ejemplo n.º 25
0
        public void ChangeState_ExpiresAfter()
        {
            // Arrange
            var fixture = Create();
            var message = new CapPublishedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                StatusName = StatusName.Scheduled
            };
            var state           = Mock.Of <IState>(s => s.Name == "s" && s.ExpiresAfter == TimeSpan.FromHours(1));
            var mockTransaction = new Mock <IStorageTransaction>();

            // Act
            fixture.ChangeState(message, state, mockTransaction.Object);

            // Assert
            Assert.Equal("s", message.StatusName);
            Assert.NotNull(message.ExpiresAt);
            mockTransaction.Verify(t => t.UpdateMessage(message), Times.Once);
            mockTransaction.Verify(t => t.CommitAsync(), Times.Never);
        }
Ejemplo n.º 26
0
        public async Task GetPublishedMessageAsync_Test()
        {
            var sql            = "INSERT INTO `cap.published`(`Id`,`Version`,`Name`,`Content`,`Retries`,`Added`,`ExpiresAt`,`StatusName`) VALUES(@Id,'v1',@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
            var insertedId     = SnowflakeId.Default().NextId();
            var publishMessage = new CapPublishedMessage
            {
                Id         = insertedId,
                Name       = "MySqlStorageConnectionTest",
                Content    = "",
                StatusName = StatusName.Scheduled
            };

            using (var connection = ConnectionUtil.CreateConnection())
            {
                await connection.ExecuteAsync(sql, publishMessage);
            }
            var message = await _storage.GetPublishedMessageAsync(insertedId);

            Assert.NotNull(message);
            Assert.Equal("MySqlStorageConnectionTest", message.Name);
            Assert.Equal(StatusName.Scheduled, message.StatusName);
        }
Ejemplo n.º 27
0
        public async Task GetPublishedMessageAsync_Test()
        {
            var sql            = @"INSERT INTO ""cap"".""published""(""Id"",""Version"",""Name"",""Content"",""Retries"",""Added"",""ExpiresAt"",""StatusName"") VALUES(@Id,'v1',@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
            var insertedId     = SnowflakeId.Default().NextId();
            var publishMessage = new CapPublishedMessage
            {
                Id         = insertedId,
                Name       = "PostgreSqlStorageConnectionTest",
                Content    = "",
                StatusName = StatusName.Scheduled
            };

            using (var connection = ConnectionUtil.CreateConnection())
            {
                await connection.ExecuteAsync(sql, publishMessage);
            }
            var message = await _storage.GetPublishedMessageAsync(insertedId);

            Assert.NotNull(message);
            Assert.Equal("PostgreSqlStorageConnectionTest", message.Name);
            Assert.Equal(StatusName.Scheduled, message.StatusName);
        }
        public async Task SendAsync(string messageId, string topicName, object bodyObj)
        {
            string body;

            if (bodyObj != null && Helper.IsComplexType(bodyObj.GetType()))
            {
                body = _contentSerializer.Serialize(bodyObj);
            }
            else
            {
                body = bodyObj?.ToString();
            }

            _logger.LogDebug($"Callback message will publishing, name:{topicName},content:{body}");

            var callbackMessage = new CapMessageDto
            {
                Id      = messageId,
                Content = body
            };

            var content = _messagePacker.Pack(callbackMessage);

            var publishedMessage = new CapPublishedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                Name       = topicName,
                Content    = content,
                StatusName = StatusName.Scheduled
            };

            using (var scope = _serviceProvider.CreateScope())
            {
                var provider          = scope.ServiceProvider;
                var callbackPublisher = provider.GetService <ICallbackPublisher>();
                await callbackPublisher.PublishCallbackAsync(publishedMessage);
            }
        }
        public async Task GetPublishedMessageAsync_Test()
        {
            var sql            = "INSERT INTO [Cap].[Published]([Id],[Name],[Content],[Retries],[Added],[ExpiresAt],[StatusName]) VALUES(@Id,@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
            var insertedId     = SnowflakeId.Default().NextId();
            var publishMessage = new CapPublishedMessage
            {
                Id         = insertedId,
                Name       = "SqlServerStorageConnectionTest",
                Content    = "",
                StatusName = StatusName.Scheduled
            };

            using (var connection = ConnectionUtil.CreateConnection())
            {
                await connection.ExecuteAsync(sql, publishMessage);
            }

            var message = await _storage.GetPublishedMessageAsync(insertedId);

            Assert.NotNull(message);
            Assert.Equal("SqlServerStorageConnectionTest", message.Name);
            Assert.Equal(StatusName.Scheduled, message.StatusName);
        }
Ejemplo n.º 30
0
        public void StoreReceivedMessageAsync_Test()
        {
            var receivedMessage = new CapReceivedMessage
            {
                Id         = SnowflakeId.Default().NextId(),
                Name       = "PostgreSqlStorageConnectionTest",
                Content    = "",
                Group      = "mygroup",
                StatusName = StatusName.Scheduled
            };

            Exception exception = null;

            try
            {
                _storage.StoreReceivedMessage(receivedMessage);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            Assert.Null(exception);
        }