Exemple #1
0
        public void EventSourceClient_IncorrectFormat_ShouldReceiveError()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SSE_Channels_Response(
                    @"{ 'event': 'message', 
                        'data': {
                            'id':'1',
                            'channel':'mauroc',
                            'content': {
                                'type': 'CONTROL', 
                                'controlType': 'test-control-type'
                            },
                            'name':'name-test'
                         }
                        }");

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _connectedEvent.TryTake(out EventArgs e, -1);
                Assert.IsNotNull(e);
                Assert.AreEqual(0, _eventsReceived.Count);

                eventSourceClient.Disconnect();
            }
        }
Exemple #2
0
        public void EventSourceClient_NotificationError_ShouldReceiveError()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "event: error\ndata: {\"message\":\"Token expired\",\"code\":40142,\"statusCode\":401,\"href\":\"https://help.ably.io/error/40142\"}\n\n";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.DISCONNECT, action.Action);
            }
        }
Exemple #3
0
        public void EventSourceClient_SplitUpdateEvent_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"xxxx_xxxx_splits\",\"data\":\"{\\\"type\\\":\\\"SPLIT_UPDATE\\\",\\\"changeNumber\\\":1585867723838}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient();
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _eventsReceived.TryTake(out EventReceivedEventArgs ev, -1);
                Assert.IsTrue(eventSourceClient.IsConnected());
                Assert.AreEqual(NotificationType.SPLIT_UPDATE, ev.Event.Type);
                Assert.AreEqual(1585867723838, ((SplitChangeNotifiaction)ev.Event).ChangeNumber);
                Assert.IsTrue(_connectedEvent.Count >= 1);

                eventSourceClient.Disconnect();
            }
        }
Exemple #4
0
        public void EventSourceClient_ControlEvent_StreamingDisabled_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"control_pri\",\"data\":\"{\\\"type\\\":\\\"CONTROL\\\",\\\"controlType\\\":\\\"STREAMING_DISABLED\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _eventsReceived.TryTake(out EventReceivedEventArgs ev, -1);
                Assert.AreEqual(NotificationType.CONTROL, ev.Event.Type);
                Assert.AreEqual(ControlType.STREAMING_DISABLED, ((ControlNotification)ev.Event).ControlType);
                Assert.IsTrue(_connectedEvent.Count >= 1);

                eventSourceClient.Disconnect();
            }
        }
Exemple #5
0
        public void EventSourceClient_KeepAliveResponse()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SSE_Channels_Response(":keepalive\n\n");

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
                Thread.Sleep(1000);
                Assert.AreEqual(0, eventsReceived.Count);
            }
        }
Exemple #6
0
        public void EventSourceClient_ControlEvent_StreamingDisabled_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"[?occupancy=metrics.publishers]control_pri\",\"data\":\"{\\\"type\\\":\\\"CONTROL\\\",\\\"controlType\\\":\\\"STREAMING_DISABLED\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                eventsReceived.TryTake(out EventReceivedEventArgs ev, 10000);
                Assert.AreEqual(NotificationType.CONTROL, ev.Event.Type);
                Assert.AreEqual(ControlType.STREAMING_DISABLED, ((ControlNotification)ev.Event).ControlType);
                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
            }
        }
Exemple #7
0
        public void EventSourceClient_SegmentUpdateEvent_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"xxxx_xxxx_segments\",\"data\":\"{\\\"type\\\":\\\"SEGMENT_UPDATE\\\",\\\"changeNumber\\\":1585868933303,\\\"segmentName\\\":\\\"test-segment\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _eventsReceived.TryTake(out EventReceivedEventArgs ev, -1);
                Assert.AreEqual(NotificationType.SEGMENT_UPDATE, ev.Event.Type);
                Assert.AreEqual(1585868933303, ((SegmentChangeNotification)ev.Event).ChangeNumber);
                Assert.AreEqual("test-segment", ((SegmentChangeNotification)ev.Event).SegmentName);
                _connectedEvent.TryTake(out EventArgs e, -1);
                Assert.IsNotNull(e);
            }
        }
Exemple #8
0
        public void EventSourceClient_SplitKillEvent_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"xxxx_xxxx_splits\",\"data\":\"{\\\"type\\\":\\\"SPLIT_KILL\\\",\\\"changeNumber\\\":1585868246622,\\\"defaultTreatment\\\":\\\"off\\\",\\\"splitName\\\":\\\"test-split\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _eventsReceived.TryTake(out EventReceivedEventArgs ev, -1);
                Assert.AreEqual(NotificationType.SPLIT_KILL, ev.Event.Type);
                Assert.AreEqual(1585868246622, ((SplitKillNotification)ev.Event).ChangeNumber);
                Assert.AreEqual("off", ((SplitKillNotification)ev.Event).DefaultTreatment);
                Assert.AreEqual("test-split", ((SplitKillNotification)ev.Event).SplitName);
                Assert.IsTrue(_connectedEvent.Count >= 1);

                eventSourceClient.Disconnect();
            }
        }
Exemple #9
0
        public void EventSourceClient_KeepAliveResponse()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SSE_Channels_Response(":keepalive\n\n");

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _connectedEvent.TryTake(out EventArgs e, -1);
                Assert.IsNotNull(e);
                Thread.Sleep(1000);
                Assert.AreEqual(0, _eventsReceived.Count);

                eventSourceClient.Disconnect();
            }
        }
Exemple #10
0
        public void EventSourceClient_SegmentUpdateEvent_ShouldReceiveEvent()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "id: 234234432\nevent: message\ndata: {\"id\":\"jSOE7oGJWo:0:0\",\"clientId\":\"pri:ODc1NjQyNzY1\",\"timestamp\":1588254699236,\"encoding\":\"json\",\"channel\":\"xxxx_xxxx_segments\",\"data\":\"{\\\"type\\\":\\\"SEGMENT_UPDATE\\\",\\\"changeNumber\\\":1585868933303,\\\"segmentName\\\":\\\"test-segment\\\"}\"}";
                httpClientMock.SSE_Channels_Response(notification);

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                eventsReceived.TryTake(out EventReceivedEventArgs ev, 10000);
                Assert.AreEqual(NotificationType.SEGMENT_UPDATE, ev.Event.Type);
                Assert.AreEqual(1585868933303, ((SegmentChangeNotification)ev.Event).ChangeNumber);
                Assert.AreEqual("test-segment", ((SegmentChangeNotification)ev.Event).SegmentName);
                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
            }
        }
Exemple #11
0
 public static void Main(string[] args)
 {
     using (var client = new EventSourceClient("http://localhost:8080/v1/testapp/testchannel"))
     {
         client.Event += (sender, e) => Console.WriteLine("Event: " + e.Data);
         client.Start();
         Console.ReadLine();
     }
 }
Exemple #12
0
        private EventSourceClient CreateClient(Uri uri, Action <dynamic> callback)
        {
            var client = new EventSourceClient(uri);

            client.Event     += (sender, e) => { Debug.WriteLine("[SignalhubSubscriber] Event Received"); callback(e.Data); };
            client.Heartbeat += (sender, e) => { LastHeartbeatReceived = DateTime.Now; Debug.WriteLine("[SignalhubSubscriber] Heartbeat"); };
            client.Start();
            return(client);
        }
Exemple #13
0
        /// <summary>
        /// Subscribe to the service
        /// Messages are sent to service message listener until enter is pressed.
        /// </summary>
        /// <param name="method">A method from GetSubscribableMethods</param>
        public void SubscribeMethod(MethodInfo method)
        {
            if (!Initialized)
            {
                throw new InvalidOperationException("Service not initialized");
            }

            Object[] subAttributes = method.GetCustomAttributes(typeof(DPWSSubscription), true);
            if (subAttributes.Length < 1)
            {
                throw new ArgumentException("Not a subscribable method");
            }

            String eventOut = ((DPWSSubscription)subAttributes[0]).EventOut;

            /// Open connection
            InstanceContext instanceContext = new InstanceContext(this);
            Object          client          = Activator.CreateInstance(clientType, instanceContext, GetConfigurationName());
            ServiceEndpoint endpoint        = (ServiceEndpoint)endpointField.GetValue(client, null);

            endpoint.Address = endpointAddress;
            endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 0, 2);

            clientOpenMethod.Invoke(client, null);


            IDuplexContextChannel innerDuplexChannel = (IDuplexContextChannel)clientChannelField.GetValue(client, null);
            EndpointAddress       callbackEndpoint   = innerDuplexChannel.LocalAddress;
            EventSourceClient     eventSource        = new EventSourceClient(instanceContext, "WSEventing");

            eventSource.Endpoint.Address = endpointAddress;
            eventSource.Open();
            String subscriptionId = SubscribeMsg(eventSource, callbackEndpoint, eventOut);

            /// Invoke

            Console.WriteLine("Got subscription: {0}", subscriptionId);

            object[] args = new object[] { client };
            try
            {
                method.Invoke(this, args);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("Press <ENTER> to unsubscribe.");
            Console.ReadLine();

            Console.WriteLine("Unsubscribing {0}", subscriptionId);

            /// Close connection
            UnsubscribeMsg(subscriptionId);
            clientCloseMethod.Invoke(client, null);
        }
Exemple #14
0
        /// <summary>
        /// Send the subscription message to the endpoint
        /// </summary>
        /// <param name="eventSource"></param>
        /// <param name="callbackEndpoint"></param>
        /// <param name="eventOut"></param>
        /// <returns></returns>
        ///
        protected String SubscribeMsg(EventSourceClient eventSource, EndpointAddress callbackEndpoint, String eventOut)
        {
            Subscribe s = new Subscribe();

            (s.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";

            XmlDocument doc = new XmlDocument();

            using (XmlWriter writer = doc.CreateNavigator().AppendChild())
            {
                EndpointReferenceType notifyTo = new EndpointReferenceType();

                (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint.Uri.AbsoluteUri;

                XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo");
                notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing";

                XmlDocument doc2 = new XmlDocument();
                using (XmlWriter writer2 = doc2.CreateNavigator().AppendChild())
                {
                    XmlRootAttribute ReferenceElement = new XmlRootAttribute("ReferenceElement");
                    foreach (AddressHeader h in callbackEndpoint.Headers)
                    {
                        h.WriteAddressHeader(writer2);
                    }

                    writer2.Close();
                    notifyTo.ReferenceParameters     = new ReferenceParametersType();
                    notifyTo.ReferenceParameters.Any = notifyTo.ReferenceParameters.Any = doc2.ChildNodes.Cast <XmlElement>().ToArray <XmlElement>();
                }

                new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo);
            }

            (s.Delivery.Any = new XmlElement[1])[0]       = doc.DocumentElement;
            (s.Filter = new FilterType()).Dialect         = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action";
            (s.Filter.Any = new System.Xml.XmlNode[1])[0] = new System.Xml.XmlDocument().CreateTextNode(eventOut);

            SubscribeResponse subscription;

            Console.WriteLine("Subscribing to the event...");
            //Console.ReadLine();
            subscription = eventSource.SubscribeOp(s);


            String subscriptionId = null;

            foreach (XmlNode xel in subscription.SubscriptionManager.ReferenceParameters.Any)
            {
                if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing"))
                {
                    subscriptionId = xel.InnerText;
                }
            }
            return(subscriptionId);
        }
Exemple #15
0
        private void BuildSyncManager()
        {
            try
            {
                // Synchronizer
                var impressionsCountSender = new ImpressionsCountSender(_impressionsSdkApiClient, _impressionsCounter, _tasksManager);
                var backOff      = new BackOff(backOffBase: 10, attempt: 0, maxAllowed: 60);
                var synchronizer = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, impressionsCountSender, _wrapperAdapter, _statusManager, _telemetrySyncTask, _tasksManager, _splitCache, backOff, _config.OnDemandFetchMaxRetries, _config.OnDemandFetchRetryDelayMs, _segmentCache);

                // Workers
                var splitsWorker   = new SplitsWorker(_splitCache, synchronizer, _tasksManager);
                var segmentsWorker = new SegmentsWorker(synchronizer, _tasksManager);

                // NotificationProcessor
                var notificationProcessor = new NotificationProcessor(splitsWorker, segmentsWorker);

                // NotificationParser
                var notificationParser = new NotificationParser();

                // NotificationManagerKeeper
                var notificationManagerKeeper = new NotificationManagerKeeper(_telemetryRuntimeProducer);

                // EventSourceClient
                var headers = GetHeaders();
                headers.Add(Constants.Http.SplitSDKClientKey, ApiKey.Substring(ApiKey.Length - 4));
                headers.Add(Constants.Http.Accept, Constants.Http.EventStream);
                var sseHttpClient     = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, headers);
                var eventSourceClient = new EventSourceClient(notificationParser, _wrapperAdapter, sseHttpClient, _telemetryRuntimeProducer, _tasksManager);

                // SSEHandler
                var sseHandler = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);

                // AuthApiClient
                var httpClient    = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, GetHeaders());
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, httpClient, _telemetryRuntimeProducer);

                // PushManager
                var backoff     = new BackOff(_config.AuthRetryBackoffBase, attempt: 1);
                var pushManager = new PushManager(sseHandler, authApiClient, _wrapperAdapter, _telemetryRuntimeProducer, backoff);

                // SyncManager
                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper, _telemetryRuntimeProducer, _statusManager, _tasksManager, _wrapperAdapter, _telemetrySyncTask);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
Exemple #16
0
        public void EventSourceClient_IncorrectFormat_ShouldReceiveError()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SSE_Channels_Response(
                    @"{ 'event': 'message', 
                        'data': {
                            'id':'1',
                            'channel':'mauroc',
                            'content': {
                                'type': 'CONTROL', 
                                'controlType': 'test-control-type'
                            },
                            'name':'name-test'
                         }
                        }");

                var url            = httpClientMock.GetUrl();
                var eventsReceived = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                var actionEvent    = new BlockingCollection <SSEActionsEventArgs>(new ConcurrentQueue <SSEActionsEventArgs>());

                var notificationParser       = new NotificationParser();
                var wrapperAdapter           = new WrapperAdapter();
                var sseHttpClient            = new SplitioHttpClient("api-key", 5000);
                var telemetryRuntimeProducer = new InMemoryTelemetryStorage();

                var eventSourceClient = new EventSourceClient(notificationParser, wrapperAdapter, sseHttpClient, telemetryRuntimeProducer, new TasksManager(wrapperAdapter));
                eventSourceClient.EventReceived += delegate(object sender, EventReceivedEventArgs e)
                {
                    eventsReceived.TryAdd(e);
                };
                eventSourceClient.ActionEvent += delegate(object sender, SSEActionsEventArgs e)
                {
                    actionEvent.TryAdd(e);
                };
                eventSourceClient.ConnectAsync(url);

                actionEvent.TryTake(out SSEActionsEventArgs action, 10000);
                Assert.AreEqual(SSEClientActions.CONNECTED, action.Action);
                Assert.AreEqual(0, eventsReceived.Count);
            }
        }
Exemple #17
0
        public void EventSourceClient_NotificationError_ShouldReceiveError()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                var notification = "event: error\ndata: {\"message\":\"Token expired\",\"code\":40142,\"statusCode\":401,\"href\":\"https://help.ably.io/error/40142\"}\n\n";
                httpClientMock.SSE_Channels_Response(notification);

                var url = httpClientMock.GetUrl();
                _eventsReceived  = new BlockingCollection <EventReceivedEventArgs>(new ConcurrentQueue <EventReceivedEventArgs>());
                _connectedEvent  = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());
                _disconnectEvent = new BlockingCollection <EventArgs>(new ConcurrentQueue <EventArgs>());

                var eventSourceClient = new EventSourceClient(backOffBase: 5);
                eventSourceClient.EventReceived   += EventReceived;
                eventSourceClient.ConnectedEvent  += ConnectedEvent;
                eventSourceClient.DisconnectEvent += DisconnectEvent;
                eventSourceClient.ConnectAsync(url);

                _disconnectEvent.TryTake(out EventArgs e, -1);
                Assert.IsNotNull(e);
            }
        }
Exemple #18
0
        private void BuildSyncManager()
        {
            try
            {
                var synchronizer              = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, _metricsLog, _wrapperAdapter);
                var splitsWorker              = new SplitsWorker(_splitCache, synchronizer);
                var segmentsWorker            = new SegmentsWorker(_segmentCache, synchronizer);
                var notificationProcessor     = new NotificationProcessor(splitsWorker, segmentsWorker);
                var notificationParser        = new NotificationParser();
                var eventSourceClient         = new EventSourceClient(_config.StreamingReconnectBackoffBase, notificationParser: notificationParser);
                var notificationManagerKeeper = new NotificationManagerKeeper();
                var sseHandler    = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, _config.HttpReadTimeout);
                var pushManager   = new PushManager(_config.AuthRetryBackoffBase, sseHandler, authApiClient, _wrapperAdapter);

                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
        private static void subscribeToLDC(EndpointAddress hostedEndPoint)
        {
            Console.WriteLine("Starting subscription event...");

            //  endpointAddress = StartDiscoveryProcess(false);
            if (hostedEndPoint != null)
            {
                //Get Metadata of the address.
                //  EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                InstanceContext ithis = new InstanceContext(new DiscoveryCallBack());

                using (AccelerationServiceClient client = new AccelerationServiceClient(ithis))
                {
                    client.Endpoint.Address = hostedEndPoint;
                    client.Open();

                    EndpointAddress   callbackEndpoint = client.InnerDuplexChannel.LocalAddress;
                    EventSourceClient eventSource      = new EventSourceClient(ithis, "WSEventing");
                    eventSource.Endpoint.Address = hostedEndPoint;
                    eventSource.Open();

                    Subscribe s = new Subscribe();
                    (s.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";

                    XmlDocument doc = new XmlDocument();
                    using (XmlWriter writer = doc.CreateNavigator().AppendChild())
                    {
                        EndpointReferenceType notifyTo = new EndpointReferenceType();

                        (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint.Uri.AbsoluteUri;

                        XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo");
                        notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing";

                        XmlDocument doc2 = new XmlDocument();
                        using (XmlWriter writer2 = doc2.CreateNavigator().AppendChild())
                        {
                            XmlRootAttribute ReferenceElement = new XmlRootAttribute("ReferenceElement");
                            foreach (AddressHeader h in callbackEndpoint.Headers)
                            {
                                h.WriteAddressHeader(writer2);
                            }

                            writer2.Close();
                            notifyTo.ReferenceParameters     = new ReferenceParametersType();
                            notifyTo.ReferenceParameters.Any = notifyTo.ReferenceParameters.Any = doc2.ChildNodes.Cast <XmlElement>().ToArray <XmlElement>();
                        }

                        new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo);
                    }

                    (s.Delivery.Any = new XmlElement[1])[0]       = doc.DocumentElement;
                    (s.Filter = new FilterType()).Dialect         = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action";
                    (s.Filter.Any = new System.Xml.XmlNode[1])[0] = new System.Xml.XmlDocument().CreateTextNode("http://www.teco.edu/AccelerationService/AccelerationServiceEventOut");

                    SubscribeResponse subscription;
                    try
                    {
                        Console.WriteLine("Subscribing to the event...");
                        //Console.ReadLine();
                        subscription = eventSource.SubscribeOp(s);
                    }
                    catch (TimeoutException t)
                    {
                        Console.WriteLine("Error reply time out: {0}!!", t.Message);
                        return;
                    }

                    String subscriptionId = null;
                    foreach (XmlNode xel in subscription.SubscriptionManager.ReferenceParameters.Any)
                    {
                        if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing"))
                        {
                            subscriptionId = xel.InnerText;
                        }
                    }

                    Console.WriteLine("Got subscription: {0}", subscriptionId);

                    Console.WriteLine("Press <ENTER> to unsubscribe.");
                    Console.ReadLine();

                    Console.WriteLine("Unsubscribing {0}", subscriptionId);
                    SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe");
                    subscriptionManager.Endpoint.Address = hostedEndPoint;
                    subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe());
                    client.Close();
                }
            }
        }
        /// <summary>
        /// Initial point of the program.
        /// </summary>
        /// <param name="args">Arguments.</param>
        public static void Main(string[] args)
        {
            // Check if the console application will continually run.
            bool continuousRun = false;

            if (args.Length > 0 && args[0].ToLower() == "-o")
            {
                continuousRun = (args.Length > 1 && args[1].ToLower() == "continous");
            }

            // Write the header.
            Console.WriteLine(
                @"ABB  DECRC - SERVICE and usability LAB
Advanced Identification and Labeling for Service
DECRC 2009
DPWS Discovery Project,
Contact N. L. Fantana ([email protected])

 * Please, start Gateway before select the options.
   Additionally a running dummynode is required when using manual discovery (Option D) 
");
            // Go always into the menu, until the user selects to exit.
            while (true)
            {
                // Check the option.
                ConsoleKeyInfo ki = new ConsoleKeyInfo();
                Console.Write(
                    @"Select one option: 
   A-Wait for Announcement;
   C-Configuration Sample;
   D-Discover the service;
   I-Invoke the service;
   S-Eventing Subscribe; 
   P-Performance Test; 
   E-Exit
Select: ");
                ki = Console.ReadKey();
                Console.WriteLine();


                switch (ki.Key)
                {
                // Start the announcement procedure.
                case ConsoleKey.A:
                    StartAnouncementProcess();
                    break;

                // Call the Configuration Method.
                case ConsoleKey.C:
                    if (hostedEndPoint != null)
                    {
                        ConfigureNodes(hostedEndPoint, false);
                    }
                    break;

                // Call the GetValues method (with or without showing information on the console).
                case ConsoleKey.D:
                    // Finds a valid Endpoint for a Node.
                    endpointAddress = StartDiscoveryProcess(false);
                    if (endpointAddress != null)
                    {
                        // Get Metadata and the endpoint of the service.
                        hostedEndPoint = GetMetaData(endpointAddress);

                        // Check if the invokation of the service will be called again.
                    }
                    // Kill the current processes.
                    if (UsbBridgeProcess != null)
                    {
                        UsbBridgeProcess.Kill();
                    }
                    if (SSimpDevice != null)
                    {
                        SSimpDevice.Kill();
                    }

                    break;

                case ConsoleKey.I:
                    if (hostedEndPoint != null)
                    {
                        //Invoke the service to get the values.
                        InvokeService(hostedEndPoint, false);
                    }
                    break;

                // Make a performance test.
                case ConsoleKey.P:
                    // endpointAddress = StartDiscoveryProcess(false);
                    if (hostedEndPoint != null)
                    {
                        // Get Metadata and the endpoint of the service.
                        //EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                        bool runAgainPerformance = true;
                        while (runAgainPerformance)
                        {
                            runAgainPerformance = false;

                            string valueStr = string.Empty;
                            int    quantity = 0;
                            int    timeWait = -1;

                            // Check the quantity of samples to try the performance test.
                            while (!int.TryParse(valueStr, out quantity))
                            {
                                Console.Write("Select the quantity of samples (C-Cancel): ");
                                valueStr = Console.ReadLine();
                                if (valueStr == "C" || valueStr == "c")
                                {
                                    break;
                                }
                            }
                            if (quantity <= 0)
                            {
                                break;
                            }

                            // Get the time to wait between each sample invoke.
                            valueStr = string.Empty;
                            while (!int.TryParse(valueStr, out timeWait))
                            {
                                Console.Write("Select the time to wait between samples in miliseconds (C-Cancel): ");
                                valueStr = Console.ReadLine();
                                if (valueStr == "C" || valueStr == "c")
                                {
                                    break;
                                }
                            }
                            if (timeWait < 0)
                            {
                                break;
                            }

                            Console.Write("Reading Values. This may take some time...");
                            System.Diagnostics.Stopwatch stp1 = new System.Diagnostics.Stopwatch();
                            stp1.Start();
                            for (int i = 0; i < quantity; i++)
                            {
                                // Invoke the service.
                                InvokeService(hostedEndPoint, true);
                                System.Threading.Thread.Sleep(timeWait);
                            }
                            stp1.Stop();
                            Console.WriteLine("done.");
                            Console.WriteLine("Time elapsed: {0}", stp1.ElapsedMilliseconds);

                            // Ask if the user wants to run again.
                            Console.Write("Run again (Y-yes, N-no)?");
                            ConsoleKeyInfo ky = Console.ReadKey();
                            if (ky.Key == ConsoleKey.Y)
                            {
                                runAgainPerformance = true;
                            }
                            Console.WriteLine();
                        }
                    }
                    // Kill the current processes.
                    if (UsbBridgeProcess != null)
                    {
                        UsbBridgeProcess.Kill();
                    }
                    if (SSimpDevice != null)
                    {
                        SSimpDevice.Kill();
                    }

                    break;

                // Initialize the Subcription event.
                case ConsoleKey.S:
                    Console.WriteLine("Starting subscription event...");

                    //  endpointAddress = StartDiscoveryProcess(false);
                    if (hostedEndPoint != null)
                    {
                        //Get Metadata of the address.
                        //  EndpointAddress hostedEndPoint = GetMetaData(endpointAddress);

                        InstanceContext ithis = new InstanceContext(new DiscoveryCallBack());



                        // Create a client
                        using (SensorValuesClient client = new SensorValuesClient(ithis))
                        {
                            client.Endpoint.Address = hostedEndPoint;
                            client.Open();

                            EndpointAddress   callbackEndpoint = client.InnerDuplexChannel.LocalAddress;
                            EventSourceClient eventSource      = new EventSourceClient(ithis, "WSEventing");
                            eventSource.Endpoint.Address = hostedEndPoint;
                            eventSource.Open();

                            Subscribe s = new Subscribe();
                            (s.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";

                            XmlDocument doc = new XmlDocument();
                            using (XmlWriter writer = doc.CreateNavigator().AppendChild())
                            {
                                EndpointReferenceType notifyTo = new EndpointReferenceType();

                                (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint.Uri.AbsoluteUri;

                                XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo");
                                notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing";

                                XmlDocument doc2 = new XmlDocument();
                                using (XmlWriter writer2 = doc2.CreateNavigator().AppendChild())
                                {
                                    XmlRootAttribute ReferenceElement = new XmlRootAttribute("ReferenceElement");
                                    foreach (AddressHeader h in callbackEndpoint.Headers)
                                    {
                                        h.WriteAddressHeader(writer2);
                                    }

                                    writer2.Close();
                                    notifyTo.ReferenceParameters     = new ReferenceParametersType();
                                    notifyTo.ReferenceParameters.Any = notifyTo.ReferenceParameters.Any = doc2.ChildNodes.Cast <XmlElement>().ToArray <XmlElement>();
                                }

                                new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo);
                            }

                            (s.Delivery.Any = new XmlElement[1])[0]       = doc.DocumentElement;
                            (s.Filter = new FilterType()).Dialect         = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action";
                            (s.Filter.Any = new System.Xml.XmlNode[1])[0] = new System.Xml.XmlDocument().CreateTextNode("http://www.teco.edu/SensorValues/SensorValuesEventOut");

                            SubscribeResponse subscription;
                            try
                            {
                                Console.WriteLine("Subscribing to the event...");
                                //Console.ReadLine();
                                subscription = eventSource.SubscribeOp(s);
                            }
                            catch (TimeoutException t)
                            {
                                Console.WriteLine("Error reply time out: {0}!!", t.Message);
                                hostedEndPoint = null;
                                return;
                            }
                            catch (EndpointNotFoundException e)
                            {
                                return;
                            }

                            String subscriptionId = null;
                            foreach (XmlNode xel in subscription.SubscriptionManager.ReferenceParameters.Any)
                            {
                                if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing"))
                                {
                                    subscriptionId = xel.InnerText;
                                }
                            }

                            Console.WriteLine("Got subscription: {0}", subscriptionId);

                            Console.WriteLine("Press <ENTER> to unsubscribe.");
                            Console.ReadLine();

                            Console.WriteLine("Unsubscribing {0}", subscriptionId);
                            SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient("WSEventingUnsubscribe");
                            subscriptionManager.Endpoint.Address = hostedEndPoint;
                            subscriptionManager.UnsubscribeOp(subscriptionId, new Unsubscribe());
                            client.Close();
                        }
                    }

                    break;

                // Close the application.
                case ConsoleKey.E:
                    return;

                // Invalid key.
                default:
                    Console.WriteLine("Invalid value.");
                    break;
                }
            }
        }
Exemple #21
0
        void InvokeService(EndpointAddress endpointAddress)
        {
            InstanceContext ithis            = new InstanceContext(this);
            String          callbackEndpoint = "http://vs2010test/blub";


            // Create a client
            SensorValuesClient client = new SensorValuesClient(new InstanceContext(this));

            client.Endpoint.Address = endpointAddress;
            //    callbackEndpoint=client.InnerChannel.LocalAddress.Uri.AbsoluteUri;
            callbackEndpoint = client.InnerDuplexChannel.LocalAddress.Uri.AbsoluteUri;

            Console.WriteLine("Invoking at {0}", endpointAddress);

            // client.GetSensorValues(out accelleration,out audio,out light,out force,out temperature);
            SSimpSample response = client.GetSensorValues();

            Console.WriteLine("Got response: {0}", response);


            Console.WriteLine("Subscribing event {1} at {0}", endpointAddress, "http://www.teco.edu/SensorValues/SensorValuesEventOut");
            EventSourceClient eventSource = new EventSourceClient(ithis);

            eventSource.Endpoint.Address = endpointAddress;

            SubscribeOpRequest s = new SubscribeOpRequest();

            s.Subscribe = new Subscribe();

            (s.Subscribe.Delivery = new DeliveryType()).Mode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";

            XmlDocument doc = new XmlDocument();

            using (XmlWriter writer = doc.CreateNavigator().AppendChild())
            {
                EndpointReferenceType notifyTo = new EndpointReferenceType();

                (notifyTo.Address = new AttributedURI()).Value = callbackEndpoint;
                XmlRootAttribute notifyToElem = new XmlRootAttribute("NotifyTo");
                notifyToElem.Namespace = "http://schemas.xmlsoap.org/ws/2004/08/eventing";

                new XmlSerializer(notifyTo.GetType(), notifyToElem).Serialize(writer, notifyTo);
            }

            (s.Subscribe.Delivery.Any = new XmlElement[1])[0] =
                doc.DocumentElement;

            (s.Subscribe.Filter = new FilterType()).Dialect = "http://schemas.xmlsoap.org/ws/2006/02/devprof/Action";

            (s.Subscribe.Filter.Any = new System.Xml.XmlNode[1]) [0] =
                new System.Xml.XmlDocument().CreateTextNode("http://www.teco.edu/SensorValues/SensorValuesEventOut");

            SubscribeOpResponse subscription;

            try
            {
                Console.WriteLine("Press <ENTER> to subscribe.");
                Console.ReadLine();
                subscription = eventSource.SubscribeOp(s);
            }
            catch (TimeoutException t)
            {
                Console.WriteLine("Error reply time out: {0}!!", t.Message);
                return;
            }
            //  eventSource.Close();


            String subscriptionId = null;


            foreach (XmlNode xel in subscription.SubscribeResponse.SubscriptionManager.ReferenceParameters.Any)
            {
                if (xel.LocalName.Equals("Identifier") && xel.NamespaceURI.Equals("http://schemas.xmlsoap.org/ws/2004/08/eventing"))
                {
                    subscriptionId = xel.InnerText;
                }
            }

            Console.WriteLine("Got subscription: {0}", subscriptionId);

            Console.WriteLine("Press <ENTER> to unsubscribe.");
            Console.ReadLine();

            UnsubscribeOpRequest unsubscribe = new UnsubscribeOpRequest();

            unsubscribe.Identifier = subscriptionId;

            Console.WriteLine("Unsubscribing {0}", subscriptionId);
            SubscriptionManagerClient subscriptionManager = new SubscriptionManagerClient();

            subscriptionManager.Endpoint.Address = endpointAddress;
            subscriptionManager.UnsubscribeOp(unsubscribe);

            //Closing the client gracefully closes the connection and cleans up resources
            //client.Close();
        }