Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .autover/autover.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
"Libraries/src/Amazon.Lambda.DurableExecution.Analyzers/Amazon.Lambda.DurableExecution.Analyzers.csproj"
]
},
{
"Name": "Amazon.Lambda.DurableExecution.OpenTelemetry",
"Path": "Libraries/src/Amazon.Lambda.DurableExecution.OpenTelemetry/Amazon.Lambda.DurableExecution.OpenTelemetry.csproj"
},
{
"Name": "Amazon.Lambda.DurableExecution.Testing",
"Path": "Libraries/src/Amazon.Lambda.DurableExecution.Testing/Amazon.Lambda.DurableExecution.Testing.csproj"
Expand Down
11 changes: 11 additions & 0 deletions .autover/changes/7c2d4e19-5a3b-4f6e-8b0d-1e9f2a3b4c5d.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Projects": [
{
"Name": "Amazon.Lambda.DurableExecution.OpenTelemetry",
"Type": "Minor",
"ChangelogMessages": [
"Initial preview of OpenTelemetry tracing for Amazon.Lambda.DurableExecution. The Invocation view emits Workflow, Invocation, operation and attempt spans through System.Diagnostics.ActivitySource, with no OpenTelemetry package dependency. ContextExtractors.W3C anchors the execution on a W3C traceparent instead of an X-Ray header."
]
}
]
}
2 changes: 2 additions & 0 deletions Libraries/Amazon.Lambda.DurableExecution.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
"src\\Amazon.Lambda.TestUtilities\\Amazon.Lambda.TestUtilities.csproj",
"src\\Amazon.Lambda.DurableExecution\\Amazon.Lambda.DurableExecution.csproj",
"src\\Amazon.Lambda.DurableExecution.Testing\\Amazon.Lambda.DurableExecution.Testing.csproj",
"src\\Amazon.Lambda.DurableExecution.OpenTelemetry\\Amazon.Lambda.DurableExecution.OpenTelemetry.csproj",
"test\\Amazon.Lambda.DurableExecution.Tests\\Amazon.Lambda.DurableExecution.Tests.csproj",
"test\\Amazon.Lambda.DurableExecution.Testing.Tests\\Amazon.Lambda.DurableExecution.Testing.Tests.csproj",
"test\\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests\\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj",
"test\\Amazon.Lambda.DurableExecution.IntegrationTests\\Amazon.Lambda.DurableExecution.IntegrationTests.csproj",
"test\\Amazon.Lambda.DurableExecution.AotPublishTest\\Amazon.Lambda.DurableExecution.AotPublishTest.csproj"
]
Expand Down
30 changes: 30 additions & 0 deletions Libraries/Libraries.sln
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.OCI.Builder.Tests", "te
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.OCI.Builder.IntegrationTests", "test\AWS.OCI.Builder.IntegrationTests\AWS.OCI.Builder.IntegrationTests.csproj", "{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Amazon.Lambda.DurableExecution.OpenTelemetry", "src\Amazon.Lambda.DurableExecution.OpenTelemetry\Amazon.Lambda.DurableExecution.OpenTelemetry.csproj", "{F7163946-2476-45F1-B56F-8B9340B1533A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Amazon.Lambda.DurableExecution.OpenTelemetry.Tests", "test\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests\Amazon.Lambda.DurableExecution.OpenTelemetry.Tests.csproj", "{9336B275-FC95-4590-8D57-D1FB6BAA7A33}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -1151,6 +1155,30 @@ Global
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x64.Build.0 = Release|Any CPU
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x86.ActiveCfg = Release|Any CPU
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9}.Release|x86.Build.0 = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x64.ActiveCfg = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x64.Build.0 = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x86.ActiveCfg = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Debug|x86.Build.0 = Debug|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|Any CPU.Build.0 = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x64.ActiveCfg = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x64.Build.0 = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x86.ActiveCfg = Release|Any CPU
{F7163946-2476-45F1-B56F-8B9340B1533A}.Release|x86.Build.0 = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x64.ActiveCfg = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x64.Build.0 = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x86.ActiveCfg = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Debug|x86.Build.0 = Debug|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|Any CPU.Build.0 = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x64.ActiveCfg = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x64.Build.0 = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x86.ActiveCfg = Release|Any CPU
{9336B275-FC95-4590-8D57-D1FB6BAA7A33}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1240,6 +1268,8 @@ Global
{BB37A746-2351-9685-2D1F-1571F8F23E06} = {AAB54E74-20B1-42ED-BC3D-CE9F7BC7FD12}
{7636C459-D2A3-30DB-4964-CAF22E6BA256} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
{39FD406D-D77B-9593-CF95-B1BE32F4B7F9} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
{F7163946-2476-45F1-B56F-8B9340B1533A} = {AAB54E74-20B1-42ED-BC3D-CE9F7BC7FD12}
{9336B275-FC95-4590-8D57-D1FB6BAA7A33} = {1DE4EE60-45BA-4EF7-BE00-B9EB861E4C69}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {503678A4-B8D1-4486-8915-405A3E9CF0EB}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\..\..\buildtools\common.props" />

<PropertyGroup>
<TargetFrameworks>$(DefaultPackageTargets)</TargetFrameworks>
<Description>OpenTelemetry tracing for Amazon.Lambda.DurableExecution. Emits Workflow, Invocation, operation and attempt spans through System.Diagnostics.ActivitySource.</Description>
<AssemblyTitle>Amazon.Lambda.DurableExecution.OpenTelemetry</AssemblyTitle>
<Version>0.1.0</Version>
<AssemblyName>Amazon.Lambda.DurableExecution.OpenTelemetry</AssemblyName>
<PackageId>Amazon.Lambda.DurableExecution.OpenTelemetry</PackageId>
<PackageTags>AWS;Amazon;Lambda;Durable;Workflow;OpenTelemetry;Tracing</PackageTags>
<IsTrimmable>true</IsTrimmable>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors>IL2026,IL2067,IL2075,IL3050</WarningsAsErrors>
</PropertyGroup>

<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>Amazon.Lambda.DurableExecution.OpenTelemetry.Tests, PublicKey="0024000004800000940000000602000000240000525341310004000001000100db5f59f098d27276c7833875a6263a3cc74ab17ba9a9df0b52aedbe7252745db7274d5271fd79c1f08f668ecfa8eaab5626fa76adc811d3c8fc55859b0d09d3bc0a84eecd0ba891f2b8a2fc55141cdcc37c2053d53491e650a479967c3622762977900eddbf1252ed08a2413f00a28f3a0752a81203f03ccb7f684db373518b4"</_Parameter1>
</AssemblyAttribute>
</ItemGroup>

<!--
No OpenTelemetry NuGet package is referenced. Tracing goes through System.Diagnostics.ActivitySource, which the
OpenTelemetry SDK, the ADOT layer and OpenTelemetry.Instrumentation.AWSLambda listen to once the application adds
the source name (OtelPlugin.ActivitySourceName) to its tracer provider.
-->
<ItemGroup>
<ProjectReference Include="..\Amazon.Lambda.DurableExecution\Amazon.Lambda.DurableExecution.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

using Amazon.Lambda.DurableExecution.Instrumentation;

namespace Amazon.Lambda.DurableExecution.OpenTelemetry;

/// <summary>Finds the trace context of a durable execution.</summary>
public static class ContextExtractors
{
/// <summary>
/// Reads <see cref="InvocationInfo.XRayTraceId"/>. The durable service keeps the X-Ray <c>Root</c> the same for
/// every invocation of an execution, so its trace id anchors the whole execution.
/// </summary>
public static ExtractedContext? XRay(InvocationInfo info) => ParseXRayHeader(info.XRayTraceId);

/// <summary>
/// Reads <see cref="InvocationInfo.TraceParent"/>, the W3C <c>traceparent</c> the invoke carried on
/// <c>clientContext.w3c</c>. Use it when the caller propagates W3C context instead of an X-Ray header. Like any
/// extractor it must return the same context on every invocation of an execution, or the execution splits
/// across traces.
/// </summary>
public static ExtractedContext? W3C(InvocationInfo info) => ParseTraceParent(info.TraceParent);

/// <summary>
/// Parses a W3C <c>traceparent</c>: <c>version-traceid-parentid-flags</c>, lowercase hex. A zero trace id or
/// parent id, a <c>ff</c> version, or a malformed field returns null. Version <c>00</c> has exactly four
/// fields; a later version may add more after them. The sampled flag is the low bit of the flags.
/// </summary>
internal static ExtractedContext? ParseTraceParent(string? traceParent)
{
if (string.IsNullOrWhiteSpace(traceParent))
return null;

var parts = traceParent.Trim().Split('-');
if (parts.Length < 4)
return null;

var (version, traceId, parentId, flags) = (parts[0], parts[1], parts[2], parts[3]);
if (version.Length != 2 || !DeterministicIds.IsLowerHex(version) || version == "ff" || (version == "00" && parts.Length != 4))
return null;
if (!DeterministicIds.IsValidTraceId(traceId) || !DeterministicIds.IsValidSpanId(parentId))
return null;
if (flags.Length != 2 || !DeterministicIds.IsLowerHex(flags))
return null;

return new ExtractedContext
{
TraceId = traceId,
ParentSpanId = parentId,
Sampling = (Convert.ToInt32(flags, 16) & 1) != 0 ? UpstreamSampling.Sampled : UpstreamSampling.NotSampled,
};
}

/// <summary>
/// Parses an <c>X-Amzn-Trace-Id</c> header. <c>Root</c>, <c>Parent</c> and <c>Sampled</c> are read independently;
/// an all-zero or malformed <c>Root</c> or <c>Parent</c> is ignored. Returns null without a valid <c>Root</c>.
/// </summary>
internal static ExtractedContext? ParseXRayHeader(string? header)
{
if (string.IsNullOrWhiteSpace(header))
return null;

string? root = null, parent = null, sampled = null;
foreach (var part in header.Split(';'))
{
var eq = part.IndexOf('=');
if (eq <= 0)
continue;

var key = part[..eq].Trim();
var value = part[(eq + 1)..].Trim();
switch (key)
{
case "Root": root = value; break;
case "Parent": parent = value; break;
case "Sampled": sampled = value; break;
}
}

if (root == null)
return null;

var rootValue = root.StartsWith("1-", StringComparison.Ordinal) ? root[2..] : root;
var traceId = rootValue.Replace("-", string.Empty).ToLowerInvariant();
if (!DeterministicIds.IsValidTraceId(traceId))
return null;

var parentSpanId = parent?.ToLowerInvariant();
return new ExtractedContext
{
TraceId = traceId,
ParentSpanId = parentSpanId != null && DeterministicIds.IsValidSpanId(parentSpanId) ? parentSpanId : null,
Sampling = sampled switch
{
"1" => UpstreamSampling.Sampled,
"0" => UpstreamSampling.NotSampled,
_ => UpstreamSampling.Undecided,
},
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace Amazon.Lambda.DurableExecution.OpenTelemetry;

/// <summary>
/// Gives an <see cref="Activity"/> a span id of our choosing.
/// </summary>
/// <remarks>
/// <para>The public API cannot do this: <c>SpanId</c> is read-only, and a parent context or <c>SetParentId</c>
/// only chooses the parent. A durable execution needs it, because spans in one invocation must name spans that
/// another invocation exports (the Workflow span, the first segment of an operation), and nothing is stored
/// between invocations.</para>
/// <para>This writes the private <c>_spanId</c> and <c>_id</c> fields through <see cref="UnsafeAccessorAttribute"/>,
/// which is generated at compile time and is safe for trimming and Native AOT. The fields are not a contract. If
/// a runtime renames them the first call throws, the override switches itself off, and spans get random ids:
/// parenting inside one invocation still works, references across invocations do not. A test fails when the
/// fields are missing, so a new runtime is noticed.</para>
/// <para>Listeners notified when the activity starts have already seen the random id. Export and child spans see
/// the one set here.</para>
/// </remarks>
internal static class ActivityIdOverride
{
private static volatile bool _disabled;

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_spanId")]
private static extern ref string? SpanIdField(Activity activity);

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_id")]
private static extern ref string? IdField(Activity activity);

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_parentSpanId")]
private static extern ref string? ParentSpanIdField(Activity activity);

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_parentId")]
private static extern ref string? ParentIdField(Activity activity);

/// <summary>True once an override failed. Spans then have random ids.</summary>
internal static bool IsDisabled => _disabled;

/// <summary>Switches the override back on. For tests.</summary>
internal static void Reset() => _disabled = false;

/// <summary>
/// Sets the span id of a started activity, and optionally removes its parent so it exports as a root.
/// Returns false, and leaves the activity unchanged, when the override is unavailable.
/// </summary>
internal static bool TrySet(Activity? activity, string spanId, bool asRoot = false)
{
if (activity == null || _disabled)
return false;

try
{
var traceId = activity.TraceId.ToHexString();
var flags = (activity.ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0 ? "01" : "00";

SpanIdField(activity) = spanId;
IdField(activity) = $"00-{traceId}-{spanId}-{flags}";
if (asRoot)
{
ParentSpanIdField(activity) = null;
ParentIdField(activity) = null;
}
return true;
}
catch (Exception ex) when (ex is MissingFieldException or MissingMemberException or NullReferenceException)
{
_disabled = true;
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

using System.Security.Cryptography;
using System.Text;

namespace Amazon.Lambda.DurableExecution.OpenTelemetry;

/// <summary>
/// Trace and span ids that every invocation of an execution derives the same way. A span exported by one
/// invocation can then be the parent of, or be linked from, a span exported by another, with nothing stored
/// between them. The derivations match the JavaScript, Python and Java SDKs, so a trace that crosses SDKs stays
/// consistent.
/// </summary>
internal static class DeterministicIds
{
private const string ZeroSpanId = "0000000000000000";
private const string ZeroTraceId = "00000000000000000000000000000000";

internal static bool IsValidTraceId(string? value) =>
value is { Length: 32 } && value != ZeroTraceId && IsLowerHex(value);

internal static bool IsValidSpanId(string? value) =>
value is { Length: 16 } && value != ZeroSpanId && IsLowerHex(value);

internal static bool IsLowerHex(string value)
{
foreach (var c in value)
{
if (!(c is >= '0' and <= '9' || c is >= 'a' and <= 'f'))
return false;
}
return true;
}

private static string Sha256Hex(string value, int length) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))).ToLowerInvariant()[..length];

/// <summary>The trace id of an execution that has no propagated trace: SHA-256 of the ARN and start time.</summary>
internal static string TraceIdFromArn(string executionArn, DateTimeOffset? executionStart)
{
var identity = executionStart is { } start
? $"{executionArn}:{start.UtcDateTime:yyyy-MM-ddTHH:mm:ss.fffZ}"
: executionArn;
return Sha256Hex(identity, 32);
}

/// <summary>The id of the first span of an operation, scoped to the execution.</summary>
internal static string SpanIdFromOperationId(string operationId, string executionArn) =>
Sha256Hex(executionArn + ":" + operationId, 16);

/// <summary>The id of the Workflow span.</summary>
internal static string WorkflowSpanId(string executionArn) => NonZero(Sha256Hex("workflow:" + executionArn, 16));

/// <summary>The id of the synthetic root that anchors an execution with no propagated parent.</summary>
internal static string ExecutionRootSpanId(string executionArn) =>
NonZero(Sha256Hex("execution-root:" + executionArn, 16));

private static string NonZero(string spanId) => spanId == ZeroSpanId ? "0000000000000001" : spanId;
}
Loading
Loading