@sanity/runtime-cli 17.21.4 → 17.21.5-next.g584ecfe
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -19
- package/dist/cores/functions/test.js +2 -3
- package/dist/utils/functions/child-process-wrapper.js +15 -4
- package/dist/utils/functions/child-runtime/callback.d.ts +10 -10
- package/dist/utils/functions/child-runtime/callback.js +4 -29
- package/dist/utils/functions/child-runtime/durables/delegate.js +44 -0
- package/dist/utils/functions/child-runtime/durables/durable.d.ts +29 -0
- package/dist/utils/functions/child-runtime/durables/durable.js +91 -0
- package/dist/utils/functions/child-runtime/durables/eventsFactoryPlugin.js +171 -0
- package/dist/utils/functions/child-runtime/durables/fanout.js +24 -0
- package/dist/utils/functions/child-runtime/durables/index.js +45 -0
- package/dist/utils/functions/child-runtime/durables/logger.js +31 -0
- package/dist/utils/functions/child-runtime/durables/retry.js +60 -0
- package/dist/utils/functions/child-runtime/durables/run.js +23 -0
- package/dist/utils/functions/child-runtime/durables/utils.js +20 -0
- package/dist/utils/functions/child-runtime/durables/wait.js +11 -0
- package/dist/utils/functions/child-runtime/durables/waitForCallback.js +40 -0
- package/dist/utils/functions/child-runtime/durables/waitForCondition.js +44 -0
- package/oclif.manifest.json +1 -1
- package/package.json +3 -1
- package/dist/utils/functions/child-runtime/durable.d.ts +0 -18
- package/dist/utils/functions/child-runtime/durable.js +0 -264
- package/dist/utils/functions/child-runtime/getBatchResults.d.ts +0 -6
- package/dist/utils/functions/child-runtime/getBatchResults.js +0 -74
- package/dist/utils/functions/child-runtime/step-history.d.ts +0 -15
- package/dist/utils/functions/child-runtime/step-history.js +0 -52
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {createDurableContextParameter} from './index.js'
|
|
2
|
+
|
|
3
|
+
const createFanoutFunction = (durableContext, runtime) => {
|
|
4
|
+
return ({name, branches}) => {
|
|
5
|
+
const wrap = (branch) => (branchCtx) =>
|
|
6
|
+
branch(createDurableContextParameter(branchCtx, runtime))
|
|
7
|
+
|
|
8
|
+
return durableContext.parallel(
|
|
9
|
+
name,
|
|
10
|
+
branches.map((branch) => {
|
|
11
|
+
return typeof branch === 'function'
|
|
12
|
+
? wrap(branch)
|
|
13
|
+
: {name: branch.name, func: wrap(branch.func)}
|
|
14
|
+
}),
|
|
15
|
+
{
|
|
16
|
+
// default to `Promise.allSettled` semantics: wait for every branch to settle
|
|
17
|
+
// in the future, we will expose this configuration to users
|
|
18
|
+
completionConfig: {toleratedFailurePercentage: 100},
|
|
19
|
+
},
|
|
20
|
+
)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {createFanoutFunction}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {DurableOperationError, withDurableExecution} from '@aws/durable-execution-sdk-js'
|
|
2
|
+
import {createDelegateFunction} from './delegate.js'
|
|
3
|
+
import {createFanoutFunction} from './fanout.js'
|
|
4
|
+
import {createRunFunction} from './run.js'
|
|
5
|
+
import {wrapLogger} from './utils.js'
|
|
6
|
+
import {createWaitFunction} from './wait.js'
|
|
7
|
+
import {createWaitForCallbackFunction} from './waitForCallback.js'
|
|
8
|
+
import {createWaitForConditionFunction} from './waitForCondition.js'
|
|
9
|
+
|
|
10
|
+
export const createDurableContextParameter = (durableCtx, runtime) => {
|
|
11
|
+
return {
|
|
12
|
+
logger: wrapLogger(durableCtx),
|
|
13
|
+
step: {
|
|
14
|
+
run: createRunFunction(durableCtx, runtime),
|
|
15
|
+
wait: createWaitFunction(durableCtx),
|
|
16
|
+
waitForCondition: createWaitForConditionFunction(durableCtx),
|
|
17
|
+
fanout: createFanoutFunction(durableCtx, runtime),
|
|
18
|
+
delegate: createDelegateFunction(durableCtx, runtime),
|
|
19
|
+
waitForCallback: createWaitForCallbackFunction(durableCtx, runtime),
|
|
20
|
+
},
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const durableHandler = (handler, {context, event, runtime, eventsPlugin}) =>
|
|
25
|
+
withDurableExecution(
|
|
26
|
+
async (_input, durableCtx) => {
|
|
27
|
+
// Send every log line through our logger instead of the SDK's default one.
|
|
28
|
+
durableCtx.configureLogger({customLogger: runtime.logger})
|
|
29
|
+
try {
|
|
30
|
+
return await handler({
|
|
31
|
+
context,
|
|
32
|
+
event,
|
|
33
|
+
...createDurableContextParameter(durableCtx, runtime),
|
|
34
|
+
})
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// A step's error reaches the handler rebuilt from a checkpoint, without
|
|
37
|
+
// the user's stack. Remember errors thrown outside any step as they are.
|
|
38
|
+
if (!(error instanceof DurableOperationError)) runtime.lastHandlerError = error
|
|
39
|
+
throw error
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
{plugins: [eventsPlugin]},
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
export {durableHandler}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {formatArgs} from './utils.js'
|
|
2
|
+
|
|
3
|
+
const createDurableLogger = (io, RealDate) => {
|
|
4
|
+
let loggingContext
|
|
5
|
+
|
|
6
|
+
const send = (level, args, step) => {
|
|
7
|
+
const data = loggingContext?.getDurableLogData()
|
|
8
|
+
const date = new RealDate()
|
|
9
|
+
io.emit({
|
|
10
|
+
timestamp: `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`,
|
|
11
|
+
kind: 'log',
|
|
12
|
+
phase: 'log',
|
|
13
|
+
step: step ?? data?.operationName ?? null,
|
|
14
|
+
level,
|
|
15
|
+
message: formatArgs(args),
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
configureDurableLoggingContext: (context) => {
|
|
21
|
+
loggingContext = context
|
|
22
|
+
},
|
|
23
|
+
debug: (...args) => send('info', args),
|
|
24
|
+
error: (...args) => send('error', args),
|
|
25
|
+
info: (...args) => send('info', args),
|
|
26
|
+
log: (...args) => send('info', args),
|
|
27
|
+
warn: (...args) => send('warn', args),
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export {createDurableLogger}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {createRetryStrategy, JitterStrategy} from '@aws/durable-execution-sdk-js'
|
|
2
|
+
import {durationToMs} from './utils.js'
|
|
3
|
+
|
|
4
|
+
const DEFAULT_MAX_ATTEMPTS = 3
|
|
5
|
+
const DEFAULT_INITIAL_DELAY = {seconds: 5}
|
|
6
|
+
const DEFAULT_MAX_DELAY = {minutes: 5}
|
|
7
|
+
const DEFAULT_BACKOFF_RATE = 2
|
|
8
|
+
|
|
9
|
+
const retryConfig = (retry) => {
|
|
10
|
+
if (!retry) {
|
|
11
|
+
return undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS
|
|
15
|
+
|
|
16
|
+
if (retry.delay) {
|
|
17
|
+
return {
|
|
18
|
+
maxAttempts,
|
|
19
|
+
initialDelay: retry.delay,
|
|
20
|
+
maxDelay: retry.delay,
|
|
21
|
+
backoffRate: 1,
|
|
22
|
+
jitter: JitterStrategy.NONE,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
maxAttempts,
|
|
28
|
+
initialDelay: DEFAULT_INITIAL_DELAY,
|
|
29
|
+
maxDelay: DEFAULT_MAX_DELAY,
|
|
30
|
+
backoffRate: DEFAULT_BACKOFF_RATE,
|
|
31
|
+
jitter: JitterStrategy.FULL,
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const createRetryTracker = () => {
|
|
36
|
+
const steps = new Map()
|
|
37
|
+
return {
|
|
38
|
+
set: (name, maxAttempts) => steps.set(name, {maxAttempts, lastDelayMs: undefined}),
|
|
39
|
+
recordDelay: (name, delayMs) => {
|
|
40
|
+
const entry = steps.get(name)
|
|
41
|
+
if (entry) entry.lastDelayMs = delayMs
|
|
42
|
+
},
|
|
43
|
+
get: (name) => steps.get(name),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const createStepRetryStrategy = (name, retry, tracker) => {
|
|
48
|
+
const config = retryConfig(retry)
|
|
49
|
+
const awsStrategy = createRetryStrategy(config)
|
|
50
|
+
tracker.set(name, config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS)
|
|
51
|
+
|
|
52
|
+
return (error, attemptsMade) => {
|
|
53
|
+
const decision =
|
|
54
|
+
error?.name === 'UnrecoverableError' ? {shouldRetry: false} : awsStrategy(error, attemptsMade)
|
|
55
|
+
if (decision.shouldRetry) tracker.recordDelay(name, durationToMs(decision.delay))
|
|
56
|
+
return decision
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export {createRetryTracker, createStepRetryStrategy, retryConfig}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {createStepRetryStrategy} from './retry.js'
|
|
2
|
+
import {wrapLogger} from './utils.js'
|
|
3
|
+
|
|
4
|
+
export function createRunFunction(durableContext, runtime) {
|
|
5
|
+
const {retries} = runtime
|
|
6
|
+
return async ({name, handler, retry}) => {
|
|
7
|
+
const stepName = name || ''
|
|
8
|
+
/**
|
|
9
|
+
* This matches the current lambda wrapper and prod behavior. Default retry is `3` with a 5 sec backoff
|
|
10
|
+
*/
|
|
11
|
+
const stepConfig = {retryStrategy: createStepRetryStrategy(stepName, retry, retries)}
|
|
12
|
+
return await durableContext.step(
|
|
13
|
+
stepName,
|
|
14
|
+
async (stepContext) => {
|
|
15
|
+
return await handler({
|
|
16
|
+
attempt: stepContext.attempt,
|
|
17
|
+
logger: wrapLogger(stepContext),
|
|
18
|
+
})
|
|
19
|
+
},
|
|
20
|
+
stepConfig,
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {inspect} from 'node:util'
|
|
2
|
+
|
|
3
|
+
export const durationToMs = (duration = {}) => {
|
|
4
|
+
const {days = 0, hours = 0, minutes = 0, seconds = 0} = duration
|
|
5
|
+
return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Join log arguments into one message
|
|
10
|
+
*/
|
|
11
|
+
export const formatArgs = (args) =>
|
|
12
|
+
args.map((a) => (typeof a === 'string' ? a : inspect(a, {depth: null}))).join(' ')
|
|
13
|
+
|
|
14
|
+
export const wrapLogger = (ctx) => ({
|
|
15
|
+
debug: (...args) => ctx.logger.debug(...args),
|
|
16
|
+
error: (...args) => ctx.logger.error(...args),
|
|
17
|
+
info: (...args) => ctx.logger.info(...args),
|
|
18
|
+
log: (...args) => ctx.logger.info(...args),
|
|
19
|
+
warn: (...args) => ctx.logger.warn(...args),
|
|
20
|
+
})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const createWaitFunction = (durableContext) => {
|
|
2
|
+
return async ({name, duration}) => {
|
|
3
|
+
if (!duration) {
|
|
4
|
+
throw new Error('Invalid step.wait arguments! `duration` parameter is required')
|
|
5
|
+
}
|
|
6
|
+
const stepName = name || ''
|
|
7
|
+
return durableContext.wait(stepName, duration)
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export {createWaitFunction}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import {createStepRetryStrategy} from './retry.js'
|
|
2
|
+
import {wrapLogger} from './utils.js'
|
|
3
|
+
|
|
4
|
+
const createWaitForCallbackFunction = (durableContext, runtime) => {
|
|
5
|
+
return async ({name, submitter, retry, timeout}) => {
|
|
6
|
+
const stepName = name || ''
|
|
7
|
+
const {io} = runtime
|
|
8
|
+
const raw = await durableContext.waitForCallback(
|
|
9
|
+
stepName,
|
|
10
|
+
async (callbackId, ctx) => {
|
|
11
|
+
io.registerCallback({callbackId, name: stepName})
|
|
12
|
+
io.emit({name: stepName, kind: 'wait-for-callback', phase: 'waiting', callbackId})
|
|
13
|
+
|
|
14
|
+
try {
|
|
15
|
+
await submitter({callbackId, logger: wrapLogger(ctx)})
|
|
16
|
+
} catch (error) {
|
|
17
|
+
io.cancelCallback(callbackId)
|
|
18
|
+
throw error
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
timeout,
|
|
23
|
+
...(retry && {
|
|
24
|
+
retryStrategy: await createStepRetryStrategy(stepName, retry, runtime.retries),
|
|
25
|
+
}),
|
|
26
|
+
},
|
|
27
|
+
)
|
|
28
|
+
const trimmed = raw.trim()
|
|
29
|
+
if (trimmed.length && trimmed.charAt(0) === '{' && trimmed.charAt(trimmed.length - 1) === '}') {
|
|
30
|
+
return JSON.parse(trimmed)
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Matches the lambda wrapper output and prod: only JSON object results are parsed. Strings, arrays,
|
|
34
|
+
* numbers, and booleans are returned still JSON-encoded
|
|
35
|
+
*/
|
|
36
|
+
return raw
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export {createWaitForCallbackFunction}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import {wrapLogger} from './utils.js'
|
|
2
|
+
|
|
3
|
+
const createWaitForConditionFunction = (durableContext) => {
|
|
4
|
+
return async ({name, initial, next, poller}) => {
|
|
5
|
+
if (!poller || typeof poller !== 'function') {
|
|
6
|
+
throw new Error(
|
|
7
|
+
'Invalid step.waitForCondition arguments! `poller` parameter is required and must be a function',
|
|
8
|
+
)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
if (!next || typeof next !== 'function') {
|
|
12
|
+
throw new Error(
|
|
13
|
+
'Invalid step.waitForCondition arguments! `next` parameter is required and must be a function',
|
|
14
|
+
)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const waitPoller = async (state, waitContext) =>
|
|
18
|
+
poller(state, {
|
|
19
|
+
attempt: waitContext.attempt,
|
|
20
|
+
logger: wrapLogger(waitContext),
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
const waitStrategyOptions = {
|
|
24
|
+
initialState: initial,
|
|
25
|
+
waitStrategy: (state, attempt) => {
|
|
26
|
+
const result = next(state, {
|
|
27
|
+
attempt,
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
if (result.shouldRetry) {
|
|
31
|
+
return {shouldContinue: true, delay: result.delay}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {shouldContinue: false}
|
|
35
|
+
},
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return typeof name === 'string'
|
|
39
|
+
? durableContext.waitForCondition(name, waitPoller, waitStrategyOptions)
|
|
40
|
+
: durableContext.waitForCondition(waitPoller, waitStrategyOptions)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export {createWaitForConditionFunction}
|
package/oclif.manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/runtime-cli",
|
|
3
3
|
"description": "Sanity's Runtime CLI for Blueprints and Functions",
|
|
4
|
-
"version": "17.21.
|
|
4
|
+
"version": "17.21.5-next.g584ecfe",
|
|
5
5
|
"author": "Sanity Runtime Team",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"license": "MIT",
|
|
@@ -64,6 +64,8 @@
|
|
|
64
64
|
"dependencies": {
|
|
65
65
|
"@architect/hydrate": "~6.0.2",
|
|
66
66
|
"@architect/inventory": "~6.1.0",
|
|
67
|
+
"@aws/durable-execution-sdk-js": "^3.0.0",
|
|
68
|
+
"@aws/durable-execution-sdk-js-testing": "^1.3.2",
|
|
67
69
|
"@inquirer/prompts": "^8.7.5",
|
|
68
70
|
"@oclif/core": "^4.14.0",
|
|
69
71
|
"@oclif/plugin-help": "^6.3.0",
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import type {DurableContext, DurableHandler, DurableLogger, GenericEvent} from '@sanity/functions'
|
|
2
|
-
import type {DurableRuntimeEvent} from '../../types.js'
|
|
3
|
-
|
|
4
|
-
type RunDurableArgs = {
|
|
5
|
-
context: DurableContext
|
|
6
|
-
event: GenericEvent
|
|
7
|
-
logger: DurableLogger
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
type DurableIO = {
|
|
11
|
-
emit: (event: DurableRuntimeEvent) => void
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function runDurable(
|
|
15
|
-
handler: DurableHandler,
|
|
16
|
-
args: RunDurableArgs,
|
|
17
|
-
io: DurableIO,
|
|
18
|
-
): Promise<unknown>
|
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
import {randomUUID} from 'node:crypto'
|
|
2
|
-
import {performance} from 'node:perf_hooks'
|
|
3
|
-
import {inspect} from 'node:util'
|
|
4
|
-
import {getBatchResults} from './getBatchResults.js'
|
|
5
|
-
import {createStepHistory} from './step-history.js'
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
*
|
|
9
|
-
* @param duration
|
|
10
|
-
* @return {number}
|
|
11
|
-
*/
|
|
12
|
-
const durationToMs = (duration = {}) => {
|
|
13
|
-
const {days = 0, hours = 0, minutes = 0, seconds = 0} = duration
|
|
14
|
-
return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
*
|
|
19
|
-
* @param args
|
|
20
|
-
*/
|
|
21
|
-
const formatArgs = (args) =>
|
|
22
|
-
args.map((a) => (typeof a === 'string' ? a : inspect(a, {depth: null}))).join(' ')
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Runs a durable function handler
|
|
26
|
-
* @param handler - callback being run
|
|
27
|
-
* @param context - data to send to the operation
|
|
28
|
-
* @param event - the step being run
|
|
29
|
-
* @param [branchName] - the name of the branch being run
|
|
30
|
-
* @param io
|
|
31
|
-
*/
|
|
32
|
-
export async function runDurable(handler, {context, event, branchName}, io) {
|
|
33
|
-
const history = createStepHistory()
|
|
34
|
-
let currentStep = null
|
|
35
|
-
|
|
36
|
-
const streamLog = (level, args) => {
|
|
37
|
-
const date = new Date()
|
|
38
|
-
const timestamp = `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
|
|
39
|
-
|
|
40
|
-
return io.emit({
|
|
41
|
-
timestamp,
|
|
42
|
-
kind: 'log',
|
|
43
|
-
phase: 'log',
|
|
44
|
-
step: currentStep,
|
|
45
|
-
level,
|
|
46
|
-
message: formatArgs(args),
|
|
47
|
-
})
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const logger = {
|
|
51
|
-
log: (...a) => streamLog('info', a),
|
|
52
|
-
info: (...a) => streamLog('info', a),
|
|
53
|
-
warn: (...a) => streamLog('warn', a),
|
|
54
|
-
error: (...a) => streamLog('error', a),
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const emitFailure = (pending) => {
|
|
58
|
-
history.settle(pending)
|
|
59
|
-
io.emit(pending.event)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const settleUnretried = () => {
|
|
63
|
-
const pending = history.getPending()
|
|
64
|
-
if (pending !== null) {
|
|
65
|
-
emitFailure(pending)
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const track = async (name, kind, produce, retry) => {
|
|
70
|
-
settleUnretried()
|
|
71
|
-
const {index, saved} = history.nextStep()
|
|
72
|
-
|
|
73
|
-
if (saved?.phase === 'complete') {
|
|
74
|
-
return saved.output
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const maxAttempts = retry?.maxAttempts ?? 1
|
|
78
|
-
const retries = Math.max((retry?.maxAttempts ?? 1) - 1, 0)
|
|
79
|
-
const waitingOnRetry = typeof saved?.retryDelayMs === 'number'
|
|
80
|
-
|
|
81
|
-
if (saved?.phase === 'error' && !waitingOnRetry) {
|
|
82
|
-
throw saved.output
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const attempt = (saved?.attempt ?? 0) + 1
|
|
86
|
-
const prev = currentStep
|
|
87
|
-
currentStep = name
|
|
88
|
-
|
|
89
|
-
io.emit({name, kind, phase: 'start'})
|
|
90
|
-
const startedAt = performance.now()
|
|
91
|
-
|
|
92
|
-
try {
|
|
93
|
-
const value = await produce(attempt)
|
|
94
|
-
const completeEvent = {
|
|
95
|
-
name,
|
|
96
|
-
kind,
|
|
97
|
-
phase: 'complete',
|
|
98
|
-
output: value,
|
|
99
|
-
durationMs: performance.now() - startedAt,
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
history.recordSuccess(index, completeEvent)
|
|
103
|
-
io.emit(completeEvent)
|
|
104
|
-
|
|
105
|
-
return value
|
|
106
|
-
} catch (err) {
|
|
107
|
-
const errorEvent = {
|
|
108
|
-
name,
|
|
109
|
-
kind,
|
|
110
|
-
phase: 'error',
|
|
111
|
-
error: {
|
|
112
|
-
name: err?.name ?? 'Error',
|
|
113
|
-
message: err?.message ?? String(err),
|
|
114
|
-
stack: err?.stack ?? '',
|
|
115
|
-
},
|
|
116
|
-
durationMs: performance.now() - startedAt,
|
|
117
|
-
attempt,
|
|
118
|
-
retries,
|
|
119
|
-
maxAttempts,
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const retryPending = history.recordFailure(index, {
|
|
123
|
-
event: errorEvent,
|
|
124
|
-
error: err,
|
|
125
|
-
delayMs: retry?.delay ? durationToMs(retry.delay) : 0,
|
|
126
|
-
})
|
|
127
|
-
|
|
128
|
-
if (!retryPending) {
|
|
129
|
-
io.emit(errorEvent)
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
throw err
|
|
133
|
-
} finally {
|
|
134
|
-
currentStep = prev
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const FANOUT_STATUS = {
|
|
139
|
-
STARTED: 'STARTED',
|
|
140
|
-
ALL_COMPLETED: 'ALL_COMPLETED',
|
|
141
|
-
FAILURE_TOLERANCE_EXCEEDED: 'FAILURE_TOLERANCE_EXCEEDED',
|
|
142
|
-
SUCCEEDED: 'SUCCEEDED',
|
|
143
|
-
FAILED: 'FAILED',
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
const step = {
|
|
147
|
-
run: ({name, handler: fn, retry}) =>
|
|
148
|
-
track(name || '', 'run', (attempt) => fn({logger, attempt}), retry),
|
|
149
|
-
delegate: ({name, handler, event, retry}) =>
|
|
150
|
-
track(
|
|
151
|
-
name || '',
|
|
152
|
-
'delegate',
|
|
153
|
-
() => {
|
|
154
|
-
const fn = typeof handler === 'string' ? handler : handler?.name
|
|
155
|
-
if (!fn) {
|
|
156
|
-
throw new Error('No function name provided for delegation')
|
|
157
|
-
}
|
|
158
|
-
return io.invoke(fn, event?.data ?? {})
|
|
159
|
-
},
|
|
160
|
-
retry,
|
|
161
|
-
),
|
|
162
|
-
fanout: async ({name, branches}) => {
|
|
163
|
-
if (
|
|
164
|
-
!Array.isArray(branches) ||
|
|
165
|
-
Array.from(branches).some((branch) => typeof branch !== 'function')
|
|
166
|
-
) {
|
|
167
|
-
throw new TypeError('fanout branches must be an array of functions')
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
const outcomes = branches.map((_, index) => ({index, status: FANOUT_STATUS.STARTED}))
|
|
171
|
-
return new Promise((resolve, reject) => {
|
|
172
|
-
const execs = branches.map(async (branch, index) => {
|
|
173
|
-
try {
|
|
174
|
-
const branchName = `${name || 'fanout'} / branch ${index}`
|
|
175
|
-
const result = await runDurable(branch, {context, event, branchName}, io)
|
|
176
|
-
outcomes[index] = {index, status: FANOUT_STATUS.SUCCEEDED, result}
|
|
177
|
-
} catch (err) {
|
|
178
|
-
const error = err instanceof Error ? err : new Error(String(err))
|
|
179
|
-
outcomes[index] = {index, status: FANOUT_STATUS.FAILED, error}
|
|
180
|
-
}
|
|
181
|
-
})
|
|
182
|
-
|
|
183
|
-
Promise.allSettled(execs)
|
|
184
|
-
.then(() => {
|
|
185
|
-
resolve(getBatchResults(outcomes, FANOUT_STATUS.ALL_COMPLETED))
|
|
186
|
-
})
|
|
187
|
-
.catch(() => {
|
|
188
|
-
reject(reject)
|
|
189
|
-
})
|
|
190
|
-
})
|
|
191
|
-
},
|
|
192
|
-
waitForCondition: ({name, initial, poller, next}) =>
|
|
193
|
-
track(name || '', 'wait-for-condition', async () => {
|
|
194
|
-
let state = initial
|
|
195
|
-
let attempt = 1
|
|
196
|
-
let polling = true
|
|
197
|
-
while (polling) {
|
|
198
|
-
state = await poller(state, {logger, attempt})
|
|
199
|
-
const decision = next(state, {attempt})
|
|
200
|
-
if (decision.shouldRetry) {
|
|
201
|
-
await io.wait(durationToMs(decision.delay))
|
|
202
|
-
attempt += 1
|
|
203
|
-
} else {
|
|
204
|
-
polling = false
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
return state
|
|
208
|
-
}),
|
|
209
|
-
waitForCallback: ({name, submitter, timeout, retry}) => {
|
|
210
|
-
return track(
|
|
211
|
-
name || '',
|
|
212
|
-
'wait-for-callback',
|
|
213
|
-
async () => {
|
|
214
|
-
const callbackId = randomUUID()
|
|
215
|
-
const result = io.registerCallback({
|
|
216
|
-
callbackId,
|
|
217
|
-
name,
|
|
218
|
-
timeout: durationToMs(timeout),
|
|
219
|
-
})
|
|
220
|
-
io.emit({name, kind: 'wait-for-callback', phase: 'waiting', callbackId})
|
|
221
|
-
try {
|
|
222
|
-
await submitter({callbackId, logger})
|
|
223
|
-
} catch (err) {
|
|
224
|
-
io.cancelCallback(callbackId)
|
|
225
|
-
throw err
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
return await result
|
|
229
|
-
},
|
|
230
|
-
retry,
|
|
231
|
-
)
|
|
232
|
-
},
|
|
233
|
-
wait: ({name, duration}) =>
|
|
234
|
-
track(name || '', 'wait', async () => {
|
|
235
|
-
await io.wait(durationToMs(duration))
|
|
236
|
-
return undefined
|
|
237
|
-
}),
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
let result
|
|
241
|
-
let done = false
|
|
242
|
-
const handlerArgs = branchName !== undefined ? {step, logger} : {context, event, step, logger}
|
|
243
|
-
while (!done) {
|
|
244
|
-
history.startRun()
|
|
245
|
-
try {
|
|
246
|
-
result = await handler(handlerArgs)
|
|
247
|
-
settleUnretried()
|
|
248
|
-
done = true
|
|
249
|
-
} catch (err) {
|
|
250
|
-
const pending = history.getPending()
|
|
251
|
-
if (pending === null) {
|
|
252
|
-
throw err
|
|
253
|
-
}
|
|
254
|
-
if (err?.name === 'UnrecoverableError') {
|
|
255
|
-
emitFailure(pending)
|
|
256
|
-
throw err
|
|
257
|
-
}
|
|
258
|
-
io.emit({...pending.event, retryDelayMs: pending.delayMs})
|
|
259
|
-
await io.wait(pending.delayMs)
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
return result
|
|
264
|
-
}
|