-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathAzureFunctionsCommon.cs
More file actions
641 lines (557 loc) · 31.2 KB
/
Copy pathAzureFunctionsCommon.cs
File metadata and controls
641 lines (557 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// <copyright file="AzureFunctionsCommon.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#if !NETFRAMEWORK
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Datadog.Trace.ClrProfiler.AutoInstrumentation.Azure.Shared;
using Datadog.Trace.ClrProfiler.AutoInstrumentation.Proxy;
using Datadog.Trace.ClrProfiler.CallTarget;
using Datadog.Trace.Configuration;
using Datadog.Trace.DuckTyping;
using Datadog.Trace.ExtensionMethods;
using Datadog.Trace.Logging;
using Datadog.Trace.PlatformHelpers;
using Datadog.Trace.Propagators;
using Datadog.Trace.Tagging;
using Datadog.Trace.Util;
using Datadog.Trace.Util.Json;
using Datadog.Trace.Vendors.Newtonsoft.Json;
using Datadog.Trace.Vendors.Serilog.Events;
#nullable enable
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Azure.Functions
{
internal static class AzureFunctionsCommon
{
// Key used by the Azure Functions .NET Worker to store the ASP.NET Core HttpContext in FunctionContext.Items.
// Defined in Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore:
// https://github.com/Azure/azure-functions-dotnet-worker/blob/596a94ef97f458d68381678fec6d92585e80d83d/extensions/Worker.Extensions.Http.AspNetCore/src/Constants.cs#L14
// Set by FunctionsHttpProxyingMiddleware:
// https://github.com/Azure/azure-functions-dotnet-worker/blob/596a94ef97f458d68381678fec6d92585e80d83d/extensions/Worker.Extensions.Http.AspNetCore/src/FunctionsMiddleware/FunctionsHttpProxyingMiddleware.cs#L124
private const string HttpRequestContextKey = "HttpRequestContext";
private const string SpanType = SpanTypes.Serverless;
public const string IntegrationName = nameof(Configuration.IntegrationId.AzureFunctions);
public const string OperationName = AzureFunctionsConstants.AzureFunctionName;
public const string AzureApim = AzureFunctionsConstants.AzureApimName;
public const IntegrationId IntegrationId = Configuration.IntegrationId.AzureFunctions;
private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(AzureFunctionsCommon));
public static CallTargetState OnFunctionExecutionBegin<TTarget, TFunction>(TTarget instance, TFunction instanceParam)
where TFunction : IFunctionInstance
{
var tracer = Tracer.Instance;
if (!tracer.CurrentTraceSettings.Settings.IsIntegrationEnabled(IntegrationId))
{
return CallTargetState.GetDefault();
}
if (tracer.Settings.AzureAppServiceMetadata is { IsIsolatedFunctionsApp: true }
&& tracer.InternalActiveScope is null)
{
// in a "timer" trigger, or similar. Context won't be propagated to child, so no
// need to create the scope etc.
return CallTargetState.GetDefault();
}
var scope = CreateScope(tracer, instanceParam);
return new CallTargetState(scope);
}
private static Scope? CreateScope<TFunction>(Tracer tracer, TFunction instanceParam)
where TFunction : IFunctionInstance
{
Scope? scope = null;
try
{
var triggerType = "Unknown";
var bindingSourceType = instanceParam.BindingSource.GetType();
var bindingSourceFullName = bindingSourceType.FullName ?? string.Empty;
switch (instanceParam.Reason)
{
case AzureFunctionsExecutionReason.HostCall:
// The root span will be the AspNetCoreDiagnosticObserver
// This could be HttpTrigger or EventGridTrigger
// Default HttpTrigger binding source: Microsoft.Azure.WebJobs.Host.Executors.BindingSource
triggerType = "Http";
if (bindingSourceFullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
// ex: Microsoft.Azure.WebJobs.Host.Triggers.TriggerBindingSource`1[[Newtonsoft.Json.Linq.JObject, Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed]]
triggerType = "EventGrid";
}
break;
case AzureFunctionsExecutionReason.AutomaticTrigger:
// This can apply to anything not triggered by HTTP or manually from the dashboard
// e.g., timer, queues ...
// Automatic is the catch all for any triggers we don't explicitly handle
triggerType = "Automatic";
if (bindingSourceFullName.Contains("Timer"))
{
// ex: Microsoft.Azure.WebJobs.Host.Triggers.TriggerBindingSource`1[[Microsoft.Azure.WebJobs.TimerInfo, Microsoft.Azure.WebJobs.Extensions, Version=4.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]
triggerType = "Timer";
}
else if (bindingSourceFullName.Contains("ServiceBus"))
{
// ex: Microsoft.Azure.WebJobs.Host.Triggers.TriggerBindingSource`1[[Microsoft.Azure.WebJobs.ServiceBus.ServiceBusTriggerInput, Microsoft.Azure.WebJobs.ServiceBus, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]
triggerType = "ServiceBus";
}
else if (bindingSourceFullName.Contains("Blob"))
{
// ex: Microsoft.Azure.WebJobs.Host.Triggers.TriggerBindingSource`1[[Microsoft.Azure.Storage.Blob.ICloudBlob, Microsoft.Azure.Storage.Blob, Version=11.1.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]
triggerType = "Blob";
}
else if (bindingSourceFullName.Contains("Microsoft.Azure.DocumentDB.Core"))
{
// ex: Microsoft.Azure.WebJobs.Host.Triggers.TriggerBindingSource`1[[System.Collections.Generic.IReadOnlyList`1[[Microsoft.Azure.Documents.Document, Microsoft.Azure.DocumentDB.Core, Version=2.13.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
triggerType = "Cosmos";
}
break;
case AzureFunctionsExecutionReason.Dashboard:
triggerType = "Dashboard";
break;
}
var functionName = instanceParam.FunctionDescriptor.ShortName;
// Check if there's an inferred proxy span (e.g., azure.apim) that we shouldn't overwrite
var isProxySpan = tracer.InternalActiveScope?.Root.Span.OperationName == AzureApim;
// Ignoring null because guaranteed running in AAS
if (tracer.Settings.AzureAppServiceMetadata is { IsIsolatedFunctionsApp: true }
&& tracer.InternalActiveScope is { } activeScope)
{
// We don't want to create a new scope here when running isolated functions,
// otherwise it is essentially a duplicate of the span created inside the
// isolated app. We _do_ want to populate the "root" span here with the appropriate names
// and update it to be a "serverless" span.
if (!isProxySpan)
{
var rootSpan = activeScope.Root.Span;
// The shortname is prefixed with "Functions.", so strip that off
var remoteFunctionName = functionName?.StartsWith("Functions.") == true
? functionName.Substring(10)
: functionName;
AzureFunctionsTags.SetRootSpanTags(
rootSpan.Tags,
shortName: remoteFunctionName,
fullName: rootSpan.Tags is AzureFunctionsTags t ? t.FullName : null, // can't get anything meaningful here, so leave it as-is
bindingSource: bindingSourceType.FullName,
triggerType: triggerType);
rootSpan.Type = SpanType;
}
return null;
}
if (tracer.InternalActiveScope == null)
{
var tags = new AzureFunctionsTags
{
TriggerType = triggerType,
ShortName = functionName,
FullName = instanceParam.FunctionDescriptor.FullName,
BindingSource = bindingSourceType.FullName
};
// This is the root scope
tags.SetAnalyticsSampleRate(IntegrationId, tracer.CurrentTraceSettings.Settings, enabledWithGlobalSetting: false);
scope = tracer.StartActiveInternal(OperationName, tags: tags);
}
else
{
scope = tracer.StartActiveInternal(OperationName);
if (!isProxySpan)
{
AzureFunctionsTags.SetRootSpanTags(
scope.Root.Span.Tags,
shortName: functionName,
fullName: instanceParam.FunctionDescriptor.FullName,
bindingSource: bindingSourceType.FullName,
triggerType: triggerType);
}
}
if (!isProxySpan)
{
scope.Root.Span.Type = SpanType;
}
scope.Span.ResourceName = $"{triggerType} {functionName}";
scope.Span.Type = SpanType;
tracer.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);
}
catch (Exception ex)
{
Log.Error(ex, "Error creating or populating scope.");
}
// always returns the scope, even if it's null because we couldn't create it,
// or we couldn't populate it completely (some tags is better than no tags)
return scope;
}
public static CallTargetState OnIsolatedFunctionBegin<T>(T functionContext)
where T : IFunctionContext
{
var tracer = Tracer.Instance;
if (!tracer.CurrentTraceSettings.Settings.IsIntegrationEnabled(IntegrationId))
{
return CallTargetState.GetDefault();
}
// Look up the aspnet_core.request scope once so we can both use it as parent
// (in CreateIsolatedFunctionScope) and propagate exceptions onto it later
// (in OnAsyncMethodEnd of the calling integration).
var aspNetCoreScope = GetAspNetCoreScope(functionContext);
var scope = CreateIsolatedFunctionScope(tracer, functionContext, aspNetCoreScope);
if (scope == null && aspNetCoreScope == null)
{
return CallTargetState.GetDefault();
}
return new CallTargetState(scope, state: aspNetCoreScope);
}
private static Scope? CreateIsolatedFunctionScope<T>(Tracer tracer, T functionContext, Scope? aspNetCoreScope)
where T : IFunctionContext
{
Scope? scope = null;
try
{
// Try to work out which trigger type it is
var triggerType = "Unknown";
PropagationContext extractedContext = default;
#pragma warning disable CS8605 // Unboxing a possibly null value. This is a lie, that only affects .NET Core 3.1
foreach (DictionaryEntry entry in functionContext.FunctionDefinition.InputBindings)
#pragma warning restore CS8605 // Unboxing a possibly null value.
{
var binding = entry.Value.DuckCast<BindingMetadata>();
if (binding.Direction != BindingDirection.In || binding.BindingType is null)
{
continue;
}
var type = binding.BindingType;
triggerType = type switch
{
_ when type.Equals("httpTrigger", StringComparison.OrdinalIgnoreCase) => "Http", // Microsoft.Azure.Functions.Worker.Extensions.Http
_ when type.Equals("timerTrigger", StringComparison.OrdinalIgnoreCase) => "Timer", // Microsoft.Azure.Functions.Worker.Extensions.Timer
_ when type.Equals("serviceBusTrigger", StringComparison.OrdinalIgnoreCase) => "ServiceBus", // Microsoft.Azure.Functions.Worker.Extensions.ServiceBus
_ when type.Equals("queue", StringComparison.OrdinalIgnoreCase) => "Queue", // Microsoft.Azure.Functions.Worker.Extensions.Queues
_ when type.StartsWith("blob", StringComparison.OrdinalIgnoreCase) => "Blob", // Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs
_ when type.StartsWith("eventHub", StringComparison.OrdinalIgnoreCase) => "EventHub", // Microsoft.Azure.Functions.Worker.Extensions.EventHubs
_ when type.StartsWith("cosmosDb", StringComparison.OrdinalIgnoreCase) => "Cosmos", // Microsoft.Azure.Functions.Worker.Extensions.CosmosDB
_ when type.StartsWith("eventGrid", StringComparison.OrdinalIgnoreCase) => "EventGrid", // Microsoft.Azure.Functions.Worker.Extensions.EventGrid.CosmosDB
_ => "Automatic", // Automatic is the catch all for any triggers we don't explicitly handle
};
switch (triggerType)
{
case "Http":
{
// Detect ASP.NET Core integration by checking for HttpContext in FunctionContext.Items.
// In ASP.NET Core mode, HTTP requests are proxied directly (not via gRPC).
// The headers in the gRPC message are STALE (contain host's root span context).
// The key "HttpRequestContext" is set by FunctionsHttpProxyingMiddleware in the worker.
// Only skip gRPC extraction when we successfully retrieved the ASP.NET Core scope bridge,
// otherwise fall back to the (stale) gRPC headers to at least keep the spans in the same trace.
var isAspNetCoreIntegration = functionContext.Items?.ContainsKey(HttpRequestContextKey) == true;
if (isAspNetCoreIntegration && aspNetCoreScope is not null)
{
// Skip gRPC header extraction in HTTP proxying mode. We already have the
// ASP.NET Core scope from the HttpContext.Items bridge and will use it as
// the parent below.
Log.Debug("Skipping header extraction - HTTP trigger with ASP.NET Core integration detected (HTTP proxying mode)");
}
else
{
// Fall back to gRPC message extraction when not using ASP.NET Core integration,
// or when proxying is detected but the ASP.NET Core scope bridge is unavailable.
extractedContext = ExtractPropagatedContextFromHttp(functionContext, entry.Key as string).MergeBaggageInto(Baggage.Current);
if (isAspNetCoreIntegration)
{
// ASP.NET Core integration detected but the scope bridge was not available
// (GetAspNetCoreScope returned null). Fall back to gRPC headers: the parent
// will be the host's root span (wrong, but keeps the spans in the same trace).
Log.Debug("HTTP trigger detected ASP.NET Core integration, but no active scope was found. Falling back to gRPC header extraction for trace correlation.");
}
else
{
Log.Debug("Extracted trace context from gRPC message (non-ASP.NET Core mode)");
}
}
break;
}
case "ServiceBus" when tracer.CurrentTraceSettings.Settings.IsIntegrationEnabled(IntegrationId.AzureServiceBus):
extractedContext = ExtractPropagatedContextFromMessaging(functionContext, "UserProperties", "UserPropertiesArray").MergeBaggageInto(Baggage.Current);
break;
case "EventHub" when tracer.CurrentTraceSettings.Settings.IsIntegrationEnabled(IntegrationId.AzureEventHubs):
extractedContext = ExtractPropagatedContextFromMessaging(functionContext, "Properties", "PropertiesArray").MergeBaggageInto(Baggage.Current);
break;
}
break;
}
var tags = new AzureFunctionsTags
{
TriggerType = triggerType,
ShortName = functionContext.FunctionDefinition.Name,
FullName = functionContext.FunctionDefinition.EntryPoint,
};
// Use the supplied aspnet_core.request scope (from HttpContext.Items bridge)
// if available, otherwise fall back to the existing local active scope.
var activeScope = tracer.InternalActiveScope;
// Check if the ASP.NET Core scope is already active
if (aspNetCoreScope != null && activeScope == aspNetCoreScope)
{
// The ASP.NET Core span is already active - don't create a new span,
// just update the existing root span's tags to make it a "serverless" span.
// Don't assign to `scope`: the ASP.NET Core middleware owns this scope's
// lifetime, and returning it here would cause OnAsyncMethodEnd to dispose it.
var rootSpan = activeScope.Root.Span;
AzureFunctionsTags.SetRootSpanTags(
rootSpan.Tags,
shortName: tags.ShortName,
fullName: tags.FullName,
bindingSource: rootSpan.Tags is AzureFunctionsTags t ? t.BindingSource : null,
triggerType: tags.TriggerType);
rootSpan.Type = SpanType; // "serverless"
rootSpan.ResourceName = $"{tags.TriggerType} {tags.ShortName}";
}
else
{
// Create a new span with the appropriate parent context from:
// 1. Extracted from propagation headers (gRPC message from the host process).
// 2. ASP.NET Core scope (if available but not active - shouldn't happen).
// 3. Existing local span (fallback).
var parentSpanContext = extractedContext.SpanContext ??
aspNetCoreScope?.Span.Context ??
activeScope?.Span.Context;
scope = tracer.StartActiveInternal(OperationName, parent: parentSpanContext, tags: tags);
var span = scope.Span;
var rootSpan = scope.Root.Span;
if (span == rootSpan)
{
// this is the local root span
tags.SetAnalyticsSampleRate(IntegrationId, tracer.CurrentTraceSettings.Settings, enabledWithGlobalSetting: false);
}
else
{
// this is NOT the local root span, copy some tags to the root span
AzureFunctionsTags.SetRootSpanTags(
rootSpan.Tags,
shortName: tags.ShortName,
fullName: tags.FullName,
bindingSource: rootSpan.Tags is AzureFunctionsTags t ? t.BindingSource : null,
triggerType: tags.TriggerType);
rootSpan.Type = SpanType; // "serverless"
}
span.ResourceName = $"{tags.TriggerType} {tags.ShortName}";
span.Type = SpanType;
}
tracer.TracerManager.Telemetry.IntegrationGeneratedSpan(IntegrationId);
}
catch (Exception ex)
{
Log.Error(ex, "Error creating or populating scope.");
}
// always returns the scope, even if it's null because we couldn't create it,
// or we couldn't populate it completely (some tags is better than no tags)
return scope;
}
private static Scope? GetAspNetCoreScope<T>(T functionContext)
where T : IFunctionContext
{
// Try to retrieve the aspnet_core.request scope via the HttpContext.Items bridge.
// This is needed because AsyncLocal context doesn't reliably flow between the worker's
// ASP.NET Core pipeline and the Azure Functions worker middleware pipeline.
Scope? parentScope = null;
try
{
if (functionContext.Items is not null &&
functionContext.Items.TryGetValue(HttpRequestContextKey, out var httpContextObj) &&
httpContextObj is not null &&
httpContextObj.TryDuckCast<IHttpContextItems>(out var httpContext) &&
httpContext is not null &&
httpContext.Items.TryGetValue(AspNetCoreHttpRequestHandler.HttpContextActiveScopeKey, out var scopeObj) &&
scopeObj is Scope aspNetCoreScope)
{
parentScope = aspNetCoreScope;
if (Log.IsEnabled(LogEventLevel.Debug))
{
var spanContext = parentScope.Span.Context;
Log.Debug(
"Azure Functions: retrieved AspNetCore scope from HttpContext.Items {TraceId}-{SpanId}",
spanContext.RawTraceId,
spanContext.RawSpanId);
}
}
else
{
Log.Debug("Azure Functions: could not retrieve AspNetCore scope from HttpContext.Items");
}
}
catch (Exception ex)
{
Log.Error(ex, "Azure Functions: error retrieving AspNetCore scope from HttpContext.Items");
}
return parentScope;
}
/// <summary>
/// Propagates an exception thrown by an isolated worker user function onto the
/// aspnet_core.request span. The exception is caught internally by the worker's
/// FunctionExecutionMiddleware, so the ASP.NET Core diagnostic observer never sees it
/// and the worker's HttpContext.Response.StatusCode remains at the default 200. Mirror
/// what AspNetCoreHttpRequestHandler.HandleAspNetCoreException does, without the AppSec
/// side effects (which already ran when the request entered ASP.NET Core).
/// </summary>
public static void SetExceptionOnAspNetCoreScope(Scope aspNetCoreScope, Exception exception, Tracer tracer)
{
try
{
var span = aspNetCoreScope.Span;
var settings = tracer.CurrentTraceSettings.Settings;
if (!span.HasHttpStatusCode())
{
span.SetHttpStatusCode(statusCode: 500, isServer: true, settings);
}
span.SetException(exception);
}
catch (Exception ex)
{
Log.Error(ex, "Azure Functions: error propagating user function exception to AspNetCore scope");
}
}
private static PropagationContext ExtractPropagatedContextFromHttp<T>(T functionContext, string? bindingName)
where T : IFunctionContext
{
// Need to try and grab the headers from the context
// Unfortunately, the parsed object isn't available yet, so we grab it
// directly from the grpc call instead. This is... interesting. It
// is effectively doing the equivalent of context.GetHttpRequestDataAsync() which is
// the suggested approach in the docs.
if (functionContext.Features is null || string.IsNullOrEmpty(bindingName))
{
return default;
}
try
{
object? feature = null;
foreach (var keyValuePair in functionContext.Features)
{
if (keyValuePair.Key.FullName?.Equals("Microsoft.Azure.Functions.Worker.Context.Features.IFunctionBindingsFeature") == true)
{
feature = keyValuePair.Value;
break;
}
}
if (feature is null || !feature.TryDuckCast<FunctionBindingsFeatureStruct>(out var bindingFeature))
{
return default;
}
if (bindingFeature.InputData is null
|| !bindingFeature.InputData.TryGetValue(bindingName!, out var requestDataObject)
|| requestDataObject is null)
{
return default;
}
if (!requestDataObject.TryDuckCast<HttpRequestDataStruct>(out var httpRequest))
{
return default;
}
return Tracer.Instance.TracerManager.SpanContextPropagator.Extract(new HttpHeadersCollection(httpRequest.Headers));
}
catch (Exception ex)
{
Log.Error(ex, "Error extracting propagated HTTP context from Http binding");
return default;
}
}
internal static PropagationContext ExtractPropagatedContextFromMessaging<T>(T context, string singlePropertyKey, string batchPropertyKey)
where T : IFunctionContext
{
try
{
var bindingsFeature = GetFeatureFromContext<T, FunctionBindingsFeatureStruct>(context, "Microsoft.Azure.Functions.Worker.Context.Features.IFunctionBindingsFeature");
if (bindingsFeature == null)
{
return default;
}
var triggerMetadata = bindingsFeature.Value.TriggerMetadata;
var extractedContexts = new List<PropagationContext>();
// Extract from single message properties
if (triggerMetadata?.TryGetValue(singlePropertyKey, out var singlePropsObj) == true &&
TryParseJson<Dictionary<string, object>>(singlePropsObj, out var singleProps) && singleProps != null)
{
var singleContext = Shared.AzureMessagingCommon.ExtractContext(singleProps);
if (singleContext.SpanContext != null)
{
extractedContexts.Add(singleContext);
}
}
// Extract from batch properties array
if (triggerMetadata?.TryGetValue(batchPropertyKey, out var arrayPropsObj) == true &&
TryParseJson<Dictionary<string, object>[]>(arrayPropsObj, out var propsArray) && propsArray != null)
{
foreach (var props in propsArray)
{
var batchContext = Shared.AzureMessagingCommon.ExtractContext(props);
if (batchContext.SpanContext != null)
{
extractedContexts.Add(batchContext);
}
}
}
if (extractedContexts.Count == 0)
{
return default;
}
bool areAllTheSame = extractedContexts.Count == 1 ||
(extractedContexts.Count > 1 && AreAllSpanContextsIdentical(extractedContexts));
if (!areAllTheSame)
{
Log.Warning("Multiple different contexts found in messages. Using first context for parentship.");
}
return extractedContexts[0];
}
catch (Exception ex)
{
Log.Error(ex, "Error extracting propagated context from messaging binding");
return default;
}
}
private static bool TryParseJson<T>(object? jsonObj, [NotNullWhen(true)] out T? result)
where T : class
{
result = null;
if (jsonObj is not string jsonString)
{
return false;
}
try
{
result = JsonHelper.DeserializeObject<T>(jsonString);
return result != null;
}
catch (Exception ex)
{
Log.Debug(ex, "Failed to parse JSON: {Json}", jsonString);
return false;
}
}
// Checks if all SpanContexts are identical (ignores baggage)
private static bool AreAllSpanContextsIdentical(List<PropagationContext> contexts)
{
if (contexts.Count <= 1)
{
return true;
}
var first = contexts[0].SpanContext;
return contexts.All(ctx =>
ctx.SpanContext != null &&
ctx.SpanContext.TraceId128 == first!.TraceId128 &&
ctx.SpanContext.SpanId == first.SpanId);
}
private static TFeature? GetFeatureFromContext<T, TFeature>(T context, string featureTypeName)
where T : IFunctionContext
where TFeature : struct
{
if (context.Features == null)
{
return null;
}
foreach (var kvp in context.Features)
{
if (kvp.Key.FullName == featureTypeName)
{
return kvp.Value?.TryDuckCast<TFeature>(out var feature) == true ? feature : null;
}
}
return null;
}
}
}
#endif