@sanity/runtime-cli 17.21.3 → 17.21.4-next.g63b83f1

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.
Files changed (30) hide show
  1. package/README.md +20 -20
  2. package/dist/commands/blueprints/destroy.js +1 -1
  3. package/dist/cores/blueprints/destroy.js +8 -4
  4. package/dist/cores/functions/test.js +2 -3
  5. package/dist/utils/bundles/stamp-config-version.js +8 -27
  6. package/dist/utils/functions/child-process-wrapper.js +15 -4
  7. package/dist/utils/functions/child-runtime/callback.d.ts +10 -10
  8. package/dist/utils/functions/child-runtime/callback.js +4 -29
  9. package/dist/utils/functions/child-runtime/durables/delegate.js +44 -0
  10. package/dist/utils/functions/child-runtime/durables/durable.d.ts +29 -0
  11. package/dist/utils/functions/child-runtime/durables/durable.js +91 -0
  12. package/dist/utils/functions/child-runtime/durables/eventsFactoryPlugin.js +171 -0
  13. package/dist/utils/functions/child-runtime/durables/fanout.js +24 -0
  14. package/dist/utils/functions/child-runtime/durables/index.js +45 -0
  15. package/dist/utils/functions/child-runtime/durables/logger.js +31 -0
  16. package/dist/utils/functions/child-runtime/durables/retry.js +60 -0
  17. package/dist/utils/functions/child-runtime/durables/run.js +23 -0
  18. package/dist/utils/functions/child-runtime/durables/utils.js +20 -0
  19. package/dist/utils/functions/child-runtime/durables/wait.js +11 -0
  20. package/dist/utils/functions/child-runtime/durables/waitForCallback.js +40 -0
  21. package/dist/utils/functions/child-runtime/durables/waitForCondition.js +44 -0
  22. package/oclif.manifest.json +2 -2
  23. package/package.json +4 -2
  24. package/skills/blueprints-destroy.md +1 -1
  25. package/dist/utils/functions/child-runtime/durable.d.ts +0 -18
  26. package/dist/utils/functions/child-runtime/durable.js +0 -264
  27. package/dist/utils/functions/child-runtime/getBatchResults.d.ts +0 -6
  28. package/dist/utils/functions/child-runtime/getBatchResults.js +0 -74
  29. package/dist/utils/functions/child-runtime/step-history.d.ts +0 -15
  30. package/dist/utils/functions/child-runtime/step-history.js +0 -52
@@ -0,0 +1,171 @@
1
+ // SDK to Sanity mapping
2
+ const KINDS = {
3
+ 'STEP/Step': 'run',
4
+ 'STEP/WaitForCondition': 'wait-for-condition',
5
+ 'WAIT/Wait': 'wait',
6
+ 'CHAINED_INVOKE/ChainedInvoke': 'delegate',
7
+ 'CONTEXT/RunInChildContext': 'delegate',
8
+ 'CONTEXT/WaitForCallback': 'wait-for-callback',
9
+ }
10
+
11
+ const HAS_INTERNAL_CHILDREN = new Set(['CONTEXT/RunInChildContext', 'CONTEXT/WaitForCallback'])
12
+
13
+ const kindOf = (info) => KINDS[`${info.type}/${info.subType}`]
14
+
15
+ const parseResult = (result) => {
16
+ if (result === undefined) return undefined
17
+ try {
18
+ return JSON.parse(result)
19
+ } catch {
20
+ return result
21
+ }
22
+ }
23
+
24
+ const toEventError = (error) => ({
25
+ name: error?.name ?? 'Error',
26
+ message: error?.message ?? String(error),
27
+ stack: error?.stack ?? '',
28
+ })
29
+
30
+ export const createEventsFactoryPlugin = ({io, realNow, retries, callbackOperationIds}) => {
31
+ const startedAt = new Map()
32
+ const internalParents = new Set()
33
+ const delegateAttempts = new Map()
34
+ let lastFailedStepError
35
+
36
+ const isInternal = (info) => internalParents.has(info.parentId)
37
+ const duration = (info) =>
38
+ startedAt.has(info.id) ? realNow() - startedAt.get(info.id) : undefined
39
+
40
+ const sendStart = (info, phase) => {
41
+ startedAt.set(info.id, realNow())
42
+ io.emit({name: info.name || '', kind: kindOf(info), phase})
43
+ }
44
+
45
+ const sendComplete = (info) => {
46
+ io.emit({
47
+ name: info.name || '',
48
+ kind: kindOf(info),
49
+ phase: 'complete',
50
+ output: parseResult(info.result),
51
+ durationMs: duration(info),
52
+ })
53
+ }
54
+
55
+ const sendError = (
56
+ info,
57
+ {
58
+ stepName = info.name || '',
59
+ kind = kindOf(info),
60
+ attempt = info.attempt,
61
+ willRetry = false,
62
+ } = {},
63
+ ) => {
64
+ const retry = retries.get(stepName)
65
+ const maxAttempts = retry?.maxAttempts ?? 1
66
+ if (!willRetry) lastFailedStepError = info.error
67
+ io.emit({
68
+ name: stepName,
69
+ kind,
70
+ phase: 'error',
71
+ error: toEventError(info.error),
72
+ durationMs: duration(info),
73
+ attempt,
74
+ maxAttempts,
75
+ retries: maxAttempts - 1,
76
+ ...(willRetry && {retryDelayMs: retry?.lastDelayMs}),
77
+ })
78
+ }
79
+
80
+ const hooks = {
81
+ onOperationStart(info) {
82
+ const key = `${info.type}/${info.subType}`
83
+ if (HAS_INTERNAL_CHILDREN.has(key)) {
84
+ internalParents.add(info.id)
85
+ }
86
+
87
+ if (key === 'CONTEXT/RunInChildContext' && !delegateAttempts.has(info.id)) {
88
+ delegateAttempts.set(info.id, {name: info.name || '', count: 0})
89
+ }
90
+
91
+ if (info.type === 'CALLBACK') {
92
+ callbackOperationIds.add(info.id)
93
+ }
94
+
95
+ if (info.isReplay) return
96
+
97
+ const delegate = delegateAttempts.get(info.parentId)
98
+ if (delegate && info.type === 'WAIT') {
99
+ sendError(
100
+ {error: delegate.lastError},
101
+ {stepName: delegate.name, kind: 'delegate', attempt: delegate.count, willRetry: true},
102
+ )
103
+ return
104
+ }
105
+
106
+ if (isInternal(info)) return
107
+
108
+ switch (key) {
109
+ case 'WAIT/Wait':
110
+ sendStart(info, 'waiting')
111
+ break
112
+ case 'STEP/WaitForCondition':
113
+ sendStart(info, 'start')
114
+ io.emit({name: info.name || '', kind: 'wait', phase: 'waiting'})
115
+ break
116
+ case 'CHAINED_INVOKE/ChainedInvoke':
117
+ case 'CONTEXT/RunInChildContext':
118
+ case 'CONTEXT/WaitForCallback':
119
+ sendStart(info, 'start')
120
+ break
121
+ }
122
+ },
123
+
124
+ onOperationAttemptStart(info) {
125
+ if (info.isReplay || isInternal(info)) return
126
+ if (kindOf(info) === 'run') sendStart(info, 'start')
127
+ },
128
+
129
+ onOperationAttemptEnd(info) {
130
+ if (info.isReplay || isInternal(info)) return
131
+
132
+ const kind = kindOf(info)
133
+ if (kind !== 'run' && kind !== 'wait-for-condition') return
134
+
135
+ if (info.status === 'SUCCEEDED') {
136
+ sendComplete(info)
137
+ } else if (info.outcome === 'FAILED' && info.status === 'PENDING') {
138
+ sendError(info, {willRetry: true})
139
+ } else if (info.status === 'FAILED') {
140
+ sendError(info)
141
+ }
142
+ },
143
+
144
+ onOperationEnd(info) {
145
+ const delegate = delegateAttempts.get(info.parentId)
146
+ if (delegate && info.type === 'CHAINED_INVOKE') {
147
+ if (!info.isReplay && info.status === 'FAILED') {
148
+ delegate.count += 1
149
+ delegate.lastError = info.error
150
+ }
151
+ return
152
+ }
153
+
154
+ if (info.isReplay || isInternal(info)) return
155
+
156
+ const kind = kindOf(info)
157
+ if (kind !== 'wait' && kind !== 'delegate' && kind !== 'wait-for-callback') return
158
+
159
+ if (info.status === 'FAILED' || info.status === 'TIMED_OUT') {
160
+ sendError(info, {attempt: undefined})
161
+ } else {
162
+ sendComplete(info)
163
+ }
164
+ },
165
+ }
166
+
167
+ return {
168
+ createPlugin: () => hooks,
169
+ lastFailedStepError: () => lastFailedStepError,
170
+ }
171
+ }
@@ -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}
@@ -536,7 +536,7 @@
536
536
  "blueprints:destroy": {
537
537
  "aliases": [],
538
538
  "args": {},
539
- "description": "Permanently removes the remote Stack and all its provisioned resources. Your Blueprint manifest and resource files remain intact; \"stackId\" is unset in your local config.\n\nThis is a destructive operation. You will be prompted to confirm unless --force is specified.\n\nUse this to clean up test environments or decommission a Stack you no longer need.\n\nExit codes: 0 destroyed, 2 destruction failed, 75 destruction accepted but completion could not be confirmed (rerun 'blueprints info' to check).",
539
+ "description": "Permanently removes the remote Stack and all its provisioned resources. Your Blueprint manifest and resource files remain intact; \"stackId\" is unset in your local config once destruction completes (or immediately with --no-wait).\n\nThis is a destructive operation. You will be prompted to confirm unless --force is specified.\n\nUse this to clean up test environments or decommission a Stack you no longer need.\n\nExit codes: 0 destroyed, 2 destruction failed, 75 destruction accepted but completion could not be confirmed (rerun 'blueprints info' to check).",
540
540
  "examples": [
541
541
  "<%= config.bin %> <%= command.id %>",
542
542
  "<%= config.bin %> <%= command.id %> --stack <name-or-id> --project-id <projectId> --force --no-wait"
@@ -3150,5 +3150,5 @@
3150
3150
  ]
3151
3151
  }
3152
3152
  },
3153
- "version": "17.21.3"
3153
+ "version": "17.21.4-next.g63b83f1"
3154
3154
  }
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.3",
4
+ "version": "17.21.4-next.g63b83f1",
5
5
  "author": "Sanity Runtime Team",
6
6
  "type": "module",
7
7
  "license": "MIT",
@@ -64,11 +64,13 @@
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",
70
72
  "@sanity-labs/oclif-plugin-skills-flag": "^0.2.1",
71
- "@sanity/blueprints": "^0.33.0",
73
+ "@sanity/blueprints": "^0.34.0",
72
74
  "@sanity/blueprints-parser": "^0.5.0",
73
75
  "@sanity/cli-build": "^7.1.1",
74
76
  "@sanity/cli-core": "^3.14.1",
@@ -1,6 +1,6 @@
1
1
  # `npx @sanity/cli blueprints destroy`
2
2
 
3
- Permanently destroy a remote Stack and its provisioned resources. The local Blueprint manifest and resource files remain, and a matching local Stack ID is cleared from `.sanity/blueprint.config.json`.
3
+ Permanently destroy a remote Stack and its provisioned resources. The local Blueprint manifest and resource files remain. A matching local Stack ID is cleared from `.sanity/blueprint.config.json` once destruction completes, or immediately with `--no-wait`. If destruction fails or cannot be confirmed, the Stack ID is kept.
4
4
 
5
5
  ## Required safety checks
6
6
 
@@ -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>