@cogover/sdk 0.12.2 → 0.14.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.
@@ -12,7 +12,7 @@ The reference is split into the following pages. Each page covers one area of th
12
12
  | Page | Covers |
13
13
  |---|---|
14
14
  | [Scripts and HTTP routes](scripts-and-routes.md) | `defineScript`; HTTP routers and request context; Invocation identity and workspace; HTTP response API; Logging |
15
- | [Records and schema](records.md) | Record API; Filters and sorting; Record execution identities; Schema API; Workspace declarations |
15
+ | [Records and schema](records.md) | Record API; Choosing fields; Linked records; Aggregates; Filters and sorting; Record execution identities; Schema API; Workspace declarations |
16
16
  | [Record triggers](record-triggers.md) | Record triggers |
17
17
  | [Background jobs](background-jobs.md) | Background jobs |
18
18
  | [Outbound HTTP and secrets](fetch-and-secrets.md) | Outbound HTTP `fetch`; Secrets and credentials |
@@ -23,7 +23,7 @@ The reference is split into the following pages. Each page covers one area of th
23
23
  | [Notifications and email](notifications-and-email.md) | Notifications; Email |
24
24
  | [Organization structure](organization-structure.md) | Organization structure |
25
25
 
26
- The sections below apply to every area: the errors every API can throw, the limits of one execution, and the compatibility helper.
26
+ The sections below apply to every area: the errors every API can throw, the limits of one execution, reading those limits in code, and the compatibility helper.
27
27
 
28
28
  ## Errors
29
29
 
@@ -89,6 +89,12 @@ throws it to report a temporary failure, and Cogover runs the handler again late
89
89
  meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
90
90
  that throws it rejects the write like any other failure.
91
91
 
92
+ A record read (`get`, `getMany`, or `list`) without a valid `fields` option throws
93
+ `ValidationError` with the message `fields is required: pass field slugs or "*"
94
+ (@cogover/sdk 0.13.0+)`. Cogover returns the same error to a project version that was
95
+ published with an older SDK and reads without `fields` (see
96
+ [Choosing fields](records.md#choosing-fields)).
97
+
92
98
  `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
93
99
  `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
94
100
  with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
@@ -165,28 +171,117 @@ These responses do not roll back earlier writes; do not retry writes automatical
165
171
  Every execution runs within platform limits. These are the default values; they are
166
172
  set by the platform and may differ between environments.
167
173
 
168
- - An HTTP route and a record trigger may make at most 20 capability calls. Every call
169
- to `data`, `schema`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`,
170
- `secrets`, `crypto`, `org`, or `fetch` counts once. A background job may make 200.
171
- The call over the budget, and every call after it, throws `RateLimitError`
172
- (`details.limit` is the budget) without being sent, so a script can catch it.
174
+ | Budget of one execution | HTTP route | Before-change trigger | After-change trigger | Background job |
175
+ |---|---|---|---|---|
176
+ | Capability calls (`capabilityCalls`) | 100 | 20 | 100 | 1,000 |
177
+ | Local calls (`localCalls`) | 200 | 50 | 200 | 1,000 |
178
+ | Records read (`recordsRead`) | 10,000 | 4,000 | 10,000 | 50,000 |
179
+ | Records written (`recordsWritten`) | 10,000 | — | 10,000 | 50,000 |
180
+
181
+ - **Capability calls.** Every call to `data`, `schema`, `state`, `locks`, `push`,
182
+ `notifications`, `email`, `jobs`, `secrets`, or `fetch`, and every `org` read with
183
+ `withDisplay: true`, counts once.
184
+ - **Local calls.** `crypto` calls and `org` reads without `withDisplay` are handled by
185
+ Cogover itself, so they count against their own budget instead. A `crypto` key given as
186
+ `{ secret: name }` is still a secret read (see its quota below).
187
+ - **Records read.** The records returned by `records.get`, `records.getMany`, and
188
+ `records.list`, and the linked records that `expandLookups` reads. A read is refused
189
+ before it is sent when it could go over the budget: `records.get` counts 1,
190
+ `records.getMany` the number of IDs, and `records.list` its `limit` (20 by default).
191
+ `records.aggregate` returns no records and does not count.
192
+ - **Records written.** 1 for `create`, `update`, and `upsertByUniqueField`, the number of
193
+ records for `batchInsert` and `batchUpdate`, and the number of IDs for `deleteMany`,
194
+ counted when the call is sent. A before-change trigger cannot write records.
195
+ - A call that would go over a budget, and every later call against that budget, throws
196
+ `RateLimitError` without being sent, so a script can catch it. `details.budget` names
197
+ the budget, `details.limit` is its size, `details.used` is what the execution had used,
198
+ and for records `details.requested` is what the call asked for. Waiting does not help:
199
+ the budget belongs to the execution. Read fewer records, use `records.aggregate` for
200
+ totals, or move the work to a background job. An execution that keeps calling after
201
+ 1,000 refused calls is ended with `code: "RATE_LIMITED"`; the script cannot catch that.
173
202
  - An HTTP route has 8 seconds of wall-clock time, counted from when its handler
174
203
  starts, including the time spent waiting for capability calls, a lock, or a remote
175
204
  server. A record trigger has its own `timeoutMs`, and a background job its
176
205
  `timeoutMs`. Exceeding the time ends the whole execution: the script cannot catch it,
177
- and an HTTP route returns the generic HTTP 422 response.
206
+ and an HTTP route returns the generic HTTP 422 response. Capability calls of one
207
+ execution run one after another, also when they are started together with
208
+ `Promise.all`.
178
209
  - A single capability request, JSON-encoded with its arguments, must not exceed
179
210
  262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
180
211
  or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
181
212
  is the limit. A capability result larger than 1,048,576 bytes is withheld the same
182
- way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records or fields. The
213
+ way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records, or name the
214
+ fields instead of `"*"`. The
183
215
  operation itself did run, so a write may have completed.
184
216
  - When the Workspace already has too many executions waiting, a new HTTP call is
185
217
  refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
218
+ This refusal has no `details.budget`.
219
+
220
+ Some APIs also keep their own quota per execution, such as 20 `fetch` calls or 20
221
+ secret reads. Going over one is reported as `RateLimitError` too.
222
+
223
+ ## Reading limits in code
224
+
225
+ ```typescript
226
+ const limits: LimitsApi;
227
+
228
+ interface LimitsApi {
229
+ usage(): LimitUsage;
230
+ }
231
+
232
+ interface LimitUsage {
233
+ readonly capabilityCalls: LimitCounter;
234
+ readonly localCalls: LimitCounter;
235
+ readonly recordsRead: LimitCounter;
236
+ readonly recordsWritten: LimitCounter;
237
+ readonly elapsedMs: number;
238
+ readonly timeLimitMs: number;
239
+ }
240
+
241
+ interface LimitCounter {
242
+ readonly used: number;
243
+ readonly limit: number;
244
+ readonly remaining: number;
245
+ }
246
+ ```
247
+
248
+ `limits` is exported by the package and is also the `limits` member of the context of
249
+ a script, a route, a record trigger, and a background job. `limits.usage()` returns the
250
+ budgets of the current execution as of its last Cogover call: reading them is not a
251
+ capability call. `remaining` is `limit - used` and never below 0. `elapsedMs` is the
252
+ time since the handler started, as of that last call, and `timeLimitMs` is the
253
+ wall-clock time the execution may take. Called outside a handler, for example while the
254
+ module loads or in a test that runs outside Cogover, `usage()` throws `CogoverApiError`
255
+ with `code: "CAPABILITY_UNAVAILABLE"`.
256
+
257
+ When code runs locally with Cogover Dev CLI, each handler gets the budgets of its kind of
258
+ execution and the same refusals; linked records read by `expandLookups` are not counted
259
+ there.
260
+
261
+ ```typescript
262
+ import { defineScript } from "@cogover/sdk";
263
+
264
+ export default defineScript(async ({ data, jobs, limits }) => {
265
+ const orders = data.object("order");
266
+ let cursor: string | undefined;
267
+ let total = 0;
268
+ do {
269
+ const page = await orders.records.list({ fields: ["amount"], limit: 200, cursor });
270
+ for (const order of page.items) total += Number(order.fields.amount ?? 0);
271
+ cursor = page.nextCursor;
272
+ const usage = limits.usage();
273
+ if (cursor !== undefined && (usage.recordsRead.remaining < 200 || usage.capabilityCalls.remaining < 2)) {
274
+ // Hand the rest to a background job, which has larger budgets.
275
+ await jobs.enqueue("sum_orders", { cursor, total });
276
+ return { total, complete: false };
277
+ }
278
+ } while (cursor !== undefined);
279
+ return { total, complete: true };
280
+ });
281
+ ```
186
282
 
187
- When an API has its own per-execution quota that is not below the call budget, such
188
- as 20 `fetch` calls or 20 secret reads, the call budget is reached first in a route
189
- or a trigger; both are reported as `RateLimitError`.
283
+ For a total like this one, `records.aggregate` is one capability call and reads no
284
+ records; page through records only when the result cannot be expressed as an aggregate.
190
285
 
191
286
  ## Compatibility helper
192
287
 
@@ -226,6 +226,7 @@ interface TriggerContext<
226
226
  readonly secrets: SecretsApi;
227
227
  readonly crypto: CryptoApi;
228
228
  readonly org: OrgApi;
229
+ readonly limits: LimitsApi;
229
230
  }
230
231
 
231
232
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -262,7 +263,8 @@ once per record. Keep `fields` short, and read related data for the whole list w
262
263
  one `records.getMany` call rather than one read per record.
263
264
 
264
265
  `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
265
- `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
266
+ `crypto`, `org`, and `limits` are the same APIs that scripts receive; a before-change trigger has
267
+ smaller budgets (see [Execution limits](overview.md#execution-limits)). A trigger context has no `input`,
266
268
  `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
267
269
  before-change trigger. `trigger.operation` is
268
270
  the operation of the current call, `trigger.id` identifies the trigger registration, and
@@ -287,6 +289,14 @@ trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
287
289
  `TriggerOldValues` make every field optional because a field that is not listed in
288
290
  `fields`, or that has no value, is `undefined`.
289
291
 
292
+ Lookup and reference values in `new` and `old` carry the linked record's `name`. This
293
+ differs from records read through `data`, whose lookup values have `name: ""` unless
294
+ the read uses `expandLookups` (see [Linked records](records.md#linked-records)). Reads
295
+ through `data` in a trigger follow the same rules as in a script, including the
296
+ required `fields`. For a change made by a user, `data.object()` reads as that user, so
297
+ its `records.aggregate` has the limits of `data.asUser()`: use `data.asSystem()` to
298
+ group (see [Aggregates](records.md#aggregates)).
299
+
290
300
  ### Validating and changing records
291
301
 
292
302
  This section applies to before-change triggers. In an after-change trigger the
@@ -387,6 +397,10 @@ a request that only validates input without saving.
387
397
  receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
388
398
  - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
389
399
  one write share a total budget of 8 seconds.
400
+ - **Reads delay the write.** The user's write waits while the handler reads. Each
401
+ expanded lookup reads another Object, and `records.aggregate`, which is allowed, is
402
+ computed from a search index that is about one second behind: it does not count the
403
+ change being made, and may miss changes saved just before it. Keep such calls few.
390
404
 
391
405
  ### After-change execution rules
392
406