@farm.js/jobs 0.1.66 → 0.1.68
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/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +14 -0
- package/dist/index.d.ts +75 -30
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +59 -71
- package/dist/local.d.ts +67 -0
- package/dist/local.d.ts.map +1 -0
- package/dist/local.js +568 -0
- package/dist/runtime.d.ts +169 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +345 -0
- package/dist/testing.d.ts +46 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +251 -0
- package/dist/time.d.ts +21 -0
- package/dist/time.d.ts.map +1 -0
- package/dist/time.js +66 -0
- package/package.json +7 -3
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { JobsBatchTriggerRunResult, JobsCancelResult, JobsResolvedBatchItem, JobsResolvedLaunchOptions, JobsRunStatus, JobsRunStatusResult, JobsRuntimeCapabilities, JobsTaskDefinition } from "./index.js";
|
|
2
|
+
/**
|
|
3
|
+
* The version of the runtime contract this package implements. A runtime made
|
|
4
|
+
* with `defineJobsRuntime()` records the version it was built against, and
|
|
5
|
+
* `jobs()` refuses one built for a different version.
|
|
6
|
+
*/
|
|
7
|
+
export declare const JOBS_RUNTIME_CONTRACT = 1;
|
|
8
|
+
export type JobsRuntimeLogger = Pick<Console, "debug" | "info" | "warn" | "error">;
|
|
9
|
+
/** A task as a runtime sees it. `remoteId` is what `resolveRemoteId` returned. */
|
|
10
|
+
export interface JobsRuntimeTask {
|
|
11
|
+
readonly key: string;
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly remoteId: string;
|
|
14
|
+
readonly definition: JobsTaskDefinition<any, any>;
|
|
15
|
+
}
|
|
16
|
+
export interface JobsRuntimeLaunch {
|
|
17
|
+
handleId: string;
|
|
18
|
+
/** ISO timestamp. Defaults to the time the launch returned. */
|
|
19
|
+
queuedAt?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface JobsRuntimeBatchLaunch {
|
|
22
|
+
batchId?: string | null;
|
|
23
|
+
runs: readonly {
|
|
24
|
+
index: number;
|
|
25
|
+
handleId: string;
|
|
26
|
+
queuedAt?: string;
|
|
27
|
+
}[];
|
|
28
|
+
}
|
|
29
|
+
/** What a runtime's `status` returns. Farm fills omitted fields with `null` or `[]`. */
|
|
30
|
+
export interface JobsRuntimeRunStatus {
|
|
31
|
+
status: JobsRunStatus;
|
|
32
|
+
providerRunId?: string | null;
|
|
33
|
+
providerStatus?: string | null;
|
|
34
|
+
queuedAt?: string | null;
|
|
35
|
+
startedAt?: string | null;
|
|
36
|
+
finishedAt?: string | null;
|
|
37
|
+
output?: unknown;
|
|
38
|
+
error?: unknown;
|
|
39
|
+
tags?: readonly string[];
|
|
40
|
+
raw?: unknown;
|
|
41
|
+
}
|
|
42
|
+
export type JobsRuntimeRouteVerdict = boolean | Response;
|
|
43
|
+
/**
|
|
44
|
+
* A route the runtime itself needs, such as a tick a scheduler calls or a
|
|
45
|
+
* provider webhook. It is mounted at `<basePath>/_runtime/<kind>/<path>`.
|
|
46
|
+
*/
|
|
47
|
+
export interface JobsRuntimeRoute {
|
|
48
|
+
method: "GET" | "POST";
|
|
49
|
+
/** Lowercase segments separated by `/`, for example `"tick"`. */
|
|
50
|
+
path: string;
|
|
51
|
+
/**
|
|
52
|
+
* Decides whether the request may reach `handler`: `true` allows it, `false`
|
|
53
|
+
* answers `401`, and a Response is sent as is. Required, because these routes
|
|
54
|
+
* are called by schedulers and providers rather than by the app's users.
|
|
55
|
+
*/
|
|
56
|
+
verify(request: Request): JobsRuntimeRouteVerdict | Promise<JobsRuntimeRouteVerdict>;
|
|
57
|
+
handler(request: Request): Response | Promise<Response>;
|
|
58
|
+
}
|
|
59
|
+
/** The object a runtime's `create()` returns. */
|
|
60
|
+
export interface JobsRuntime {
|
|
61
|
+
/** What the runtime can honor. Farm rejects any option whose capability is `false`. */
|
|
62
|
+
readonly capabilities: JobsRuntimeCapabilities;
|
|
63
|
+
/** Whether credentials are present, reported by `api.jobs.tasks.list()`. Defaults to `true`. */
|
|
64
|
+
isConfigured?(): boolean;
|
|
65
|
+
/** The provider-side name for a task id. Defaults to the id itself. */
|
|
66
|
+
resolveRemoteId?(taskId: string): string;
|
|
67
|
+
/** Throw to refuse a task at setup. Unsupported task defaults are already refused. */
|
|
68
|
+
validateTask?(task: JobsRuntimeTask): void;
|
|
69
|
+
trigger(task: JobsRuntimeTask, input: unknown, options: JobsResolvedLaunchOptions): Promise<JobsRuntimeLaunch>;
|
|
70
|
+
/** Optional. Without it, a batch triggers each item in order. */
|
|
71
|
+
batchTrigger?(task: JobsRuntimeTask, items: readonly JobsResolvedBatchItem[]): Promise<JobsRuntimeBatchLaunch>;
|
|
72
|
+
/** Throw `new JobsRuntimeError(message, 404)` for a run that is not this task's. */
|
|
73
|
+
status(task: JobsRuntimeTask, handleId: string): Promise<JobsRuntimeRunStatus>;
|
|
74
|
+
/** Required when `capabilities.cancel` is `true`. */
|
|
75
|
+
cancel?(task: JobsRuntimeTask, handleId: string): Promise<void>;
|
|
76
|
+
routes?: readonly JobsRuntimeRoute[];
|
|
77
|
+
/** Called when the app's server starts, never during `farm build`. Start timers here. */
|
|
78
|
+
start?(): void | Promise<void>;
|
|
79
|
+
/** Called when the app shuts down. Stop timers and close connections here. */
|
|
80
|
+
dispose?(): void | Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
export interface JobsExecuteInput {
|
|
83
|
+
/** The task key, as stored with the run. */
|
|
84
|
+
task: string;
|
|
85
|
+
input: unknown;
|
|
86
|
+
run: {
|
|
87
|
+
id: string;
|
|
88
|
+
attempt: number;
|
|
89
|
+
};
|
|
90
|
+
signal?: AbortSignal;
|
|
91
|
+
}
|
|
92
|
+
/** A task error reduced to its name and message, so it can be stored and returned. */
|
|
93
|
+
export interface JobsSerializedError {
|
|
94
|
+
name: string;
|
|
95
|
+
message: string;
|
|
96
|
+
}
|
|
97
|
+
export type JobsExecuteResult = {
|
|
98
|
+
ok: true;
|
|
99
|
+
output: unknown;
|
|
100
|
+
} | {
|
|
101
|
+
ok: false;
|
|
102
|
+
error: JobsSerializedError;
|
|
103
|
+
};
|
|
104
|
+
export interface JobsRuntimeContext {
|
|
105
|
+
readonly kind: string;
|
|
106
|
+
/** The jobs integration's route prefix, such as `/api/jobs`. */
|
|
107
|
+
readonly basePath: string;
|
|
108
|
+
/** The full path a runtime route with this `path` is mounted at. */
|
|
109
|
+
routePath(path: string): string;
|
|
110
|
+
/** The task registered under this key. Available once `jobs()` has finished setup. */
|
|
111
|
+
getTask(key: string): JobsRuntimeTask | undefined;
|
|
112
|
+
/**
|
|
113
|
+
* Calls the task's `run` in this process. A thrown error becomes
|
|
114
|
+
* `{ ok: false }`; an unknown task key throws a `JobsRuntimeError` with 404.
|
|
115
|
+
*/
|
|
116
|
+
execute(input: JobsExecuteInput): Promise<JobsExecuteResult>;
|
|
117
|
+
readonly logger: JobsRuntimeLogger;
|
|
118
|
+
}
|
|
119
|
+
/** A runtime ready to pass to `jobs({ runtime })`. */
|
|
120
|
+
export interface CustomJobsRuntimeDefinition<TKind extends string = string> {
|
|
121
|
+
readonly kind: TKind;
|
|
122
|
+
readonly contract: number;
|
|
123
|
+
/**
|
|
124
|
+
* Builds the runtime. It runs whenever the app loads its integrations,
|
|
125
|
+
* including during `farm build`, so open connections and start timers lazily.
|
|
126
|
+
*/
|
|
127
|
+
create(context: JobsRuntimeContext): JobsRuntime;
|
|
128
|
+
}
|
|
129
|
+
export interface DefineJobsRuntimeInput<TKind extends string> {
|
|
130
|
+
/** Lowercase letters, digits, and dashes, starting with a letter. */
|
|
131
|
+
kind: TKind;
|
|
132
|
+
create(context: JobsRuntimeContext): JobsRuntime;
|
|
133
|
+
}
|
|
134
|
+
/** Declares a jobs runtime that `jobs({ runtime })` accepts alongside the built-in ones. */
|
|
135
|
+
export declare function defineJobsRuntime<const TKind extends string>(input: DefineJobsRuntimeInput<TKind>): CustomJobsRuntimeDefinition<TKind>;
|
|
136
|
+
export declare function isCustomJobsRuntimeDefinition(value: unknown): value is CustomJobsRuntimeDefinition;
|
|
137
|
+
export interface JobsRuntimeSetup {
|
|
138
|
+
basePath: string;
|
|
139
|
+
routePath(kind: string, path: string): string;
|
|
140
|
+
getTask(key: string): JobsRuntimeTask | undefined;
|
|
141
|
+
}
|
|
142
|
+
export interface AdaptedJobsRuntimeRoute extends JobsRuntimeRoute {
|
|
143
|
+
fullPath: string;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Builds a custom runtime and wraps it in the shape the built-in runtimes
|
|
147
|
+
* have, enforcing its declared capabilities in one place.
|
|
148
|
+
*/
|
|
149
|
+
export declare function adaptCustomRuntime(definition: CustomJobsRuntimeDefinition, setup: JobsRuntimeSetup): {
|
|
150
|
+
kind: string;
|
|
151
|
+
capabilities: JobsRuntimeCapabilities;
|
|
152
|
+
routes: AdaptedJobsRuntimeRoute[];
|
|
153
|
+
isConfigured(): boolean;
|
|
154
|
+
resolveRemoteId(taskId: string): string;
|
|
155
|
+
validateTask(task: JobsRuntimeTask): void;
|
|
156
|
+
trigger(task: JobsRuntimeTask, input: unknown, options: JobsResolvedLaunchOptions): Promise<{
|
|
157
|
+
handleId: string;
|
|
158
|
+
queuedAt: string;
|
|
159
|
+
}>;
|
|
160
|
+
batchTrigger(task: JobsRuntimeTask, items: readonly JobsResolvedBatchItem[]): Promise<{
|
|
161
|
+
batchId: string | null;
|
|
162
|
+
runs: JobsBatchTriggerRunResult[];
|
|
163
|
+
}>;
|
|
164
|
+
status(task: JobsRuntimeTask, handleId: string): Promise<Omit<JobsRunStatusResult<unknown, string>, "task" | "runtime">>;
|
|
165
|
+
cancel(task: JobsRuntimeTask, handleId: string): Promise<JobsCancelResult<string>>;
|
|
166
|
+
start(): Promise<void>;
|
|
167
|
+
dispose(): Promise<void>;
|
|
168
|
+
};
|
|
169
|
+
//# sourceMapping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AAe,SACd,SAAS,qBAAqB,EAAE,GACtC,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,IAAI,EAAE,yBAAyB,EAAE,CAAA;KAAE,CAAC;iBAuCjE,eAAe,YACX,MAAM,GACf,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;iBAqBvD,eAAe,YAAY,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;;;EAgB3F"}
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { JobsRuntimeError } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* The version of the runtime contract this package implements. A runtime made
|
|
4
|
+
* with `defineJobsRuntime()` records the version it was built against, and
|
|
5
|
+
* `jobs()` refuses one built for a different version.
|
|
6
|
+
*/
|
|
7
|
+
export const JOBS_RUNTIME_CONTRACT = 1;
|
|
8
|
+
/** Declares a jobs runtime that `jobs({ runtime })` accepts alongside the built-in ones. */
|
|
9
|
+
export function defineJobsRuntime(input) {
|
|
10
|
+
return {
|
|
11
|
+
kind: input.kind,
|
|
12
|
+
contract: JOBS_RUNTIME_CONTRACT,
|
|
13
|
+
create: input.create,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function isCustomJobsRuntimeDefinition(value) {
|
|
17
|
+
return (!!value &&
|
|
18
|
+
typeof value === "object" &&
|
|
19
|
+
typeof value.create === "function");
|
|
20
|
+
}
|
|
21
|
+
const CAPABILITY_KEYS = [
|
|
22
|
+
"delay",
|
|
23
|
+
"schedule",
|
|
24
|
+
"debounce",
|
|
25
|
+
"tags",
|
|
26
|
+
"cancel",
|
|
27
|
+
"batchTrigger",
|
|
28
|
+
"queue",
|
|
29
|
+
"retry",
|
|
30
|
+
"ttl",
|
|
31
|
+
"concurrencyKey",
|
|
32
|
+
"idempotencyKey",
|
|
33
|
+
];
|
|
34
|
+
const RUN_STATUSES = new Set([
|
|
35
|
+
"queued",
|
|
36
|
+
"delayed",
|
|
37
|
+
"running",
|
|
38
|
+
"waiting",
|
|
39
|
+
"completed",
|
|
40
|
+
"failed",
|
|
41
|
+
"canceled",
|
|
42
|
+
"expired",
|
|
43
|
+
"unknown",
|
|
44
|
+
]);
|
|
45
|
+
const KIND_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
46
|
+
const ROUTE_PATH_PATTERN = /^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/;
|
|
47
|
+
const BUILT_IN_KINDS = new Set(["trigger", "inngest"]);
|
|
48
|
+
function unsupported(kind, capability, status, what) {
|
|
49
|
+
return new JobsRuntimeError(`The "${kind}" jobs runtime does not support ${what}; check task metadata capabilities before sending.`, status, {
|
|
50
|
+
code: "JOBS_RUNTIME_CAPABILITY_UNSUPPORTED",
|
|
51
|
+
runtime: kind,
|
|
52
|
+
capability,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function serializeError(error) {
|
|
56
|
+
if (error instanceof Error) {
|
|
57
|
+
return { name: error.name || "Error", message: error.message };
|
|
58
|
+
}
|
|
59
|
+
// Never stringify an arbitrary thrown object: it can carry user data.
|
|
60
|
+
return { name: "Error", message: typeof error === "string" ? error : "Task run failed." };
|
|
61
|
+
}
|
|
62
|
+
function createLogger(prefix) {
|
|
63
|
+
return {
|
|
64
|
+
debug: (...args) => console.debug(prefix, ...args),
|
|
65
|
+
info: (...args) => console.info(prefix, ...args),
|
|
66
|
+
warn: (...args) => console.warn(prefix, ...args),
|
|
67
|
+
error: (...args) => console.error(prefix, ...args),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function isNonEmptyString(value) {
|
|
71
|
+
return typeof value === "string" && value.length > 0;
|
|
72
|
+
}
|
|
73
|
+
function validateDefinition(definition) {
|
|
74
|
+
const issues = [];
|
|
75
|
+
const kind = definition.kind;
|
|
76
|
+
if (typeof kind !== "string" || !KIND_PATTERN.test(kind)) {
|
|
77
|
+
issues.push(`\`kind\` must be lowercase letters, digits, and dashes, starting with a letter; received ${JSON.stringify(kind)}.`);
|
|
78
|
+
}
|
|
79
|
+
else if (BUILT_IN_KINDS.has(kind)) {
|
|
80
|
+
issues.push(`\`kind\` "${kind}" is reserved for the built-in ${kind}() runtime. Pick another name.`);
|
|
81
|
+
}
|
|
82
|
+
if (definition.contract !== JOBS_RUNTIME_CONTRACT) {
|
|
83
|
+
issues.push(`it was built for jobs runtime contract ${JSON.stringify(definition.contract)}, but this @farm.js/jobs implements contract ${JOBS_RUNTIME_CONTRACT}. Install versions of @farm.js/jobs and the runtime package that match, and create runtimes with defineJobsRuntime().`);
|
|
84
|
+
}
|
|
85
|
+
if (issues.length > 0) {
|
|
86
|
+
throw new TypeError(`Jobs runtime ${JSON.stringify(kind)} is invalid:\n${issues.map((issue) => `- ${issue}`).join("\n")}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function validateRuntime(kind, runtime) {
|
|
90
|
+
const issues = [];
|
|
91
|
+
if (!runtime || typeof runtime !== "object") {
|
|
92
|
+
throw new TypeError(`Jobs runtime "${kind}" create() must return an object.`);
|
|
93
|
+
}
|
|
94
|
+
const capabilities = runtime.capabilities;
|
|
95
|
+
if (!capabilities || typeof capabilities !== "object") {
|
|
96
|
+
issues.push("`capabilities` must be an object with a boolean for every capability.");
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
const missing = CAPABILITY_KEYS.filter((key) => typeof capabilities[key] !== "boolean");
|
|
100
|
+
if (missing.length > 0) {
|
|
101
|
+
issues.push(`\`capabilities\` needs a boolean for ${missing.map((key) => `\`${key}\``).join(", ")}.`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
for (const method of ["trigger", "status"]) {
|
|
105
|
+
if (typeof runtime[method] !== "function")
|
|
106
|
+
issues.push(`\`${method}\` must be a function.`);
|
|
107
|
+
}
|
|
108
|
+
for (const method of [
|
|
109
|
+
"isConfigured",
|
|
110
|
+
"resolveRemoteId",
|
|
111
|
+
"validateTask",
|
|
112
|
+
"batchTrigger",
|
|
113
|
+
"cancel",
|
|
114
|
+
"start",
|
|
115
|
+
"dispose",
|
|
116
|
+
]) {
|
|
117
|
+
if (runtime[method] !== undefined && typeof runtime[method] !== "function") {
|
|
118
|
+
issues.push(`\`${method}\` must be a function when it is set.`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (capabilities?.cancel === true && typeof runtime.cancel !== "function") {
|
|
122
|
+
issues.push("`capabilities.cancel` is true, so `cancel` must be a function.");
|
|
123
|
+
}
|
|
124
|
+
if (runtime.routes !== undefined && !Array.isArray(runtime.routes)) {
|
|
125
|
+
issues.push("`routes` must be an array when it is set.");
|
|
126
|
+
}
|
|
127
|
+
const seen = new Set();
|
|
128
|
+
for (const [index, route] of (Array.isArray(runtime.routes) ? runtime.routes : []).entries()) {
|
|
129
|
+
const label = `routes[${index}]`;
|
|
130
|
+
if (!route || typeof route !== "object") {
|
|
131
|
+
issues.push(`\`${label}\` must be an object.`);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (route.method !== "GET" && route.method !== "POST") {
|
|
135
|
+
issues.push(`\`${label}.method\` must be "GET" or "POST".`);
|
|
136
|
+
}
|
|
137
|
+
if (typeof route.path !== "string" || !ROUTE_PATH_PATTERN.test(route.path)) {
|
|
138
|
+
issues.push(`\`${label}.path\` must be lowercase segments separated by "/", such as "tick"; received ${JSON.stringify(route.path)}.`);
|
|
139
|
+
}
|
|
140
|
+
if (typeof route.verify !== "function") {
|
|
141
|
+
issues.push(`\`${label}.verify\` must be a function that decides who may call the route.`);
|
|
142
|
+
}
|
|
143
|
+
if (typeof route.handler !== "function")
|
|
144
|
+
issues.push(`\`${label}.handler\` must be a function.`);
|
|
145
|
+
const id = `${route.method} ${route.path}`;
|
|
146
|
+
if (seen.has(id))
|
|
147
|
+
issues.push(`\`${label}\` repeats ${id}.`);
|
|
148
|
+
seen.add(id);
|
|
149
|
+
}
|
|
150
|
+
if (issues.length > 0) {
|
|
151
|
+
throw new TypeError(`Jobs runtime "${kind}" is invalid:\n${issues.map((issue) => `- ${issue}`).join("\n")}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function unsupportedDefaults(task, capabilities) {
|
|
155
|
+
const defaults = task.definition.defaults;
|
|
156
|
+
const fields = [];
|
|
157
|
+
if (defaults?.queue && !capabilities.queue)
|
|
158
|
+
fields.push("defaults.queue");
|
|
159
|
+
if (defaults?.retry !== undefined && !capabilities.retry)
|
|
160
|
+
fields.push("defaults.retry");
|
|
161
|
+
if (defaults?.ttl !== undefined && !capabilities.ttl)
|
|
162
|
+
fields.push("defaults.ttl");
|
|
163
|
+
if (defaults?.concurrencyKey && !capabilities.concurrencyKey) {
|
|
164
|
+
fields.push("defaults.concurrencyKey");
|
|
165
|
+
}
|
|
166
|
+
if (defaults?.idempotencyKey && !capabilities.idempotencyKey) {
|
|
167
|
+
fields.push("defaults.idempotencyKey");
|
|
168
|
+
}
|
|
169
|
+
if (defaults?.tags && defaults.tags.length > 0 && !capabilities.tags)
|
|
170
|
+
fields.push("defaults.tags");
|
|
171
|
+
return fields;
|
|
172
|
+
}
|
|
173
|
+
function assertLaunchSupported(kind, capabilities, options) {
|
|
174
|
+
// Task defaults were checked at setup, so only per-call options can fail here.
|
|
175
|
+
if (options.delayMode && !capabilities.schedule) {
|
|
176
|
+
throw unsupported(kind, "schedule", 501, "one-off schedules");
|
|
177
|
+
}
|
|
178
|
+
if (options.delay != null && !options.delayMode && !capabilities.delay) {
|
|
179
|
+
throw unsupported(kind, "delay", 400, "a launch delay");
|
|
180
|
+
}
|
|
181
|
+
if (options.debounce && !capabilities.debounce) {
|
|
182
|
+
throw unsupported(kind, "debounce", 400, "debounce");
|
|
183
|
+
}
|
|
184
|
+
if (options.tags?.length && !capabilities.tags) {
|
|
185
|
+
throw unsupported(kind, "tags", 400, "tags");
|
|
186
|
+
}
|
|
187
|
+
if (options.idempotencyKey && !capabilities.idempotencyKey) {
|
|
188
|
+
throw unsupported(kind, "idempotencyKey", 400, "idempotency keys");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function invalidResult(kind, what, data) {
|
|
192
|
+
return new JobsRuntimeError(`The "${kind}" jobs runtime ${what}.`, 502, data);
|
|
193
|
+
}
|
|
194
|
+
function normalizeLaunch(kind, launch) {
|
|
195
|
+
if (!launch || !isNonEmptyString(launch.handleId)) {
|
|
196
|
+
throw invalidResult(kind, "did not return a run handle id");
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
handleId: launch.handleId,
|
|
200
|
+
queuedAt: isNonEmptyString(launch.queuedAt) ? launch.queuedAt : new Date().toISOString(),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function orNull(value) {
|
|
204
|
+
return value ?? null;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Builds a custom runtime and wraps it in the shape the built-in runtimes
|
|
208
|
+
* have, enforcing its declared capabilities in one place.
|
|
209
|
+
*/
|
|
210
|
+
export function adaptCustomRuntime(definition, setup) {
|
|
211
|
+
validateDefinition(definition);
|
|
212
|
+
const kind = definition.kind;
|
|
213
|
+
const logger = createLogger(`[farm:jobs:${kind}]`);
|
|
214
|
+
const context = {
|
|
215
|
+
kind,
|
|
216
|
+
basePath: setup.basePath,
|
|
217
|
+
routePath: (path) => setup.routePath(kind, path),
|
|
218
|
+
getTask: (key) => setup.getTask(key),
|
|
219
|
+
async execute(input) {
|
|
220
|
+
const task = setup.getTask(input.task);
|
|
221
|
+
if (!task) {
|
|
222
|
+
throw new JobsRuntimeError(`Task "${input.task}" is not registered with this jobs integration.`, 404);
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const output = await task.definition.run(input.input, {
|
|
226
|
+
runtime: kind,
|
|
227
|
+
task: { key: task.key, id: task.id },
|
|
228
|
+
logger: createLogger(`[farm:jobs:${task.key}]`),
|
|
229
|
+
run: { id: input.run.id, attempt: input.run.attempt },
|
|
230
|
+
signal: input.signal,
|
|
231
|
+
});
|
|
232
|
+
return { ok: true, output };
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
return { ok: false, error: serializeError(error) };
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
logger,
|
|
239
|
+
};
|
|
240
|
+
const runtime = definition.create(context);
|
|
241
|
+
validateRuntime(kind, runtime);
|
|
242
|
+
const capabilities = Object.freeze(Object.fromEntries(CAPABILITY_KEYS.map((key) => [key, runtime.capabilities[key]])));
|
|
243
|
+
const routes = (runtime.routes ?? []).map((route) => ({
|
|
244
|
+
...route,
|
|
245
|
+
fullPath: setup.routePath(kind, route.path),
|
|
246
|
+
}));
|
|
247
|
+
let started;
|
|
248
|
+
let disposed;
|
|
249
|
+
return {
|
|
250
|
+
kind,
|
|
251
|
+
capabilities,
|
|
252
|
+
routes,
|
|
253
|
+
isConfigured() {
|
|
254
|
+
return runtime.isConfigured ? runtime.isConfigured() === true : true;
|
|
255
|
+
},
|
|
256
|
+
resolveRemoteId(taskId) {
|
|
257
|
+
const remoteId = runtime.resolveRemoteId ? runtime.resolveRemoteId(taskId) : taskId;
|
|
258
|
+
if (!isNonEmptyString(remoteId)) {
|
|
259
|
+
throw new TypeError(`Jobs runtime "${kind}" resolveRemoteId(${JSON.stringify(taskId)}) must return a non-empty string.`);
|
|
260
|
+
}
|
|
261
|
+
return remoteId;
|
|
262
|
+
},
|
|
263
|
+
validateTask(task) {
|
|
264
|
+
const fields = unsupportedDefaults(task, capabilities);
|
|
265
|
+
if (fields.length > 0) {
|
|
266
|
+
throw new Error(`Task "${task.key}" sets ${fields.map((field) => `\`${field}\``).join(", ")}, which the "${kind}" jobs runtime does not support. Remove ${fields.length === 1 ? "it" : "them"} or use a runtime whose capabilities include ${fields.length === 1 ? "it" : "them"}.`);
|
|
267
|
+
}
|
|
268
|
+
runtime.validateTask?.(task);
|
|
269
|
+
},
|
|
270
|
+
async trigger(task, input, options) {
|
|
271
|
+
assertLaunchSupported(kind, capabilities, options);
|
|
272
|
+
return normalizeLaunch(kind, await runtime.trigger(task, input, options));
|
|
273
|
+
},
|
|
274
|
+
async batchTrigger(task, items) {
|
|
275
|
+
if (!capabilities.batchTrigger) {
|
|
276
|
+
throw unsupported(kind, "batchTrigger", 501, "batch triggers");
|
|
277
|
+
}
|
|
278
|
+
for (const item of items)
|
|
279
|
+
assertLaunchSupported(kind, capabilities, item.options);
|
|
280
|
+
if (runtime.batchTrigger) {
|
|
281
|
+
const result = await runtime.batchTrigger(task, items);
|
|
282
|
+
if (!result || !Array.isArray(result.runs) || result.runs.length === 0) {
|
|
283
|
+
throw invalidResult(kind, "did not return any batch run handles");
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
batchId: isNonEmptyString(result.batchId) ? result.batchId : null,
|
|
287
|
+
runs: result.runs.map((run) => ({
|
|
288
|
+
index: run.index,
|
|
289
|
+
...normalizeLaunch(kind, run),
|
|
290
|
+
})),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
const runs = [];
|
|
294
|
+
for (const [index, item] of items.entries()) {
|
|
295
|
+
try {
|
|
296
|
+
runs.push({
|
|
297
|
+
index,
|
|
298
|
+
...normalizeLaunch(kind, await runtime.trigger(task, item.input, item.options)),
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
// The earlier items already started, so return their handles with the failure.
|
|
303
|
+
throw new JobsRuntimeError(`Batch item ${index} failed after ${runs.length} item${runs.length === 1 ? "" : "s"} started: ${error instanceof Error ? error.message : "unknown error"}`, error instanceof JobsRuntimeError ? error.status : 500, { code: "JOBS_BATCH_PARTIAL", runtime: kind, failedIndex: index, runs });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return { batchId: null, runs };
|
|
307
|
+
},
|
|
308
|
+
async status(task, handleId) {
|
|
309
|
+
const result = await runtime.status(task, handleId);
|
|
310
|
+
if (!result || typeof result !== "object") {
|
|
311
|
+
throw invalidResult(kind, "returned no status");
|
|
312
|
+
}
|
|
313
|
+
return {
|
|
314
|
+
handleId,
|
|
315
|
+
providerRunId: orNull(result.providerRunId),
|
|
316
|
+
status: RUN_STATUSES.has(result.status) ? result.status : "unknown",
|
|
317
|
+
providerStatus: orNull(result.providerStatus),
|
|
318
|
+
queuedAt: orNull(result.queuedAt),
|
|
319
|
+
startedAt: orNull(result.startedAt),
|
|
320
|
+
finishedAt: orNull(result.finishedAt),
|
|
321
|
+
output: orNull(result.output),
|
|
322
|
+
error: orNull(result.error),
|
|
323
|
+
tags: Array.isArray(result.tags)
|
|
324
|
+
? result.tags.filter((tag) => typeof tag === "string")
|
|
325
|
+
: [],
|
|
326
|
+
raw: orNull(result.raw),
|
|
327
|
+
};
|
|
328
|
+
},
|
|
329
|
+
async cancel(task, handleId) {
|
|
330
|
+
if (!capabilities.cancel || !runtime.cancel) {
|
|
331
|
+
throw unsupported(kind, "cancel", 501, "cancel");
|
|
332
|
+
}
|
|
333
|
+
await runtime.cancel(task, handleId);
|
|
334
|
+
return { handleId, task: task.key, runtime: kind, canceled: true };
|
|
335
|
+
},
|
|
336
|
+
start() {
|
|
337
|
+
started ??= Promise.resolve().then(() => runtime.start?.());
|
|
338
|
+
return started;
|
|
339
|
+
},
|
|
340
|
+
dispose() {
|
|
341
|
+
disposed ??= Promise.resolve().then(() => runtime.dispose?.());
|
|
342
|
+
return disposed;
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type CustomJobsRuntimeDefinition, type JobsRuntimeCapabilities } from "./index.js";
|
|
2
|
+
/** Calls the jobs integration's routes the way server code calling `api` does. */
|
|
3
|
+
export interface JobsRuntimeConformanceHarness {
|
|
4
|
+
readonly capabilities: JobsRuntimeCapabilities;
|
|
5
|
+
/** Calls `<basePath>/<path>` as trusted server code and returns the JSON answer. */
|
|
6
|
+
request(method: "GET" | "POST", path: string, body?: unknown): Promise<{
|
|
7
|
+
status: number;
|
|
8
|
+
body: any;
|
|
9
|
+
}>;
|
|
10
|
+
/** Calls one of the runtime's own routes, such as `"tick"`, as its scheduler would. */
|
|
11
|
+
runtimeRoute(method: "GET" | "POST", path: string, init?: RequestInit): Promise<{
|
|
12
|
+
status: number;
|
|
13
|
+
body: any;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
export interface JobsRuntimeConformanceOptions {
|
|
17
|
+
/** Returns a new runtime for each case, so cases share no state. */
|
|
18
|
+
runtime(): CustomJobsRuntimeDefinition | Promise<CustomJobsRuntimeDefinition>;
|
|
19
|
+
/**
|
|
20
|
+
* Makes started runs execute, for a runtime that calls `run` in this
|
|
21
|
+
* process, for example by calling its tick route. Without it, the cases
|
|
22
|
+
* that check execution are not returned.
|
|
23
|
+
*/
|
|
24
|
+
drive?(harness: JobsRuntimeConformanceHarness): Promise<void>;
|
|
25
|
+
/** How many times to call `drive` before a run must have finished. @default 5 */
|
|
26
|
+
driveAttempts?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface JobsRuntimeConformanceCase {
|
|
29
|
+
name: string;
|
|
30
|
+
run(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The behavior every jobs runtime must have, as framework-agnostic cases.
|
|
34
|
+
* Register each with your test runner:
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* for (const conformance of createJobsRuntimeConformance({ runtime: () => myRuntime() })) {
|
|
38
|
+
* it(conformance.name, conformance.run);
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* Cases for capabilities the runtime declares as unsupported check that Farm
|
|
43
|
+
* refuses them; cases that need `drive` are left out without it.
|
|
44
|
+
*/
|
|
45
|
+
export declare function createJobsRuntimeConformance(options: JobsRuntimeConformanceOptions): JobsRuntimeConformanceCase[];
|
|
46
|
+
//# sourceMappingURL=testing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,2BAA2B,EAChC,KAAK,uBAAuB,EAE7B,MAAM,YAAY,CAAC;AAQpB,kFAAkF;AAClF,MAAM,WAAW,6BAA6B;IAC5C,QAAQ,CAAC,YAAY,EAAE,uBAAuB,CAAC;IAC/C,oFAAoF;IACpF,OAAO,CACL,MAAM,EAAE,KAAK,GAAG,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,GACb,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,GAAG,CAAA;KAAE,CAAC,CAAC;IAC1C,uFAAuF;IACvF,YAAY,CACV,MAAM,EAAE,KAAK,GAAG,MAAM,EACtB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,WAAW,GACjB,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,GAAG,CAAA;KAAE,CAAC,CAAC;CAC3C;AAED,MAAM,WAAW,6BAA6B;IAC5C,oEAAoE;IACpE,OAAO,IAAI,2BAA2B,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAC9E;;;;OAIG;IACH,KAAK,CAAC,CAAC,OAAO,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D,iFAAiF;IACjF,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACtB;AAsKD;;;;;;;;;;;;GAYG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,GACrC,0BAA0B,EAAE,CAoK9B"}
|