示例#1
0
        private static async Task <Response> SendCloudEventsInternalAsync(
            EventGridPublisherClient client,
            IEnumerable <CloudEvent> cloudEvents,
            bool async,
            CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(client, nameof(client));
            string   activityId      = null;
            string   traceState      = null;
            Activity currentActivity = Activity.Current;

            if (currentActivity != null && currentActivity.IsW3CFormat())
            {
                activityId = currentActivity.Id;
                currentActivity.TryGetTraceState(out traceState);
            }

            using var stream = new MemoryStream();
            using var writer = new Utf8JsonWriter(stream);
            writer.WriteStartArray();
            foreach (var cloudEvent in cloudEvents)
            {
                var attributes = cloudEvent.GetAttributes();
                if (activityId != null &&
                    !attributes.ContainsKey(TraceParentHeaderName) &&
                    !attributes.ContainsKey(TraceStateHeaderName))
                {
                    attributes.Add(TraceParentHeaderName, activityId);
                    if (traceState != null)
                    {
                        attributes.Add(TraceStateHeaderName, traceState);
                    }
                }

                byte[] bytes = s_eventFormatter.EncodeStructuredEvent(cloudEvent, out var _);
                using JsonDocument document = JsonDocument.Parse(bytes);
                document.RootElement.WriteTo(writer);
            }
            writer.WriteEndArray();
            writer.Flush();
            if (async)
            {
                return(await client.SendEncodedCloudEventsAsync(stream.GetBuffer().AsMemory(0, (int)stream.Position), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                return(client.SendEncodedCloudEvents(stream.GetBuffer().AsMemory(0, (int)stream.Position), cancellationToken));
            }
        }