-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDurableContextImpl.java
More file actions
390 lines (343 loc) · 16.4 KB
/
DurableContextImpl.java
File metadata and controls
390 lines (343 loc) · 16.4 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.lambda.durable.context;
import com.amazonaws.services.lambda.runtime.Context;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.lambda.model.OperationType;
import software.amazon.lambda.durable.DurableCallbackFuture;
import software.amazon.lambda.durable.DurableConfig;
import software.amazon.lambda.durable.DurableContext;
import software.amazon.lambda.durable.DurableFuture;
import software.amazon.lambda.durable.ParallelDurableFuture;
import software.amazon.lambda.durable.StepContext;
import software.amazon.lambda.durable.TypeToken;
import software.amazon.lambda.durable.config.CallbackConfig;
import software.amazon.lambda.durable.config.InvokeConfig;
import software.amazon.lambda.durable.config.MapConfig;
import software.amazon.lambda.durable.config.ParallelConfig;
import software.amazon.lambda.durable.config.RunInChildContextConfig;
import software.amazon.lambda.durable.config.StepConfig;
import software.amazon.lambda.durable.config.WaitForCallbackConfig;
import software.amazon.lambda.durable.config.WaitForConditionConfig;
import software.amazon.lambda.durable.execution.ExecutionManager;
import software.amazon.lambda.durable.execution.OperationIdGenerator;
import software.amazon.lambda.durable.execution.ThreadType;
import software.amazon.lambda.durable.logging.DurableLogger;
import software.amazon.lambda.durable.model.MapResult;
import software.amazon.lambda.durable.model.OperationIdentifier;
import software.amazon.lambda.durable.model.OperationSubType;
import software.amazon.lambda.durable.model.WaitForConditionResult;
import software.amazon.lambda.durable.operation.CallbackOperation;
import software.amazon.lambda.durable.operation.ChildContextOperation;
import software.amazon.lambda.durable.operation.InvokeOperation;
import software.amazon.lambda.durable.operation.MapOperation;
import software.amazon.lambda.durable.operation.ParallelOperation;
import software.amazon.lambda.durable.operation.StepOperation;
import software.amazon.lambda.durable.operation.WaitForConditionOperation;
import software.amazon.lambda.durable.operation.WaitOperation;
import software.amazon.lambda.durable.util.ParameterValidator;
/**
* User-facing API for defining durable operations within a workflow.
*
* <p>Provides methods for creating steps, waits, chained invokes, callbacks, and child contexts. Each method creates a
* checkpoint-backed operation that survives Lambda interruptions.
*/
public class DurableContextImpl extends BaseContextImpl implements DurableContext {
private static final String WAIT_FOR_CALLBACK_CALLBACK_SUFFIX = "-callback";
private static final String WAIT_FOR_CALLBACK_SUBMITTER_SUFFIX = "-submitter";
private static final int MAX_WAIT_FOR_CALLBACK_NAME_LENGTH = ParameterValidator.MAX_OPERATION_NAME_LENGTH
- Math.max(WAIT_FOR_CALLBACK_CALLBACK_SUFFIX.length(), WAIT_FOR_CALLBACK_SUBMITTER_SUFFIX.length());
private final OperationIdGenerator operationIdGenerator;
private volatile DurableLogger logger;
/** Shared initialization — sets all fields. */
private DurableContextImpl(
ExecutionManager executionManager,
DurableConfig durableConfig,
Context lambdaContext,
String contextId,
String contextName) {
super(executionManager, durableConfig, lambdaContext, contextId, contextName, ThreadType.CONTEXT);
operationIdGenerator = new OperationIdGenerator(contextId);
}
/**
* Creates a root context (contextId = null)
*
* <p>The context itself always has a null contextId (making it a root context).
*
* @param executionManager the execution manager
* @param durableConfig the durable configuration
* @param lambdaContext the Lambda context
* @return a new root DurableContext
*/
public static DurableContextImpl createRootContext(
ExecutionManager executionManager, DurableConfig durableConfig, Context lambdaContext) {
return new DurableContextImpl(executionManager, durableConfig, lambdaContext, null, null);
}
/**
* Creates a child context.
*
* @param childContextId the child context's ID (the CONTEXT operation's operation ID)
* @param childContextName the name of the child context
* @return a new DurableContext for the child context
*/
public DurableContextImpl createChildContext(String childContextId, String childContextName) {
return new DurableContextImpl(
getExecutionManager(), getDurableConfig(), getLambdaContext(), childContextId, childContextName);
}
/**
* Creates a step context for executing step operations.
*
* @param stepOperationId the ID of the step operation (used for thread registration)
* @param stepOperationName the name of the step operation
* @param attempt the current retry attempt number (0-based)
* @return a new StepContext instance
*/
public StepContextImpl createStepContext(String stepOperationId, String stepOperationName, int attempt) {
return new StepContextImpl(
getExecutionManager(),
getDurableConfig(),
getLambdaContext(),
stepOperationId,
stepOperationName,
attempt);
}
@Override
public <T> DurableFuture<T> stepAsync(
String name, TypeToken<T> resultType, Function<StepContext, T> func, StepConfig config) {
Objects.requireNonNull(config, "config cannot be null");
Objects.requireNonNull(resultType, "resultType cannot be null");
ParameterValidator.validateOperationName(name);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
var operationId = nextOperationId();
// Create and start step operation with TypeToken
var operation = new StepOperation<>(
OperationIdentifier.of(operationId, name, OperationType.STEP), func, resultType, config, this);
operation.execute(); // Start the step (returns immediately)
return operation;
}
@Override
public DurableFuture<Void> waitAsync(String name, Duration duration) {
ParameterValidator.validateDuration(duration, "Wait duration");
ParameterValidator.validateOperationName(name);
var operationId = nextOperationId();
// Create and start wait operation
var operation =
new WaitOperation(OperationIdentifier.of(operationId, name, OperationType.WAIT), duration, this);
operation.execute(); // Checkpoint the wait
return operation;
}
@Override
public <T, U> DurableFuture<T> invokeAsync(
String name, String functionName, U payload, TypeToken<T> resultType, InvokeConfig config) {
Objects.requireNonNull(config, "config cannot be null");
Objects.requireNonNull(resultType, "resultType cannot be null");
ParameterValidator.validateOperationName(name);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
if (config.payloadSerDes() == null) {
config = config.toBuilder()
.payloadSerDes(getDurableConfig().getSerDes())
.build();
}
var operationId = nextOperationId();
// Create and start invoke operation
var operation = new InvokeOperation<>(
OperationIdentifier.of(operationId, name, OperationType.CHAINED_INVOKE),
functionName,
payload,
resultType,
config,
this);
operation.execute(); // checkpoint the invoke operation
return operation; // Block (will throw SuspendExecutionException if needed)
}
@Override
public <T> DurableCallbackFuture<T> createCallback(String name, TypeToken<T> resultType, CallbackConfig config) {
ParameterValidator.validateOperationName(name);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
var operationId = nextOperationId();
var operation = new CallbackOperation<>(
OperationIdentifier.of(operationId, name, OperationType.CALLBACK), resultType, config, this);
operation.execute();
return operation;
}
/**
* Runs a function in a child context, blocking until it completes.
*
* <p>Child contexts provide isolated operation ID namespaces, allowing nested workflows to be composed without ID
* collisions. On replay, the child context's operations are replayed independently.
*
* @param name the operation name within this context
* @param resultType the result class for deserialization
* @param func the function to execute, receiving a child {@link DurableContext}
* @param config the configuration for the child context
* @return the DurableFuture wrapping the child context result
*/
@Override
public <T> DurableFuture<T> runInChildContextAsync(
String name, TypeToken<T> resultType, Function<DurableContext, T> func, RunInChildContextConfig config) {
return runInChildContextAsync(name, resultType, func, config, OperationSubType.RUN_IN_CHILD_CONTEXT);
}
private <T> DurableFuture<T> runInChildContextAsync(
String name,
TypeToken<T> resultType,
Function<DurableContext, T> func,
RunInChildContextConfig config,
OperationSubType subType) {
Objects.requireNonNull(resultType, "resultType cannot be null");
Objects.requireNonNull(config, "RunInChildContextConfig cannot be null");
ParameterValidator.validateOperationName(name);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
var operationId = nextOperationId();
var operation = new ChildContextOperation<>(
OperationIdentifier.of(operationId, name, OperationType.CONTEXT, subType),
func,
resultType,
config,
this);
operation.execute();
return operation;
}
@Override
public <I, O> DurableFuture<MapResult<O>> mapAsync(
String name, Collection<I> items, TypeToken<O> resultType, MapFunction<I, O> function, MapConfig config) {
Objects.requireNonNull(items, "items cannot be null");
Objects.requireNonNull(function, "function cannot be null");
Objects.requireNonNull(resultType, "resultType cannot be null");
Objects.requireNonNull(config, "config cannot be null");
ParameterValidator.validateOperationName(name);
ParameterValidator.validateOrderedCollection(items);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
// Convert to List for deterministic index-based access
var itemList = List.copyOf(items);
var operationId = nextOperationId();
var operation = new MapOperation<>(
OperationIdentifier.of(operationId, name, OperationType.CONTEXT, OperationSubType.MAP),
itemList,
function,
resultType,
config,
this);
operation.execute();
return operation;
}
@Override
public ParallelDurableFuture parallel(String name, ParallelConfig config) {
Objects.requireNonNull(config, "config cannot be null");
var operationId = nextOperationId();
var parallelOp = new ParallelOperation(
OperationIdentifier.of(operationId, name, OperationType.CONTEXT, OperationSubType.PARALLEL),
getDurableConfig().getSerDes(),
this,
config);
parallelOp.execute();
return parallelOp;
}
@Override
public <T> DurableFuture<T> waitForCallbackAsync(
String name,
TypeToken<T> resultType,
BiConsumer<String, StepContext> func,
WaitForCallbackConfig waitForCallbackConfig) {
Objects.requireNonNull(resultType, "resultType cannot be null");
Objects.requireNonNull(waitForCallbackConfig, "waitForCallbackConfig cannot be null");
// waitForCallback adds a suffix for the callback operation name and the submitter operation name so
// the length restriction of waitForCallback name is different from the other operations.
ParameterValidator.validateOperationName(name, MAX_WAIT_FOR_CALLBACK_NAME_LENGTH);
var finalWaitForCallbackConfig = waitForCallbackConfig.stepConfig().serDes() == null
? waitForCallbackConfig.toBuilder()
.stepConfig(waitForCallbackConfig.stepConfig().toBuilder()
.serDes(getDurableConfig().getSerDes())
.build())
.build()
: waitForCallbackConfig;
return runInChildContextAsync(
name,
resultType,
childCtx -> {
var callback = childCtx.createCallback(
name + WAIT_FOR_CALLBACK_CALLBACK_SUFFIX,
resultType,
finalWaitForCallbackConfig.callbackConfig());
childCtx.step(
name + WAIT_FOR_CALLBACK_SUBMITTER_SUFFIX,
Void.class,
stepCtx -> {
func.accept(callback.callbackId(), stepCtx);
return null;
},
finalWaitForCallbackConfig.stepConfig());
return callback.get();
},
RunInChildContextConfig.builder()
.serDes(finalWaitForCallbackConfig.stepConfig().serDes())
.build(),
OperationSubType.WAIT_FOR_CALLBACK);
}
@Override
public <T> DurableFuture<T> waitForConditionAsync(
String name,
TypeToken<T> resultType,
BiFunction<T, StepContext, WaitForConditionResult<T>> checkFunc,
WaitForConditionConfig<T> config) {
Objects.requireNonNull(config, "config cannot be null");
Objects.requireNonNull(resultType, "resultType cannot be null");
Objects.requireNonNull(checkFunc, "checkFunc cannot be null");
ParameterValidator.validateOperationName(name);
if (config.serDes() == null) {
config = config.toBuilder().serDes(getDurableConfig().getSerDes()).build();
}
var operationId = nextOperationId();
var operation = new WaitForConditionOperation<>(operationId, name, checkFunc, resultType, config, this);
operation.execute();
return operation;
}
// =============== accessors ================
@Override
public DurableLogger getLogger() {
// lazy initialize logger
if (logger == null) {
synchronized (this) {
if (logger == null) {
logger = new DurableLogger(LoggerFactory.getLogger(DurableContext.class), this);
}
}
}
return logger;
}
/**
* Clears the logger's thread properties. Called during context destruction to prevent memory leaks and ensure clean
* state for subsequent executions.
*/
@Override
public void close() {
if (logger != null) {
logger.close();
}
}
/**
* Get the next operationId. Returns a globally unique operation ID by hashing a sequential operation counter. For
* root contexts, the counter value is hashed directly (e.g. "1", "2", "3"). For child contexts, the values are
* prefixed with the parent hashed contextId (e.g. "<hash>-1", "<hash>-2" inside parent context <hash>). This
* matches the Python SDK's stepPrefix convention and prevents ID collisions in checkpoint batches.
*/
private String nextOperationId() {
return operationIdGenerator.nextOperationId();
}
}