-
Notifications
You must be signed in to change notification settings - Fork 40
/
v0.ts
642 lines (553 loc) · 18.8 KB
/
v0.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
import canonicalize from "canonicalize";
import { sha1 } from "hash.js";
import { z } from "zod";
import {
ErrCode,
deserializeError,
functionStoppedRunningErr,
prettyError,
serializeError,
} from "../../helpers/errors";
import { undefinedToNull } from "../../helpers/functions";
import {
resolveAfterPending,
resolveNextTick,
runAsPromise,
} from "../../helpers/promises";
import { type MaybePromise, type PartialK } from "../../helpers/types";
import {
StepOpCode,
failureEventErrorSchema,
type BaseContext,
type ClientOptions,
type Context,
type EventPayload,
type FailureEventArgs,
type Handler,
type HashedOp,
type IncomingOp,
type OpStack,
type OutgoingOp,
} from "../../types";
import { getHookStack, type RunHookStack } from "../InngestMiddleware";
import {
createStepTools,
getStepOptions,
type StepHandler,
} from "../InngestStepTools";
import { NonRetriableError } from "../NonRetriableError";
import { RetryAfterError } from "../RetryAfterError";
import {
InngestExecution,
type ExecutionResult,
type IInngestExecution,
type InngestExecutionFactory,
type InngestExecutionOptions,
} from "./InngestExecution";
export const createV0InngestExecution: InngestExecutionFactory = (options) => {
return new V0InngestExecution(options);
};
export class V0InngestExecution
extends InngestExecution
implements IInngestExecution
{
private state: V0ExecutionState;
private execution: Promise<ExecutionResult> | undefined;
private userFnToRun: Handler.Any;
private fnArg: Context.Any;
constructor(options: InngestExecutionOptions) {
super(options);
this.userFnToRun = this.getUserFnToRun();
this.state = this.createExecutionState();
this.fnArg = this.createFnArg();
}
public start() {
this.debug("starting V0 execution");
return (this.execution ??= this._start().then((result) => {
this.debug("result:", result);
return result;
}));
}
private async _start(): Promise<ExecutionResult> {
this.state.hooks = await this.initializeMiddleware();
try {
await this.transformInput();
await this.state.hooks.beforeMemoization?.();
if (this.state.opStack.length === 0 && !this.options.requestedRunStep) {
await this.state.hooks.afterMemoization?.();
await this.state.hooks.beforeExecution?.();
}
const userFnPromise = runAsPromise(() => this.userFnToRun(this.fnArg));
let pos = -1;
do {
if (pos >= 0) {
if (
!this.options.requestedRunStep &&
pos === this.state.opStack.length - 1
) {
await this.state.hooks.afterMemoization?.();
await this.state.hooks.beforeExecution?.();
}
this.state.tickOps = {};
const incomingOp = this.state.opStack[pos] as IncomingOp;
this.state.currentOp = this.state.allFoundOps[incomingOp.id];
if (!this.state.currentOp) {
/**
* We're trying to resume the function, but we can't find where to go.
*
* This means that either the function has changed or there are async
* actions in-between steps that we haven't noticed in previous
* executions.
*
* Whichever the case, this is bad and we can't continue in this
* undefined state.
*/
throw new NonRetriableError(
prettyError({
whatHappened: " Your function was stopped from running",
why: "We couldn't resume your function's state because it may have changed since the run started or there are async actions in-between steps that we haven't noticed in previous executions.",
consequences:
"Continuing to run the function may result in unexpected behaviour, so we've stopped your function to ensure nothing unexpected happened!",
toFixNow:
"Ensure that your function is either entirely step-based or entirely non-step-based, by either wrapping all asynchronous logic in `step.run()` calls or by removing all `step.*()` calls.",
otherwise:
"For more information on why step functions work in this manner, see https://www.inngest.com/docs/functions/multi-step#gotchas",
stack: true,
code: ErrCode.NON_DETERMINISTIC_FUNCTION,
})
);
}
this.state.currentOp.fulfilled = true;
if (typeof incomingOp.data !== "undefined") {
this.state.currentOp.resolve(incomingOp.data);
} else {
this.state.currentOp.reject(incomingOp.error);
}
}
await resolveAfterPending();
this.state.reset();
pos++;
} while (pos < this.state.opStack.length);
await this.state.hooks.afterMemoization?.();
const discoveredOps = Object.values(this.state.tickOps).map<OutgoingOp>(
tickOpToOutgoing
);
const runStep =
this.options.requestedRunStep ||
this.getEarlyExecRunStep(discoveredOps);
if (runStep) {
const userFnOp = this.state.allFoundOps[runStep];
const stepToRun = userFnOp?.fn;
if (!stepToRun) {
throw new Error(
`Bad stack; executor requesting to run unknown step "${runStep}"`
);
}
const outgoingUserFnOp = {
...tickOpToOutgoing(userFnOp),
op: StepOpCode.Step,
};
await this.state.hooks.beforeExecution?.();
this.state.executingStep = true;
const result = await runAsPromise(stepToRun)
.finally(() => {
this.state.executingStep = false;
})
.catch(async (error: Error) => {
return await this.transformOutput({ error }, outgoingUserFnOp);
})
.then(async (data) => {
await this.state.hooks?.afterExecution?.();
return await this.transformOutput({ data }, outgoingUserFnOp);
});
const { type: _type, ...rest } = result;
return { type: "step-ran", step: { ...outgoingUserFnOp, ...rest } };
}
if (!discoveredOps.length) {
const fnRet = await Promise.race([
userFnPromise.then((data) => ({ type: "complete", data }) as const),
resolveNextTick().then(() => ({ type: "incomplete" }) as const),
]);
if (fnRet.type === "complete") {
await this.state.hooks.afterExecution?.();
const allOpsFulfilled = Object.values(this.state.allFoundOps).every(
(op) => {
return op.fulfilled;
}
);
if (allOpsFulfilled) {
return await this.transformOutput({ data: fnRet.data });
}
} else if (!this.state.hasUsedTools) {
this.state.nonStepFnDetected = true;
const data = await userFnPromise;
await this.state.hooks.afterExecution?.();
return await this.transformOutput({ data });
} else {
const hasOpsPending = Object.values(this.state.allFoundOps).some(
(op) => {
return op.fulfilled === false;
}
);
if (!hasOpsPending) {
throw new NonRetriableError(
functionStoppedRunningErr(
ErrCode.ASYNC_DETECTED_AFTER_MEMOIZATION
)
);
}
}
}
await this.state.hooks.afterExecution?.();
return {
type: "steps-found",
steps: discoveredOps as [OutgoingOp, ...OutgoingOp[]],
};
} catch (error) {
return await this.transformOutput({ error });
} finally {
await this.state.hooks.beforeResponse?.();
}
}
private async initializeMiddleware(): Promise<RunHookStack> {
const ctx = this.options.data as Pick<
Readonly<BaseContext<ClientOptions, string>>,
"event" | "events" | "runId"
>;
const hooks = await getHookStack(
this.options.fn["middleware"],
"onFunctionRun",
{
ctx,
fn: this.options.fn,
steps: Object.values(this.options.stepState),
reqArgs: this.options.reqArgs,
},
{
transformInput: (prev, output) => {
return {
ctx: { ...prev.ctx, ...output?.ctx },
fn: this.options.fn,
steps: prev.steps.map((step, i) => ({
...step,
...output?.steps?.[i],
})),
reqArgs: prev.reqArgs,
};
},
transformOutput: (prev, output) => {
return {
result: { ...prev.result, ...output?.result },
step: prev.step,
};
},
}
);
return hooks;
}
private createExecutionState(): V0ExecutionState {
const state: V0ExecutionState = {
allFoundOps: {},
tickOps: {},
tickOpHashes: {},
currentOp: undefined,
hasUsedTools: false,
reset: () => {
state.tickOpHashes = {};
state.allFoundOps = { ...state.allFoundOps, ...state.tickOps };
},
nonStepFnDetected: false,
executingStep: false,
opStack: this.options.stepCompletionOrder.reduce<IncomingOp[]>(
(acc, stepId) => {
const stepState = this.options.stepState[stepId];
if (!stepState) {
return acc;
}
return [...acc, stepState];
},
[]
),
};
return state;
}
private getUserFnToRun(): Handler.Any {
if (!this.options.isFailureHandler) {
// TODO: Review; inferred types results in an `any` here!
return this.options.fn["fn"] as Handler.Any;
}
if (!this.options.fn["onFailureFn"]) {
/**
* Somehow, we've ended up detecting that this is a failure handler but
* doesn't have an `onFailure` function. This should never happen.
*/
throw new Error("Cannot find function `onFailure` handler");
}
return this.options.fn["onFailureFn"];
}
private createFnArg(): Context.Any {
// Start referencing everything
this.state.tickOps = this.state.allFoundOps;
/**
* Create a unique hash of an operation using only a subset of the operation's
* properties; will never use `data` and will guarantee the order of the
* object so we don't rely on individual tools for that.
*
* If the operation already contains an ID, the current ID will be used
* instead, so that users can provide their own IDs.
*/
const hashOp = (
/**
* The op to generate a hash from. We only use a subset of the op's
* properties when creating the hash.
*/
op: PartialK<HashedOp, "id">
): HashedOp => {
/**
* It's difficult for v0 to understand whether or not an op has
* historically contained a custom ID, as all step usage now require them.
*
* For this reason, we make the assumption that steps in v0 do not have a
* custom ID and generate one for them as we would in all recommendations
* and examples.
*/
const obj = {
parent: this.state.currentOp?.id ?? null,
op: op.op,
name: op.name as string,
opts: op.opts ?? null,
};
const collisionHash = _internals.hashData(obj);
const pos = (this.state.tickOpHashes[collisionHash] =
(this.state.tickOpHashes[collisionHash] ?? -1) + 1);
return {
...op,
id: _internals.hashData({ pos, ...obj }),
};
};
const stepHandler: StepHandler = ({ args, matchOp, opts }) => {
if (this.state.nonStepFnDetected) {
if (opts?.nonStepExecuteInline && opts.fn) {
return Promise.resolve(opts.fn(...args));
}
throw new NonRetriableError(
functionStoppedRunningErr(ErrCode.STEP_USED_AFTER_ASYNC)
);
}
if (this.state.executingStep) {
throw new NonRetriableError(
prettyError({
whatHappened: "Your function was stopped from running",
why: "We detected that you have nested `step.*` tooling.",
consequences: "Nesting `step.*` tooling is not supported.",
stack: true,
toFixNow:
"Make sure you're not using `step.*` tooling inside of other `step.*` tooling. If you need to compose steps together, you can create a new async function and call it from within your step function, or use promise chaining.",
otherwise:
"For more information on step functions with Inngest, see https://www.inngest.com/docs/functions/multi-step",
code: ErrCode.NESTING_STEPS,
})
);
}
this.state.hasUsedTools = true;
const stepOptions = getStepOptions(args[0]);
const opId = hashOp(matchOp(stepOptions, ...args.slice(1)));
return new Promise<unknown>((resolve, reject) => {
this.state.tickOps[opId.id] = {
...opId,
...(opts?.fn ? { fn: () => opts.fn?.(...args) } : {}),
resolve,
reject,
fulfilled: false,
};
});
};
const step = createStepTools(this.options.client, stepHandler);
let fnArg = {
...(this.options.data as { event: EventPayload }),
step,
} as Context.Any;
if (this.options.isFailureHandler) {
const eventData = z
.object({ error: failureEventErrorSchema })
.parse(fnArg.event?.data);
(fnArg as Partial<Pick<FailureEventArgs, "error">>) = {
...fnArg,
error: deserializeError(eventData.error),
};
}
return fnArg;
}
/**
* Using middleware, transform input before running.
*/
private async transformInput() {
const inputMutations = await this.state.hooks?.transformInput?.({
ctx: { ...this.fnArg },
steps: Object.values(this.options.stepState),
fn: this.options.fn,
reqArgs: this.options.reqArgs,
});
if (inputMutations?.ctx) {
this.fnArg = inputMutations.ctx;
}
if (inputMutations?.steps) {
this.state.opStack = [...inputMutations.steps];
}
}
private getEarlyExecRunStep(ops: OutgoingOp[]): string | undefined {
if (ops.length !== 1) return;
const op = ops[0];
if (
op &&
op.op === StepOpCode.StepPlanned &&
typeof op.opts === "undefined"
) {
return op.id;
}
}
/**
* Using middleware, transform output before returning.
*/
private async transformOutput(
dataOrError: Parameters<
NonNullable<RunHookStack["transformOutput"]>
>[0]["result"],
step?: Readonly<Omit<OutgoingOp, "id">>
): Promise<ExecutionResult> {
const output = { ...dataOrError };
if (typeof output.error !== "undefined") {
output.data = serializeError(output.error);
}
const transformedOutput = await this.state.hooks?.transformOutput?.({
result: { ...output },
step,
});
const { data, error } = { ...output, ...transformedOutput?.result };
if (typeof error !== "undefined") {
/**
* Ensure we give middleware the chance to decide on retriable behaviour
* by looking at the error returned from output transformation.
*/
let retriable: boolean | string = !(error instanceof NonRetriableError);
if (retriable && error instanceof RetryAfterError) {
retriable = error.retryAfter;
}
const serializedError = serializeError(error);
return { type: "function-rejected", error: serializedError, retriable };
}
return { type: "function-resolved", data: undefinedToNull(data) };
}
}
interface TickOp extends HashedOp {
fn?: (...args: unknown[]) => unknown;
fulfilled: boolean;
resolve: (value: MaybePromise<unknown>) => void;
reject: (reason?: unknown) => void;
}
export interface V0ExecutionState {
/**
* The tree of all found ops in the entire invocation.
*/
allFoundOps: Record<string, TickOp>;
/**
* All synchronous operations found in this particular tick. The array is
* reset every tick.
*/
tickOps: Record<string, TickOp>;
/**
* A hash of operations found within this tick, with keys being the hashed
* ops themselves (without a position) and the values being the number of
* times that op has been found.
*
* This is used to provide some mutation resilience to the op stack,
* allowing us to survive same-tick mutations of code by ensuring per-tick
* hashes are based on uniqueness rather than order.
*/
tickOpHashes: Record<string, number>;
/**
* Tracks the current operation being processed. This can be used to
* understand the contextual parent of any recorded operations.
*/
currentOp: TickOp | undefined;
/**
* If we've found a user function to run, we'll store it here so a component
* higher up can invoke and await it.
*/
userFnToRun?: (...args: unknown[]) => unknown;
/**
* A boolean to represent whether the user's function is using any step
* tools.
*
* If the function survives an entire tick of the event loop and hasn't
* touched any tools, we assume that it is a single-step async function and
* should be awaited as usual.
*/
hasUsedTools: boolean;
/**
* A function that should be used to reset the state of the tools after a
* tick has completed.
*/
reset: () => void;
/**
* If `true`, any use of step tools will, by default, throw an error. We do
* this when we detect that a function may be mixing step and non-step code.
*
* Created step tooling can decide how to manually handle this on a
* case-by-case basis.
*
* In the future, we can provide a way for a user to override this if they
* wish to and understand the danger of side-effects.
*
* Defaults to `false`.
*/
nonStepFnDetected: boolean;
/**
* When true, we are currently executing a user's code for a single step
* within a step function.
*/
executingStep: boolean;
/**
* Initialized middleware hooks for this execution.
*
* Middleware hooks are cached to ensure they can only be run once, which
* means that these hooks can be called in many different places to ensure we
* handle all possible execution paths.
*/
hooks?: RunHookStack;
/**
* The op stack to pass to the function as state, likely stored in
* `ctx._state` in the Inngest payload.
*
* This must be provided in order to always be cognizant of step function
* state and to allow for multi-step functions.
*/
opStack: OpStack;
}
const tickOpToOutgoing = (op: TickOp): OutgoingOp => {
return {
op: op.op,
id: op.id,
name: op.name,
opts: op.opts,
};
};
/**
* An operation ready to hash to be used to memoise step function progress.
*
* @internal
*/
export type UnhashedOp = {
name: string;
op: StepOpCode;
opts: Record<string, unknown> | null;
parent: string | null;
pos?: number;
};
const hashData = (op: UnhashedOp): string => {
return sha1().update(canonicalize(op)).digest("hex");
};
/**
* Exported for testing.
*/
export const _internals = { hashData };