@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.
@@ -0,0 +1,251 @@
1
+ import { FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY } from "@farm.js/core/integrations";
2
+ import { defineTasks, jobs, task, } from "./index.js";
3
+ const BASE_PATH = "/api/jobs";
4
+ const UNSUPPORTED = "JOBS_RUNTIME_CAPABILITY_UNSUPPORTED";
5
+ const TERMINAL = new Set(["completed", "failed", "canceled", "expired"]);
6
+ const serverContext = {
7
+ req: {
8
+ get: (key) => key === FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY ? true : undefined,
9
+ },
10
+ };
11
+ class ConformanceError extends Error {
12
+ constructor(message, detail) {
13
+ super(detail === undefined ? message : `${message}\nReceived: ${JSON.stringify(detail)}`);
14
+ this.name = "JobsRuntimeConformanceError";
15
+ }
16
+ }
17
+ function check(condition, message, detail) {
18
+ if (!condition)
19
+ throw new ConformanceError(message, detail);
20
+ }
21
+ function createTasks(capabilities) {
22
+ return defineTasks({
23
+ echo: task({
24
+ async run(input) {
25
+ return { echoed: input.value };
26
+ },
27
+ }),
28
+ other: task({
29
+ async run(input) {
30
+ return { other: input.value };
31
+ },
32
+ }),
33
+ explode: task({
34
+ ...(capabilities.retry ? { defaults: { retry: false } } : {}),
35
+ async run(_input) {
36
+ throw new Error("conformance failure");
37
+ },
38
+ }),
39
+ });
40
+ }
41
+ async function disposeIntegration(integration) {
42
+ await integration.dispose?.({});
43
+ }
44
+ /** Builds a throwaway integration to read what the runtime declares. */
45
+ async function readCapabilities(options) {
46
+ const integration = jobs({
47
+ runtime: await options.runtime(),
48
+ tasks: defineTasks({ probe: task({ run: () => null }) }),
49
+ });
50
+ try {
51
+ return integration.instance.tasks[0].capabilities;
52
+ }
53
+ finally {
54
+ await disposeIntegration(integration);
55
+ }
56
+ }
57
+ async function setup(options) {
58
+ const capabilities = await readCapabilities(options);
59
+ const integration = jobs({
60
+ runtime: await options.runtime(),
61
+ tasks: createTasks(capabilities),
62
+ });
63
+ const metadata = integration.instance.tasks;
64
+ const routes = integration.routes;
65
+ const find = (method, path) => routes.find((route) => route.method === method && route.path === path);
66
+ async function call(route, request, label) {
67
+ check(route, `No route answers ${label}.`);
68
+ const response = await route.handler(request, serverContext);
69
+ const text = await response.text();
70
+ let body = text;
71
+ try {
72
+ body = text ? JSON.parse(text) : null;
73
+ }
74
+ catch { }
75
+ return { status: response.status, body: body };
76
+ }
77
+ const harness = {
78
+ capabilities,
79
+ request(method, path, body) {
80
+ const full = `${BASE_PATH}/${path}`;
81
+ const url = new URL(full, "http://conformance.test");
82
+ return call(find(method, url.pathname), new Request(url, {
83
+ method,
84
+ ...(body === undefined
85
+ ? {}
86
+ : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),
87
+ }), `${method} ${full}`);
88
+ },
89
+ runtimeRoute(method, path, init) {
90
+ const kind = metadata[0].runtime;
91
+ const full = `${BASE_PATH}/_runtime/${kind}/${path}`;
92
+ return call(find(method, full), new Request(new URL(full, "http://conformance.test"), { ...init, method }), `${method} ${full}`);
93
+ },
94
+ };
95
+ return { harness, dispose: () => disposeIntegration(integration) };
96
+ }
97
+ function expectUnsupported(result, capability, status) {
98
+ check(result.status === status && result.body?.details?.code === UNSUPPORTED, `Expected ${status} with code ${UNSUPPORTED} for the unsupported "${capability}" capability.`, result);
99
+ check(result.body.details.capability === capability, `Expected the error to name the "${capability}" capability.`, result.body.details);
100
+ }
101
+ async function triggerEcho(harness, value, options) {
102
+ const result = await harness.request("POST", "echo/trigger", {
103
+ value,
104
+ ...(options ? { $options: options } : {}),
105
+ });
106
+ check(result.status === 200 && typeof result.body?.handleId === "string" && result.body.handleId, "Expected trigger to answer 200 with a non-empty handleId.", result);
107
+ return result.body.handleId;
108
+ }
109
+ async function waitForTerminal(options, harness, taskPath, handleId) {
110
+ const attempts = options.driveAttempts ?? 5;
111
+ let last;
112
+ for (let index = 0; index < attempts; index += 1) {
113
+ await options.drive(harness);
114
+ last = await harness.request("GET", `${taskPath}/status?handleId=${encodeURIComponent(handleId)}`);
115
+ if (last.status === 200 && TERMINAL.has(last.body?.status))
116
+ return last.body;
117
+ }
118
+ throw new ConformanceError(`Run ${handleId} did not finish after ${attempts} drive calls.`, last);
119
+ }
120
+ /**
121
+ * The behavior every jobs runtime must have, as framework-agnostic cases.
122
+ * Register each with your test runner:
123
+ *
124
+ * ```ts
125
+ * for (const conformance of createJobsRuntimeConformance({ runtime: () => myRuntime() })) {
126
+ * it(conformance.name, conformance.run);
127
+ * }
128
+ * ```
129
+ *
130
+ * Cases for capabilities the runtime declares as unsupported check that Farm
131
+ * refuses them; cases that need `drive` are left out without it.
132
+ */
133
+ export function createJobsRuntimeConformance(options) {
134
+ const cases = [];
135
+ const add = (name, body) => {
136
+ cases.push({
137
+ name,
138
+ async run() {
139
+ const { harness, dispose } = await setup(options);
140
+ try {
141
+ await body(harness);
142
+ }
143
+ finally {
144
+ await dispose();
145
+ }
146
+ },
147
+ });
148
+ };
149
+ add("reports its kind and capabilities in task metadata", async (harness) => {
150
+ const list = await harness.request("GET", "tasks");
151
+ check(list.status === 200 && Array.isArray(list.body), "Expected the task list.", list);
152
+ for (const entry of list.body) {
153
+ check(typeof entry.runtime === "string" && entry.runtime.length > 0, "Missing runtime kind.", entry);
154
+ check(entry.capabilities && typeof entry.capabilities === "object", "Missing capabilities.", entry);
155
+ }
156
+ });
157
+ add("returns a run handle from trigger", async (harness) => {
158
+ await triggerEcho(harness, "handle");
159
+ });
160
+ add("reads the status of a run it started", async (harness) => {
161
+ const handleId = await triggerEcho(harness, "status");
162
+ const result = await harness.request("GET", `echo/status?handleId=${encodeURIComponent(handleId)}`);
163
+ check(result.status === 200, "Expected status to answer 200.", result);
164
+ check(result.body.handleId === handleId, "Expected status to echo the handleId.", result.body);
165
+ check(result.body.task === "echo", "Expected status to name the task.", result.body);
166
+ });
167
+ add("refuses to read another task's run", async (harness) => {
168
+ const handleId = await triggerEcho(harness, "isolation");
169
+ const result = await harness.request("GET", `other/status?handleId=${encodeURIComponent(handleId)}`);
170
+ check(result.status === 404, "Expected 404 when a task reads another task's run.", result);
171
+ });
172
+ add("handles idempotency keys as declared", async (harness) => {
173
+ if (!harness.capabilities.idempotencyKey) {
174
+ const result = await harness.request("POST", "echo/trigger", {
175
+ value: "idem",
176
+ $options: { idempotencyKey: "conformance" },
177
+ });
178
+ expectUnsupported(result, "idempotencyKey", 400);
179
+ return;
180
+ }
181
+ const first = await triggerEcho(harness, "idem", { idempotencyKey: "conformance" });
182
+ const second = await triggerEcho(harness, "idem", { idempotencyKey: "conformance" });
183
+ check(first === second, "Expected the same idempotency key to return the same run.", {
184
+ first,
185
+ second,
186
+ });
187
+ });
188
+ add("refuses per-call options it does not support", async (harness) => {
189
+ const checks = [
190
+ ["tags", { tags: ["conformance"] }],
191
+ ["debounce", { debounce: { key: "conformance", delay: "1m" } }],
192
+ ["delay", { delay: "1m" }],
193
+ ];
194
+ for (const [capability, launch] of checks) {
195
+ if (harness.capabilities[capability])
196
+ continue;
197
+ const result = await harness.request("POST", "echo/trigger", {
198
+ value: "x",
199
+ $options: launch,
200
+ });
201
+ expectUnsupported(result, capability, 400);
202
+ }
203
+ });
204
+ add("schedules and cancels as declared", async (harness) => {
205
+ const scheduled = await harness.request("POST", "echo/schedule", {
206
+ value: "later",
207
+ $schedule: { after: "1h" },
208
+ });
209
+ if (!harness.capabilities.schedule) {
210
+ expectUnsupported(scheduled, "schedule", 501);
211
+ return;
212
+ }
213
+ check(scheduled.status === 200 && scheduled.body.handleId, "Expected schedule to answer 200.", scheduled);
214
+ const canceled = await harness.request("POST", "echo/cancel", {
215
+ handleId: scheduled.body.handleId,
216
+ });
217
+ if (!harness.capabilities.cancel) {
218
+ expectUnsupported(canceled, "cancel", 501);
219
+ return;
220
+ }
221
+ check(canceled.status === 200 && canceled.body.canceled === true, "Expected cancel to answer 200.", canceled);
222
+ const status = await harness.request("GET", `echo/status?handleId=${encodeURIComponent(scheduled.body.handleId)}`);
223
+ check(status.body?.status === "canceled", "Expected a canceled run to report canceled.", status);
224
+ });
225
+ add("batch triggers as declared", async (harness) => {
226
+ const result = await harness.request("POST", "echo/batch-trigger", {
227
+ items: [{ value: "a" }, { value: "b" }],
228
+ });
229
+ if (!harness.capabilities.batchTrigger) {
230
+ expectUnsupported(result, "batchTrigger", 501);
231
+ return;
232
+ }
233
+ check(result.status === 200 && Array.isArray(result.body.runs) && result.body.runs.length === 2, "Expected a batch of two items to return two runs.", result);
234
+ });
235
+ if (options.drive) {
236
+ add("runs a task to completion with its output", async (harness) => {
237
+ const handleId = await triggerEcho(harness, "done");
238
+ const status = await waitForTerminal(options, harness, "echo", handleId);
239
+ check(status.status === "completed", "Expected the run to complete.", status);
240
+ check(status.output?.echoed === "done", "Expected the run's output.", status);
241
+ });
242
+ add("reports a failing task as failed with its error", async (harness) => {
243
+ const queued = await harness.request("POST", "explode/trigger", { value: "x" });
244
+ check(queued.status === 200, "Expected trigger to answer 200.", queued);
245
+ const status = await waitForTerminal(options, harness, "explode", queued.body.handleId);
246
+ check(status.status === "failed", "Expected the run to fail.", status);
247
+ check(JSON.stringify(status.error ?? null).includes("conformance failure"), "Expected the run's error message.", status);
248
+ });
249
+ }
250
+ return cases;
251
+ }
package/dist/time.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { JobsRuntimeError } from "./errors.js";
2
+ /** Which runtime a schedule error names, for example `{ kind: "inngest", label: "Inngest" }`. */
3
+ export interface JobsScheduleRuntime {
4
+ kind: string;
5
+ label: string;
6
+ }
7
+ export declare function scheduleError(message: string, value: string | number, runtime: string): JobsRuntimeError;
8
+ /** Positive milliseconds, or a duration such as `"10s"` ending in ms, s, m, h, or d. */
9
+ export declare function parseDurationMs(value: string | number): number | undefined;
10
+ /** An ISO timestamp with an explicit `Z` or UTC offset. */
11
+ export declare function parseAbsoluteTime(value: string | number): number | undefined;
12
+ /**
13
+ * The epoch milliseconds a delayed launch should start at, or `undefined` for
14
+ * an immediate launch. An ISO timestamp is absolute and must be in the future;
15
+ * a number or duration is relative to `now`.
16
+ */
17
+ export declare function resolveScheduledTimestamp(options: {
18
+ delay?: string | number;
19
+ delayMode?: "at" | "after";
20
+ }, now: number, runtime: JobsScheduleRuntime): number | undefined;
21
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../src/time.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAW/C,iGAAiG;AACjG,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,EAAE,MAAM,oBAMrF;AAED,wFAAwF;AACxF,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAW1E;AAED,2DAA2D;AAC3D,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAK5E;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE;IAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,IAAI,GAAG,OAAO,CAAA;CAAE,EAChE,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,mBAAmB,GAC3B,MAAM,GAAG,SAAS,CAyCpB"}
package/dist/time.js ADDED
@@ -0,0 +1,66 @@
1
+ import { JobsRuntimeError } from "./errors.js";
2
+ const DURATION_UNITS = {
3
+ ms: 1,
4
+ s: 1_000,
5
+ m: 60_000,
6
+ h: 3_600_000,
7
+ d: 86_400_000,
8
+ };
9
+ const MAX_TIMESTAMP = 8_640_000_000_000_000;
10
+ export function scheduleError(message, value, runtime) {
11
+ return new JobsRuntimeError(message, 400, {
12
+ code: "JOBS_INVALID_SCHEDULE",
13
+ runtime,
14
+ value,
15
+ });
16
+ }
17
+ /** Positive milliseconds, or a duration such as `"10s"` ending in ms, s, m, h, or d. */
18
+ export function parseDurationMs(value) {
19
+ if (typeof value === "number") {
20
+ return Number.isFinite(value) && value > 0 ? Math.ceil(value) : undefined;
21
+ }
22
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/i.exec(value);
23
+ if (!match)
24
+ return undefined;
25
+ const amount = Number(match[1]);
26
+ const unit = match[2].toLowerCase();
27
+ const duration = Math.ceil(amount * DURATION_UNITS[unit]);
28
+ return Number.isFinite(duration) && duration > 0 ? duration : undefined;
29
+ }
30
+ /** An ISO timestamp with an explicit `Z` or UTC offset. */
31
+ export function parseAbsoluteTime(value) {
32
+ if (typeof value !== "string")
33
+ return undefined;
34
+ if (!/^\d{4}-\d{2}-\d{2}T.+(?:Z|[+-]\d{2}:?\d{2})$/i.test(value))
35
+ return undefined;
36
+ const timestamp = Date.parse(value);
37
+ return Number.isFinite(timestamp) ? timestamp : undefined;
38
+ }
39
+ /**
40
+ * The epoch milliseconds a delayed launch should start at, or `undefined` for
41
+ * an immediate launch. An ISO timestamp is absolute and must be in the future;
42
+ * a number or duration is relative to `now`.
43
+ */
44
+ export function resolveScheduledTimestamp(options, now, runtime) {
45
+ if (options.delay == null)
46
+ return undefined;
47
+ const absolute = options.delayMode === "after" ? undefined : parseAbsoluteTime(options.delay);
48
+ if (absolute != null) {
49
+ if (absolute <= now) {
50
+ throw scheduleError(`${runtime.label} at/delay timestamps must be in the future.`, options.delay, runtime.kind);
51
+ }
52
+ return absolute;
53
+ }
54
+ if (options.delayMode === "at") {
55
+ throw scheduleError(`${runtime.label} at must be an ISO timestamp with an explicit Z or UTC offset.`, options.delay, runtime.kind);
56
+ }
57
+ const duration = parseDurationMs(options.delay);
58
+ if (duration == null) {
59
+ throw scheduleError(`${runtime.label} after/delay must be positive milliseconds or a duration ending in ms, s, m, h, or d.`, options.delay, runtime.kind);
60
+ }
61
+ const timestamp = now + duration;
62
+ if (!Number.isSafeInteger(timestamp) || timestamp > MAX_TIMESTAMP) {
63
+ throw scheduleError(`${runtime.label} after/delay exceeds the supported date range.`, options.delay, runtime.kind);
64
+ }
65
+ return timestamp;
66
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farm.js/jobs",
3
- "version": "0.1.66",
3
+ "version": "0.1.68",
4
4
  "description": "Jobs integration primitives for Farm.js",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -19,14 +19,18 @@
19
19
  ".": {
20
20
  "types": "./dist/index.d.ts",
21
21
  "import": "./dist/index.js"
22
+ },
23
+ "./testing": {
24
+ "types": "./dist/testing.d.ts",
25
+ "import": "./dist/testing.js"
22
26
  }
23
27
  },
24
28
  "publishConfig": {
25
29
  "access": "public"
26
30
  },
27
31
  "dependencies": {
28
- "@farm.js/core": "0.1.66",
29
- "@farm.js/integration-utils": "0.1.66"
32
+ "@farm.js/integration-utils": "0.1.68",
33
+ "@farm.js/core": "0.1.68"
30
34
  },
31
35
  "scripts": {
32
36
  "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",