public async Task <IActionResult> CreateSession(MessageSessionCreateViewModel viewModel) { if (ModelState.IsValid) { var fromEmail = await Services.AuthorizationServices.VerifyToken(clientFactory, viewModel.FromJwt); if (fromEmail != null) { var session = new MessageSession { Title = viewModel.Title, Description = viewModel.Description, Emails = fromEmail }; if (viewModel.Emails != null) { session.Emails += ";" + string.Join(';', viewModel.Emails).ToLower(); } await sessionRepository.CreateMessageSessionAsync(session); return(Ok(JsonConvert.SerializeObject(session))); } return(BadRequest("Specified Token Not Found")); } return(BadRequest(ModelState)); }
protected override async Task ReceiveMessageImplAsync( BrokeredMessage message, MessageSession session, CancellationToken cancellationToken) { var userId = message.GetBody <Guid>(); var transportation = new Transportation { TransportationId = Guid.NewGuid(), IsActive = true, CreatedAt = DateTime.UtcNow.Subtract(DateTime.MinValue.AddYears(1969)).TotalSeconds }; await _transportationRepository.SaveTransportation(transportation, userId); WriteLog($"Handling queue message {message.MessageId}"); var payload = new PostTransporationResultMessage { TransportationId = transportation.TransportationId }; await _serviceBusCommunicationService.SendBrokeredMessage(new BrokeredMessage(payload) { SessionId = message.SessionId }, "Processed-Post-Transportation-Queue"); }
protected override Task ReceiveMessageImplAsync(BrokeredMessage message, MessageSession session, CancellationToken cancellationToken) { ServiceEventSource.Current.ServiceMessage(_service, $"Handling queue message {message.MessageId} in session {session?.SessionId ?? "none"}"); RPA.RPATicket ticket; try { ticket = message.GetBody <RPA.RPATicket>(); ticket = checkScope(ticket); if (ticket.Matches.Count > 0) { sendToInScopeQueue(ticket); } else { sendToOutOfScopeQueue(message); } } catch (Exception) { sendToErrorQueue(message); return(Task.FromResult(false)); } return(Task.FromResult(true)); }
/// <summary> /// Create a new session handler. /// </summary> /// <param name="session"></param> /// <param name="message"></param> /// <returns></returns> public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message) { ServiceBusEventSource.Log.SessonAccepted(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId); // Use the current handler. return(new SessionMessageAsyncHandler(_receiverNamespace, _receiverPath, session, _messageHandler, _options)); }
public Task OnCloseSessionAsync(MessageSession session) { ServiceBusEventSource.Log.SessionClosed(_receiverNamespace, _receiverPath, session.SessionId); // No need to do anything else. return(Task.FromResult(0)); }
public async Task ResubmitTheEvent() { var identifiedRemovedLearningAimEvent = Context.Get <IdentifiedRemovedLearningAim>(IdentifiedRemovedLearningAim); identifiedRemovedLearningAimEvent.EventId = Guid.NewGuid(); await MessageSession.Publish(identifiedRemovedLearningAimEvent); }
internal void OnInteract(Entity entity, MessageSession session, InteractMsg msg) { if (entity.Has <Fightable>()) { var template = DataCenter.Instance.GetDatum <InteractTemplate>(msg.InteractId); if (template == null) { Logger.Write("Request a invalid interact[{0}]", msg.InteractId); return; } EffectSystem.Affect(entity, template); } else { PositionSystem.Global.Interact(entity, targets => { // default interaction - remove removables foreach (var target in targets.Where(target => target.Has <Removable>() && target.Get <Removable>().Action)) { // despawn target PositionSystem.Global.Disappear(target); EntityBinder.Instance.Remove(target); EntityManager.Instance.Remove(target.Id); } }); } }
protected override Task ReceiveMessageImplAsync(BrokeredMessage message, MessageSession session, CancellationToken cancellationToken) { ServiceEventSource.Current.ServiceMessage(_service, $"Handling queue message {message.MessageId} in session {session?.SessionId ?? "none"}"); RPATicket ticket; try { ticket = message.GetBody <RPATicket>(); ticket.TicketId = Guid.NewGuid().ToString(); bool isValid = validate(ticket); if (isValid) { sendToEmail(new BrokeredMessage(ticket)); } else { sendToErrorQueue(message); } } catch (Exception e) { Console.WriteLine(e.Message); sendToErrorQueue(message); return(Task.FromResult(false)); } return(Task.FromResult(true)); }
protected async void cmdSend2_Click(object sender, EventArgs e) { byte[] dataArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; BrokeredMessage msg = new BrokeredMessage(dataArr); msg.Properties.Add("suma", 1); msg.ReplyToSessionId = Guid.NewGuid().ToString("N"); await m_tc.SendAsync(msg); MessageSession session = m_qc.AcceptMessageSession(msg.ReplyToSessionId, TimeSpan.FromSeconds(60)); List <BrokeredMessage> lst = new List <BrokeredMessage>(); while (lst.Count < 2) { msg = await session.ReceiveAsync(); if (msg != null) { lst.Add(msg); await msg.CompleteAsync(); } } lblInfo.Text = ""; foreach (var item in lst) { lblInfo.Text += item.GetBody <string>(); } }
public async Task WhenThereIsAChangeToTheApprenticeshipDetailsForOneOfTheProviderSLearners() { await MessageSession.Publish <ApprenticeshipUpdated>(m => { m.Ukprn = TestSession.Ukprn; }); }
/// <summary> /// Creates an instance of the handler factory. /// </summary> /// <returns> /// The created instance. /// </returns> /// <param name="session">The message session.</param> /// <param name="message">The message.</param> IMessageSessionAsyncHandler IMessageSessionAsyncHandlerFactory.CreateInstance(MessageSession session, BrokeredMessage message) { return new SessionHandler( msg => messageSubject.OnNext(msg), ex => exceptionSubject.OnNext(ex), scheduler); }
public async Task GenerateMetricsFromLatestJob(int count) { //set these to the period you have data for var academicYear = 2122; var collectionPeriod = 11; var dataContext = Container.Resolve <JobsDataContext>(); var jobs = await dataContext.Jobs .Where(job => job.JobType == JobType.EarningsJob && (job.Status == JobStatus.Completed || job.Status == JobStatus.CompletedWithErrors) && job.AcademicYear == academicYear && job.CollectionPeriod > collectionPeriod ).OrderByDescending(job => job.LearnerCount) .Take(count) .ToListAsync(); var messages = jobs.Select(job => new RecordPeriodEndRequestReportsJob { JobId = job.DcJobId.Value, CollectionPeriod = job.CollectionPeriod, CollectionYear = job.AcademicYear, }) .ToList(); foreach (var periodEndRequestReportsEvent in messages) { await MessageSession.Send(periodEndRequestReportsEvent).ConfigureAwait(false); } }
public async Task GenerateMetricsFromLatestJob(int count) { var dataContext = Container.Resolve <JobsDataContext>(); var jobs = await dataContext.Jobs .Where(job => job.JobType == JobType.EarningsJob && (job.Status == JobStatus.Completed || job.Status == JobStatus.CompletedWithErrors) ).OrderByDescending(job => job.LearnerCount) .Take(count) .ToListAsync(); var messages = jobs.Select(job => new GenerateSubmissionSummary { Ukprn = job.Ukprn.Value, CollectionPeriod = job.CollectionPeriod, AcademicYear = job.AcademicYear, JobId = job.DcJobId.Value, }) .ToList(); foreach (var generateSubmissionSummary in messages) { await MessageSession.Send(generateSubmissionSummary).ConfigureAwait(false); } }
public Task OnCloseSessionAsync(MessageSession session) { ServiceBusEventSource.Log.SessionClosed(_receiverNamespace, _receiverPath, session.SessionId); // No need to do anything else. return Task.FromResult(0); }
public async Task Send() { await CreateResponseQueue(); QueueClient sendClient = QueueClient.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey], Helpers.BasicQueueName); QueueClient responseClient = QueueClient.CreateFromConnectionString(ConfigurationManager.AppSettings[Helpers.ConnectionStringKey], Helpers.ResponseQueue); byte[] messageData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Helpers.GetModels())); string sessionId = Guid.NewGuid().ToString("N"); BrokeredMessage message = new BrokeredMessage(new MemoryStream(messageData), true) { ContentType = "application/json", Label = "dynamic data", TimeToLive = TimeSpan.FromMinutes(20), ReplyToSessionId = sessionId, ReplyTo = Helpers.ResponseQueue }; await sendClient.SendAsync(message); MessageSession messageSession = await responseClient.AcceptMessageSessionAsync(sessionId); BrokeredMessage responseMessage = await messageSession.ReceiveAsync(); string responseMessageBody = responseMessage.GetBody <string>(); Console.WriteLine($"Message response received: \n{responseMessageBody}"); }
public MessageSessionAsyncHandler(ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, BrokeredMessage message) { _supervisor = supervisor; _receiver = receiver; _session = session; _message = message; }
protected override async Task <SessionWorkItem> OnFetchWorkItem(TimeSpan receiveTimeout) { MessageSession session = await orchestratorQueueClient.AcceptMessageSessionAsync(receiveTimeout); if (session == null) { return(null); } IEnumerable <BrokeredMessage> newMessages = await Utils.ExecuteWithRetries(() => session.ReceiveBatchAsync(PrefetchCount), session.SessionId, "Receive Session Message Batch", MaxRetries, IntervalBetweenRetriesSecs); TraceHelper.TraceSession(TraceEventType.Information, session.SessionId, GetFormattedLog( $@"{newMessages.Count()} new messages to process: { string.Join(",", newMessages.Select(m => m.MessageId)) }, max latency: { newMessages.Max(message => message.DeliveryLatency())}ms" )); return(new SessionWorkItem { Session = session, Messages = newMessages }); }
protected override async Task <SessionWorkItem> OnFetchWorkItem(TimeSpan receiveTimeout) { IEnumerable <BrokeredMessage> newMessages = null; MessageSession session = await trackingQueueClient.AcceptMessageSessionAsync(receiveTimeout); if (session == null) { return(null); } newMessages = await Utils.ExecuteWithRetries(() => session.ReceiveBatchAsync(PrefetchCount), session.SessionId, "Receive Tracking Message Batch", MaxRetriesServiceBus, IntervalBetweenRetriesSecs); TraceHelper.TraceSession(TraceEventType.Information, session.SessionId, GetFormattedLog( string.Format("{0} new messages to process: {1}", newMessages.Count(), string.Join(",", newMessages.Select(m => m.MessageId + " [" + m.SequenceNumber + "]"))))); return(new SessionWorkItem { Session = session, Messages = newMessages }); }
public async Task WhenTheEventIsDuplicatedButWithADifferentCommandIdOnTheProcessLearnerCommand() { var command = Context.Get <ProcessLearnerCommand>(ProcessLearnerCommand); command.CommandId = Guid.NewGuid(); await MessageSession.Send(command); }
protected override async Task ReceiveMessageImplAsync( BrokeredMessage message, MessageSession session, CancellationToken cancellationToken) { var postUserRoleMessage = message.GetBody <PostUserRoleMessage>(); foreach (var role in (RoleType[])Enum.GetValues(typeof(RoleType))) { await _roleRepository.DeleteUserRole(postUserRoleMessage.UserId, role); } foreach (var role in postUserRoleMessage.Roles) { await _roleRepository.AddUserRole(postUserRoleMessage.UserId, (RoleType)Enum.Parse(typeof(RoleType), role)); } WriteLog($"Handling queue message {message.MessageId}"); var payload = new PostUserRoleResultMessage(); await _serviceBusCommunicationService.SendBrokeredMessage(new BrokeredMessage(payload) { SessionId = message.SessionId }, "Processed-Post-User-Roles-Queue"); }
static void SendMessages(TopicClient topicClient, SubscriptionClient responseClient) { // Send request messages to queue: Console.WriteLine("Sending request messages to topic {0}", topicClient.Path); Console.WriteLine("Receiving response messages on subscription {0}", responseClient.Name); MessageSession session = responseClient.AcceptMessageSession(ClientId); for (int i = 0; i < SampleManager.NumMessages; ++i) { // send request message BrokeredMessage message = new BrokeredMessage { ReplyToSessionId = ClientId, MessageId = i.ToString(), CorrelationId = SampleManager.RequestSubName }; topicClient.Send(message); SampleManager.OutputMessageInfo("REQUEST: ", message); // start asynchronous receive operation //TODO: Fix //session.ReceiveAsync ( TimeSpan.FromSeconds(ResponseMessageTimeout), ProcessResponse, session); var brokeredMessage = session.Receive(TimeSpan.FromSeconds(ResponseMessageTimeout)); ProcessResponse(brokeredMessage); } Console.WriteLine(); }
public static void ReceiveQ() { Console.WriteLine("In Receive method()."); TokenProvider credentials = TokenProvider.CreateSharedSecretTokenProvider(QReceiver.IssuerName, QReceiver.IssuerKey); Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", QReceiver.ServiceNamespace, string.Empty); MessagingFactory factory = null; factory = MessagingFactory.Create(serviceUri, credentials); QueueClient sessionQueueClient = factory.CreateQueueClient(QReceiver.QueueName); //Create sessionQueueClient and subscribe to SessionIDs that have a value of "Mike" MessageSession sessionReceiver = sessionQueueClient.AcceptMessageSession("92610", TimeSpan.FromSeconds(60)); BrokeredMessage receivedMessage; while ((receivedMessage = sessionReceiver.Receive(TimeSpan.FromSeconds(60))) != null) { Console.WriteLine("Received Messages."); var data = receivedMessage.GetBody <FireEvent>(new DataContractSerializer(typeof(FireEvent))); //Console.WriteLine(String.Format("Customer Name: {0}", data.CustomerName)); Console.WriteLine("SessionID: {0}", receivedMessage.SessionId); //remove message from Topic receivedMessage.Complete(); } Console.WriteLine("All received on this session...press enter to exit"); Console.Read(); }
/// <summary> /// Create a new session handler. /// </summary> /// <param name="session"></param> /// <param name="message"></param> /// <returns></returns> public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message) { ServiceBusEventSource.Log.SessonAccepted(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId); // Use the current handler. return new SessionMessageAsyncHandler(_receiverNamespace, _receiverPath, session, _messageHandler, _options); }
/// <summary> /// Get all messages that has a session /// </summary> /// <param name="client">QueueClient</param> private void GetSessionMessages(QueueClient client) { try { MessageSession ses = client.AcceptMessageSession(properties.Session); BrokeredMessage item = ses.Receive(properties.ReceiveTimeout); while (true) { if (item == null) { break; } if (SubmitMessage(item) == false) { ses.Abort(); break; } //allow setting timeout item = ses.Receive(properties.ReceiveTimeout); } } catch (Exception) { //probably lock } }
/// <summary> /// Get all messages with a specific session /// </summary> /// <param name="client">QueueClient</param> private void GetAllMessagesWithSession(QueueClient client) { foreach (MessageSession sessions in client.GetMessageSessions()) { try { MessageSession ses = client.AcceptMessageSession(sessions.SessionId); BrokeredMessage item = ses.Receive(properties.ReceiveTimeout); while (true) { if (item == null) { break; } if (SubmitMessage(item) == false) { ses.Abort(); break; } //allow setting timeout item = ses.Receive(properties.ReceiveTimeout); } } catch (Exception) { break; } } }
public async Task <ActionResult> Sub(int a = 5, int b = 12) { int result = 0; Param p = new Param { A = a, B = b }; BrokeredMessage msg = new BrokeredMessage(p); msg.Properties.Add("operation", 2); msg.ReplyToSessionId = Guid.NewGuid().ToString("N"); await m_tc.SendAsync(msg); string session = msg.ReplyToSessionId; msg = null; while (msg == null) { MessageSession msgsession = m_qc.AcceptMessageSession(session, TimeSpan.FromSeconds(360)); msg = await msgsession.ReceiveAsync(); if (msg != null) { result = msg.GetBody <int>(); } } return(View(result)); }
public MessageSessionPage(SessionSettings settings, MessageSession session) { _settings = settings; BindingContext = new MessageSessionPageContext(session); _context = BindingContext as MessageSessionPageContext; _threadStart = new ThreadStart(() => { while (true) { try { _context.RefreshMessages(_settings.Jwt); Thread.Sleep(3000); } catch (ThreadAbortException) { break; } } }); _refreshThread = new Thread(_threadStart); InitializeComponent(); }
public async Task <IActionResult> UpdateSession(MessageSessionUpdateViewModel viewModel) { if (ModelState.IsValid) { var fromEmail = await Services.AuthorizationServices.VerifyToken(clientFactory, viewModel.JwtFrom); if (fromEmail == null) { return(Unauthorized()); } var session = new MessageSession { Title = viewModel.Title, Description = viewModel.Description, Emails = fromEmail }; if (viewModel.Emails != null) { session.Emails += ";" + string.Join(';', viewModel.Emails).ToLower(); } await sessionRepository.UpdateMessageSessionAsync(viewModel.Id, session); return(Ok(JsonConvert.SerializeObject(session))); } return(BadRequest()); }
static void ProcessMessage(BrokeredMessage message, MessageSession session = null) { DateTime startProcessingNewMessage = DateTime.Now; TimeSpan elapsed = startProcessingNewMessage - lastReceive; lastReceive = startProcessingNewMessage; // Using the Session State to track how much processing time was spent on a group. // This value will persist even if a receiver process is killed and the remaining // messages are picked up by another receiver. string readState = null; if (session != null) { TimeSpan totalElapsed = elapsed; readState = GetState(session); if (readState != null) { TimeSpan prevElapsed = TimeSpan.FromSeconds(Double.Parse(readState)); totalElapsed = elapsed + prevElapsed; } SetState(session, totalElapsed.TotalSeconds.ToString()); } SampleManager.OutputMessageInfo("RECV: ", message, "State: " + readState); Thread.Sleep(receiverDelay); }
public void VerifyTokensForAmendedTemplate() { VerifyCommonTokensForTemplate("review"); MessageSession.Verify(x => x.Send(It.Is <SendEmailToEmployerCommand>(p => p.Tokens["provider_name"] == Commitment.ProviderName && p.Tokens["employer_hashed_account"] == Commitment.EmployerAccountId.ToString()), It.IsAny <SendOptions>())); }
/// <summary> /// 转换为MessageSession用于数据库存储 /// </summary> public MessageSession AsMessageSession() { MessageSession messageSession; if (SessionId > 0) { MessageService messageService = new MessageService(); messageSession = messageService.GetSession(SessionId); messageSession.LastMessageId = this.LastMessageId; messageSession.MessageCount = this.MessageCount; messageSession.MessageType = this.MessageType; messageSession.OtherUserId = this.OtherUserId; messageSession.UnreadMessageCount = this.UnreadMessageCount; messageSession.UserId = this.UserId; } else { messageSession = MessageSession.New(); messageSession.LastMessageId = this.LastMessageId; messageSession.MessageCount = this.MessageCount; messageSession.MessageType = this.MessageType; messageSession.OtherUserId = this.OtherUserId; messageSession.UnreadMessageCount = this.UnreadMessageCount; messageSession.UserId = this.UserId; } return(messageSession); }
public Task OnCloseSessionAsync(MessageSession session) { if (_log.IsDebugEnabled) _log.DebugFormat("Session Closed: {0} ({1})", session.SessionId, _receiver.InputAddress); return TaskUtil.Completed; }
protected override Task ReceiveMessageImplAsync(BrokeredMessage message, MessageSession session, CancellationToken cancellationToken) { ServiceEventSource.Current.ServiceMessage(_service, $"Handling queue message {message.MessageId} in session {session?.SessionId ?? "none"}"); RPATicket ticket = null; try { ticket = message.GetBody <RPATicket>(); bool isValid = validate(ticket); if (isValid) { executionScript(ticket); } else { sendToErrorQueue(ticket); } } catch (Exception e) { ticket.Error = e.Message; sendToErrorQueue(ticket); return(Task.FromResult(false)); } storeResultToDB(ticket); return(Task.FromResult(true)); }
static void SendMessages(QueueClient requestClient, QueueClient responseClient) { // Send request messages to queue: Console.WriteLine("Sending request messages to queue {0}", requestClient.Path); Console.WriteLine("Receiving response messages on queue {0}", responseClient.Path); MessageSession receiver = responseClient.AcceptMessageSession(ReplyToSessionId); for (int i = 0; i < SampleManager.NumMessages; ++i) { // send request message BrokeredMessage message = CreateRequestMessage(i); requestClient.Send(message); SampleManager.OutputMessageInfo("REQUEST: ", message); // receive response message BrokeredMessage receivedMessage = receiver.Receive(TimeSpan.FromSeconds(ResponseMessageTimeout)); if (receivedMessage != null) { SampleManager.OutputMessageInfo("RESPONSE: ", message); receivedMessage.Complete(); } else { Console.WriteLine("ERROR: Response timed out."); } } receiver.Close(); Console.WriteLine(); }
public MessageSessionAsyncHandler(ConnectionContext context, ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, BrokeredMessage message) { _context = context; _supervisor = supervisor; _receiver = receiver; _session = session; _message = message; }
public SessionMessageAsyncHandler(string receiverNamespace, string receiverPath, MessageSession session, OnSessionMessage messageHandler, OnSessionMessageOptions options) { _receiverNamespace = receiverNamespace; _receiverPath = receiverPath; _session = session; _messageHandler = messageHandler; _options = options; }
public MessageSessionAsyncHandler(NamespaceContext context, ITaskSupervisor supervisor, ISessionReceiver receiver, MessageSession session, IDeliveryTracker tracker, ISendEndpointProvider sendEndpointProvider, IPublishEndpointProvider publishEndpointProvider) { _context = context; _supervisor = supervisor; _receiver = receiver; _session = session; _tracker = tracker; _sendEndpointProvider = sendEndpointProvider; _publishEndpointProvider = publishEndpointProvider; }
public StartableEndpoint(SettingsHolder settings, IBuilder builder, FeatureActivator featureActivator, PipelineConfiguration pipelineConfiguration, IEventAggregator eventAggregator, TransportInfrastructure transportInfrastructure, CriticalError criticalError) { this.criticalError = criticalError; this.settings = settings; this.builder = builder; this.featureActivator = featureActivator; this.pipelineConfiguration = pipelineConfiguration; this.eventAggregator = eventAggregator; this.transportInfrastructure = transportInfrastructure; pipelineCache = new PipelineCache(builder, settings); messageSession = new MessageSession(new RootContext(builder, pipelineCache, eventAggregator)); }
async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message) { if (_receiver.IsShuttingDown) { await WaitAndAbandonMessage(message).ConfigureAwait(false); return; } using (var delivery = _tracker.BeginDelivery()) { if (_log.IsDebugEnabled) _log.DebugFormat("Receiving {0}:{1}({3}) - {2}", delivery.Id, message.MessageId, _receiver.QueuePath, session.SessionId); var context = new ServiceBusReceiveContext(_receiver.InputAddress, message, _context, _sendEndpointProvider, _publishEndpointProvider); context.GetOrAddPayload<MessageSessionContext>(() => new BrokeredMessageSessionContext(session)); context.GetOrAddPayload(() => _context); try { await _context.PreReceive(context).ConfigureAwait(false); await _receiver.ReceivePipe.Send(context).ConfigureAwait(false); await context.CompleteTask.ConfigureAwait(false); await message.CompleteAsync().ConfigureAwait(false); await _context.PostReceive(context).ConfigureAwait(false); if (_log.IsDebugEnabled) _log.DebugFormat("Receive completed: {0}", message.MessageId); } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"Received faulted: {message.MessageId}", ex); await message.AbandonAsync().ConfigureAwait(false); await _context.ReceiveFault(context, ex).ConfigureAwait(false); } finally { context.Dispose(); } } }
async Task IMessageSessionAsyncHandler.OnMessageAsync(MessageSession session, BrokeredMessage message) { if (_receiver.IsShuttingDown) { await WaitAndAbandonMessage(message).ConfigureAwait(false); return; } var deliveryCount = _receiver.IncrementDeliveryCount(); if (_log.IsDebugEnabled) _log.DebugFormat("Receiving {0}:{1}({3}) - {2}", deliveryCount, message.MessageId, _receiver.QueuePath, session.SessionId); var context = new ServiceBusReceiveContext(_receiver.InputAddress, message, _receiver.ReceiveObserver); context.GetOrAddPayload<MessageSessionContext>(() => new BrokeredMessageSessionContext(session)); try { await _receiver.ReceiveObserver.PreReceive(context).ConfigureAwait(false); await _receiver.ReceivePipe.Send(context).ConfigureAwait(false); await context.CompleteTask.ConfigureAwait(false); await message.CompleteAsync().ConfigureAwait(false); await _receiver.ReceiveObserver.PostReceive(context).ConfigureAwait(false); if (_log.IsDebugEnabled) _log.DebugFormat("Receive completed: {0}", message.MessageId); } catch (Exception ex) { if (_log.IsErrorEnabled) _log.Error($"Received faulted: {message.MessageId}", ex); await message.AbandonAsync().ConfigureAwait(false); await _receiver.ReceiveObserver.ReceiveFault(context, ex).ConfigureAwait(false); } finally { _receiver.DeliveryComplete(); } }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { try { ServiceBusEventSource.Log.SessionMessageReceived(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId); // Handle the message. await _messageHandler(session, message); } catch (Exception exception) { ServiceBusEventSource.Log.SessionMessageReceiverException(_receiverNamespace, _receiverPath, session.SessionId, message.MessageId, message.CorrelationId, "OnMessage", exception.Message, exception.StackTrace); // Don't allow other messages to be processed. if (_options.RequireSequentialProcessing) { message.Abandon(); session.Abort(); } throw; } }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { try { ServiceBusEventSource.Log.SessionMessageReceived(_receiverNamespace, _receiverPath, message.MessageId, message.CorrelationId, message.SessionId, message.DeliveryCount, message.Size); // Handle the message. await _messageHandler(session, message) .ConfigureAwait(false); } catch (Exception exception) { ServiceBusEventSource.Log.MessagePumpExceptionReceived(_receiverNamespace, _receiverPath, "OnSessionMessage", exception); // Don't allow other messages to be processed. if (_options.RequireSequentialProcessing) { message.Abandon(); session.Abort(); } throw; } }
public async Task OnCloseSessionAsync(MessageSession session) { // nothing to do }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { try { if (message == null) { return; } if (session == null) { return; } if (configuration == null) { return; } if (configuration.MessageInspector != null) { message = configuration.MessageInspector.AfterReceiveMessage(message); } if (configuration.Logging) { var builder = new StringBuilder(string.Format(MessageSuccessfullyReceived, string.IsNullOrWhiteSpace(message.MessageId) ? NullValue : message.MessageId, string.IsNullOrWhiteSpace(message.SessionId) ? NullValue : message.SessionId, string.IsNullOrWhiteSpace(message.Label) ? NullValue : message.Label, message.Size)); if (configuration.Verbose) { configuration.ServiceBusHelper.GetMessageAndProperties(builder, message, configuration.MessageEncoder); } configuration.WriteToLog(builder.ToString(), false); } if (configuration.Tracking) { configuration.TrackMessage(message.Clone()); } if (configuration.Graph) { configuration.UpdateStatistics(1, configuration.GetElapsedTime(), message.Size); } if (configuration.ReceiveMode == ReceiveMode.PeekLock && !configuration.AutoComplete) { await message.CompleteAsync(); } if (!SessionDictionary.ContainsKey(message.SessionId)) { SessionDictionary.Add(message.SessionId, 1); } else { SessionDictionary[message.SessionId]++; } } catch (Exception ex) { HandleException(ex); } }
/// <summary> /// Handle the message. /// </summary> /// <param name="session"></param> /// <param name="brokeredMessage"></param> /// <param name="receiver"></param> /// <param name="handlerMap"></param> /// <returns></returns> private async Task OnHandleMessage(IMessageReceiver receiver, MessageSession session, BrokeredMessage brokeredMessage, MessageHandlerMap handlerMap) { MessagingEventSource.Log.MessageReceived(brokeredMessage.ContentType, receiver, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId); // Create new isolated scope. using (var scope = Configuration.Container.BeginScope()) { var envelope = await BuildMessage(brokeredMessage); // Dispatch the message. var dispatcher = new MessageDispatcher(scope, handlerMap); await dispatcher.Dispatch(brokeredMessage.ContentType, envelope, session != null ? new Session(session, Configuration.Serializer) : null); // Cleanup the message. var messageReceiver = receiver as IMessagePump; if (messageReceiver != null && messageReceiver.Mode == ReceiveMode.PeekLock) { // Log. MessagingEventSource.Log.MessageCompleting(brokeredMessage.ContentType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId); // Complete the message. brokeredMessage.TryComplete(); return; } // Cleanup the message. var sessionMessageReceiver = receiver as ISessionMessagePump; if (sessionMessageReceiver != null && sessionMessageReceiver.Mode == ReceiveMode.PeekLock) { // Log. MessagingEventSource.Log.MessageCompleting(brokeredMessage.ContentType, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId); // Complete the message. brokeredMessage.TryComplete(); } } }
public Task OnCloseSessionAsync(MessageSession session) { throw new NotImplementedException(); }
public Task OnMessageAsync(MessageSession session, BrokeredMessage message) { throw new NotImplementedException(); }
public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message) { return new CustomMessageSessionAsyncHandler(Configuration); }
/// <summary> /// Raises an event that occurs when the session has been asynchronously closed. /// </summary> /// <returns> /// The task object representing the asynchronous operation. /// </returns> /// <param name="session">The closed session.</param> public async Task OnCloseSessionAsync(MessageSession session) { }
/// <summary> /// Receives the messages in an asynchronous loop and closes the session once there are no more messages. /// </summary> private void ReceiveMessagesAndCloseSession(MessageSession session, CancellationToken cancellationToken) { CountdownEvent unreleasedMessages = new CountdownEvent(1); Action<bool> closeSession = (bool success) => { Action doClose = () => { try { unreleasedMessages.Signal(); if (!unreleasedMessages.Wait(15000, cancellationToken)) { Trace.TraceWarning("Waited for pending unreleased messages before closing session in subscription {0} but they did not complete in time", this.subscription); } } catch (OperationCanceledException) { } finally { unreleasedMessages.Dispose(); } this.receiveRetryPolicy.ExecuteAction( cb => session.BeginClose(cb, null), session.EndClose, () => { this.instrumentation.SessionEnded(); if (success) { this.dynamicThrottling.NotifyWorkCompleted(); } else { this.dynamicThrottling.NotifyWorkCompletedWithError(); } }, ex => { this.instrumentation.SessionEnded(); Trace.TraceError("An unrecoverable error occurred while trying to close a session in subscription {1}:\r\n{0}", ex, this.subscription); this.dynamicThrottling.NotifyWorkCompletedWithError(); }); }; if (this.requiresSequentialProcessing) { doClose.Invoke(); } else { // Allow some time for releasing the messages before closing. Also, continue in a non I/O completion thread in order to block. TaskEx.Delay(200).ContinueWith(t => doClose()); } }; // Declare an action to receive the next message in the queue or closes the session if cancelled. Action receiveNext = null; // Declare an action acting as a callback whenever a non-transient exception occurs while receiving or processing messages. Action<Exception> recoverReceive = null; // Declare an action responsible for the core operations in the message receive loop. Action receiveMessage = (() => { // Use a retry policy to execute the Receive action in an asynchronous and reliable fashion. this.receiveRetryPolicy.ExecuteAction ( cb => { // Start receiving a new message asynchronously. // Does not wait for new messages to arrive in a session. If no further messages we will just close the session. session.BeginReceive(TimeSpan.Zero, cb, null); }, // Complete the asynchronous operation. This may throw an exception that will be handled internally by retry policy. session.EndReceive, msg => { // Process the message once it was successfully received // Check if we actually received any messages. if (msg != null) { var roundtripStopwatch = Stopwatch.StartNew(); long schedulingElapsedMilliseconds = 0; long processingElapsedMilliseconds = 0; unreleasedMessages.AddCount(); Task.Factory.StartNew(() => { var releaseAction = MessageReleaseAction.AbandonMessage; try { this.instrumentation.MessageReceived(); schedulingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds; // Make sure the process was told to stop receiving while it was waiting for a new message. if (!cancellationToken.IsCancellationRequested) { try { try { // Process the received message. releaseAction = this.InvokeMessageHandler(msg); processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds; this.instrumentation.MessageProcessed(releaseAction.Kind == MessageReleaseActionKind.Complete, processingElapsedMilliseconds); } catch { processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds; this.instrumentation.MessageProcessed(false, processingElapsedMilliseconds); throw; } } finally { if (roundtripStopwatch.Elapsed > TimeSpan.FromSeconds(45)) { this.dynamicThrottling.Penalize(); } } } } finally { // Ensure that any resources allocated by a BrokeredMessage instance are released. if (this.requiresSequentialProcessing) { this.ReleaseMessage(msg, releaseAction, () => { receiveNext(); }, () => { closeSession(false); }, unreleasedMessages, processingElapsedMilliseconds, schedulingElapsedMilliseconds, roundtripStopwatch); } else { // Receives next without waiting for the message to be released. this.ReleaseMessage(msg, releaseAction, () => { }, () => { this.dynamicThrottling.Penalize(); }, unreleasedMessages, processingElapsedMilliseconds, schedulingElapsedMilliseconds, roundtripStopwatch); receiveNext.Invoke(); } } }); } else { // no more messages in the session, close it and do not continue receiving closeSession(true); } }, ex => { // Invoke a custom action to indicate that we have encountered an exception and // need further decision as to whether to continue receiving messages. recoverReceive.Invoke(ex); }); }); // Initialize an action to receive the next message in the queue or closes the session if cancelled. receiveNext = () => { if (!cancellationToken.IsCancellationRequested) { // Continue receiving and processing new messages until told to stop. receiveMessage.Invoke(); } else { closeSession(true); } }; // Initialize a custom action acting as a callback whenever a non-transient exception occurs while receiving or processing messages. recoverReceive = ex => { // Just log an exception. Do not allow an unhandled exception to terminate the message receive loop abnormally. Trace.TraceError("An unrecoverable error occurred while trying to receive a new message from subscription {1}:\r\n{0}", ex, this.subscription); // Cannot continue to receive messages from this session. closeSession(false); }; // Start receiving messages asynchronously for the session. receiveNext.Invoke(); }
/// <summary> /// Handle the message. /// </summary> /// <param name="session"></param> /// <param name="brokeredMessage"></param> /// <param name="receiver"></param> /// <param name="handlerMap"></param> /// <returns></returns> private async Task OnHandleMessage(IMessageReceiver receiver, MessageSession session, BrokeredMessage brokeredMessage, MessageHandlerMap handlerMap) { MessengerEventSource.Log.MessageReceived(brokeredMessage.ContentType, receiver, brokeredMessage.MessageId, brokeredMessage.CorrelationId, brokeredMessage.SessionId); // Create new isolated scope. using (var scope = Configuration.Container.BeginScope()) { var envelope = await BuildMessage(brokeredMessage) .ConfigureAwait(false); // Dispatch the message. var dispatcher = new MessageDispatcher(scope, handlerMap); await dispatcher.Dispatch(brokeredMessage.ContentType, envelope, session != null ? new Session(session, Configuration.Serializer) : null) .ConfigureAwait(false); } }
public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message) { return new MessageSessionAsyncHandler(_context, _supervisor, _receiver, session, message); }
public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { if (message.Label != null && message.ContentType != null && message.Label.Equals("RecipeStep", StringComparison.InvariantCultureIgnoreCase) && message.ContentType.Equals("application/json", StringComparison.InvariantCultureIgnoreCase)) { var body = message.GetBody<Stream>(); dynamic recipeStep = JsonConvert.DeserializeObject(new StreamReader(body, true).ReadToEnd()); lock (Console.Out) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine( "\t\t\t\tMessage received: \n\t\t\t\t\t\tSessionId = {0}, \n\t\t\t\t\t\tMessageId = {1}, \n\t\t\t\t\t\tSequenceNumber = {2}," + "\n\t\t\t\t\t\tContent: [ step = {3}, title = {4} ]", message.SessionId, message.MessageId, message.SequenceNumber, recipeStep.step, recipeStep.title); Console.ResetColor(); } await message.CompleteAsync(); if (recipeStep.step == 5) { // end of the session! await session.CloseAsync(); } } else { await message.DeadLetterAsync("BadMessage", "Unexpected message"); } }
public Task OnCloseSessionAsync(MessageSession session) { if (session == null) { return Task.FromResult(0); } if (configuration == null) { return Task.FromResult(0); } configuration.WriteToLog(string.Format(SessionClosed, session.SessionId, SessionDictionary[session.SessionId])); return Task.FromResult(0); }
/// <summary> /// Raises an event that occurs when a message has been brokered. /// </summary> /// <returns> /// The task object representing the asynchronous operation. /// </returns> /// <param name="session">The message session.</param> /// <param name="message">The brokered message.</param> public async Task OnMessageAsync(MessageSession session, BrokeredMessage message) { var json = message.GetBody<string>(); var @event = json.FromJsonTo<ServiceBusScheduledCommand>(); @event.BrokeredMessage = message; onMessage(@event); var result = await clockTrigger.Trigger(commands => commands.Due(@event.DueTime) .Where(c => c.AggregateId == @event.AggregateId)); if (!result.FailedCommands.Any()) { if (result.SuccessfulCommands.Any()) { Debug.WriteLine("ServiceBusCommandQueueReceiver: completing on success: " + @event.AggregateId); await message.CompleteAsync(); return; } using (var db = createCommandSchedulerDbContext()) { // if the command was already applied, we can complete the message. its job is done. if (db.ScheduledCommands .Where(cmd => cmd.AppliedTime != null || cmd.FinalAttemptTime != null) .Where(cmd => cmd.SequenceNumber == @event.SequenceNumber) .Any(cmd => cmd.AggregateId == @event.AggregateId)) { Debug.WriteLine("ServiceBusCommandQueueReceiver: completing because command was previously applied: " + @event.AggregateId); await message.CompleteAsync(); } } } }
public BrokeredMessageSessionContext(MessageSession session) { _session = session; }
/// <summary> /// Creates an instance of the handler factory. /// </summary> /// <returns> /// The created instance. /// </returns> /// <param name="session">The message session.</param> /// <param name="message">The message.</param> IMessageSessionAsyncHandler IMessageSessionAsyncHandlerFactory.CreateInstance(MessageSession session, BrokeredMessage message) { return new SessionHandler( msg => messageSubject.OnNext(msg), ex => exceptionSubject.OnNext(ex), clockTrigger, createCommandSchedulerDbContext); }
public IMessageSessionAsyncHandler CreateInstance(MessageSession session, BrokeredMessage message) { return new MessageSessionAsyncHandler(_context, _supervisor, _receiver, session, _tracker, _sendEndpointProvider, _publishEndpointProvider); }