@cogover/sdk 0.17.0 → 0.18.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.
- package/README.md +12 -0
- package/dist/router.d.ts +5 -0
- package/dist/router.js +129 -12
- package/docs/en/api-reference/fetch-and-secrets.md +3 -1
- package/docs/en/api-reference/overview.md +59 -7
- package/docs/en/api-reference/scripts-and-routes.md +44 -0
- package/docs/en/api-reference/state-and-locks.md +10 -2
- package/docs/en/usage-guide.md +166 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -52,6 +52,8 @@ authentication credentials are not exposed to project code, and Cogover enforces
|
|
|
52
52
|
the configured permissions and the per-execution limits on capability calls and
|
|
53
53
|
records. `limits.usage()` (also `context.limits`) reports how much of each budget
|
|
54
54
|
the execution has used, without a capability call.
|
|
55
|
+
Calls started together, for example with `Promise.all`, run in parallel up to a
|
|
56
|
+
platform limit; every call still counts towards the budgets.
|
|
55
57
|
|
|
56
58
|
## Current identity and workspace
|
|
57
59
|
|
|
@@ -116,6 +118,16 @@ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide expl
|
|
|
116
118
|
status, safe response headers, and text/binary bodies. Missing routes, including a
|
|
117
119
|
path registered only for other methods, return 404; methods other than these five
|
|
118
120
|
return 405. Existing `defineScript()` projects continue at `/`.
|
|
121
|
+
|
|
122
|
+
To keep a group of routes in its own file, export a router created with
|
|
123
|
+
`createRouter()` from that file and mount it with `router.route(prefix, childRouter)`:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { ordersRouter } from "./orders-router.js";
|
|
127
|
+
|
|
128
|
+
router.route("/orders", ordersRouter); // the routes of ordersRouter, under /orders
|
|
129
|
+
```
|
|
130
|
+
|
|
119
131
|
The complete router contract is included in `docs/en/api-reference/scripts-and-routes.md`.
|
|
120
132
|
|
|
121
133
|
## Record triggers
|
package/dist/router.d.ts
CHANGED
|
@@ -8,6 +8,11 @@ export interface ScriptRouter<TSchema extends object = EffectiveWorkspaceObjects
|
|
|
8
8
|
put<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
9
9
|
patch<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
10
10
|
delete<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
11
|
+
/**
|
|
12
|
+
* Mounts every route of `router` under `prefix` (`"/"` mounts them unchanged) and returns this router. The routes
|
|
13
|
+
* of `router` are read when `toHandler()` is called, so routes added to it after this call are included.
|
|
14
|
+
*/
|
|
15
|
+
route(prefix: string, router: ScriptRouter<TSchema>): ScriptRouter<TSchema>;
|
|
11
16
|
toHandler(): SandboxHandler;
|
|
12
17
|
}
|
|
13
18
|
export declare function createRouter<TSchema extends object = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>;
|
package/dist/router.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import { NotFoundError, ValidationError } from "./errors.js";
|
|
2
2
|
import { validateRoutePath, withRouteParams } from "./internal/request.js";
|
|
3
3
|
import { createSandboxHandler } from "./script.js";
|
|
4
|
+
// Routers created by createRouter(); route() accepts only these.
|
|
5
|
+
const ROUTER_ITEMS = new WeakMap();
|
|
6
|
+
const MAX_MOUNTS_PER_ROUTER = 64;
|
|
7
|
+
const MAX_MOUNT_DEPTH = 8;
|
|
8
|
+
const MAX_FLATTENED_ROUTES = 2048;
|
|
4
9
|
export function createRouter() {
|
|
5
10
|
const routes = [];
|
|
11
|
+
const items = [];
|
|
12
|
+
let mounts = 0;
|
|
6
13
|
const router = {
|
|
7
14
|
addRoute(method, path, handler) {
|
|
8
15
|
if (!isRequestMethod(method))
|
|
@@ -16,8 +23,10 @@ export function createRouter() {
|
|
|
16
23
|
}
|
|
17
24
|
if (routes.length >= 256)
|
|
18
25
|
throw new ValidationError("A router supports at most 256 routes");
|
|
19
|
-
|
|
20
|
-
handler: handler })
|
|
26
|
+
const route = Object.freeze({ method, path, signature,
|
|
27
|
+
handler: handler });
|
|
28
|
+
routes.push(route);
|
|
29
|
+
items.push(Object.freeze({ route }));
|
|
21
30
|
return router;
|
|
22
31
|
},
|
|
23
32
|
post(path, handler) {
|
|
@@ -35,19 +44,40 @@ export function createRouter() {
|
|
|
35
44
|
delete(path, handler) {
|
|
36
45
|
return router.addRoute("DELETE", path, handler);
|
|
37
46
|
},
|
|
47
|
+
route(prefix, child) {
|
|
48
|
+
validateRoutePath(prefix);
|
|
49
|
+
if (typeof child !== "object" || child === null || !ROUTER_ITEMS.has(child)) {
|
|
50
|
+
throw new ValidationError("route() requires a router created by createRouter()");
|
|
51
|
+
}
|
|
52
|
+
if (child === router)
|
|
53
|
+
throw new ValidationError("A router cannot be mounted on itself");
|
|
54
|
+
if (mounts >= MAX_MOUNTS_PER_ROUTER) {
|
|
55
|
+
throw new ValidationError(`A router supports at most ${MAX_MOUNTS_PER_ROUTER} mounted routers`);
|
|
56
|
+
}
|
|
57
|
+
items.push(Object.freeze({ prefix, child, mount: mounts++ }));
|
|
58
|
+
return router;
|
|
59
|
+
},
|
|
38
60
|
toHandler() {
|
|
39
61
|
// Each exported handler gets a stable route table, never a global registry.
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
62
|
+
const flat = flattenRouter(router, 0, new Set(), new Map()).routes;
|
|
63
|
+
const signatures = new Set();
|
|
64
|
+
const registered = [];
|
|
65
|
+
for (const { route } of flat) {
|
|
66
|
+
validateRoutePath(route.path);
|
|
67
|
+
const signature = routeSignature(route.path);
|
|
68
|
+
const key = `${route.method} ${signature}`;
|
|
69
|
+
if (signatures.has(key)) {
|
|
70
|
+
throw new ValidationError(`Duplicate or ambiguous route: ${route.method} ${route.path}`);
|
|
71
|
+
}
|
|
72
|
+
signatures.add(key);
|
|
73
|
+
registered.push(route.signature === signature ? route : Object.freeze({ ...route, signature }));
|
|
74
|
+
}
|
|
75
|
+
Object.freeze(registered);
|
|
76
|
+
const handler = createSandboxHandler(context => {
|
|
77
|
+
const matched = selectRoute(registered, context.request.method, context.request.path);
|
|
78
|
+
if (matched === null)
|
|
49
79
|
throw new NotFoundError("route", context.request.path);
|
|
50
|
-
return matched.
|
|
80
|
+
return registered[matched.index].handler({
|
|
51
81
|
input: context.input,
|
|
52
82
|
request: withRouteParams(context.request, matched.params),
|
|
53
83
|
get invocation() {
|
|
@@ -71,10 +101,97 @@ export function createRouter() {
|
|
|
71
101
|
agents: context.agents,
|
|
72
102
|
});
|
|
73
103
|
});
|
|
104
|
+
// Hidden, read-only description of the flattened table; matching is the handler's own selection.
|
|
105
|
+
Object.defineProperty(handler, "__cogoverRoutes", {
|
|
106
|
+
value: Object.freeze({
|
|
107
|
+
version: 1,
|
|
108
|
+
routes: Object.freeze(flat.map(entry => Object.freeze({
|
|
109
|
+
method: entry.route.method,
|
|
110
|
+
path: entry.route.path,
|
|
111
|
+
owner: entry.owner,
|
|
112
|
+
mount: entry.mount,
|
|
113
|
+
prefix: entry.prefix,
|
|
114
|
+
}))),
|
|
115
|
+
match(method, path) {
|
|
116
|
+
if (typeof method !== "string" || typeof path !== "string")
|
|
117
|
+
return -1;
|
|
118
|
+
return selectRoute(registered, method, path)?.index ?? -1;
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
enumerable: false,
|
|
122
|
+
writable: false,
|
|
123
|
+
configurable: false,
|
|
124
|
+
});
|
|
125
|
+
return handler;
|
|
74
126
|
},
|
|
75
127
|
};
|
|
128
|
+
ROUTER_ITEMS.set(router, items);
|
|
76
129
|
return Object.freeze(router);
|
|
77
130
|
}
|
|
131
|
+
// Flattens own routes and mounted routers in registration order. A router mounted more than once is flattened once
|
|
132
|
+
// per call; `height` bounds nesting from any depth it is reached at.
|
|
133
|
+
function flattenRouter(router, depth, ancestors, done) {
|
|
134
|
+
const cached = done.get(router);
|
|
135
|
+
if (cached !== undefined) {
|
|
136
|
+
if (depth + cached.height > MAX_MOUNT_DEPTH)
|
|
137
|
+
throw new ValidationError("Router mounts are nested too deeply");
|
|
138
|
+
return cached;
|
|
139
|
+
}
|
|
140
|
+
if (ancestors.has(router))
|
|
141
|
+
throw new ValidationError("Router mounts form a cycle");
|
|
142
|
+
if (depth > MAX_MOUNT_DEPTH)
|
|
143
|
+
throw new ValidationError("Router mounts are nested too deeply");
|
|
144
|
+
ancestors.add(router);
|
|
145
|
+
const items = ROUTER_ITEMS.get(router);
|
|
146
|
+
const routes = [];
|
|
147
|
+
let height = 0;
|
|
148
|
+
const append = (entry) => {
|
|
149
|
+
if (routes.length >= MAX_FLATTENED_ROUTES) {
|
|
150
|
+
throw new ValidationError(`A router supports at most ${MAX_FLATTENED_ROUTES} routes including mounted routers`);
|
|
151
|
+
}
|
|
152
|
+
routes.push(entry);
|
|
153
|
+
};
|
|
154
|
+
for (const item of items) {
|
|
155
|
+
if ("route" in item) {
|
|
156
|
+
append({ route: item.route, owner: null, mount: -1, prefix: null });
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const child = flattenRouter(item.child, depth + 1, ancestors, done);
|
|
160
|
+
height = Math.max(height, child.height + 1);
|
|
161
|
+
for (const { route } of child.routes) {
|
|
162
|
+
const path = joinRoutePath(item.prefix, route.path);
|
|
163
|
+
append({ route: path === route.path ? route : Object.freeze({ ...route, path }),
|
|
164
|
+
owner: item.child, mount: item.mount, prefix: item.prefix });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
ancestors.delete(router);
|
|
168
|
+
const result = Object.freeze({ routes: Object.freeze(routes), height });
|
|
169
|
+
done.set(router, result);
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
function joinRoutePath(prefix, path) {
|
|
173
|
+
if (prefix === "/")
|
|
174
|
+
return path;
|
|
175
|
+
return path === "/" ? prefix : prefix + path;
|
|
176
|
+
}
|
|
177
|
+
// Static routes that equal the path win; otherwise the first registered route that matches.
|
|
178
|
+
function selectRoute(registered, method, path) {
|
|
179
|
+
for (let index = 0; index < registered.length; index++) {
|
|
180
|
+
const route = registered[index];
|
|
181
|
+
if (route.method === method && !route.path.includes(":") && route.path === path) {
|
|
182
|
+
return { index, params: {} };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (let index = 0; index < registered.length; index++) {
|
|
186
|
+
const route = registered[index];
|
|
187
|
+
if (route.method !== method)
|
|
188
|
+
continue;
|
|
189
|
+
const params = matchRoute(route.path, path);
|
|
190
|
+
if (params !== null)
|
|
191
|
+
return { index, params };
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
78
195
|
function isRequestMethod(method) {
|
|
79
196
|
return method === "GET" || method === "POST" || method === "PUT"
|
|
80
197
|
|| method === "PATCH" || method === "DELETE";
|
|
@@ -78,7 +78,9 @@ headers, time, calls, destinations, and concurrency are bounded by platform quot
|
|
|
78
78
|
U+FFFD, so binary content cannot be read exactly.
|
|
79
79
|
- A host name that resolves to an address that is not public fails with
|
|
80
80
|
`FETCH_FAILED`.
|
|
81
|
-
- Calls started together, for example with `Promise.all`,
|
|
81
|
+
- Calls started together, for example with `Promise.all`, run in parallel up to a
|
|
82
|
+
number of simultaneous `fetch` calls set by the platform; further calls wait for a
|
|
83
|
+
free slot instead of failing.
|
|
82
84
|
- A before-change trigger cannot call `fetch`: it throws `PermissionDeniedError` with
|
|
83
85
|
`details.reason` `"TRIGGER_READ_ONLY"`. A read-only version preview allows only `GET`
|
|
84
86
|
and `HEAD` without `credential` and refuses other calls with `PermissionDeniedError`.
|
|
@@ -25,7 +25,7 @@ The reference is split into the following pages. Each page covers one area of th
|
|
|
25
25
|
| [Custom Module Actions](actions.md) | Custom Module Actions; Schema builder |
|
|
26
26
|
| [Processes and AI Agents](processes-and-agents.md) | Processes and AI Agents |
|
|
27
27
|
|
|
28
|
-
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.
|
|
28
|
+
The sections below apply to every area: the errors every API can throw, the limits of one execution, calls that run in parallel, reading those limits in code, and the compatibility helper.
|
|
29
29
|
|
|
30
30
|
## Errors
|
|
31
31
|
|
|
@@ -226,9 +226,9 @@ set by the platform and may differ between environments.
|
|
|
226
226
|
server. A record trigger has its own `timeoutMs`, and a background job its
|
|
227
227
|
`timeoutMs`. A Custom Module Action has the budgets of an HTTP route and its own
|
|
228
228
|
`timeoutMs`, at most 8 seconds. Exceeding the time ends the whole execution: the script cannot catch it,
|
|
229
|
-
and an HTTP route returns the generic HTTP 422 response.
|
|
230
|
-
|
|
231
|
-
|
|
229
|
+
and an HTTP route returns the generic HTTP 422 response. Calls started together run
|
|
230
|
+
in parallel (see [Parallel calls](#parallel-calls)), which shortens the time spent
|
|
231
|
+
waiting.
|
|
232
232
|
- A single capability request, JSON-encoded with its arguments, must not exceed
|
|
233
233
|
262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
|
|
234
234
|
or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
|
|
@@ -236,14 +236,66 @@ set by the platform and may differ between environments.
|
|
|
236
236
|
way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records, or name the
|
|
237
237
|
fields instead of `"*"`. The
|
|
238
238
|
operation itself did run, so a write may have completed.
|
|
239
|
-
- When the Workspace already has
|
|
240
|
-
|
|
241
|
-
This refusal has no `details.budget
|
|
239
|
+
- When the Workspace already has so many executions waiting that a new HTTP call could
|
|
240
|
+
not start in time, the call is refused at once with HTTP 429 and
|
|
241
|
+
`code: "RATE_LIMITED"` before anything runs. This refusal has no `details.budget`; it
|
|
242
|
+
carries a `Retry-After` header (seconds) and `retryAfterMillis` in the body when
|
|
243
|
+
Cogover can estimate when to send the request again. The caller should wait at least
|
|
244
|
+
that long, and send an `Idempotency-Key` with calls that write so that a retry is
|
|
245
|
+
safe.
|
|
242
246
|
|
|
243
247
|
Some APIs also keep their own quota per execution, such as 20 `fetch` calls, 20
|
|
244
248
|
secret reads, 20 `processes.start` calls, or 5 `agents.start` calls. Going over one is
|
|
245
249
|
reported as `RateLimitError` too.
|
|
246
250
|
|
|
251
|
+
## Parallel calls
|
|
252
|
+
|
|
253
|
+
Capability calls that a handler starts together run in parallel, up to a number of
|
|
254
|
+
simultaneous calls set by the platform; further calls wait for a free slot. A handler
|
|
255
|
+
that awaits each call before it starts the next one runs them one after another.
|
|
256
|
+
Independent reads and writes can therefore be grouped with `Promise.all`:
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
import { defineScript } from "@cogover/sdk";
|
|
260
|
+
|
|
261
|
+
export default defineScript(async ({ data, input }) => {
|
|
262
|
+
const { orderId, customerId } = input as { orderId: string; customerId: string };
|
|
263
|
+
const [order, customer] = await Promise.all([
|
|
264
|
+
data.object("order").records.get(orderId, { fields: ["amount", "status"] }),
|
|
265
|
+
data.object("customer").records.get(customerId, { fields: ["credit_limit"] }),
|
|
266
|
+
]);
|
|
267
|
+
return { order, customer };
|
|
268
|
+
});
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
- Every call counts towards the budgets of the execution as usual, whether it runs
|
|
272
|
+
alone or in parallel. Prefer one `records.getMany` or `records.batchInsert` to many
|
|
273
|
+
parallel `get` or `create` calls: it is one capability call instead of many.
|
|
274
|
+
- A call started without `await` still runs to completion before the execution ends,
|
|
275
|
+
within its time limit.
|
|
276
|
+
- The order of parallel calls is not fixed. Push messages and notifications sent
|
|
277
|
+
together can arrive in any order, and a `push.refreshRecords` started in the same
|
|
278
|
+
`Promise.all` as the update it announces can reach users before the update is saved:
|
|
279
|
+
await the write first, then refresh.
|
|
280
|
+
- Two `state.set` calls for the same key without `expectedVersion` leave either value.
|
|
281
|
+
Use `expectedVersion` or a lock when the result matters.
|
|
282
|
+
- Do not give two calls in the same `Promise.all` the same `idempotencyKey`: the second
|
|
283
|
+
one fails with `DUPLICATE_IN_PROGRESS` or `RETRYABLE` instead of returning the first
|
|
284
|
+
result with `duplicate: true`.
|
|
285
|
+
- When one call of a `Promise.all` fails, the others still run; writes that they made
|
|
286
|
+
are not undone.
|
|
287
|
+
- When code runs locally with Cogover Dev CLI, calls run one after another: the
|
|
288
|
+
results are the same, only slower.
|
|
289
|
+
|
|
290
|
+
Separate executions can also run at the same time. Several invocations of the same
|
|
291
|
+
Workspace, for example two requests, or a request together with an after-change record
|
|
292
|
+
trigger or a background job, can run interleaved, up to a limit set by the platform for
|
|
293
|
+
each Workspace. Code that reads a record or a state key, changes it, and writes it back
|
|
294
|
+
must hold a lock from `locks` around that sequence, or write state with `state.set` and
|
|
295
|
+
`expectedVersion` (see [Project state and locks](state-and-locks.md)). A project can
|
|
296
|
+
also be limited to fewer simultaneous invocations, down to one at a time, with its
|
|
297
|
+
`maxConcurrentRuns` setting. Cogover Dev CLI runs local executions one after another.
|
|
298
|
+
|
|
247
299
|
## Reading limits in code
|
|
248
300
|
|
|
249
301
|
```typescript
|
|
@@ -259,6 +259,50 @@ The same handler may be registered at more than one path.
|
|
|
259
259
|
Method-specific shorthand for `addRoute()`, with identical validation, return value,
|
|
260
260
|
and errors.
|
|
261
261
|
|
|
262
|
+
### `router.route(prefix: string, router: ScriptRouter<TSchema>): ScriptRouter<TSchema>`
|
|
263
|
+
|
|
264
|
+
Mounts every route of another router under `prefix` and returns this router for
|
|
265
|
+
chaining. Use it to keep a group of related routes in its own file:
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
// src/orders-router.ts
|
|
269
|
+
import { createRouter } from "@cogover/sdk";
|
|
270
|
+
|
|
271
|
+
export const ordersRouter = createRouter();
|
|
272
|
+
ordersRouter.get("/", () => ({ orders: [] }));
|
|
273
|
+
ordersRouter.get("/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
274
|
+
|
|
275
|
+
// src/main.ts
|
|
276
|
+
import { createRouter } from "@cogover/sdk";
|
|
277
|
+
import { ordersRouter } from "./orders-router.js";
|
|
278
|
+
|
|
279
|
+
const router = createRouter();
|
|
280
|
+
router.get("/health", () => ({ ok: true }));
|
|
281
|
+
router.route("/orders", ordersRouter); // GET /orders, GET /orders/:orderId
|
|
282
|
+
export default router.toHandler();
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
`prefix` follows the same rules as a route path and may contain parameters, such as
|
|
286
|
+
`/customers/:customerId`; their values appear in `request.params` together with the
|
|
287
|
+
route's own parameters. `"/"` mounts the routes unchanged. A route `/` of the mounted
|
|
288
|
+
router answers at `prefix` itself. The mounted router must come from `createRouter()`
|
|
289
|
+
and cannot be the router itself; one router accepts at most 64 mounts. These errors
|
|
290
|
+
throw `ValidationError` immediately.
|
|
291
|
+
|
|
292
|
+
Mounted routes are read when `toHandler()` is called, so routes added to the mounted
|
|
293
|
+
router after `route()` are included. Routers can be mounted inside mounted routers, up
|
|
294
|
+
to 8 levels, and the same router can be mounted under several prefixes. When
|
|
295
|
+
`toHandler()` builds the table, a cycle of mounts, deeper nesting, a full path that
|
|
296
|
+
breaks the path rules (for example a parameter name repeated in the prefix and the
|
|
297
|
+
route), a duplicate or structurally ambiguous route across routers, or more than 2,048
|
|
298
|
+
routes in total throw `ValidationError`. The limit of 256 routes registered on one
|
|
299
|
+
router still applies.
|
|
300
|
+
|
|
301
|
+
Routes are matched exactly as if they had been registered on one router in
|
|
302
|
+
registration order, a mount inserting its routes where `route()` was called: static
|
|
303
|
+
routes that equal the path win, otherwise the first matching route handles the
|
|
304
|
+
request. Mounting is optional; a router without mounts behaves as before.
|
|
305
|
+
|
|
262
306
|
### `router.toHandler(): SandboxHandler`
|
|
263
307
|
|
|
264
308
|
Returns a default-exportable handler that captures a snapshot of the current routes.
|
|
@@ -90,8 +90,16 @@ large data.
|
|
|
90
90
|
## Distributed locks
|
|
91
91
|
|
|
92
92
|
Locks are distributed leases scoped by workspace, project, namespace, and key. They
|
|
93
|
-
prevent concurrent executions from entering the same protected section.
|
|
94
|
-
|
|
93
|
+
prevent concurrent executions from entering the same protected section.
|
|
94
|
+
|
|
95
|
+
Several executions of the same Workspace can run at the same time: two requests, or a
|
|
96
|
+
request together with an after-change record trigger or a background job, can
|
|
97
|
+
interleave. When code reads a record or a state key, changes it, and writes it back,
|
|
98
|
+
hold a lock on that record or key for the whole sequence, or use `expectedVersion` on
|
|
99
|
+
`state.set`; otherwise one execution can overwrite the change of another. Clients that
|
|
100
|
+
resend a write should also send an `Idempotency-Key`.
|
|
101
|
+
|
|
102
|
+
Prefer `withLock` for automatic release:
|
|
95
103
|
|
|
96
104
|
```typescript
|
|
97
105
|
interface LockOptions {
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -422,6 +422,44 @@ and the JWT algorithm names.
|
|
|
422
422
|
call whatever the number of records.
|
|
423
423
|
- Do not automatically retry writes after a timeout because the commit outcome may
|
|
424
424
|
be unknown.
|
|
425
|
+
- When a Workspace has too many executions waiting, a new HTTP call is refused at once
|
|
426
|
+
with HTTP 429, `code: "RATE_LIMITED"`, and a `Retry-After` header. Callers should wait
|
|
427
|
+
that long before sending the request again, with an `Idempotency-Key` for writes.
|
|
428
|
+
|
|
429
|
+
## Run independent calls together
|
|
430
|
+
|
|
431
|
+
Calls started together, for example with `Promise.all`, run in parallel, while a call
|
|
432
|
+
that is awaited before the next one starts runs alone. Group the reads that do not
|
|
433
|
+
depend on each other, write many records of one Object with one `records.batchInsert`
|
|
434
|
+
or `records.batchUpdate`, and then send the independent writes together:
|
|
435
|
+
|
|
436
|
+
```typescript
|
|
437
|
+
router.post("/orders/:orderId/confirm", async ({ data, request }) => {
|
|
438
|
+
const orderId = request.params.orderId ?? "";
|
|
439
|
+
const orders = data.object("order");
|
|
440
|
+
const lines = data.object("order_line");
|
|
441
|
+
const [order, products] = await Promise.all([
|
|
442
|
+
orders.records.get(orderId, { fields: ["customer", "status"] }),
|
|
443
|
+
data.object("product").records.list({ fields: ["price"], limit: 50 }),
|
|
444
|
+
]);
|
|
445
|
+
if (order === null) return { confirmed: false };
|
|
446
|
+
const [, inserted] = await Promise.all([
|
|
447
|
+
orders.records.update(order.id, { status: "confirmed" }),
|
|
448
|
+
lines.records.batchInsert(products.items.map(product => ({
|
|
449
|
+
order: order.id,
|
|
450
|
+
product: product.id,
|
|
451
|
+
price: product.fields.price,
|
|
452
|
+
}))),
|
|
453
|
+
]);
|
|
454
|
+
return { confirmed: inserted.success };
|
|
455
|
+
});
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Each call still counts towards the budgets. Parallel calls have no fixed order: await a
|
|
459
|
+
write before a `push.refreshRecords` that announces it, and do not give two calls of the
|
|
460
|
+
same `Promise.all` the same `idempotencyKey`. Cogover Dev CLI runs the calls one after
|
|
461
|
+
another locally, with the same results. See
|
|
462
|
+
[Parallel calls](api-reference/overview.md#parallel-calls).
|
|
425
463
|
|
|
426
464
|
## Store small progress with state
|
|
427
465
|
|
|
@@ -1218,6 +1256,134 @@ path registered only for other methods, return 404; methods other than these fiv
|
|
|
1218
1256
|
return 405. Existing `defineScript()` projects continue at `/`.
|
|
1219
1257
|
Validate all business input. See the [router API reference](api-reference/scripts-and-routes.md#http-routers-and-request-context).
|
|
1220
1258
|
|
|
1259
|
+
### Organize routes in groups
|
|
1260
|
+
|
|
1261
|
+
As a module grows, you can keep each group of related routes in its own file: create
|
|
1262
|
+
a router with `createRouter()` in that file, export it, and mount it on the main
|
|
1263
|
+
router with `router.route(prefix, childRouter)`. This is optional; routes registered
|
|
1264
|
+
directly on the main router keep working.
|
|
1265
|
+
|
|
1266
|
+
```typescript
|
|
1267
|
+
// src/orders-router.ts
|
|
1268
|
+
import { createRouter } from "@cogover/sdk";
|
|
1269
|
+
|
|
1270
|
+
export const ordersRouter = createRouter();
|
|
1271
|
+
ordersRouter.get("/", () => ({ orders: [] }));
|
|
1272
|
+
ordersRouter.get("/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
1273
|
+
|
|
1274
|
+
// src/main.ts
|
|
1275
|
+
import { createRouter } from "@cogover/sdk";
|
|
1276
|
+
import { ordersRouter } from "./orders-router.js";
|
|
1277
|
+
|
|
1278
|
+
const router = createRouter();
|
|
1279
|
+
router.get("/health", () => ({ ok: true }));
|
|
1280
|
+
router.route("/orders", ordersRouter);
|
|
1281
|
+
export default router.toHandler();
|
|
1282
|
+
```
|
|
1283
|
+
|
|
1284
|
+
Mounted routes are matched as if they were registered on the main router where
|
|
1285
|
+
`route()` is called. Two groups may share a prefix, such as `/me`, as long as their
|
|
1286
|
+
routes do not overlap. See [`router.route()`](api-reference/scripts-and-routes.md#routerrouteprefix-string-router-scriptroutertschema-scriptroutertschema).
|
|
1287
|
+
|
|
1288
|
+
### Keep the module fast to load
|
|
1289
|
+
|
|
1290
|
+
Every invocation loads the module code it runs. When a module is published,
|
|
1291
|
+
Cogover can load only the code one trigger, job, action, or group of routes
|
|
1292
|
+
needs instead of the whole module, which makes the first invocation after a
|
|
1293
|
+
publish or an idle period much faster. The `cogover-dev publish` load profile
|
|
1294
|
+
shows what each entry point gets. To benefit from it:
|
|
1295
|
+
|
|
1296
|
+
- Define each trigger, job, or action (`defineTrigger`, `defineJob`,
|
|
1297
|
+
`defineAction`) in a file other than `src/main.ts` and export it from there,
|
|
1298
|
+
directly or in an exported array. `src/main.ts` only imports and collects.
|
|
1299
|
+
- Put each group of routes in a router file that contains only
|
|
1300
|
+
`createRouter()` and its route registrations, import that file only from
|
|
1301
|
+
`src/main.ts`, and mount it with `router.route()`. Keep handlers and shared
|
|
1302
|
+
logic in other files, so that a job or another route importing a handler
|
|
1303
|
+
does not also load the whole group. Routes registered directly on the main
|
|
1304
|
+
router always load the whole module.
|
|
1305
|
+
- Code that runs while a file loads may compute values and build objects of
|
|
1306
|
+
its own: calling your own functions and static methods (also from other
|
|
1307
|
+
files) whose code follows these rules too, `.map()`, `.filter()`, loops,
|
|
1308
|
+
`if`, `try`, `throw`, an immediately called function, `new Intl.Collator()`,
|
|
1309
|
+
registering routes on a router the file created, filling an array, an
|
|
1310
|
+
object, or a `Map` the same file created (also from the file's own
|
|
1311
|
+
functions). It must not change anything outside: a variable or an object of
|
|
1312
|
+
another file (an imported registry, a configuration object, a list a
|
|
1313
|
+
function returns), a global or a prototype, a parameter of a function, a
|
|
1314
|
+
variable of another file from one of that file's functions.
|
|
1315
|
+
- It must also give the same result each time it loads: no `Date.now()`,
|
|
1316
|
+
`new Date()` without arguments, `Intl.DateTimeFormat#format()` without a
|
|
1317
|
+
date, `Math.random()`, `performance`, `globalThis`, globals the runtime
|
|
1318
|
+
defines, or SDK services such as `fetch`, `crypto`, or `limits` while files
|
|
1319
|
+
load.
|
|
1320
|
+
- A call of a method of one of your objects or classes (`Config.select()`,
|
|
1321
|
+
`registry.get()`) counts only when nothing in the project hands that object
|
|
1322
|
+
or class around or changes it, anywhere, including in handlers: passing it to
|
|
1323
|
+
a function, assigning it to another variable, spreading it, storing it in
|
|
1324
|
+
another object or array, returning it, writing one of its members
|
|
1325
|
+
(`registry.get = ...`), creating instances of a class (`new Config()`) or
|
|
1326
|
+
reading its `prototype`. Otherwise Cogover cannot know which code the method
|
|
1327
|
+
runs, and the call counts as changing something outside. The same applies to
|
|
1328
|
+
converting such an object to a string or JSON.
|
|
1329
|
+
- What Cogover cannot check at publish time counts as changing something
|
|
1330
|
+
outside: calling a parameter, a function assigned more than once, a method
|
|
1331
|
+
of a value it cannot trace back to your code or to a built-in type (on such
|
|
1332
|
+
a value only common read-only methods such as `map`, `filter`, `includes`,
|
|
1333
|
+
`join`, `slice`, `split`, `trim`, or `toString` are accepted), an `async`
|
|
1334
|
+
function or a generator, `console.log()`; `Object.defineProperty()`,
|
|
1335
|
+
`Object.setPrototypeOf()`, `Object.create(prototype)`, `new Object(value)`,
|
|
1336
|
+
a built-in called with spread arguments (`Math.max(...values)` is fine),
|
|
1337
|
+
methods or conversions of data imported from a JSON file, and getters,
|
|
1338
|
+
setters, or `toString`/`toJSON`/`Symbol` methods that change something
|
|
1339
|
+
outside, in objects or classes created while loading.
|
|
1340
|
+
- A file that breaks these rules is loaded, with what it imports, with every
|
|
1341
|
+
entry point; the load profile lists it under `REQUIRED_MODULES` with the
|
|
1342
|
+
statement and the chain of calls that leads to it. Move such code into
|
|
1343
|
+
handlers, or into a file that only the entry points needing it import.
|
|
1344
|
+
- When `src/main.ts` breaks these rules, every entry point loads the whole
|
|
1345
|
+
module (`MAIN_TOP_LEVEL_EFFECT`). Do configuration in a file the entry points
|
|
1346
|
+
import.
|
|
1347
|
+
- When code anywhere in the project writes globals or built-in objects (a
|
|
1348
|
+
polyfill such as `URL` or `TextEncoder`, a patched prototype, a value put on
|
|
1349
|
+
`globalThis`), or the whole module changes them while it loads, every entry
|
|
1350
|
+
point loads the whole module (`PART_GLOBALS_MODIFIED`).
|
|
1351
|
+
|
|
1352
|
+
Entry points run from their smaller modules only when you declare that the
|
|
1353
|
+
project follows these rules: set `"entryPointParts": true` in `cogover.json`
|
|
1354
|
+
(or publish with `cogover-dev publish --parts`). Without it the platform
|
|
1355
|
+
default applies, which is the whole module unless the platform says otherwise;
|
|
1356
|
+
`false` (or `--no-parts`) always keeps the whole module. The load profile
|
|
1357
|
+
printed by `cogover-dev publish` says what the version runs on.
|
|
1358
|
+
|
|
1359
|
+
Declaring `true` means you confirm that code running while files load changes
|
|
1360
|
+
nothing outside its file, and you answer for any difference if it does: an
|
|
1361
|
+
entry point may then run without a configuration another file sets while
|
|
1362
|
+
loading, including an authorization check your project writes itself. Cogover
|
|
1363
|
+
reads the code to check what it can: a file found to break the rules is loaded
|
|
1364
|
+
with every entry point, and the cases above load the whole module. It does not
|
|
1365
|
+
guarantee to catch every violation. Known limits:
|
|
1366
|
+
|
|
1367
|
+
- the `.name` of a class or function (also `constructor.name`, `error.name`)
|
|
1368
|
+
can differ between the whole module and a smaller one when two files define
|
|
1369
|
+
a top-level class or function of the same name: do not rely on it, set
|
|
1370
|
+
`name` explicitly where it matters;
|
|
1371
|
+
- a value Cogover cannot trace (a function parameter, the result of a call)
|
|
1372
|
+
whose method has the name of an accepted read-only built-in method (`map`,
|
|
1373
|
+
`filter`, `includes`, `join`...), or whose getter, setter, `Proxy`, iterator,
|
|
1374
|
+
`toString`, `valueOf`, `toJSON`, or `Symbol` method runs when loading code
|
|
1375
|
+
reads or converts it, is not checked;
|
|
1376
|
+
- a built-in object changed through another name
|
|
1377
|
+
(`const p = Array.prototype; p.x = ...`) and restored while loading is not
|
|
1378
|
+
seen;
|
|
1379
|
+
- code that depends on the date or time while loading behaves as it did on the
|
|
1380
|
+
day of publishing.
|
|
1381
|
+
|
|
1382
|
+
Keep such code inside handlers. Check the `REQUIRED_MODULES` list of the load
|
|
1383
|
+
profile: if a file there changes an object of another file, or a call Cogover
|
|
1384
|
+
cannot resolve, and you are not sure it is harmless, do not declare `true`.
|
|
1385
|
+
When in doubt, do not declare it.
|
|
1386
|
+
|
|
1221
1387
|
## Receive webhooks
|
|
1222
1388
|
|
|
1223
1389
|
An external system can call a route without a Cogover user session through an
|