Esempio n. 1
0
            public override void Recieve(IPublishedMessage message)
            {
                var payload = message.GetPayload <Payload>();

                Assert.AreEqual(123, payload.x);
                Assert.AreEqual(321, payload.y);
            }
        public virtual void Handle(IPublishedMessage <TCommand> message)
        {
            var command   = message.Payload;
            var aggregate = repository.GetById <TAggregate>(command.AggregateId);

            HandleCommand(aggregate, command);
        }
Esempio n. 3
0
        public async Task Should_contain_the_same_payloads()
        {
            var publishObserver = new BusTestPublishObserver(TimeSpan.FromSeconds(3));

            using (Bus.ConnectPublishObserver(publishObserver))
            {
                await Bus.Publish(new A());

                IPublishedMessage <A> a = publishObserver.Messages.Select <A>().FirstOrDefault();
                IPublishedMessage <B> b = publishObserver.Messages.Select <B>().FirstOrDefault();

                a.ShouldNotBeNull();
                b.ShouldNotBeNull();

                Dictionary <string, object> ah = a.Context.Headers.GetAll().ToDictionary(x => x.Key, x => x.Value);
                Dictionary <string, object> bh = b.Context.Headers.GetAll().ToDictionary(x => x.Key, x => x.Value);

                ah.ShouldContainKey("x-send-filter");
                ah.ShouldContainKey("x-send-message-filter");
                ah["x-send-filter"].ShouldBe("send-filter");
                ah["x-send-message-filter"].ShouldBe("send-message-filter");

                bh.ShouldContainKey("x-send-filter");
                bh.ShouldContainKey("x-send-message-filter");

                // those fails, as while they DO have ",has-consume-context" they don't have access to SomePayload
                bh["x-send-filter"].ShouldBe("send-filter,has-consume-context,has-some-payload:hello");
                bh["x-send-message-filter"].ShouldBe("send-message-filter,has-consume-context,has-some-payload:hello");
            }
        }
        public async void HandleMessage(IPublishedMessage publishedMessage)
        {
            try
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    // Create a scope so all dependency injections are available.
                    var text = Encoding.UTF8.GetString(publishedMessage.DataBytes);

                    var packageMessage = JsonConvert.DeserializeObject <PackageMessage>(text);
                    //if (_serverIdentityService.Id.Equals(packageMessage.ServerId)) // Do not process own package messages
                    //   return;

                    logger.LogInformation($"Received message from {packageMessage.ServerId}");

                    _packageMessageValidator.Validate(packageMessage);

                    var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();
                    var package  = mediator.SendAndWait(new FetchPackageCommand(packageMessage.File));

                    if (package == null)
                    {
                        logger.LogError($"Error wrong notitifiation returned from FatchPackageCommand");
                        return;
                    }

                    if (package.Timestamps == null || package.Timestamps.Count == 0)
                    {
                        logger.LogError($"Error no timestamps was found on package id {package.Id} from server id {packageMessage.ServerId}");
                        return;
                    }

                    var packageValidator = scope.ServiceProvider.GetRequiredService <IPackageSchemaValidator>();
                    SchemaValidationResult validationResult = packageValidator.Validate(package); //
                    if (validationResult.ErrorsFound > 0)
                    {
                        logger.LogError(validationResult.ToString());
                        return;
                    }

                    var timestampValidator = scope.ServiceProvider.GetRequiredService <ITimestampProofValidator>();
                    if (!timestampValidator.Validate(package.Timestamps[0], out IList <string> errors))
                    {
                        var msg = string.Join(", ", errors);
                        logger.LogError(msg);
                        return;
                    }

                    //var peers = await Ipfs.PubSub.PublishAsync;

                    // Now add the package!
                    await mediator.Send(new AddPackageCommand(package));
                }
            }
            catch (Exception ex)
            {
                var msg = $"Message from server {publishedMessage.Sender.Id} failed with: {ex.Message}";
                logger.LogError(msg);
            }
        }
Esempio n. 5
0
 /// <summary>
 ///     Create a new instance of the <see cref="MessageDto" />
 ///     from the <see cref="IPublishedMessage" />.
 /// </summary>
 /// <param name="msg">
 ///     A pubsub messagee.
 /// </param>
 public MessageDto(IPublishedMessage msg)
 {
     From     = Convert.ToBase64String(msg.Sender.Id.ToArray());
     Seqno    = Convert.ToBase64String(msg.SequenceNumber);
     Data     = Convert.ToBase64String(msg.DataBytes);
     TopicIDs = msg.Topics.ToArray();
 }
Esempio n. 6
0
            public Message(IPublishedMessage message)
                : this(message.Context)
            {
                MessageType   = message.MessageType;
                ShortTypeName = message.ShortTypeName;
                EventType     = MessageEventType.Publish;

                StartTime   = message.StartTime;
                ElapsedTime = message.ElapsedTime;
            }
Esempio n. 7
0
 public void Add(IPublishedMessage message)
 {
     lock (_messages)
     {
         if (_messages.Add(message))
         {
             _published.Set();
         }
     }
 }
Esempio n. 8
0
        public void Publish(IPublishedMessage message)
        {
            this.Logger.LogInformation($"Publishing event '{message.Id}' of type '{message.Type}'.");
            var subscribers = (this.broker as MessageBroker).GetSubscribers(message.Type);

            foreach (var subscriber in subscribers)
            {
                subscriber.Recieve(message);
            }

            this.Logger.LogInformation($"{subscribers.Count()} subscribers notified.");
        }
 public void Handle(IPublishedMessage <TestData> message)
 {
     messageReceived = message;
 }
Esempio n. 10
0
 public virtual void Recieve(IPublishedMessage message)
 {
     //var response = MessageResponse.Default;
     //var uriPatched = new PublishSubscribeMessage(message);
     //this.OnRecieve?.Invoke(uriPatched, out response);
 }
Esempio n. 11
0
        public async Task Relays_PublishedMessage()
        {
            var topic = Guid.NewGuid().ToString();

            var swarm1 = new SwarmService {
                LocalPeer = self
            };
            var router1 = new FloodRouter {
                SwarmService = swarm1
            };
            var ns1 = new PubSubService {
                LocalPeer = self
            };

            ns1.Routers.Add(router1);
            await swarm1.StartAsync();

            await ns1.StartAsync();

            var swarm2 = new SwarmService {
                LocalPeer = other
            };
            var router2 = new FloodRouter {
                SwarmService = swarm2
            };
            var ns2 = new PubSubService {
                LocalPeer = other
            };

            ns2.Routers.Add(router2);
            await swarm2.StartAsync();

            await ns2.StartAsync();

            var swarm3 = new SwarmService {
                LocalPeer = other1
            };
            var router3 = new FloodRouter {
                SwarmService = swarm3
            };
            var ns3 = new PubSubService {
                LocalPeer = other1
            };

            ns3.Routers.Add(router3);
            await swarm3.StartAsync();

            await ns3.StartAsync();

            try
            {
                IPublishedMessage lastMessage2 = null;
                IPublishedMessage lastMessage3 = null;
                await swarm1.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                await swarm2.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                await swarm3.StartListeningAsync("/ip4/127.0.0.1/tcp/0");

                var cs = new CancellationTokenSource();
                await ns2.SubscribeAsync(topic, msg => lastMessage2 = msg, cs.Token);

                await ns3.SubscribeAsync(topic, msg => lastMessage3 = msg, cs.Token);

                await swarm1.ConnectAsync(other, cs.Token);

                await swarm3.ConnectAsync(other, cs.Token);

                var peers   = new Peer[0];
                var endTime = DateTime.Now.AddSeconds(3);
                while (peers.Length == 0)
                {
                    if (DateTime.Now > endTime)
                    {
                        Assert.Fail("timeout");
                    }

                    await Task.Delay(100, cs.Token);

                    peers = (await ns2.PeersAsync(topic, cs.Token)).ToArray();
                }

                CollectionAssert.Contains(peers, other1);

                await ns1.PublishAsync(topic, new byte[] { 1 }, cs.Token);

                endTime = DateTime.Now.AddSeconds(3);
                while (lastMessage2 == null || lastMessage3 == null)
                {
                    if (DateTime.Now > endTime)
                    {
                        Assert.Fail("timeout");
                    }

                    await Task.Delay(100, cs.Token);
                }

                Assert.IsNotNull(lastMessage2);
                Assert.AreEqual(self, lastMessage2.Sender);
                CollectionAssert.AreEqual(new byte[] { 1 }, lastMessage2.DataBytes);
                CollectionAssert.Contains(lastMessage2.Topics.ToArray(), topic);

                Assert.IsNotNull(lastMessage3);
                Assert.AreEqual(self, lastMessage3.Sender);
                CollectionAssert.AreEqual(new byte[] { 1 }, lastMessage3.DataBytes);
                CollectionAssert.Contains(lastMessage3.Topics.ToArray(), topic);
            }
            finally
            {
                await swarm1.StopAsync();

                await ns1.StopAsync();

                await swarm2.StopAsync();

                await ns2.StopAsync();

                await swarm3.StopAsync();

                await ns3.StopAsync();
            }
        }
Esempio n. 12
0
 public void Handle(IPublishedMessage <object> message)
 {
     messageReceivedForObject = message;
 }
Esempio n. 13
0
 public void Publish(IPublishedMessage message)
 {
     this.publishSubscribeChannel.Publish(message);
 }
Esempio n. 14
0
 public virtual void Handle(IPublishedMessage <T> message)
 {
     Handle(message.Payload);
 }
Esempio n. 15
0
 public void AddPublished(IPublishedMessage message)
 {
     _published.Add(message);
 }
Esempio n. 16
0
 public void Handle(IPublishedMessage <ExtendedTestData> message)
 {
     messageReceivedForExtendedTestData = message;
 }
 bool Filter(IPublishedMessage element)
 {
     return(element is IPublishedMessage <T> result && filter(result));
 }
 public void Handle(IPublishedMessage <TestData> message)
 {
 }