-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
state.ts
680 lines (608 loc) · 16.8 KB
/
state.ts
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
import { IConstruct, Construct, Node } from 'constructs';
import { Token } from '../../../core';
import { Condition } from '../condition';
import { FieldUtils } from '../fields';
import { StateGraph } from '../state-graph';
import { CatchProps, Errors, IChainable, INextable, ProcessorConfig, ProcessorMode, RetryProps } from '../types';
/**
* Properties shared by all states
*/
export interface StateProps {
/**
* Optional name for this state
*
* @default - The construct ID will be used as state name
*/
readonly stateName?: string;
/**
* A comment describing this state
*
* @default No comment
*/
readonly comment?: string;
/**
* JSONPath expression to select part of the state to be the input to this state.
*
* May also be the special value JsonPath.DISCARD, which will cause the effective
* input to be the empty object {}.
*
* @default $
*/
readonly inputPath?: string;
/**
* Parameters pass a collection of key-value pairs, either static values or JSONPath expressions that select from the input.
*
* @see
* https://docs.aws.amazon.com/step-functions/latest/dg/input-output-inputpath-params.html#input-output-parameters
*
* @default No parameters
*/
readonly parameters?: { [name: string]: any };
/**
* JSONPath expression to select part of the state to be the output to this state.
*
* May also be the special value JsonPath.DISCARD, which will cause the effective
* output to be the empty object {}.
*
* @default $
*/
readonly outputPath?: string;
/**
* JSONPath expression to indicate where to inject the state's output
*
* May also be the special value JsonPath.DISCARD, which will cause the state's
* input to become its output.
*
* @default $
*/
readonly resultPath?: string;
/**
* The JSON that will replace the state's raw result and become the effective
* result before ResultPath is applied.
*
* You can use ResultSelector to create a payload with values that are static
* or selected from the state's raw result.
*
* @see
* https://docs.aws.amazon.com/step-functions/latest/dg/input-output-inputpath-params.html#input-output-resultselector
*
* @default - None
*/
readonly resultSelector?: { [key: string]: any };
}
/**
* Base class for all other state classes
*/
export abstract class State extends Construct implements IChainable {
/**
* Add a prefix to the stateId of all States found in a construct tree
*/
public static prefixStates(root: IConstruct, prefix: string) {
const queue = [root];
while (queue.length > 0) {
const el = queue.splice(0, 1)[0]!;
if (isPrefixable(el)) {
el.addPrefix(prefix);
}
queue.push(...Node.of(el).children);
}
}
/**
* Find the set of states reachable through transitions from the given start state.
* This does not retrieve states from within sub-graphs, such as states within a Parallel state's branch.
*/
public static findReachableStates(start: State, options: FindStateOptions = {}): State[] {
const visited = new Set<State>();
const ret = new Set<State>();
const queue = [start];
while (queue.length > 0) {
const state = queue.splice(0, 1)[0]!;
if (visited.has(state)) { continue; }
visited.add(state);
const outgoing = state.outgoingTransitions(options);
queue.push(...outgoing);
ret.add(state);
}
return Array.from(ret);
}
/**
* Find the set of end states states reachable through transitions from the given start state
*/
public static findReachableEndStates(start: State, options: FindStateOptions = {}): State[] {
const visited = new Set<State>();
const ret = new Set<State>();
const queue = [start];
while (queue.length > 0) {
const state = queue.splice(0, 1)[0]!;
if (visited.has(state)) { continue; }
visited.add(state);
const outgoing = state.outgoingTransitions(options);
if (outgoing.length > 0) {
// We can continue
queue.push(...outgoing);
} else {
// Terminal state
ret.add(state);
}
}
return Array.from(ret);
}
/**
* Return only the states that allow chaining from an array of states
*/
public static filterNextables(states: State[]): INextable[] {
return states.filter(isNextable) as any;
}
/**
* First state of this Chainable
*/
public readonly startState: State;
/**
* Continuable states of this Chainable
*/
public abstract readonly endStates: INextable[];
// This class has a superset of most of the features of the other states,
// and the subclasses decide which part of the features to expose. Most
// features are shared by a couple of states, and it becomes cumbersome to
// slice it out across all states. This is not great design, but it is
// pragmatic!
protected readonly stateName?: string;
protected readonly comment?: string;
protected readonly inputPath?: string;
protected readonly parameters?: object;
protected readonly outputPath?: string;
protected readonly resultPath?: string;
protected readonly resultSelector?: object;
protected readonly branches: StateGraph[] = [];
protected iteration?: StateGraph;
protected processorMode?: ProcessorMode = ProcessorMode.INLINE;
protected processor?: StateGraph;
protected processorConfig?: ProcessorConfig;
protected defaultChoice?: State;
/**
* @internal
*/
protected _next?: State;
private readonly retries: RetryProps[] = [];
private readonly catches: CatchTransition[] = [];
private readonly choices: ChoiceTransition[] = [];
private readonly prefixes: string[] = [];
/**
* The graph that this state is part of.
*
* Used for guaranteeing consistency between graphs and graph components.
*/
private containingGraph?: StateGraph;
/**
* States with references to this state.
*
* Used for finding complete connected graph that a state is part of.
*/
private readonly incomingStates: State[] = [];
constructor(scope: Construct, id: string, props: StateProps) {
super(scope, id);
this.startState = this;
this.stateName = props.stateName;
this.comment = props.comment;
this.inputPath = props.inputPath;
this.parameters = props.parameters;
this.outputPath = props.outputPath;
this.resultPath = props.resultPath;
this.resultSelector = props.resultSelector;
this.node.addValidation({ validate: () => this.validateState() });
}
/**
* Allows the state to validate itself.
*/
protected validateState(): string[] {
return [];
}
public get id() {
return this.node.id;
}
/**
* Tokenized string that evaluates to the state's ID
*/
public get stateId(): string {
return this.prefixes.concat(this.stateName? this.stateName: this.id).join('');
}
/**
* Add a prefix to the stateId of this state
*/
public addPrefix(x: string) {
if (x !== '') {
this.prefixes.splice(0, 0, x);
}
}
/**
* Register this state as part of the given graph
*
* Don't call this. It will be called automatically when you work
* with states normally.
*/
public bindToGraph(graph: StateGraph) {
if (this.containingGraph === graph) { return; }
if (this.containingGraph) {
// eslint-disable-next-line max-len
throw new Error(`Trying to use state '${this.stateId}' in ${graph}, but is already in ${this.containingGraph}. Every state can only be used in one graph.`);
}
this.containingGraph = graph;
this.whenBoundToGraph(graph);
for (const incoming of this.incomingStates) {
incoming.bindToGraph(graph);
}
for (const outgoing of this.outgoingTransitions({ includeErrorHandlers: true })) {
outgoing.bindToGraph(graph);
}
for (const branch of this.branches) {
branch.registerSuperGraph(this.containingGraph);
}
if (!!this.iteration) {
this.iteration.registerSuperGraph(this.containingGraph);
}
if (!!this.processor) {
this.processor.registerSuperGraph(this.containingGraph);
}
}
/**
* Render the state as JSON
*/
public abstract toStateJson(): object;
/**
* Add a retrier to the retry list of this state
* @internal
*/
protected _addRetry(props: RetryProps = {}) {
validateErrors(props.errors);
this.retries.push({
...props,
errors: props.errors ?? [Errors.ALL],
});
}
/**
* Add an error handler to the catch list of this state
* @internal
*/
protected _addCatch(handler: State, props: CatchProps = {}) {
validateErrors(props.errors);
this.catches.push({
next: handler,
props: {
errors: props.errors ?? [Errors.ALL],
resultPath: props.resultPath,
},
});
handler.addIncoming(this);
if (this.containingGraph) {
handler.bindToGraph(this.containingGraph);
}
}
/**
* Make the indicated state the default transition of this state
*/
protected makeNext(next: State) {
// Can't be called 'setNext' because of JSII
if (this._next) {
throw new Error(`State '${this.id}' already has a next state`);
}
this._next = next;
next.addIncoming(this);
if (this.containingGraph) {
next.bindToGraph(this.containingGraph);
}
}
/**
* Add a choice branch to this state
*/
protected addChoice(condition: Condition, next: State, options?: ChoiceTransitionOptions) {
this.choices.push({ condition, next, ...options });
next.startState.addIncoming(this);
if (this.containingGraph) {
next.startState.bindToGraph(this.containingGraph);
}
}
/**
* Add a parallel branch to this state
*/
protected addBranch(branch: StateGraph) {
this.branches.push(branch);
if (this.containingGraph) {
branch.registerSuperGraph(this.containingGraph);
}
}
/**
* Add a map iterator to this state
*/
protected addIterator(iteration: StateGraph) {
this.iteration = iteration;
if (this.containingGraph) {
iteration.registerSuperGraph(this.containingGraph);
}
}
/**
* Add a item processor to this state
*/
protected addItemProcessor(processor: StateGraph, config: ProcessorConfig = {}) {
this.processor = processor;
this.processorConfig = config;
if (this.containingGraph) {
processor.registerSuperGraph(this.containingGraph);
}
}
/**
* Make the indicated state the default choice transition of this state
*/
protected makeDefault(def: State) {
// Can't be called 'setDefault' because of JSII
if (this.defaultChoice) {
throw new Error(`Choice '${this.id}' already has a default next state`);
}
this.defaultChoice = def;
}
/**
* Render the default next state in ASL JSON format
*/
protected renderNextEnd(): any {
if (this._next) {
return { Next: this._next.stateId };
} else {
return { End: true };
}
}
/**
* Render the choices in ASL JSON format
*/
protected renderChoices(): any {
return {
Choices: renderList(this.choices, renderChoice),
Default: this.defaultChoice?.stateId,
};
}
/**
* Render InputPath/Parameters/OutputPath in ASL JSON format
*/
protected renderInputOutput(): any {
return {
InputPath: renderJsonPath(this.inputPath),
Parameters: this.parameters,
OutputPath: renderJsonPath(this.outputPath),
};
}
/**
* Render parallel branches in ASL JSON format
*/
protected renderBranches(): any {
return {
Branches: this.branches.map(b => b.toGraphJson()),
};
}
/**
* Render map iterator in ASL JSON format
*/
protected renderIterator(): any {
if (!this.iteration) return undefined;
return {
Iterator: this.iteration.toGraphJson(),
};
}
/**
* Render error recovery options in ASL JSON format
*/
protected renderRetryCatch(): any {
return {
Retry: renderList(this.retries, renderRetry, (a, b) => compareErrors(a.errors, b.errors)),
Catch: renderList(this.catches, renderCatch, (a, b) => compareErrors(a.props.errors, b.props.errors)),
};
}
/**
* Render ResultSelector in ASL JSON format
*/
protected renderResultSelector(): any {
return FieldUtils.renderObject({
ResultSelector: this.resultSelector,
});
}
/**
* Render ItemProcessor in ASL JSON format
*/
protected renderItemProcessor(): any {
if (!this.processor) return undefined;
return {
ItemProcessor: {
...this.renderProcessorConfig(),
...this.processor.toGraphJson(),
},
};
}
/**
* Render ProcessorConfig in ASL JSON format
*/
private renderProcessorConfig() {
const mode = this.processorConfig?.mode?.toString() ?? this.processorMode;
if (mode === ProcessorMode.INLINE) {
return {
ProcessorConfig: {
Mode: mode,
},
};
}
const executionType = this.processorConfig?.executionType?.toString();
return {
ProcessorConfig: {
Mode: mode,
ExecutionType: executionType,
},
};
}
/**
* Called whenever this state is bound to a graph
*
* Can be overridden by subclasses.
*/
protected whenBoundToGraph(graph: StateGraph) {
graph.registerState(this);
}
/**
* Add a state to the incoming list
*/
private addIncoming(source: State) {
this.incomingStates.push(source);
}
/**
* Return all states this state can transition to
*/
private outgoingTransitions(options: FindStateOptions): State[] {
const ret = new Array<State>();
if (this._next) { ret.push(this._next); }
if (this.defaultChoice) { ret.push(this.defaultChoice); }
for (const c of this.choices) {
ret.push(c.next);
}
if (options.includeErrorHandlers) {
for (const c of this.catches) {
ret.push(c.next);
}
}
return ret;
}
}
/**
* Options for finding reachable states
*/
export interface FindStateOptions {
/**
* Whether or not to follow error-handling transitions
*
* @default false
*/
readonly includeErrorHandlers?: boolean;
}
/**
* A Choice Transition
*/
interface ChoiceTransition extends ChoiceTransitionOptions {
/**
* State to transition to
*/
next: State;
/**
* Condition for this transition
*/
condition: Condition;
}
/**
* Options for Choice Transition
*/
export interface ChoiceTransitionOptions {
/**
* An optional description for the choice transition
*
* @default No comment
*/
readonly comment?: string;
}
/**
* Render a choice transition
*/
function renderChoice(c: ChoiceTransition) {
return {
...c.condition.renderCondition(),
Next: c.next.stateId,
Comment: c.comment,
};
}
/**
* A Catch Transition
*/
interface CatchTransition {
/**
* State to transition to
*/
next: State;
/**
* Additional properties for this transition
*/
props: CatchProps;
}
/**
* Render a Retry object to ASL
*/
function renderRetry(retry: RetryProps) {
return {
ErrorEquals: retry.errors,
IntervalSeconds: retry.interval && retry.interval.toSeconds(),
MaxAttempts: retry.maxAttempts,
BackoffRate: retry.backoffRate,
MaxDelaySeconds: retry.maxDelay && retry.maxDelay.toSeconds(),
JitterStrategy: retry.jitterStrategy,
};
}
/**
* Render a Catch object to ASL
*/
function renderCatch(c: CatchTransition) {
return {
ErrorEquals: c.props.errors,
ResultPath: renderJsonPath(c.props.resultPath),
Next: c.next.stateId,
};
}
/**
* Compares a list of Errors to move Errors.ALL last in a sort function
*/
function compareErrors(a?: string[], b?: string[]) {
if (a?.includes(Errors.ALL)) {
return 1;
}
if (b?.includes(Errors.ALL)) {
return -1;
}
return 0;
}
/**
* Validates an errors list
*/
function validateErrors(errors?: string[]) {
if (errors?.includes(Errors.ALL) && errors.length > 1) {
throw new Error(`${Errors.ALL} must appear alone in an error list`);
}
}
/**
* Render a list or return undefined for an empty list
*/
export function renderList<T>(xs: T[], mapFn: (x: T) => any, sortFn?: (a: T, b: T) => number): any {
if (xs.length === 0) { return undefined; }
let list = xs;
if (sortFn) {
list = xs.sort(sortFn);
}
return list.map(mapFn);
}
/**
* Render JSON path, respecting the special value JsonPath.DISCARD
*/
export function renderJsonPath(jsonPath?: string): undefined | null | string {
if (jsonPath === undefined) { return undefined; }
if (!Token.isUnresolved(jsonPath) && !jsonPath.startsWith('$')) {
throw new Error(`Expected JSON path to start with '$', got: ${jsonPath}`);
}
return jsonPath;
}
/**
* Interface for structural feature testing (to make TypeScript happy)
*/
interface Prefixable {
addPrefix(x: string): void;
}
/**
* Whether an object is a Prefixable
*/
function isPrefixable(x: any): x is Prefixable {
return typeof(x) === 'object' && x.addPrefix;
}
/**
* Whether an object is INextable
*/
function isNextable(x: any): x is INextable {
return typeof(x) === 'object' && x.next;
}