public void HandleExecution(IReceivedMessage<MessageExpression> receivedMessage, IWorkerNotification workerNotification) { switch (receivedMessage.Body.PayLoad) { case MessageExpressionPayloads.Action: using (_runMethodCompiledCodeTimer.NewContext()) { _handler.HandleExecution(receivedMessage, workerNotification); } break; case MessageExpressionPayloads.ActionText: using (_runMethodDynamicCodeTimer.NewContext()) { _handler.HandleExecution(receivedMessage, workerNotification); } break; case MessageExpressionPayloads.Function: using (_runFunctionCompiledCodeTimer.NewContext()) { _handler.HandleExecution(receivedMessage, workerNotification); } break; case MessageExpressionPayloads.FunctionText: using (_runFunctionDynamicCodeTimer.NewContext()) { _handler.HandleExecution(receivedMessage, workerNotification); } break; default: throw new DotNetWorkQueueException($"Logic error - failed to handle type {receivedMessage.Body.PayLoad}"); } }
public async Task Should_trigger_the_consume_message_observer() { var observer = GetConsumeObserver(); TestConsumeMessageObserver <PingMessage> pingObserver = GetConsumeObserver <PingMessage>(); var mediator = MassTransit.Bus.Factory.CreateMediator(cfg => { }); mediator.ConnectConsumeObserver(observer); mediator.ConnectConsumeMessageObserver(pingObserver); TaskCompletionSource <ConsumeContext <PingMessage> > received = GetTask <ConsumeContext <PingMessage> >(); var handle = mediator.ConnectHandler <PingMessage>(x => { received.SetResult(x); return(TaskUtil.Completed); }); await mediator.Publish(new PingMessage()); await received.Task; handle.Disconnect(); await pingObserver.PostConsumed; IReceivedMessage <PingMessage> context = observer.Messages.Select <PingMessage>().First(); context.ShouldNotBeNull(); }
/// <summary> /// Handles processing of linq expression tree messages. /// </summary> /// <param name="receivedMessage">The received message.</param> /// <param name="workerNotification">The worker notification.</param> public void HandleExecution(IReceivedMessage<MessageExpression> receivedMessage, IWorkerNotification workerNotification) { ThrowIfDisposed(); Guard.NotNull(() => receivedMessage, receivedMessage); Guard.NotNull(() => workerNotification, workerNotification); switch (receivedMessage.Body.PayLoad) { case MessageExpressionPayloads.Action: HandleAction(receivedMessage, workerNotification); break; case MessageExpressionPayloads.Function: HandleFunction(receivedMessage, workerNotification); break; case MessageExpressionPayloads.ActionText: var targetMethod = _linqCompiler.CompileAction( _compositeSerialization.InternalSerializer.ConvertBytesTo<LinqExpressionToRun>( receivedMessage.Body.SerializedExpression)); try { HandleAction(targetMethod, receivedMessage, workerNotification); } catch (Exception error) //throw the real exception if needed { if (error.Message == "Exception has been thrown by the target of an invocation." && error.InnerException != null) { throw error.InnerException; } throw; } break; case MessageExpressionPayloads.FunctionText: var targetFunction = _linqCompiler.CompileFunction( _compositeSerialization.InternalSerializer.ConvertBytesTo<LinqExpressionToRun>( receivedMessage.Body.SerializedExpression)); try { HandleFunction(targetFunction, receivedMessage, workerNotification); } catch (Exception error) //throw the real exception if needed { if (error.Message == "Exception has been thrown by the target of an invocation." && error.InnerException != null) { throw error.InnerException; } throw; } break; default: throw new DotNetWorkQueueException($"The method type of {receivedMessage.Body.PayLoad} is not implemented"); } }
/// <inheritdoc /> public Task HandleAsync <T>(IWorkGroup workGroup, IReceivedMessage <T> message, IWorkerNotification notifications, Action <IReceivedMessage <T>, IWorkerNotification> functionToRun, ITaskFactory taskFactory) where T : class { using (var scope = _tracer.StartActivity("SchedulerMessageHandler")) { return(_handler.HandleAsync(workGroup, message, notifications, functionToRun, taskFactory)); } }
public async Task HandleMessageAsync(IPlayer player, IReceivedMessage message) { var castedMessage = (FindGameMessage)message; if (player.GameSessionGUID != Guid.Empty) { await collections.RemovePlayer(player); collections.AddPlayer(player); } var expectedGame = new ExpectedTicTacToe(castedMessage.Size); player.SetAsSearchingForGame(expectedGame); try { var opponent = collections.FindPlayerSearchingForGame(player); var session = sessionFactory.Create(player, opponent, expectedGame); collections.AddSession(session); logger.LogInformation("Created new game session."); await messageSender.SendMessageAsync(player.Socket, new GameFoundMessage(true)); await messageSender.SendMessageAsync(opponent.Socket, new GameFoundMessage(false)); } catch (InvalidOperationException) { } }
public Task SendMessage(IReceivedMessage message) { var messagesToSend = Encoding.UTF8.GetString(message.GetBody()); var promises = new List <Task>(); foreach (var hub in hubs.Values) { try { if (hub.Item1.State == ConnectionState.Connected) { hub.Item2.Invoke("MessageUpdate", messagesToSend); } else { hub.Item1.Start(); } } catch (Exception ex) { Console.WriteLine(ex); } } return(TaskDone.Done); }
public async Task HandleMessageAsync(IPlayer player, IReceivedMessage message) { var castedMessage = (CancelSessionMessage)message; await collections.RemovePlayer(player); collections.AddPlayer(player); }
public override async Task ProcessMessageAsync(IReceivedMessage <TBody> message, CancellationToken cancellation) { try { var data = message.Body; if (data?.Context == null) { Logger.LogError($"Message body is incorrect\n{nameof(data)}: {{@message:j}}", data); message.Nack(); return; } if (data.Context?.WebContext == null) { message.Ack(); } var mobileAppType = GetMobileAppType(data.Context.ClientType); var attributionHashes = new AttributionDataHashes( data.Context.WebContext?.AttributionDataHash, data.Context.WebContext?.AttributionDataLingeringHash); var channelAttributesId = await _channelAttributesManager.GetChannelAttributesIdAsync(attributionHashes.ActualHash); await SaveUserActionAsync(message.Body, mobileAppType, channelAttributesId, attributionHashes, cancellation); message.Ack(); } catch (Exception ex) { Logger.LogError(0, ex, "Unexpected error:\nMessage: {@message:j}", message.Body); message.Requeue(); } }
public static void HandleFakeMessagesRollback <TMessage>(IReceivedMessage <TMessage> message, int runTime, IncrementWrapper processedCount, long messageCount, ManualResetEventSlim waitForFinish, ConcurrentDictionary <string, int> haveIProcessedYouBefore) where TMessage : class { var key = message.CorrelationId.Id.Value.ToString(); if (haveIProcessedYouBefore.ContainsKey(key)) { if (runTime > 0) { Thread.Sleep(runTime * 1000); } Interlocked.Increment(ref processedCount.ProcessedCount); haveIProcessedYouBefore[key] = haveIProcessedYouBefore[key] + 1; if (Interlocked.Read(ref processedCount.ProcessedCount) == messageCount) { waitForFinish.Set(); } return; } haveIProcessedYouBefore.TryAdd(key, 0); throw new OperationCanceledException("I don't feel like processing this message"); }
public Task SendMessage(IReceivedMessage message) { var messagesToSend = Encoding.UTF8.GetString(message.GetBody()); var msg = JsonHelper.DeserializeJsonToObject <MessageDto>(messagesToSend); foreach (var hub in hubs.Values) { try { if (hub.Item1.State == ConnectionState.Connected) { hub.Item2.Invoke("MessageUpdate", messagesToSend, msg.DeviceId); } else { hub.Item1.Start(); } } catch (Exception ex) { Console.WriteLine(ex); } } return(TaskDone.Done); }
public async Task ProcessMessage(IReceivedMessage message) { _logger.Information(AppendingPrimaryKeyInfoToMessage("ProcessMessage() enter.")); string str = Encoding.UTF8.GetString(message.GetBody()); var msg = JsonHelper.DeserializeJsonToObject <MessageDto>(str); if (msg.MessageDirection == MessageDirection.ToClient) { var clientRouterGrain = GrainFactory.GetGrain <IClientMessageRouterGrain>(Guid.NewGuid()); await clientRouterGrain.RouteMessageToClient(message); } if (msg.MessageDirection == MessageDirection.ToHub) { var hubRouterGrain = GrainFactory.GetGrain <IHubMessageRouterGrain>(Guid.NewGuid()); await hubRouterGrain.RouteMessageToHub(message); } if (msg.MessageDirection == MessageDirection.ToPush) { var pushRouterGrain = GrainFactory.GetGrain <IPushRouterGrain>(Guid.NewGuid()); await pushRouterGrain.RouteMessageToPush(message); } if (msg.MessageDirection == MessageDirection.ToStart) { var commandListenerGrain = GrainFactory.GetGrain <ICommandListenerGrain>("CommandListener"); await commandListenerGrain.StartCommandProcessorHost(ConnectionConst.AmqpConnection, msg.Message); } _logger.Information(string.Format("Message received: {0}", str)); }
public static void HandleFakeMessages <TMessage>(IReceivedMessage <TMessage> message, int runTime, IncrementWrapper processedCount, int messageCount, ManualResetEventSlim waitForFinish) where TMessage : class { if (runTime > 0) { Thread.Sleep(runTime * 1000); } Interlocked.Increment(ref processedCount.ProcessedCount); var body = message?.Body as FakeMessage; if (body != null) { var result = processedCount.AddId(body.Id); if (!result) { waitForFinish.Set(); } } if (Interlocked.Read(ref processedCount.ProcessedCount) == messageCount) { waitForFinish.Set(); } }
public bool Execute(IReceivedMessage message) { var content = Encoding.UTF8.GetString(message.Body); var resource = JsonConvert.DeserializeObject <LinnappsSalesAccountResource>(content); this.salesAccountService.UpdateSalesAccountNameAndAddress( resource.AccountId, resource.AccountName, resource.AccountAddress, "/employees/100"); if (!string.IsNullOrEmpty(resource.DateClosed)) { this.salesAccountService.CloseSalesAccount( resource.AccountId, new SalesAccountCloseResource { ClosedOn = resource.DateClosed }, "/employees/100"); } else { this.salesAccountService.ReopenSalesAccountIfClosed(resource.AccountId, "/employees/100"); } this.rabbitTerminator.Close(); this.transactionManager.Commit(); return(true); }
private void ProcessRegisterMessageInternal(IReceivedMessage registerMessage) { IReadOnlyDictionary <IRegisterGroup, IRegister[]> requestMap = _device.RegisterGroups.MapRegistersToPossibleGroups(registerMessage.Registers); _log.AppendMessage(LogMessageType.Info, "Updating registers..."); switch (registerMessage.OperationType) { case OperationType.Write: requestMap.Update(); break; case OperationType.Read: requestMap.UpdateWithoutValues(); break; default: // todo: create a custom exception throw new Exception("Wrong operation type"); } _log.AppendMessage(LogMessageType.Info, "Registers updated. Sending response"); var response = new CommonMessage(_device.Address, MessageType.Response, registerMessage.OperationType, requestMap.Keys); _protocol.SendMessage(response); _log.AppendMessage(LogMessageType.Info, "Response has been successfully sent"); }
/// <inheritdoc /> public Task HandleAsync <T>(IWorkGroup workGroup, IReceivedMessage <T> message, IWorkerNotification notifications, Action <IReceivedMessage <T>, IWorkerNotification> functionToRun, ITaskFactory taskFactory) where T : class { using (IScope scope = _tracer.BuildSpan("SchedulerMessageHandler").StartActive(finishSpanOnDispose: true)) { return(_handler.HandleAsync(workGroup, message, notifications, functionToRun, taskFactory)); } }
public static void Run <TMessage>(IReceivedMessage <TMessage> message, IWorkerNotification notification, Guid queueId, int runTime) where TMessage : class { if (MethodIncrementWrapper.HasRollBack(queueId, (Guid)message.CorrelationId.Id.Value)) { var counter = runTime / 3; for (var i = 0; i < counter; i++) { if (notification.WorkerStopping.StopWorkToken.IsCancellationRequested || notification.WorkerStopping.CancelWorkToken.IsCancellationRequested) { MethodIncrementWrapper.IncreaseCounter(queueId); return; } Thread.Sleep(1000); } MethodIncrementWrapper.IncreaseCounter(queueId); } else { var counter = runTime / 2; for (var i = 0; i < counter; i++) { Thread.Sleep(1000); } MethodIncrementWrapper.SetRollback(queueId, (Guid)message.CorrelationId.Id.Value); throw new OperationCanceledException("I don't feel like processing this message"); } }
private void HandleMessages(IReceivedMessage <SimpleMessage> message, IWorkerNotification notifications) { notifications.Log.LogDebug( $"Processing Message {message.MessageId} with run time {message.Body.RunTimeInMs}"); if (message.Body.RunTimeInMs > 0) { var end = DateTime.Now + TimeSpan.FromMilliseconds(message.Body.RunTimeInMs); if (notifications.TransportSupportsRollback) { Task.Delay(message.Body.RunTimeInMs, notifications.WorkerStopping.CancelWorkToken).Wait(notifications.WorkerStopping.CancelWorkToken); } else //no rollback possible; we will ignore cancel / stop requests { Task.Delay(message.Body.RunTimeInMs); } if (DateTime.Now < end) //did we finish? { //nope - we probably are being canceled if (notifications.TransportSupportsRollback && notifications.WorkerStopping.CancelWorkToken.IsCancellationRequested) { notifications.Log.LogDebug("Cancel has been requested - aborting"); notifications.WorkerStopping.CancelWorkToken.ThrowIfCancellationRequested(); } } } notifications.Log.LogDebug($"Processed message {message.MessageId}"); }
public async Task Should_be_handled_by_the_consumer() { Assert.That(_consumer.Consumed.Select <TestEvent>().Any(), Is.True); IReceivedMessage <TestEvent> message = _consumer.Consumed.Select <TestEvent>().First(); Assert.That(message.Context.CorrelationId, Is.EqualTo(_correlationId)); }
public async Task Should_have_the_content_type() { Assert.That(_consumer.Consumed.Select <TestEvent>().Any(), Is.True); IReceivedMessage <TestEvent> message = _consumer.Consumed.Select <TestEvent>().First(); Assert.That(message.Context.ReceiveContext.ContentType, Is.EqualTo(JsonMessageSerializer.JsonContentType)); }
/// <summary> /// Checks to see if the queue is stopping; if not, runs the user provided message processing delegate /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message">The message.</param> /// <param name="notifications">The notifications.</param> /// <param name="functionToRun">The function to run.</param> private void WrappedFunction <T>(IReceivedMessage <T> message, IWorkerNotification notifications, Action <IReceivedMessage <T>, IWorkerNotification> functionToRun) where T : class { if (ShouldHandle(notifications)) { functionToRun(message, notifications); } }
public void RouteMessage(Type payloadType, IReceivedMessage <object> receivedMessage) { Action <IReceivedMessage <object> > handler; if (handlersByPayloadType.TryGetValue(payloadType, out handler)) { handler(receivedMessage); } }
public async Task Should_have_the_content_type_transport_header() { Assert.That(_consumer.Consumed.Select <TestEvent>().Any(), Is.True); IReceivedMessage <TestEvent> message = _consumer.Consumed.Select <TestEvent>().First(); Assert.That(message.Context.ReceiveContext.TransportHeaders.Get("Content-Type", default(string)), Is.EqualTo(JsonMessageSerializer.ContentTypeHeaderValue)); }
public bool Execute(IReceivedMessage message) { var content = Encoding.UTF8.GetString(message.Body); var resource = JsonConvert.DeserializeObject <StartTriggerRunResource>(content); this.log.Warning($"Trigger run started at {DateTime.Now.ToLongTimeString()} by {resource.RequestedByUri}"); this.triggerRunPack.AutoTriggerRun(); return(true); }
public async Task RouteMessageToPush(IReceivedMessage message) { _logger.Information(AppendingPrimaryKeyInfoToMessage("RouteMessageToPush() enter.")); var pusher = GrainFactory.GetGrain <IMessagePushGrain>(0); await pusher.SendMessage(message); _logger.Information(AppendingPrimaryKeyInfoToMessage("RouteMessageToClient() exit.")); }
public void Add(IReceivedMessage message) { lock (_messages) { if (_messages.Add(message)) { _received.Set(); } } }
public Message(IReceivedMessage message) : this(message.Context) { MessageType = message.MessageType; ShortTypeName = message.ShortTypeName; EventType = MessageEventType.Consume; StartTime = message.StartTime; ElapsedTime = message.ElapsedTime; }
/// <inheritdoc /> public void HandleExecution(IReceivedMessage <MessageExpression> receivedMessage, IWorkerNotification workerNotification) { var ActivityContext = receivedMessage.Headers.Extract(_tracer, _headers); using (var scope = _tracer.StartActivity("LinqExecution", ActivityKind.Internal, parentContext: ActivityContext)) { scope?.SetTag("ActionType", receivedMessage.Body.PayLoad.ToString()); _handler.HandleExecution(receivedMessage, workerNotification); } }
public void Handle(IReceivedMessage <AnotherTestMessage> message) { if (!timerSet) { sw.Start(); timerSet = true; } logger.Info("AnotherTestMessageSubscriber Message received: {0} {1} {2}", message.Message.Value, message.Message.MessageId, sw.ElapsedMilliseconds); throw new Exception("Bad Day"); }
public bool Execute(IReceivedMessage message) { var content = Encoding.UTF8.GetString(message.Body); var resource = JsonConvert.DeserializeObject <InvoiceResource>(content); this.log.Info($"Checking invoice {resource.id} for dem root products"); this.invoiceProcessingService.CaptureDemRootProductsFromInvoice(resource); return(true); }
private void Reply(IReceivedMessage message, JsonTransportResponse response) { var reply = message.CreateReply(); var headers = AmqpRpc.CreateHeaders(null, response.Status); reply.Properties.Headers = headers; _log.Debug("Sending reply: {0}", response.Body); reply.Body = Json.Serialize(response.Body); reply.From = null; _messaging.Send(reply); }
private static String EndpointFor(IReceivedMessage message) { var headers = message.Properties.Headers; if (!headers.Contains(AmqpRpc.EndpointHeader)) { throw new KeyNotFoundException("Message did not contain header: " + AmqpRpc.EndpointHeader); } var endpointHeader = headers[AmqpRpc.EndpointHeader]; return(Encoding.UTF8.GetString((byte[])endpointHeader)); }
public async Task Should_be_received() { var message = new B { Id = Guid.NewGuid() }; await Bus.Publish(message); _consumer.Received.Select <B>().Any().ShouldBe(true); IReceivedMessage <B> receivedMessage = _consumer.Received.Select <B>().First(); Assert.AreEqual(message.Id, receivedMessage.Context.Message.Id); }
private static String EndpointFor(IReceivedMessage message) { var headers = message.Properties.Headers; if (! headers.Contains(AmqpRpc.EndpointHeader)) { throw new KeyNotFoundException("Message did not contain header: " + AmqpRpc.EndpointHeader); } var endpointHeader = headers[AmqpRpc.EndpointHeader]; return Encoding.UTF8.GetString((byte[]) endpointHeader); }
private void Ack(IReceivedMessage message) { _messaging.Ack(message); }
/// <summary> /// De-serializes and runs a compiled linq func expression. /// </summary> /// <param name="receivedMessage">The received message.</param> /// <param name="workerNotification">The worker notification.</param> private void HandleFunction(IReceivedMessage<MessageExpression> receivedMessage, IWorkerNotification workerNotification) { var target = _serializer.ConvertBytesToFunction(receivedMessage.Body.SerializedExpression); try { HandleFunction(target.Compile(), receivedMessage, workerNotification); } catch (Exception error) //throw the real exception if needed { if (error.Message == "Exception has been thrown by the target of an invocation." && error.InnerException != null) { throw error.InnerException; } throw; } }
private static void HandleGamePadState(IReceivedMessage<GamePadStateDto> x) { var state = x.Payload; Console.WriteLine($"Got gamepad state: {state}"); }
/// <summary> /// De-serializes and runs a compiled linq func expression. /// </summary> /// <param name="function">The function.</param> /// <param name="receivedMessage">The received message.</param> /// <param name="workerNotification">The worker notification.</param> private void HandleFunction(Func<IReceivedMessage<MessageExpression>, IWorkerNotification, object> function, IReceivedMessage<MessageExpression> receivedMessage, IWorkerNotification workerNotification) { var result = function.DynamicInvoke(receivedMessage, workerNotification); if (result == null) return; //if we have a connection, this is an rpc request var connection = receivedMessage.GetHeader(workerNotification.HeaderNames.StandardHeaders.RpcConnectionInfo); //if no connection, then this was not RPC if (connection == null) return; var timeOut = receivedMessage.GetHeader(workerNotification.HeaderNames.StandardHeaders.RpcTimeout).Timeout; //if we don't have an RPC queue for this queue, create one CreateRpcModuleIfNeeded(connection); //send the response var response = _rpcQueues[connection].Send( result, _rpcQueues[connection].CreateResponse(receivedMessage.MessageId, timeOut)); if (response.HasError) { _log.ErrorException("Failed to send a response for message {0}", response.SendingException, receivedMessage.MessageId.Id.Value); } }
/// <summary> /// Runs a compiled linq expression. /// </summary> /// <param name="action">The action.</param> /// <param name="receivedMessage">The received message.</param> /// <param name="workerNotification">The worker notification.</param> private void HandleAction(Action<IReceivedMessage<MessageExpression>, IWorkerNotification> action, IReceivedMessage<MessageExpression> receivedMessage, IWorkerNotification workerNotification) { action.DynamicInvoke(receivedMessage, workerNotification); }