@sanity/functions 1.4.0 → 1.6.0
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/dist/durables.d.ts +32 -0
- package/dist/durables.js +74 -0
- package/dist/durables.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/invoke.d.ts +38 -2
- package/dist/invoke.js +106 -20
- package/dist/invoke.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types.d.ts +255 -1
- package/package.json +1 -1
- package/src/durables.ts +104 -0
- package/src/index.ts +1 -0
- package/src/invoke.ts +125 -21
- package/src/types.ts +259 -1
package/dist/types.d.ts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Callback provided by Sanity CLI when doing local development
|
|
3
3
|
*/
|
|
4
|
-
export type InvokeCallback = (name: string, payload: FunctionPayload) => Promise<
|
|
4
|
+
export type InvokeCallback = <T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions) => Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* Options provided to invoke
|
|
7
|
+
*/
|
|
8
|
+
export type InvokeOptions = {
|
|
9
|
+
sync?: boolean;
|
|
10
|
+
};
|
|
5
11
|
/**
|
|
6
12
|
* The context object passed to the function handler.
|
|
7
13
|
*/
|
|
@@ -14,6 +20,8 @@ export interface FunctionContext {
|
|
|
14
20
|
functionResourceType: string;
|
|
15
21
|
/** The resource ID of the function container; resource ID that houses the function. */
|
|
16
22
|
functionResourceId: string;
|
|
23
|
+
/** Sanity lineage token */
|
|
24
|
+
lineage?: string | undefined;
|
|
17
25
|
/**
|
|
18
26
|
* `local` is set to `true` when testing your function locally.
|
|
19
27
|
* i.e. `sanity function test func-name`
|
|
@@ -48,6 +56,8 @@ export interface FunctionContext {
|
|
|
48
56
|
* The context object passed to the schedule function handler.
|
|
49
57
|
*/
|
|
50
58
|
export interface ScheduledFunctionContext {
|
|
59
|
+
/** Sanity lineage token */
|
|
60
|
+
lineage?: string | undefined;
|
|
51
61
|
/**
|
|
52
62
|
* `local` is set to `true` when testing your function locally.
|
|
53
63
|
* i.e. `sanity function test func-name`
|
|
@@ -214,4 +224,248 @@ export type FunctionResourceEnvelope = {
|
|
|
214
224
|
[P in Exclude<FunctionResourceKey, K>]?: FunctionResource;
|
|
215
225
|
};
|
|
216
226
|
}[FunctionResourceKey];
|
|
227
|
+
type DurableLogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
|
|
228
|
+
/**
|
|
229
|
+
* Context logger interface for durables.
|
|
230
|
+
* Exposes console.log through the durable context.
|
|
231
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
232
|
+
* @hidden
|
|
233
|
+
*/
|
|
234
|
+
interface DurableLogger {
|
|
235
|
+
log?(level: DurableLogLevel, ...params: unknown[]): void;
|
|
236
|
+
debug(...params: unknown[]): void;
|
|
237
|
+
info(...params: unknown[]): void;
|
|
238
|
+
warn(...params: unknown[]): void;
|
|
239
|
+
error(...params: unknown[]): void;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
243
|
+
* @hidden
|
|
244
|
+
*/
|
|
245
|
+
export type DurableContext = FunctionContext & {
|
|
246
|
+
/**
|
|
247
|
+
* Durable logger
|
|
248
|
+
*/
|
|
249
|
+
log: DurableLogger;
|
|
250
|
+
/**
|
|
251
|
+
* Current attempt of the active durable operation.
|
|
252
|
+
* Only available in methods that expose the attempt like `waitForCondition`
|
|
253
|
+
*/
|
|
254
|
+
attempt?: number;
|
|
255
|
+
/**
|
|
256
|
+
* Unique ID for a durable execution
|
|
257
|
+
*/
|
|
258
|
+
runId?: string;
|
|
259
|
+
};
|
|
260
|
+
/**
|
|
261
|
+
* The signature of the duration object passed to the `wait` method of a durable function.
|
|
262
|
+
* It can be specified in days, hours, minutes, or seconds.
|
|
263
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
264
|
+
* @hidden
|
|
265
|
+
*/
|
|
266
|
+
export type DurableDuration = {
|
|
267
|
+
days: number;
|
|
268
|
+
hours?: number;
|
|
269
|
+
minutes?: number;
|
|
270
|
+
seconds?: number;
|
|
271
|
+
} | {
|
|
272
|
+
hours: number;
|
|
273
|
+
minutes?: number;
|
|
274
|
+
seconds?: number;
|
|
275
|
+
} | {
|
|
276
|
+
minutes: number;
|
|
277
|
+
seconds?: number;
|
|
278
|
+
} | {
|
|
279
|
+
seconds: number;
|
|
280
|
+
};
|
|
281
|
+
/**
|
|
282
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
283
|
+
* @hidden
|
|
284
|
+
*/
|
|
285
|
+
export type DurableWaitForConditionDecision = {
|
|
286
|
+
shouldContinue: true;
|
|
287
|
+
delay: DurableDuration;
|
|
288
|
+
} | {
|
|
289
|
+
shouldContinue: false;
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
293
|
+
* @hidden
|
|
294
|
+
*/
|
|
295
|
+
export interface DurableWaitForConditionOptions<T> {
|
|
296
|
+
initial: T;
|
|
297
|
+
next: (state: T, context: DurableContext) => DurableWaitForConditionDecision;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The interface defining the operations available to a durable function.
|
|
301
|
+
* These operations are steps that delegate to other functions, and wait for external callbacks.
|
|
302
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
303
|
+
* @hidden
|
|
304
|
+
*/
|
|
305
|
+
export interface DurableOperations {
|
|
306
|
+
/**
|
|
307
|
+
* Runs a named step. Its result is recorded, so if the workflow re-runs the step
|
|
308
|
+
* is not executed again. Failures are retried on their own.
|
|
309
|
+
* similar to ctx.step()
|
|
310
|
+
* @remarks cannot be nested inside another step
|
|
311
|
+
* @param name - Step name
|
|
312
|
+
* @param fn - function being executed
|
|
313
|
+
* @returns The value returned by the executed function
|
|
314
|
+
*/
|
|
315
|
+
run<T>(name: string, fn: (ctx: DurableContext) => T | Promise<T>): Promise<T>;
|
|
316
|
+
/**
|
|
317
|
+
* Calls another function and awaits its result.
|
|
318
|
+
* similar to ctx.invoke()
|
|
319
|
+
* @remarks cannot be nested inside another step
|
|
320
|
+
* @param name - Step name
|
|
321
|
+
* @param input - Data passed to the called function
|
|
322
|
+
* @returns The value returned by the called function
|
|
323
|
+
*/
|
|
324
|
+
delegate<T>(name: string, input?: unknown): Promise<T>;
|
|
325
|
+
/**
|
|
326
|
+
* Waits for an external callback
|
|
327
|
+
* similar to ctx.waitForCallback()
|
|
328
|
+
* @remarks cannot be nested inside another step
|
|
329
|
+
* @param name - Step name
|
|
330
|
+
* @param fn - Receives the generated callbackId and returns a delivered promise
|
|
331
|
+
* @returns The value returned by the executed function
|
|
332
|
+
*/
|
|
333
|
+
waitForCallback<T>(name: string, fn: (callbackId: string, ctx: DurableContext) => Promise<void>): Promise<T>;
|
|
334
|
+
/**
|
|
335
|
+
* Waits for a specified duration
|
|
336
|
+
* similar to ctx.wait()
|
|
337
|
+
* @remarks cannot be nested inside another step
|
|
338
|
+
* @example
|
|
339
|
+
* Wait for 30 seconds
|
|
340
|
+
* ```ts
|
|
341
|
+
* await step.wait('wait30Sec', { seconds: 30 });
|
|
342
|
+
* ```
|
|
343
|
+
* Wait for 2 days and 3 hours
|
|
344
|
+
* ```ts
|
|
345
|
+
* await step.wait('waitALongTime', { days: 2, hours: 3 });
|
|
346
|
+
* ```
|
|
347
|
+
* @param name - Step name
|
|
348
|
+
* @param duration - Amount of time the function will wait before continuing.
|
|
349
|
+
* Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
|
|
350
|
+
* @returns Resolves after the duration
|
|
351
|
+
*/
|
|
352
|
+
wait(name: string, duration: DurableDuration): Promise<void>;
|
|
353
|
+
/**
|
|
354
|
+
* Waits for a specified duration
|
|
355
|
+
* similar to ctx.wait()
|
|
356
|
+
* @remarks cannot be nested inside another step
|
|
357
|
+
* @example
|
|
358
|
+
* Wait for 30 seconds
|
|
359
|
+
* ```ts
|
|
360
|
+
* await step.wait({ seconds: 30 });
|
|
361
|
+
* ```
|
|
362
|
+
* @param duration - Amount of time the function will wait before continuing.
|
|
363
|
+
* Duration is an object with properties of `seconds`, `minutes`, `hours`, or `days`. Must be at least {seconds: 1}
|
|
364
|
+
* @returns Resolves after the duration
|
|
365
|
+
*/
|
|
366
|
+
wait(duration: DurableDuration): Promise<void>;
|
|
367
|
+
/**
|
|
368
|
+
* Waits for a specified condition to be met
|
|
369
|
+
* similar to ctx.waitForCondition()
|
|
370
|
+
* @remarks cannot be nested inside another step
|
|
371
|
+
* @example
|
|
372
|
+
* ```ts
|
|
373
|
+
* await step.waitForCondition(
|
|
374
|
+
* 'waitForCondition',
|
|
375
|
+
* async (state, context) => {
|
|
376
|
+
* context.log.info('Checking for article', {
|
|
377
|
+
* runId: context.runId,
|
|
378
|
+
* attempt: context.attempt,
|
|
379
|
+
* })
|
|
380
|
+
*
|
|
381
|
+
* const client = createClient({
|
|
382
|
+
* apiVersion: '2026-08-05',
|
|
383
|
+
* ...context.clientOptions,
|
|
384
|
+
* })
|
|
385
|
+
* const article = await client.fetch<Article | null>(
|
|
386
|
+
* '*[_type == "article"][0]',
|
|
387
|
+
* )
|
|
388
|
+
* return {...state, article}
|
|
389
|
+
* },
|
|
390
|
+
* {
|
|
391
|
+
* initial: {
|
|
392
|
+
* article: null as Article | null,
|
|
393
|
+
* },
|
|
394
|
+
* next: (state, context) => {
|
|
395
|
+
* if (state.article) return {shouldContinue: false}
|
|
396
|
+
*
|
|
397
|
+
* return {
|
|
398
|
+
* shouldContinue: true,
|
|
399
|
+
* delay: {
|
|
400
|
+
* seconds: Math.min((context.attempt ?? 1) * 2, 60),
|
|
401
|
+
* },
|
|
402
|
+
* }
|
|
403
|
+
* },
|
|
404
|
+
* },
|
|
405
|
+
* )
|
|
406
|
+
* ```
|
|
407
|
+
* @param name - Step name
|
|
408
|
+
* @param fn - Called on each attempt with the current state and durable context.
|
|
409
|
+
* Returns a promise resolving to the updated state,
|
|
410
|
+
* which is passed to next to determine whether the condition has been met or another check should be scheduled.
|
|
411
|
+
* @param options - Configuration options for the condition
|
|
412
|
+
* @returns The value returned by the executed function
|
|
413
|
+
*/
|
|
414
|
+
waitForCondition<T>(name: string, fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
|
|
415
|
+
/**
|
|
416
|
+
* Waits for a specified condition to be met
|
|
417
|
+
* similar to ctx.waitForCondition()
|
|
418
|
+
* @remarks cannot be nested inside another step
|
|
419
|
+
* @example
|
|
420
|
+
* ```ts
|
|
421
|
+
* await step.waitForCondition(
|
|
422
|
+
* async (state, context) => {
|
|
423
|
+
* context.log.info('Checking for article', {
|
|
424
|
+
* runId: context.runId,
|
|
425
|
+
* attempt: context.attempt,
|
|
426
|
+
* })
|
|
427
|
+
*
|
|
428
|
+
* const client = createClient({
|
|
429
|
+
* apiVersion: '2026-08-05',
|
|
430
|
+
* ...context.clientOptions,
|
|
431
|
+
* })
|
|
432
|
+
* const article = await client.fetch<Article | null>(
|
|
433
|
+
* '*[_type == "article"][0]',
|
|
434
|
+
* )
|
|
435
|
+
* return {...state, article}
|
|
436
|
+
* },
|
|
437
|
+
* {
|
|
438
|
+
* initial: {
|
|
439
|
+
* article: null as Article | null,
|
|
440
|
+
* },
|
|
441
|
+
* next: (state, context) => {
|
|
442
|
+
* if (state.article) return {shouldContinue: false}
|
|
443
|
+
*
|
|
444
|
+
* return {
|
|
445
|
+
* shouldContinue: true,
|
|
446
|
+
* delay: {
|
|
447
|
+
* seconds: Math.min((context.attempt ?? 1) * 2, 60),
|
|
448
|
+
* },
|
|
449
|
+
* }
|
|
450
|
+
* },
|
|
451
|
+
* },
|
|
452
|
+
* )
|
|
453
|
+
* ```
|
|
454
|
+
* @param fn - Called on each attempt with the current state and durable context.
|
|
455
|
+
* Returns a promise resolving to the updated state,
|
|
456
|
+
* which is passed to next to determine whether the condition has been met or another check should be scheduled.
|
|
457
|
+
* @param options - Configuration options for the condition
|
|
458
|
+
* @returns The value returned by the executed function
|
|
459
|
+
*/
|
|
460
|
+
waitForCondition<T>(fn: (state: T, context: DurableContext) => Promise<T>, options: DurableWaitForConditionOptions<T>): Promise<T>;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* @alpha Using durables is considered experimental and may change in the future.
|
|
464
|
+
* @hidden
|
|
465
|
+
*/
|
|
466
|
+
export type DurableHandler = (envelope: {
|
|
467
|
+
context: DurableContext;
|
|
468
|
+
event?: GenericEvent;
|
|
469
|
+
step: DurableOperations;
|
|
470
|
+
}) => unknown | Promise<unknown>;
|
|
217
471
|
export {};
|
package/package.json
CHANGED
package/src/durables.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type {DurableHandler} from './types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Determine if `createDurable({}, () => {})` or `createDurable(() => {})`.
|
|
5
|
+
* @param configOrHandler
|
|
6
|
+
* @param maybeHandler
|
|
7
|
+
* @returns resolved arguments
|
|
8
|
+
*/
|
|
9
|
+
const resolveFuncArgs = <TConfig extends {name: string}>(
|
|
10
|
+
configOrHandler: TConfig | DurableHandler,
|
|
11
|
+
maybeHandler?: DurableHandler,
|
|
12
|
+
): {config?: TConfig; handler?: DurableHandler; hadConfigArg: boolean} => {
|
|
13
|
+
return typeof configOrHandler === 'function'
|
|
14
|
+
? {config: undefined, handler: configOrHandler, hadConfigArg: false}
|
|
15
|
+
: {config: configOrHandler, handler: maybeHandler, hadConfigArg: true}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Validates the config to ensure config contains proper elements
|
|
20
|
+
* @param config
|
|
21
|
+
* @returns Errors while validating a config object
|
|
22
|
+
*/
|
|
23
|
+
const validateConfig = (config: unknown) => {
|
|
24
|
+
const EVENT_TYPES = ['document', 'media-library', 'cron', 'sync-tag-invalidate']
|
|
25
|
+
const errors: string[] = []
|
|
26
|
+
|
|
27
|
+
if (config === undefined || config === null) {
|
|
28
|
+
errors.push('`config` must be defined')
|
|
29
|
+
return errors
|
|
30
|
+
}
|
|
31
|
+
if (typeof config !== 'object') {
|
|
32
|
+
errors.push('`config` must be an object')
|
|
33
|
+
return errors
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const name = 'name' in config ? config.name : undefined
|
|
37
|
+
const event = 'event' in config ? config.event : undefined
|
|
38
|
+
if (typeof name !== 'string') errors.push('`config.name` must be a string')
|
|
39
|
+
|
|
40
|
+
if ('event' in config) {
|
|
41
|
+
if (typeof event !== 'object' || event === null) {
|
|
42
|
+
errors.push('`event` must be an object')
|
|
43
|
+
} else if ('type' in event) {
|
|
44
|
+
if (typeof event.type !== 'string') {
|
|
45
|
+
errors.push('`event.type` must be defined')
|
|
46
|
+
} else if (!EVENT_TYPES.includes(event.type)) {
|
|
47
|
+
errors.push(`\`event.type\` must be one of: ${EVENT_TYPES.join(', ')}`)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return errors
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Durables creation function that can be called with or without a config object.
|
|
56
|
+
* @alpha Durables are an experimental feature and may change in the future.
|
|
57
|
+
* @hidden
|
|
58
|
+
* @param handler
|
|
59
|
+
* @returns The handler function, unmodified.
|
|
60
|
+
*/
|
|
61
|
+
export function createDurable(handler: DurableHandler): DurableHandler & {config?: undefined}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Durables creation function that can be called with or without a config object.
|
|
65
|
+
* @alpha Durables are an experimental feature and may change in the future.
|
|
66
|
+
* @hidden
|
|
67
|
+
* @param config
|
|
68
|
+
* @param handler
|
|
69
|
+
* @returns The handler function, unmodified and the provided config object.
|
|
70
|
+
*/
|
|
71
|
+
export function createDurable<TConfig extends {name: string}>(config: TConfig, handler: DurableHandler): DurableHandler & {config: TConfig}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Durables creation function that can be called with or without a config object.
|
|
75
|
+
* @alpha Durable functions are an experimental feature and may change in the future.
|
|
76
|
+
* @hidden
|
|
77
|
+
* @public
|
|
78
|
+
* @param configOrHandler
|
|
79
|
+
* @param maybeHandler
|
|
80
|
+
* @returns The handler function, unmodified and the config object if provided
|
|
81
|
+
*/
|
|
82
|
+
export function createDurable<TConfig extends {name: string}>(
|
|
83
|
+
configOrHandler: TConfig | DurableHandler,
|
|
84
|
+
maybeHandler?: DurableHandler,
|
|
85
|
+
): DurableHandler {
|
|
86
|
+
const {config, handler, hadConfigArg} = resolveFuncArgs(configOrHandler, maybeHandler)
|
|
87
|
+
const errors = [
|
|
88
|
+
...(hadConfigArg ? validateConfig(config) : []),
|
|
89
|
+
...(typeof handler !== 'function' ? ['`handler` must be a function'] : []),
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
if (errors.length > 0) {
|
|
93
|
+
throw new TypeError(errors.join(', '))
|
|
94
|
+
}
|
|
95
|
+
// Separate config from the handler during build
|
|
96
|
+
return Object.assign(handler as DurableHandler, {config})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* @alpha Durable functions are an experimental feature and may change in the future.
|
|
101
|
+
* @hidden
|
|
102
|
+
* @public
|
|
103
|
+
*/
|
|
104
|
+
export const durable = {createDurable}
|
package/src/index.ts
CHANGED
package/src/invoke.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import {Buffer} from 'node:buffer'
|
|
2
|
+
import crypto from 'node:crypto'
|
|
2
3
|
import {env} from 'node:process'
|
|
3
4
|
import type awsLite from '@aws-lite/client'
|
|
4
|
-
import type {FunctionPayload, FunctionResourceEnvelope} from './types.js'
|
|
5
|
-
|
|
6
|
-
const MAX_EVENT_SIZE_BYTES = 256 * 1024
|
|
5
|
+
import type {FunctionPayload, FunctionResourceEnvelope, InvokeOptions} from './types.js'
|
|
7
6
|
|
|
8
7
|
let awsPromise: Promise<awsLite.AwsLiteClient> | undefined
|
|
9
8
|
|
|
10
9
|
const PARTITION_KEY = 'arc-app-res'
|
|
10
|
+
/** @internal */
|
|
11
|
+
export const MAX_RECURSION_COUNT = 16
|
|
11
12
|
|
|
12
13
|
/**
|
|
14
|
+
* @internal
|
|
13
15
|
* lazy load aws-lite
|
|
14
16
|
*/
|
|
15
17
|
function getAwsLite() {
|
|
@@ -28,6 +30,7 @@ function getAwsLite() {
|
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
/**
|
|
33
|
+
* @internal
|
|
31
34
|
* Gets a specific resource based off of function name
|
|
32
35
|
* @param {string} name
|
|
33
36
|
*/
|
|
@@ -48,22 +51,93 @@ async function getResource(name: string, aws: awsLite.AwsLiteClient): Promise<Fu
|
|
|
48
51
|
return result.Item['resources'] as unknown as FunctionResourceEnvelope
|
|
49
52
|
}
|
|
50
53
|
|
|
51
|
-
|
|
54
|
+
/**
|
|
55
|
+
* @internal
|
|
56
|
+
* Generate a short UUID.
|
|
57
|
+
* @param {number} [length] - The length of the UUID to generate.
|
|
58
|
+
* @param {string} [characters] - The characters to use to generate the UUID.
|
|
59
|
+
* @returns {string} The generated UUID.
|
|
60
|
+
*/
|
|
61
|
+
export function genID(length = 32, characters = '23456789abcdefghijklmnopqrstuvwxyz') {
|
|
62
|
+
let result = ''
|
|
63
|
+
const bytes = crypto.randomBytes(length)
|
|
64
|
+
for (let i = 0; i < length; i++) {
|
|
65
|
+
result += characters[bytes[i] % characters.length]
|
|
66
|
+
}
|
|
67
|
+
return result
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @internal
|
|
72
|
+
* Builds the new lineage token given the existing token.
|
|
73
|
+
* @param {string} name
|
|
74
|
+
* @param {string | undefined} lineage
|
|
75
|
+
* @param {object} options
|
|
76
|
+
* @param {number} options.maxRecursionCount The maximum recursion depth
|
|
77
|
+
* @returns The new lineage token with the count incremented
|
|
78
|
+
*/
|
|
79
|
+
export function buildLineageToken(name: string, lineage: string | undefined) {
|
|
80
|
+
let recursionCount = 0
|
|
81
|
+
try {
|
|
82
|
+
if (lineage) {
|
|
83
|
+
// split the token, usually into two parts
|
|
84
|
+
const parts = lineage.trim().split(':')
|
|
85
|
+
if (parts.length > 1) {
|
|
86
|
+
// the current count is in the last part
|
|
87
|
+
const count = parts[parts.length - 1]
|
|
88
|
+
recursionCount = Number.parseInt(count, 10)
|
|
89
|
+
|
|
90
|
+
// if parsing didn't work or the value was invalid, reset to 0
|
|
91
|
+
if (Number.isNaN(recursionCount) || recursionCount < 0) {
|
|
92
|
+
recursionCount = 0
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// this handles whitespace, and also if the first parts of the token contained colons
|
|
96
|
+
lineage = parts.slice(0, -1).join(':')
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
} catch {
|
|
100
|
+
// ignore
|
|
101
|
+
}
|
|
102
|
+
if (recursionCount >= MAX_RECURSION_COUNT) {
|
|
103
|
+
throw new Error(`Function ${name} exceeded the maximum recursion depth of ${MAX_RECURSION_COUNT}`)
|
|
104
|
+
}
|
|
105
|
+
return `${lineage || genID(32)}:${recursionCount + 1}`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Invokes another Sanity Function.
|
|
110
|
+
*
|
|
111
|
+
* By default the invocation is async: the payload is handed off to the function's
|
|
112
|
+
* event source and nothing is returned. Pass `{sync: true}` to invoke the function and
|
|
113
|
+
* wait for its return value.
|
|
114
|
+
*
|
|
115
|
+
* @param name - Name of the function to invoke
|
|
116
|
+
* @param payload - The `{event, context}` envelope to deliver
|
|
117
|
+
* @param options - Set `sync: true` to wait for and return the function's result
|
|
118
|
+
*/
|
|
119
|
+
export async function invoke<T = unknown>(name: string, payload: FunctionPayload, options: InvokeOptions & {sync: true}): Promise<T>
|
|
120
|
+
export async function invoke(name: string, payload: FunctionPayload, options?: InvokeOptions & {sync?: false}): Promise<void>
|
|
121
|
+
export async function invoke<T = unknown>(name: string, payload: FunctionPayload, options?: InvokeOptions): Promise<T | undefined> {
|
|
52
122
|
if (!name) throw new Error('Function name was not provided')
|
|
123
|
+
const sync = options?.sync ?? false
|
|
53
124
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
125
|
+
// Update lineage or throw error if we exceed the max recursion value
|
|
126
|
+
const outgoingPayload: FunctionPayload = {
|
|
127
|
+
...payload,
|
|
128
|
+
context: {...payload.context, lineage: buildLineageToken(name, payload.context?.lineage)},
|
|
58
129
|
}
|
|
59
130
|
|
|
131
|
+
const stringPayload = JSON.stringify(outgoingPayload)
|
|
132
|
+
// Check to make sure payload is not over the max we can handle
|
|
133
|
+
checkPayloadSize(stringPayload, sync)
|
|
134
|
+
|
|
60
135
|
// Local invoke path for Sanity CLI
|
|
61
|
-
if (
|
|
62
|
-
if (!
|
|
136
|
+
if (outgoingPayload?.context?.local) {
|
|
137
|
+
if (!outgoingPayload?.context?.invoke) {
|
|
63
138
|
throw new Error(`No local invoke handler configured for function: ${name}`)
|
|
64
139
|
}
|
|
65
|
-
|
|
66
|
-
return
|
|
140
|
+
return await outgoingPayload.context.invoke(name, outgoingPayload, options)
|
|
67
141
|
}
|
|
68
142
|
|
|
69
143
|
const aws = await getAwsLite()
|
|
@@ -71,25 +145,55 @@ export async function invoke(name: string, payload: FunctionPayload) {
|
|
|
71
145
|
|
|
72
146
|
// Look up the function details
|
|
73
147
|
const resource = await getResource(name, aws)
|
|
148
|
+
const contextResource = payload?.context?.resources?.(name)
|
|
149
|
+
|
|
150
|
+
// Synchronous invocation
|
|
151
|
+
if (sync === true) {
|
|
152
|
+
if (!resource.function || !contextResource) {
|
|
153
|
+
throw new Error(`Function ${name} cannot be invoked synchronously.`)
|
|
154
|
+
}
|
|
155
|
+
if (contextResource.type !== 'sanity.function.pubsub') {
|
|
156
|
+
throw new Error(`Function ${name} of type ${contextResource.type} cannot be invoked synchronously.`)
|
|
157
|
+
}
|
|
158
|
+
const {Payload, FunctionError} = await aws.Lambda.Invoke({
|
|
159
|
+
FunctionName: resource.function.physicalResourceId,
|
|
160
|
+
Payload: outgoingPayload,
|
|
161
|
+
InvocationType: 'RequestResponse',
|
|
162
|
+
})
|
|
163
|
+
if (FunctionError) {
|
|
164
|
+
const detail = typeof Payload === 'object' && Payload !== null ? (Payload as {errorMessage?: string}).errorMessage : undefined
|
|
165
|
+
throw new Error(`Function ${name} failed: ${detail ?? FunctionError}`)
|
|
166
|
+
}
|
|
167
|
+
// TODO: can we not type cast? might be an aws-lite issue, why is the return type UInt8BlobAdapter
|
|
168
|
+
return Payload as T
|
|
169
|
+
}
|
|
74
170
|
|
|
75
|
-
//
|
|
76
|
-
if (resource.topic) {
|
|
171
|
+
// Async invocation by type
|
|
172
|
+
if (resource.topic && contextResource?.type === 'sanity.function.pubsub') {
|
|
77
173
|
await aws.SNS.Publish({
|
|
78
174
|
TopicArn: resource.topic.physicalResourceId,
|
|
79
175
|
Message: stringPayload,
|
|
80
176
|
})
|
|
81
|
-
} else if (resource.queue) {
|
|
177
|
+
} else if (resource.queue && contextResource?.type === 'sanity.function.queue') {
|
|
82
178
|
await aws.SQS.SendMessage({
|
|
83
179
|
MessageBody: stringPayload,
|
|
84
180
|
QueueUrl: resource.queue.physicalResourceId,
|
|
85
181
|
})
|
|
86
|
-
} else if (resource.function) {
|
|
87
|
-
await aws.Lambda.Invoke({
|
|
88
|
-
FunctionName: resource.function.physicalResourceId,
|
|
89
|
-
Payload: payload,
|
|
90
|
-
InvocationType: 'Event',
|
|
91
|
-
})
|
|
92
182
|
} else {
|
|
93
183
|
throw new Error(`No invokeable resource for function: ${name}`)
|
|
94
184
|
}
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @internal */
|
|
189
|
+
function checkPayloadSize(payload: string, sync: boolean) {
|
|
190
|
+
if (sync) {
|
|
191
|
+
if (Buffer.byteLength(payload, 'utf8') > 6 * 1024 * 1024) {
|
|
192
|
+
throw new Error(`Payload exceeds maximum size of 6MB`)
|
|
193
|
+
}
|
|
194
|
+
} else {
|
|
195
|
+
if (Buffer.byteLength(payload, 'utf8') > 256 * 1024) {
|
|
196
|
+
throw new Error(`Payload exceeds maximum size of 256KB`)
|
|
197
|
+
}
|
|
198
|
+
}
|
|
95
199
|
}
|