@sanity/runtime-cli 17.20.1 → 17.21.0-next.g420037d
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/constants.js +1 -0
- package/dist/cores/functions/env/list.js +8 -3
- package/dist/cores/functions/test.js +18 -14
- package/dist/utils/agents/build-package.d.ts +18 -7
- package/dist/utils/agents/build-package.js +80 -27
- package/dist/utils/agents/prepare-asset.d.ts +18 -4
- package/dist/utils/agents/prepare-asset.js +20 -10
- package/dist/utils/functions/callback/routes.d.ts +10 -0
- package/dist/utils/functions/callback/routes.js +34 -0
- package/dist/utils/functions/child-process-wrapper.js +17 -1
- package/dist/utils/functions/child-runtime/callback.d.ts +15 -0
- package/dist/utils/functions/child-runtime/callback.js +152 -0
- package/dist/utils/functions/child-runtime/durable.js +25 -0
- package/dist/utils/functions/child-runtime/getBatchResults.d.ts +6 -0
- package/dist/utils/functions/child-runtime/getBatchResults.js +1 -2
- package/dist/utils/functions/child-runtime/step-history.d.ts +1 -1
- package/dist/utils/functions/durable-logs.js +5 -0
- package/dist/utils/functions/invoke/local.js +79 -2
- package/dist/utils/functions/invoke/nested.js +2 -1
- package/dist/utils/types.d.ts +42 -2
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -90,7 +90,7 @@ EXAMPLES
|
|
|
90
90
|
$ sanity-run blueprints add function --name my-function --fn-type document-create --fn-type document-update --lang js
|
|
91
91
|
```
|
|
92
92
|
|
|
93
|
-
_See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
93
|
+
_See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/add.ts)_
|
|
94
94
|
|
|
95
95
|
## `sanity-run blueprints config`
|
|
96
96
|
|
|
@@ -127,7 +127,7 @@ EXAMPLES
|
|
|
127
127
|
$ sanity-run blueprints config --edit --project-id <projectId> --stack <name-or-id>
|
|
128
128
|
```
|
|
129
129
|
|
|
130
|
-
_See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
130
|
+
_See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/config.ts)_
|
|
131
131
|
|
|
132
132
|
## `sanity-run blueprints deploy`
|
|
133
133
|
|
|
@@ -183,7 +183,7 @@ EXAMPLES
|
|
|
183
183
|
$ sanity-run blueprints deploy --new-stack-name <new-name>
|
|
184
184
|
```
|
|
185
185
|
|
|
186
|
-
_See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
186
|
+
_See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/deploy.ts)_
|
|
187
187
|
|
|
188
188
|
## `sanity-run blueprints destroy`
|
|
189
189
|
|
|
@@ -221,7 +221,7 @@ EXAMPLES
|
|
|
221
221
|
$ sanity-run blueprints destroy --stack <name-or-id> --project-id <projectId> --force --no-wait
|
|
222
222
|
```
|
|
223
223
|
|
|
224
|
-
_See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
224
|
+
_See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/destroy.ts)_
|
|
225
225
|
|
|
226
226
|
## `sanity-run blueprints doctor`
|
|
227
227
|
|
|
@@ -253,7 +253,7 @@ EXAMPLES
|
|
|
253
253
|
$ sanity-run blueprints doctor --fix
|
|
254
254
|
```
|
|
255
255
|
|
|
256
|
-
_See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
256
|
+
_See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/doctor.ts)_
|
|
257
257
|
|
|
258
258
|
## `sanity-run blueprints info`
|
|
259
259
|
|
|
@@ -291,7 +291,7 @@ EXAMPLES
|
|
|
291
291
|
$ sanity-run blueprints info --organization-id <orgId> --stack <name-or-id>
|
|
292
292
|
```
|
|
293
293
|
|
|
294
|
-
_See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
294
|
+
_See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/info.ts)_
|
|
295
295
|
|
|
296
296
|
## `sanity-run blueprints init [DIR]`
|
|
297
297
|
|
|
@@ -355,7 +355,7 @@ EXAMPLES
|
|
|
355
355
|
$ sanity-run blueprints init old-stack --type <json|js|ts> --project-id <projectId> --stack-id <existingStackId>
|
|
356
356
|
```
|
|
357
357
|
|
|
358
|
-
_See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
358
|
+
_See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/init.ts)_
|
|
359
359
|
|
|
360
360
|
## `sanity-run blueprints logs`
|
|
361
361
|
|
|
@@ -401,7 +401,7 @@ EXAMPLES
|
|
|
401
401
|
$ sanity-run blueprints logs --before 2026-05-01T00:00:00Z
|
|
402
402
|
```
|
|
403
403
|
|
|
404
|
-
_See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
404
|
+
_See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/logs.ts)_
|
|
405
405
|
|
|
406
406
|
## `sanity-run blueprints mint-deploy-token`
|
|
407
407
|
|
|
@@ -446,7 +446,7 @@ EXAMPLES
|
|
|
446
446
|
$ sanity-run blueprints mint-deploy-token --organization-id <orgId>
|
|
447
447
|
```
|
|
448
448
|
|
|
449
|
-
_See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
449
|
+
_See code: [src/commands/blueprints/mint-deploy-token.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/mint-deploy-token.ts)_
|
|
450
450
|
|
|
451
451
|
## `sanity-run blueprints plan`
|
|
452
452
|
|
|
@@ -479,7 +479,7 @@ EXAMPLES
|
|
|
479
479
|
$ sanity-run blueprints plan --organization-id <orgId> --stack <name-or-id>
|
|
480
480
|
```
|
|
481
481
|
|
|
482
|
-
_See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
482
|
+
_See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/plan.ts)_
|
|
483
483
|
|
|
484
484
|
## `sanity-run blueprints promote`
|
|
485
485
|
|
|
@@ -515,7 +515,7 @@ EXAMPLES
|
|
|
515
515
|
$ sanity-run blueprints promote --new-stack-name <new-name>
|
|
516
516
|
```
|
|
517
517
|
|
|
518
|
-
_See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
518
|
+
_See code: [src/commands/blueprints/promote.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/promote.ts)_
|
|
519
519
|
|
|
520
520
|
## `sanity-run blueprints stacks`
|
|
521
521
|
|
|
@@ -556,7 +556,7 @@ EXAMPLES
|
|
|
556
556
|
$ sanity-run blueprints stacks --organization-id <organizationId> --include-projects
|
|
557
557
|
```
|
|
558
558
|
|
|
559
|
-
_See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
559
|
+
_See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/blueprints/stacks.ts)_
|
|
560
560
|
|
|
561
561
|
## `sanity-run functions add`
|
|
562
562
|
|
|
@@ -608,7 +608,7 @@ EXAMPLES
|
|
|
608
608
|
$ sanity-run functions add --name my-function --type document-create --type document-update --lang js
|
|
609
609
|
```
|
|
610
610
|
|
|
611
|
-
_See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
611
|
+
_See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/add.ts)_
|
|
612
612
|
|
|
613
613
|
## `sanity-run functions dev`
|
|
614
614
|
|
|
@@ -643,7 +643,7 @@ EXAMPLES
|
|
|
643
643
|
$ sanity-run functions dev --timeout 60
|
|
644
644
|
```
|
|
645
645
|
|
|
646
|
-
_See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
646
|
+
_See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/dev.ts)_
|
|
647
647
|
|
|
648
648
|
## `sanity-run functions env add NAME KEY VALUE`
|
|
649
649
|
|
|
@@ -676,7 +676,7 @@ EXAMPLES
|
|
|
676
676
|
$ sanity-run functions env add --stack <name-or-id> MyFunction API_URL https://api.example.com/
|
|
677
677
|
```
|
|
678
678
|
|
|
679
|
-
_See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
679
|
+
_See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/env/add.ts)_
|
|
680
680
|
|
|
681
681
|
## `sanity-run functions env list NAME`
|
|
682
682
|
|
|
@@ -706,7 +706,7 @@ EXAMPLES
|
|
|
706
706
|
$ sanity-run functions env list --stack <name-or-id> MyFunction
|
|
707
707
|
```
|
|
708
708
|
|
|
709
|
-
_See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
709
|
+
_See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/env/list.ts)_
|
|
710
710
|
|
|
711
711
|
## `sanity-run functions env remove NAME KEY`
|
|
712
712
|
|
|
@@ -738,7 +738,7 @@ EXAMPLES
|
|
|
738
738
|
$ sanity-run functions env remove --stack <name-or-id> MyFunction API_URL
|
|
739
739
|
```
|
|
740
740
|
|
|
741
|
-
_See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
741
|
+
_See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/env/remove.ts)_
|
|
742
742
|
|
|
743
743
|
## `sanity-run functions logs [NAME]`
|
|
744
744
|
|
|
@@ -778,7 +778,7 @@ EXAMPLES
|
|
|
778
778
|
$ sanity-run functions logs <name> --delete
|
|
779
779
|
```
|
|
780
780
|
|
|
781
|
-
_See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
781
|
+
_See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/logs.ts)_
|
|
782
782
|
|
|
783
783
|
## `sanity-run functions test [NAME]`
|
|
784
784
|
|
|
@@ -836,7 +836,7 @@ EXAMPLES
|
|
|
836
836
|
$ sanity-run functions test <name> --event update --data-before '{ "title": "before" }' --data-after '{ "title": "after" }'
|
|
837
837
|
```
|
|
838
838
|
|
|
839
|
-
_See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.
|
|
839
|
+
_See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v17.21.0-next.g420037d/src/commands/functions/test.ts)_
|
|
840
840
|
|
|
841
841
|
## `sanity-run help [COMMAND]`
|
|
842
842
|
|
package/dist/constants.js
CHANGED
|
@@ -12,9 +12,14 @@ export async function functionEnvListCore(options) {
|
|
|
12
12
|
spinner.stop();
|
|
13
13
|
return { success: false, error: result.error || 'Unknown error' };
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
if (result.envvars.length > 0) {
|
|
16
|
+
spinner.succeed(`Environment variables for "${args.name}"`);
|
|
17
|
+
for (const key of result.envvars) {
|
|
18
|
+
options.log(key);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
spinner.succeed(`"${args.name}" has no configured environment variables`);
|
|
18
23
|
}
|
|
19
24
|
return { success: true, json: { name: args.name, envvars: result.envvars } };
|
|
20
25
|
}
|
|
@@ -3,6 +3,7 @@ import { testAction } from '../../actions/functions/test.js';
|
|
|
3
3
|
import config from '../../config.js';
|
|
4
4
|
import { SANITY_FUNCTION_DURABLE, STEP_PHASE_GLYPH } from '../../constants.js';
|
|
5
5
|
import { resolveDeployedResources } from '../../utils/blueprints/resolve-deployed-resources.js';
|
|
6
|
+
import { createCallbackRoutes } from '../../utils/functions/callback/routes.js';
|
|
6
7
|
import { createDurableJsonCollector } from '../../utils/functions/durable-logs.js';
|
|
7
8
|
import { findFunctionInResources, getFunctionNames } from '../../utils/functions/find.js';
|
|
8
9
|
import { runFunction } from '../../utils/functions/invoke/nested.js';
|
|
@@ -66,19 +67,18 @@ export async function functionTestCore(options) {
|
|
|
66
67
|
// Records each nested context.invoke() so they can be surfaced in order after the spinner resolves.
|
|
67
68
|
const nestedRuns = [];
|
|
68
69
|
let nestedOrder = 0;
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
durableJson.record(event);
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
for (const line of renderStepTimeline([event])) {
|
|
77
|
-
if (line !== null)
|
|
78
|
-
log(line);
|
|
79
|
-
}
|
|
70
|
+
const handlerStepEvent = async (event) => {
|
|
71
|
+
if (flags.json) {
|
|
72
|
+
durableJson.record(event);
|
|
73
|
+
return;
|
|
80
74
|
}
|
|
81
|
-
|
|
75
|
+
for (const line of renderStepTimeline([event])) {
|
|
76
|
+
if (line !== null)
|
|
77
|
+
log(line);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const durableJson = createDurableJsonCollector();
|
|
81
|
+
const onStepEvent = plan.isDurable ? handlerStepEvent : undefined;
|
|
82
82
|
/**
|
|
83
83
|
* Re-entrant callback that resolves a nested context.invoke(name, payload):
|
|
84
84
|
* it finds the named function in the same blueprint, reuses the already
|
|
@@ -96,9 +96,11 @@ export async function functionTestCore(options) {
|
|
|
96
96
|
log(`↳ BEGIN: invoke('${nestedName}')`);
|
|
97
97
|
}
|
|
98
98
|
try {
|
|
99
|
-
const result = await runFunction(nestedResource, { payload: nestedPayload, event: 'nested' }, { ...ctx, resources: resolvedResources }, { depth, callStack, onNestedInvoke: runNested, onStepEvent });
|
|
100
|
-
if (result.error && isLiveDurable) {
|
|
99
|
+
const result = await runFunction(nestedResource, { payload: nestedPayload, event: 'nested' }, { ...ctx, resources: resolvedResources }, { depth, callStack, onNestedInvoke: runNested, onStepEvent, callbackRoutes });
|
|
100
|
+
if (result.error && (isLiveDurable || plan.isDurable)) {
|
|
101
101
|
log(result.error.stack || result.error.message);
|
|
102
|
+
// if an error occurs in a nested durable function, we want to fail the callback so the parent durable function can handle it
|
|
103
|
+
callbackRoutes.fail(result.error);
|
|
102
104
|
}
|
|
103
105
|
nestedRuns.push({
|
|
104
106
|
order,
|
|
@@ -173,6 +175,7 @@ export async function functionTestCore(options) {
|
|
|
173
175
|
}
|
|
174
176
|
return lines;
|
|
175
177
|
}
|
|
178
|
+
const callbackRoutes = createCallbackRoutes();
|
|
176
179
|
const spinner = log.ora('Executing function...').start();
|
|
177
180
|
const { json: response, logs, error, } = await testAction(resource, invokeOptions, context, {
|
|
178
181
|
timeout: timeout ? timeout : resource.timeout,
|
|
@@ -181,6 +184,7 @@ export async function functionTestCore(options) {
|
|
|
181
184
|
callStack: [fnName],
|
|
182
185
|
onStepEvent,
|
|
183
186
|
noWait,
|
|
187
|
+
callbackRoutes,
|
|
184
188
|
});
|
|
185
189
|
if (error) {
|
|
186
190
|
spinner.fail('Function execution failed.');
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import AdmZip from 'adm-zip';
|
|
2
2
|
import type { AgentResource } from '../types.js';
|
|
3
|
-
/** `sanityID`
|
|
3
|
+
/** The platform manifest gate requires `sanityID` to be exactly 36 characters. */
|
|
4
4
|
export declare const SANITY_ID_LENGTH = 36;
|
|
5
5
|
/** The manifest written to `package.json` at the bundle root. */
|
|
6
6
|
export interface AgentManifest {
|
|
@@ -9,14 +9,25 @@ export interface AgentManifest {
|
|
|
9
9
|
description?: string;
|
|
10
10
|
region: string;
|
|
11
11
|
}
|
|
12
|
-
/** Derive
|
|
12
|
+
/** Derive a stable 36-char `sanityID` from the project scope id (UUID-shaped hash). */
|
|
13
13
|
export declare function deriveSanityId(scopeId: string): string;
|
|
14
14
|
/** Build the manifest from the resource and project scope. */
|
|
15
15
|
export declare function buildAgentManifest(resource: AgentResource, scopeId: string): AgentManifest;
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* the
|
|
17
|
+
* Run `eve build` and return the produced `.output` dir. Runs with `cwd` set to
|
|
18
|
+
* the agent src since eve builds a single agent from its own directory. Output
|
|
19
|
+
* is captured, not inherited, so it does not clobber the caller's spinner or
|
|
20
|
+
* --json output; the captured output is surfaced in the error on failure.
|
|
21
21
|
*/
|
|
22
|
-
export
|
|
22
|
+
export type EveBuildRunner = (agentPath: string) => Promise<string>;
|
|
23
|
+
/** Seam so tests can supply a fixture `.output` instead of a real build. */
|
|
24
|
+
export declare const eveBuild: {
|
|
25
|
+
run: EveBuildRunner;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Assemble the Web Function bundle for a `sanity.agent` resource: a runnable
|
|
29
|
+
* root `index.mjs` bootstrap, eve's built node-server under `.output/`, and the
|
|
30
|
+
* root `package.json` manifest. Asset prep is the sole producer; the Provider
|
|
31
|
+
* only reads the bytes, so the layout is complete here.
|
|
32
|
+
*/
|
|
33
|
+
export declare function buildAgentPackage(agentPath: string, manifest: AgentManifest, build?: EveBuildRunner): Promise<AdmZip>;
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
1
2
|
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import path from 'node:path';
|
|
2
6
|
import AdmZip from 'adm-zip';
|
|
3
|
-
/** `sanityID`
|
|
7
|
+
/** The platform manifest gate requires `sanityID` to be exactly 36 characters. */
|
|
4
8
|
export const SANITY_ID_LENGTH = 36;
|
|
5
|
-
/** Derive
|
|
9
|
+
/** Derive a stable 36-char `sanityID` from the project scope id (UUID-shaped hash). */
|
|
6
10
|
export function deriveSanityId(scopeId) {
|
|
7
11
|
const hex = crypto.createHash('sha256').update(scopeId).digest('hex');
|
|
8
12
|
return [
|
|
@@ -25,36 +29,85 @@ export function buildAgentManifest(resource, scopeId) {
|
|
|
25
29
|
}
|
|
26
30
|
return manifest;
|
|
27
31
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
//
|
|
31
|
-
|
|
32
|
+
// The Web Function runtime loads this root index.mjs and expects an HTTP
|
|
33
|
+
// listener on AWS_LAMBDA_HTTP_ENDPOINT. eve's node-server reads HOST/NITRO_HOST/
|
|
34
|
+
// PORT/NITRO_PORT, so map the endpoint onto those before importing the server.
|
|
35
|
+
// Only /tmp is writable, so ensure EVE_DATA_ROOT exists.
|
|
36
|
+
const WEB_FUNCTION_ENTRY = `import {mkdirSync} from 'node:fs'
|
|
37
|
+
const endpoint = process.env.AWS_LAMBDA_HTTP_ENDPOINT || '0.0.0.0:3000'
|
|
38
|
+
const sep = endpoint.lastIndexOf(':')
|
|
39
|
+
const host = sep > 0 ? endpoint.slice(0, sep).replace(/^\\[|\\]$/g, '') : '0.0.0.0'
|
|
40
|
+
const port = sep > 0 ? endpoint.slice(sep + 1) : '3000'
|
|
41
|
+
process.env.HOST = host
|
|
42
|
+
process.env.NITRO_HOST = host
|
|
43
|
+
process.env.PORT = port
|
|
44
|
+
process.env.NITRO_PORT = port
|
|
45
|
+
const dataRoot = process.env.EVE_DATA_ROOT || '/tmp/eve-data'
|
|
46
|
+
process.env.EVE_DATA_ROOT = dataRoot
|
|
47
|
+
mkdirSync(dataRoot, {recursive: true})
|
|
48
|
+
await import('./.output/server/index.mjs')
|
|
32
49
|
`;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
50
|
+
// Resolve the eve CLI from the agent's own install so its pinned version runs.
|
|
51
|
+
// eve's exports map blocks the bin subpath, so resolve its package.json and read
|
|
52
|
+
// the bin field rather than require.resolve('eve/bin/eve.js').
|
|
53
|
+
function resolveEveBin(agentPath) {
|
|
54
|
+
const require = createRequire(path.join(agentPath, 'noop.js'));
|
|
55
|
+
try {
|
|
56
|
+
const pkgPath = require.resolve('eve/package.json');
|
|
57
|
+
const pkg = require('eve/package.json');
|
|
58
|
+
const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.eve;
|
|
59
|
+
if (!bin)
|
|
60
|
+
throw new Error('eve package has no bin entry');
|
|
61
|
+
return path.join(path.dirname(pkgPath), bin);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new Error(`eve is not installed for the agent at ${agentPath}. ` +
|
|
65
|
+
'Run `npm install` in the agent project so `eve build` can run.');
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function runEveBuild(agentPath) {
|
|
69
|
+
const eveBin = resolveEveBin(agentPath);
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
const child = spawn(process.execPath, [eveBin, 'build'], { cwd: agentPath });
|
|
72
|
+
let output = '';
|
|
73
|
+
child.stdout?.on('data', (d) => {
|
|
74
|
+
output += d;
|
|
75
|
+
});
|
|
76
|
+
child.stderr?.on('data', (d) => {
|
|
77
|
+
output += d;
|
|
78
|
+
});
|
|
79
|
+
child.on('error', reject);
|
|
80
|
+
child.on('close', (code) => {
|
|
81
|
+
if (code !== 0) {
|
|
82
|
+
reject(new Error(`eve build failed for ${agentPath} (exit code ${code}).\n${output.trim()}`));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const outputDir = path.join(agentPath, '.output');
|
|
86
|
+
const serverEntry = path.join(outputDir, 'server', 'index.mjs');
|
|
87
|
+
if (!fs.existsSync(serverEntry)) {
|
|
88
|
+
reject(new Error(`eve build did not produce ${serverEntry}.\n${output.trim()}`));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
resolve(outputDir);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** Seam so tests can supply a fixture `.output` instead of a real build. */
|
|
96
|
+
export const eveBuild = { run: runEveBuild };
|
|
44
97
|
/**
|
|
45
|
-
* Assemble the
|
|
46
|
-
*
|
|
47
|
-
* `
|
|
48
|
-
*
|
|
98
|
+
* Assemble the Web Function bundle for a `sanity.agent` resource: a runnable
|
|
99
|
+
* root `index.mjs` bootstrap, eve's built node-server under `.output/`, and the
|
|
100
|
+
* root `package.json` manifest. Asset prep is the sole producer; the Provider
|
|
101
|
+
* only reads the bytes, so the layout is complete here.
|
|
49
102
|
*/
|
|
50
|
-
export function buildAgentPackage(agentPath, manifest) {
|
|
103
|
+
export async function buildAgentPackage(agentPath, manifest, build = eveBuild.run) {
|
|
104
|
+
const outputDir = await build(agentPath);
|
|
51
105
|
const zip = new AdmZip();
|
|
106
|
+
zip.addFile('index.mjs', Buffer.from(WEB_FUNCTION_ENTRY, 'utf8'));
|
|
107
|
+
zip.addLocalFolder(outputDir, '.output');
|
|
52
108
|
zip.addFile('package.json', Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'));
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
zip.addFile('public/.gitkeep', Buffer.from(PUBLIC_KEEP, 'utf8'));
|
|
56
|
-
zip.addFile('Dockerfile', Buffer.from(DOCKERFILE, 'utf8'));
|
|
57
|
-
// Fixed entry times so the same input gives the same bytes, and the same asset id
|
|
109
|
+
// Zero entry times so identical inputs hash identically and the stash reuses
|
|
110
|
+
// the asset.
|
|
58
111
|
for (const entry of zip.getEntries())
|
|
59
112
|
entry.header.time = new Date(0);
|
|
60
113
|
return zip;
|
|
@@ -1,9 +1,23 @@
|
|
|
1
1
|
import type { AgentResource, AssetPrepResult, AuthParams } from '../types.js';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
* path, with the manifest
|
|
5
|
-
* producer
|
|
6
|
-
*
|
|
3
|
+
* Builds the complete Web Function bundle for a `sanity.agent` resource from its
|
|
4
|
+
* `src` source path, with the manifest INSIDE the zip. Asset prep is the sole
|
|
5
|
+
* producer of this bundle: the Provider only reads the prepared bytes and never
|
|
6
|
+
* builds, assembles, or merges a manifest, so the bundle emitted here is
|
|
7
|
+
* complete -- a runnable root `index.mjs` bootstrap, eve's built node-server
|
|
8
|
+
* under `.output/`, and the root `package.json` manifest. The platform deploys
|
|
9
|
+
* it as a zip Web Function (`EntryPoint index.mjs`, `Runtime nodejs24.x`), which
|
|
10
|
+
* loads the root `index.mjs`; a container layout (raw `.ts` + Dockerfile) never
|
|
11
|
+
* boots there.
|
|
12
|
+
*
|
|
13
|
+
* The `sanityID` in the manifest is derived from the project scope (`auth.scopeId`);
|
|
14
|
+
* `name`, `description`, and `region` come from the resource.
|
|
15
|
+
*
|
|
16
|
+
* The returned `assetParameter` is `src`, so once the bytes are stashed the
|
|
17
|
+
* resource `src` is rewritten from the source path to the returned `AS-...` asset
|
|
18
|
+
* id before deploy. A build failure (including a failed `eve build`) returns
|
|
19
|
+
* `{success: false}`, which fails the CLI prep step before the Blueprints API is
|
|
20
|
+
* called.
|
|
7
21
|
*/
|
|
8
22
|
export declare function prepareAsset({ blueprintFileDir, resource, auth, }: {
|
|
9
23
|
blueprintFileDir: string;
|
|
@@ -1,13 +1,26 @@
|
|
|
1
1
|
import { existsSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { CONVERT_BYTES_TO_MB, MAX_ASSET_SIZE } from '../../constants.js';
|
|
4
|
-
import { isFolderLargerThan } from '../functions/is-folder-larger-than.js';
|
|
5
4
|
import { buildAgentManifest, buildAgentPackage } from './build-package.js';
|
|
6
5
|
/**
|
|
7
|
-
*
|
|
8
|
-
* path, with the manifest
|
|
9
|
-
* producer
|
|
10
|
-
*
|
|
6
|
+
* Builds the complete Web Function bundle for a `sanity.agent` resource from its
|
|
7
|
+
* `src` source path, with the manifest INSIDE the zip. Asset prep is the sole
|
|
8
|
+
* producer of this bundle: the Provider only reads the prepared bytes and never
|
|
9
|
+
* builds, assembles, or merges a manifest, so the bundle emitted here is
|
|
10
|
+
* complete -- a runnable root `index.mjs` bootstrap, eve's built node-server
|
|
11
|
+
* under `.output/`, and the root `package.json` manifest. The platform deploys
|
|
12
|
+
* it as a zip Web Function (`EntryPoint index.mjs`, `Runtime nodejs24.x`), which
|
|
13
|
+
* loads the root `index.mjs`; a container layout (raw `.ts` + Dockerfile) never
|
|
14
|
+
* boots there.
|
|
15
|
+
*
|
|
16
|
+
* The `sanityID` in the manifest is derived from the project scope (`auth.scopeId`);
|
|
17
|
+
* `name`, `description`, and `region` come from the resource.
|
|
18
|
+
*
|
|
19
|
+
* The returned `assetParameter` is `src`, so once the bytes are stashed the
|
|
20
|
+
* resource `src` is rewritten from the source path to the returned `AS-...` asset
|
|
21
|
+
* id before deploy. A build failure (including a failed `eve build`) returns
|
|
22
|
+
* `{success: false}`, which fails the CLI prep step before the Blueprints API is
|
|
23
|
+
* called.
|
|
11
24
|
*/
|
|
12
25
|
export async function prepareAsset({ blueprintFileDir, resource, auth, }) {
|
|
13
26
|
if (!resource.src)
|
|
@@ -24,12 +37,9 @@ export async function prepareAsset({ blueprintFileDir, resource, auth, }) {
|
|
|
24
37
|
if (!existsSync(agentPath)) {
|
|
25
38
|
throw new Error(`Agent source path not found: ${agentPath}`);
|
|
26
39
|
}
|
|
27
|
-
if (isFolderLargerThan(agentPath, MAX_ASSET_SIZE)) {
|
|
28
|
-
throw new Error('Resource is larger than max asset size of 200 MB.');
|
|
29
|
-
}
|
|
30
40
|
const manifest = buildAgentManifest(resource, auth.scopeId);
|
|
31
|
-
const zip = buildAgentPackage(agentPath, manifest);
|
|
32
|
-
// Sum uncompressed entry sizes so the limit check reflects
|
|
41
|
+
const zip = await buildAgentPackage(agentPath, manifest);
|
|
42
|
+
// Sum uncompressed entry sizes so the limit check reflects the zip size.
|
|
33
43
|
const zipEntrySize = zip
|
|
34
44
|
.getEntries()
|
|
35
45
|
.map((entry) => entry.header.size)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CallbackResponse, InvocationError } from '../../types.js';
|
|
2
|
+
type Deliver = (result: CallbackResponse) => void;
|
|
3
|
+
export declare const createCallbackRoutes: () => {
|
|
4
|
+
set: (id: string, deliver: Deliver) => void;
|
|
5
|
+
remove: (id: string) => boolean;
|
|
6
|
+
deliver: (id: string, response: CallbackResponse) => 'ok' | 'unknown' | 'delivered' | 'cancelled';
|
|
7
|
+
fail: (error: InvocationError) => void;
|
|
8
|
+
};
|
|
9
|
+
export type CallbackRoutes = ReturnType<typeof createCallbackRoutes>;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export const createCallbackRoutes = () => {
|
|
2
|
+
const routes = new Map();
|
|
3
|
+
const finished = new Map();
|
|
4
|
+
const set = (id, deliver) => {
|
|
5
|
+
routes.set(id, deliver);
|
|
6
|
+
};
|
|
7
|
+
const remove = (id) => {
|
|
8
|
+
if (!routes.delete(id))
|
|
9
|
+
return false;
|
|
10
|
+
finished.set(id, 'cancelled');
|
|
11
|
+
return true;
|
|
12
|
+
};
|
|
13
|
+
const deliver = (id, response) => {
|
|
14
|
+
const fn = routes.get(id);
|
|
15
|
+
if (!fn) {
|
|
16
|
+
return finished.get(id) ?? 'unknown';
|
|
17
|
+
}
|
|
18
|
+
routes.delete(id);
|
|
19
|
+
finished.set(id, 'delivered');
|
|
20
|
+
fn(response);
|
|
21
|
+
return 'ok';
|
|
22
|
+
};
|
|
23
|
+
const fail = (error) => {
|
|
24
|
+
for (const [id] of routes.entries()) {
|
|
25
|
+
deliver(id, { ok: false, error });
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
set,
|
|
30
|
+
remove,
|
|
31
|
+
deliver,
|
|
32
|
+
fail,
|
|
33
|
+
};
|
|
34
|
+
};
|
|
@@ -2,6 +2,7 @@ import {existsSync, statSync} from 'node:fs'
|
|
|
2
2
|
import {isAbsolute, join} from 'node:path'
|
|
3
3
|
import process from 'node:process'
|
|
4
4
|
import {pathToFileURL} from 'node:url'
|
|
5
|
+
import {createCallbackHandler} from './child-runtime/callback.js'
|
|
5
6
|
import {installConsole} from './child-runtime/console.js'
|
|
6
7
|
import {runDurable} from './child-runtime/durable.js'
|
|
7
8
|
import {createInvoker} from './child-runtime/invoke.js'
|
|
@@ -9,6 +10,7 @@ import {createResourcesApi} from './child-runtime/resources.js'
|
|
|
9
10
|
|
|
10
11
|
installConsole()
|
|
11
12
|
const invoker = createInvoker()
|
|
13
|
+
const callback = createCallbackHandler()
|
|
12
14
|
|
|
13
15
|
export function getFunctionSource(src) {
|
|
14
16
|
const pathToCheck = isAbsolute(src) ? src : join(process.cwd(), src)
|
|
@@ -39,9 +41,14 @@ process.on('message', async (data) => {
|
|
|
39
41
|
return
|
|
40
42
|
}
|
|
41
43
|
|
|
44
|
+
if (jsonData?.type === 'callback-response') {
|
|
45
|
+
callback.handleResponse(jsonData)
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
|
|
42
49
|
// Otherwise this is the initial start message. Support the legacy untyped
|
|
43
50
|
// `{srcPath, payload}` shape as well as the new `{type: 'start', ...}`.
|
|
44
|
-
const {srcPath, payload, isDurable, noWait} = jsonData
|
|
51
|
+
const {srcPath, payload, isDurable, noWait, callbacks} = jsonData
|
|
45
52
|
const {context, ...event} = payload
|
|
46
53
|
let logs = ''
|
|
47
54
|
let errorLogs = ''
|
|
@@ -79,6 +86,13 @@ process.on('message', async (data) => {
|
|
|
79
86
|
// Allow the handler to invoke other blueprint functions by name.
|
|
80
87
|
context.invoke = invoker.invoke
|
|
81
88
|
|
|
89
|
+
if (callbacks) {
|
|
90
|
+
context.clientOptions = {
|
|
91
|
+
...context.clientOptions,
|
|
92
|
+
requestHandler: callback.handleRequest,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
82
96
|
if (isDurable) {
|
|
83
97
|
json = await runDurable(
|
|
84
98
|
handler,
|
|
@@ -87,6 +101,8 @@ process.on('message', async (data) => {
|
|
|
87
101
|
emit: (e) => process.send(JSON.stringify({type: 'step-event', event: e})),
|
|
88
102
|
wait: (ms) => new Promise((resolve) => setTimeout(resolve, noWait ? 0 : ms)),
|
|
89
103
|
invoke: invoker.delegate,
|
|
104
|
+
registerCallback: callback.register,
|
|
105
|
+
cancelCallback: callback.cancel,
|
|
90
106
|
},
|
|
91
107
|
)
|
|
92
108
|
} else {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type {ParentToChildMessage} from '../../types.js'
|
|
2
|
+
|
|
3
|
+
export function createCallbackHandler(): {
|
|
4
|
+
cancel: (callbackId: string) => void
|
|
5
|
+
register: ({
|
|
6
|
+
callbackId,
|
|
7
|
+
name,
|
|
8
|
+
timeout,
|
|
9
|
+
}: {
|
|
10
|
+
callbackId: string
|
|
11
|
+
name: string
|
|
12
|
+
timeout: number
|
|
13
|
+
}) => Promise<unknown>
|
|
14
|
+
handleResponse: (msg: Extract<ParentToChildMessage, {type: 'callback-response'}>) => void
|
|
15
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import process from 'node:process'
|
|
2
|
+
|
|
3
|
+
export const createCallbackHandler = () => {
|
|
4
|
+
/**
|
|
5
|
+
* Pending nested `context.registerCallback()` calls, keyed by correlation id. Each entry
|
|
6
|
+
* holds the resolve/reject of the Promise returned to the user's handler; it is
|
|
7
|
+
* settled when the matching `callback-response` arrives from the parent.
|
|
8
|
+
* @type {Map<string, {resolve: (value: unknown) => void, reject: (reason: Error) => void, timer: ReturnType<typeof setTimeout> | undefined}>}
|
|
9
|
+
*/
|
|
10
|
+
const pendingResponses = new Map([])
|
|
11
|
+
const pendingRequests = new Map([])
|
|
12
|
+
let nextAttempt = 0
|
|
13
|
+
|
|
14
|
+
// Register a callback with the parent process. Returns a Promise that resolves when the callback is invoked, or rejects if the callback times out.
|
|
15
|
+
const register = ({callbackId, name, timeout}) => {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
const timer = timeout
|
|
18
|
+
? setTimeout(() => {
|
|
19
|
+
cancel(callbackId)
|
|
20
|
+
reject(new Error(`Callback ${callbackId} timed out after ${timeout}ms`))
|
|
21
|
+
}, timeout)
|
|
22
|
+
: undefined
|
|
23
|
+
|
|
24
|
+
pendingResponses.set(callbackId, {resolve, reject, timer})
|
|
25
|
+
process.send(JSON.stringify({type: 'callback-register', callbackId, name}))
|
|
26
|
+
})
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Handle a response from the parent process for a registered callback. This is called when the parent process sends a `callback-response` message.
|
|
31
|
+
*/
|
|
32
|
+
const handleResponse = (msg) => {
|
|
33
|
+
if (msg.attempt !== undefined) {
|
|
34
|
+
const entry = removeRequest(msg.attempt)
|
|
35
|
+
|
|
36
|
+
if (!entry) {
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (msg.ok) {
|
|
41
|
+
entry.resolve(msg.result)
|
|
42
|
+
} else {
|
|
43
|
+
entry.reject(new Error(msg.error.message))
|
|
44
|
+
}
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const pendingEntry = pendingResponses.get(msg.callbackId)
|
|
49
|
+
if (!pendingEntry) return
|
|
50
|
+
|
|
51
|
+
pendingResponses.delete(msg.callbackId)
|
|
52
|
+
clearTimeout(pendingEntry?.timer)
|
|
53
|
+
if (msg.ok) {
|
|
54
|
+
pendingEntry.resolve(msg.result)
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const {message, stack, name} = msg.error
|
|
59
|
+
const error = new Error(message)
|
|
60
|
+
error.stack = stack
|
|
61
|
+
error.name = name
|
|
62
|
+
pendingEntry.reject(error)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Handle a request from the parent process to invoke a registered callback. This is called when the parent process sends a `callback-request` message.
|
|
67
|
+
*/
|
|
68
|
+
const handleRequest = (request, next) => {
|
|
69
|
+
// Match the request from the callback.sucess or callback.failure sanity client functions
|
|
70
|
+
const CALLBACK_URL =
|
|
71
|
+
/^https?:\/\/[^/?#]+\/v[^/?#]+\/functions\/durables\/callback\/([^/?#]+)\/(success|failure)(?:[?#].*)?$/
|
|
72
|
+
|
|
73
|
+
const match = request.method?.toUpperCase() === 'POST' && CALLBACK_URL.exec(request.url)
|
|
74
|
+
if (!match) {
|
|
75
|
+
return next(request)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const [, callbackId, outcome] = match
|
|
79
|
+
const {body, timeout} = request
|
|
80
|
+
if (typeof body !== 'string') {
|
|
81
|
+
throw new TypeError('Callback body must be serialized JSON')
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const timeoutMs = typeof timeout === 'object' && timeout !== null ? timeout.total : timeout
|
|
85
|
+
const signals = [request.signal, timeoutMs > 0 && AbortSignal.timeout(timeoutMs)].filter(
|
|
86
|
+
Boolean,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
const signal = signals.length > 0 ? AbortSignal.any(signals) : undefined
|
|
90
|
+
signal?.throwIfAborted()
|
|
91
|
+
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
const attempt = ++nextAttempt
|
|
94
|
+
const onAbort = () => removeRequest(attempt)?.reject(signal.reason)
|
|
95
|
+
pendingRequests.set(attempt, {
|
|
96
|
+
callbackId,
|
|
97
|
+
resolve,
|
|
98
|
+
reject,
|
|
99
|
+
cleanup: () => signal?.removeEventListener('abort', onAbort),
|
|
100
|
+
})
|
|
101
|
+
signal?.addEventListener('abort', onAbort, {once: true})
|
|
102
|
+
try {
|
|
103
|
+
process.send(
|
|
104
|
+
JSON.stringify({type: 'callback-request', callbackId, attempt, outcome, body}),
|
|
105
|
+
(error) => {
|
|
106
|
+
if (error) removeRequest(attempt)?.reject(error)
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
} catch (error) {
|
|
110
|
+
removeRequest(attempt)?.reject(error)
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Remove a pending request from the map and clean up its resources. This is called when a request is completed or aborted.
|
|
117
|
+
*/
|
|
118
|
+
const removeRequest = (attempt) => {
|
|
119
|
+
const entry = pendingRequests.get(attempt)
|
|
120
|
+
if (!entry) {
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
pendingRequests.delete(attempt)
|
|
125
|
+
entry.cleanup()
|
|
126
|
+
return entry
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
process.once('disconnect', () => {
|
|
130
|
+
const error = new Error('Local callback IPC disconnected')
|
|
131
|
+
for (const attempt of pendingRequests.keys()) removeRequest(attempt)?.reject(error)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Cancel a pending callback request. This is called when the parent process sends a `callback-cancel` message.
|
|
136
|
+
*/
|
|
137
|
+
const cancel = (callbackId) => {
|
|
138
|
+
const pendingEntry = pendingResponses.get(callbackId)
|
|
139
|
+
if (!pendingEntry) return
|
|
140
|
+
pendingResponses.delete(callbackId)
|
|
141
|
+
clearTimeout(pendingEntry?.timer)
|
|
142
|
+
process.send(JSON.stringify({type: 'callback-cancel', callbackId}))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
cancel,
|
|
147
|
+
register,
|
|
148
|
+
handleRequest,
|
|
149
|
+
handleResponse,
|
|
150
|
+
removeRequest,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto'
|
|
1
2
|
import {performance} from 'node:perf_hooks'
|
|
2
3
|
import {inspect} from 'node:util'
|
|
3
4
|
import {getBatchResults} from './getBatchResults.js'
|
|
@@ -205,6 +206,30 @@ export async function runDurable(handler, {context, event, branchName}, io) {
|
|
|
205
206
|
}
|
|
206
207
|
return state
|
|
207
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
|
+
},
|
|
208
233
|
wait: ({name, duration}) =>
|
|
209
234
|
track(name || '', 'wait', async () => {
|
|
210
235
|
await io.wait(durationToMs(duration))
|
|
@@ -18,8 +18,7 @@ export const getBatchResults = (outcomes, reason) => {
|
|
|
18
18
|
/**
|
|
19
19
|
* Returns an array of outcomes that have succeeded (status 'SUCCEEDED').
|
|
20
20
|
*/
|
|
21
|
-
const succeeded = () =>
|
|
22
|
-
all.filter((outcome) => outcome.result !== undefined && outcome.status === 'SUCCEEDED')
|
|
21
|
+
const succeeded = () => all.filter((outcome) => outcome.status === 'SUCCEEDED')
|
|
23
22
|
|
|
24
23
|
/**
|
|
25
24
|
* Returns an array of outcomes that are still in progress (status 'STARTED').
|
|
@@ -35,6 +35,11 @@ export const createDurableJsonCollector = () => {
|
|
|
35
35
|
const step = activeSteps.get(event.name);
|
|
36
36
|
if (!step)
|
|
37
37
|
return;
|
|
38
|
+
if (event.phase === 'waiting') {
|
|
39
|
+
step.phase = 'waiting';
|
|
40
|
+
step.callbackId = event.callbackId;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
38
43
|
step.phase = event.phase;
|
|
39
44
|
step.durationMs = event.durationMs;
|
|
40
45
|
if (event.phase === 'complete') {
|
|
@@ -8,6 +8,7 @@ import * as groq from 'groq-js';
|
|
|
8
8
|
import config from '../../../config.js';
|
|
9
9
|
import { SANITY_FUNCTION_DURABLE } from '../../../constants.js';
|
|
10
10
|
import { groupBlueprintResources } from '../../blueprints/group-resources.js';
|
|
11
|
+
import { isRecord } from '../../is-record.js';
|
|
11
12
|
import { isGroqContextOptions, } from '../../types.js';
|
|
12
13
|
import { findFunctionEntryPoint } from '../find-entry-point.js';
|
|
13
14
|
import { assertConsole } from './assert-console.js';
|
|
@@ -50,7 +51,7 @@ export default async function invoke(resource, payload, context, options) {
|
|
|
50
51
|
if (!resource.src) {
|
|
51
52
|
throw new Error(`Function resource "${resource.name}" is missing the 'src' property.`);
|
|
52
53
|
}
|
|
53
|
-
const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, } = options;
|
|
54
|
+
const { forceColor = true, timeout = 10, onNestedInvoke, depth = 0, callStack = [], onStepEvent = () => { }, noWait = false, callbackRoutes, } = options;
|
|
54
55
|
// Ensure a user when running a durable is using the provided logger and not the `console`
|
|
55
56
|
if (resource.type === SANITY_FUNCTION_DURABLE) {
|
|
56
57
|
const sourcePath = resolve(context.blueprintFileDir, resource.src);
|
|
@@ -236,6 +237,80 @@ export default async function invoke(resource, payload, context, options) {
|
|
|
236
237
|
catch {
|
|
237
238
|
return;
|
|
238
239
|
}
|
|
240
|
+
if (msg?.type === 'callback-register') {
|
|
241
|
+
// if the routes handler is not available, kill the process with an error
|
|
242
|
+
if (!callbackRoutes) {
|
|
243
|
+
child.send(JSON.stringify({
|
|
244
|
+
type: 'callback-response',
|
|
245
|
+
callbackId: msg.callbackId,
|
|
246
|
+
ok: false,
|
|
247
|
+
error: {
|
|
248
|
+
name: 'Error',
|
|
249
|
+
message: 'The callback server is not available',
|
|
250
|
+
},
|
|
251
|
+
}));
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
pauseTimer();
|
|
255
|
+
callbackRoutes.set(msg.callbackId, async (result) => {
|
|
256
|
+
if (child && !child.killed) {
|
|
257
|
+
child.send(JSON.stringify({
|
|
258
|
+
type: 'callback-response',
|
|
259
|
+
callbackId: msg.callbackId,
|
|
260
|
+
...result,
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
resumeTimer();
|
|
264
|
+
});
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (msg.type === 'callback-cancel') {
|
|
268
|
+
if (callbackRoutes?.remove(msg.callbackId)) {
|
|
269
|
+
resumeTimer();
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (msg?.type === 'callback-request') {
|
|
274
|
+
const { callbackId, attempt, outcome, body } = msg;
|
|
275
|
+
let response;
|
|
276
|
+
try {
|
|
277
|
+
let value;
|
|
278
|
+
try {
|
|
279
|
+
value = JSON.parse(body);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
throw new Error('Invalid callback payload');
|
|
283
|
+
}
|
|
284
|
+
let delivery = { ok: true, result: value };
|
|
285
|
+
if (outcome === 'failure') {
|
|
286
|
+
const fields = isRecord(value) ? value : {};
|
|
287
|
+
delivery = {
|
|
288
|
+
ok: false,
|
|
289
|
+
error: {
|
|
290
|
+
name: 'Error',
|
|
291
|
+
message: typeof fields.errorMessage === 'string' ? fields.errorMessage : '',
|
|
292
|
+
stack: Array.isArray(fields.stackTrace) ? fields.stackTrace.join('\n') : '',
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
const result = callbackRoutes?.deliver(callbackId, delivery) ?? 'unknown';
|
|
297
|
+
if (result !== 'ok')
|
|
298
|
+
throw new Error(`Local callback ${callbackId}: ${result}`);
|
|
299
|
+
response = { ok: true, result: null };
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
response = {
|
|
303
|
+
ok: false,
|
|
304
|
+
error: {
|
|
305
|
+
name: err instanceof Error ? err.name : 'Error',
|
|
306
|
+
message: err instanceof Error ? err.message : String(err),
|
|
307
|
+
stack: err instanceof Error ? (err.stack ?? '') : '',
|
|
308
|
+
},
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
child.send(JSON.stringify({ type: 'callback-response', callbackId, attempt, ...response }));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
239
314
|
if (msg?.type === 'step-event') {
|
|
240
315
|
onStepEvent(msg.event);
|
|
241
316
|
return;
|
|
@@ -321,7 +396,8 @@ export default async function invoke(resource, payload, context, options) {
|
|
|
321
396
|
...(isGroqContextOptions(context) && {
|
|
322
397
|
clientOptions: {
|
|
323
398
|
...context.clientOptions,
|
|
324
|
-
|
|
399
|
+
// trailing slash is being added, but not certain where. Strips it off here to remove `apiHost//vx/`
|
|
400
|
+
apiHost: (context.clientOptions.apiHost ?? config.apiUrl).replace(/\/+$/, ''),
|
|
325
401
|
},
|
|
326
402
|
}),
|
|
327
403
|
},
|
|
@@ -332,6 +408,7 @@ export default async function invoke(resource, payload, context, options) {
|
|
|
332
408
|
payload,
|
|
333
409
|
isDurable: resource.type === SANITY_FUNCTION_DURABLE,
|
|
334
410
|
noWait,
|
|
411
|
+
callbacks: Boolean(callbackRoutes),
|
|
335
412
|
};
|
|
336
413
|
child.send(JSON.stringify(startMessage));
|
|
337
414
|
}
|
|
@@ -28,7 +28,7 @@ export function assertNestedInvokeAllowed(name, depth, callStack) {
|
|
|
28
28
|
* stack extended by this function, and normalize timings.
|
|
29
29
|
*/
|
|
30
30
|
export async function runFunction(resource, payload, context, options) {
|
|
31
|
-
const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent } = options;
|
|
31
|
+
const { forceColor, timeout, depth = 0, callStack = [], onNestedInvoke, onStepEvent, callbackRoutes, } = options;
|
|
32
32
|
assertNestedInvokeAllowed(resource.name, depth, callStack);
|
|
33
33
|
const response = await invoke(resource, payload, context, {
|
|
34
34
|
forceColor,
|
|
@@ -37,6 +37,7 @@ export async function runFunction(resource, payload, context, options) {
|
|
|
37
37
|
depth,
|
|
38
38
|
callStack: [...callStack, resource.name],
|
|
39
39
|
onStepEvent,
|
|
40
|
+
callbackRoutes,
|
|
40
41
|
});
|
|
41
42
|
return { ...response, timings: response.timings ?? {} };
|
|
42
43
|
}
|
package/dist/utils/types.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type BlueprintCorsOriginResource, type BlueprintDatasetResource, type BlueprintDocumentFunctionResource, type BlueprintDocumentWebhookResource, type BlueprintDurableFunctionResource, type BlueprintMediaLibraryAssetFunctionResource, type BlueprintProjectResource, type BlueprintPubSubFunctionResource, type BlueprintResource, type BlueprintRobotResource, type BlueprintRoleResource, type BlueprintScheduledFunctionResource, type BlueprintStudioResource, type BlueprintSyncTagInvalidateFunctionResource } from '@sanity/blueprints';
|
|
2
2
|
import { type SANITY_AGENT_TYPE } from '../constants.js';
|
|
3
|
+
import type { CallbackRoutes } from './functions/callback/routes.js';
|
|
3
4
|
export type ScopeType = 'organization' | 'project';
|
|
4
5
|
/** Result utility type */
|
|
5
6
|
export type Result<T, E = string> = {
|
|
@@ -165,6 +166,7 @@ export interface InvokeGroqContextOptions extends BaseContextOptions {
|
|
|
165
166
|
projectId?: string;
|
|
166
167
|
organizationId?: string;
|
|
167
168
|
token?: string;
|
|
169
|
+
apiHost?: string;
|
|
168
170
|
};
|
|
169
171
|
/** The resource type of the event source; resource type that invoked the function. */
|
|
170
172
|
eventResourceType: string;
|
|
@@ -201,7 +203,18 @@ export interface InvokeExecutionOptions {
|
|
|
201
203
|
onStepEvent?: (event: DurableRuntimeEvent) => void;
|
|
202
204
|
/** Don't wait the full duration during a wait durable event @internal */
|
|
203
205
|
noWait?: boolean;
|
|
206
|
+
callbackRoutes?: CallbackRoutes;
|
|
204
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* @internal
|
|
210
|
+
*/
|
|
211
|
+
export type CallbackResponse = {
|
|
212
|
+
ok: true;
|
|
213
|
+
result: unknown;
|
|
214
|
+
} | {
|
|
215
|
+
ok: false;
|
|
216
|
+
error: InvocationError;
|
|
217
|
+
};
|
|
205
218
|
export type NestedInvokeMetadata = {
|
|
206
219
|
origin?: 'step.delegate';
|
|
207
220
|
};
|
|
@@ -223,6 +236,7 @@ export type ParentToChildMessage = {
|
|
|
223
236
|
payload: unknown;
|
|
224
237
|
isDurable?: boolean;
|
|
225
238
|
noWait?: boolean;
|
|
239
|
+
callbacks?: boolean;
|
|
226
240
|
} | {
|
|
227
241
|
type: 'invoke-response';
|
|
228
242
|
id: string;
|
|
@@ -238,6 +252,18 @@ export type ParentToChildMessage = {
|
|
|
238
252
|
} | {
|
|
239
253
|
type: 'step-event';
|
|
240
254
|
event: DurableRuntimeEvent;
|
|
255
|
+
} | {
|
|
256
|
+
type: 'callback-response';
|
|
257
|
+
callbackId: string;
|
|
258
|
+
ok: true;
|
|
259
|
+
result: unknown;
|
|
260
|
+
attempt?: number;
|
|
261
|
+
} | {
|
|
262
|
+
type: 'callback-response';
|
|
263
|
+
callbackId: string;
|
|
264
|
+
ok: false;
|
|
265
|
+
error: InvocationError;
|
|
266
|
+
attempt?: number;
|
|
241
267
|
};
|
|
242
268
|
/**
|
|
243
269
|
* IPC messages sent from a function child process back up to the parent.
|
|
@@ -261,6 +287,19 @@ export type ChildToParentMessage = {
|
|
|
261
287
|
} | {
|
|
262
288
|
type: 'step-event';
|
|
263
289
|
event: DurableRuntimeEvent;
|
|
290
|
+
} | {
|
|
291
|
+
type: 'callback-register';
|
|
292
|
+
callbackId: string;
|
|
293
|
+
name: string;
|
|
294
|
+
} | {
|
|
295
|
+
type: 'callback-cancel';
|
|
296
|
+
callbackId: string;
|
|
297
|
+
} | {
|
|
298
|
+
type: 'callback-request';
|
|
299
|
+
attempt: number;
|
|
300
|
+
callbackId: string;
|
|
301
|
+
outcome: 'success' | 'failure';
|
|
302
|
+
body: string;
|
|
264
303
|
};
|
|
265
304
|
/** @internal */
|
|
266
305
|
export interface InvocationResponse {
|
|
@@ -381,9 +420,9 @@ export type Warning = {
|
|
|
381
420
|
suggestions: string[];
|
|
382
421
|
};
|
|
383
422
|
/** @internal */
|
|
384
|
-
export type DurableOperationSteps = 'run' | 'wait' | '
|
|
423
|
+
export type DurableOperationSteps = 'run' | 'delegate' | 'fanout' | 'wait' | 'wait-for-condition' | 'wait-for-callback';
|
|
385
424
|
/** @internal */
|
|
386
|
-
export type DurableStepPhase = 'start' | 'complete' | 'error';
|
|
425
|
+
export type DurableStepPhase = 'start' | 'complete' | 'error' | 'waiting';
|
|
387
426
|
/**
|
|
388
427
|
* Represents a single step in a durable operation
|
|
389
428
|
*/
|
|
@@ -398,6 +437,7 @@ export interface DurableStepEvent {
|
|
|
398
437
|
attempt?: number;
|
|
399
438
|
retries?: number;
|
|
400
439
|
maxAttempts?: number;
|
|
440
|
+
callbackId?: string;
|
|
401
441
|
}
|
|
402
442
|
export interface DurableLogEvent {
|
|
403
443
|
kind: 'log';
|
package/oclif.manifest.json
CHANGED
package/package.json
CHANGED