@jskit-ai/agent-docs 0.1.319 → 0.1.321
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/guide/agent/app-setup/authentication.md +9 -4
- package/guide/agent/app-setup/database-layer.md +3 -0
- package/guide/agent/framework/data-access.md +312 -22
- package/guide/agent/framework/typed-features.md +51 -9
- package/package.json +1 -1
- package/patterns/feature-package/example/booking-engine/package.json +1 -1
- package/patterns/minimal-foundation/example/package.json +4 -4
- package/patterns/shell-foundation/example/package.json +5 -5
- package/patterns/shell-foundation/example/packages/main/package.json +1 -1
- package/reference/autogen/KERNEL_MAP.md +4 -2
- package/reference/autogen/PATTERN_INDEX.md +38 -38
- package/reference/autogen/packages/auth-web.md +2 -0
- package/reference/autogen/packages/kernel.md +7 -4
- package/reference/autogen/packages/resource-runtime.md +7 -2
- package/reference/autogen/packages/workspaces-core.md +7 -2
- package/skills/jskit/references/data-access.md +312 -22
- package/skills/jskit/references/database-layer.md +3 -0
- package/skills/jskit/references/heuristics/INDEX.md +3 -3
- package/skills/jskit/references/heuristics/data-access.md +4 -1
- package/skills/jskit/references/heuristics/row-policies.md +6 -1
- package/skills/jskit/references/heuristics/typed-features.md +2 -0
- package/skills/jskit/references/pattern-index.md +38 -38
- package/skills/jskit/references/patterns/app/minimal-foundation/example/package.json +4 -4
- package/skills/jskit/references/patterns/app/shell-foundation/example/package.json +5 -5
- package/skills/jskit/references/patterns/app/shell-foundation/example/packages/main/package.json +1 -1
- package/skills/jskit/references/patterns/auth/accounts-hub/example/package.json +3 -3
- package/skills/jskit/references/patterns/auth/oidc-sign-in/example/package.json +2 -2
- package/skills/jskit/references/patterns/auth/supabase-auth/example/package.json +1 -1
- package/skills/jskit/references/patterns/connectors/calendar-cli/example/package.json +4 -4
- package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/package.json +3 -3
- package/skills/jskit/references/patterns/database/mysql-application/example/package.json +2 -2
- package/skills/jskit/references/patterns/database/postgres-application/example/package.json +2 -2
- package/skills/jskit/references/patterns/realtime/realtime-application/example/package.json +2 -2
- package/skills/jskit/references/patterns/server/feature-package/example/booking-engine/package.json +1 -1
- package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/package.json +3 -3
- package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/package.json +6 -6
- package/skills/jskit/references/typed-features.md +51 -9
|
@@ -247,14 +247,19 @@ execute(input, context) {
|
|
|
247
247
|
under `@jskit-ai/auth-web/client/views/` so that only a page that shows one
|
|
248
248
|
loads it (the settings' QR code library included). `SecondFactorSettings`
|
|
249
249
|
sets an authenticator up (a QR code and the key as text, shown once, then the
|
|
250
|
-
app's first code), shows the recovery codes once
|
|
251
|
-
|
|
252
|
-
|
|
250
|
+
app's first code), shows the recovery codes once (to copy, or to download as
|
|
251
|
+
`recovery-codes.txt`), replaces them, and removes the authenticator, each with
|
|
252
|
+
a code or a recovery code; an app places it as an account settings section,
|
|
253
|
+
whose title names it ("Authenticator app"). It emits `codes-saved` when the
|
|
254
|
+
person says they saved a new set of codes, so a page that needs an
|
|
255
|
+
authenticator before it goes on, such as a console's way in, goes on then.
|
|
253
256
|
`SecondFactorPrompt` proves the session's second factor on a page of the app's.
|
|
254
257
|
For a route that asks for a recent code, `useSecondFactorStepUp()` runs the
|
|
255
258
|
request, and when it is refused with `auth.secondFactor.required` opens
|
|
256
259
|
`SecondFactorDialog` and runs it again after the code; cancelling throws the
|
|
257
|
-
refusal to the caller
|
|
260
|
+
refusal to the caller. The dialog gives focus back to the element that had it
|
|
261
|
+
when it opened (the control that sent the request), after the code as after a
|
|
262
|
+
cancel:
|
|
258
263
|
|
|
259
264
|
```vue
|
|
260
265
|
<script setup>
|
|
@@ -330,6 +330,9 @@ the application's `knexfile.js`:
|
|
|
330
330
|
prepare), the files run one at a time on the connected database. A copy
|
|
331
331
|
named like the application's database or `PROD_DB_NAME`, or a server that
|
|
332
332
|
cannot be reached, fails the run instead.
|
|
333
|
+
Every file starts from the snapshot, rows included: a copy an earlier file of
|
|
334
|
+
the run used is restored before the next file takes it, so no file sees what
|
|
335
|
+
another wrote.
|
|
333
336
|
- The snapshot holds the schema as the engine reports it and the rows the
|
|
334
337
|
migrations wrote, including the migration ledger. On MySQL and MariaDB it is
|
|
335
338
|
each table's `SHOW CREATE TABLE` and rows, in
|
|
@@ -44,6 +44,7 @@ through its handle's calls, and every call takes the call's `options` last:
|
|
|
44
44
|
| `patchMany(rows, options)` | many records, each with its own changes |
|
|
45
45
|
| `patchWhere(filters, changes, options)`, `deleteWhere(filters, options)` | every matching row |
|
|
46
46
|
| `lock(id, txOptions)`, `lockMany(ids, txOptions)`, `lockWhere(filters, txOptions)` | rows locked until the transaction ends |
|
|
47
|
+
| `lockPages(filters, txOptions)` | every matching row locked, handed over a page at a time ([Layer 4](#layer-4-locks)) |
|
|
47
48
|
| `lockOrCreate({ id, ...initial }, options, work)` | a keyed record locked, created first when missing, for `work` |
|
|
48
49
|
| `claim({ filters, sort, take }, txOptions)` | the next rows no other worker holds |
|
|
49
50
|
| `withTransaction(options, work)` | one transaction; `work` gets its `txOptions` |
|
|
@@ -88,6 +89,7 @@ the filters match.
|
|
|
88
89
|
| scoped query | The read-only Knex builder `scopedQuery()` returns, with ownership and the row policy already applied. |
|
|
89
90
|
| system scope | Why a feature works across every workspace and user, declared with `systemScope`. |
|
|
90
91
|
| system context | The context of that work, from `systemContext(reason)`; `forWorkspace`, `forUser` and `forWorkspaceUser` narrow it. |
|
|
92
|
+
| member context | The context of work done as one member of one workspace, from `workspaces.memberContext({ workspaceId, userId }, { context: systemContext(reason) })`: resolved as the member's request is, and signed in as them. |
|
|
91
93
|
| `txOptions` | What `withTransaction(options, work)` hands `work`: only the call's context and its transaction, `{ context, trx }`, passed to every call inside. |
|
|
92
94
|
| record | What a handle answers: `{ id, ...fields }`, relationships as ids, included records nested. |
|
|
93
95
|
|
|
@@ -333,6 +335,43 @@ code reads by the key with a filter and writes by it with an upsert,
|
|
|
333
335
|
guide](/guide/app-setup/existing-application-migration#moving-hand-written-sql-behind-resources)
|
|
334
336
|
has the migration for a table that exists already.
|
|
335
337
|
|
|
338
|
+
A table its feature counts but must never read back row by row (who took part
|
|
339
|
+
in an anonymous survey whose answers are stored without names) takes a `uuid`
|
|
340
|
+
primary key the code makes with `crypto.randomUUID()`, never a sequence, and a
|
|
341
|
+
unique index on the columns that identify a row, the ownership column among
|
|
342
|
+
them. A random v4 id carries no time and no order, and MySQL and MariaDB store
|
|
343
|
+
rows in primary key order, so the stored order is random too; a sequence or a
|
|
344
|
+
time-ordered id (UUIDv7, or the v1 that MySQL's and MariaDB's `UUID()` makes)
|
|
345
|
+
would let whoever reads the rows match them to the order of the answers.
|
|
346
|
+
PostgreSQL's heap keeps the order rows were inserted in, which a direct read
|
|
347
|
+
of the table shows whatever the key, so the protection that holds everywhere is
|
|
348
|
+
that no code reads the rows: the owning feature offers only an insert and a
|
|
349
|
+
count, functions of its own over its handle, and ownership keeps every other
|
|
350
|
+
feature from reading the table.
|
|
351
|
+
|
|
352
|
+
```js
|
|
353
|
+
import { randomUUID } from "node:crypto";
|
|
354
|
+
|
|
355
|
+
// the owning feature's whole API over the table: record that a member took part, and count who did
|
|
356
|
+
const recordParticipation = ({ recordId, userId }, options) =>
|
|
357
|
+
participations.createMany([{ id: randomUUID(), recordId, userId }], {
|
|
358
|
+
...options,
|
|
359
|
+
onConflict: { keys: ["workspaceId", "recordId", "userId"], action: "ignore" }
|
|
360
|
+
});
|
|
361
|
+
const countParticipants = async (recordId, options) => {
|
|
362
|
+
const [{ participants }] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId } }, options);
|
|
363
|
+
return participants;
|
|
364
|
+
};
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
`onConflict` ignore makes a second participation a no-op that keeps the stored
|
|
368
|
+
row and its id, and a new row takes the id it brings. Only a clash on the keys'
|
|
369
|
+
unique index is ignored, so an id that is already another row's still fails.
|
|
370
|
+
Plain `create({ id: randomUUID(), recordId, userId }, options)` refuses the
|
|
371
|
+
second participation instead, with the unique key's error; inside a
|
|
372
|
+
transaction the failed insert fails the whole transaction (PostgreSQL aborts it
|
|
373
|
+
at once), so work that must go on uses the ignore.
|
|
374
|
+
|
|
336
375
|
A route that reads or writes without an action (a provider's callback, a
|
|
337
376
|
download it streams) takes its options from `await request.callOptions()`: the
|
|
338
377
|
context the same request's action would get, its user, workspace and route
|
|
@@ -435,10 +474,13 @@ request, `{ kind: "anonymous" }` for one by no one, and `{ kind: "system" }` or
|
|
|
435
474
|
`reason`, for background work. A job names a user only as `actorId`, the
|
|
436
475
|
person it works for ([below](#background-work)), so never read a missing actor
|
|
437
476
|
as an anonymous request. The owner's policy also receives the capabilities its
|
|
438
|
-
feature requires (and its optional ones), by local name, as
|
|
439
|
-
same ones its setup receives: a policy that needs another
|
|
440
|
-
declares that feature's capability in `requires` and reads
|
|
441
|
-
|
|
477
|
+
feature requires (and its optional and late ones), by local name, as
|
|
478
|
+
`requires`, the same ones its setup receives: a policy that needs another
|
|
479
|
+
feature's answer declares that feature's capability in `requires` and reads
|
|
480
|
+
`requires.<name>`. When that feature requires the policy's own feature, the
|
|
481
|
+
two form a ring; the policy's feature declares the capability `late` instead
|
|
482
|
+
([Capability cycles](#capability-cycles)). A policy runs on every read, so
|
|
483
|
+
what it asks there must be cheap.
|
|
442
484
|
|
|
443
485
|
```js
|
|
444
486
|
// good: one predicate on the row being read
|
|
@@ -473,7 +515,12 @@ subquery to the row with `whereExists`: over `ownTable(name)`, which may join
|
|
|
473
515
|
the owner's other tables, or over another owner's join source. A policy is told
|
|
474
516
|
the call's `options`, `{ context, trx }` as the caller passed them, and passes
|
|
475
517
|
them on unchanged to `joinSource({ alias }, options)`, so the join source reads
|
|
476
|
-
in the caller's scope and transaction; never build them by hand.
|
|
518
|
+
in the caller's scope and transaction; never build them by hand. `options.trx`
|
|
519
|
+
names the transaction the read runs in: the caller's, or, for a write whose
|
|
520
|
+
caller named none, the one json-rest-api opens for it, which the lookup before
|
|
521
|
+
a patch and the read-back after a create run in. So an owner API the policy
|
|
522
|
+
calls with its `options` (a join source, or a handle read such as a role check)
|
|
523
|
+
joins that transaction and never waits for a second connection.
|
|
477
524
|
|
|
478
525
|
```js
|
|
479
526
|
// good: a member of the document's team sees it, through the teams owner's join source
|
|
@@ -495,6 +542,45 @@ function teamDocumentsPolicy({ query, caller, column }) {
|
|
|
495
542
|
}
|
|
496
543
|
```
|
|
497
544
|
|
|
545
|
+
A policy whose rule reads another owner's rows as stored (a document is
|
|
546
|
+
visible while its folder is open, whether or not the reader may see the folder
|
|
547
|
+
itself) reads them through that owner's API, never through a context it builds.
|
|
548
|
+
The owner answers a join source of its rows under its own `systemScope`,
|
|
549
|
+
narrowed to the call's workspace, so the rows stay that workspace's and `jskit
|
|
550
|
+
check` lists the reason. The policy passes its `options` on unchanged, as
|
|
551
|
+
always, and returns early for background work, whose own context already
|
|
552
|
+
decides. It still only narrows: the stored rows feed its predicate and are
|
|
553
|
+
never answered, so the reader sees no folder it could not see before.
|
|
554
|
+
|
|
555
|
+
```js
|
|
556
|
+
// good: the folders' owner API, in the folders feature, whose setup receives systemContext
|
|
557
|
+
function storedSource({ alias }, options) {
|
|
558
|
+
const context = systemContext("the documents' row policy reads each folder's status as stored")
|
|
559
|
+
.forWorkspace(resolveWorkspaceScopeValue(options.context));
|
|
560
|
+
return folders.joinSource({ alias }, { ...passedOn(options), context });
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// good: the documents' policy, which requires the folders' owner API
|
|
564
|
+
async function openFolderDocuments({ query, caller, column, options, requires }) {
|
|
565
|
+
if (caller.kind !== "user") {
|
|
566
|
+
return caller.kind !== "anonymous";
|
|
567
|
+
}
|
|
568
|
+
const folder = await requires.folders.storedSource({ alias: "f" }, options);
|
|
569
|
+
query.whereExists(folder.query.select(1).whereColumn(folder.column("id"), column("folderId")).where(folder.column("status"), "open"));
|
|
570
|
+
return true;
|
|
571
|
+
}
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
A policy never walks a tree with a recursive query (`withRecursive`). No builder
|
|
575
|
+
it holds takes a common table expression, and a walk that starts at the row
|
|
576
|
+
being read does not compile on MariaDB, which lets no outer column into a
|
|
577
|
+
recursive query's first member; a walk that starts elsewhere (the reader's
|
|
578
|
+
grants, walking down) reads the reader's whole subtree on every read. Keep the
|
|
579
|
+
tree's ancestry stored instead: its owner writes a closure table (each node's
|
|
580
|
+
ancestors, one row each, with their depth) in the same transaction that adds
|
|
581
|
+
or moves a node, and the policy ties one `whereExists` over that table's join
|
|
582
|
+
source to the row, on indexed columns, on every database.
|
|
583
|
+
|
|
498
584
|
A rule that depends on the caller's role reads `context.permissions` with
|
|
499
585
|
`hasPermission(context.permissions, "bookings.view-all")` from
|
|
500
586
|
`@jskit-ai/kernel/shared/support`, never with `includes()`. A role may hold
|
|
@@ -689,11 +775,14 @@ could update or hide another workspace's row. `merge` is refused under a row
|
|
|
689
775
|
policy; use `ignore`, then `patchMany`. A table with no owners and no row
|
|
690
776
|
policy, keyed by a natural id such as an email, may key the upsert on the id
|
|
691
777
|
alone: `onConflict: { keys: ["id"], action: "merge" }`, with an id on every
|
|
692
|
-
row, creates the record or replaces the fields given in one statement.
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
778
|
+
row, creates the record or replaces the fields given in one statement. A merge's
|
|
779
|
+
rows carry no other id; an `ignore`'s may, for ids the code makes (a random
|
|
780
|
+
`uuid`): a new row takes its own, and a row the keys match keeps the stored one
|
|
781
|
+
(see the count-only table above). Of two upserts at once the later stays, so a
|
|
782
|
+
counter that must count both is created plainly and its duplicate retried
|
|
783
|
+
instead. Inserting and catching the duplicate works only outside a transaction:
|
|
784
|
+
inside one, the failed insert fails the whole transaction, so use an upsert
|
|
785
|
+
there.
|
|
697
786
|
|
|
698
787
|
A transaction whose insert loses a race for a unique key (another request with
|
|
699
788
|
the same idempotency key committed first) runs once more:
|
|
@@ -727,6 +816,21 @@ or a counter row taken with `lock(id)`. Every lock needs a transaction; SQLite
|
|
|
727
816
|
runs one transaction at a time, so there is no row lock to take. Take locks in
|
|
728
817
|
one order on every path, a parent before its children.
|
|
729
818
|
|
|
819
|
+
`lockWhere` takes that order from `sort` too: `lockWhere({ batchId }, {
|
|
820
|
+
...txOptions, sort: ["moduleKey"] })` locks the rows in `sort` order
|
|
821
|
+
(fields, `"-moduleKey"` for descending), then by id, and answers them in it,
|
|
822
|
+
so two paths that lock overlapping rows wait for each other instead of
|
|
823
|
+
deadlocking. `limit` locks only the first rows of that order, by id without a
|
|
824
|
+
`sort`: a check whether any row matches, or the lock of one row by a unique key
|
|
825
|
+
other than its id, takes `limit: 1`, one statement as `lock(id)` is
|
|
826
|
+
(`workspaces.memberships.lockByWorkspaceIdAndUserId` locks its membership so).
|
|
827
|
+
Without either, `lockWhere` locks every match in id order (on MySQL and MariaDB
|
|
828
|
+
in the order of the index it reads, below), at most 1,000 (more throw), and
|
|
829
|
+
PostgreSQL reads them once more under its locks, for a row that started to
|
|
830
|
+
match while it waited; with a `limit` it stops once it holds that many. A
|
|
831
|
+
`limit` outside 1 to 1,000, or a `sort` on no stored field, is refused before
|
|
832
|
+
any statement.
|
|
833
|
+
|
|
730
834
|
A lock answers the rows it locks, with the fields `fields` names. Its
|
|
731
835
|
`include` names belongs-to relationships (`include: ["customer"]`, or
|
|
732
836
|
`"batch.yard"` a level further): after its own rows, the lock locks the
|
|
@@ -766,13 +870,57 @@ const [booked] = await bookings.queryAll({ filters: { seatIds: [seatId] }, take:
|
|
|
766
870
|
await seats.lock(seatId, txOptions);
|
|
767
871
|
```
|
|
768
872
|
|
|
873
|
+
A whole set of rows the work decides on (a register's entries, an account's
|
|
874
|
+
movements) is read the same way: every writer of the set first locks the one
|
|
875
|
+
row that governs it (the register, the account), and the work locks that row
|
|
876
|
+
before its first plain read. The plain reads after it (`queryAll`,
|
|
877
|
+
`queryPages`, `aggregate`) are then current and stay so until commit, at any
|
|
878
|
+
size, for one statement more. Work that joins its caller's transaction cannot
|
|
879
|
+
know whether the caller already read plainly, and on MySQL and MariaDB a lock
|
|
880
|
+
taken after that no longer moves the snapshot, so it reads the set with
|
|
881
|
+
locking reads, which see the latest rows whatever the snapshot:
|
|
882
|
+
`lockPages(filters, txOptions)` locks every row the filters select, a page of
|
|
883
|
+
up to 1,000 (`pageSize`) at a time, in id order, each page one locking read
|
|
884
|
+
after the last id of the page before. It still locks the governing row first,
|
|
885
|
+
since PostgreSQL keeps no new row out of a page already locked. In a request it
|
|
886
|
+
throws past the request row limit, as `queryPages` does. Isolation is not the
|
|
887
|
+
tool: MySQL and MariaDB fix it when a transaction starts, and READ COMMITTED
|
|
888
|
+
alone reads each page at a different moment. `patchWhere` and `deleteWhere`
|
|
889
|
+
select their rows with a locking read on MySQL and MariaDB, so they too see
|
|
890
|
+
what committed after the transaction's first plain read. With MariaDB's
|
|
891
|
+
`innodb_snapshot_isolation` on, a locking read that meets a row changed since
|
|
892
|
+
the snapshot fails (errno 1020) instead, and `withTransaction` runs the work
|
|
893
|
+
again when it opened the transaction.
|
|
894
|
+
|
|
895
|
+
```js
|
|
896
|
+
// good: inside the caller's transaction, the register locked, then every entry locked and read as it is now
|
|
897
|
+
const closeRegister = (registerId, options) => registers.withTransaction({ ...options, joinOnly: true }, async (txOptions) => {
|
|
898
|
+
await registers.lock(registerId, { ...txOptions, lockMode: "share", fields: ["id"] });
|
|
899
|
+
let total = 0;
|
|
900
|
+
for await (const page of entries.lockPages({ registerId }, { ...txOptions, lockMode: "share", fields: ["amount"] })) {
|
|
901
|
+
total += page.reduce((sum, entry) => sum + entry.amount, 0);
|
|
902
|
+
}
|
|
903
|
+
return total;
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
// bad: a plain read inside a joined transaction reads the caller's snapshot, which can miss entries
|
|
907
|
+
const all = await entries.queryAll({ filters: { registerId } }, txOptions);
|
|
908
|
+
```
|
|
909
|
+
|
|
769
910
|
On MySQL and MariaDB a locking read locks every row it examines, so two rules
|
|
770
911
|
apply there. Lock ids taken from your own scoped reads, never a list straight
|
|
771
912
|
from a request: every id listed is locked, a hidden one too, before it is left
|
|
772
913
|
out. And `lockWhere` needs an index that starts with the ownership columns (on
|
|
773
914
|
a table with no owners, with a column the filters compare); without one it
|
|
774
915
|
refuses with `RestApiBulkWriteUnsupportedError` naming the index to add in a
|
|
775
|
-
migration.
|
|
916
|
+
migration. With `sort` or `limit` the index must also read the rows in the
|
|
917
|
+
lock's order, since the database locks them in the order it reads them: after
|
|
918
|
+
the ownership columns and the columns the filters fix to one value, it holds
|
|
919
|
+
the sort's columns, ascending, and then nothing but the id, and the sort's
|
|
920
|
+
fields go one way (all ascending or all descending). A unique key the filters
|
|
921
|
+
fix whole, as a membership's workspace and user are, needs nothing more.
|
|
922
|
+
`lockPages` locks in id order, so its index holds nothing after the ownership
|
|
923
|
+
columns and the columns the filters fix but the id.
|
|
776
924
|
|
|
777
925
|
A worker taking the next job uses `claim({ filters, sort, take }, txOptions)`,
|
|
778
926
|
which skips rows another worker holds. A record that serializes work on a key
|
|
@@ -827,8 +975,15 @@ await memberships.patch(input.membershipId, { lastFiledAt: new Date() }, txOptio
|
|
|
827
975
|
```
|
|
828
976
|
|
|
829
977
|
Locks stay on the owner's handle and its owner API. A `scopedQuery()` or
|
|
830
|
-
`joinSource()` builder takes no lock,
|
|
831
|
-
|
|
978
|
+
`joinSource()` builder takes no lock, not even a shared one: PostgreSQL's `FOR
|
|
979
|
+
SHARE OF` an alias would lock only that source's rows, but MariaDB has no `FOR
|
|
980
|
+
SHARE OF` at all, and its `LOCK IN SHARE MODE` covers every row the statement
|
|
981
|
+
examines, in every table. A report that needs another
|
|
982
|
+
owner's rows unchanged until it commits first locks them through that owner's
|
|
983
|
+
handle or owner API with `lockMode: "share"` (by a unique key with `limit:
|
|
984
|
+
1`), then reads its join. A row policy is not told a read's lock mode, and
|
|
985
|
+
never takes a lock: it says which rows a caller may see, the same for every
|
|
986
|
+
read, and the lock call it narrows takes its own mode. Rows
|
|
832
987
|
of several owners are never locked in one statement over a join, which on
|
|
833
988
|
MySQL and MariaDB locks every joined row the read examines: lock each owner's
|
|
834
989
|
rows with its own `lock`, `lockMany` or `lockWhere`, the owners in one fixed
|
|
@@ -1222,6 +1377,38 @@ const SettlementFeature = defineFeature({
|
|
|
1222
1377
|
request's `caller.userId`, so a job for a person sees what that person may
|
|
1223
1378
|
see, and a job for no one its whole scope. Work on one person's rows only
|
|
1224
1379
|
takes their scope (`forUser`, `forWorkspaceUser`) or filters its reads.
|
|
1380
|
+
- Work done as one member of a workspace, running what their own request would
|
|
1381
|
+
(an action that checks their permissions, code that reads `context.actor`):
|
|
1382
|
+
a record started for the person it is assigned to, a notification for one
|
|
1383
|
+
recipient, a submission synced for the person who made it. It asks
|
|
1384
|
+
workspaces-core for the member's context, never builds one by hand, since a
|
|
1385
|
+
hand-built context drifts from what a request resolves:
|
|
1386
|
+
|
|
1387
|
+
```js
|
|
1388
|
+
// requires: { workspaces: "workspaces.core", actions: "runtime.actions" }; the feature declares systemScope
|
|
1389
|
+
const member = await workspaces.memberContext(
|
|
1390
|
+
{ workspaceId: record.workspaceId, userId: record.assigneeId },
|
|
1391
|
+
{ context: systemContext("start each scheduled record for the person it is assigned to") }
|
|
1392
|
+
);
|
|
1393
|
+
await actions.execute({ actionId: "crud.visits.create", input, context: { ...member, surface: "app" } });
|
|
1394
|
+
```
|
|
1395
|
+
|
|
1396
|
+
`memberContext` resolves the member as their request on a `workspace_user`
|
|
1397
|
+
route does, by the same reads: the workspace, their active membership (the
|
|
1398
|
+
owner's ensured), their role's permissions and the settings. It refuses as
|
|
1399
|
+
that request does: a missing or deleted workspace is 404
|
|
1400
|
+
`workspaces.workspace.notFound`, and a user who is no active member of it
|
|
1401
|
+
(removed, inactive, never one, or no user) 403
|
|
1402
|
+
`workspaces.workspace.accessDenied`. The context signs the member in, unlike
|
|
1403
|
+
`{ actorId }`: `resolveActorId` answers them, an action checks their
|
|
1404
|
+
permissions, a row policy is told `caller.kind` "user", request row limits
|
|
1405
|
+
apply and other owners' hidden fields stay hidden. Its scope is the workspace
|
|
1406
|
+
and the member, so an event reaches that member there. Only a system context
|
|
1407
|
+
makes one, and an action it runs names the surface the member's request would
|
|
1408
|
+
use. It reads no sign-in state: JSKIT keeps no disabled flag on users, so an
|
|
1409
|
+
account its auth provider refuses at sign-in (a local account marked
|
|
1410
|
+
disabled) is still resolved; a job that must skip such people asks the
|
|
1411
|
+
provider first.
|
|
1225
1412
|
- A job finds its units with an `aggregate` grouped by the ownership field,
|
|
1226
1413
|
which a system context may group by (and count distinct) even when the table
|
|
1227
1414
|
hides it, then runs each unit scoped to it. It reads the units in pages, all
|
|
@@ -1242,21 +1429,46 @@ const SettlementFeature = defineFeature({
|
|
|
1242
1429
|
}
|
|
1243
1430
|
}
|
|
1244
1431
|
```
|
|
1432
|
+
- A job whose units are the workspaces themselves (each workspace's daily
|
|
1433
|
+
digest, whether or not it has rows yet) pages through them with the
|
|
1434
|
+
`workspaces` owner API, never the table by name:
|
|
1435
|
+
`workspaces.listForSystem({ afterId, limit }, { context: systemContext(reason) })`
|
|
1436
|
+
answers the `{ id, slug }` of the workspaces that are not deleted, in id
|
|
1437
|
+
order, after `afterId` (from the first when it is null), at most `limit` (1 to
|
|
1438
|
+
`pageLimits().request`, 100 by default). Each page is one statement however
|
|
1439
|
+
many workspaces there are: pass a page's last id as the next `afterId`, and a
|
|
1440
|
+
page shorter than `limit` is the last. Any other context, a `forWorkspace`
|
|
1441
|
+
job's too, is refused, as are an `afterId` that is no workspace id and a
|
|
1442
|
+
`limit` out of range:
|
|
1443
|
+
|
|
1444
|
+
```js
|
|
1445
|
+
// requires: { workspaceRecords: "workspaces" }; the feature declares systemScope
|
|
1446
|
+
for (let afterId = null; ;) {
|
|
1447
|
+
const page = await workspaceRecords.listForSystem({ afterId, limit: 100 }, { context: systemContext("send every workspace's daily digest") });
|
|
1448
|
+
for (const { id } of page) await sendDigest({ context: systemContext("send every workspace's daily digest").forWorkspace(id) });
|
|
1449
|
+
if (page.length < 100) break;
|
|
1450
|
+
afterId = page.at(-1).id;
|
|
1451
|
+
}
|
|
1452
|
+
```
|
|
1245
1453
|
- A job that must learn each row's owner across workspaces names the hidden
|
|
1246
1454
|
ownership field in its read's `fields`, `queryAll({ filters, fields:
|
|
1247
1455
|
["workspaceId", "email"] }, { context })`, as a system context may do through
|
|
1248
1456
|
another feature's CRUD repository too (see [Layer
|
|
1249
1457
|
1](#layer-1-the-table-resource)). Never unhide it for the job.
|
|
1250
1458
|
- A request uses its own context. The exceptions are a console report
|
|
1251
|
-
behind a console permission, with bounded output,
|
|
1252
|
-
row it has proved it reaches ([Layer 1](#layer-1-the-table-resource))
|
|
1459
|
+
behind a console permission, with bounded output, the write of a shared
|
|
1460
|
+
row it has proved it reaches ([Layer 1](#layer-1-the-table-resource)), and
|
|
1461
|
+
an owner API that answers its own rows as stored to another owner's row
|
|
1462
|
+
policy, narrowed to the call's workspace ([Layer
|
|
1463
|
+
1](#layer-1-the-table-resource)).
|
|
1253
1464
|
- `jskit check` lists every system scope and every `systemContext` call with
|
|
1254
1465
|
its reason, read from the string literal at the call: a reason kept in a
|
|
1255
1466
|
constant reads as none.
|
|
1256
1467
|
- A system context comes only from `systemScope`, and a context's scope only
|
|
1257
|
-
from the request
|
|
1258
|
-
lint refuses `createSystemContext` and
|
|
1259
|
-
context naming two workspaces or two users
|
|
1468
|
+
from the request, from `forWorkspace`, `forUser` and `forWorkspaceUser`, or
|
|
1469
|
+
from `workspaces.memberContext`: lint refuses `createSystemContext` and
|
|
1470
|
+
hand-written `scopeValues`, and a context naming two workspaces or two users
|
|
1471
|
+
throws.
|
|
1260
1472
|
- A table only the feature's own background work reads and writes, whose rows
|
|
1261
1473
|
belong to no workspace or user (an agent's runs, a server's leases, a queue
|
|
1262
1474
|
keyed by something other than an owner), takes ownership `system`. Every call
|
|
@@ -1298,7 +1510,7 @@ never open one of its own, passes `{ ...options, joinOnly: true }`: called
|
|
|
1298
1510
|
outside a transaction it throws a TypeError before the work runs. Code never
|
|
1299
1511
|
asks whether it runs in a transaction: `withTransaction` joins the caller's,
|
|
1300
1512
|
`outermost` refuses one, `joinOnly` requires one, and `lock`, `lockMany`,
|
|
1301
|
-
`lockWhere` and `claim` refuse to run outside one; `lockOrCreate` opens its own
|
|
1513
|
+
`lockWhere`, `lockPages` and `claim` refuse to run outside one; `lockOrCreate` opens its own
|
|
1302
1514
|
(and retries a lost insert race only then).
|
|
1303
1515
|
|
|
1304
1516
|
```js
|
|
@@ -1369,6 +1581,9 @@ workspaces. A report that reads people, their settings, workspaces or
|
|
|
1369
1581
|
memberships beside its own rows joins `joinSource({ alias, filters },
|
|
1370
1582
|
options)` of `users.profiles`, `users.settings`, `workspaces` or
|
|
1371
1583
|
`workspaces.memberships` ([Layer 5](#layer-5-reports-the-resource-cannot-express)).
|
|
1584
|
+
A background job that visits every workspace pages them with
|
|
1585
|
+
`workspaces.listForSystem({ afterId, limit }, options)`, in its system context
|
|
1586
|
+
([Background work](#background-work)).
|
|
1372
1587
|
|
|
1373
1588
|
An app that had a table resource of its own over a JSKIT table (such as
|
|
1374
1589
|
`users`) deletes it: its CRUD contract is built on the package's table resource
|
|
@@ -1425,7 +1640,8 @@ without it.
|
|
|
1425
1640
|
|
|
1426
1641
|
A capability cycle is a ring of requires: feature A requires a capability that
|
|
1427
1642
|
feature B provides while B, directly or through others, requires one that A
|
|
1428
|
-
provides. An `optional` require closes a ring as a required one does
|
|
1643
|
+
provides. An `optional` require closes a ring as a required one does; a
|
|
1644
|
+
`late` one does not ([below](#late-requirements)). The
|
|
1429
1645
|
kernel sets features up in the order their requires give, so it cannot start a
|
|
1430
1646
|
ring: boot fails before any setup, naming it,
|
|
1431
1647
|
`Provider capability cycle detected: children -> parents -> children.`
|
|
@@ -1449,10 +1665,74 @@ Keep every require pointing one way:
|
|
|
1449
1665
|
definitions, move those table resources into a package of their own that
|
|
1450
1666
|
holds only shared definitions and depends on neither.
|
|
1451
1667
|
- Never break a ring with a value handed over later (a setter, a capability
|
|
1452
|
-
looked up at call time): a call's destination then depends on what
|
|
1453
|
-
before. A setter kept until the split carries typed features' `cycle:`
|
|
1668
|
+
looked up by name at call time): a call's destination then depends on what
|
|
1669
|
+
ran before. A setter kept until the split carries typed features' `cycle:`
|
|
1454
1670
|
exception ([Optional tokens](/guide/framework/typed-features#optional-tokens)).
|
|
1455
1671
|
|
|
1672
|
+
### Late requirements
|
|
1673
|
+
|
|
1674
|
+
A ring that only a read at call time closes, most often a row policy's, and
|
|
1675
|
+
that you cannot or do not want to split, is broken with a late requirement:
|
|
1676
|
+
the kernel's declared alternative to a setter. An audit history whose row
|
|
1677
|
+
policy narrows through the evidence files' owner, while the evidence owner
|
|
1678
|
+
records each change in the audit history, is one: the evidence feature
|
|
1679
|
+
requires `audit.history` as usual, and the audit feature declares
|
|
1680
|
+
`late: { evidence: "evidence.files" }`.
|
|
1681
|
+
|
|
1682
|
+
- A late requirement takes no part in the order features start in, nor in the
|
|
1683
|
+
cycle check, so the ring starts. The kernel resolves it once, after every
|
|
1684
|
+
feature's `boot()`: its destination is declared, so it never depends on what
|
|
1685
|
+
ran before.
|
|
1686
|
+
- It is read at call time only: in a row policy (`requires.evidence`), a
|
|
1687
|
+
request handler, or a method setup builds that runs later, which keeps the
|
|
1688
|
+
capabilities object and reads the name when it runs. A read before every
|
|
1689
|
+
feature has booted (in setup or boot, or a late name destructured in setup's
|
|
1690
|
+
parameters) throws `Provider "audit" read its late requirement "evidence"
|
|
1691
|
+
(capability "evidence.files") before every provider booted: ...`, which
|
|
1692
|
+
says where it may be read. A shutdown reads it only after a start that
|
|
1693
|
+
finished.
|
|
1694
|
+
- It is required: when no feature or runtime input provides it, start fails at
|
|
1695
|
+
the end of boot, `Provider "audit" late-requires missing capability
|
|
1696
|
+
"evidence.files": no provider or runtime input provides it.`, and stops what
|
|
1697
|
+
started, as any startup failure does. The package manifest lists it under
|
|
1698
|
+
`requires`.
|
|
1699
|
+
- A feature never late-requires a capability it provides, nor one it already
|
|
1700
|
+
requires or takes as optional.
|
|
1701
|
+
- The one-way rules above still come first: split the ring when you can. A
|
|
1702
|
+
ring that both features' setup or boot needs cannot be broken this way,
|
|
1703
|
+
since a late requirement is never read there.
|
|
1704
|
+
|
|
1705
|
+
```js
|
|
1706
|
+
// good: the audit history's row policy reads the evidence owner's join source at call time
|
|
1707
|
+
const AuditFeature = defineFeature({
|
|
1708
|
+
id: "audit",
|
|
1709
|
+
owns: [{ resource: auditEntryResource, rowPolicy: auditEntriesPolicy }],
|
|
1710
|
+
late: {
|
|
1711
|
+
evidence: "evidence.files"
|
|
1712
|
+
},
|
|
1713
|
+
provides: {
|
|
1714
|
+
history: "audit.history"
|
|
1715
|
+
},
|
|
1716
|
+
setup({ resources }) {
|
|
1717
|
+
return { history: createAuditHistory({ entries: resources.auditEntries }) };
|
|
1718
|
+
}
|
|
1719
|
+
});
|
|
1720
|
+
|
|
1721
|
+
async function auditEntriesPolicy({ query, caller, column, options, requires }) {
|
|
1722
|
+
if (caller.kind !== "user") {
|
|
1723
|
+
return caller.kind !== "anonymous";
|
|
1724
|
+
}
|
|
1725
|
+
const file = await requires.evidence.joinSource({ alias: "ef" }, options);
|
|
1726
|
+
query.whereExists(file.query.select(1).whereColumn(file.column("id"), column("evidenceFileId")));
|
|
1727
|
+
return true;
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
// bad: the late name destructured in setup, before every feature has booted; boot fails
|
|
1731
|
+
setup({ resources, evidence }) {
|
|
1732
|
+
return { history: createAuditHistory({ entries: resources.auditEntries, evidence }) };
|
|
1733
|
+
}
|
|
1734
|
+
```
|
|
1735
|
+
|
|
1456
1736
|
## Check and judge
|
|
1457
1737
|
|
|
1458
1738
|
Before calling data work done, apply the
|
|
@@ -1609,6 +1889,16 @@ server code is server code. Neither `eslint-disable`, an inline
|
|
|
1609
1889
|
|
|
1610
1890
|
### Exceptions
|
|
1611
1891
|
|
|
1892
|
+
A data-access rule that refuses a statement points at a missing API, never at a
|
|
1893
|
+
statement to excuse: no rule takes a per-statement exception. When no owner
|
|
1894
|
+
API does what the work needs (locks in a given order, one row by a unique key,
|
|
1895
|
+
a check the row policy cannot write), ask for one: from the feature that owns
|
|
1896
|
+
the table, or from JSKIT for its own packages and for the handle itself. Only
|
|
1897
|
+
statements that are data access themselves go under an exception, in a file
|
|
1898
|
+
of their own declared as infrastructure (below), kept small and holding only
|
|
1899
|
+
those statements, so the exception hides nothing else: a repository, a row
|
|
1900
|
+
policy or a report never moves into such a file to pass lint.
|
|
1901
|
+
|
|
1612
1902
|
A module whose job is data access itself (a database runtime, a migration
|
|
1613
1903
|
runner, test-database setup, an operator's data import or cutover tool, a
|
|
1614
1904
|
database console that runs the person's own SQL) may opt out of
|
|
@@ -29,8 +29,9 @@ rule in [client features](/guide/framework/client-features).
|
|
|
29
29
|
> so each call has exactly one visible destination for a reader and for the
|
|
30
30
|
> code map.
|
|
31
31
|
|
|
32
|
-
- A **capability** is a value a feature `provides`, `requires
|
|
33
|
-
(`optional`)
|
|
32
|
+
- A **capability** is a value a feature `provides`, `requires`, may use
|
|
33
|
+
(`optional`) or requires once every feature has booted (`late`), named by a
|
|
34
|
+
**token** such as `"feature.invoices"`.
|
|
34
35
|
- A **collaborator** is an object or function with behaviour that code calls:
|
|
35
36
|
a service, store, repository, runtime, router, publisher, catalogue, logger
|
|
36
37
|
or clock. Plain data (an input, a record, a list, an options bag) is not one.
|
|
@@ -47,8 +48,8 @@ it reports the call as exact instead of guessing from the method name.
|
|
|
47
48
|
### Feature files
|
|
48
49
|
|
|
49
50
|
**A `defineFeature` lives in `<Name>Feature.js`, its keys in one order, one
|
|
50
|
-
per line: `id, domain, owns, systemScope, requires, optional,
|
|
51
|
-
setup, actions, boot, shutdown`.** A `defineProvider` lives in `<Name>Provider.js`.
|
|
51
|
+
per line: `id, domain, owns, systemScope, requires, optional, late,
|
|
52
|
+
provides, setup, actions, boot, shutdown`.** A `defineProvider` lives in `<Name>Provider.js`.
|
|
52
53
|
|
|
53
54
|
- `setup` builds each provided value with a named `create<Name>` factory from
|
|
54
55
|
a module of its own, never inline. It returns exactly the keys `provides`
|
|
@@ -86,8 +87,8 @@ actions: ({ invoices }) => [{ id: "invoices.list", execute: () => invoices.list(
|
|
|
86
87
|
**A package's manifest, `jskit.capabilities` in its `package.json`, lists
|
|
87
88
|
exactly what its features provide, and every capability they require beyond
|
|
88
89
|
the kernel's own (`runtime.actions`, `runtime.events`, `runtime.http`,
|
|
89
|
-
`runtime.bootstrap`) and those the package provides itself.**
|
|
90
|
-
capabilities are not
|
|
90
|
+
`runtime.bootstrap`) and those the package provides itself.** Late
|
|
91
|
+
capabilities are required; optional ones are not. A requirement no feature has stays only when
|
|
91
92
|
the package needs it at install time, such as the database its migrations
|
|
92
93
|
need.
|
|
93
94
|
|
|
@@ -261,7 +262,8 @@ function createMailer({ env = process.env } = {}) {
|
|
|
261
262
|
- When the slot's supplier requires the slot's owner, the two form a cycle.
|
|
262
263
|
Split the part of the owner the supplier needs into its own feature. Until
|
|
263
264
|
then the setter stays, with a `cycle:` [exception comment](#exceptions), and
|
|
264
|
-
is cleared at shutdown.
|
|
265
|
+
is cleared at shutdown. A value with no default that the owner reads only
|
|
266
|
+
when called is no slot: it is a [late requirement](#late-requirements).
|
|
265
267
|
|
|
266
268
|
Why: a slot filled later makes a call's destination depend on what ran
|
|
267
269
|
before.
|
|
@@ -291,6 +293,46 @@ function setNumbering(next) {
|
|
|
291
293
|
}
|
|
292
294
|
```
|
|
293
295
|
|
|
296
|
+
### Late requirements
|
|
297
|
+
|
|
298
|
+
**A capability that closes a ring and is read only when called, such as by a
|
|
299
|
+
row policy, is `late`: the kernel resolves it once every feature has booted,
|
|
300
|
+
and code reads it from the capabilities object at call time, never in
|
|
301
|
+
`setup()` or `boot()`.**
|
|
302
|
+
|
|
303
|
+
- Split the ring first ([capability cycles](/guide/framework/data-access#capability-cycles)).
|
|
304
|
+
A late requirement is for a ring a call-time read closes, after splitting
|
|
305
|
+
is not possible or not wanted.
|
|
306
|
+
- `late` maps local names to tokens, as `requires` does, with names no other
|
|
307
|
+
map of the feature uses. It never names a token the feature provides,
|
|
308
|
+
requires or takes as optional.
|
|
309
|
+
- It is required: when nothing provides it, start-up fails at the end of
|
|
310
|
+
boot, naming the feature and the token, and the package manifest lists it.
|
|
311
|
+
- A row policy reads it from `requires`
|
|
312
|
+
([data access](/guide/framework/data-access#late-requirements)). A value
|
|
313
|
+
`setup()` builds receives the capabilities object, typed, and reads the
|
|
314
|
+
late name in its methods; `setup()` never destructures it. A read before
|
|
315
|
+
every feature has booted throws, naming the feature, the name and the token.
|
|
316
|
+
|
|
317
|
+
Why: the token is declared and the kernel resolves it once, so a call's
|
|
318
|
+
destination never depends on what ran before, as it does with a setter.
|
|
319
|
+
|
|
320
|
+
```js
|
|
321
|
+
// good: the token declared late; the factory reads it when a report runs
|
|
322
|
+
late: {
|
|
323
|
+
evidence: "evidence.files"
|
|
324
|
+
},
|
|
325
|
+
/** @param {{ resources: { auditEntries: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }, evidence: import("@local/evidence/server/types").EvidenceFiles }} capabilities */
|
|
326
|
+
setup(capabilities) {
|
|
327
|
+
return { reports: createAuditReports({ capabilities }) };
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
// bad: destructured in setup, before every feature has booted; start-up fails
|
|
331
|
+
setup({ resources, evidence }) {
|
|
332
|
+
return { reports: createAuditReports({ entries: resources.auditEntries, evidence }) };
|
|
333
|
+
},
|
|
334
|
+
```
|
|
335
|
+
|
|
294
336
|
### Owned state
|
|
295
337
|
|
|
296
338
|
**A capability owns its state: built in `setup()`, started in `boot()`,
|
|
@@ -1161,7 +1203,7 @@ Why: the limits measure code a person reads; a table is scanned, not read.
|
|
|
1161
1203
|
an object that spans lines, braces once an `if` spans lines.** `eslint --fix`
|
|
1162
1204
|
applies it.
|
|
1163
1205
|
|
|
1164
|
-
- A returned frozen result and a `requires`, `optional` or `provides` map put
|
|
1206
|
+
- A returned frozen result and a `requires`, `optional`, `late` or `provides` map put
|
|
1165
1207
|
each property on its own line. A short leaf literal of at most three scalar
|
|
1166
1208
|
properties (`{ type: "string", required: true }`) may stay on one line.
|
|
1167
1209
|
- Long prose stays inline in its string or template; never split a sentence
|
|
@@ -1304,7 +1346,7 @@ Every finding ends with a link to the section of this page that explains it.
|
|
|
1304
1346
|
| `jskit/no-patched-error` | `Object.assign(new Error(…), { statusCode })`, or an error builder's result given its status afterwards | [One construction per error](#one-construction-per-error) |
|
|
1305
1347
|
| `jskit/no-test-only-export` | an export whose name says only tests use it (`…ForTests`, `__reset…`; `__testables` aside) | [No test-only exports](#no-test-only-exports) |
|
|
1306
1348
|
| `jskit/narrow-in-query` | `.filter()`, `.find()`, `.some()`, `.every()`, `.slice()`, a lone `.length` or a loop that skips with `continue`, over the rows a read in the same function answered and uses no other way | [Narrow in the query](#narrow-in-the-query) |
|
|
1307
|
-
| `jskit/one-property-per-line` | two properties on one line in a returned `Object.freeze({ … })` or a `requires` / `optional` / `provides` map (`eslint --fix` splits them) | [Formatter](#formatter) |
|
|
1349
|
+
| `jskit/one-property-per-line` | two properties on one line in a returned `Object.freeze({ … })` or a `requires` / `optional` / `late` / `provides` map (`eslint --fix` splits them) | [Formatter](#formatter) |
|
|
1308
1350
|
| `jskit/jsdoc-description-inside` | a `//` description directly above a `/** */` block | [Comments](#comments) |
|
|
1309
1351
|
| `jskit/allow-comment-form` | a `readable-check: allow` reason without a prefix from the table below, or one that cites tests or the state of a project | [Exceptions](#exceptions) |
|
|
1310
1352
|
| `max-lines`, `max-lines-per-function` | files over 750 lines, functions over 600 | [Size limits](#size-limits) |
|
package/package.json
CHANGED