public override Task InvokeAllAsync(string methodName, object[] args)
        {
            var message = new InvocationMessage(Guid.NewGuid().ToString(), nonBlocking: true, target: methodName, arguments: args);

            return(this._allStream.OnNextAsync(new AllMessage {
                Payload = message
            }));
        }
Example #2
0
        public override Task SendAllExceptAsync(string methodName, object?[]?args,
                                                IReadOnlyList <string> excludedConnectionIds,
                                                CancellationToken cancellationToken = new CancellationToken())
        {
            var message = new InvocationMessage(methodName, args);

            return(_allStream.OnNextAsync(new AllMessage(message, excludedConnectionIds)));
        }
Example #3
0
        public override Task InvokeConnectionAsync(string connectionId, string methodName, object[] args)
        {
            var connection = _connections[connectionId];

            var message = new InvocationMessage(GetInvocationId(), nonBlocking: true, target: methodName, arguments: args);

            return(WriteAsync(connection, message));
        }
Example #4
0
        public override Task SendAllAsync(string methodName, object[] args, CancellationToken cancellationToken = new CancellationToken())
        {
            var message = new InvocationMessage(methodName, args);

            return(_allStream.OnNextAsync(new AllMessage {
                Payload = message
            }));
        }
 private bool InvocationMessagesEqual(InvocationMessage x, InvocationMessage y)
 {
     return(SequenceEqual(x.Headers, y.Headers) &&
            string.Equals(x.InvocationId, y.InvocationId, StringComparison.Ordinal) &&
            string.Equals(x.Target, y.Target, StringComparison.Ordinal) &&
            ArgumentListsEqual(x.Arguments, y.Arguments) &&
            StringArrayEqual(x.StreamIds, y.StreamIds));
 }
        public override Task InvokeAllExceptAsync(string methodName, object[] args, IReadOnlyList <string> excludedIds)
        {
            var message = new InvocationMessage(Guid.NewGuid().ToString(), nonBlocking: true, target: methodName, arguments: args);

            return(this._allStream.OnNextAsync(new AllMessage {
                Payload = message, ExcludedIds = excludedIds
            }));
        }
Example #7
0
    private void WriteInvocationMessage(InvocationMessage message, Utf8JsonWriter writer)
    {
        WriteInvocationId(message, writer);
        writer.WriteString(TargetPropertyNameBytes, message.Target);

        WriteArguments(message.Arguments, writer);

        WriteStreamIds(message.StreamIds, writer);
    }
        public void Setup()
        {
            var logger = NullLogger <ProtobufHubProtocol> .Instance;
            var types  = new[] { typeof(BenchMessage) };

            _hubProtocol = new ProtobufHubProtocol(types, logger);

            var data = new BenchMessage
            {
                Email  = "*****@*****.**",
                Data   = new string('@', 512),
                Length = 256,
                Price  = 23451.5436d,
                Time   = new Google.Protobuf.WellKnownTypes.Timestamp()
                {
                    Seconds = DateTime.UtcNow.Second
                }
            };

            switch (InputArgument)
            {
            case MessageArgument.NoArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", Array.Empty <object>());
                break;

            case MessageArgument.IntArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { int.MinValue, 0, int.MaxValue });
                break;

            case MessageArgument.DoubleArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { double.MinValue, 0.5d, double.MaxValue });
                break;

            case MessageArgument.StringArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { "Foo", "Bar", new string('#', 512) });
                break;

            case MessageArgument.ProtobufArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { data, data, data });
                break;

            case MessageArgument.FewArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { data, "FooBar", 1 });
                break;

            case MessageArgument.ManyArguments:
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { data, "FooBar", 1, 234.543d, data, "*****@*****.**", 4242, 21.123456d, data });
                break;

            case MessageArgument.LargeArguments:
                data.Data          = new string('@', 4096);
                _invocationMessage = new InvocationMessage("BenchmarkTarget", new object[] { data, new string('L', 10240) });
                break;
            }

            _serializedMessageRef = _hubProtocol.GetMessageBytes(_invocationMessage);
        }
Example #9
0
        public static void Reset()
        {
            if (!IsPaused)
            {
                return;
            }

            _interceptedInvocationMessage = null;
            OnUnpause();
        }
Example #10
0
    private void WriteInvocationMessage(InvocationMessage message, JsonTextWriter writer)
    {
        WriteInvocationId(message, writer);
        writer.WritePropertyName(TargetPropertyName);
        writer.WriteValue(message.Target);

        WriteArguments(message.Arguments, writer);

        WriteStreamIds(message.StreamIds, writer);
    }
        public void MagicCast()
        {
            var input = Frame("{\"type\":1,\"target\":\"Method\",\"arguments\":[1.1]}");
            var expectedMessage = new InvocationMessage("Method", new object[] { 1 });

            var binder = new TestBinder(new[] { typeof(int) });
            var data = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(input));
            JsonHubProtocol.TryParseMessage(ref data, binder, out var message);

            Assert.Equal(expectedMessage, message);
        }
Example #12
0
        protected IDictionary <string, ReadOnlyMemory <byte> > SerializeAllProtocols(string method, object[] args)
        {
            var payloads = new Dictionary <string, ReadOnlyMemory <byte> >();
            var message  = new InvocationMessage(method, args);

            foreach (var hubProtocol in _allProtocols)
            {
                payloads.Add(hubProtocol.Name, hubProtocol.GetMessageBytes(message));
            }
            return(payloads);
        }
        public override Task InvokeConnectionAsync(string connectionId, string methodName, object[] args)
        {
            if (connectionId == null)
            {
                throw new ArgumentNullException(nameof(connectionId));
            }

            var message = new InvocationMessage(GetInvocationId(), nonBlocking: true, target: methodName, arguments: args);

            return(PublishAsync(_channelNamePrefix + "." + connectionId, message));
        }
 // This method is to protect against connections throwing synchronously when writing to them and preventing other connections from being written to
 private async Task SafeWriteAsync(HubConnectionContext connection, InvocationMessage message)
 {
     try
     {
         await connection.WriteAsync(message);
     }
     catch (Exception ex)
     {
         _logger.FailedWritingMessage(ex);
     }
 }
Example #15
0
        private void WriteInvocationMessage(InvocationMessage message, JsonTextWriter writer)
        {
            writer.WriteStartObject();
            WriteHubInvocationMessageCommon(message, writer, HubProtocolConstants.InvocationMessageType);
            writer.WritePropertyName(TargetPropertyName);
            writer.WriteValue(message.Target);

            WriteArguments(message.Arguments, writer);

            writer.WriteEndObject();
        }
        public override Task InvokeGroupAsync(string groupName, string methodName, object[] args)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException(nameof(groupName));
            }

            var message = new InvocationMessage(GetInvocationId(), nonBlocking: true, target: methodName, argumentBindingException: null, arguments: args);

            return(PublishAsync(_channelNamePrefix + ".group." + groupName, message));
        }
Example #17
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Level;
         hashCode = (hashCode * 397) ^ (Party != null ? Party.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (InvocationMessage != null ? InvocationMessage.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ReturnMessage != null ? ReturnMessage.GetHashCode() : 0);
         return(hashCode);
     }
 }
Example #18
0
        protected IDictionary <string, ReadOnlyMemory <byte> > SerializeAllProtocols(string method, object[] args)
        {
            var payloads = new Dictionary <string, ReadOnlyMemory <byte> >();
            var message  = new InvocationMessage(method, args);
            var serializedHubMessages = _messageSerializer.SerializeMessage(message);

            foreach (var serializedMessage in serializedHubMessages)
            {
                payloads.Add(serializedMessage.ProtocolName, serializedMessage.Serialized);
            }
            return(payloads);
        }
Example #19
0
 // This method is to protect against connections throwing synchronously when writing to them and preventing other connections from being written to
 private async Task SafeWriteAsync(HubConnectionContext connection, InvocationMessage message)
 {
     try
     {
         await connection.WriteAsync(message);
     }
     // This exception isn't interesting to users
     catch (Exception ex)
     {
         Log.FailedWritingMessage(_logger, ex);
     }
 }
Example #20
0
    public void GetSerializedMessageSerializesUsingHubProtocolIfNoCacheAvailable()
    {
        var invocation = new InvocationMessage("Foo", new object[0]);
        var message    = new SerializedHubMessage(invocation);
        var protocol   = new DummyHubProtocol("p1");

        var serialized = message.GetSerializedMessage(protocol);

        Assert.Equal(DummyHubProtocol.DummySerialization, serialized.ToArray());
        Assert.Collection(protocol.GetWrittenMessages(),
                          actualMessage => Assert.Same(invocation, actualMessage));
    }
Example #21
0
        public async Task SendMessage(string target, object[] args)
        {
            var callHubRequest        = new InvocationMessage(invocationId: _invId++.ToString(), target: target, arguments: args);
            var callHubServiceMessage = new ConnectionDataMessage(ConnectionId, _signalRPro.GetMessageBytes(callHubRequest));

            _servicePro.WriteMessage(callHubServiceMessage, ServiceSideConnection.MockServicePipe.Output);
            var flushResult = await ServiceSideConnection.MockServicePipe.Output.FlushAsync();

            if (flushResult.IsCanceled || flushResult.IsCompleted)
            {
                throw new InvalidOperationException($"Sending InvocationMessage {_invId} for client connection id {ConnectionId} resulted in FlushResult with IsCanceled {flushResult.IsCanceled} IsCompleted {flushResult.IsCompleted}");
            }
        }
Example #22
0
        public static InvocationMessage TryGetMessageInject()
        {
            if (_interceptedInvocationMessage == null)
            {
                return(null);
            }

            var message = _interceptedInvocationMessage;

            _interceptedInvocationMessage = null;

            return(message);
        }
Example #23
0
        private Task DispatchInvocationAsync(InvocationMessage invocation, CancellationToken cancellationToken)
        {
            // Find the handler
            if (!_handlers.TryGetValue(invocation.Target, out InvocationHandler handler))
            {
                _logger.MissingHandler(invocation.Target);
                return(Task.CompletedTask);
            }

            // TODO: Return values
            // TODO: Dispatch to a sync context to ensure we aren't blocking this loop.
            return(handler.Handler(invocation.Arguments));
        }
Example #24
0
        public Task Send(InvocationMessage message)
        {
            if (State.ServerId != Guid.Empty)
            {
                _logger.LogDebug("Sending message on {hubName}.{targetMethod} to connection {connectionId}", _keyData.HubName, message.Target, _keyData.Id);
                return(_serverStream.OnNextAsync(new ClientMessage {
                    ConnectionId = _keyData.Id, Payload = message, HubName = _keyData.HubName
                }));
            }

            _logger.LogError("Client not connected for connectionId '{connectionId}' and hub '{hubName}'", _keyData.Id, _keyData.HubName);
            return(Task.CompletedTask);
        }
Example #25
0
 private async Task Execute(HubConnectionContext connection, InvocationMessage invocationMessage)
 {
     if (!_methods.TryGetValue(invocationMessage.Target, out var descriptor))
     {
         // Send an error to the client. Then let the normal completion process occur
         _logger.UnknownHubMethod(invocationMessage.Target);
         await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, $"Unknown hub method '{invocationMessage.Target}'"));
     }
     else
     {
         await Invoke(descriptor, connection, invocationMessage);
     }
 }
Example #26
0
 private async Task SendInvocationError(InvocationMessage invocationMessage, HubConnectionContext connection, Type returnType, Exception ex)
 {
     if (!invocationMessage.NonBlocking)
     {
         if (IsIObservable(returnType) || IsChannel(returnType, out _))
         {
             await SendMessageAsync(connection, new StreamCompletionMessage(invocationMessage.InvocationId, ex.Message));
         }
         else
         {
             await SendMessageAsync(connection, CompletionMessage.WithError(invocationMessage.InvocationId, ex.Message));
         }
     }
 }
Example #27
0
 private async Task ProcessInvocation(HubConnectionContext connection, InvocationMessage invocationMessage)
 {
     try
     {
         // If an unexpected exception occurs then we want to kill the entire connection
         // by ending the processing loop
         await Execute(connection, invocationMessage);
     }
     catch (Exception ex)
     {
         // Abort the entire connection if the invocation fails in an unexpected way
         connection.Abort(ex);
     }
 }
Example #28
0
        private static bool TryGetPayload(IHubProtocol protocol, InvocationMessage invocationMessage, out ReadOnlySequence <byte> payload)
        {
            var buffer = new ReadOnlySequence <byte>(protocol.GetMessageBytes(invocationMessage));

            if (protocol is JsonHubProtocol)
            {
                return(TextMessageParser.TryParseMessage(ref buffer, out payload));
            }
            else if (protocol is MessagePackHubProtocol)
            {
                return(BinaryMessageParser.TryParseMessage(ref buffer, out payload));
            }

            throw new ArgumentException($"{protocol.GetType()} is not supported");
        }
        public virtual Task Send(InvocationMessage message)
        {
            _logger.LogDebug("Sending message to {hubName}.{targetMethod} on group {groupId} to {connectionsCount} connection(s)",
                             KeyData.HubName, message.Target, KeyData.Id, State.Connections.Count);

            var tasks = new List <Task>();

            foreach (var connection in State.Connections)
            {
                var client = GrainFactory.GetClientGrain(KeyData.HubName, connection);
                tasks.Add(client.Send(message));
            }

            return(Task.WhenAll(tasks));
        }
Example #30
0
        private void InnerInvokeCore(string methodName, string invocationId, object[] args)
        {
            InvocationMessage invocationMessage;

            if (string.IsNullOrEmpty(invocationId))
            {
                invocationMessage = new InvocationMessage(methodName, args);
            }
            else
            {
                invocationMessage = new InvocationMessage(invocationId, methodName, args);
            }
            Log.Debug("开始发送远程调用消息");
            SendHubMessage(invocationMessage);
        }