-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtypes.ts
521 lines (489 loc) · 12.8 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import type { FlowControl, Receiver } from "@upstash/qstash";
import type { Client } from "@upstash/qstash";
import type { HTTPMethods } from "@upstash/qstash";
import type { WorkflowContext } from "./context";
import type { WorkflowLogger } from "./logger";
import { z } from "zod";
/**
* Interface for Client with required methods
*
* Neeeded to resolve import issues
*/
export type WorkflowClient = {
batch: InstanceType<typeof Client>["batch"];
batchJSON: InstanceType<typeof Client>["batchJSON"];
publishJSON: InstanceType<typeof Client>["publishJSON"];
publish: InstanceType<typeof Client>["publish"];
http: InstanceType<typeof Client>["http"];
};
/**
* Interface for Receiver with required methods
*
* Neeeded to resolve import issues
*/
export type WorkflowReceiver = {
verify: InstanceType<typeof Receiver>["verify"];
};
export const StepTypes = [
"Initial",
"Run",
"SleepFor",
"SleepUntil",
"Call",
"Wait",
"Notify",
"Invoke",
] as const;
export type StepType = (typeof StepTypes)[number];
type ThirdPartyCallFields<TBody = unknown> = {
/**
* Third party call URL. Set when context.call is used.
*/
callUrl: string;
/**
* Third party call method. Set when context.call is used.
*/
callMethod: HTTPMethods;
/**
* Third party call body. Set when context.call is used.
*/
callBody: TBody;
/**
* Third party call headers. Set when context.call is used.
*/
callHeaders: Record<string, string>;
};
type WaitFields = {
waitEventId: string;
timeout: string;
waitTimeout?: boolean;
};
type NotifyFields = {
notifyEventId?: string;
eventData?: string;
};
export type Step<TResult = unknown, TBody = unknown> = {
/**
* index of the step
*/
stepId: number;
/**
* name of the step
*/
stepName: string;
/**
* type of the step (Initial/Run/SleepFor/SleepUntil/Call)
*/
stepType: StepType;
/**
* step result. Set if context.run or context.call are used.
*/
out?: TResult;
/**
* sleep duration in seconds. Set when context.sleep is used.
*/
sleepFor?: number | Duration;
/**
* unix timestamp (in seconds) to wait until. Set when context.sleepUntil is used.
*/
sleepUntil?: number;
/**
* number of steps running concurrently if the step is in a parallel run.
* Set to 1 if step is not parallel.
*/
concurrent: number;
/**
* target step of a plan step. In other words, the step to assign the
* result of a plan step.
*
* undefined if the step is not a plan step (of a parallel run). Otherwise,
* set to the target step.
*/
targetStep?: number;
} & (ThirdPartyCallFields<TBody> | { [P in keyof ThirdPartyCallFields]?: never }) &
(WaitFields | { [P in keyof WaitFields]?: never }) &
(NotifyFields | { [P in keyof NotifyFields]?: never });
export type RawStep = {
messageId: string;
body: string; // body is a base64 encoded step or payload
callType: "step" | "toCallback" | "fromCallback";
};
export type SyncStepFunction<TResult> = () => TResult;
export type AsyncStepFunction<TResult> = () => Promise<TResult>;
export type StepFunction<TResult> = AsyncStepFunction<TResult> | SyncStepFunction<TResult>;
export type ParallelCallState = "first" | "partial" | "discard" | "last";
export type RouteFunction<TInitialPayload, TResult = unknown> = (
context: WorkflowContext<TInitialPayload>
) => Promise<TResult>;
export type FinishCondition =
| "success"
| "duplicate-step"
| "fromCallback"
| "auth-fail"
| "failure-callback"
| "workflow-already-ended";
export type WorkflowServeOptions<
TResponse extends Response = Response,
TInitialPayload = unknown,
> = ValidationOptions<TInitialPayload> & {
/**
* QStash client
*/
qstashClient?: WorkflowClient;
/**
* Function called to return a response after each step execution
*
* @param workflowRunId
* @returns response
*/
onStepFinish?: (workflowRunId: string, finishCondition: FinishCondition) => TResponse;
/**
* Url of the endpoint where the workflow is set up.
*
* If not set, url will be inferred from the request.
*/
url?: string;
/**
* Verbose mode
*
* Disabled if not set. If set to true, a logger is created automatically.
*
* Alternatively, a WorkflowLogger can be passed.
*/
verbose?: WorkflowLogger | true;
/**
* Receiver to verify *all* requests by checking if they come from QStash
*
* By default, a receiver is created from the env variables
* QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY if they are set.
*/
receiver?: WorkflowReceiver;
/**
* Url to call if QStash retries are exhausted while executing the workflow
*/
failureUrl?: string;
/**
* Error handler called when an error occurs in the workflow. This is
* different from `failureFunction` in that it is called when an error
* occurs in the workflow, while `failureFunction` is called when QStash
* retries are exhausted.
*/
onError?: (error: Error) => void;
/**
* Failure function called when QStash retries are exhausted while executing
* the workflow. Will overwrite `failureUrl` parameter with the workflow
* endpoint if passed.
*
* @param context workflow context at the moment of error
* @param failStatus error status
* @param failResponse error message
* @returns void
*/
failureFunction?: (failureData: {
context: Omit<
WorkflowContext<TInitialPayload>,
| "run"
| "sleepUntil"
| "sleep"
| "call"
| "waitForEvent"
| "notify"
| "cancel"
| "api"
| "invoke"
| "agents"
>;
failStatus: number;
failResponse: string;
failHeaders: Record<string, string[]>;
}) => Promise<void> | void;
/**
* Base Url of the workflow endpoint
*
* Can be used to set if there is a local tunnel or a proxy between
* QStash and the workflow endpoint.
*
* Will be set to the env variable UPSTASH_WORKFLOW_URL if not passed.
* If the env variable is not set, the url will be infered as usual from
* the `request.url` or the `url` parameter in `serve` options.
*
* @default undefined
*/
baseUrl?: string;
/**
* Optionally, one can pass an env object mapping environment
* variables to their keys.
*
* Useful in cases like cloudflare with hono.
*/
env?: Record<string, string | undefined>;
/**
* Number of retries to use in workflow requests
*
* @default 3
*/
retries?: number;
/**
* Whether the framework should use `content-type: application/json`
* in `triggerFirstInvocation`.
*
* Not part of the public API. Only available in serveBase, which is not exported.
*/
useJSONContent?: boolean;
/**
* By default, Workflow SDK sends telemetry about SDK version, framework or runtime.
*
* Set `disableTelemetry` to disable this behavior.
*
* @default false
*/
disableTelemetry?: boolean;
/**
* Settings for controlling the number of active requests
* and number of requests per second with the same key.
*/
flowControl?: FlowControl;
} & ValidationOptions<TInitialPayload>;
type ValidationOptions<TInitialPayload> = {
schema?: z.ZodType<TInitialPayload>;
initialPayloadParser?: (initialPayload: string) => TInitialPayload;
};
export type ExclusiveValidationOptions<TInitialPayload> =
| {
schema?: ValidationOptions<TInitialPayload>["schema"];
initialPayloadParser?: never;
}
| {
schema?: never;
initialPayloadParser?: ValidationOptions<TInitialPayload>["initialPayloadParser"];
};
export type Telemetry = {
/**
* sdk version
*/
sdk: string;
/**
* platform (such as nextjs/cloudflare)
*/
framework: string;
/**
* node version
*/
runtime?: string;
};
export type PublicServeOptions<
TInitialPayload = unknown,
TResponse extends Response = Response,
> = Omit<
WorkflowServeOptions<TResponse, TInitialPayload>,
"onStepFinish" | "useJSONContent" | "schema" | "initialPayloadParser"
> &
ExclusiveValidationOptions<TInitialPayload>;
/**
* Payload passed as body in failureFunction
*/
export type FailureFunctionPayload = {
/**
* error name
*/
error: string;
/**
* error message
*/
message: string;
};
/**
* Makes all fields except the ones selected required
*/
export type RequiredExceptFields<T, K extends keyof T> = Omit<Required<T>, K> & Partial<Pick<T, K>>;
export type Waiter = {
url: string;
deadline: number;
headers: Record<string, string[]>;
timeoutUrl?: string;
timeoutBody?: unknown;
timeoutHeaders?: Record<string, string[]>;
};
export type NotifyResponse = {
waiter: Waiter;
messageId: string;
error: string;
};
export type WaitRequest = {
url: string;
step: Step;
timeout: string;
timeoutUrl?: string;
timeoutBody?: string;
timeoutHeaders?: Record<string, string[]>;
};
export type WaitStepResponse = {
/**
* whether the wait for event step timed out. false if
* the step is notified
*/
timeout: boolean;
/**
* body passed in notify request
*/
eventData: unknown;
};
export type NotifyStepResponse = {
/**
* notified event id
*/
eventId: string;
/**
* event data sent with notify
*/
eventData: unknown;
/**
* response from notify
*/
notifyResponse: NotifyResponse[];
};
export type CallResponse<TResult = unknown> = {
status: number;
body: TResult;
header: Record<string, string[]>;
};
/**
* Valid duration string formats
* @example "30s" // 30 seconds
* @example "5m" // 5 minutes
* @example "2h" // 2 hours
* @example "1d" // 1 day
*/
export type Duration = `${bigint}${"s" | "m" | "h" | "d"}`;
export interface WaitEventOptions {
/**
* Duration in seconds to wait for an event before timing out the workflow.
* @example 300 // 5 minutes in seconds
* @example "5m" // 5 minutes as duration string
* @default "7d"
*/
timeout?: number | Duration;
}
export type CallSettings<TBody = unknown> = {
url: string;
method?: HTTPMethods;
body?: TBody;
headers?: Record<string, string>;
retries?: number;
timeout?: Duration | number;
flowControl?: FlowControl;
};
export type HeaderParams = {
/**
* whether the request is a first invocation request.
*/
initHeaderValue: "true" | "false";
/**
* run id of the workflow
*/
workflowRunId: string;
/**
* url where the workflow is hosted
*/
workflowUrl: string;
/**
* user headers which will be forwarded in the request
*/
userHeaders?: Headers;
/**
* failure url to call incase of failure
*/
failureUrl?: WorkflowServeOptions["failureUrl"];
/**
* retry setting of requests except context.call
*/
retries?: number;
/**
* telemetry to include in timeoutHeaders.
*
* Only needed/used when the step is a waitForEvent step
*/
telemetry?: Telemetry;
/**
* invoke count to include in headers
*/
invokeCount?: number;
/**
* Settings for controlling the number of active requests
* and number of requests per second with the same key.
*/
flowControl?: FlowControl;
} & (
| {
/**
* step to generate headers for
*/
step: Step;
/**
* number of retries in context.call
*/
callRetries?: number;
/**
* timeout duration in context.call
*/
callTimeout?: number | Duration;
/**
* Settings for controlling the number of active requests
* and number of requests per second with the same key.
*
* will be passed in context.call.
*/
callFlowControl?: FlowControl;
}
| {
/**
* step not passed. Either first invocation or simply getting headers for
* third party callack.
*/
step?: never;
/**
* number of retries in context.call
*
* set to never because this is not a context.call step
*/
callRetries?: never;
/**
* timeout duration in context.call
*
* set to never because this is not a context.call step
*/
callTimeout?: never;
/**
* Settings for controlling the number of active requests
* and number of requests per second with the same key.
*
* will be passed in context.call.
*/
callFlowControl?: never;
}
);
export type InvokeWorkflowRequest = {
workflowUrl: string;
workflowRunId: string;
headers: Record<string, string[]>;
step: Step;
body: string;
};
export type LazyInvokeStepParams<TInitiaPayload, TResult> = {
workflow: Pick<
InvokableWorkflow<TInitiaPayload, TResult>,
"routeFunction" | "workflowId" | "options"
>;
body: TInitiaPayload; // TODO make optional
workflowRunId?: string;
} & Pick<CallSettings, "retries" | "headers" | "flowControl">;
export type InvokeStepResponse<TBody> = {
body: TBody;
isCanceled?: boolean;
isFailed?: boolean;
};
export type InvokableWorkflow<TInitialPayload, TResult> = {
routeFunction: RouteFunction<TInitialPayload, TResult>;
options: WorkflowServeOptions<Response, TInitialPayload>;
workflowId?: string;
};