Exemplo n.º 1
0
        /// <summary>
        /// Processes the hub's incoming method calls.
        /// </summary>
        protected override Task OnReceived(HttpRequest request, string connectionId, string data)
        {
            HubRequest hubRequest = _requestParser.Parse(data, _serializer);

            // Create the hub
            HubDescriptor descriptor = _manager.EnsureHub(hubRequest.Hub,
                                                          _counters.ErrorsHubInvocationTotal,
                                                          _counters.ErrorsHubInvocationPerSec,
                                                          _counters.ErrorsAllTotal,
                                                          _counters.ErrorsAllPerSec);

            IJsonValue[] parameterValues = hubRequest.ParameterValues;

            // Resolve the method

            MethodDescriptor methodDescriptor = _manager.GetHubMethod(descriptor.Name, hubRequest.Method, parameterValues);

            if (methodDescriptor == null)
            {
                // Empty (noop) method descriptor
                // Use: Forces the hub pipeline module to throw an error.  This error is encapsulated in the HubDispatcher.
                //      Encapsulating it in the HubDispatcher prevents the error from bubbling up to the transport level.
                //      Specifically this allows us to return a faulted task (call .fail on client) and to not cause the
                //      transport to unintentionally fail.
                IEnumerable <MethodDescriptor> availableMethods = _manager.GetHubMethods(descriptor.Name, m => m.Name == hubRequest.Method);
                methodDescriptor = new NullMethodDescriptor(descriptor, hubRequest.Method, availableMethods);
            }

            // Resolving the actual state object
            var tracker = new StateChangeTracker(hubRequest.State);
            var hub     = CreateHub(request, descriptor, connectionId, tracker, throwIfFailedToCreate: true);

            return(InvokeHubPipeline(hub, parameterValues, methodDescriptor, hubRequest, tracker)
                   .ContinueWithPreservedCulture(task => hub.Dispose(), TaskContinuationOptions.ExecuteSynchronously));
        }
Exemplo n.º 2
0
 public HubInvokerContext(IHub hub, StateChangeTracker tracker, MethodDescriptor methodDescriptor, IList <object> args)
 {
     Hub = hub;
     MethodDescriptor = methodDescriptor;
     Args             = args;
     StateTracker     = tracker;
 }
Exemplo n.º 3
0
        private Task InvokeHubPipeline(IHub hub,
                                       IJsonValue[] parameterValues,
                                       MethodDescriptor methodDescriptor,
                                       HubRequest hubRequest,
                                       StateChangeTracker tracker)
        {
            // TODO: Make adding parameters here pluggable? IValueProvider? ;)
            HubInvocationProgress progress = GetProgressInstance(methodDescriptor, value => SendProgressUpdate(hub.Context.ConnectionId, tracker, value, hubRequest), Logger);

            Task <object> piplineInvocation;

            try
            {
                var args = _binder.ResolveMethodParameters(methodDescriptor, parameterValues);

                // We need to add the IProgress<T> instance after resolving the method as the resolution
                // itself looks for overload matches based on the incoming arg values
                if (progress != null)
                {
                    args = args.Concat(new[] { progress }).ToList();
                }

                var context = new HubInvokerContext(hub, tracker, methodDescriptor, args);

                // Invoke the pipeline and save the task
                piplineInvocation = _pipelineInvoker.Invoke(context);
            }
            catch (Exception ex)
            {
                piplineInvocation = TaskAsyncHelper.FromError <object>(ex);
            }

            // Determine if we have a faulted task or not and handle it appropriately.
            return(piplineInvocation.ContinueWithPreservedCulture(task =>
            {
                if (progress != null)
                {
                    // Stop ability to send any more progress updates
                    progress.SetComplete();
                }

                if (task.IsFaulted)
                {
                    return ProcessResponse(tracker, result: null, request: hubRequest, error: task.Exception);
                }
                else if (task.IsCanceled)
                {
                    return ProcessResponse(tracker, result: null, request: hubRequest, error: new OperationCanceledException());
                }
                else
                {
                    return ProcessResponse(tracker, task.Result, hubRequest, error: null);
                }
            })
                   .FastUnwrap());
        }
Exemplo n.º 4
0
        private Task SendProgressUpdate(string connectionId, StateChangeTracker tracker, object value, HubRequest request)
        {
            var hubResult = new HubResponse
            {
                State    = tracker.GetChanges(),
                Progress = new { I = request.Id, D = value },
                // We prefix the ID here to ensure old clients treat this as a hub response
                // but fail to lookup a corresponding callback and thus no-op
                Id = "P|" + request.Id,
            };

            return(Connection.Send(connectionId, hubResult));
        }
Exemplo n.º 5
0
        private Task ProcessResponse(StateChangeTracker tracker, object result, HubRequest request, Exception error)
        {
            var hubResult = new HubResponse
            {
                State  = tracker.GetChanges(),
                Result = result,
                Id     = request.Id,
            };

            if (error != null)
            {
                _counters.ErrorsHubInvocationTotal.Increment();
                _counters.ErrorsHubInvocationPerSec.Increment();
                _counters.ErrorsAllTotal.Increment();
                _counters.ErrorsAllPerSec.Increment();

                var hubError = error.InnerException as HubException;

                if (_enableDetailedErrors || hubError != null)
                {
                    var exception = error.InnerException ?? error;
                    hubResult.StackTrace = _isDebuggingEnabled ? exception.StackTrace : null;
                    hubResult.Error      = exception.Message;

                    if (hubError != null)
                    {
                        hubResult.IsHubException = true;
                        hubResult.ErrorData      = hubError.ErrorData;
                    }
                }
                else
                {
                    hubResult.Error = String.Format(CultureInfo.CurrentCulture, Resources.Error_HubInvocationFailed, request.Hub, request.Method);
                }
            }

            return(Transport.Send(hubResult));
        }
Exemplo n.º 6
0
        private IHub CreateHub(HttpRequest request, HubDescriptor descriptor, string connectionId, StateChangeTracker tracker = null, bool throwIfFailedToCreate = false)
        {
            try
            {
                var hub = _manager.ResolveHub(descriptor.Name);

                if (hub != null)
                {
                    tracker = tracker ?? new StateChangeTracker();

                    hub.Context = new HubCallerContext(request, connectionId);
                    hub.Clients = new HubConnectionContext(_pipelineInvoker, Connection, descriptor.Name, connectionId, tracker);
                    hub.Groups  = new GroupManager(Connection, PrefixHelper.GetHubGroupName(descriptor.Name));
                }

                return(hub);
            }
            catch (Exception ex)
            {
                Logger.LogInformation(String.Format("Error creating Hub {0}. {1}", descriptor.Name, ex.Message));

                if (throwIfFailedToCreate)
                {
                    throw;
                }

                return(null);
            }
        }
Exemplo n.º 7
0
 public StatefulSignalProxy(IConnection connection, IHubPipelineInvoker invoker, string signal, string hubName, string prefix, StateChangeTracker tracker)
     : base(connection, invoker, signal, prefix, hubName, ListHelper <string> .Empty)
 {
     _tracker = tracker;
 }
Exemplo n.º 8
0
 public CallerStateProxy(StateChangeTracker tracker)
 {
     _tracker = tracker;
 }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HubConnectionContext"/>.
        /// </summary>
        /// <param name="pipelineInvoker">The pipeline invoker.</param>
        /// <param name="connection">The connection.</param>
        /// <param name="hubName">The hub name.</param>
        /// <param name="connectionId">The connection id.</param>
        /// <param name="tracker">The connection hub state.</param>
        public HubConnectionContext(IHubPipelineInvoker pipelineInvoker, IConnection connection, string hubName, string connectionId, StateChangeTracker tracker)
            : base(connection, pipelineInvoker, hubName)
        {
            _connectionId = connectionId;

            Caller      = new StatefulSignalProxy(connection, pipelineInvoker, connectionId, PrefixHelper.HubConnectionIdPrefix, hubName, tracker);
            CallerState = new CallerStateProxy(tracker);
            All         = AllExcept();
            Others      = AllExcept(connectionId);
        }