public void TestMethod_AdvancedLinkFlowControl() { string testName = "AdvancedLinkFlowControl"; int nMsgs = 20; Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; ++i) { Message message = new Message(); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message, null, null); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); receiver.SetCredit(2, false); Message m1 = receiver.Receive(); Message m2 = receiver.Receive(); Assert.AreEqual("msg0", m1.Properties.MessageId); Assert.AreEqual("msg1", m2.Properties.MessageId); receiver.Accept(m1); receiver.Accept(m2); ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, "q1"); receiver2.SetCredit(2, false); Message m3 = receiver2.Receive(); Message m4 = receiver2.Receive(); Assert.AreEqual("msg2", m3.Properties.MessageId); Assert.AreEqual("msg3", m4.Properties.MessageId); receiver2.Accept(m3); receiver2.Accept(m4); receiver.SetCredit(4); for (int i = 4; i < nMsgs; i++) { Message m = receiver.Receive(); Assert.AreEqual("msg" + i, m.Properties.MessageId); receiver.Accept(m); } sender.Close(); receiver.Close(); receiver2.Close(); session.Close(); connection.Close(); }
public void DuplicateLinkNameDifferentRoleTest() { string name = "DuplicateLinkNameDifferentRoleTest"; this.linkProcessor = new TestLinkProcessor(); this.host.RegisterLinkProcessor(this.linkProcessor); string linkName = "same-link-for-different-role"; var connection = new Connection(Address); var session1 = new Session(connection); var sender = new SenderLink(session1, linkName, name); sender.Send(new Message("msg1"), SendTimeout); var session2 = new Session(connection); var receiver = new ReceiverLink(session2, linkName, name); receiver.SetCredit(2, false); var message = receiver.Receive(); Assert.IsTrue(message != null, "No message was received"); receiver.Accept(message); connection.Close(); }
public async Task OnFlow_SendsMessageToReceiverLink() { var message = new Message("x") { Properties = new Properties { CorrelationId = "abc123" } }; IDeliveryQueue fakeDeliveryQueue = Substitute.For <IDeliveryQueue>(); fakeDeliveryQueue .Dequeue(Arg.Any <CancellationToken>()) .Returns(message); var endpoint = new OutgoingLinkEndpoint(fakeDeliveryQueue); ReceiverLink receiver = await TestAmqpHost.OpenAndLinkReceiverAsync(endpoint); try { receiver.SetCredit(1, CreditMode.Manual); Message receivedMessage = await receiver.ReceiveAsync(); receivedMessage.Properties.CorrelationId .ShouldBe(message.Properties.CorrelationId); } finally { await receiver.Session.Connection.CloseAsync(); } }
public void Receive(IDictionary <string, Type> eventTypeLookup) { if (Link != null) { throw new InvalidOperationException("Already receiving."); } EventTypeLookup = eventTypeLookup; Logger.LogInformation($"Registering {eventTypeLookup.Count} event types:"); foreach (var pair in eventTypeLookup) { Logger.LogInformation($"{pair.Key} = {pair.Value}"); } Error = null; var session = CreateSession(); var attach = new Attach() { Source = new Source() { Address = Settings.Address, Durable = Settings.Durable }, Target = new Target() { Address = null } }; Link = new ReceiverLink(session, Settings.AppName, attach, null); Link.Closed += OnClosed; Link.SetCredit(Settings.Credits, true); //Not sure if this is sufficient to renew credits... Link.Start(Settings.Credits, OnMessageCallback); }
// // Sample invocation: Interop.Drain.exe --broker localhost:5672 --timeout 30 --address my-queue // static int Main(string[] args) { const int ERROR_SUCCESS = 0; const int ERROR_NO_MESSAGE = 1; const int ERROR_OTHER = 2; int exitCode = ERROR_SUCCESS; Connection connection = null; try { Options options = new Options(args); Address address = new Address(options.Url); connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", options.Address); TimeSpan timeout = TimeSpan.MaxValue; if (!options.Forever) { timeout = TimeSpan.FromSeconds(options.Timeout); } Message message = new Message(); int nReceived = 0; receiver.SetCredit(options.InitialCredit); while ((message = receiver.Receive(timeout)) != null) { nReceived++; if (!options.Quiet) { Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}", message.Properties, message.ApplicationProperties, message.Body); } receiver.Accept(message); if (options.Count > 0 && nReceived == options.Count) { break; } } if (message == null) { exitCode = ERROR_NO_MESSAGE; } receiver.Close(); session.Close(); connection.Close(); } catch (Exception e) { Console.Error.WriteLine("Exception {0}.", e); if (null != connection) { connection.Close(); } exitCode = ERROR_OTHER; } return(exitCode); }
private void OnMessage(ReceiverLink receiver, Message message) { Log.DebugFormat("Message received {body}", Convert.ToBase64String((byte[])message.Body)); foreach (var observer in _observers) { observer.OnNext(message); } receiver.Accept(message); receiver.SetCredit(5); }
public void Receive(IDictionary <string, Type> eventTypeLookup) { if (Link != null) { throw new InvalidOperationException("Already receiving."); } EventTypeLookup = eventTypeLookup; var session = CreateSession(); Link = new ReceiverLink(session, Settings.AppName, Settings.Address); Link.SetCredit(Settings.Credits, true); //Not sure if this is sufficient to renew credits... Link.Start(Settings.Credits, OnMessageCallback); }
public static async Task <Message> SendControlRequestAsync(this Session session, string controller, Message request) { if (request.Properties == null) { request.Properties = new Properties(); } request.Properties.ReplyTo = "c-client-reply-to"; var cbsSender = new SenderLink(session, "c-sender", controller); var cbsReceiver = new ReceiverLink(session, "c-receiver", new Attach { Source = new Source { Address = controller }, Target = new Target { Address = "c-client-reply-to" } }, null); try { cbsReceiver.SetCredit(200, true); await cbsSender.SendAsync(request); return(await cbsReceiver.ReceiveAsync()); } finally { try { try { await cbsSender.CloseAsync(); } finally { await cbsReceiver.CloseAsync(); } } catch (AmqpException) { // ignore for closeasync } } }
public void TransactedRetiringAndPosting() { if (enabled) { string testName = "TransactedRetiringAndPosting"; path = "test." + testName; int nMsgs = 10; var ids = new List <string>(); Connection connection = new Connection(address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, path); for (int i = 0; i < nMsgs; i++) { Message message = new Message("test") { Properties = new Properties() { MessageId = "msg" + i, GroupId = testName } }; ids.Add(message.Properties.MessageId); sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, path); receiver.SetCredit(2, false); Message message1 = receiver.Receive(); Message message2 = receiver.Receive(); // ack message1 and send a new message in a txn using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { receiver.Accept(message1); ids.Remove(message1.Properties.MessageId); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + nMsgs, GroupId = testName }; ids.Add(message.Properties.MessageId); sender.Send(message); ts.Complete(); } // ack message2 and send a new message in a txn but abort the txn using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { receiver.Accept(message2); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + (nMsgs + 1), GroupId = testName }; sender.Send(message1); } // release the message, since it shouldn't have been accepted above receiver.Release(message2); // receive all messages. should see the effect of the first txn receiver.SetCredit(nMsgs, false); for (int i = 1; i <= nMsgs; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.Contains(message.Properties.MessageId, ids); ids.Remove(message.Properties.MessageId); } // at this point, the queue should have zero messages. // If there are messages, it is a bug in the broker. Assert.Empty(ids); // shouldn't be any messages left Message empty = receiver.Receive(TimeSpan.Zero); Assert.Null(empty); connection.Close(); } }
/// <summary> /// Main method for receiver (receive messages) /// </summary> /// <param name="args">array arguments from command line</param> /// <returns>return code</returns> public void Run(string[] args) { ReceiverOptions options = new ReceiverOptions(); try { this.ParseArguments(args, options); if (options.RecvListener) { this.InitListener(options); } else { //init timestamping this.ptsdata = Utils.TsInit(options.LogStats); Utils.TsSnapStore(this.ptsdata, 'B', options.LogStats); this.SetAddress(options.Url); this.CreateConnection(options); Utils.TsSnapStore(this.ptsdata, 'C', options.LogStats); this.CreateSession(); Utils.TsSnapStore(this.ptsdata, 'D', options.LogStats); ReceiverLink receiver = this.PrepareReceiverLink(options); Message message = new Message(); this.ts = Utils.GetTime(); Utils.TsSnapStore(this.ptsdata, 'E', options.LogStats); int nReceived = 0; if (options.Capacity > -1) { receiver.SetCredit(options.Capacity); } bool tx_batch_flag = String.IsNullOrEmpty(options.TxLoopendAction) ? (options.TxSize > 0) : true; //receiving of messages if (options.RecvBrowse || !String.IsNullOrEmpty(options.MsgSelector) || options.isInfinityReceiving) { this.ReceiveAll(receiver, options); } else { if (tx_batch_flag) { this.TransactionReceive(receiver, options); } else { this.Receive(receiver, options); } } if (options.CloseSleep > 0) { System.Threading.Thread.Sleep(options.CloseSleep); } //close connection and link this.CloseLink(receiver); this.CloseConnection(); Utils.TsSnapStore(this.ptsdata, 'G', options.LogStats); //report timestamping if (this.ptsdata.Count > 0) { Console.WriteLine("STATS " + Utils.TsReport(this.ptsdata, nReceived, message.Body.ToString().Length *sizeof(Char), 0)); } } this.exitCode = ReturnCode.ERROR_SUCCESS; } catch (ArgumentException ex) { this.ArgumentExceptionHandler(ex, options); } catch (Exception ex) { this.OtherExceptionHandler(ex, options); } finally { this.CloseConnection(); } Environment.Exit(exitCode); }
public void TransactedRetiringAndPosting() { string testName = "TransactedRetiringAndPosting"; int nMsgs = 10; Connection connection = new Connection(testTarget.Address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path); for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path); receiver.SetCredit(2, false); Message message1 = receiver.Receive(); Message message2 = receiver.Receive(); // ack message1 and send a new message in a txn using (var ts = new TransactionScope()) { receiver.Accept(message1); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + nMsgs, GroupId = testName }; sender.Send(message); ts.Complete(); } // ack message2 and send a new message in a txn but abort the txn using (var ts = new TransactionScope()) { receiver.Accept(message2); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + (nMsgs + 1), GroupId = testName }; sender.Send(message1); } receiver.Release(message2); // receive all messages. should see the effect of the first txn receiver.SetCredit(nMsgs, false); for (int i = 1; i <= nMsgs; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.AreEqual("msg" + i, message.Properties.MessageId); } connection.Close(); }
public void Stop() { receiverLink.SetCredit(0, CreditMode.Drain); }
public static void Main(string[] args) { Trace.TraceLevel = TraceLevel.Frame; Trace.TraceListener = (f, a) => { var t = DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a); Console.WriteLine(t); }; connection = new Connection(amqpAddress, null, new Open() { ContainerId = Guid.NewGuid().ToString(), ChannelMax = 64, MaxFrameSize = 200, }, null); connection.Closed = OnClosed; session = new Session(connection); session.Closed = OnClosed; var linkName = Guid.NewGuid().ToString(); senderLink = new SenderLink(session, linkName, new Attach() { Target = new Target() { Address = "TestQueue1", }, //RcvSettleMode = ReceiverSettleMode.Second, //SndSettleMode = SenderSettleMode.Settled, }, null); senderLink.Closed = OnClosed; for (int i = 0; i < 10; i++) { senderLink.Send(CreateMessage(), 5000); } senderLink.Close(); linkName = Guid.NewGuid().ToString(); receiverLink = new ReceiverLink(session, linkName, "TestQueue1"); receiverLink.Closed = OnClosed; receiverLink.SetCredit(1); var message = receiverLink.Receive(20000); int receiveCount = 0; while (message != null) { receiveCount++; //Console.WriteLine(message.Body.GetType()); Console.WriteLine(message.BodySection.GetType()); Console.WriteLine("Receive #{0}. Message = \"{1}\"", receiveCount.ToString(), Encoding.UTF8.GetString(message.GetBody <byte[]>())); if (receiveCount % 7 == 0) { receiverLink.Release(message); } else if (receiveCount % 4 == 0) { receiverLink.Reject(message); } else { receiverLink.Accept(message); } Thread.Sleep(10000); message = receiverLink.Receive(20000); } receiverLink.Close(); session.Close(); connection.Close(); }
public static int ResendDeadLetters(AmqpMessageHandler handler, BaseOptions opts) { var dlq = EntityNameHelper.FormatDeadLetterPath(opts.Queue); var max = opts.Max; logger.LogInformation($"Connecting to {opts.Queue} to shovel maximum of {max} messages"); if (opts.ConnectionString != null) { var managementClient = new ManagementClient(opts.ConnectionString); var queue = managementClient.GetQueueRuntimeInfoAsync(opts.Queue).GetAwaiter().GetResult(); var messageCount = queue.MessageCountDetails.DeadLetterMessageCount; logger.LogInformation($"Message queue {dlq} has {messageCount} messages"); if (messageCount < opts.Max) { max = Convert.ToInt32(messageCount); logger.LogInformation($"resetting max messages to {max}"); } } int exitCode = ERROR_SUCCESS; Connection connection = null; try { Address address = new Address(opts.Url); connection = new Connection(address); Session session = new Session(connection); ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", dlq); Amqp.Message message; int nReceived = 0; receiver.SetCredit(opts.InitialCredit); while ((message = receiver.Receive(opts.TimeSpan)) != null) { nReceived++; logger.LogInformation("Message(Properties={0}, ApplicationProperties={1}, Body={2}", message.Properties, message.ApplicationProperties, message.Body); handler.Send(message); receiver.Accept(message); if (opts.Max > 0 && nReceived == max) { logger.LogInformation("max messages received"); break; } } if (message == null) { logger.LogInformation("No message"); exitCode = ERROR_NO_MESSAGE; } receiver.Close(); session.Close(); connection.Close(); } catch (Exception e) { logger.LogError(e, "Exception {0}."); if (null != connection) { connection.Close(); } exitCode = ERROR_OTHER; } logger.LogInformation("done"); return(exitCode); }
public void ContainerHostMessageSourceTest() { string name = "ContainerHostMessageSourceTest"; int count = 100; Queue <Message> messages = new Queue <Message>(); for (int i = 0; i < count; i++) { messages.Enqueue(new Message("test") { Properties = new Properties() { MessageId = name + i } }); } var source = new TestMessageSource(messages); host.RegisterMessageSource(name, source); var connection = new Connection(Address); var session = new Session(connection); var receiver = new ReceiverLink(session, "receiver0", name); receiver.SetCredit(count, CreditMode.Manual); int released = 0; int rejected = 0; int ignored = 0; for (int i = 1; i <= count; i++) { Message message = receiver.Receive(); if (i % 5 == 0) { receiver.Reject(message); rejected++; } else if (i % 17 == 0) { receiver.Release(message); released++; } else if (i % 36 == 0) { ignored++; } else { receiver.Accept(message); } } receiver.Close(); session.Close(); connection.Close(); Thread.Sleep(500); Assert.Equal(released + ignored, source.Count); Assert.Equal(rejected, source.DeadLetterCount); }