@cogover/sdk 0.12.0 → 0.12.1

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.
@@ -1,21 +1,22 @@
1
- /** Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. */
1
+ const NON_ASCII = /[^\u0000-\u007f]/;
2
+ const TWO_BYTE_UNITS = /[\u0080-\u07ff]/g;
3
+ const THREE_BYTE_UNITS = /[\u0800-\ud7ff\ue000-\uffff]/g;
4
+ const SURROGATE_UNITS = /[\ud800-\udfff]/g;
5
+ const SURROGATE_PAIRS = /[\ud800-\udbff][\udc00-\udfff]/g;
6
+ /**
7
+ * Number of bytes of the UTF-8 encoding of a string; a lone surrogate counts as three bytes. Native regular
8
+ * expressions count the code units, so the cost in the sandbox statement budget does not grow with the length.
9
+ */
2
10
  export function utf8ByteLength(value) {
3
- let bytes = 0;
4
- for (let index = 0; index < value.length; index++) {
5
- const code = value.charCodeAt(index);
6
- if (code < 0x80)
7
- bytes++;
8
- else if (code < 0x800)
9
- bytes += 2;
10
- else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length
11
- && value.charCodeAt(index + 1) >= 0xdc00 && value.charCodeAt(index + 1) <= 0xdfff) {
12
- bytes += 4;
13
- index++;
14
- }
15
- else
16
- bytes += 3;
17
- }
18
- return bytes;
11
+ if (!NON_ASCII.test(value))
12
+ return value.length;
13
+ const matchedUnits = (pattern) => value.length - value.replace(pattern, "").length;
14
+ const surrogateUnits = matchedUnits(SURROGATE_UNITS);
15
+ const pairedUnits = surrogateUnits === 0 ? 0 : matchedUnits(SURROGATE_PAIRS);
16
+ // Every unit counts one byte, plus one for U+0080-U+07FF, two for the rest of the BMP, one for each unit of
17
+ // a surrogate pair (four bytes a pair) and two for a lone surrogate (encoded as U+FFFD).
18
+ return value.length + matchedUnits(TWO_BYTE_UNITS) + 2 * matchedUnits(THREE_BYTE_UNITS)
19
+ + pairedUnits + 2 * (surrogateUnits - pairedUnits);
19
20
  }
20
21
  /** UTF-8 encoding without TextEncoder, which the sandbox does not provide; a lone surrogate becomes U+FFFD. */
21
22
  export function encodeUtf8(value) {
package/dist/locks.js CHANGED
@@ -30,12 +30,22 @@ export function createLocksApi() {
30
30
  const acquired = await api.acquire(key, options);
31
31
  if (acquired === null)
32
32
  throw new LockUnavailableError(key);
33
+ let result;
33
34
  try {
34
- return await callback(acquired);
35
+ result = await callback(acquired);
35
36
  }
36
- finally {
37
- await acquired.release();
37
+ catch (error) {
38
+ try {
39
+ await acquired.release();
40
+ }
41
+ catch {
42
+ // The callback's error is the one the caller must see; an unreleased lease expires on its own.
43
+ }
44
+ throw error;
38
45
  }
46
+ // After a successful callback a failed release (for example LockLostError) is reported.
47
+ await acquired.release();
48
+ return result;
39
49
  },
40
50
  };
41
51
  return Object.freeze(api);
package/dist/logger.js CHANGED
@@ -1,9 +1,55 @@
1
+ // Longest details text written for one log line; the rest is cut and marked.
2
+ const MAX_DETAILS_CHARS = 8192;
1
3
  function writeLog(level, message, details) {
2
4
  if (details === undefined) {
3
5
  console.log(`[${level}] ${message}`);
4
6
  return;
5
7
  }
6
- console.log(`[${level}] ${message}`, details);
8
+ // One preformatted string: the sandbox console does not format a second argument ("[object Object]").
9
+ console.log(`[${level}] ${message} ${formatDetails(details)}`);
10
+ }
11
+ /** JSON text of a details value that never throws, whatever the value contains. */
12
+ function formatDetails(details) {
13
+ let text;
14
+ try {
15
+ text = JSON.stringify(details, safeReplacer());
16
+ }
17
+ catch {
18
+ // A hostile toJSON() or getter must not turn a log call into a failure.
19
+ text = undefined;
20
+ }
21
+ if (text === undefined)
22
+ text = "[unserializable]";
23
+ return text.length > MAX_DETAILS_CHARS ? `${text.slice(0, MAX_DETAILS_CHARS)}…[truncated]` : text;
24
+ }
25
+ /** Replaces cycles, BigInt, errors, maps and sets, which JSON.stringify would reject or print as {}. */
26
+ function safeReplacer() {
27
+ // Objects on the path from the root to the value being written; a value found on it is a cycle.
28
+ const ancestors = [];
29
+ return function replacer(_key, value) {
30
+ if (ancestors.length > 0) {
31
+ const holder = ancestors.indexOf(this);
32
+ if (holder >= 0)
33
+ ancestors.length = holder + 1;
34
+ else
35
+ ancestors.push(this);
36
+ }
37
+ if (typeof value === "bigint")
38
+ return value.toString();
39
+ if (typeof value !== "object" || value === null)
40
+ return value;
41
+ if (ancestors.includes(value))
42
+ return "[Circular]";
43
+ if (ancestors.length === 0)
44
+ ancestors.push(value);
45
+ if (value instanceof Error)
46
+ return { name: value.name, message: value.message };
47
+ if (value instanceof Map)
48
+ return Object.fromEntries(value);
49
+ if (value instanceof Set)
50
+ return [...value];
51
+ return value;
52
+ };
7
53
  }
8
54
  /** @internal */
9
55
  export const SCRIPT_LOGGER = Object.freeze({
package/dist/org.js CHANGED
@@ -81,12 +81,12 @@ export function createOrgApi(invocation) {
81
81
  includeSubDepartments: "boolean", accountOnly: "boolean", limit: "limit", cursor: "cursor",
82
82
  };
83
83
  const personnel = {
84
- get(id, options) {
84
+ async get(id, options) {
85
85
  return nullableObject("org.personnel.get", {
86
86
  ...payloadFor("personnel.get()", options, {}, true), id: requireId(id, "personnel id"),
87
87
  });
88
88
  },
89
- getMany(ids, options) {
89
+ async getMany(ids, options) {
90
90
  if (!Array.isArray(ids))
91
91
  throw new ValidationError("personnel.getMany() requires an array of ids");
92
92
  const unique = [...new Set(ids.map(id => requireId(id, "personnel id")))];
@@ -97,7 +97,7 @@ export function createOrgApi(invocation) {
97
97
  ...payloadFor("personnel.getMany()", options, {}, true), ids: unique,
98
98
  });
99
99
  },
100
- managerChain(id, options) {
100
+ async managerChain(id, options) {
101
101
  return list("org.personnel.managerChain", {
102
102
  ...payloadFor("personnel.managerChain()", options, { departmentId: "id", accountOnly: "boolean" }, true),
103
103
  id: requireId(id, "personnel id"),
@@ -105,32 +105,32 @@ export function createOrgApi(invocation) {
105
105
  },
106
106
  };
107
107
  const departments = {
108
- get(id, options) {
108
+ async get(id, options) {
109
109
  return nullableObject("org.departments.get", {
110
110
  ...payloadFor("departments.get()", options, {}, true), id: requireId(id, "department id"),
111
111
  });
112
112
  },
113
- tree(options) {
113
+ async tree(options) {
114
114
  return list("org.departments.tree", payloadFor("departments.tree()", options, { rootId: "id", depth: "depth" }, true));
115
115
  },
116
- ancestors(id, options) {
116
+ async ancestors(id, options) {
117
117
  return list("org.departments.ancestors", {
118
118
  ...payloadFor("departments.ancestors()", options, {}, true), id: requireId(id, "department id"),
119
119
  });
120
120
  },
121
- members(id, options) {
121
+ async members(id, options) {
122
122
  return object("org.departments.members", {
123
123
  ...payloadFor("departments.members()", options, { ...pageOptions, positionId: "id" }, true),
124
124
  id: requireId(id, "department id"),
125
125
  });
126
126
  },
127
- managers(id, options) {
127
+ async managers(id, options) {
128
128
  return list("org.departments.managers", {
129
129
  ...payloadFor("departments.managers()", options, { accountOnly: "boolean" }, true),
130
130
  id: requireId(id, "department id"),
131
131
  });
132
132
  },
133
- managerChain(id, options) {
133
+ async managerChain(id, options) {
134
134
  return object("org.departments.managerChain", {
135
135
  ...payloadFor("departments.managerChain()", options, { accountOnly: "boolean" }, true),
136
136
  id: requireId(id, "department id"),
@@ -138,15 +138,15 @@ export function createOrgApi(invocation) {
138
138
  },
139
139
  };
140
140
  const positions = {
141
- list(options) {
141
+ async list(options) {
142
142
  return list("org.positions.list", payloadFor("positions.list()", options, {}, true));
143
143
  },
144
- get(id, options) {
144
+ async get(id, options) {
145
145
  return nullableObject("org.positions.get", {
146
146
  ...payloadFor("positions.get()", options, {}, true), id: requireId(id, "position id"),
147
147
  });
148
148
  },
149
- members(id, options) {
149
+ async members(id, options) {
150
150
  return object("org.positions.members", {
151
151
  ...payloadFor("positions.members()", options, { ...pageOptions, departmentId: "id" }, true),
152
152
  id: requireId(id, "position id"),
@@ -166,14 +166,14 @@ export function createOrgApi(invocation) {
166
166
  return null;
167
167
  return personnel.get(personnelId, options);
168
168
  },
169
- isInDepartment(personnelId, departmentId, options) {
169
+ async isInDepartment(personnelId, departmentId, options) {
170
170
  return flag("org.isInDepartment", {
171
171
  ...payloadFor("isInDepartment()", options, { includeSubDepartments: "boolean" }, false),
172
172
  personnelId: requireId(personnelId, "personnel id"),
173
173
  departmentId: requireId(departmentId, "department id"),
174
174
  });
175
175
  },
176
- isManagerOf(managerId, personnelId, options) {
176
+ async isManagerOf(managerId, personnelId, options) {
177
177
  return flag("org.isManagerOf", {
178
178
  ...payloadFor("isManagerOf()", options, { departmentId: "id", directOnly: "boolean" }, false),
179
179
  managerId: requireId(managerId, "manager id"),
package/dist/records.d.ts CHANGED
@@ -42,6 +42,15 @@ export interface GetManyResult<TFields> {
42
42
  export interface DeleteResult {
43
43
  readonly deleted: CogoverRecordId[];
44
44
  readonly notDeleted: CogoverRecordId[];
45
+ /**
46
+ * Present only when a before-change record trigger kept some of the records from being deleted: record ID to
47
+ * the trigger's error codes by field slug (`$record` for the whole record) and its texts.
48
+ */
49
+ readonly recordErrors?: Readonly<Record<CogoverRecordId, {
50
+ readonly reason: "TRIGGER_REJECTED";
51
+ readonly fieldErrors?: Readonly<Record<string, string>>;
52
+ readonly messages?: readonly string[];
53
+ }>>;
45
54
  }
46
55
  export interface BatchWriteRowResult {
47
56
  readonly referenceId: string;
@@ -49,6 +58,10 @@ export interface BatchWriteRowResult {
49
58
  readonly r: number;
50
59
  readonly msg?: string;
51
60
  readonly success: boolean;
61
+ /** Row a before-change record trigger rejected (`r` 70): error code by field slug, `$record` for the whole record. */
62
+ readonly fieldErrors?: Readonly<Record<string, string>>;
63
+ /** Row a before-change record trigger rejected (`r` 70): the texts the trigger attached to its error codes. */
64
+ readonly messages?: readonly string[];
52
65
  }
53
66
  /** Batch writes are best-effort per row; inspect `success` or every row result. */
54
67
  export interface BatchWriteResponse {
package/dist/response.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import { ValidationError } from "./errors.js";
2
2
  import { encodeBase64 } from "./internal/base64.js";
3
3
  const RESPONSE_KEY = "__cogoverHttpResponse";
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4
5
  const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
5
6
  const DENIED_HEADERS = new Set([
6
7
  "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "trailer",
7
8
  "set-cookie", "server", "date", "proxy-authenticate",
8
9
  ]);
10
+ // Only objects made by these helpers are responses. A returned value that merely has the same JSON shape is data.
11
+ const envelopes = new WeakMap();
9
12
  /** @internal */
10
13
  export function createResponseApi() {
11
14
  return Object.freeze({
@@ -40,6 +43,9 @@ export function createResponseApi() {
40
43
  || /[\r\n]/.test(location)) {
41
44
  throw new ValidationError("response.redirect() location is invalid");
42
45
  }
46
+ if (!REDIRECT_STATUSES.has(status)) {
47
+ throw new ValidationError("response.redirect() status must be 301, 302, 303, 307 or 308");
48
+ }
43
49
  return response("empty", null, { status, headers: { location } });
44
50
  },
45
51
  });
@@ -54,9 +60,23 @@ function response(bodyType, body, init, defaultContentType) {
54
60
  bodyType,
55
61
  body,
56
62
  });
57
- return Object.freeze({
63
+ const scriptResponse = Object.freeze({
58
64
  toJSON: () => Object.freeze({ [RESPONSE_KEY]: envelope }),
59
65
  });
66
+ envelopes.set(scriptResponse, envelope);
67
+ return scriptResponse;
68
+ }
69
+ /**
70
+ * @internal JSON text of a handler result. Cogover passes each invocation a token that only a response made by
71
+ * these helpers carries, so a returned value can never choose the status, headers or body type by imitating the
72
+ * envelope. Without a token (outside Cogover) a response serializes to the bare envelope.
73
+ */
74
+ export function serializeHandlerOutput(output, responseToken) {
75
+ const envelope = typeof output === "object" && output !== null ? envelopes.get(output) : undefined;
76
+ if (envelope !== undefined && typeof responseToken === "string" && responseToken.length > 0) {
77
+ return JSON.stringify({ [RESPONSE_KEY]: { ...envelope, token: responseToken } });
78
+ }
79
+ return JSON.stringify(output);
60
80
  }
61
81
  function validateStatus(status) {
62
82
  if (!Number.isInteger(status) || status < 200 || status > 599) {
package/dist/schema.d.ts CHANGED
@@ -12,6 +12,7 @@ export interface ObjectMetadata {
12
12
  readonly multiple: boolean;
13
13
  readonly readOnly: boolean;
14
14
  readonly manualModifyAllow?: boolean;
15
+ readonly creatable?: boolean;
15
16
  readonly metaData?: Readonly<Record<string, unknown>>;
16
17
  readonly options?: readonly {
17
18
  readonly id: string;
package/dist/script.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createDataApi } from "./data.js";
2
2
  import { NotFoundError, ValidationError } from "./errors.js";
3
3
  import { scriptRequest } from "./internal/request.js";
4
- import { createResponseApi } from "./response.js";
4
+ import { createResponseApi, serializeHandlerOutput } from "./response.js";
5
5
  import { errorMessage } from "./internal/values.js";
6
6
  import { SCRIPT_LOGGER } from "./logger.js";
7
7
  import { createSchemaApi } from "./schema.js";
@@ -16,6 +16,7 @@ import { createJobsApi } from "./internal/jobs-api.js";
16
16
  import { createSecretsApi } from "./secrets.js";
17
17
  import { crypto } from "./crypto.js";
18
18
  import { createOrgApi } from "./org.js";
19
+ const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
19
20
  export function defineScript(handler) {
20
21
  if (typeof handler !== "function") {
21
22
  throw new ValidationError("defineScript() requires a handler function");
@@ -28,7 +29,7 @@ export function defineScript(handler) {
28
29
  }
29
30
  /** @internal */
30
31
  export function createSandboxHandler(handler) {
31
- return async (inputJson) => {
32
+ const sandboxHandler = async (inputJson, responseToken) => {
32
33
  installCogoverFetch();
33
34
  let input;
34
35
  try {
@@ -61,10 +62,13 @@ export function createSandboxHandler(handler) {
61
62
  if (output === null) {
62
63
  return null;
63
64
  }
64
- const outputJson = JSON.stringify(output);
65
+ const outputJson = serializeHandlerOutput(output, responseToken);
65
66
  if (outputJson === undefined) {
66
67
  throw new ValidationError("Script output must be JSON serializable");
67
68
  }
68
69
  return outputJson;
69
70
  };
71
+ // Tells Cogover that this handler accepts a per-invocation response token as its second argument.
72
+ Object.defineProperty(sandboxHandler, RESPONSE_TOKEN_VERSION_MEMBER, { value: 1 });
73
+ return sandboxHandler;
70
74
  }
@@ -0,0 +1,288 @@
1
+ # `@cogover/sdk` API reference: Background jobs
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Background jobs
6
+
7
+ A background job runs project code outside an HTTP request: enqueued by a script, a
8
+ trigger, another job, or an administrator, or started by a cron schedule. Declare
9
+ each job with `defineJob` and list the results in the project's named `jobs`
10
+ export. The default export is still the HTTP handler and is optional in a project
11
+ that only declares jobs and triggers.
12
+
13
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
14
+ fields used below.
15
+
16
+ ```typescript
17
+ import { defineJob } from "@cogover/sdk";
18
+
19
+ interface RecalcPayload {
20
+ cursor?: string;
21
+ }
22
+
23
+ export const jobs = [
24
+ // Enqueued by a route or a trigger; walks all orders one page per run.
25
+ defineJob<RecalcPayload>({
26
+ key: "recalc_totals",
27
+ name: "Recalculate order totals",
28
+ timeoutMs: 60_000,
29
+ }, async ({ payload, data, jobs, log }) => {
30
+ const orders = data.object("order");
31
+ const page = await orders.records.list({
32
+ fields: ["subtotal", "tax"],
33
+ limit: 200,
34
+ ...(payload?.cursor ? { cursor: payload.cursor } : {}),
35
+ });
36
+ for (const order of page.items) {
37
+ await orders.records.update(order.id, {
38
+ total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
39
+ });
40
+ }
41
+ if (page.nextCursor) {
42
+ // Continue with the next page in a new run instead of one long run.
43
+ await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
44
+ return;
45
+ }
46
+ log.info("Order totals recalculated");
47
+ }),
48
+
49
+ // Runs every day at 02:00 in the given time zone.
50
+ defineJob({
51
+ key: "cancel_stale_orders",
52
+ schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
53
+ }, async ({ data }) => {
54
+ const orders = data.object("order");
55
+ const stale = await orders.records.list({
56
+ where: orders.fields.status.eq("new"),
57
+ fields: ["status"],
58
+ limit: 200,
59
+ });
60
+ for (const order of stale.items) {
61
+ await orders.records.update(order.id, { status: "cancelled" });
62
+ }
63
+ }),
64
+ ];
65
+ ```
66
+
67
+ Cogover reads the job configuration when a project version is published and applies
68
+ it while that version is active: `jobs.enqueue` accepts only the keys declared by the
69
+ active version, and schedules run only while their version is active. Deactivating
70
+ the project removes its schedules. A project can declare at most 50 jobs.
71
+
72
+ ### `defineJob(config, handler): JobDefinition`
73
+
74
+ ```typescript
75
+ function defineJob<
76
+ Payload = unknown,
77
+ Schema extends object = EffectiveWorkspaceObjects,
78
+ >(config: JobConfig, handler: JobHandler<Payload, Schema>): JobDefinition;
79
+ ```
80
+
81
+ `Payload` is the type of the value passed to `jobs.enqueue`; it is not validated at
82
+ run time, so treat the payload like request input. `defineJob` validates the
83
+ configuration immediately and throws `ValidationError` for any violation, for an
84
+ unknown configuration key, or for a handler that is not a function. It returns a
85
+ frozen `JobDefinition`.
86
+
87
+ ```typescript
88
+ interface JobConfig {
89
+ readonly key: string;
90
+ readonly name?: string;
91
+ readonly timeoutMs?: number;
92
+ readonly maxAttempts?: number;
93
+ readonly schedule?: JobSchedule;
94
+ }
95
+
96
+ interface JobSchedule {
97
+ readonly cron: string;
98
+ readonly timezone?: string;
99
+ }
100
+ ```
101
+
102
+ | Option | Required | Rules and meaning |
103
+ |---|---|---|
104
+ | `key` | Yes | Identifies the job inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters; unique in the project regardless of case. Keep it stable between versions: a new key is a different job. |
105
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
106
+ | `timeoutMs` | No | Integer from 1000 through 60000; defaults to `30000`. Time budget of one attempt. |
107
+ | `maxAttempts` | No | Integer from 1 through 10; defaults to `5`. Total number of attempts of one run, including the first. |
108
+ | `schedule` | No | Runs the job automatically. `cron` has five fields — minute, hour, day-of-month, month, day-of-week — and `timezone` is an IANA time zone ID of at most 64 characters, defaulting to `"UTC"`. |
109
+
110
+ A cron field is `*`, a number, a range `a-b`, a list `a,b`, a step `*/n`, or a
111
+ stepped range `a-b/n`; the fields accept minutes 0–59, hours 0–23, days 1–31,
112
+ months 1–12, and weekdays 0–7 where both 0 and 7 are Sunday. Names such as `MON`,
113
+ the characters `L`, `W`, `#`, and `?`, and macros such as `@daily` are not supported.
114
+ The shortest period is one minute. Whitespace between the fields is normalized to
115
+ one space in the manifest, and the normalized expression may have at most 128
116
+ characters; a longer one throws `ValidationError`. Cogover stores the time zone in its
117
+ normalized form, so an offset such as `UTC+7` is listed as `UTC+07:00` in the project's
118
+ schedules.
119
+
120
+ ### `JobDefinition` and `JobManifest`
121
+
122
+ ```typescript
123
+ interface JobManifest {
124
+ readonly key: string;
125
+ readonly name?: string;
126
+ readonly timeoutMs: number;
127
+ readonly maxAttempts: number;
128
+ readonly schedule?: { readonly cron: string; readonly timezone: string };
129
+ }
130
+
131
+ interface JobDefinition {
132
+ readonly key: string;
133
+ readonly config: JobManifest;
134
+ readonly __cogoverJobHandler: SandboxHandler;
135
+ }
136
+ ```
137
+
138
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
139
+ default applied: `timeoutMs: 30000`, `maxAttempts: 5`, and `schedule.timezone:
140
+ "UTC"`. Optional settings that were not provided are absent. It is detached from the
141
+ object passed to `defineJob`, so later edits of that object have no effect.
142
+ `__cogoverJobHandler` is reserved for Cogover; project code does not call it.
143
+
144
+ ### Job handler context
145
+
146
+ ```typescript
147
+ type JobHandler<
148
+ Payload = unknown,
149
+ Schema extends object = EffectiveWorkspaceObjects,
150
+ > = (context: JobContext<Payload, Schema>) => void | Promise<void>;
151
+
152
+ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspaceObjects> {
153
+ readonly job: JobInfo;
154
+ readonly payload: Payload | null;
155
+ readonly invocation: InvocationContext;
156
+ readonly data: DataApi<Schema>;
157
+ readonly schema: SchemaApi<Schema>;
158
+ readonly log: ScriptLogger;
159
+ readonly state: ProjectState;
160
+ readonly locks: DistributedLocks;
161
+ readonly notifications: NotificationsApi;
162
+ readonly email: EmailApi<Schema>;
163
+ readonly jobs: JobsApi;
164
+ readonly secrets: SecretsApi;
165
+ readonly crypto: CryptoApi;
166
+ readonly org: OrgApi;
167
+ }
168
+
169
+ interface JobInfo {
170
+ readonly id: string;
171
+ readonly key: string;
172
+ readonly attempt: number;
173
+ readonly maxAttempts: number;
174
+ readonly source: "enqueue" | "schedule";
175
+ readonly runAt: number;
176
+ readonly enqueuedAt?: number;
177
+ }
178
+ ```
179
+
180
+ A handler may be synchronous or asynchronous; its return value is ignored. `data`,
181
+ `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
182
+ `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
183
+ no `input`, `request`, `response`, or `push`.
184
+
185
+ - `job.id` identifies the run and stays the same across its attempts; use it as the
186
+ idempotency key of external calls. `job.attempt` starts at 1.
187
+ - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
188
+ administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
189
+ is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
190
+ milliseconds, and `enqueuedAt` is absent for a scheduled run.
191
+ - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
192
+ passed or the run is scheduled. It is plain, mutable data.
193
+
194
+ ### `jobs.enqueue(jobKey, payload?, options?): Promise<EnqueueResult>`
195
+
196
+ ```typescript
197
+ interface JobsApi {
198
+ enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
199
+ }
200
+
201
+ interface EnqueueOptions {
202
+ readonly delayMs?: number;
203
+ readonly runAt?: number;
204
+ readonly idempotencyKey?: string;
205
+ }
206
+
207
+ interface EnqueueResult {
208
+ readonly runId: string;
209
+ readonly duplicate: boolean;
210
+ }
211
+ ```
212
+
213
+ ```typescript
214
+ const { runId, duplicate } = await jobs.enqueue("sync_order", { orderId: order.id }, {
215
+ delayMs: 60_000,
216
+ idempotencyKey: `sync_order:${order.id}:${order.system.updatedAt}`,
217
+ });
218
+ ```
219
+
220
+ `jobKey` must be a job declared by the active version; otherwise Cogover throws
221
+ `ValidationError`. `payload` is any JSON value of at most 65,536 UTF-8 bytes in its
222
+ `JSON.stringify` form, in which a quote, a backslash, or a control character counts as
223
+ its escape sequence; `undefined` and `null` enqueue the run without a payload. Values that
224
+ JSON would silently change, such as `NaN` or class instances, are rejected with
225
+ `ValidationError`. `delayMs` is an integer from 0 through 2,592,000,000 (30 days)
226
+ and `runAt` a Unix millisecond time at most 30 days ahead; pass one or neither, not
227
+ both. `idempotencyKey` starts with a letter or digit, contains letters, digits, `.`,
228
+ `_`, `:`, or `-`, and is at most 128 characters: a second enqueue of the same job
229
+ with the same key while the earlier run is still kept returns that run with
230
+ `duplicate: true` instead of creating another. Run history is kept for 7 days.
231
+
232
+ `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
233
+ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
234
+ (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
235
+ without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
236
+ enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
237
+ running; beyond that `RateLimitError` is thrown. An HTTP route or a trigger reaches
238
+ its budget of 20 capability calls first (see
239
+ [Execution limits](overview.md#execution-limits)), so there the limit of 50 enqueues
240
+ is not reached. When jobs are not enabled for the Workspace, the error is
241
+ `CogoverApiError` with `code: "JOBS_DISABLED"`.
242
+
243
+ ### Job execution rules
244
+
245
+ - **Identity.** A run enqueued from a script, route, or trigger runs as the user of
246
+ that invocation: `invocation` describes that user and `data.object()` acts with
247
+ that user's permissions. A run that a Super Admin enqueues through the job
248
+ management API likewise runs as that Super Admin, and the run history shows it with
249
+ `enqueuedBy: "management"`. A scheduled run and a run enqueued from an inbound
250
+ webhook call have no user: `invocation.identity`
251
+ is `"system"`, and `data.object()` works only if the project's approved identity
252
+ policy sets `allowInternalSystem: true`; otherwise its calls throw
253
+ `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
254
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
255
+ - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
256
+ `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
257
+ within the runtime limits of the job lane.
258
+ - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
259
+ split: process one page, save the cursor, and enqueue the same job again with the
260
+ cursor in the payload, as in the example above.
261
+ - **At least once.** Cogover does not guarantee that a run executes exactly once: an
262
+ attempt that was interrupted, for example by a restart, is started again. Make
263
+ every handler idempotent. `job.id` identifies the run across attempts, and
264
+ `idempotencyKey` on `enqueue` prevents duplicate runs.
265
+ - **Retries.** Throw `RetryableError` when the handler fails for a temporary reason,
266
+ such as an external service that is unavailable. Cogover runs the attempt again
267
+ later, waiting longer before each attempt, from a few seconds to about half an
268
+ hour, until `maxAttempts` attempts have been made. An attempt that exceeds
269
+ `timeoutMs`, or that Cogover could not run for a temporary reason, is retried the
270
+ same way. Any other error ends the run as failed: the failure is logged and the
271
+ handler does not run again for that run.
272
+ - **Order and concurrency.** Runs execute in no guaranteed order, and two runs of the
273
+ same project, even of the same job, may execute at the same time. Use `locks` when
274
+ a section must not run concurrently, and delay through `delayMs` or `runAt` rather
275
+ than by waiting inside the handler.
276
+ - **Loops end.** Record writes made by a run carry the automation budget of the
277
+ invocation that enqueued it (a scheduled run and an administrator's enqueue start
278
+ with the full budget of 10 steps), so a chain of jobs and triggers started by
279
+ record writes ends the same way as a trigger chain. Enqueueing a job does not use
280
+ a step: a job that enqueues itself must stop on its own, for example when the
281
+ cursor is exhausted.
282
+
283
+ A scheduled job creates one run for each time the schedule matches, in the
284
+ schedule's time zone; the run may start a little later than the scheduled minute
285
+ under load. A slot that is missed while the project is inactive is not run later.
286
+ A run is still created when the previous scheduled run has not finished, so a
287
+ schedule whose work can take longer than its period should guard itself with a
288
+ lock.