Exemplo n.º 1
0
        public async Task EdgeHubChecksMessageSize()
        {
            // Create a mock endpoint capable of returning a mock processor
            var processor = Mock.Of<IProcessor>();
            var endpoint = new Mock<Endpoint>("myId");
            endpoint.Setup(ep => ep.CreateProcessor()).Returns(processor);
            endpoint.SetupGet(ep => ep.Id).Returns("myId");

            // Create a mock endpoint executor factory to create the endpoint executor to verify invocation
            var endpointExecutor = Mock.Of<IEndpointExecutor>();
            Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object);
            var endpointExecutorFactory = Mock.Of<IEndpointExecutorFactory>();
            Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny<Endpoint>())).ReturnsAsync(endpointExecutor);

            // Create a route to map to the message
            var endpoints = new HashSet<Endpoint> { endpoint.Object };
            var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoints);

            // Create a router
            var routerConfig = new RouterConfig(new[] { route });
            Router router = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory);

            // Create mock for IConnectionManager
            var connectionManager = Mock.Of<IConnectionManager>();

            // Mock of twin manager
            var twinManager = Mock.Of<ITwinManager>();

            // Mock of identity
            var identity = new Mock<IIdentity>();
            identity.SetupGet(id => id.Id).Returns("something");

            var messageConverter = new RoutingMessageConverter();

            Message badMessage = new EdgeMessage.Builder(new byte[300 * 1024]).Build();

            var routingEdgeHub = new RoutingEdgeHub(
                router,
                messageConverter,
                connectionManager,
                twinManager,
                "testEdgeDevice",
                Mock.Of<IInvokeMethodHandler>(),
                Mock.Of<ISubscriptionProcessor>());

            await Assert.ThrowsAsync<EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage));

            string badString = Encoding.UTF8.GetString(new byte[300 * 1024], 0, 300 * 1024);
            var badProperties = new Dictionary<string, string> { ["toolong"] = badString };

            badMessage = new EdgeMessage.Builder(new byte[1]).SetProperties(badProperties).Build();

            await Assert.ThrowsAsync<EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage));

            badMessage = new Message(new byte[1], new Dictionary<string, string>(), badProperties);

            await Assert.ThrowsAsync<EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage));
        }
Exemplo n.º 2
0
        public async Task SendMessageTest()
        {
            // Arrange
            var feedbackStatus = FeedbackStatus.Abandon;
            var deviceListener = new Mock <IDeviceListener>();

            deviceListener.Setup(d => d.ProcessMessageFeedbackAsync(It.IsAny <string>(), It.IsAny <FeedbackStatus>()))
            .Callback <string, FeedbackStatus>((m, s) => feedbackStatus = s)
            .Returns(Task.CompletedTask);
            AmqpMessage receivedAmqpMessage = null;
            var         connectionHandler   = Mock.Of <IConnectionHandler>(c => c.GetDeviceListener() == Task.FromResult(deviceListener.Object));
            var         amqpAuthenticator   = new Mock <IAmqpAuthenticator>();

            amqpAuthenticator.Setup(c => c.AuthenticateAsync("d1")).ReturnsAsync(true);
            Mock <ICbsNode> cbsNodeMock    = amqpAuthenticator.As <ICbsNode>();
            ICbsNode        cbsNode        = cbsNodeMock.Object;
            var             amqpConnection = Mock.Of <IAmqpConnection>(
                c =>
                c.FindExtension <IConnectionHandler>() == connectionHandler &&
                c.FindExtension <ICbsNode>() == cbsNode);
            var amqpSession = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            var sendingLink = Mock.Of <ISendingAmqpLink>(l => l.Session == amqpSession && !l.IsReceiver && l.Settings == new AmqpLinkSettings() && l.State == AmqpObjectState.Opened);

            Mock.Get(sendingLink).Setup(s => s.SendMessageNoWait(It.IsAny <AmqpMessage>(), It.IsAny <ArraySegment <byte> >(), It.IsAny <ArraySegment <byte> >()))
            .Callback <AmqpMessage, ArraySegment <byte>, ArraySegment <byte> >((m, d, t) => { receivedAmqpMessage = m; });

            var requestUri     = new Uri("amqps://foo.bar/devices/d1");
            var boundVariables = new Dictionary <string, string> {
                { "deviceid", "d1" }
            };
            var messageConverter = new AmqpMessageConverter();
            var identity         = Mock.Of <IIdentity>(d => d.Id == "d1");
            var metadataStore    = Mock.Of <IMetadataStore>();

            var      sendingLinkHandler = new DeviceBoundLinkHandler(identity, sendingLink, requestUri, boundVariables, connectionHandler, messageConverter, metadataStore);
            var      body          = new byte[] { 0, 1, 2, 3 };
            IMessage message       = new EdgeMessage.Builder(body).Build();
            var      deliveryState = new Mock <DeliveryState>(new AmqpSymbol(string.Empty), AmqpConstants.AcceptedOutcome.DescriptorCode);
            var      delivery      = Mock.Of <Delivery>(
                d => d.State == deliveryState.Object &&
                d.DeliveryTag == new ArraySegment <byte>(Guid.NewGuid().ToByteArray()));

            // Act
            await sendingLinkHandler.OpenAsync(TimeSpan.FromSeconds(5));

            await sendingLinkHandler.SendMessage(message);

            // Assert
            Assert.NotNull(receivedAmqpMessage);
            Assert.Equal(body, receivedAmqpMessage.GetPayloadBytes());

            // Act
            sendingLinkHandler.DispositionListener(delivery);
            await Task.Delay(TimeSpan.FromSeconds(5));

            // Assert
            Assert.Equal(FeedbackStatus.Complete, feedbackStatus);
        }
Exemplo n.º 3
0
        public async Task AddEdgeSystemPropertiesTest()
        {
            // Create a mock endpoint capable of returning a mock processor
            var endpoint = new Mock<Endpoint>("myId");

            // Create a mock endpoint executor factory to create the endpoint executor to verify invocation
            var endpointExecutor = Mock.Of<IEndpointExecutor>();
            Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object);
            var endpointExecutorFactory = Mock.Of<IEndpointExecutorFactory>();
            Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny<Endpoint>())).ReturnsAsync(endpointExecutor);

            // Create a route to map to the message
            var endpoints = new HashSet<Endpoint> { endpoint.Object };
            var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoints);

            // Create a router
            var routerConfig = new RouterConfig(new[] { route });
            Router router = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory);

            var messageConverter = Mock.Of<Core.IMessageConverter<Devices.Routing.Core.IMessage>>();

            // Create mock for IConnectionManager
            var connectionManager = Mock.Of<IConnectionManager>();

            // Mock of twin manager
            var twinManager = Mock.Of<ITwinManager>();

            string edgeDeviceId = "testEdgeDevice";
            // Test Scenario
            var routingEdgeHub = new RoutingEdgeHub(
                router,
                messageConverter,
                connectionManager,
                twinManager,
                edgeDeviceId,
                Mock.Of<IInvokeMethodHandler>(),
                Mock.Of<ISubscriptionProcessor>());

            Message clientMessage1 = new EdgeMessage.Builder(new byte[0]).Build();
            clientMessage1.SystemProperties[SystemProperties.ConnectionDeviceId] = edgeDeviceId;
            routingEdgeHub.AddEdgeSystemProperties(clientMessage1);
            Assert.True(clientMessage1.SystemProperties.ContainsKey(SystemProperties.EdgeHubOriginInterface));
            Assert.True(clientMessage1.SystemProperties.ContainsKey(SystemProperties.EdgeMessageId));
            Assert.Equal(Constants.InternalOriginInterface, clientMessage1.SystemProperties[SystemProperties.EdgeHubOriginInterface]);

            Message clientMessage2 = new EdgeMessage.Builder(new byte[0]).Build();
            clientMessage2.SystemProperties[SystemProperties.ConnectionDeviceId] = "downstreamDevice";
            routingEdgeHub.AddEdgeSystemProperties(clientMessage2);
            Assert.True(clientMessage2.SystemProperties.ContainsKey(SystemProperties.EdgeHubOriginInterface));
            Assert.True(clientMessage2.SystemProperties.ContainsKey(SystemProperties.EdgeMessageId));
            Assert.Equal(Constants.DownstreamOriginInterface, clientMessage2.SystemProperties[SystemProperties.EdgeHubOriginInterface]);

            Message clientMessage3 = new EdgeMessage.Builder(new byte[0]).Build();
            routingEdgeHub.AddEdgeSystemProperties(clientMessage3);
            Assert.False(clientMessage3.SystemProperties.ContainsKey(SystemProperties.EdgeHubOriginInterface));
            Assert.True(clientMessage3.SystemProperties.ContainsKey(SystemProperties.EdgeMessageId));
        }
Exemplo n.º 4
0
 Task <bool> HandleUpdateReported(Match match, MqttPublishInfo publishInfo)
 {
     return(this.HandleUpstreamRequest(
                async(listener, rid) =>
     {
         var message = new EdgeMessage.Builder(publishInfo.Payload).Build();
         await listener.UpdateReportedPropertiesAsync(message, rid);
     },
                match,
                publishInfo));
 }
        void HandleDesiredProperyUpdate(string id, string version, byte[] payload)
        {
            var messageBuilder = new EdgeMessage.Builder(payload);

            messageBuilder.SetSystemProperties(
                new Dictionary <string, string>()
            {
                [SystemProperties.Version] = version
            });

            _ = this.edgeHub.UpdateDesiredPropertiesAsync(id, messageBuilder.Build());
        }
Exemplo n.º 6
0
        public async Task SendMessageWithFeedbackExactlyOnceModeTest()
        {
            // Arrange
            var feedbackStatus = FeedbackStatus.Abandon;
            var deviceListener = new Mock <IDeviceListener>();

            deviceListener.Setup(d => d.ProcessMessageFeedbackAsync(It.IsAny <string>(), It.IsAny <FeedbackStatus>()))
            .Callback <string, FeedbackStatus>((m, s) => feedbackStatus = s)
            .Returns(Task.CompletedTask);
            AmqpMessage receivedAmqpMessage = null;
            var         connectionHandler   = Mock.Of <IConnectionHandler>(c => c.GetDeviceListener() == Task.FromResult(deviceListener.Object) &&
                                                                           c.GetAmqpAuthentication() == Task.FromResult(new AmqpAuthentication(true, Option.Some(Mock.Of <IClientCredentials>()))));
            var amqpConnection   = Mock.Of <IAmqpConnection>(c => c.FindExtension <IConnectionHandler>() == connectionHandler);
            var amqpSession      = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            var amqpLinkSettings = new AmqpLinkSettings();
            var sendingLink      = Mock.Of <ISendingAmqpLink>(l => l.Session == amqpSession && !l.IsReceiver && l.Settings == amqpLinkSettings && l.State == AmqpObjectState.Opened);

            Mock.Get(sendingLink).Setup(s => s.SendMessageNoWait(It.IsAny <AmqpMessage>(), It.IsAny <ArraySegment <byte> >(), It.IsAny <ArraySegment <byte> >()))
            .Callback <AmqpMessage, ArraySegment <byte>, ArraySegment <byte> >((m, d, t) => { receivedAmqpMessage = m; });

            var requestUri     = new Uri("amqps://foo.bar/devices/d1");
            var boundVariables = new Dictionary <string, string> {
                { "deviceid", "d1" }
            };
            var messageConverter = new AmqpMessageConverter();

            var      sendingLinkHandler = new TestSendingLinkHandler(sendingLink, requestUri, boundVariables, messageConverter, QualityOfService.ExactlyOnce);
            var      body          = new byte[] { 0, 1, 2, 3 };
            IMessage message       = new EdgeMessage.Builder(body).Build();
            var      deliveryState = new Mock <DeliveryState>(new AmqpSymbol(""), AmqpConstants.AcceptedOutcome.DescriptorCode);
            var      delivery      = Mock.Of <Delivery>(d => d.State == deliveryState.Object &&
                                                        d.DeliveryTag == new ArraySegment <byte>(Guid.NewGuid().ToByteArray()));

            // Act
            await sendingLinkHandler.OpenAsync(TimeSpan.FromSeconds(5));

            await sendingLinkHandler.SendMessage(message);

            // Assert
            Assert.NotNull(receivedAmqpMessage);
            Assert.Equal(body, receivedAmqpMessage.GetPayloadBytes());

            // Act
            sendingLinkHandler.DispositionListener(delivery);
            await Task.Delay(TimeSpan.FromSeconds(5));

            // Assert
            Assert.Equal(feedbackStatus, FeedbackStatus.Complete);
            Assert.Equal(null, amqpLinkSettings.SndSettleMode);
            Assert.Equal((byte)ReceiverSettleMode.Second, amqpLinkSettings.RcvSettleMode);
        }
Exemplo n.º 7
0
        public async Task UpdateDesiredPropertiesForwardsToTwinManager()
        {
            // Create a mock endpoint capable of returning a mock processor
            var processor = Mock.Of <IProcessor>();
            var endpoint  = new Mock <Endpoint>("myId");

            endpoint.Setup(ep => ep.CreateProcessor()).Returns(processor);
            endpoint.SetupGet(ep => ep.Id).Returns("myId");

            // Create a mock endpoint executor factory to create the endpoint executor to verify invocation
            var endpointExecutor = Mock.Of <IEndpointExecutor>();

            Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object);
            var endpointExecutorFactory = Mock.Of <IEndpointExecutorFactory>();

            Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny <Endpoint>(), new List <uint>()
            {
                0
            })).ReturnsAsync(endpointExecutor);

            // Create a route to map to the message
            var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoint.Object, 0, 3600);

            // Create a router
            var    routerConfig = new RouterConfig(new[] { route });
            Router router       = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory);

            var      messageConverter  = Mock.Of <Core.IMessageConverter <Devices.Routing.Core.IMessage> >();
            var      connectionManager = Mock.Of <IConnectionManager>();
            var      twinManager       = new Mock <ITwinManager>();
            var      message           = Mock.Of <IMessage>();
            IMessage received          = new EdgeMessage.Builder(new byte[0]).Build();

            twinManager.Setup(t => t.UpdateDesiredPropertiesAsync(It.IsAny <string>(), It.IsAny <IMessage>())).Callback <string, IMessage>((s, m) => received = message).Returns(Task.CompletedTask);
            var routingEdgeHub = new RoutingEdgeHub(
                router,
                messageConverter,
                connectionManager,
                twinManager.Object,
                "testEdgeDevice",
                "$edgeHub",
                Mock.Of <IInvokeMethodHandler>(),
                Mock.Of <ISubscriptionProcessor>(),
                Mock.Of <IDeviceScopeIdentitiesCache>());

            await routingEdgeHub.UpdateDesiredPropertiesAsync("*", message);

            twinManager.Verify(x => x.UpdateDesiredPropertiesAsync("*", message), Times.Once);

            Assert.Equal(message, received);
        }
Exemplo n.º 8
0
        public void ConvertsTwinMessagesToMqttMessages(Twin twin, string expectedJson)
        {
            EdgeMessage expectedMessage = new EdgeMessage.Builder(expectedJson.ToBody())
                                          .SetSystemProperties(new Dictionary <string, string>()
            {
                [SystemProperties.EnqueuedTime] = ""
            })
                                          .Build();
            IMessage actualMessage = new TwinMessageConverter().ToMessage(twin);

            Assert.Equal(expectedMessage.Body, actualMessage.Body);
            Assert.Equal(expectedMessage.Properties, actualMessage.Properties);
            Assert.Equal(expectedMessage.SystemProperties.Keys, actualMessage.SystemProperties.Keys);
        }
Exemplo n.º 9
0
        public async Task SendMessageWithNoFeedbackTest()
        {
            // Arrange
            var productInfoStore = Mock.Of <IProductInfoStore>();
            var modelIdStore     = Mock.Of <IModelIdStore>();
            var identity         = Mock.Of <IIdentity>(i => i.Id == "d1");
            var deviceListener   = new Mock <IDeviceListener>();

            deviceListener.Setup(d => d.ProcessMessageFeedbackAsync(It.IsAny <string>(), It.IsAny <FeedbackStatus>()))
            .Returns(Task.CompletedTask);
            AmqpMessage receivedAmqpMessage = null;
            var         connectionHandler   = Mock.Of <IConnectionHandler>(c => c.GetDeviceListener() == Task.FromResult(deviceListener.Object));
            var         amqpAuthenticator   = new Mock <IAmqpAuthenticator>();

            amqpAuthenticator.Setup(c => c.AuthenticateAsync("d1")).ReturnsAsync(true);
            Mock <ICbsNode> cbsNodeMock    = amqpAuthenticator.As <ICbsNode>();
            ICbsNode        cbsNode        = cbsNodeMock.Object;
            var             amqpConnection = Mock.Of <IAmqpConnection>(
                c =>
                c.FindExtension <IConnectionHandler>() == connectionHandler &&
                c.FindExtension <ICbsNode>() == cbsNode);
            var amqpSession      = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            var amqpLinkSettings = new AmqpLinkSettings();
            var sendingLink      = Mock.Of <ISendingAmqpLink>(l => l.Session == amqpSession && !l.IsReceiver && l.Settings == amqpLinkSettings && l.State == AmqpObjectState.Opened);

            Mock.Get(sendingLink).Setup(s => s.SendMessageAsync(It.IsAny <AmqpMessage>(), It.IsAny <ArraySegment <byte> >(), It.IsAny <ArraySegment <byte> >(), It.IsAny <TimeSpan>()))
            .Callback <AmqpMessage, ArraySegment <byte>, ArraySegment <byte>, TimeSpan>((m, d, t, ts) => { receivedAmqpMessage = m; })
            .Returns(Task.CompletedTask);

            var requestUri     = new Uri("amqps://foo.bar/devices/d1");
            var boundVariables = new Dictionary <string, string> {
                { "deviceid", "d1" }
            };
            var messageConverter = new AmqpMessageConverter();

            var      sendingLinkHandler = new TestSendingLinkHandler(identity, sendingLink, requestUri, boundVariables, connectionHandler, messageConverter, QualityOfService.AtMostOnce, productInfoStore, modelIdStore);
            var      body    = new byte[] { 0, 1, 2, 3 };
            IMessage message = new EdgeMessage.Builder(body).Build();

            // Act
            await sendingLinkHandler.OpenAsync(TimeSpan.FromSeconds(5));

            await sendingLinkHandler.SendMessage(message);

            // Assert
            Assert.NotNull(receivedAmqpMessage);
            Assert.Equal(body, receivedAmqpMessage.GetPayloadBytes());
            Assert.Equal((byte)SenderSettleMode.Settled, amqpLinkSettings.SndSettleMode);
            Assert.Equal((byte)ReceiverSettleMode.First, amqpLinkSettings.RcvSettleMode);
        }
Exemplo n.º 10
0
        public async Task UpdateReportedPropertiesAsync(IMessage reportedPropertiesMessage, string correlationId)
        {
            reportedPropertiesMessage.SystemProperties[SystemProperties.EnqueuedTime]  = DateTime.UtcNow.ToString("o");
            reportedPropertiesMessage.SystemProperties[SystemProperties.MessageSchema] = Constants.TwinChangeNotificationMessageSchema;
            reportedPropertiesMessage.SystemProperties[SystemProperties.MessageType]   = Constants.TwinChangeNotificationMessageType;

            switch (this.Identity)
            {
            case IModuleIdentity moduleIdentity:
                reportedPropertiesMessage.SystemProperties[SystemProperties.RpConnectionDeviceIdInternal] = moduleIdentity.DeviceId;
                reportedPropertiesMessage.SystemProperties[SystemProperties.RpConnectionModuleIdInternal] = moduleIdentity.ModuleId;
                break;

            case IDeviceIdentity deviceIdentity:
                reportedPropertiesMessage.SystemProperties[SystemProperties.RpConnectionDeviceIdInternal] = deviceIdentity.DeviceId;
                break;
            }

            reportedPropertiesMessage.SystemProperties[SystemProperties.ConnectionDeviceId] = this.edgeHub.GetEdgeDeviceId();
            reportedPropertiesMessage.SystemProperties[SystemProperties.ConnectionModuleId] = Constants.EdgeHubModuleId;

            try
            {
                using (Metrics.TimeReportedPropertiesUpdate(this.Identity.Id))
                {
                    await this.edgeHub.UpdateReportedPropertiesAsync(this.Identity, reportedPropertiesMessage);

                    Metrics.AddUpdateReportedProperties(this.Identity.Id);
                    if (!string.IsNullOrWhiteSpace(correlationId))
                    {
                        IMessage responseMessage = new EdgeMessage.Builder(new byte[0])
                                                   .SetSystemProperties(
                            new Dictionary <string, string>
                        {
                            [SystemProperties.CorrelationId] = correlationId,
                            [SystemProperties.EnqueuedTime]  = DateTime.UtcNow.ToString("o"),
                            [SystemProperties.StatusCode]    = ((int)HttpStatusCode.NoContent).ToString()
                        })
                                                   .Build();
                        await this.SendTwinUpdate(responseMessage);
                    }
                }
            }
            catch (Exception e)
            {
                Events.ErrorUpdatingReportedPropertiesTwin(this.Identity, e);
                await this.HandleTwinOperationException(correlationId, e);
            }
        }
Exemplo n.º 11
0
        public async Task OnDesiredPropertyUpdatesForwardsToEdgeHub()
        {
            var      edgeHub  = new Mock <IEdgeHub>();
            var      identity = Mock.Of <IIdentity>(i => i.Id == "device1");
            IMessage actual   = null;

            edgeHub.Setup(r => r.UpdateDesiredPropertiesAsync(It.IsAny <string>(), It.IsAny <IMessage>()))
            .Callback <string, IMessage>((s, m) => actual = m)
            .Returns(Task.FromResult(true));

            IMessage expected      = new EdgeMessage.Builder(Encoding.UTF8.GetBytes("{\"abc\":\"xyz\"}")).Build();
            var      cloudListener = new CloudListener(edgeHub.Object, identity.Id);
            await cloudListener.OnDesiredPropertyUpdates(expected);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 12
0
        public async Task RemoveDesiredPropertyUpdatesSubscription(string correlationId)
        {
            await this.edgeHub.RemoveSubscription(this.Identity.Id, DeviceSubscription.DesiredPropertyUpdates);

            if (!string.IsNullOrWhiteSpace(correlationId))
            {
                IMessage responseMessage = new EdgeMessage.Builder(new byte[0])
                                           .SetSystemProperties(new Dictionary <string, string>
                {
                    [SystemProperties.CorrelationId] = correlationId,
                    [SystemProperties.StatusCode]    = ((int)HttpStatusCode.OK).ToString()
                })
                                           .Build();
                await this.SendTwinUpdate(responseMessage);
            }
        }
Exemplo n.º 13
0
        public async Task InvokedMethodMismatchedResponseTest()
        {
            DeviceMessageHandler deviceMessageHandler = this.GetDeviceMessageHandler();
            var methodRequest = new DirectMethodRequest("device10", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(10));

            Task <DirectMethodResponse> responseTask = deviceMessageHandler.InvokeMethodAsync(methodRequest);

            Assert.False(responseTask.IsCompleted);

            IMessage message = new EdgeMessage.Builder(new byte[0]).Build();

            message.Properties[SystemProperties.CorrelationId] = methodRequest.CorrelationId + 1;
            message.Properties[SystemProperties.StatusCode]    = "200";
            await deviceMessageHandler.ProcessMethodResponseAsync(message);

            Assert.False(responseTask.IsCompleted);
        }
Exemplo n.º 14
0
        public async Task DesiredUpdateRequiresVersion()
        {
            var(connectionRegistry, identityProvider) = GetHandlerDependencies();
            var connector = GetConnector();

            var identity = new DeviceIdentity("hub", "device_id");
            var twin     = new EdgeMessage.Builder(new byte[] { 1, 2, 3 }).Build();

            var sut = new TwinHandler(connectionRegistry, identityProvider);

            sut.SetConnector(connector);

            await sut.SendDesiredPropertiesUpdate(twin, identity, true);

            Mock.Get(connector)
            .Verify(c => c.SendAsync(It.IsAny <string>(), It.IsAny <byte[]>()), Times.Never());
        }
        public void ConvertsTwinCollectionsToMqttMessages(TwinCollection collection, string expectedJson)
        {
            EdgeMessage expectedMessage = new EdgeMessage.Builder(expectedJson.ToBody())
                                          .SetSystemProperties(
                new Dictionary <string, string>()
            {
                [SystemProperties.EnqueuedTime] = string.Empty,
                [SystemProperties.Version]      = collection.Version.ToString()
            })
                                          .Build();
            IMessage actualMessage = new TwinCollectionMessageConverter().ToMessage(collection);

            Assert.Equal(expectedMessage.Body, actualMessage.Body);
            Assert.Equal(expectedMessage.Properties, actualMessage.Properties);
            Assert.Equal(expectedMessage.SystemProperties.Keys, actualMessage.SystemProperties.Keys);
            Assert.Equal(expectedMessage.SystemProperties[SystemProperties.Version], actualMessage.SystemProperties[SystemProperties.Version]);
        }
        public IMessage ToMessage(IProtocolGatewayMessage sourceMessage)
        {
            if (!this.addressConvertor.TryParseProtocolMessagePropsFromAddress(sourceMessage))
            {
                throw new InvalidOperationException("Topic name could not be matched against any of the configured routes.");
            }

            byte[] payloadBytes = this.byteBufferConverter.ToByteArray(sourceMessage.Payload);

            // TODO - What about the other properties (like sequence number, etc)? Ignoring for now, as they are not used anyways.

            var systemProperties = new Dictionary <string, string>();
            var properties       = new Dictionary <string, string>();

            if (sourceMessage.Properties.TryGetValue(TemplateParameters.DeviceIdTemplateParam, out string deviceIdValue))
            {
                systemProperties[SystemProperties.ConnectionDeviceId] = deviceIdValue;
                sourceMessage.Properties.Remove(TemplateParameters.DeviceIdTemplateParam);
            }

            if (sourceMessage.Properties.TryGetValue(Constants.ModuleIdTemplateParameter, out string moduleIdValue))
            {
                systemProperties[SystemProperties.ConnectionModuleId] = moduleIdValue;
                sourceMessage.Properties.Remove(Constants.ModuleIdTemplateParameter);
            }

            foreach (KeyValuePair <string, string> property in sourceMessage.Properties)
            {
                if (SystemProperties.IncomingSystemPropertiesMap.TryGetValue(property.Key, out string systemPropertyName))
                {
                    systemProperties.Add(systemPropertyName, property.Value);
                }
                else
                {
                    properties.Add(property.Key, property.Value);
                }
            }

            EdgeMessage hubMessage = new EdgeMessage.Builder(payloadBytes)
                                     .SetProperties(properties)
                                     .SetSystemProperties(systemProperties)
                                     .Build();

            return(hubMessage);
        }
        public async Task DoesNotSendToDevice()
        {
            var connector          = GetConnector();
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new DeviceIdentity("hub", "device_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new ModuleToModuleMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity);

            Mock.Get(connector)
            .Verify(c => c.SendAsync(It.IsAny <string>(), It.IsAny <byte[]>()), Times.Never());
        }
        public async Task SendsMessageDataAsPayload()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new ModuleIdentity("hub", "device_id", "module_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new ModuleToModuleMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity);

            Assert.Equal(new byte[] { 0x01, 0x02, 0x03 }, capture.Content);
        }
        public async Task EncodesModuleNameInTopic()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new ModuleIdentity("hub", "device_id", "module_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new ModuleToModuleMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity);

            Assert.Equal("$edgehub/device_id/module_id/inputs/some_input/", capture.Topic);
        }
Exemplo n.º 20
0
        public async Task EncodesDeviceNameInTopic()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new DeviceIdentity("hub", "device_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new Cloud2DeviceMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendC2DMessageAsync(message, identity);

            Assert.Equal("$edgehub/device_id/messages/c2d/post/", capture.Topic);
        }
Exemplo n.º 21
0
        public async Task TestProcessMessage()
        {
            var edgeHub  = new Mock <IEdgeHub>();
            var identity = Mock.Of <IIdentity>(i => i.Id == "device1");

            IMessage sentMessage = null;

            edgeHub.Setup(r => r.SendC2DMessageAsync(It.IsAny <string>(), It.IsAny <IMessage>()))
            .Returns(Task.FromResult(true))
            .Callback <string, IMessage>((id, m) => sentMessage = m);

            var cloudListener = new CloudListener(edgeHub.Object, identity.Id);

            var      payload = new byte[] { 1, 2, 3 };
            IMessage message = new EdgeMessage.Builder(payload).Build();
            await cloudListener.ProcessMessageAsync(message);

            Assert.NotNull(sentMessage);
        }
Exemplo n.º 22
0
        async Task HandleTwinOperationException(string correlationId, Exception e)
        {
            if (!string.IsNullOrWhiteSpace(correlationId))
            {
                int statusCode = e is InvalidOperationException || e is ArgumentException
                    ? (int)HttpStatusCode.BadRequest
                    : (int)HttpStatusCode.InternalServerError;

                IMessage responseMessage = new EdgeMessage.Builder(new byte[0])
                                           .SetSystemProperties(new Dictionary <string, string>
                {
                    [SystemProperties.CorrelationId] = correlationId,
                    [SystemProperties.EnqueuedTime]  = DateTime.UtcNow.ToString("o"),
                    [SystemProperties.StatusCode]    = statusCode.ToString()
                })
                                           .Build();
                await this.SendTwinUpdate(responseMessage);
            }
        }
Exemplo n.º 23
0
        public async Task DesiredUpdateCallForwarded()
        {
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new DeviceIdentity("hub", "device_id");

            var desired = new EdgeMessage.Builder(new byte[0]).Build();

            Mock.Get(twinHandler)
            .Setup(h => h.SendDesiredPropertiesUpdate(It.Is <IMessage>(m => m == desired), It.Is <IIdentity>(i => i == identity)))
            .Returns(Task.CompletedTask);

            var sut = new DeviceProxy(identity, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            await sut.OnDesiredPropertyUpdates(desired);

            Mock.Get(directMethodHandler).VerifyAll();
        }
Exemplo n.º 24
0
        public async Task Cloud2DeviceMessagesForwarded()
        {
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new DeviceIdentity("hub", "device_id");

            var message = new EdgeMessage.Builder(new byte[0]).Build();

            Mock.Get(c2dHandler)
            .Setup(h => h.SendC2DMessageAsync(It.Is <IMessage>(m => m == message), It.Is <IIdentity>(i => i == identity)))
            .Returns(Task.CompletedTask);

            var sut = new DeviceProxy(identity, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            await sut.SendC2DMessageAsync(message);

            Mock.Get(directMethodHandler).VerifyAll();
        }
Exemplo n.º 25
0
        public async Task MultipleMessageCompletionTest()
        {
            var connMgr = new Mock <IConnectionManager>();

            connMgr.Setup(c => c.AddDeviceConnection(It.IsAny <IIdentity>(), It.IsAny <IDeviceProxy>()));
            var identity   = Mock.Of <IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1");
            var cloudProxy = new Mock <ICloudProxy>();

            cloudProxy.Setup(c => c.SendFeedbackMessageAsync(It.IsAny <string>(), It.IsAny <FeedbackStatus>()))
            .Returns(Task.CompletedTask);
            var      edgeHub = Mock.Of <IEdgeHub>();
            var      underlyingDeviceProxy = new Mock <IDeviceProxy>();
            IMessage receivedMessage       = null;

            underlyingDeviceProxy.Setup(d => d.SendMessageAsync(It.IsAny <IMessage>(), It.IsAny <string>()))
            .Callback <IMessage, string>((m, s) => receivedMessage = m)
            .Returns(Task.CompletedTask);
            connMgr.Setup(c => c.GetCloudConnection(It.IsAny <string>())).Returns(Task.FromResult(Option.Some(cloudProxy.Object)));
            var deviceMessageHandler = new DeviceMessageHandler(identity, edgeHub, connMgr.Object, DefaultMessageAckTimeout, Option.None <string>());

            deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object);

            IMessage message         = new EdgeMessage.Builder(new byte[0]).Build();
            Task     sendMessageTask = deviceMessageHandler.SendMessageAsync(message, "input1");

            Assert.False(sendMessageTask.IsCompleted);

            string messageId = receivedMessage.SystemProperties[SystemProperties.LockToken];
            await deviceMessageHandler.ProcessMessageFeedbackAsync(messageId, FeedbackStatus.Complete);

            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.True(sendMessageTask.IsCompleted);

            await deviceMessageHandler.ProcessMessageFeedbackAsync(messageId, FeedbackStatus.Complete);

            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.True(sendMessageTask.IsCompleted);
            cloudProxy.Verify(c => c.SendFeedbackMessageAsync(It.IsAny <string>(), It.IsAny <FeedbackStatus>()), Times.Never);
        }
Exemplo n.º 26
0
        public async Task EdgeHubIsIndirect()
        {
            var connectionHandler   = Mock.Of <IConnectionRegistry>();
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new ModuleIdentity("hub", "device_id", "$edgeHub");

            var twin = new EdgeMessage.Builder(new byte[0]).Build();

            Mock.Get(twinHandler)
            .Setup(h => h.SendTwinUpdate(It.IsAny <IMessage>(), It.Is <IIdentity>(i => i == identity), It.Is <bool>(d => d == false)))
            .Returns(Task.CompletedTask);

            var sut = new DeviceProxy(identity, true, connectionHandler, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            await sut.SendTwinUpdate(twin);

            Mock.Get(twinHandler).VerifyAll();
        }
Exemplo n.º 27
0
        public async Task TestHandleNonRecoverableExceptions(Type exceptionType)
        {
            // Arrange
            var      messageConverter         = Mock.Of <IMessageConverter <Message> >(m => m.FromMessage(It.IsAny <IMessage>()) == new Message());
            var      messageConverterProvider = Mock.Of <IMessageConverterProvider>(m => m.Get <Message>() == messageConverter);
            string   clientId      = "d1";
            var      cloudListener = Mock.Of <ICloudListener>();
            TimeSpan idleTimeout   = TimeSpan.FromSeconds(60);
            Action <string, CloudConnectionStatus> connectionStatusChangedHandler = (s, status) => { };
            var client = new Mock <IClient>(MockBehavior.Strict);

            client.Setup(c => c.SendEventAsync(It.IsAny <Message>())).ThrowsAsync((Exception)Activator.CreateInstance(exceptionType, "dummy message"));
            client.Setup(c => c.CloseAsync()).Returns(Task.CompletedTask);
            var      cloudProxy = new CloudProxy(client.Object, messageConverterProvider, clientId, connectionStatusChangedHandler, cloudListener, idleTimeout, false);
            IMessage message    = new EdgeMessage.Builder(new byte[0]).Build();

            // Act
            await Assert.ThrowsAsync(exceptionType, () => cloudProxy.SendMessageAsync(message));

            // Assert.
            client.VerifyAll();
        }
Exemplo n.º 28
0
        public IMessage ToMessage(AmqpMessage amqpMessage)
        {
            var properties = new Dictionary <string, string>();

            if (amqpMessage.Properties.CorrelationId != null)
            {
                properties[SystemProperties.CorrelationId] = amqpMessage.Properties.CorrelationId.ToString();
            }

            if (amqpMessage.ApplicationProperties.Map.TryGetValue(Constants.MessagePropertiesStatusKey, out int status))
            {
                properties[SystemProperties.StatusCode] = status.ToString();
            }

            byte[] payload = amqpMessage.GetPayloadBytes();

            EdgeMessage message = new EdgeMessage.Builder(payload)
                                  .SetProperties(properties)
                                  .Build();

            return(message);
        }
Exemplo n.º 29
0
        public async Task Moudle2MoudleMessagesForwarded()
        {
            var connectionHandler   = Mock.Of <IConnectionRegistry>();
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new DeviceIdentity("hub", "device_id");

            var input   = "input";
            var message = new EdgeMessage.Builder(new byte[0]).Build();

            Mock.Get(m2mHandler)
            .Setup(h => h.SendModuleToModuleMessageAsync(It.Is <IMessage>(m => m == message), It.Is <string>(s => s == input), It.Is <IIdentity>(i => i == identity), It.IsAny <bool>()))
            .Returns(Task.CompletedTask);

            var sut = new DeviceProxy(identity, true, connectionHandler, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            await sut.SendMessageAsync(message, input);

            Mock.Get(m2mHandler).VerifyAll();
        }
Exemplo n.º 30
0
            public async Task <DirectMethodResponse> InvokeMethodAsync(DirectMethodRequest request)
            {
                if (!this.connectionHandler.registry.TryGetValue(LinkType.MethodSending, out ILinkHandler linkHandler))
                {
                    Events.LinkNotFound(LinkType.ModuleMessages, this.Identity, "method request");
                    return(default(DirectMethodResponse));
                }

                IMessage message = new EdgeMessage.Builder(request.Data)
                                   .SetProperties(new Dictionary <string, string>
                {
                    [Constants.MessagePropertiesMethodNameKey] = request.Name
                })
                                   .SetSystemProperties(new Dictionary <string, string>
                {
                    [SystemProperties.CorrelationId] = request.CorrelationId
                })
                                   .Build();

                await((ISendingLinkHandler)linkHandler).SendMessage(message);
                return(default(DirectMethodResponse));
            }