@cogover/sdk 0.11.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.
- package/README.md +65 -21
- package/dist/crypto.js +89 -46
- package/dist/data.js +4 -1
- package/dist/email.d.ts +77 -0
- package/dist/email.js +192 -0
- package/dist/index.d.ts +2 -0
- package/dist/internal/base64.js +76 -27
- package/dist/internal/bridge.js +41 -3
- package/dist/internal/job-config.js +7 -1
- package/dist/internal/job-runtime.js +4 -0
- package/dist/internal/messaging.js +75 -0
- package/dist/internal/trigger-runtime.js +5 -0
- package/dist/internal/utf8.js +18 -17
- package/dist/jobs.d.ts +4 -0
- package/dist/locks.js +13 -3
- package/dist/logger.js +47 -1
- package/dist/notifications.d.ts +56 -0
- package/dist/notifications.js +92 -0
- package/dist/org.js +14 -14
- package/dist/records.d.ts +13 -0
- package/dist/response.js +21 -1
- package/dist/router.js +2 -0
- package/dist/schema.d.ts +1 -0
- package/dist/script.d.ts +4 -0
- package/dist/script.js +11 -3
- package/dist/trigger.d.ts +6 -0
- package/docs/en/api-reference/background-jobs.md +288 -0
- package/docs/en/api-reference/cryptography.md +317 -0
- package/docs/en/api-reference/fetch-and-secrets.md +184 -0
- package/docs/en/api-reference/inbound-webhooks.md +65 -0
- package/docs/en/api-reference/notifications-and-email.md +317 -0
- package/docs/en/api-reference/organization-structure.md +304 -0
- package/docs/en/api-reference/overview.md +198 -0
- package/docs/en/api-reference/push-messages.md +115 -0
- package/docs/en/api-reference/record-triggers.md +469 -0
- package/docs/en/api-reference/records.md +447 -0
- package/docs/en/api-reference/scripts-and-routes.md +354 -0
- package/docs/en/api-reference/state-and-locks.md +162 -0
- package/docs/en/usage-guide.md +218 -19
- package/package.json +1 -1
- package/docs/en/api-reference.md +0 -2619
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Scripts and HTTP routes
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## `defineScript`
|
|
6
|
+
|
|
7
|
+
`defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
|
|
8
|
+
the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
|
|
9
|
+
`push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
|
|
10
|
+
result.
|
|
11
|
+
|
|
12
|
+
```typescript
|
|
13
|
+
function defineScript<
|
|
14
|
+
Input = unknown,
|
|
15
|
+
Output = unknown,
|
|
16
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
17
|
+
>(handler: ScriptHandler<Input, Output, Schema>): SandboxHandler;
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The related public types are:
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
type SandboxHandler = (inputJson: string) => Promise<string | null>;
|
|
24
|
+
|
|
25
|
+
type ScriptHandler<Input, Output, Schema extends object = EffectiveWorkspaceObjects> =
|
|
26
|
+
(context: ScriptContext<Input, Schema>) =>
|
|
27
|
+
Output | ScriptResponse<unknown> | null |
|
|
28
|
+
Promise<Output | ScriptResponse<unknown> | null>;
|
|
29
|
+
|
|
30
|
+
interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects> {
|
|
31
|
+
readonly input: Input;
|
|
32
|
+
readonly request: ScriptRequest<Input>;
|
|
33
|
+
readonly invocation: InvocationContext;
|
|
34
|
+
readonly data: DataApi<Schema>;
|
|
35
|
+
readonly schema: SchemaApi<Schema>;
|
|
36
|
+
readonly log: ScriptLogger;
|
|
37
|
+
readonly response: ResponseApi;
|
|
38
|
+
readonly state: ProjectState;
|
|
39
|
+
readonly locks: DistributedLocks;
|
|
40
|
+
readonly push: PushApi<Schema>;
|
|
41
|
+
readonly notifications: NotificationsApi;
|
|
42
|
+
readonly email: EmailApi<Schema>;
|
|
43
|
+
readonly jobs: JobsApi;
|
|
44
|
+
readonly secrets: SecretsApi;
|
|
45
|
+
readonly crypto: CryptoApi;
|
|
46
|
+
readonly org: OrgApi;
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`defineScript` rejects a non-function handler with `ValidationError`. The returned
|
|
51
|
+
handler rejects invalid input JSON and values that cannot be serialized to JSON.
|
|
52
|
+
Returning `null` produces a null handler result; returning `undefined` is invalid.
|
|
53
|
+
|
|
54
|
+
## HTTP routers and request context
|
|
55
|
+
|
|
56
|
+
`ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
|
|
57
|
+
`log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
|
|
58
|
+
and route handlers. `input`
|
|
59
|
+
preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
|
|
60
|
+
metadata and transport/authentication fields removed by Cogover.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
64
|
+
type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
|
|
65
|
+
type ScriptHeaders = Readonly<Record<string, string>>;
|
|
66
|
+
type ScriptPathParams = Readonly<Record<string, string>>;
|
|
67
|
+
|
|
68
|
+
interface ScriptRequest<TBody = unknown> {
|
|
69
|
+
readonly method: RequestMethod;
|
|
70
|
+
readonly path: string; // Relative to /api/v1/ts-projects/{projectSlug}
|
|
71
|
+
readonly params: ScriptPathParams;
|
|
72
|
+
readonly query: ScriptQuery;
|
|
73
|
+
readonly headers: ScriptHeaders;
|
|
74
|
+
readonly body: TBody;
|
|
75
|
+
readonly rawBody?: string; // Webhook calls only
|
|
76
|
+
readonly contentType?: string; // Webhook calls only
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The descriptor and metadata maps are frozen; its body is not deeply frozen. Method,
|
|
81
|
+
path, query, and allowlisted headers come from Cogover, not from business fields.
|
|
82
|
+
Repeated query names become readonly arrays. Header names are lower-case and
|
|
83
|
+
credentials such as `authorization` and `cookie` are never exposed. Dynamic path
|
|
84
|
+
parameters are percent-decoded after safe route matching. TypeScript types do not
|
|
85
|
+
validate runtime business input.
|
|
86
|
+
|
|
87
|
+
`rawBody` and `contentType` are present only for a call that reached the project
|
|
88
|
+
through an inbound webhook (see [Inbound webhooks](inbound-webhooks.md#inbound-webhooks)): `rawBody`
|
|
89
|
+
is the request body exactly as received, as a UTF-8 string, and `contentType` is
|
|
90
|
+
the request's `Content-Type` header. For every other call both fields are absent.
|
|
91
|
+
|
|
92
|
+
## Invocation identity and workspace
|
|
93
|
+
|
|
94
|
+
`context.invocation` is a synchronous, immutable snapshot built from metadata that
|
|
95
|
+
Cogover already authenticated and loaded for the current execution. Reading it
|
|
96
|
+
does not make a data API request.
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
|
|
100
|
+
|
|
101
|
+
interface CurrentWorkspace {
|
|
102
|
+
readonly id: string;
|
|
103
|
+
readonly name?: string;
|
|
104
|
+
readonly domain?: string;
|
|
105
|
+
readonly language?: string;
|
|
106
|
+
readonly timezone?: string;
|
|
107
|
+
readonly dateFormat?: string;
|
|
108
|
+
readonly timeFormat?: string;
|
|
109
|
+
readonly numberFormat?: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface CurrentWorkspaceRole {
|
|
113
|
+
readonly id: string;
|
|
114
|
+
readonly name: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface CurrentWorkspaceMembership {
|
|
118
|
+
readonly personnelId?: string;
|
|
119
|
+
readonly language?: string;
|
|
120
|
+
readonly timezone?: string;
|
|
121
|
+
readonly isSuperAdmin: boolean; // Holds the workspace's Super Admin role
|
|
122
|
+
readonly roles: readonly CurrentWorkspaceRole[]; // Sorted by name
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface CurrentUser {
|
|
126
|
+
readonly accountId: string;
|
|
127
|
+
readonly email?: string;
|
|
128
|
+
readonly firstName?: string;
|
|
129
|
+
readonly lastName?: string;
|
|
130
|
+
readonly avatar?: string;
|
|
131
|
+
readonly language?: string;
|
|
132
|
+
readonly timezone?: string;
|
|
133
|
+
readonly membership: CurrentWorkspaceMembership;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
interface UserInvocationContext {
|
|
137
|
+
readonly identity: "user";
|
|
138
|
+
readonly workspace: CurrentWorkspace;
|
|
139
|
+
readonly user: CurrentUser;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface SystemInvocationContext {
|
|
143
|
+
readonly identity: "system";
|
|
144
|
+
readonly workspace: CurrentWorkspace;
|
|
145
|
+
readonly user: null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
interface InboundInvocationContext {
|
|
149
|
+
readonly identity: "inbound";
|
|
150
|
+
readonly workspace: CurrentWorkspace;
|
|
151
|
+
readonly user: null;
|
|
152
|
+
readonly inbound: {
|
|
153
|
+
readonly id: string; // Part of the webhook URL
|
|
154
|
+
readonly name: string;
|
|
155
|
+
readonly mode: "KEY" | "HMAC"; // How the call was authenticated
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
All fields are readonly. Optional profile and workspace fields may be absent, so
|
|
161
|
+
scripts must not assume that they contain a value.
|
|
162
|
+
|
|
163
|
+
`identity` is `"user"` for a call made by an authenticated Workspace user,
|
|
164
|
+
`"system"` for an execution without a user, such as a scheduled job, and
|
|
165
|
+
`"inbound"` for a webhook call authenticated by one of the project's inbound
|
|
166
|
+
accesses (see [Inbound webhooks](inbound-webhooks.md#inbound-webhooks)). An inbound invocation has no
|
|
167
|
+
user; `inbound` identifies the inbound access that authenticated the call.
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
export default defineScript(({ invocation }) => {
|
|
171
|
+
if (invocation.identity === "system") {
|
|
172
|
+
return {workspaceId: invocation.workspace.id, user: null};
|
|
173
|
+
}
|
|
174
|
+
if (invocation.identity === "inbound") {
|
|
175
|
+
return {workspaceId: invocation.workspace.id, inbound: invocation.inbound.name};
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
workspaceId: invocation.workspace.id,
|
|
179
|
+
accountId: invocation.user.accountId,
|
|
180
|
+
personnelId: invocation.user.membership.personnelId,
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Cogover ignores caller-supplied invocation metadata and creates this snapshot from
|
|
186
|
+
the authenticated request context. Raw authentication data, tokens, inbound keys,
|
|
187
|
+
and credentials are not included. A handler called outside Cogover has no
|
|
188
|
+
authenticated invocation snapshot.
|
|
189
|
+
|
|
190
|
+
### Workspace roles of the current user
|
|
191
|
+
|
|
192
|
+
`user.membership` describes the caller's membership in the current workspace:
|
|
193
|
+
|
|
194
|
+
- `isSuperAdmin` is `true` when one of the user's roles is the workspace's
|
|
195
|
+
highest administrator (Super Admin) role, otherwise `false`.
|
|
196
|
+
- `roles` lists the roles assigned to the user in the current workspace, sorted
|
|
197
|
+
by name. Each `CurrentWorkspaceRole` has only an `id` and a `name`; the list is
|
|
198
|
+
empty when the user has no role. Role permissions are not exposed.
|
|
199
|
+
|
|
200
|
+
Compare roles by `id`: a role can be renamed, and the same role name has a
|
|
201
|
+
different `id` in each workspace. Record and field access is still enforced by
|
|
202
|
+
Cogover under the user's identity, so use these fields for business rules, such
|
|
203
|
+
as who may approve an order, not as a replacement for security rules.
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
|
|
207
|
+
|
|
208
|
+
export default defineScript(({ invocation }) => {
|
|
209
|
+
const user = invocation.user;
|
|
210
|
+
const canApprove = user !== null && (user.membership.isSuperAdmin
|
|
211
|
+
|| user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
|
|
212
|
+
return {canApprove};
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
HTTP invocations reflect the user's roles at the time of the request. Record
|
|
217
|
+
triggers and background jobs may see a role change up to about one minute late.
|
|
218
|
+
In local development with the Cogover Dev CLI, the values are captured when the
|
|
219
|
+
development session starts; restart `cogover-dev` to pick up role changes. A
|
|
220
|
+
`system` or `inbound` invocation has `user: null` and therefore no membership.
|
|
221
|
+
|
|
222
|
+
### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
|
|
223
|
+
|
|
224
|
+
Creates an independent router. `TSchema extends object` defaults to the effective
|
|
225
|
+
workspace schema, preserving `WorkspaceObjects` augmentation for data and schema
|
|
226
|
+
APIs. Routes match a method and case-sensitive static or dynamic path; static routes
|
|
227
|
+
take precedence over dynamic routes. When several dynamic routes of the same method
|
|
228
|
+
match a path, such as `/orders/:id` and `/:collection/new` for `/orders/new`, the one
|
|
229
|
+
registered first handles it. `/` addresses
|
|
230
|
+
the canonical project URL without a route suffix.
|
|
231
|
+
`/index` is a separate route, registered explicitly. `defineScript()` remains valid
|
|
232
|
+
for `/`; requesting a child path on it throws `NotFoundError` before its handler runs.
|
|
233
|
+
|
|
234
|
+
### `router.addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>`
|
|
235
|
+
|
|
236
|
+
Registers a handler and returns the same router for chaining. Supported methods are
|
|
237
|
+
`GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. A path is `/` or static/dynamic
|
|
238
|
+
components such as `/orders/:orderId`. Static components start with an ASCII letter
|
|
239
|
+
or digit, may contain letters, digits, `_`, or `-`, and are at most 100 characters.
|
|
240
|
+
Parameter names start with an ASCII letter, may contain letters, digits, or `_`, are
|
|
241
|
+
at most 64 characters, and must be unique in a route. The complete path is at most
|
|
242
|
+
1,024 characters.
|
|
243
|
+
Child trailing slashes, empty segments, `.`, `..`, percent escapes in the template,
|
|
244
|
+
`?`, `#`, and wildcards are rejected. Duplicate or structurally ambiguous routes for
|
|
245
|
+
one method, invalid handlers, or more than 256 routes throw `ValidationError`.
|
|
246
|
+
|
|
247
|
+
Handlers are ordinary `ScriptHandler` functions, not functions already wrapped in
|
|
248
|
+
`defineScript()`. They receive the same data/schema/log APIs, input and request context.
|
|
249
|
+
The same handler may be registered at more than one path.
|
|
250
|
+
|
|
251
|
+
### `router.get/post/put/patch/delete(path, handler): ScriptRouter<TSchema>`
|
|
252
|
+
|
|
253
|
+
Method-specific shorthand for `addRoute()`, with identical validation, return value,
|
|
254
|
+
and errors.
|
|
255
|
+
|
|
256
|
+
### `router.toHandler(): SandboxHandler`
|
|
257
|
+
|
|
258
|
+
Returns a default-exportable handler that captures a snapshot of the current routes.
|
|
259
|
+
Later registrations do not affect an existing handler. It parses input, dispatches
|
|
260
|
+
exactly one route, awaits it, and serializes the result just like `defineScript()`.
|
|
261
|
+
`null` remains null; an undefined result throws `ValidationError`. Missing routes
|
|
262
|
+
throw `NotFoundError` (HTTP 404), including a path that is registered only for other
|
|
263
|
+
methods: the router does not answer 405 for a method mismatch. Unsupported invocation methods use
|
|
264
|
+
`CogoverApiError` with `code: "METHOD_NOT_ALLOWED"` (HTTP 405). Invalid invocation
|
|
265
|
+
metadata throws `ValidationError`.
|
|
266
|
+
When invoked directly without Cogover request metadata, handlers default to POST `/`.
|
|
267
|
+
|
|
268
|
+
Routes inherit project authentication, permissions and runtime limits. Registering a
|
|
269
|
+
route grants no additional permission or separate security boundary. Idempotency
|
|
270
|
+
replay is scoped to method/path as well as project version and caller; use a new key
|
|
271
|
+
for each distinct business operation.
|
|
272
|
+
|
|
273
|
+
## HTTP response API
|
|
274
|
+
|
|
275
|
+
Returning a plain JSON-serializable value keeps the compatible `200
|
|
276
|
+
application/json` behavior. Use the context's `response` helpers to control status,
|
|
277
|
+
headers, content type, or body representation. Only a response made by these helpers
|
|
278
|
+
can do so: a returned value is always sent as JSON data with HTTP 200, even when it has
|
|
279
|
+
the shape of Cogover's internal response envelope, for example a request body that a
|
|
280
|
+
route returns unchanged.
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
router.post("/orders", ({ response }) => response.json({ id: "ORD-1" }, {
|
|
284
|
+
status: 201,
|
|
285
|
+
headers: { location: "/orders/ORD-1", "x-request-state": "created" },
|
|
286
|
+
}));
|
|
287
|
+
|
|
288
|
+
router.get("/files/:fileId", ({ response }) =>
|
|
289
|
+
response.bytes(new Uint8Array([0, 1, 255]), { contentType: "application/octet-stream" }));
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
type ResponseHeaderValue = string | readonly string[];
|
|
294
|
+
|
|
295
|
+
interface ResponseInit {
|
|
296
|
+
readonly status?: number;
|
|
297
|
+
readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
interface BinaryResponseInit extends ResponseInit {
|
|
301
|
+
readonly contentType?: string;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
interface ResponseApi {
|
|
305
|
+
json<T>(body: T, init?: ResponseInit): ScriptResponse<T>;
|
|
306
|
+
text(body: string, init?: ResponseInit): ScriptResponse<string>;
|
|
307
|
+
bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
|
|
308
|
+
empty(init?: ResponseInit): ScriptResponse<null>;
|
|
309
|
+
redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
response.json(body, init?)
|
|
313
|
+
response.text(body, init?)
|
|
314
|
+
response.bytes(body: Uint8Array, { status?, headers?, contentType? }?)
|
|
315
|
+
response.empty(init?) // status defaults to 204
|
|
316
|
+
response.redirect(location, status?) // status defaults to 302
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Status must be an integer from 200 through 599. Header values may be one string or
|
|
320
|
+
a readonly string array. Hop-by-hop, credential-setting, and reserved Cogover headers
|
|
321
|
+
are rejected. Header names and values cannot contain newlines;
|
|
322
|
+
at most 50 headers are accepted. A header name is at most 128 characters and each
|
|
323
|
+
value at most 8,192 characters. Default content types are
|
|
324
|
+
`application/json; charset=utf-8`, `text/plain; charset=utf-8`, and
|
|
325
|
+
`application/octet-stream`. Redirect status is restricted to 301, 302, 303, 307, or
|
|
326
|
+
308; any other value throws `ValidationError`. Helpers return an opaque `ScriptResponse`; application code must not construct
|
|
327
|
+
the transport envelope directly. A redirect location must be non-empty, at most
|
|
328
|
+
4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
|
|
329
|
+
`response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
|
|
330
|
+
|
|
331
|
+
## Logging
|
|
332
|
+
|
|
333
|
+
`context.log` implements `ScriptLogger`:
|
|
334
|
+
|
|
335
|
+
```typescript
|
|
336
|
+
interface ScriptLogger {
|
|
337
|
+
debug(message: string, details?: unknown): void;
|
|
338
|
+
info(message: string, details?: unknown): void;
|
|
339
|
+
warn(message: string, details?: unknown): void;
|
|
340
|
+
error(message: string, details?: unknown): void;
|
|
341
|
+
}
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Each call writes one line to the execution's standard output, for every level:
|
|
345
|
+
`[LEVEL] message`, followed by a space and `details` as JSON when `details` is given,
|
|
346
|
+
for example `[WARN] Stock is low {"sku":"A-1","left":2}`. A string detail is written
|
|
347
|
+
quoted. The JSON text is cut at 8,192 characters and then ends with `…[truncated]`.
|
|
348
|
+
A value that JSON cannot represent is written in a readable form instead of failing:
|
|
349
|
+
a repeated reference to an enclosing object becomes `"[Circular]"`, a `bigint` its
|
|
350
|
+
decimal string, an `Error` `{"name":…,"message":…}` without the stack, a `Map` an
|
|
351
|
+
object, and a `Set` an array. When `details` cannot be serialized at all, for example
|
|
352
|
+
because its `toJSON()` throws, the line ends with `[unserializable]`; a log call never
|
|
353
|
+
throws. Do not include credentials, tokens, personal data, or other secrets in either
|
|
354
|
+
argument.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Project state and locks
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Project state
|
|
6
|
+
|
|
7
|
+
State is durable JSON scoped by workspace, project, namespace, and key. It is not
|
|
8
|
+
version-scoped, so it remains available after a new project version is published.
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
interface StateEntry<T> {
|
|
12
|
+
readonly value: T;
|
|
13
|
+
readonly version: number;
|
|
14
|
+
readonly expiresAt?: number;
|
|
15
|
+
readonly createdAt: number;
|
|
16
|
+
readonly updatedAt: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface StateWriteOptions {
|
|
20
|
+
readonly expectedVersion?: number;
|
|
21
|
+
readonly ttlSeconds?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface StateDeleteOptions {
|
|
25
|
+
readonly expectedVersion?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface StateNamespace {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
get<T>(key: string): Promise<StateEntry<T> | null>;
|
|
31
|
+
set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
|
|
32
|
+
delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface ProjectState {
|
|
36
|
+
namespace(name: string): StateNamespace;
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
const progress = state.namespace("inventory-sync");
|
|
42
|
+
const current = await progress.get<{ cursor: string }>("cursor");
|
|
43
|
+
|
|
44
|
+
const saved = await progress.set("cursor", { cursor: "next-page" }, {
|
|
45
|
+
expectedVersion: current?.version ?? 0,
|
|
46
|
+
ttlSeconds: 3600,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
await progress.delete("cursor", { expectedVersion: saved.version });
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### `state.namespace(name): StateNamespace`
|
|
53
|
+
|
|
54
|
+
Creates an immutable namespace client. Namespaces are at most 128 characters and
|
|
55
|
+
keys at most 255. Both start with an ASCII letter or digit and may contain letters,
|
|
56
|
+
digits, `.`, `_`, `:`, `/`, and `-`.
|
|
57
|
+
|
|
58
|
+
### `namespace.get<T>(key): Promise<StateEntry<T> | null>`
|
|
59
|
+
|
|
60
|
+
Returns `null` when the entry is missing or expired. An entry contains `value`,
|
|
61
|
+
`version`, `createdAt`, `updatedAt`, and optional `expiresAt`; timestamps are Unix
|
|
62
|
+
milliseconds.
|
|
63
|
+
|
|
64
|
+
### `namespace.set<T>(key, value, options?): Promise<StateEntry<T>>`
|
|
65
|
+
|
|
66
|
+
Stores a JSON value of at most 32 KiB: 32,768 UTF-8 bytes of its `JSON.stringify`
|
|
67
|
+
form, in which a quote, a backslash, or a control character counts as its escape
|
|
68
|
+
sequence.
|
|
69
|
+
`ttlSeconds` ranges from one second through 365 days; omit it for no automatic
|
|
70
|
+
expiry. Both option values must be safe integers. `expectedVersion` enables
|
|
71
|
+
compare-and-set: `0` means create only, a positive value must match the current
|
|
72
|
+
version, and omission is an unconditional upsert.
|
|
73
|
+
Conflicts throw `StateConflictError`; the returned entry has the new version.
|
|
74
|
+
|
|
75
|
+
A version counts the writes since the entry was created. After `delete` or expiry, the
|
|
76
|
+
next `set` creates a new entry whose version starts again at 1, so a version seen
|
|
77
|
+
before the deletion can match an unrelated new entry (the ABA problem). When that
|
|
78
|
+
matters, store your own unique token in the value and compare it as well.
|
|
79
|
+
|
|
80
|
+
### `namespace.delete(key, options?): Promise<boolean>`
|
|
81
|
+
|
|
82
|
+
Deletes an entry and returns whether it existed. `expectedVersion` has the same CAS
|
|
83
|
+
meaning as on `set`. Expired entries are treated as absent. State operations do not
|
|
84
|
+
form a transaction with Record API calls. Do not use state for secrets, files, or
|
|
85
|
+
large data.
|
|
86
|
+
|
|
87
|
+
## Distributed locks
|
|
88
|
+
|
|
89
|
+
Locks are distributed leases scoped by workspace, project, namespace, and key. They
|
|
90
|
+
prevent concurrent executions from entering the same protected section. Prefer
|
|
91
|
+
`withLock` for automatic release:
|
|
92
|
+
|
|
93
|
+
```typescript
|
|
94
|
+
interface LockOptions {
|
|
95
|
+
readonly namespace?: string;
|
|
96
|
+
readonly waitMs?: number;
|
|
97
|
+
readonly leaseMs?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface LockLease {
|
|
101
|
+
readonly id: string;
|
|
102
|
+
readonly key: string;
|
|
103
|
+
readonly namespace: string;
|
|
104
|
+
readonly fencingToken: number;
|
|
105
|
+
readonly expiresAt: number;
|
|
106
|
+
renew(leaseMs?: number): Promise<void>;
|
|
107
|
+
release(): Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface DistributedLocks {
|
|
111
|
+
acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
|
|
112
|
+
withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
113
|
+
withLock<T>(key: string, options: LockOptions,
|
|
114
|
+
callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
await locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
|
|
120
|
+
await processInvoice("INV-1", lease.fencingToken);
|
|
121
|
+
// Renew only if work can approach expiresAt.
|
|
122
|
+
// await lease.renew(30_000);
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### `locks.acquire(key, options?): Promise<LockLease | null>`
|
|
127
|
+
|
|
128
|
+
Returns a lease, or `null` when it cannot acquire one within `waitMs`. The namespace
|
|
129
|
+
defaults to `default`; `waitMs` ranges from 0 through 10,000 ms; `leaseMs` ranges
|
|
130
|
+
from 5,000 through 60,000 ms and defaults to 30,000 ms. One invocation may hold at
|
|
131
|
+
most 16 locks; acquiring a 17th throws `ValidationError`. Keys are at most 255
|
|
132
|
+
characters and namespaces at most 128; both use the same character rules as state
|
|
133
|
+
names. Numeric options must be safe integers.
|
|
134
|
+
|
|
135
|
+
Waiting counts toward the execution's wall-clock time. In an HTTP route, which has 8
|
|
136
|
+
seconds in total by default (see [Execution limits](overview.md#execution-limits)), a
|
|
137
|
+
`waitMs` close to or above the time left ends the whole execution with the generic
|
|
138
|
+
HTTP 422 response instead of returning `null`; keep `waitMs` well below the time left.
|
|
139
|
+
|
|
140
|
+
A lease exposes `id`, `key`, `namespace`, `fencingToken`, `expiresAt`,
|
|
141
|
+
`renew(leaseMs?)`, and `release()`. Cogover renews and releases a lease by its `id`
|
|
142
|
+
within the project that acquired it: any execution of the same project that knows the
|
|
143
|
+
`id` can renew or release that lease, and another project cannot. Treat the `id` as
|
|
144
|
+
private and do not return it to callers. A lost or expired lease throws
|
|
145
|
+
`LockLostError`. Repeated `release()` on the same successfully released lease object is
|
|
146
|
+
a no-op.
|
|
147
|
+
|
|
148
|
+
### `locks.withLock(key, callback)` / `locks.withLock(key, options, callback)`
|
|
149
|
+
|
|
150
|
+
Acquires the lock, runs the callback, and then releases the lease. Failure to acquire
|
|
151
|
+
throws `LockUnavailableError`. When the callback throws, the lease is released and the
|
|
152
|
+
callback's error is rethrown; if that release also fails, its error is ignored and the
|
|
153
|
+
lease expires after `leaseMs`. When the callback succeeds but the release fails, for
|
|
154
|
+
example with `LockLostError` because the lease expired while the callback ran, that
|
|
155
|
+
error is thrown instead of the callback's result. It does not auto-renew; long
|
|
156
|
+
callbacks must call `lease.renew()` before `expiresAt`.
|
|
157
|
+
|
|
158
|
+
A lock only guarantees one valid lease at a time. Timeouts, pauses, or network
|
|
159
|
+
failures may let old work continue after its lease expires. When the downstream
|
|
160
|
+
system supports it, store/check `fencingToken` and reject stale tokens. Locks do not
|
|
161
|
+
replace idempotency, provide exactly-once execution, or combine Record API and state
|
|
162
|
+
operations into a transaction.
|