Ejemplo n.º 1
0
 public LinkProducerMessage(byte[] body, LinkMessageProperties properties,
                            LinkPublishProperties publishProperties, CancellationToken cancellation) : base(cancellation)
 {
     Body              = body;
     Properties        = properties;
     PublishProperties = publishProperties;
 }
Ejemplo n.º 2
0
        private void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
        {
            try
            {
                var props = new LinkMessageProperties();
                props.Extend(e.BasicProperties);

                var recieveProps = new LinkRecieveProperties(e.Redelivered, e.Exchange, e.RoutingKey, _queue.Name,
                                                             props.AppId == _appId);

                var token = _consumerCancellationTokenSource.Token;

                var msg = new LinkConsumedMessage <byte[]>(e.Body, props, recieveProps, token);

                HandleMessageAsync(msg, e.DeliveryTag);
            }
            catch (Exception ex)
            {
                _logger.Error($"Recieve message error, NACKing: {ex}");

                try
                {
                    _actionQueue.Put(new LinkConsumerMessageAction(
                                         e.DeliveryTag,
                                         LinkConsumerAckStrategy.Nack,
                                         _consumerCancellationTokenSource.Token)
                                     );
                }
                catch
                {
                    // No-op
                }
            }
        }
Ejemplo n.º 3
0
        public LinkProducerBuilder
        (
            Link link,
            TimeSpan recoveryInterval,
            ILinkSerializer serializer,
            TimeSpan?publishTimeout = null,
            bool?confirmsMode       = null,
            bool?setUserId          = null,
            ILinkMessageIdGenerator messageIdGenerator              = null,
            LinkPublishProperties publishProperties                 = null,
            LinkMessageProperties messageProperties                 = null,
            ILinkProducerTopologyHandler topologyHandler            = null,
            LinkStateHandler <LinkProducerState> stateHandler       = null,
            LinkStateHandler <LinkChannelState> channelStateHandler = null,
            LinkTypeNameMapping typeNameMapping = null
        )
        {
            _link = link ?? throw new ArgumentNullException(nameof(link));

            _confirmsMode        = confirmsMode ?? false;
            _setUserId           = setUserId ?? true;
            _publishTimeout      = publishTimeout ?? Timeout.InfiniteTimeSpan;
            _recoveryInterval    = recoveryInterval;
            _messageIdGenerator  = messageIdGenerator ?? new LinkGuidMessageIdGenerator();
            _publishProperties   = publishProperties ?? new LinkPublishProperties();
            _messageProperties   = messageProperties ?? new LinkMessageProperties();
            _topologyHandler     = topologyHandler;
            _stateHandler        = stateHandler ?? ((old, @new) => { });
            _channelStateHandler = channelStateHandler ?? ((old, @new) => { });
            _serializer          = serializer;
            _typeNameMapping     = typeNameMapping ?? new LinkTypeNameMapping();
        }
        /// <summary>
        ///     Deserialize messsage and set properties
        /// </summary>
        public static object Deserialize(this ILinkSerializer @this, Type bodyType,
                                         byte[] body, LinkMessageProperties properties)
        {
            var genericMethod = DeserializeMethod.MakeGenericMethod(bodyType);

            return(genericMethod.Invoke(@this, new object[] { body, properties }));
        }
Ejemplo n.º 5
0
 private LinkProducerBuilder
 (
     LinkProducerBuilder prev,
     TimeSpan?recoveryInterval = null,
     TimeSpan?publishTimeout   = null,
     bool?confirmsMode         = null,
     bool?setUserId            = null,
     ILinkMessageIdGenerator messageIdGenerator              = null,
     LinkPublishProperties publishProperties                 = null,
     LinkMessageProperties messageProperties                 = null,
     ILinkProducerTopologyHandler topologyHandler            = null,
     LinkStateHandler <LinkProducerState> stateHandler       = null,
     LinkStateHandler <LinkChannelState> channelStateHandler = null,
     ILinkSerializer serializer          = null,
     LinkTypeNameMapping typeNameMapping = null
 ) : this
     (
         prev._link,
         recoveryInterval ?? prev._recoveryInterval,
         serializer ?? prev._serializer,
         publishTimeout ?? prev._publishTimeout,
         confirmsMode ?? prev._confirmsMode,
         setUserId ?? prev._setUserId,
         messageIdGenerator ?? prev._messageIdGenerator,
         publishProperties ?? prev._publishProperties.Clone(),
         messageProperties ?? prev._messageProperties.Clone(),
         topologyHandler ?? prev._topologyHandler,
         stateHandler ?? prev._stateHandler,
         channelStateHandler ?? prev._channelStateHandler,
         typeNameMapping ?? prev._typeNameMapping
     )
 {
 }
Ejemplo n.º 6
0
 /// <summary>
 ///     Makes instance
 /// </summary>
 /// <param name="body">Body value</param>
 /// <param name="properties">Message properties</param>
 protected LinkMessage(
     TBody body,
     LinkMessageProperties properties = null
     )
 {
     Body       = body;
     Properties = properties ?? new LinkMessageProperties();
 }
Ejemplo n.º 7
0
        public byte[] Serialize <T>(ContentType defaultContentType, T body, LinkMessageProperties props, IReadOnlyCollection <ITypeSchema> knownTypes)
        {
            var payload = _payloadManager.ToRaw(body, knownTypes, defaultContentType.ToString());

            props.ContentType = payload.ContentType;
            props.Type        = payload.TypeHint;
            return(payload.Body);
        }
Ejemplo n.º 8
0
        public ILinkProducerBuilder MessageProperties(LinkMessageProperties value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            return(new LinkProducerBuilder(this, messageProperties: value.Clone()));
        }
Ejemplo n.º 9
0
        public void ContentEncodingProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.ContentEncoding);

            props.ContentEncoding = "test";

            Assert.Equal(props.ContentEncoding, "test");
        }
Ejemplo n.º 10
0
        public void ClusterIdProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.ClusterId);

            props.ClusterId = "test";

            Assert.Equal(props.ClusterId, "test");
        }
Ejemplo n.º 11
0
        public void TypeProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.Type);

            props.Type = "test";

            Assert.Equal("test", props.Type);
        }
Ejemplo n.º 12
0
        public void TimeStampProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.TimeStamp);

            props.TimeStamp = new DateTime(2015, 01, 01).ToUnixTime();

            Assert.Equal(new DateTime(2015, 01, 01), props.TimeStamp.Value.FromUnixTime());
        }
Ejemplo n.º 13
0
        public void ReplyToProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.ReplyTo);

            props.ReplyTo = "test";

            Assert.Equal("test", props.ReplyTo);
        }
Ejemplo n.º 14
0
        public void PriorityProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.Priority);

            props.Priority = 5;

            Assert.Equal((byte)5, props.Priority);
        }
Ejemplo n.º 15
0
        public void MessageIdProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.MessageId);

            props.MessageId = "test";

            Assert.Equal("test", props.MessageId);
        }
Ejemplo n.º 16
0
        public void ExpirationProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.Expiration);

            props.Expiration = TimeSpan.FromSeconds(1);

            Assert.Equal(TimeSpan.FromSeconds(1), props.Expiration);
        }
Ejemplo n.º 17
0
        public void ContentTypeProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.ContentType);

            props.ContentType = "test";

            Assert.Equal(props.ContentType, "test");
        }
Ejemplo n.º 18
0
 /// <summary>
 ///     Creates new instance
 /// </summary>
 /// <param name="body">Body value</param>
 /// <param name="properties">Message properties</param>
 /// <param name="publishProperties">Publish properties</param>
 public LinkPublishMessage(
     TBody body,
     LinkMessageProperties properties        = null,
     LinkPublishProperties publishProperties = null
     ) : base(
         body,
         properties
         )
 {
     PublishProperties = publishProperties ?? new LinkPublishProperties();
 }
Ejemplo n.º 19
0
        public void HeadersProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Empty(props.Headers);

            props.Headers.Add("test", 1);

            Assert.Equal(props.Headers["test"], 1);
            Assert.NotEmpty(props.Headers);
        }
Ejemplo n.º 20
0
        public static ILinkPulledMessage <object> ConstructPulledMessage(
            Type bodyType,
            LinkPulledMessage <byte[]> message,
            object body,
            LinkMessageProperties properties
            )
        {
            var genericType = LinkPulledMessageType.MakeGenericType(bodyType);

            return((ILinkPulledMessage <object>)Activator
                   .CreateInstance(genericType, message, body, properties));
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Creates intance
 /// </summary>
 /// <param name="body">Body value</param>
 /// <param name="properties">Message properties</param>
 /// <param name="recieveProperties">Recieve properties</param>
 /// <param name="cancellation">Message cancellation</param>
 public LinkConsumedMessage(
     TBody body,
     LinkMessageProperties properties,
     LinkRecieveProperties recieveProperties,
     CancellationToken cancellation
     ) : base(
         body,
         properties
         )
 {
     RecieveProperties = recieveProperties ?? throw new ArgumentNullException(nameof(recieveProperties));
     Cancellation      = cancellation;
 }
Ejemplo n.º 22
0
        public void SetMessageId()
        {
            var gen = new LinkGuidMessageIdGenerator();

            var body     = new byte[1];
            var props    = new LinkMessageProperties();
            var pubProps = new LinkPublishProperties();

            gen.SetMessageId(body, props, pubProps);

            Assert.NotNull(props.MessageId);
            Assert.True(Guid.TryParse(props.MessageId, out var _));
        }
Ejemplo n.º 23
0
        public void CorrelationIdProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.CorrelationId);

            props.CorrelationId = "test";

            Assert.Equal(props.CorrelationId, "test");

            props.CorrelationId = null;
            Assert.Null(props.CorrelationId);
        }
Ejemplo n.º 24
0
        public static ILinkConsumedMessage <object> ConstructConsumedMessage(
            Type bodyType,
            object body,
            LinkMessageProperties properties,
            LinkReceiveProperties receivedProperties,
            CancellationToken cancellation
            )
        {
            var genericType = LinkConsumedMessageType.MakeGenericType(bodyType);

            return((ILinkConsumedMessage <object>)Activator
                   .CreateInstance(genericType, body, properties, receivedProperties, cancellation));
        }
        public void ContentEncodingProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Null(props.ContentEncoding);

            props.ContentEncoding = "test";

            Assert.Equal("test", props.ContentEncoding);

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                props.ContentEncoding = new string('a', 257);
            });
        }
Ejemplo n.º 26
0
        /// <inheritdoc />
        public TBody Deserialize <TBody>(byte[] body, LinkMessageProperties properties) where TBody : class
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (body == null)
            {
                return(null);
            }

            var stringBody = Encoding.UTF8.GetString(body);

            return(JsonConvert.DeserializeObject <TBody>(stringBody, _settings));
        }
Ejemplo n.º 27
0
 public LinkPulledMessage(
     LinkPulledMessage <byte[]> message,
     TBody body,
     LinkMessageProperties properties
     ) : base(
         body,
         properties,
         message.ReceiveProperties,
         message.Cancellation
         )
 {
     Ack       = message.Ack;
     Nack      = message.Nack;
     Requeue   = message.Requeue;
     Exception = message.Exception;
 }
Ejemplo n.º 28
0
        /// <inheritdoc />
        public byte[] Serialize <TBody>(TBody body, LinkMessageProperties properties) where TBody : class
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            properties.ContentType     = "application/json";
            properties.ContentEncoding = Encoding.UTF8.WebName;

            if (body == null)
            {
                return(null);
            }

            var stringBody = JsonConvert.SerializeObject(body, _settings);

            return(Encoding.UTF8.GetBytes(stringBody));
        }
Ejemplo n.º 29
0
        public async Task PublishAsync(Response <TResponse> message, CancellationToken token = default(CancellationToken))
        {
            var log = Log.With("@message", message);

            log.Trace($"{nameof(PublishAsync)} enter");
            try
            {
                var publisher = Utils.CreateProducer(Link, Schema.ResponseExchange, Schema.ContentType,
                                                     false, ConfirmsMode());
                var props = new LinkMessageProperties
                {
                    CorrelationId = message.CorrelationId
                };
                var serializer = Link.PayloadManager;
                var answer     = new LinkPublishMessage <byte[]>(message.IsFail
                        ? serializer.Serialize(Schema.ContentType, new RpcFail
                {
                    Kind    = message.Error.GetType().FullName,
                    Message = message.Error.Message
                }, props, Schema.Service.Types)
                        : serializer.Serialize(Schema.ContentType, message.Result, props, Schema.Service.Types),
                                                                 props,
                                                                 new LinkPublishProperties
                {
                    RoutingKey = message.ReplyTo
                });
                await publisher.PublishAsync(answer, token);

                log.Trace($"{nameof(PublishAsync)} success");
            }
            catch (Exception ex)
            {
                if (ex.IsCancellation())
                {
                    log.Info($"{nameof(PublishAsync)} cancelled");
                }
                else
                {
                    log.Error($"{nameof(PublishAsync)} error", ex);
                }
                throw;
            }
        }
Ejemplo n.º 30
0
        public void DeliveryModeProperty()
        {
            var props = new LinkMessageProperties();

            Assert.Equal(LinkDeliveryMode.Default, props.DeliveryMode);

            props = new LinkMessageProperties
            {
                DeliveryMode = LinkDeliveryMode.Persistent
            };

            Assert.Equal(LinkDeliveryMode.Persistent, props.DeliveryMode);

            props = new LinkMessageProperties
            {
                DeliveryMode = LinkDeliveryMode.Transient
            };

            Assert.Equal(LinkDeliveryMode.Transient, props.DeliveryMode);
        }