Пример #1
0
 /// <summary>
 /// Initializes a sender link.
 /// </summary>
 /// <param name="session">The session within which to create the link.</param>
 /// <param name="name">The link name.</param>
 /// <param name="attach">The attach frame to send for this link.</param>
 /// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
 public SenderLink(Session session, string name, Attach attach, OnAttached onAttached)
     : base(session, name, onAttached)
 {
     this.settleMode = attach.SndSettleMode;
     this.outgoingList = new LinkedList();
     this.SendAttach(false, this.deliveryCount, attach);
 }
Пример #2
0
        static void RunRequestClient(string address)
        {
            Connection connection = new Connection(new Address(address));
            Session session = new Session(connection);

            string replyTo = "client-reply-to";
            Attach recvAttach = new Attach()
            {
                Source = new Source() { Address = "request_processor" },
                Target = new Target() { Address = replyTo }
            };

            ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
            SenderLink sender = new SenderLink(session, "request-client-sender", "request_processor");

            Message request = new Message("hello");
            request.Properties = new Properties() { MessageId = "request1", ReplyTo = replyTo };
            sender.Send(request, null, null);
            Console.WriteLine("Sent request {0} body {1}", request.Properties, request.Body);

            Message response = receiver.Receive();
            Console.WriteLine("Received response: {0} body {1}", response.Properties, response.Body);
            receiver.Accept(response);

            receiver.Close();
            sender.Close();
            session.Close();
            connection.Close();
        }
Пример #3
0
 internal override void OnAttach(Attach attach)
 {
     var connection = (ListenerConnection)this.Connection;
     Link link = connection.Listener.Container.CreateLink(connection, this, attach);
     this.AddRemoteLink(attach.Handle, link);
     link.OnAttach(attach.Handle, attach);
 }
        protected override ILink CreateLink()
        {
            Attach attach = new Amqp.Framing.Attach()
            {
                Target        = CreateTarget(),
                Source        = CreateSource(),
                RcvSettleMode = ReceiverSettleMode.First,
                SndSettleMode = (IsBrowser) ? SenderSettleMode.Settled : SenderSettleMode.Unsettled,
            };
            string name = null;

            if (IsDurable)
            {
                name = consumerInfo.SubscriptionName;
            }
            else
            {
                string destinationAddress = (attach.Source as Source).Address ?? "";
                name = "nms:receiver:" + this.ConsumerId.ToString()
                       + ((destinationAddress.Length == 0) ? "" : (":" + destinationAddress));
            }
            IReceiverLink link = new ReceiverLink(Session.InnerSession as Amqp.Session, name, attach, OnAttachResponse);

            return(link);
        }
Пример #5
0
 /// <summary>
 /// Initializes a receiver link.
 /// </summary>
 /// <param name="session">The session within which to create the link.</param>
 /// <param name="name">The link name.</param>
 /// <param name="attach">The attach frame to send for this link.</param>
 /// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
 public ReceiverLink(Session session, string name, Attach attach, OnAttached onAttached)
     : base(session, name, onAttached)
 {
     this.totalCredit = -1;
     this.receivedMessages = new LinkedList();
     this.waiterList = new LinkedList();
     this.SendAttach(true, 0, attach);
 }
Пример #6
0
        async Task PutTokenAsync(Connection connection)
        {
            var session = new Session(connection);

            string cbsClientAddress = "cbs-client-reply-to";
            var cbsSender = new SenderLink(session, "cbs-sender", "$cbs");
            var receiverAttach = new Attach()
            {
                Source = new Source() { Address = "$cbs" },
                Target = new Target() { Address = cbsClientAddress }
            };
            var cbsReceiver = new ReceiverLink(session, "cbs-receiver", receiverAttach, null);
            var sasToken = GetSASToken(this.KeyName, this.KeyValue, string.Format("http://{0}/{1}", this.Namespace, this.Entity), TimeSpan.FromMinutes(20));
            Trace.WriteLine(TraceLevel.Information, " sas token: {0}", sasToken);

            // construct the put-token message
            var request = new Message(sasToken);
            request.Properties = new Properties();
            request.Properties.MessageId = "1";
            request.Properties.ReplyTo = cbsClientAddress;
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "put-token";
            request.ApplicationProperties["type"] = "servicebus.windows.net:sastoken";
            request.ApplicationProperties["name"] = string.Format("amqp://{0}/{1}", this.Namespace, this.Entity);
            await cbsSender.SendAsync(request);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties);

            // receive the response
            var response = await cbsReceiver.ReceiveAsync();
            if (response == null || response.Properties == null || response.ApplicationProperties == null)
            {
                throw new Exception("invalid response received");
            }

            // validate message properties and status code.
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.Properties);
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.ApplicationProperties);
            int statusCode = (int)response.ApplicationProperties["status-code"];
            if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK)
            {
                throw new Exception("put-token message was not accepted. Error code: " + statusCode);
            }

            // the sender/receiver may be kept open for refreshing tokens
            await cbsSender.CloseAsync();
            await cbsReceiver.CloseAsync();
            await session.CloseAsync();
        }
Пример #7
0
        private static Message ReceiveMessage(string queue)
        {
            var connection = new Connection(new Address("localhost", 5672, "user", "pass", "/", "AMQP"));

            var session = new Amqp.Session(connection);

            Amqp.Framing.Attach rcvAttach = new Amqp.Framing.Attach()
            {
                Source = new Amqp.Framing.Source()
                {
                    Address = "/queue/" + queue,
                    Durable = 1
                },

                Target = new Amqp.Framing.Target()
                {
                    Durable = 1
                }
            };

            var receiver = new Amqp.ReceiverLink(session, "foo-receiver", rcvAttach, null);

            Amqp.Message amqpMessage = null;

            try
            {
                amqpMessage = receiver.Receive(new TimeSpan(0, 0, 5)); // wait - timeout 5 seconds

                if (amqpMessage == null)
                {
                    // nothing received - timeout expired
                    // queue is empty !
                    Console.WriteLine("No message received, queue is empty ...");
                    return(null);
                }
                else
                {
                    receiver.Accept(amqpMessage);
                    return(amqpMessage);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #8
0
        internal override void OnAttach(uint remoteHandle, Attach attach)
        {
            if (role)
            {
                this.deliveryCount = attach.InitialDeliveryCount;
            }

            var container = ((ListenerConnection)this.Session.Connection).Listener.Container;

            Error error = null;

            try
            {
                bool done = container.AttachLink((ListenerConnection)this.Session.Connection, (ListenerSession)this.Session, this, attach);
                if (!done)
                {
                    return;
                }
            }
            catch (AmqpException amqpException)
            {
                error = amqpException.Error;
            }
            catch (Exception exception)
            {
                error = new Error() { Condition = ErrorCode.InternalError, Description = exception.Message };
            }

            this.CompleteAttach(attach, error);
        }
Пример #9
0
        /// <summary>
        /// Completes the link attach request. This should be called when the IContainer.AttachLink implementation returns false
        /// and the asynchronous processing completes. 
        /// </summary>
        /// <param name="attach">The attach to send back.</param>
        /// <param name="error">The error, if any, for the link.</param>
        public void CompleteAttach(Attach attach, Error error)
        {
            if (error != null)
            {
                this.SendAttach(!attach.Role, attach.InitialDeliveryCount, new Attach() { Target = null, Source = null });
            }
            else
            {
                if (!role)
                {
                    this.deliveryCount = attach.InitialDeliveryCount;
                }

                this.SendAttach(!attach.Role, attach.InitialDeliveryCount, new Attach() { Target = attach.Target, Source = attach.Source });
            }

            base.OnAttach(attach.Handle, attach);

            if (error != null)
            {
                this.Close(0, error);
            }
            else
            {
                if (this.credit > 0)
                {
                    this.SendFlow(this.deliveryCount, this.credit, false);
                }
            }
        }
Пример #10
0
        internal virtual void OnAttach(Attach attach)
        {
            lock (this.ThisLock)
            {
                if (attach.Handle > this.handleMax)
                {
                    throw new AmqpException(ErrorCode.NotAllowed,
                        Fx.Format(SRAmqp.AmqpHandleExceeded, this.handleMax + 1));
                }

                for (int i = 0; i < this.localLinks.Length; ++i)
                {
                    Link link = this.localLinks[i];
                    if (link != null && string.Compare(link.Name, attach.LinkName) == 0)
                    {
                        link.OnAttach(attach.Handle, attach);

                        int count = this.remoteLinks.Length;
                        if (count - 1 < attach.Handle)
                        {
                            int size = Math.Min(count * 2, (int)this.handleMax + 1);
                            Link[] expanded = new Link[size];
                            Array.Copy(this.remoteLinks, expanded, count);
                            this.remoteLinks = expanded;
                        }

                        var remoteLink = this.remoteLinks[attach.Handle];
                        if (remoteLink != null)
                        {
                            throw new AmqpException(ErrorCode.HandleInUse,
                                Fx.Format(SRAmqp.AmqpHandleInUse, attach.Handle, remoteLink.Name));
                        }

                        this.remoteLinks[attach.Handle] = link;
                        return;
                    }
                }
            }

            throw new AmqpException(ErrorCode.NotFound,
                Fx.Format(SRAmqp.LinkNotFound, attach.LinkName));
        }
Пример #11
0
            void Setup()
            {
                this.connection = new Connection(new Address(address));
                this.session = new Session(connection);

                Attach recvAttach = new Attach()
                {
                    Source = new Source() { Address = "request_processor" },
                    Target = new Target() { Address = this.replyTo }
                };

                this.receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
                this.receiver.Start(300);
                this.sender = new SenderLink(session, "request-client-sender", "request_processor");
            }
Пример #12
0
            void RunOnce(int id)
            {
                Connection connection = this.CreateConnection(new Address(this.Args.Address));
                connection.Closed += (o, e) => this.SetComplete();

                Session session = new Session(connection);

                Attach attach = new Attach()
                {
                    Source = new Source() { Address = this.Args.Node },
                    Target = new Target(),
                    SndSettleMode = this.Args.SenderMode,
                    RcvSettleMode = this.Args.ReceiverMode
                };

                ReceiverLink receiver = new ReceiverLink(session, "perf-test-receiver" + id, attach, null);
                receiver.Start(
                    this.Args.Queue,
                    (r, m) =>
                    {
                        r.Accept(m);
                        m.Dispose();
                        this.OnComplete();
                    });

                this.Wait();

                receiver.Close();
                session.Close();
                connection.Close();
            }
Пример #13
0
            void RunOnce(int id)
            {
                Connection connection = this.CreateConnection(new Address(this.Args.Address));
                connection.Closed += (o, e) => this.SetComplete();

                Session session = new Session(connection);

                Attach attach = new Attach()
                {
                    Source = new Source(),
                    Target = new Target() { Address = this.Args.Node },
                    SndSettleMode = this.Args.SenderMode,
                    RcvSettleMode = this.Args.ReceiverMode
                };

                SenderLink sender = new SenderLink(session, "perf-test-sender" + id, attach, null);

                for (int i = 1; i <= this.Args.Queue; i++)
                {
                    if (this.OnStart())
                    {
                        var message = this.CreateMessage();
                        sender.Send(message, onOutcome, Tuple.Create(this, sender));
                    }
                }

                this.Wait();

                sender.Close();
                session.Close();
                connection.Close();
            }
Пример #14
0
            public override void Run()
            {
                Connection connection = this.CreateConnection(new Address(this.Args.Address));
                Session session = new Session(connection);

                Attach attach = new Attach()
                {
                    Source = new Source(),
                    Target = new Target() { Address = this.Args.Node },
                    SndSettleMode = this.Args.SenderMode,
                    RcvSettleMode = this.Args.ReceiverMode
                };

                this.sender = new SenderLink(session, "perf-test-sender", attach, null);

                for (int i = 1; i <= this.Args.Queue; i++)
                {
                    if (this.OnStart())
                    {
                        Message message = new Message(new string('D', this.bodySize));
                        message.Properties = new Properties() { MessageId = "msg" };
                        sender.Send(message, onOutcome, this);
                    }
                }

                this.Wait();

                sender.Close();
                session.Close();
                connection.Close();
            }
Пример #15
0
        internal void SendAttach(bool role, uint initialDeliveryCount, Attach attach)
        {
            Fx.Assert(this.state == LinkState.Start, "state must be Start");
            this.state = LinkState.AttachSent;
            attach.LinkName = this.name;
            attach.Handle = this.handle;
            attach.Role = role;
            if (!role)
            {
                attach.InitialDeliveryCount = initialDeliveryCount;
            }

            this.session.SendCommand(attach);
        }
Пример #16
0
 /// <summary>
 /// Initializes a listener link object.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="attach">The received attach frame.</param>
 public ListenerLink(ListenerSession session, Attach attach)
     : base(session, attach.LinkName, null)
 {
     this.role = !attach.Role;
     this.SettleOnSend = attach.SndSettleMode == SenderSettleMode.Settled;
 }
Пример #17
0
            void RunOnce(int id)
            {
                Connection connection = this.CreateConnection(new Address(this.Args.Address));
                connection.Closed += (o, e) => this.SetComplete();
                Session session = new Session(connection);
                string clientId = "request-" + Guid.NewGuid().ToString().Substring(0, 6);
                Attach sendAttach = new Attach()
                {
                    Source = new Source(),
                    Target = new Target() { Address = this.Args.Node },
                    SndSettleMode = SenderSettleMode.Settled
                };
                Attach recvAttach = new Attach()
                {
                    Source = new Source() { Address = this.Args.Node },
                    Target = new Target() { Address = clientId },
                    SndSettleMode = SenderSettleMode.Settled
                };
                SenderLink sender = new SenderLink(session, "s-" + clientId, sendAttach, null);
                ReceiverLink receiver = new ReceiverLink(session, "r-" + clientId, recvAttach, null);
                receiver.Start(
                    50000,
                    (r, m) =>
                    {
                        r.Accept(m);
                        m.Dispose();
                        if (this.OnComplete())
                        {
                            this.SendRequest(sender, clientId);
                        }
                    });

                for (int i = 1; i <= this.Args.Queue; i++)
                {
                    if (this.OnStart())
                    {
                        this.SendRequest(sender, clientId);
                    }
                }

                this.Wait();

                connection.Close();
            }
Пример #18
0
 internal AttachContext(ListenerLink link, Attach attach)
 {
     this.Link = link;
     this.Attach = attach;
 }
Пример #19
0
 internal override void OnAttach(uint remoteHandle, Attach attach)
 {
     base.OnAttach(remoteHandle, attach);
     this.deliveryCount = attach.InitialDeliveryCount;
 }
Пример #20
0
        internal virtual void OnAttach(Attach attach)
        {
            if (attach.Handle > this.handleMax)
            {
                throw new AmqpException(ErrorCode.NotAllowed,
                    Fx.Format(SRAmqp.AmqpHandleExceeded, this.handleMax + 1));
            }

            Link link = null;
            lock (this.ThisLock)
            {
                for (int i = 0; i < this.localLinks.Length; ++i)
                {
                    Link temp = this.localLinks[i];
                    if (temp != null && string.Compare(temp.Name, attach.LinkName) == 0)
                    {
                        link = temp;
                        this.AddRemoteLink(attach.Handle, link);
                        break;
                    }
                }
            }

            if (link == null)
            {
                throw new AmqpException(ErrorCode.NotFound,
                    Fx.Format(SRAmqp.LinkNotFound, attach.LinkName));
            }

            link.OnAttach(attach.Handle, attach);
        }
Пример #21
0
        public void ContainerHostRequestProcessorTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            var processor = new TestRequestProcessor();
            this.host.RegisterRequestProcessor(name, processor);

            int count = 500;
            var connection = new Connection(Address);
            var session = new Session(connection);

            string replyTo = "client-reply-to";
            Attach recvAttach = new Attach()
            {
                Source = new Source() { Address = name },
                Target = new Target() { Address = replyTo }
            };

            var doneEvent = new ManualResetEvent(false);
            List<string> responses = new List<string>();
            ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
            receiver.Start(
                20,
                (link, message) =>
                {
                    responses.Add(message.GetBody<string>());
                    link.Accept(message);
                    if (responses.Count == count)
                    {
                        doneEvent.Set();
                    }
                });

            SenderLink sender = new SenderLink(session, "request-client-sender", name);
            for (int i = 0; i < count; i++)
            {
                Message request = new Message("Hello");
                request.Properties = new Properties() { MessageId = "request" + i, ReplyTo = replyTo };
                sender.Send(request, SendTimeout);
            }

            Assert.IsTrue(doneEvent.WaitOne(10000), "Not completed in time");

            receiver.Close();
            sender.Close();
            session.Close();
            connection.Close();

            Assert.AreEqual(count, processor.TotalCount);
            Assert.AreEqual(count, responses.Count);
            for (int i = 1; i <= count; i++)
            {
                Assert.AreEqual("OK" + i, responses[i - 1]);
            }
        }
Пример #22
0
        internal virtual void OnAttach(uint remoteHandle, Attach attach)
        {
            lock (this.ThisLock)
            {
                if (this.state == LinkState.AttachSent)
                {
                    this.state = LinkState.Attached;
                }
                else if (this.state == LinkState.DetachPipe)
                {
                    this.state = LinkState.DetachSent;
                }
                else
                {
                    throw new AmqpException(ErrorCode.IllegalState,
                        Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnAttach", this.state));
                }
            }

            if (this.onAttached != null)
            {
                this.onAttached(this, attach);
            }
        }