-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDurableContext.java
More file actions
581 lines (495 loc) · 24.3 KB
/
DurableContext.java
File metadata and controls
581 lines (495 loc) · 24.3 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.amazon.lambda.durable;
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.Function;
import java.util.function.Supplier;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.lambda.model.OperationType;
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.BatchResult;
import software.amazon.lambda.durable.model.OperationIdentifier;
import software.amazon.lambda.durable.model.OperationSubType;
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.StepOperation;
import software.amazon.lambda.durable.operation.WaitOperation;
import software.amazon.lambda.durable.validation.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 DurableContext extends BaseContext {
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 DurableContext(
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 DurableContext createRootContext(
ExecutionManager executionManager, DurableConfig durableConfig, Context lambdaContext) {
return new DurableContext(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 DurableContext createChildContext(String childContextId, String childContextName) {
return new DurableContext(
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 (1-based)
* @return a new StepContext instance
*/
public StepContext createStepContext(String stepOperationId, String stepOperationName, int attempt) {
return new StepContext(
getExecutionManager(),
getDurableConfig(),
getLambdaContext(),
stepOperationId,
stepOperationName,
attempt);
}
// ========== step methods ==========
public <T> T step(String name, Class<T> resultType, Function<StepContext, T> func) {
return step(name, TypeToken.get(resultType), func, StepConfig.builder().build());
}
public <T> T step(String name, Class<T> resultType, Function<StepContext, T> func, StepConfig config) {
// Simply delegate to stepAsync and block on the result
return stepAsync(name, resultType, func, config).get();
}
public <T> T step(String name, TypeToken<T> typeToken, Function<StepContext, T> func) {
return step(name, typeToken, func, StepConfig.builder().build());
}
public <T> T step(String name, TypeToken<T> typeToken, Function<StepContext, T> func, StepConfig config) {
// Simply delegate to stepAsync and block on the result
return stepAsync(name, typeToken, func, config).get();
}
public <T> DurableFuture<T> stepAsync(String name, Class<T> resultType, Function<StepContext, T> func) {
return stepAsync(
name, TypeToken.get(resultType), func, StepConfig.builder().build());
}
public <T> DurableFuture<T> stepAsync(
String name, Class<T> resultType, Function<StepContext, T> func, StepConfig config) {
return stepAsync(name, TypeToken.get(resultType), func, config);
}
public <T> DurableFuture<T> stepAsync(String name, TypeToken<T> typeToken, Function<StepContext, T> func) {
return stepAsync(name, typeToken, func, StepConfig.builder().build());
}
public <T> DurableFuture<T> stepAsync(
String name, TypeToken<T> typeToken, Function<StepContext, T> func, StepConfig config) {
Objects.requireNonNull(config, "config cannot be null");
Objects.requireNonNull(typeToken, "typeToken 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, typeToken, config, this);
operation.execute(); // Start the step (returns immediately)
return operation;
}
/** @deprecated use the variants accepting StepContext instead */
public <T> T step(String name, Class<T> resultType, Supplier<T> func) {
return stepAsync(
name,
TypeToken.get(resultType),
func,
StepConfig.builder().build())
.get();
}
/** @deprecated use the variants accepting StepContext instead */
public <T> T step(String name, Class<T> resultType, Supplier<T> func, StepConfig config) {
// Simply delegate to stepAsync and block on the result
return stepAsync(name, TypeToken.get(resultType), func, config).get();
}
/** @deprecated use the variants accepting StepContext instead */
public <T> T step(String name, TypeToken<T> typeToken, Supplier<T> func) {
return stepAsync(name, typeToken, func, StepConfig.builder().build()).get();
}
/** @deprecated use the variants accepting StepContext instead */
public <T> T step(String name, TypeToken<T> typeToken, Supplier<T> func, StepConfig config) {
// Simply delegate to stepAsync and block on the result
return stepAsync(name, typeToken, func, config).get();
}
/** @deprecated use the variants accepting StepContext instead */
public <T> DurableFuture<T> stepAsync(String name, Class<T> resultType, Supplier<T> func) {
return stepAsync(
name, TypeToken.get(resultType), func, StepConfig.builder().build());
}
/** @deprecated use the variants accepting StepContext instead */
public <T> DurableFuture<T> stepAsync(String name, Class<T> resultType, Supplier<T> func, StepConfig config) {
return stepAsync(name, TypeToken.get(resultType), func, config);
}
/** @deprecated use the variants accepting StepContext instead */
public <T> DurableFuture<T> stepAsync(String name, TypeToken<T> typeToken, Supplier<T> func) {
return stepAsync(name, typeToken, func, StepConfig.builder().build());
}
/** @deprecated use the variants accepting StepContext instead */
public <T> DurableFuture<T> stepAsync(String name, TypeToken<T> typeToken, Supplier<T> func, StepConfig config) {
return stepAsync(name, typeToken, stepContext -> func.get(), config);
}
// ========== wait methods ==========
public Void wait(String name, Duration duration) {
// Block (will throw SuspendExecutionException if there is no active thread)
return waitAsync(name, duration).get();
}
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;
}
// ========== chained invoke methods ==========
public <T, U> T invoke(String name, String functionName, U payload, Class<T> resultType) {
return invokeAsync(
name,
functionName,
payload,
TypeToken.get(resultType),
InvokeConfig.builder().build())
.get();
}
public <T, U> T invoke(String name, String functionName, U payload, Class<T> resultType, InvokeConfig config) {
return invokeAsync(name, functionName, payload, TypeToken.get(resultType), config)
.get();
}
public <T, U> T invoke(String name, String functionName, U payload, TypeToken<T> typeToken) {
return invokeAsync(
name,
functionName,
payload,
typeToken,
InvokeConfig.builder().build())
.get();
}
public <T, U> T invoke(String name, String functionName, U payload, TypeToken<T> typeToken, InvokeConfig config) {
return invokeAsync(name, functionName, payload, typeToken, config).get();
}
public <T, U> DurableFuture<T> invokeAsync(
String name, String functionName, U payload, Class<T> resultType, InvokeConfig config) {
return invokeAsync(name, functionName, payload, TypeToken.get(resultType), config);
}
public <T, U> DurableFuture<T> invokeAsync(String name, String functionName, U payload, Class<T> resultType) {
return invokeAsync(
name,
functionName,
payload,
TypeToken.get(resultType),
InvokeConfig.builder().build());
}
public <T, U> DurableFuture<T> invokeAsync(String name, String functionName, U payload, TypeToken<T> resultType) {
return invokeAsync(
name, functionName, payload, resultType, InvokeConfig.builder().build());
}
public <T, U> DurableFuture<T> invokeAsync(
String name, String functionName, U payload, TypeToken<T> typeToken, InvokeConfig config) {
Objects.requireNonNull(config, "config cannot be null");
Objects.requireNonNull(typeToken, "typeToken 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,
typeToken,
config,
this);
operation.execute(); // checkpoint the invoke operation
return operation; // Block (will throw SuspendExecutionException if needed)
}
// ========== createCallback methods ==========
public <T> DurableCallbackFuture<T> createCallback(String name, Class<T> resultType, CallbackConfig config) {
return createCallback(name, TypeToken.get(resultType), config);
}
public <T> DurableCallbackFuture<T> createCallback(String name, TypeToken<T> typeToken) {
return createCallback(name, typeToken, CallbackConfig.builder().build());
}
public <T> DurableCallbackFuture<T> createCallback(String name, Class<T> resultType) {
return createCallback(
name, TypeToken.get(resultType), CallbackConfig.builder().build());
}
public <T> DurableCallbackFuture<T> createCallback(String name, TypeToken<T> typeToken, 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), typeToken, config, this);
operation.execute();
return operation;
}
// ========== runInChildContext methods ==========
public <T> T runInChildContext(String name, Class<T> resultType, Function<DurableContext, T> func) {
return runInChildContextAsync(name, TypeToken.get(resultType), func).get();
}
public <T> T runInChildContext(String name, TypeToken<T> typeToken, Function<DurableContext, T> func) {
return runInChildContextAsync(name, typeToken, func).get();
}
public <T> DurableFuture<T> runInChildContextAsync(
String name, Class<T> resultType, Function<DurableContext, T> func) {
return runInChildContextAsync(name, TypeToken.get(resultType), func);
}
public <T> DurableFuture<T> runInChildContextAsync(
String name, TypeToken<T> typeToken, Function<DurableContext, T> func) {
return runInChildContextAsync(name, typeToken, func, OperationSubType.RUN_IN_CHILD_CONTEXT);
}
private <T> DurableFuture<T> runInChildContextAsync(
String name, TypeToken<T> typeToken, Function<DurableContext, T> func, OperationSubType subType) {
Objects.requireNonNull(typeToken, "typeToken cannot be null");
ParameterValidator.validateOperationName(name);
var operationId = nextOperationId();
var operation = new ChildContextOperation<>(
OperationIdentifier.of(operationId, name, OperationType.CONTEXT, subType),
func,
typeToken,
getDurableConfig().getSerDes(),
this);
operation.execute();
return operation;
}
// ========== map methods ==========
public <I, O> BatchResult<O> map(
String name, Collection<I> items, Class<O> resultType, MapFunction<I, O> function) {
return mapAsync(
name,
items,
TypeToken.get(resultType),
function,
MapConfig.builder().build())
.get();
}
public <I, O> BatchResult<O> map(
String name, Collection<I> items, Class<O> resultType, MapFunction<I, O> function, MapConfig config) {
return mapAsync(name, items, TypeToken.get(resultType), function, config)
.get();
}
public <I, O> BatchResult<O> map(
String name, Collection<I> items, TypeToken<O> resultType, MapFunction<I, O> function) {
return mapAsync(name, items, resultType, function, MapConfig.builder().build())
.get();
}
public <I, O> BatchResult<O> map(
String name, Collection<I> items, TypeToken<O> resultType, MapFunction<I, O> function, MapConfig config) {
return mapAsync(name, items, resultType, function, config).get();
}
public <I, O> DurableFuture<BatchResult<O>> mapAsync(
String name, Collection<I> items, Class<O> resultType, MapFunction<I, O> function) {
return mapAsync(
name,
items,
TypeToken.get(resultType),
function,
MapConfig.builder().build());
}
public <I, O> DurableFuture<BatchResult<O>> mapAsync(
String name, Collection<I> items, Class<O> resultType, MapFunction<I, O> function, MapConfig config) {
return mapAsync(name, items, TypeToken.get(resultType), function, config);
}
public <I, O> DurableFuture<BatchResult<O>> mapAsync(
String name, Collection<I> items, TypeToken<O> resultType, MapFunction<I, O> function) {
return mapAsync(name, items, resultType, function, MapConfig.builder().build());
}
public <I, O> DurableFuture<BatchResult<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();
}
// Short-circuit for empty collections — no checkpoint overhead
if (items.isEmpty()) {
return new CompletedDurableFuture<>(BatchResult.empty());
}
// Convert to List for deterministic index-based access
var itemList = List.copyOf(items);
var operationId = nextOperationId();
var operation = new MapOperation<>(operationId, name, itemList, function, resultType, config, this);
operation.execute();
return operation;
}
// ========= waitForCallback methods =============
public <T> T waitForCallback(String name, Class<T> resultType, BiConsumer<String, StepContext> func) {
return waitForCallbackAsync(
name,
TypeToken.get(resultType),
func,
WaitForCallbackConfig.builder().build())
.get();
}
public <T> T waitForCallback(String name, TypeToken<T> typeToken, BiConsumer<String, StepContext> func) {
return waitForCallbackAsync(
name, typeToken, func, WaitForCallbackConfig.builder().build())
.get();
}
public <T> T waitForCallback(
String name,
Class<T> resultType,
BiConsumer<String, StepContext> func,
WaitForCallbackConfig waitForCallbackConfig) {
return waitForCallbackAsync(name, TypeToken.get(resultType), func, waitForCallbackConfig)
.get();
}
public <T> T waitForCallback(
String name,
TypeToken<T> typeToken,
BiConsumer<String, StepContext> func,
WaitForCallbackConfig waitForCallbackConfig) {
return waitForCallbackAsync(name, typeToken, func, waitForCallbackConfig)
.get();
}
public <T> DurableFuture<T> waitForCallbackAsync(
String name, Class<T> resultType, BiConsumer<String, StepContext> func) {
return waitForCallbackAsync(
name,
TypeToken.get(resultType),
func,
WaitForCallbackConfig.builder().build());
}
public <T> DurableFuture<T> waitForCallbackAsync(
String name, TypeToken<T> typeToken, BiConsumer<String, StepContext> func) {
return waitForCallbackAsync(
name, typeToken, func, WaitForCallbackConfig.builder().build());
}
public <T> DurableFuture<T> waitForCallbackAsync(
String name,
Class<T> resultType,
BiConsumer<String, StepContext> func,
WaitForCallbackConfig waitForCallbackConfig) {
return waitForCallbackAsync(name, TypeToken.get(resultType), func, waitForCallbackConfig);
}
public <T> DurableFuture<T> waitForCallbackAsync(
String name,
TypeToken<T> typeToken,
BiConsumer<String, StepContext> func,
WaitForCallbackConfig waitForCallbackConfig) {
Objects.requireNonNull(typeToken, "typeToken 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,
typeToken,
childCtx -> {
var callback = childCtx.createCallback(
name + WAIT_FOR_CALLBACK_CALLBACK_SUFFIX,
typeToken,
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();
},
OperationSubType.WAIT_FOR_CALLBACK);
}
// =============== accessors ================
/**
* Returns a logger with execution context information for replay-aware logging.
*
* @return the durable logger
*/
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();
}
super.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();
}
}