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
12 changes: 12 additions & 0 deletions .autover/changes/3f1c7a52-8d0b-4c4e-9a41-6b2e5d7c9a10.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"Projects": [
{
"Name": "Amazon.Lambda.DurableExecution",
"Type": "Minor",
"ChangelogMessages": [
"Add an instrumentation plugin API (IDurableInstrumentationPlugin and IDurableInstrumentationPluginFactory) and DurableExecutionOptions, accepted by new DurableFunction.WrapAsync overloads. Plugins observe the invocation lifecycle and can run the workflow function inside their own context.",
"Raise the minimum AWSSDK.Lambda version to 4.0.110.1, which adds the trace header on chained invokes (ChainedInvokeOptions.XAmznTraceId). Plugins can supply that header and add fields to the log scope of durable log entries."
]
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.DurableExecution.Internal;
using Amazon.Lambda.DurableExecution.Services;

namespace Amazon.Lambda.DurableExecution.Testing;
Expand Down Expand Up @@ -92,8 +93,12 @@ public async Task<TestResult<TOutput>> DriveToTerminalAsync(

var invocationInput = BuildInvocationInput(arn);

var output = await DurableFunction.WrapAsync<TInput, TOutput>(
_handler, invocationInput, _lambdaContext, _serviceClient);
var output = _options.ExecutionOptions == null
? await DurableFunction.WrapAsync<TInput, TOutput>(
_handler, invocationInput, _lambdaContext, _serviceClient)
: await DurableFunction.WrapAsync<TInput, TOutput>(
_handler, invocationInput, _lambdaContext, _serviceClient,
new DurableInvocationOptions { Execution = _options.ExecutionOptions });

_invocationCount++;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ Invoking an unregistered function throws `UnregisteredSiblingFunctionException`.
| `LoggerFactory` | none | Optional logging during execution. |
| `DurableExecutionArn` | synthetic test ARN | Override for tests that assert on the ARN. |
| `OmitCheckpointToken` | none | Predicate over the 1-based checkpoint call number; when true, the response omits the token so the invocation suspends (`Pending`) and resumes in the next one. |
| `ExecutionOptions` | none | `DurableExecutionOptions` passed to every invocation, for example to run the workflow with instrumentation plugins. |

## Testing Against a Deployed Function

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,11 @@ public int MaxInvocations
/// omit its token from the response, which suspends the invocation. Default: null.
/// </summary>
public Func<int, bool>? OmitCheckpointToken { get; init; }

/// <summary>
/// Options passed to every invocation of the workflow, for example to run it with instrumentation plugins.
/// The in-memory service does not report <c>UpdatedOperationIds</c>, so plugins see no updated operations
/// at invocation start. Default: null.
/// </summary>
public DurableExecutionOptions? ExecutionOptions { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="AWSSDK.Lambda" Version="4.0.13.1" />
<PackageReference Include="AWSSDK.Lambda" Version="4.0.110.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>

Expand Down
17 changes: 17 additions & 0 deletions Libraries/src/Amazon.Lambda.DurableExecution/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,23 @@ String constants live in `OperationTypes` (STEP/WAIT/CALLBACK/CHAINED_INVOKE/CON
`OperationSubTypes` (PascalCase finer classifier). Plural type names (`OperationTypes`, not `OperationType`)
intentionally avoid collision with `AWSSDK.Lambda` model enums.

## Instrumentation plugins

`Instrumentation/` holds the public plugin API and `Internal/PluginRunner.cs` dispatches to it (user guide:
`docs/core/instrumentation-plugins.md`, decisions: `docs/design/instrumentation-plugin-hooks.md`). Rules to keep when
touching it:

- Operation and attempt hooks are synchronous and never awaited. Awaiting plugin work where no operation is
executing lets the invocation suspend early. Async plugin work belongs in `OnInvocationEndAsync`.
- A plugin must never fail the workflow: contain every hook exception, and keep `WrapAsync` running the user code
exactly once and letting its exception through.
- Operation start/end are reported in one place, `DurableOperation.ExecuteAsync`. An operation that hands back a
handle and finishes later (a callback) sets `EndsWhenExecuteReturns` to false and calls `ReportEnd` itself.
`IncrementalParallelOperation` is not a `DurableOperation` and reports its own start and end.
- With no plugin registered the `Plugins` reference is null and the original code path runs. Keep it that way.
- Plugins are passed to operations through the `Plugins` init property and to child contexts through
`DurableContext`, so operation constructors stay unchanged.

## Conventions

- **Programming model:** both the *executable* model (`Main` builds a `LambdaBootstrap` with a handler
Expand Down
31 changes: 18 additions & 13 deletions Libraries/src/Amazon.Lambda.DurableExecution/DurableContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ internal sealed class DurableContext : IDurableContext
private readonly OperationIdGenerator _idGenerator;
private readonly string _durableExecutionArn;
private readonly CheckpointBatcher? _batcher;
private readonly PluginRunner? _plugins;
private ILogger _logger;

public DurableContext(
Expand All @@ -29,18 +30,22 @@ public DurableContext(
OperationIdGenerator idGenerator,
string durableExecutionArn,
ILambdaContext lambdaContext,
CheckpointBatcher? batcher = null)
CheckpointBatcher? batcher = null,
PluginRunner? plugins = null)
{
_plugins = plugins;
_state = state;
_terminationManager = terminationManager;
_workflowCancellation = workflowCancellation;
_idGenerator = idGenerator;
_durableExecutionArn = durableExecutionArn;
_batcher = batcher;
LambdaContext = lambdaContext;
_logger = new ReplayAwareLogger(new LambdaCoreLogger(), state, modeAware: true);
_logger = new ReplayAwareLogger(new LambdaCoreLogger(), state, modeAware: true, ScopeFields);
}

private Func<IReadOnlyDictionary<string, object>?>? ScopeFields => _plugins == null ? null : _plugins.GetLogScope;

public ILogger Logger => _logger;
public IExecutionContext ExecutionContext => new DurableExecutionContext(_durableExecutionArn);
public ILambdaContext LambdaContext { get; }
Expand All @@ -54,7 +59,7 @@ public void ConfigureLogger(LoggerConfig config)
// so toggling ModeAware works without losing the previous custom logger.
var inner = config.CustomLogger
?? (_logger is ReplayAwareLogger existing ? existing.Inner : _logger);
_logger = new ReplayAwareLogger(inner, _state, config.ModeAware);
_logger = new ReplayAwareLogger(inner, _state, config.ModeAware, ScopeFields);
}

public Task<T> StepAsync<T>(
Expand Down Expand Up @@ -91,7 +96,7 @@ private Task<T> RunStep<T>(
var operationId = _idGenerator.NextId();
var op = new StepOperation<T>(
operationId, name, _idGenerator.ParentId, func, config, serializer, Logger,
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher);
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand All @@ -115,7 +120,7 @@ public Task WaitAsync(
var waitSeconds = (int)Math.Max(1, Math.Ceiling(duration.TotalSeconds));
var op = new WaitOperation(
operationId, name, _idGenerator.ParentId, waitSeconds,
_state, _terminationManager, _durableExecutionArn, _batcher);
_state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand Down Expand Up @@ -156,7 +161,7 @@ public Task<TState> WaitForConditionAsync<TState>(
var operationId = _idGenerator.NextId();
var op = new WaitForConditionOperation<TState>(
operationId, name, _idGenerator.ParentId, check, config, serializer, Logger,
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher);
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand All @@ -175,7 +180,7 @@ private Task<T> RunChildContext<T>(
var op = new ChildContextOperation<T>(
operationId, name, _idGenerator.ParentId, func, config, serializer, MakeChildFactory(),
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher,
isVirtual: config?.NestingType == NestingType.Flat);
isVirtual: config?.NestingType == NestingType.Flat) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand All @@ -196,7 +201,7 @@ private Task<ICallback<T>> RunCallback<T>(
var operationId = _idGenerator.NextId();
var op = new CallbackOperation<T>(
operationId, name, _idGenerator.ParentId, config, serializer,
_state, _terminationManager, _durableExecutionArn, _batcher);
_state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand Down Expand Up @@ -230,7 +235,7 @@ public IDurableParallel CreateParallel(
var operationId = _idGenerator.NextId();
return new Internal.IncrementalParallelOperation(
operationId, name, _idGenerator.ParentId, effectiveConfig, defaultSerializerFactory, MakeChildFactory(),
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher);
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher, _plugins);
}

public Task<IBatchResult<T>> ParallelAsync<T>(
Expand Down Expand Up @@ -294,7 +299,7 @@ private Task<IBatchResult<T>> RunParallel<T>(
var operationId = _idGenerator.NextId();
var op = new Internal.ParallelOperation<T>(
operationId, name, _idGenerator.ParentId, branches, effectiveConfig, serializer, MakeChildFactory(),
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher);
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand Down Expand Up @@ -329,7 +334,7 @@ private Task<IBatchResult<TResult>> RunMap<TItem, TResult>(
var operationId = _idGenerator.NextId();
var op = new Internal.MapOperation<TItem, TResult>(
operationId, name, _idGenerator.ParentId, items, func, effectiveConfig, serializer, MakeChildFactory(),
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher);
_state, _terminationManager, _workflowCancellation, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand Down Expand Up @@ -554,7 +559,7 @@ private Task<TResult> RunInvoke<TPayload, TResult>(
var op = new InvokeOperation<TPayload, TResult>(
operationId, name, _idGenerator.ParentId, functionName, payload, config,
serializer,
_state, _terminationManager, _durableExecutionArn, _batcher);
_state, _terminationManager, _durableExecutionArn, _batcher) { Plugins = _plugins };
return op.ExecuteAsync(cancellationToken);
}

Expand Down Expand Up @@ -591,7 +596,7 @@ private Task<TResult> RunInvoke<TPayload, TResult>(
isVirtual
? _idGenerator.CreateVirtualChild(operationId, reportedParentId)
: _idGenerator.CreateChild(operationId),
_durableExecutionArn, LambdaContext, _batcher);
_durableExecutionArn, LambdaContext, _batcher, _plugins);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ public sealed class DurableExecutionInvocationInput
/// </summary>
[JsonPropertyName("InitialExecutionState")]
public InitialExecutionState? InitialExecutionState { get; set; }

/// <summary>
/// Ids of operations that changed since the previous invocation of this execution, as reported by the
/// service. Absent on the first invocation.
/// </summary>
[JsonPropertyName("UpdatedOperationIds")]
public IReadOnlyList<string>? UpdatedOperationIds { get; set; }
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// 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;

/// <summary>
/// Optional settings passed to <c>DurableFunction.WrapAsync</c>.
/// Create it once, for example in a static field, and reuse it for every invocation.
/// </summary>
public sealed class DurableExecutionOptions
{
/// <summary>
/// Instrumentation plugin factories, in registration order. The SDK asks each factory for a new plugin on
/// every invocation.
/// </summary>
public IList<IDurableInstrumentationPluginFactory> Plugins { get; } = new List<IDurableInstrumentationPluginFactory>();
}
Loading
Loading