RabbitMq Consumers do Not Consume - masstransit

public class RequestConsumer :
IConsumer<StartFlowCommand>,
IConsumer<List<StartAndNextCommand>>
{
readonly IWorkFlowHandler _flowHandler;
public RequestConsumer(IContainer container)
{
_flowHandler = container.Resolve<IWorkFlowHandler>();
}
public async Task Consume(ConsumeContext<StartAndNextCommand> context)
{
var result =await _flowHandler.WorkFlowStartNext(context.Message);
await context.RespondAsync(result);
}
public async Task Consume(ConsumeContext<List<StartAndNextCommand>> context)
{
var result = await Task.Run(() => _flowHandler.WorkFlowStartNextBatch(context.Message));
await context.RespondAsync(result);
}
Message type of StartAndNextCommand can consume,but type of List are unable to consume,why?

This is by design. We can only consume one message. You can have a new contract, like:
public interface StartAndNextBatch
{
IList<StartAndNextCommand> Commands { get; }
}
and then have a consumer for that message type
public async Task Consume(ConsumeContext<StartAndNextBatch> context)
but you also need to publish that message type
await bus.Publish<StartAndNextBatch>(
new { Commands = ... }
);

Related

Troubleshooting MassTransit request client when using RoutingSlipRequestProxy/RoutingSlipResponseProxy for handling courier activities

Can someone give a working example in ASP.NET Core (with DI) of using RequestClient with RoutingSlipRequestProxy/RoutingSlipResponseProxy? I am trying the following code but somehow my message goes into skipped queue and I never get a reply in the controller action. The code in CreateESimOrderCommandResponseConsumer never gets executed:
public class CreateESimOrderCommandConsumer : RoutingSlipRequestProxy<CreateESimOrderCommand>
{
protected override Task BuildRoutingSlip(RoutingSlipBuilder builder, ConsumeContext<CreateESimOrderCommand> request)
{
builder.AddActivity("OrderSaveToDb", QueueNames.GetActivityUri(nameof(OrderSaveToDbActivity)));
builder.AddActivity("CreatePreactiveSubscriber", QueueNames.GetActivityUri(nameof(CreatePreactiveSubscriberActivity)));
builder.AddActivity("OrderUpdateStatus", QueueNames.GetActivityUri(nameof(OrderUpdateStatusActivity)));
builder.SetVariables(new
{
ProfileId = request.Message.ESimCatalogItemProfileId,
});
return Task.CompletedTask;
}
}
public class CreateESimOrderCommandResponseConsumer : RoutingSlipResponseProxy<CreateESimOrderCommand, SubscriberCreationRequested>
{
protected override Task<SubscriberCreationRequested> CreateResponseMessage(ConsumeContext<RoutingSlipCompleted> context, CreateESimOrderCommand request)
{
SubscriberCreationRequested subscriberCreationRequestedImpl = new SubscriberCreationRequestedImpl(context.GetVariable<string>("PhoneNumber"));
return Task.FromResult(subscriberCreationRequestedImpl);
}
}
public interface SubscriberCreationRequested
{
public string PhoneNumber { get; }
}
public record SubscriberCreationRequestedImpl(string PhoneNumber): SubscriberCreationRequested;
public interface CreateESimOrderCommand
{
public int ESimCatalogItemProfileId { get; }
}
In program.cs
builder.Services.AddMassTransit(x =>
{
x.SetKebabCaseEndpointNameFormatter();
x.UsingRabbitMq((context, cfg) =>
{
cfg.AutoStart = true;
cfg.ConfigureEndpoints(context, KebabCaseEndpointNameFormatter.Instance);
cfg.Host("localhost", "/", h =>
{
h.Username("guest");
h.Password("guest");
});
});
x.AddRequestClient<CreateESimOrderCommandConsumer>();
x.AddRequestClient<CreateESimOrderCommandResponseConsumer>();
x.AddConsumersFromNamespaceContaining<CreateESimOrderCommandConsumer>();
x.AddActivitiesFromNamespaceContaining<ESimOrderSaveToDbActivity>();
});
In my asp.net core controller:
private readonly IRequestClient<CreateESimOrderCommand> requestCreateOrderRequestConsumerClient;
private readonly ILogger<ESimController> logger;
public ESimController(
IRequestClient<CreateESimOrderCommand> requestCreateOrderRequestConsumerClient,
ILogger<ESimController> logger)
{
this.logger = logger;
this.requestCreateOrderRequestConsumerClient = requestCreateOrderRequestConsumerClient;
}
[HttpPost]
public async Task<IActionResult> Generate(ESimGenerateModel eSimGenerateModel, CancellationToken cancellationToken)
{
var resp = await requestCreateOrderRequestConsumerClient.GetResponse<SubscriberCreationRequested>(new
{
ESimCatalogItemProfileId = eSimGenerateModel.ESimProfileId,
}, cancellationToken);
logger.LogInformation("Resp = {0}", resp.Message.PhoneNumber);
return RedirectToAction("Index");
}
The console logging shows that the message goes to SKIP queue:
[10:31:21.994 DBG] [] SEND rabbitmq://localhost/order-update-status_execute?bind=true 0c4f0000-2019-c2f6-cdaa-08db0a78061b MassTransit.Courier.Contracts.RoutingSlip [s:MassTransit.Messages]
[10:31:21.994 DBG] [] RECEIVE rabbitmq://localhost/create-crmpreactive-subscriber_execute 0c4f0000-2019-c2f6-cdaa-08db0a78061b MassTransit.Courier.Contracts.RoutingSlip [....].ESim.CourierActivities.CreatePreactiveSubscriberActivity(00:00:00.0552592) [s:MassTransit.Messages]
[10:31:22.137 DBG] [] SKIP rabbitmq://localhost/create-esim-order-command 0c4f0000-2019-c2f6-0750-08db0a780650 [s:MassTransit.Messages]
[10:31:22.140 DBG] [] SEND rabbitmq://localhost/create-esim-order-command 0c4f0000-2019-c2f6-0750-08db0a780650 MassTransit.Courier.Contracts.RoutingSlipCompleted [s:MassTransit.Messages]
[10:31:22.140 DBG] [] RECEIVE rabbitmq://localhost/order-update-status_execute 0c4f0000-2019-c2f6-cdaa-08db0a78061b MassTransit.Courier.Contracts.RoutingSlip [...].ESim.CourierActivities.OrderUpdateStatusActivity(00:00:00.1486087) [s:MassTransit.Messages]
For calling the request/response proxy consumer from a saga I came up with the following code:
public class ESimOrderStateMachine : MassTransitStateMachine<ESimOrderState>
{
static ESimOrderStateMachine()
{
MessageContracts.Initialize();
}
public State ESimOrderSubscriberPendingActivation { get; set; }
public Event<ESimCreateOrder> ESimOrderSubmittedEvent { get; set; }
public ESimOrderStateMachine(ILogger<ESimOrderStateMachine> logger)
{
Request(() => CreateCRMSubscriber);
InstanceState(m => m.CurrentState);
Event(() => ESimOrderSubmittedEvent);
Initially(
When(ESimOrderSubmittedEvent)
.Then(context =>
{
context.Saga.CorrelationId = context.Message.CorrelationId;
})
.Then(x => logger.LogInformation("ESim order submitted"))
.Request(CreateCRMSubscriber, context => context.Init<CreateESimOrderCommand>(new
{
ESimCatalogItemProfileId = context.Message.ESimCatalogItemProfileId,
}))
.TransitionTo(ESimOrderSubscriberPendingActivation)
);
During(ESimOrderSubscriberPendingActivation,
When(ESimOrderCancelRequestEvent)
.Finalize()
);
}
public Request<ESimOrderState, CreateESimOrderCommand, SubscriberCreationRequested> CreateCRMSubscriber { get; set; }
}
Not sure if this is the intended way to make a request using request/response proxies from saga, but when I execute the saga, I get a fault:
MassTransit.EventExecutionException: The ESimOrderSubmittedEvent<ESimCreateOrder> (Event) execution faulted
---> MassTransit.EventExecutionException: The ESimOrderSubmittedEvent<ESimCreateOrder> (Event) execution faulted
---> MassTransit.EventExecutionException: The ESimOrderSubmittedEvent<ESimCreateOrder> (Event) execution faulted
---> MassTransit.ConfigurationException: A request timeout was specified but no message scheduler was specified or available
at MassTransit.SagaStateMachine.RequestActivityImpl`3.SendRequest(BehaviorContext`1 context, SendTuple`1 sendTuple, Uri serviceAddress) in /_/src/MassTransit/SagaStateMachine/SagaStateMachine/Activities/RequestActivityImpl.cs:line 45
[...]
Both proxy consumers, the request and the response proxy, should be configured to use the same endpoint. You can use a ConsumerDefinition for each consumer and specify the same endpoint name in the constructor, or manually configure the endpoint. Both of these options are documented.

How to invoke async callbacks in IEnlistmentNotification implementation

I have scenario to pass async function as callback to my own resource manager(which implements IEnlistmentNotification interface), and need to invoke asynchronously in prepare method, but it works when invoke as synchronous way, is there any way to make it without wait or asynchronous, the wait producing the AggregatorException rather than my custom exception?
Resource Manager
public class ResourceManager : IEnlistmentNotification
{
private Func<Task>? _doWorkCallback;
public async Task EnlistAsync(Func<Task> doWorkCallback)
{
_doWorkCallback = doWorkCallback;
var transaction = Transaction.Current;
if (transaction != null)
{
await transaction.EnlistVolatileAsync(this, EnlistmentOptions.None).ConfigureAwait(false);
}
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
try
{
_doWorkCallback?.Invoke().Wait();
preparingEnlistment.Prepared();
}
catch
{
preparingEnlistment.ForceRollback();
}
}
public void Commit(Enlistment enlistment)
{
enlistment.Done();
}
public void Rollback(Enlistment enlistment)
{
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
enlistment.Done();
}
}
public static class TranscationExtensions
{
public static Task EnlistVolatileAsync(this Transaction transaction,
IEnlistmentNotification
enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
return Task.FromResult(transaction.EnlistVolatile
(enlistmentNotification,
enlistmentOptions));
}
}
Usage Code
public class Test
{
private async Task DoWork()
{
Thread.Sleep(1000);// considerer here my custom exception
await Task.CompletedTask;
}
public async Task TestMethod()
{
ResourceManager rm = new ResourceManager();
await rm.EnlistAsync(async () => await DoWork().ConfigureAwait(false)).ConfigureAwait(false);
}
}

How to pass the user context details from from bot Controller to FormDialog

Bot Info
SDK Platform: .NET
Active Channels: Direct Line
Deployment Environment: Azure Bot Service
Question
How to pass user context details from from bot Controller to FormDialog?
Code Example
public virtual async Task < HttpResponseMessage > Post([FromBody] Activity activity) {
if (activity != null && activity.GetActivityType() == ActivityTypes.Message) {
await Conversation.SendAsync(activity, () => {
return Chain.From(() => FormDialog.FromForm(RequestOrder.BuildEnquiryForm));
});
} else {
HandleSystemMessage(activity);
}
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
public static IForm < RequestOrder > BuildEnquiryForm() {
return new FormBuilder < RequestOrder > ()
.Message("Hello {***Pass current user name?????****}Welcome to request bot!")
.Field(nameof(IsTermsAgreed))
.Field(nameof(ServiceRequired))
.AddRemainingFields()
.OnCompletion(ProcessParkingPermitRequest)
.Message("Thank you, I have submitted your request.")
.Build();
}
Fei Han answer is correct but using a static variable might lead to some unexpected error since all instances are sharing the same value. A better approach would be using the state of the form.
Request Order From
In your RequestOrder class you need to add a new member variable username.
public class RequestOrder
{
public string username;
/* Rest of your member variables */
}
The .Message method allows you to access the state of the form. You can get the username from the state of the form as below:
public static IForm < RequestOrder > BuildForm()
{
return new FormBuilder < RequestOrder > ()
.Message(async (state) => {
return new PromptAttribute($"Hi {state.username}, Welcome to request bot! ");
})
.Field(nameof(IsTermsAgreed))
.Field(nameof(ServiceRequired))
.AddRemainingFields()
.OnCompletion(ProcessParkingPermitRequest)
.Message("Thank you, I have submitted your request.")
.Build();
}
Root Dialog
In your root Dialog, before calling the BuildForm you need to create a new instance of your RequestOrder class and initialize username as the current user's name. Then pass your form to the BuildForm with option FormOptions.PromptInStart.
[Serializable]
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var form = new RequestOrder()
{
username = context.Activity.From.Id
};
var requestOrderform = new FormDialog<RequestOrder>(form, RequestOrder.BuildForm, FormOptions.PromptInStart);
context.Call<RequestOrder>(requestOrderform, SampleFormSubmitted);
}
private async Task SampleFormSubmitted(IDialogContext context, IAwaitable<SampleForm> result)
{
try
{
var query = await result;
context.Done(true);
}
catch (FormCanceledException<SampleForm> e)
{
string reply;
if (e.InnerException == null)
{
reply = $"You quit. Maybe you can fill some other time.";
}
else
{
reply = $"Something went wrong. Please try again.";
}
context.Done(true);
await context.PostAsync(reply);
}
}
}
This is what you get:
In following sample code, I define a constructor of SandwichOrder class with a string type parameter, then I call FormDialog as a child dialog from root dialog (not from Messages Controller directly) and pass user name as parameter, which works for me, you can refer to it.
In RootDialog:
[Serializable]
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var username = "Fei Han";
var myform = new Microsoft.Bot.Builder.FormFlow.FormDialog<SandwichOrder>(new SandwichOrder($"{username}"), SandwichOrder.BuildForm, Microsoft.Bot.Builder.FormFlow.FormOptions.PromptInStart, null);
context.Call<SandwichOrder>(myform, FormCompleteCallback);
}
private async Task FormCompleteCallback(IDialogContext context, IAwaitable<SandwichOrder> result)
{
await context.PostAsync($"The form is completed!");
context.Done(this);
}
}
In SandwichOrder class:
namespace BotFormFlowTest
{
public enum SandwichOptions
{
BLT, BlackForestHam, BuffaloChicken, ChickenAndBaconRanchMelt, ColdCutCombo, MeatballMarinara,
OvenRoastedChicken, RoastBeef, RotisserieStyleChicken, SpicyItalian, SteakAndCheese, SweetOnionTeriyaki, Tuna,
TurkeyBreast, Veggie
};
public enum LengthOptions { SixInch, FootLong };
public enum BreadOptions { NineGrainWheat, NineGrainHoneyOat, Italian, ItalianHerbsAndCheese, Flatbread };
public enum CheeseOptions { American, MontereyCheddar, Pepperjack };
public enum ToppingOptions
{
Avocado, BananaPeppers, Cucumbers, GreenBellPeppers, Jalapenos,
Lettuce, Olives, Pickles, RedOnion, Spinach, Tomatoes
};
public enum SauceOptions
{
ChipotleSouthwest, HoneyMustard, LightMayonnaise, RegularMayonnaise,
Mustard, Oil, Pepper, Ranch, SweetOnion, Vinegar
};
[Serializable]
public class SandwichOrder
{
public static string username = "User";
public SandwichOrder(string uname)
{
username = uname;
}
public SandwichOptions? Sandwich;
public LengthOptions? Length;
public BreadOptions? Bread;
public CheeseOptions? Cheese;
public List<ToppingOptions> Toppings;
public List<SauceOptions> Sauce;
public static IForm<SandwichOrder> BuildForm()
{
return new FormBuilder<SandwichOrder>()
.Message($"Hello {username}, Welcome to the simple sandwich order bot!")
.Build();
}
};
}
Test Result:

How to call integrate simple dialog and QnA maker dialog in a single bot?

First I've to take phone no as a user input, than I need to call qnadialog till user quits. Following is my code:
public class RootDialog : IDialog<object>
{
private string phoneNo;
public async Task StartAsync(IDialogContext context)
{
context.Wait(this.MessageReceivedAsync);
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result;
await this.SendWelcomeMessageAsync(context);
}
private async Task SendWelcomeMessageAsync(IDialogContext context)
{
if (string.IsNullOrEmpty(phoneNo))
{
await context.PostAsync("Hi, I'm Anna. Let's get started.");
context.Call(new PhoneNoDialog(), this.PhoneNoDialogResumeAfter);
}
else
{
await context.Forward(new SimpleQnADialog(), ResumeAfterSimpleQnADialog, context.Activity, CancellationToken.None);
}
}
private async Task PhoneNoDialogResumeAfter(IDialogContext context, IAwaitable<string> result)
{
this.phoneNo = await result;
await context.PostAsync($"Thank you for the information. How can I help you?");
context.Wait(this.MessageReceivedAsync);
}
private async Task ResumeAfterSimpleQnADialog(IDialogContext context, IAwaitable<object> result)
{
context.Done<object>(null);
}
}
PhoneNoDialog.cs
public class PhoneNoDialog : IDialog<string>
{
private int attempts = 3;
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("Please enter your phone no");
context.Wait(this.MessageReceivedAsync);
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
if ((message.Text != null) && (message.Text.Trim().Length > 0))
{
context.Done(message.Text);
}
else
{
--attempts;
if (attempts > 0)
{
await context.PostAsync("I'm sorry, I don't understand your reply. What is your phone no?");
context.Wait(this.MessageReceivedAsync);
}
else
{
context.Fail(new TooManyAttemptsException("Message was not a string or was an empty string."));
}
}
}
}
SimpleQnADialog.cs
[QnAMaker("subkey", "kbid")]
public class SimpleQnADialog : QnAMakerDialog
{
}
Everything works fine if I create independent bot with QnAmaker but if I call the context in above mentioned way, than it doesn't work as expected. I am not sure where I'm going wrong with this. And also, many a times bot emulator gives unexpected exceptions.
You are trying to complete your RootDialog after the QnA got a reply when you implement this:
private async Task ResumeAfterSimpleQnADialog(IDialogContext context, IAwaitable<object> result)
{
context.Done<object>(null);
}
In fact, the QnAMakerDialog is completing once it has tried to answer, as you can see on its sources here.
If you want to loop on questions, you should call again the wait:
private async Task ResumeAfterSimpleQnADialog(IDialogContext context, IAwaitable<object> result)
{
context.Wait(this.MessageReceivedAsync);
}

MassTransit's ISendObserver is not observing

I have a consumer that is also publishing a response back to the bus. I can get an IReceiveObserver wired up and working on the bus, but I haven't been able to get either an ISendObserver or IPublishObserver running. I have confirmed with RabbitMQ management console that the messages are being published correctly.
class Program
{
static BusHandle _BusHandle;
static void Main(string[] args)
{
InitLogging();
InitStructureMap();
InitBus();
System.Console.WriteLine("Starting processing, ENTER to stop...");
System.Console.ReadLine();
System.Console.WriteLine("See you later, alligator!");
StopBus();
}
static void InitBus()
{
var busCtrl = ObjectFactory.Container.GetInstance<IBusControl>();
var recObserver = ObjectFactory.Container.GetInstance<IReceiveObserver>();
var sendObserver = ObjectFactory.Container.GetInstance<ISendObserver>();
busCtrl.ConnectReceiveObserver(recObserver);
busCtrl.ConnectSendObserver(sendObserver);
_BusHandle = busCtrl.Start();
}
static void StopBus()
{
_BusHandle.Stop();
}
static void InitLogging()
{
XmlConfigurator.Configure();
Log4NetLogger.Use();
}
static void InitStructureMap()
{
ObjectFactory.Initialize(x => {
x.AddRegistry<MyTestConsoleRegistry>();
x.AddRegistry<MyTestRegistry>();
});
}
}
public class MyTestConsoleRegistry : Registry
{
public MyTestConsoleRegistry()
{
var rabbitURI = ConfigurationManager.AppSettings["rabbitMQHostUri"];
var queueName = ConfigurationManager.AppSettings["massTransitQueue"];
For<IBusControl>(new SingletonLifecycle())
.Use("Configure IBusControl for MassTransit consumers with RabbitMQ transport",
ctx => Bus.Factory.CreateUsingRabbitMq(cfg => {
cfg.UseJsonSerializer();
cfg.PublisherConfirmation = true;
var host = cfg.Host(new Uri(rabbitURI), rabbitCfg => { });
cfg.ReceiveEndpoint(host, queueName, endpointCfg => {
endpointCfg.LoadFrom(ctx);
});
})
);
For<IReceiveObserver>().Use<MassTransitObserver>();
For<ISendObserver>().Use<MassTransitObserver>();
// ...snip...
}
}
public class MyTestRegistry : Registry
{
public MyTestRegistry()
{
ForConcreteType<MyTestConsumer>();
// ...snip...
}
}
public class MassTransitObserver : IReceiveObserver, ISendObserver
{
// Does nothing for now, just trying to wire it up...
public Task ConsumeFault<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType, Exception exception) where T : class
{
return Task.CompletedTask;
}
public Task PostConsume<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType) where T : class
{
return Task.CompletedTask;
}
public Task PostReceive(ReceiveContext context)
{
return Task.CompletedTask;
}
public Task PreReceive(ReceiveContext context)
{
return Task.CompletedTask;
}
public Task ReceiveFault(ReceiveContext context, Exception exception)
{
return Task.CompletedTask;
}
public Task PreSend<T>(SendContext<T> context) where T : class
{
return Task.CompletedTask;
}
public Task PostSend<T>(SendContext<T> context) where T : class
{
return Task.CompletedTask;
}
public Task SendFault<T>(SendContext<T> context, Exception exception) where T : class
{
return Task.CompletedTask;
}
}
public class MyTestConsumer : IConsumer<MyTestMessage>,
// for testing only:
IConsumer<MyTestResponse>
{
readonly IDoSomething _DoSomething;
public TestConsumer(IDoSomething doSomething)
{
_DoSomething = doSomething;
}
public Task Consume(ConsumeContext<MyTestResponse> context)
{
// For testing only...
return Task.CompletedTask;
}
public async Task Consume(ConsumeContext<MyTestMessage> context)
{
var result = await _DoSomething(context.Message.Id);
var resp = new MyTestResponseMessage(result);
await context
.Publish<MyTestResponse>(resp);
}
}
Given this code, the IReceiveObserver methods are getting called, but the ISendObserver methods are not.
I'm new to MassTransit, I expect this is probably a straightforward issue.
EDIT: A unit test using NUnit and Moq, doesn't use StructureMap. I believe this properly illustrates what I'm seeing.
[Test]
public void TestSendObserver()
{
var bus = CreateBus();
var busHandle = bus.Start();
var sendObs = new Mock<ISendObserver>();
sendObs.Setup(x => x.PreSend<TestMessage>(It.IsAny<SendContext<TestMessage>>()))
.Returns(Task.FromResult(0))
.Verifiable();
sendObs.Setup(x => x.PostSend<TestMessage>(It.IsAny<SendContext<TestMessage>>()))
.Returns(Task.FromResult(0))
.Verifiable();
using (bus.ConnectSendObserver(sendObs.Object)) {
var pubTask = bus.Publish(new TestMessage { Message = "Some test message" });
pubTask.Wait();
}
busHandle.Stop();
// Fails, neither PreSend nor PostSend have been called
sendObs.Verify(x => x.PreSend<TestMessage>(It.IsAny<SendContext<TestMessage>>()), Times.Once());
sendObs.Verify(x => x.PostSend<TestMessage>(It.IsAny<SendContext<TestMessage>>()), Times.Once());
}
IBusControl CreateBus()
{
return MassTransit.Bus.Factory.CreateUsingRabbitMq(x => {
var host = x.Host(new Uri("rabbitmq://localhost/"), h => {
h.Username("guest");
h.Password("guest");
});
});
}
public class TestMessage
{
public String Message { get; set; }
}

Resources