Пример #1
0
        /// <summary>
        /// Converts a CloudEvent to <see cref="HttpContent"/>.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        public static HttpContent ToHttpContent(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            ReadOnlyMemory <byte> content;
            // The content type to include in the ContentType header - may be the data content type, or the formatter's content type.
            ContentType?contentType;

            switch (contentMode)
            {
            case ContentMode.Structured:
                content = formatter.EncodeStructuredModeMessage(cloudEvent, out contentType);
                break;

            case ContentMode.Binary:
                content     = formatter.EncodeBinaryModeEventData(cloudEvent);
                contentType = MimeUtilities.CreateContentTypeOrNull(formatter.GetOrInferDataContentType(cloudEvent));
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            ByteArrayContent ret = ToByteArrayContent(content);

            if (contentType is object)
            {
                ret.Headers.ContentType = MimeUtilities.ToMediaTypeHeaderValue(contentType);
            }
            else if (content.Length != 0)
            {
                throw new ArgumentException(Strings.ErrorContentTypeUnspecified, nameof(cloudEvent));
            }

            // Map headers in either mode.
            // Including the headers in structured mode is optional in the spec (as they're already within the body) but
            // can be useful.
            ret.Headers.Add(HttpUtilities.SpecVersionHttpHeader, HttpUtilities.EncodeHeaderValue(cloudEvent.SpecVersion.VersionId));
            foreach (var attributeAndValue in cloudEvent.GetPopulatedAttributes())
            {
                CloudEventAttribute attribute = attributeAndValue.Key;
                string headerName             = HttpUtilities.HttpHeaderPrefix + attribute.Name;
                object value = attributeAndValue.Value;

                // Skip the data content type attribute in binary mode, because it's already in the content type header.
                if (attribute == cloudEvent.SpecVersion.DataContentTypeAttribute && contentMode == ContentMode.Binary)
                {
                    continue;
                }
                else
                {
                    string headerValue = HttpUtilities.EncodeHeaderValue(attribute.Format(value));
                    ret.Headers.Add(headerName, headerValue);
                }
            }
            return(ret);
        }
Пример #2
0
        /// <summary>
        /// Copies a <see cref="CloudEvent"/> into an <see cref="HttpResponse" />.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to copy. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="destination">The response to copy the CloudEvent to. Must not be null.</param>
        /// <param name="contentMode">Content mode (structured or binary)</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        /// <returns>A task representing the asynchronous operation.</returns>
        public static async Task CopyToHttpResponseAsync(this CloudEvent cloudEvent, HttpResponse destination,
                                                         ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(destination, nameof(destination));
            Validation.CheckNotNull(formatter, nameof(formatter));

            ReadOnlyMemory <byte> content;
            ContentType?          contentType;

            switch (contentMode)
            {
            case ContentMode.Structured:
                content = formatter.EncodeStructuredModeMessage(cloudEvent, out contentType);
                break;

            case ContentMode.Binary:
                content     = formatter.EncodeBinaryModeEventData(cloudEvent);
                contentType = MimeUtilities.CreateContentTypeOrNull(formatter.GetOrInferDataContentType(cloudEvent));
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            if (contentType is object)
            {
                destination.ContentType = contentType.ToString();
            }
            else if (content.Length != 0)
            {
                throw new ArgumentException("The 'datacontenttype' attribute value must be specified", nameof(cloudEvent));
            }

            // Map headers in either mode.
            // Including the headers in structured mode is optional in the spec (as they're already within the body) but
            // can be useful.
            destination.Headers.Add(HttpUtilities.SpecVersionHttpHeader, HttpUtilities.EncodeHeaderValue(cloudEvent.SpecVersion.VersionId));
            foreach (var attributeAndValue in cloudEvent.GetPopulatedAttributes())
            {
                var attribute = attributeAndValue.Key;
                var value     = attributeAndValue.Value;
                // The content type is already handled based on the content mode.
                if (attribute != cloudEvent.SpecVersion.DataContentTypeAttribute)
                {
                    string headerValue = HttpUtilities.EncodeHeaderValue(attribute.Format(value));
                    destination.Headers.Add(HttpUtilities.HttpHeaderPrefix + attribute.Name, headerValue);
                }
            }

            destination.ContentLength = content.Length;
            await BinaryDataUtilities.CopyToStreamAsync(content, destination.Body).ConfigureAwait(false);
        }
Пример #3
0
        /// <summary>
        /// Converts a CloudEvent to <see cref="Message"/>.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        public static Message ToAmqpMessage(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            var applicationProperties = MapHeaders(cloudEvent);
            RestrictedDescribed bodySection;
            Properties          properties;

            switch (contentMode)
            {
            case ContentMode.Structured:
                bodySection = new Data
                {
                    Binary = BinaryDataUtilities.AsArray(formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType))
                };
                // TODO: What about the other parts of the content type?
                properties = new Properties {
                    ContentType = contentType.MediaType
                };
                break;

            case ContentMode.Binary:
                bodySection = new Data {
                    Binary = BinaryDataUtilities.AsArray(formatter.EncodeBinaryModeEventData(cloudEvent))
                };
                properties = new Properties {
                    ContentType = formatter.GetOrInferDataContentType(cloudEvent)
                };
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            return(new Message
            {
                ApplicationProperties = applicationProperties,
                BodySection = bodySection,
                Properties = properties
            });
        }
Пример #4
0
        /// <summary>
        /// Converts a CloudEvent to a Kafka message.
        /// </summary>
        /// <param name="cloudEvent">The CloudEvent to convert. Must not be null, and must be a valid CloudEvent.</param>
        /// <param name="contentMode">Content mode. Structured or binary.</param>
        /// <param name="formatter">The formatter to use within the conversion. Must not be null.</param>
        public static Message <string?, byte[]> ToKafkaMessage(this CloudEvent cloudEvent, ContentMode contentMode, CloudEventFormatter formatter)
        {
            Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
            Validation.CheckNotNull(formatter, nameof(formatter));

            // TODO: Is this appropriate? Why can't we transport a CloudEvent without data in Kafka?
            Validation.CheckArgument(cloudEvent.Data is object, nameof(cloudEvent), "Only CloudEvents with data can be converted to Kafka messages");
            var    headers = MapHeaders(cloudEvent);
            string?key     = (string?)cloudEvent[Partitioning.PartitionKeyAttribute];

            byte[] value;
            string?contentTypeHeaderValue;

            switch (contentMode)
            {
            case ContentMode.Structured:
                value = BinaryDataUtilities.AsArray(formatter.EncodeStructuredModeMessage(cloudEvent, out var contentType));
                // TODO: What about the non-media type parts?
                contentTypeHeaderValue = contentType.MediaType;
                break;

            case ContentMode.Binary:
                value = BinaryDataUtilities.AsArray(formatter.EncodeBinaryModeEventData(cloudEvent));
                contentTypeHeaderValue = formatter.GetOrInferDataContentType(cloudEvent);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(contentMode), $"Unsupported content mode: {contentMode}");
            }
            if (contentTypeHeaderValue is object)
            {
                headers.Add(KafkaContentTypeAttributeName, Encoding.UTF8.GetBytes(contentTypeHeaderValue));
            }
            return(new Message <string?, byte[]>
            {
                Headers = headers,
                Value = value,
                Key = key
            });
        }