Example #1
0
        public IPromise WaitForTicks <T>(ILinkHandler handle, int ticks) where T : ITimeEvent
        {
            var promise = new Promise();

            FrameTimer <T> timer = null;

            timer = new FrameTimer <T>(ticks,
                                       () =>
            {
                if (handle.IsActive)
                {
                    promise.Resolve();
                }

                timer.Dispose();
            },
                                       () =>
            {
                if (handle.IsDestroyed)
                {
                    timer.Dispose();
                }

                return(handle.IsActive);
            });

            return(promise);
        }
        public void GetLinkHandlerTest(string url, bool isReceiver, Type expectedLinkHandlerType)
        {
            // Arrange
            var messageConverter       = Mock.Of <IMessageConverter <AmqpMessage> >();
            var twinMessageConverter   = Mock.Of <IMessageConverter <AmqpMessage> >();
            var methodMessageConverter = Mock.Of <IMessageConverter <AmqpMessage> >();
            var identityProvider       = new IdentityProvider("foo.bar");
            var metadataStore          = Mock.Of <IMetadataStore>();
            var linkHandlerProvider    = new LinkHandlerProvider(messageConverter, twinMessageConverter, methodMessageConverter, identityProvider, metadataStore);

            var       uri = new Uri(url);
            var       amqpClientConnectionsHandler = Mock.Of <IClientConnectionsHandler>(c => c.GetConnectionHandler(It.IsAny <IIdentity>()) == Mock.Of <IConnectionHandler>());
            var       amqpConnection = Mock.Of <IAmqpConnection>(c => c.FindExtension <IClientConnectionsHandler>() == amqpClientConnectionsHandler);
            var       amqpSession    = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            IAmqpLink amqpLink       = isReceiver
                ? Mock.Of <IReceivingAmqpLink>(l => l.IsReceiver && l.Session == amqpSession)
                : Mock.Of <ISendingAmqpLink>(l => !l.IsReceiver && l.Session == amqpSession) as IAmqpLink;

            if (url.Contains("$cbs"))
            {
                Mock.Get(amqpConnection).Setup(c => c.FindExtension <ICbsNode>()).Returns(Mock.Of <ICbsNode>());
            }

            // Act
            ILinkHandler linkHandler = linkHandlerProvider.Create(amqpLink, uri);

            // Assert
            Assert.NotNull(linkHandler);
            Assert.IsType(expectedLinkHandlerType, linkHandler);
        }
Example #3
0
        public IPromise WaitForSeconds <T>(ILinkHandler handle, float seconds) where T : ITimeDeltaEvent
        {
            var promise = new Promise();

            Timer <T> timer = null;

            timer = new Timer <T>(seconds,
                                  () =>
            {
                if (handle.IsActive)
                {
                    promise.Resolve();
                }

                timer.Dispose();
            },
                                  () =>
            {
                if (handle.IsDestroyed)
                {
                    timer.Dispose();
                }

                return(handle.IsActive);
            });

            return(promise);
        }
        public void GetLinkHandlerTest(LinkType linkType, bool isReceiver, Type expectedLinkHandlerType)
        {
            // Arrange
            var messageConverter       = Mock.Of <IMessageConverter <AmqpMessage> >();
            var twinMessageConverter   = Mock.Of <IMessageConverter <AmqpMessage> >();
            var methodMessageConverter = Mock.Of <IMessageConverter <AmqpMessage> >();
            var linkHandlerProvider    = new LinkHandlerProvider(messageConverter, twinMessageConverter, methodMessageConverter);

            var       uri            = new Uri("amqps://foo.bar//abs/prq");
            var       amqpConnection = Mock.Of <IAmqpConnection>(c => c.FindExtension <IConnectionHandler>() == Mock.Of <IConnectionHandler>());
            var       amqpSession    = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            IAmqpLink amqpLink       = isReceiver
                ? Mock.Of <IReceivingAmqpLink>(l => l.IsReceiver && l.Session == amqpSession)
                : Mock.Of <ISendingAmqpLink>(l => !l.IsReceiver && l.Session == amqpSession) as IAmqpLink;

            if (linkType == LinkType.Cbs)
            {
                Mock.Get(amqpConnection).Setup(c => c.FindExtension <ICbsNode>()).Returns(Mock.Of <ICbsNode>());
            }

            // Act
            ILinkHandler linkHandler = linkHandlerProvider.GetLinkHandler(linkType, amqpLink, uri, new Dictionary <string, string>());

            // Assert
            Assert.NotNull(linkHandler);
            Assert.IsType(expectedLinkHandlerType, linkHandler);
        }
Example #5
0
 /// <summary>
 /// Creates a new endpoint with an absolute URI.
 /// </summary>
 /// <param name="uri">The HTTP URI of the remote element.</param>
 /// <param name="httpClient">The HTTP client used to communicate with the remote element.</param>
 /// <param name="serializer">Controls the serialization of entities sent to and received from the server.</param>
 /// <param name="errorHandler">Handles errors in HTTP responses.</param>
 /// <param name="linkHandler">Detects links in HTTP responses.</param>
 protected EndpointBase(Uri uri, HttpClient httpClient, MediaTypeFormatter serializer, IErrorHandler errorHandler, ILinkHandler linkHandler)
 {
     Uri          = uri ?? throw new ArgumentNullException(nameof(uri));
     HttpClient   = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
     Serializer   = serializer ?? throw new ArgumentNullException(nameof(serializer));
     ErrorHandler = errorHandler ?? throw new ArgumentNullException(nameof(errorHandler));
     LinkHandler  = linkHandler ?? throw new ArgumentNullException(nameof(linkHandler));
 }
Example #6
0
        AmqpLink ILinkFactory.CreateLink(AmqpSession session, AmqpLinkSettings settings)
        {
            try
            {
                this.ValidateLinkSettings(settings);

                // Override AmqpLinkSetting MaxMessageSize to restrict it to Constants.AmqpMaxMessageSize
                if (settings.MaxMessageSize == null || settings.MaxMessageSize == 0 || settings.MaxMessageSize > Constants.AmqpMaxMessageSize)
                {
                    settings.MaxMessageSize = Constants.AmqpMaxMessageSize;
                }

                AmqpLink  amqpLink;
                IAmqpLink wrappingAmqpLink;
                string    linkAddress;
                if (settings.IsReceiver())
                {
                    amqpLink         = new ReceivingAmqpLink(session, settings);
                    wrappingAmqpLink = new EdgeReceivingAmqpLink((ReceivingAmqpLink)amqpLink);
                    linkAddress      = ((Target)settings.Target).Address.ToString();
                }
                else
                {
                    amqpLink         = new SendingAmqpLink(session, settings);
                    wrappingAmqpLink = new EdgeSendingAmqpLink((SendingAmqpLink)amqpLink);
                    linkAddress      = ((Source)settings.Source).Address.ToString();
                }

                // TODO: implement the rules below
                // Link address may be of the forms:
                //
                //  amqp[s]://my.servicebus.windows.net/a/b     <-- FQ address where host name should match connection remote host name
                //  amqp[s]:a/b                                 <-- path relative to hostname specified in OPEN
                //  a/b                                         <-- pre-global addressing style path relative to hostname specified in OPEN
                //  /a/b                                        <-- same as above

                Uri linkUri;
                if (!linkAddress.StartsWith(Constants.AmqpsScheme, StringComparison.OrdinalIgnoreCase))
                {
                    string host = session.Connection.Settings.RemoteHostName;
                    linkUri = new Uri("amqps://" + host + linkAddress.EnsureStartsWith('/'));
                }
                else
                {
                    linkUri = new Uri(linkAddress, UriKind.RelativeOrAbsolute);
                }

                ILinkHandler linkHandler = this.linkHandlerProvider.Create(wrappingAmqpLink, linkUri);
                amqpLink.Settings.AddProperty(LinkHandlerPropertyKey, linkHandler);
                return(amqpLink);
            }
            catch (Exception e) when(!ExceptionEx.IsFatal(e))
            {
                // Don't throw here because we cannot provide error info. Instead delay and throw from Link.Open.
                return(new FaultedLink(e, session, settings));
            }
        }
Example #7
0
        public virtual void Subscribe(ILinkHandler handle, Action <JNode, JNodeEvent> action)
        {
            if (actions == null)
            {
                actions = new List <JDataHandleActionPair>(2);
            }

            actions.Add(new JDataHandleActionPair(handle, action));
        }
Example #8
0
 public static void Subscribe <T>(this IEventBusService eventBusService, ILinkHandler handle, Action <T> action, Func <T, bool> filter, int priority = 0)
 {
     eventBusService.Subscribe <T>(DEFAULT_CHANNEL, handle, (e) =>
     {
         if (filter(e))
         {
             action(e);
         }
     }, priority);
 }
Example #9
0
        public override void Subscribe(ILinkHandler handle, Action <JNode, JNodeEvent> action)
        {
            base.Subscribe(handle, action);

            if (subscribeToRef && internalLinkHandler == null)
            {
                internalLinkHandler = new JNodeLinkHandler(this, false);
                reference.Subscribe(internalLinkHandler, cachedTrigger);
            }
        }
Example #10
0
        public Coroutine StartCoroutine(ILinkHandler handle, IEnumerator routine)
        {
            var coroutine = new Coroutine(routine);

            lock (coroutines)
            {
                coroutines.Add(new CoroutineHandlePair(handle, coroutine));
            }

            return(coroutine);
        }
Example #11
0
        public IPromise WaitUntil(ILinkHandler handle, Func <bool> condition)
        {
            var promise = new Promise();

            lock (actions)
            {
                actions.Add(new TaskPromise(handle, condition, promise));
            }

            return(promise);
        }
        public async Task RegisterLinkHandler(ILinkHandler linkHandler)
        {
            using (await this.registryUpdateLock.LockAsync())
            {
                if (this.registry.TryGetValue(linkHandler.Type, out ILinkHandler currentLinkHandler))
                {
                    await currentLinkHandler.CloseAsync(Constants.DefaultTimeout);
                }

                ILinkHandler nonCorrelatedLinkHandler = null;
                switch (linkHandler.Type)
                {
                case LinkType.MethodReceiving:
                    if (this.registry.TryGetValue(LinkType.MethodSending, out ILinkHandler methodSendingLinkHandler) &&
                        methodSendingLinkHandler.CorrelationId != linkHandler.CorrelationId)
                    {
                        nonCorrelatedLinkHandler = methodSendingLinkHandler;
                    }

                    break;

                case LinkType.MethodSending:
                    if (this.registry.TryGetValue(LinkType.MethodReceiving, out ILinkHandler methodReceivingLinkHandler) &&
                        methodReceivingLinkHandler.CorrelationId != linkHandler.CorrelationId)
                    {
                        nonCorrelatedLinkHandler = methodReceivingLinkHandler;
                    }

                    break;

                case LinkType.TwinReceiving:
                    if (this.registry.TryGetValue(LinkType.TwinSending, out ILinkHandler twinSendingLinkHandler) &&
                        twinSendingLinkHandler.CorrelationId != linkHandler.CorrelationId)
                    {
                        nonCorrelatedLinkHandler = twinSendingLinkHandler;
                    }

                    break;

                case LinkType.TwinSending:
                    if (this.registry.TryGetValue(LinkType.TwinReceiving, out ILinkHandler twinReceivingLinkHandler) &&
                        twinReceivingLinkHandler.CorrelationId != linkHandler.CorrelationId)
                    {
                        nonCorrelatedLinkHandler = twinReceivingLinkHandler;
                    }

                    break;
                }

                await(nonCorrelatedLinkHandler?.CloseAsync(Constants.DefaultTimeout) ?? Task.CompletedTask);
                this.registry[linkHandler.Type] = linkHandler;
            }
        }
Example #13
0
    public static Action <TRemote> Bind <T, TRemote>(this JData <T> jData, ILinkHandler handle, Action <JData <T> > action, Func <TRemote, T> converter)
    {
        jData.Subscribe(handle, action);

        return((value) =>
        {
            if (jData != null && !jData.IsDisposed())
            {
                jData.Value = converter(value);
            }
        });
    }
Example #14
0
    public static Action <T> Bind <T>(this JData <T> jData, ILinkHandler handle, Action <JData <T> > action)
    {
        jData.Subscribe(handle, action);

        return((value) =>
        {
            if (jData != null && !jData.IsDisposed())
            {
                jData.Value = value;
            }
        });
    }
Example #15
0
        public void Subscribe <T>(ChannelId channel, ILinkHandler handle, Action <T> action, int priority = 0)
        {
            var type = typeof(T);

            if (action == null)
            {
                Log.Exception($"Subscriber action of event type {type.GetFriendlyName()} can't be null", new ArgumentNullException("action"));
                return;
            }

            lock (subscribers)
            {
                if (subscribers[channel] == null)
                {
                    subscribers[channel] = new Dictionary <EventType, List <SubscriberData> >();
                }

                var subscriberList  = subscribers[channel].GetOrInsertNew(type);
                var subscriberIndex = 0;

                for (int i = (subscriberList.Count - 1); i >= 0; --i)
                {
                    if (subscriberList[i].priority <= priority)
                    {
                        subscriberIndex = (i + 1);
                        break;
                    }
                }

                subscriberList.Insert(subscriberIndex, new SubscriberData(handle, action, priority));
            }

            if (stickyData.ContainsKey(type))
            {
                if (Thread.CurrentThread != mainThread)
                {
                    Log.Exception("Synchronous sticky event can't be auto fired from outside of the Main Thread", new InvalidOperationException());
                    return;
                }

                if (callStackCounter > MAX_EVENT_STACK_LIMIT)
                {
                    Log.Exception($"Max eventbus stack reached, subscriber won't get the sticky event of type {type.GetFriendlyName()}", new StackOverflowException());
                    return;
                }

                DispatchEvent(type, action, (T)stickyData[type]);
            }
        }
 public async Task RemoveLinkHandler(ILinkHandler linkHandler)
 {
     Preconditions.CheckNotNull(linkHandler);
     using (await this.registryUpdateLock.LockAsync())
     {
         if (this.registry.ContainsKey(linkHandler.Type))
         {
             this.registry.Remove(linkHandler.Type);
             if (this.registry.Count == 0)
             {
                 await this.CloseConnection();
             }
         }
     }
 }
Example #17
0
        public string GetLinkUrl(ILinkHandler linkHandler)
        {
            var gameResponse = _gameHandler.GetGame();

            // Find Link
            JToken link;

            using (var stream = gameResponse.MessageBody)
            {
                var json = stream.GetJson();
                link = linkHandler.GetLink(json);

                if (link == null)
                {
                    return(null);
                }
            }

            return((string)link["href"]);
        }
Example #18
0
        public void CreateTest()
        {
            // Arrange
            IAmqpLink registeredLink = null;
            var       cbsNode        = new Mock <ICbsNode>();

            cbsNode.Setup(c => c.RegisterLink(It.IsAny <IAmqpLink>())).Callback <IAmqpLink>(l => registeredLink = l);
            var amqpConnection = Mock.Of <IAmqpConnection>(c => c.FindExtension <ICbsNode>() == cbsNode.Object);
            var amqpSession    = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            var amqpLink       = Mock.Of <IAmqpLink>(l => l.Session == amqpSession && l.IsReceiver == false);

            var requestUri = new Uri("amqps://foo.bar/$cbs");

            // Act
            ILinkHandler linkHandler = CbsLinkHandler.Create(amqpLink, requestUri);

            // Assert
            Assert.Equal(registeredLink, amqpLink);
            Assert.NotNull(linkHandler);
            Assert.IsType <CbsLinkHandler>(linkHandler);
        }
Example #19
0
        public override void Subscribe(ILinkHandler handle, Action <JNode, JNodeEvent> action)
        {
            base.Subscribe(handle, action);

            if (subscribeToChildren && !autoSubscribeToChildren)
            {
                if (internalLinkHandler == null)
                {
                    internalLinkHandler = new JNodeLinkHandler(this, false);
                }

                for (int i = 0; i < list.Count; ++i)
                {
                    if (!list[i].IsSubscribed(this))
                    {
                        list[i].Subscribe(internalLinkHandler, cachedTriggerList);
                    }
                }

                autoSubscribeToChildren = true;
            }
        }
Example #20
0
        public override void Subscribe(ILinkHandler handle, Action <JNode, JNodeEvent> action)
        {
            base.Subscribe(handle, action);

            if (subscribeToChildren && !autoSubscribeToChildren)
            {
                if (internalLinkHandler == null)
                {
                    internalLinkHandler = new JNodeLinkHandler(this, false);
                }

                foreach (var kvp in dictionary)
                {
                    if (!kvp.Value.IsSubscribed(this))
                    {
                        kvp.Value.Subscribe(internalLinkHandler, cachedTriggerDict);
                    }
                }

                autoSubscribeToChildren = true;
            }
        }
Example #21
0
 public JDataHandleActionPair(ILinkHandler handle, Action <JNode, JNodeEvent> action)
 {
     this.handle = handle;
     this.action = action;
 }
Example #22
0
 /// <summary>
 /// Creates a new endpoint with an absolute URI.
 /// </summary>
 /// <param name="uri">The base URI of the REST API. Missing trailing slash will be appended automatically.</param>
 /// <param name="oAuthOptions">Options for OAuth 2.0 / OpenID Connect authentication. (optional)</param>
 /// <param name="httpMessageHandler">The HTTP message handler used to communicate with the remote element. (optional)</param>
 /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param>
 /// <param name="errorHandler">Handles errors in HTTP responses. Leave unset for default implementation.</param>
 /// <param name="linkHandler">Detects links in HTTP responses. Leave unset for default implementation.</param>
 public OAuthEntryEndpoint(Uri uri, OAuthOptions oAuthOptions = null, HttpMessageHandler httpMessageHandler = null, MediaTypeFormatter serializer = null, IErrorHandler errorHandler = null, ILinkHandler linkHandler = null)
     : base(
         uri,
         new HttpClient(oAuthOptions == null ? httpMessageHandler : new OAuthHandler(oAuthOptions, httpMessageHandler)),
         serializer,
         errorHandler,
         linkHandler)
 {
 }
Example #23
0
 /// <summary>
 /// Creates a new entry point using an OAuth token.
 /// </summary>
 /// <param name="uri">The base URI of the REST API.</param>
 /// <param name="token">The OAuth token to present as a "Bearer" to the REST API.</param>
 /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param>
 /// <param name="errorHandler">Handles errors in HTTP responses. Leave unset for default implementation.</param>
 /// <param name="linkHandler">Detects links in HTTP responses. Leave unset for default implementation.</param>
 public EntryEndpoint(Uri uri, string token, MediaTypeFormatter serializer = null, IErrorHandler errorHandler = null, ILinkHandler linkHandler = null)
     : this(uri, new HttpClient(), serializer, errorHandler, linkHandler)
 {
     BearerAuth(token);
 }
Example #24
0
 /// <summary>
 /// Creates a new entry point.
 /// </summary>
 /// <param name="uri">The base URI of the REST API.</param>
 /// <param name="credentials">Optional HTTP Basic Auth credentials used to authenticate against the REST API.</param>
 /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param>
 /// <param name="errorHandler">Handles errors in HTTP responses. Leave unset for default implementation.</param>
 /// <param name="linkHandler">Detects links in HTTP responses. Leave unset for default implementation.</param>
 public EntryEndpoint(Uri uri, ICredentials credentials = null, MediaTypeFormatter serializer = null, IErrorHandler errorHandler = null, ILinkHandler linkHandler = null)
     : this(uri, new HttpClient(), serializer, errorHandler, linkHandler)
 {
     BasicAuth(uri, credentials);
 }
Example #25
0
 /// <summary>
 /// Creates a new endpoint with an absolute URI.
 /// </summary>
 /// <param name="uri">The base URI of the REST API. Missing trailing slash will be appended automatically.</param>
 /// <param name="httpClient">The HTTP client used to communicate with the remote element.</param>
 /// <param name="serializer">Controls the serialization of entities sent to and received from the server. Defaults to a JSON serializer if unset.</param>
 /// <param name="errorHandler">Handles errors in HTTP responses. Leave unset for default implementation.</param>
 /// <param name="linkHandler">Detects links in HTTP responses. Leave unset for default implementation.</param>
 public EntryEndpoint(Uri uri, HttpClient httpClient, MediaTypeFormatter serializer = null, IErrorHandler errorHandler = null, ILinkHandler linkHandler = null)
     : base(
         uri.EnsureTrailingSlash(),
         httpClient,
         serializer ?? new DefaultJsonSerializer(),
         errorHandler ?? new DefaultErrorHandler(),
         linkHandler ?? new DefaultLinkHandler())
 {
     AcceptContentTypes();
 }
Example #26
0
 public ScraperApp(ILinkHandler linkHandler)
 {
     _linkHandler = linkHandler;
 }
Example #27
0
 public IPromise WaitWhile(ILinkHandler handle, Func <bool> condition)
 {
     return(WaitUntil(handle, () => !condition()));
 }
Example #28
0
 public void SetLinkHandler(ILinkHandler linkHandler)
 {
     this.linkHandler = linkHandler;
 }
Example #29
0
 public ObservableHandleActionPair(ILinkHandler handle, Action <T> action)
 {
     this.handle = handle;
     this.action = action;
 }
Example #30
0
 public TaskPromise(ILinkHandler handle, Func <bool> condition, IPromise promise)
 {
     this.handle    = handle;
     this.condition = condition;
     this.promise   = promise;
 }