@jini-ai/db 0.7.3-next.2 → 0.7.4
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/CHANGELOG.md +7 -0
- package/README.md +66 -2
- package/dist/core/ports.d.ts +2 -2
- package/dist/core/ports.js +2 -2
- package/dist/data-modules/data-module.d.ts +2 -46
- package/dist/data-modules/plugin-identity.d.ts +2 -11
- package/dist/data-modules/snapshot.d.ts +5 -3
- package/dist/data-modules/snapshot.js +5 -3
- package/dist/events/change-set-repo.sql.d.ts +18 -5
- package/dist/events/change-set-repo.sql.js +25 -8
- package/dist/events/index.d.ts +1 -1
- package/dist/events/outbox-repo.sql.d.ts +26 -1
- package/dist/events/outbox-repo.sql.js +36 -2
- package/dist/events/repo.rows.d.ts +22 -4
- package/dist/events/repo.rows.js +32 -4
- package/dist/kernel/idle-turn.d.ts +62 -0
- package/dist/kernel/idle-turn.js +32 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.js +28 -0
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/sqlite/driver.js +2 -0
- package/dist/kernel/sqlite/index.d.ts +1 -1
- package/dist/kernel/sqlite/index.js +1 -1
- package/dist/kernel/sqlite/ops.d.ts +61 -0
- package/dist/kernel/sqlite/ops.js +82 -0
- package/dist/kernel/turn-lock.d.ts +2 -0
- package/dist/kernel/turn-lock.js +7 -0
- package/dist/migrate/runner.d.ts +3 -3
- package/dist/migrate/runner.js +4 -1
- package/dist/owner-store/index.js +1 -1
- package/dist/pglite/copy-source.d.ts +45 -0
- package/dist/pglite/copy-source.js +36 -0
- package/dist/pglite/index.d.ts +1 -0
- package/dist/pglite/index.js +1 -0
- package/dist/react/recovery/Recovery.d.ts +205 -0
- package/dist/react/recovery/Recovery.js +141 -0
- package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
- package/dist/react/recovery/Recovery.restore-steps.js +71 -0
- package/dist/recovery/agent-tools.d.ts +33 -0
- package/dist/recovery/agent-tools.js +166 -0
- package/dist/recovery/drift.d.ts +47 -0
- package/dist/recovery/drift.js +51 -0
- package/dist/recovery/journal-kernel.d.ts +80 -0
- package/dist/recovery/journal-kernel.js +40 -0
- package/dist/recovery/journal-repo.sql.d.ts +154 -0
- package/dist/recovery/journal-repo.sql.js +303 -0
- package/dist/recovery/journal-schema.d.ts +37 -0
- package/dist/recovery/journal-schema.js +110 -0
- package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
- package/dist/recovery/migrate-forward-hooks.js +3 -3
- package/dist/recovery/operation-lock.d.ts +2 -17
- package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
- package/dist/recovery/reconcile-interrupted-migration.js +0 -30
- package/dist/recovery/restore-hooks.d.ts +4 -0
- package/dist/recovery/restore-hooks.js +1 -1
- package/dist/recovery/tool-registrations.d.ts +175 -0
- package/dist/recovery/tool-registrations.js +295 -0
- package/dist/site/repo.memory.d.ts +149 -0
- package/dist/site/repo.memory.js +162 -0
- package/dist/site/tool-registrations.d.ts +130 -0
- package/dist/site/tool-registrations.js +184 -0
- package/dist/sqlite/backup-policy.d.ts +14 -0
- package/dist/sqlite/backup-policy.js +47 -3
- package/dist/sqlite/compaction-steps.d.ts +43 -0
- package/dist/sqlite/compaction-steps.js +74 -0
- package/dist/sqlite/compaction.d.ts +63 -0
- package/dist/sqlite/compaction.js +263 -0
- package/dist/sqlite/db-ops.js +10 -11
- package/dist/sqlite/index.d.ts +2 -1
- package/dist/sqlite/index.js +2 -1
- package/dist/sqlite/open.d.ts +2 -1
- package/dist/sqlite/open.js +14 -4
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/plan-store.d.ts +1 -1
- package/dist/tools/plan-store.js +10 -6
- package/dist/tools/read-tools.d.ts +1 -1
- package/dist/tools/site-db-messages.d.ts +10 -0
- package/dist/tools/site-db-messages.js +23 -0
- package/dist/tools/site-transfer-messages.d.ts +9 -0
- package/dist/tools/site-transfer-messages.js +20 -0
- package/dist/transfer/confirmation-ui.d.ts +19 -0
- package/dist/transfer/confirmation-ui.js +39 -0
- package/dist/transfer/copy-engine.js +11 -11
- package/dist/transfer/copy-order.js +1 -3
- package/dist/transfer/destination-store.d.ts +83 -0
- package/dist/transfer/destination-store.js +82 -0
- package/dist/transfer/index.d.ts +2 -0
- package/dist/transfer/index.js +2 -0
- package/dist/transfer/internal-ddl.d.ts +6 -2
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +2 -2
- package/dist/transfer/schema-catalog.d.ts +148 -0
- package/dist/transfer/schema-catalog.js +141 -0
- package/dist/transfer/sqlite-backup.d.ts +27 -0
- package/dist/transfer/sqlite-backup.js +31 -0
- package/dist/transfer/table-catalog.js +1 -0
- package/dist/watermark/kernel.d.ts +64 -0
- package/dist/watermark/kernel.js +45 -0
- package/package.json +107 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
## 0.7.4
|
|
2
|
+
|
|
3
|
+
### Changes
|
|
4
|
+
|
|
5
|
+
- Add an exclusive idle turn for single-connection kernels, typed mutation actors, and reusable database operation exports.
|
|
6
|
+
- Keep the original feature-connection error while closing both kernel logs, and refuse restore confirmation without a token.
|
|
7
|
+
|
|
1
8
|
## 0.7.2
|
|
2
9
|
|
|
3
10
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -11,11 +11,11 @@ subpaths as deprecated re-export shims for one release; import db directly in ne
|
|
|
11
11
|
| `./pglite` | Owner process, owner lock, private socket paths, low-memory settings, `PgliteSocketServer`, `PgliteClass` | Nothing |
|
|
12
12
|
| `./postgres` | Structural pool/module types and `pgTypesFor` | Nothing |
|
|
13
13
|
| `./kernel` | `StorageKernel`, `buildKernel`, `TurnLock`, dialect helpers, schema introspection and type generation, `StorageOps`, errors, `postgresLockKey` | `kysely` |
|
|
14
|
-
| `./kernel/sqlite` | `sqliteKernel`, file/memory kernels, connection lookup/close, `sqliteOps
|
|
14
|
+
| `./kernel/sqlite` | `sqliteKernel`, file/memory kernels, connection lookup/close, `sqliteOps`, synchronous ledger/column/text reads and quick checks | `kysely` |
|
|
15
15
|
| `./kernel/pglite` | `openPgliteKernel`, `PgKernel`, `PgliteDialect`, `pgliteOps`, served-data copy and restore types | `kysely` |
|
|
16
16
|
| `./kernel/postgres` | `openPostgresKernel`, `openPgliteSocketKernel`, `postgresOps` | `kysely` |
|
|
17
17
|
| `./migrate` | `runMigrations`, `assertValidSteps`, `hasLedger`, `sourceChecksum`, step/error types | `kysely` |
|
|
18
|
-
| `./transfer` | Snapshot sources, completeness, DDL
|
|
18
|
+
| `./transfer` | Snapshot sources, completeness, DDL, transactional psql COPY and the ORM-neutral schema catalog (`CatalogIntrospection` injected by the host) | Nothing |
|
|
19
19
|
| `./kernel/store-copy` | Scope-selected Postgres store copy over borrowed kernels | `kysely` |
|
|
20
20
|
| `./tools` | DB catalogs, portable read/restore-point/transfer handlers and injected ports | `@jini-ai/core` |
|
|
21
21
|
|
|
@@ -23,6 +23,25 @@ There is no `.` export. Each part loads only its own files and its explicitly sh
|
|
|
23
23
|
The connection subpaths load no optional peer. Kernels need Kysely at load time, but all drivers
|
|
24
24
|
are injected when a connection is opened. Transfer and database tools have their own isolated subpaths.
|
|
25
25
|
|
|
26
|
+
`@jini-ai/db/kernel/sqlite` also exports synchronous operations for callers that must stay
|
|
27
|
+
inside a synchronous admission lock:
|
|
28
|
+
|
|
29
|
+
- `readSqliteMigrationLedger({ open, path, table })` opens an existing file read-only, returns
|
|
30
|
+
validated `{ id, checksum }` rows ordered by `applied_at, id`, and always closes the handle.
|
|
31
|
+
- `sqliteHasColumn({ client, table, column })` probes a borrowed handle with bound names.
|
|
32
|
+
- `readSqliteTextColumn({ client, table, column })` quotes both identifiers and returns every
|
|
33
|
+
text value, including duplicates and empty strings, with no ordering promise. Missing columns
|
|
34
|
+
and non-text values refuse. The host filters empty references and owns closing the handle.
|
|
35
|
+
- `quickCheckSqlite({ open, path })` checks an existing file read-only and closes it.
|
|
36
|
+
`quickCheckSqlite({ client }, { maxErrors: 1 })` checks a borrowed handle without closing it.
|
|
37
|
+
Only one exact `ok` result succeeds; open/read failures throw redacted errors for the host's
|
|
38
|
+
existing refusal policy to translate. `maxErrors`, when set, must be a positive 32-bit integer.
|
|
39
|
+
|
|
40
|
+
The structural `SqliteReadClient`, `SqliteReadonlyOpener`, `SqliteMigrationLedgerEntry`, and
|
|
41
|
+
`SqliteQuickCheckSource` types are exported from that same entry. No driver is imported.
|
|
42
|
+
`openSqliteConnection` at `@jini-ai/db/sqlite` applies the caller's pragma list in its supplied
|
|
43
|
+
order and closes the newly opened handle on any pragma failure before rethrowing that failure.
|
|
44
|
+
|
|
26
45
|
Each JavaScript subpath declares `types`, `import` and `default` export conditions.
|
|
27
46
|
The `default` condition points to the same ESM file as `import`, so loaders such as
|
|
28
47
|
the tsx CommonJS bootstrap can resolve the subpaths without an active `import` condition.
|
|
@@ -210,6 +229,42 @@ builds the same four definitions for catalog inspection; its display-only defaul
|
|
|
210
229
|
`app_`. `databaseTransferAgentToolCatalog` remains the neutral default display catalog.
|
|
211
230
|
|
|
212
231
|
|
|
232
|
+
## Wiring
|
|
233
|
+
|
|
234
|
+
### Site wording profile (`@jini-ai/db/tools`)
|
|
235
|
+
|
|
236
|
+
`SITE_DATABASE_MESSAGES` and `SITE_TRANSFER_MESSAGES` are a ready-made "this site" wording
|
|
237
|
+
profile for a host that serves one site. They change prose only: tool ids, permissions, side
|
|
238
|
+
effects and input schemas are identical to the neutral catalog. The profile carries no
|
|
239
|
+
specification ids; a host that cites its own documents spreads the profile and overrides those
|
|
240
|
+
fields. The host injects:
|
|
241
|
+
|
|
242
|
+
- `messages: SITE_DATABASE_MESSAGES` (or its spread override) into
|
|
243
|
+
`getDatabaseAgentToolCatalog({}, { messages })`, `createDatabaseReadTools(ports, { messages })`
|
|
244
|
+
and any other `DbMessages` consumer when it wants the site wording;
|
|
245
|
+
- `messages: SITE_TRANSFER_MESSAGES` plus its own persisted `TransferNaming` into
|
|
246
|
+
`getDatabaseTransferAgentToolCatalog({}, { naming, messages })`,
|
|
247
|
+
`createDatabaseTransferTools(ports, { messages })`, `countSourceRows` and `runCopy`;
|
|
248
|
+
- its own `applicationName` into `createPsqlPostgresTarget({ connectionString }, { applicationName })`
|
|
249
|
+
(the default is `database-transfer`);
|
|
250
|
+
- one `new DatabaseTransferPlanStore()` per process as `plans`, so a planId minted by the plan
|
|
251
|
+
tool is redeemable by the run tool.
|
|
252
|
+
|
|
253
|
+
Product names, schema names, marker tables and table-exclusion policy stay host inputs.
|
|
254
|
+
|
|
255
|
+
### Recovery agent-tool catalog (`@jini-ai/db/recovery/agent-tools`)
|
|
256
|
+
|
|
257
|
+
`createRecoveryAgentToolCatalog({ backupWorkflowGuidance, restorePointIdSource })` returns the seven
|
|
258
|
+
recovery tool definitions. Ids, permissions, side effects, the actor-class rule on
|
|
259
|
+
`backup_execute_restore` and every input schema are fixed by the engine. The host injects:
|
|
260
|
+
|
|
261
|
+
- `backupWorkflowGuidance`: the sentences inside `backup_get_capabilities` that name its own
|
|
262
|
+
repository-backup tools and its portable export path / admin screen;
|
|
263
|
+
- `restorePointIdSource`: the read tool(s) that return a restore point id, named in the
|
|
264
|
+
`restorePointId` field description of `backup_plan_restore` and `backup_execute_restore`.
|
|
265
|
+
|
|
266
|
+
Bind it once at the host's recovery registration site and reuse that one array everywhere.
|
|
267
|
+
|
|
213
268
|
## Design decisions
|
|
214
269
|
|
|
215
270
|
- [Operational history is a bounded read surface](docs/decisions/DR-001-bounded-operational-timeline.md).
|
|
@@ -306,3 +361,12 @@ lives in `@jini-ai/server/owner-store`.
|
|
|
306
361
|
with the same names from `'@jini-ai/server/owner-store'`, and add `@jini-ai/server` (same version as
|
|
307
362
|
`@jini-ai/db`) to the host's dependencies. `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl`
|
|
308
363
|
and `ownerStoreMigration` stay here.
|
|
364
|
+
|
|
365
|
+
## Wiring (transfer: SQLite online backup)
|
|
366
|
+
|
|
367
|
+
`captureSqliteBackupBytes` (`@jini-ai/db/transfer`): the host passes its open, structural SQLite handle
|
|
368
|
+
(`backupTo`) and its own `tempDirPrefix` for the short-lived backup directory.
|
|
369
|
+
|
|
370
|
+
- `@jini-ai/db/pglite`: `copyPgliteSourceTo({ sourceDataDir, targetDataDir, ports })` owns the served-versus-stopped
|
|
371
|
+
copy and owner-lock lifecycle of a PGlite data dir. The host supplies `runningOwner`, `copyServed`,
|
|
372
|
+
`acquireOwnerLock` (mapping a refused lock to its own error), `openStopped` and `copyStopped`.
|
package/dist/core/ports.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* module contributes zero bytes and zero `require()` calls to a consumer's runtime graph.
|
|
8
8
|
*
|
|
9
9
|
* How it relates to the package:
|
|
10
|
-
* `db/core` is the half of `@jini-ai/
|
|
11
|
-
* present — a host running Supabase/Postgres
|
|
10
|
+
* `db/core` is the half of `@jini-ai/db` that must stay installable with no native module
|
|
11
|
+
* present — a host running Supabase/Postgres imports `@jini-ai/db/core` and never compiles
|
|
12
12
|
* `better-sqlite3`. That property is not a convention here, it is enforced: `pnpm guard`'s
|
|
13
13
|
* R12 check walks this directory's transitive import closure and fails if it reaches a driver
|
|
14
14
|
* folder or a driver package. See `scripts/check-driver-isolation.ts`.
|
package/dist/core/ports.js
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* module contributes zero bytes and zero `require()` calls to a consumer's runtime graph.
|
|
8
8
|
*
|
|
9
9
|
* How it relates to the package:
|
|
10
|
-
* `db/core` is the half of `@jini-ai/
|
|
11
|
-
* present — a host running Supabase/Postgres
|
|
10
|
+
* `db/core` is the half of `@jini-ai/db` that must stay installable with no native module
|
|
11
|
+
* present — a host running Supabase/Postgres imports `@jini-ai/db/core` and never compiles
|
|
12
12
|
* `better-sqlite3`. That property is not a convention here, it is enforced: `pnpm guard`'s
|
|
13
13
|
* R12 check walks this directory's transitive import closure and fails if it reaches a driver
|
|
14
14
|
* folder or a driver package. See `scripts/check-driver-isolation.ts`.
|
|
@@ -254,53 +254,9 @@
|
|
|
254
254
|
*/
|
|
255
255
|
import { type Logger } from "@jini-ai/core/primitives";
|
|
256
256
|
import { type HeadroomCheck } from "./disk-headroom.js";
|
|
257
|
-
import { type PluginProvenance } from "./plugin-identity.js";
|
|
258
257
|
import { type PluginStore } from "./plugin-store.js";
|
|
259
|
-
|
|
260
|
-
export type PluginTier
|
|
261
|
-
export interface ColumnDecl {
|
|
262
|
-
readonly name: string;
|
|
263
|
-
readonly type: ColumnType;
|
|
264
|
-
readonly notNull?: boolean;
|
|
265
|
-
readonly primaryKey?: boolean;
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Declared FKs / the SDK stress-test finding — the dataModule seam's
|
|
269
|
-
* declared-index grammar. Comments' moderation-queue query pattern
|
|
270
|
-
* (`workspace_id, entry_id, status`) is the concrete demand this grows the seam against, per
|
|
271
|
-
* OQ-1's own instruction not to silently work around the gap. Deliberately NOT a foreign-key
|
|
272
|
-
* declaration seam too — the original design says referential integrity to `entries`/parent
|
|
273
|
-
* comments is "chokepoint-validated, not FK-enforced (v1)", so only indexes are the real,
|
|
274
|
-
* load-bearing need; adding FK-declaration grammar with no consumer would be speculative.
|
|
275
|
-
*/
|
|
276
|
-
export interface IndexDecl {
|
|
277
|
-
/** SHORT name; core prefixes it the same way tables are (`idx_p_{pluginId}__{name}`). */
|
|
278
|
-
readonly name: string;
|
|
279
|
-
readonly columns: readonly string[];
|
|
280
|
-
readonly unique?: boolean;
|
|
281
|
-
}
|
|
282
|
-
export interface TableDecl {
|
|
283
|
-
/** SHORT name; core prefixes it with the reserved `p_{pluginId}__` namespace. */
|
|
284
|
-
readonly name: string;
|
|
285
|
-
readonly columns: readonly ColumnDecl[];
|
|
286
|
-
readonly indexes?: readonly IndexDecl[];
|
|
287
|
-
/** Share policy belongs to the table owner. Missing declarations still refuse nonempty data.
|
|
288
|
-
* Portable columns are explicit so later personal fields cannot silently enter an archive. */
|
|
289
|
-
readonly portability?: {
|
|
290
|
-
readonly kind: "private";
|
|
291
|
-
} | {
|
|
292
|
-
readonly kind: "portable";
|
|
293
|
-
readonly columns: readonly string[];
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
export interface DataModuleDecl {
|
|
297
|
-
readonly pluginId: string;
|
|
298
|
-
/** §3/T6: `dataModule` is scoped to Tier-2/Tier-3 only — a Tier-1 declaration is rejected. */
|
|
299
|
-
readonly pluginTier: PluginTier;
|
|
300
|
-
readonly tables: readonly TableDecl[];
|
|
301
|
-
/** §5/§6/T5 — used by the namespace-adoption guard. */
|
|
302
|
-
readonly provenance: PluginProvenance;
|
|
303
|
-
}
|
|
258
|
+
import type { DataModuleDecl } from "@jini-ai/core/contracts/site/db-data-modules";
|
|
259
|
+
export type { ColumnType, PluginTier, ColumnDecl, IndexDecl, TableDecl, DataModuleDecl } from "@jini-ai/core/contracts/site/db-data-modules";
|
|
304
260
|
export interface DeclareResult {
|
|
305
261
|
readonly ok: boolean;
|
|
306
262
|
/** Fully-qualified names of tables created this call. */
|
|
@@ -1,15 +1,6 @@
|
|
|
1
1
|
import { type PluginStore } from "./plugin-store.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* `_plugin_identity`; they are never updated. Later declares compare all three with strict string
|
|
5
|
-
* equality, so a renamed publisher or moved URL is refused as `consent-required` the next time
|
|
6
|
-
* that plugin has DDL to apply, unless both sides carry the same `signature`.
|
|
7
|
-
*/
|
|
8
|
-
export interface PluginProvenance {
|
|
9
|
-
sourceUrl: string;
|
|
10
|
-
publisher: string;
|
|
11
|
-
signature?: string;
|
|
12
|
-
}
|
|
2
|
+
import type { PluginProvenance } from "@jini-ai/core/contracts/site/db-data-modules";
|
|
3
|
+
export type { PluginProvenance } from "@jini-ai/core/contracts/site/db-data-modules";
|
|
13
4
|
export interface PluginIdentityRecord {
|
|
14
5
|
pluginId: string;
|
|
15
6
|
provenance: PluginProvenance;
|
|
@@ -43,9 +43,11 @@ export declare function snapshotDb(required: {
|
|
|
43
43
|
* it there removes zero recovery capability: the never-brick guarantee covers the window between
|
|
44
44
|
* "snapshot taken" and "DDL committed", and that window has closed.
|
|
45
45
|
*
|
|
46
|
-
* **A failed migration keeps its snapshot**, deliberately — the catch path
|
|
47
|
-
*
|
|
48
|
-
*
|
|
46
|
+
* **A failed migration keeps its snapshot**, deliberately — the catch path marks the entry
|
|
47
|
+
* `ROLLED_BACK` (terminal; see `recordFailurePhase` in `data-module.ts`, which writes `COMMITTED`
|
|
48
|
+
* instead when the DDL had already committed) and never deletes the snapshot file, so §9's
|
|
49
|
+
* operator forensics still has it. The next boot does not restore from it: a terminal entry is not
|
|
50
|
+
* an incomplete journal entry.
|
|
49
51
|
*
|
|
50
52
|
* `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
|
|
51
53
|
* row is history — it says what protected the change at the time, which stays true — so a path
|
|
@@ -80,9 +80,11 @@ export async function snapshotDb(required, _optional = {}) {
|
|
|
80
80
|
* it there removes zero recovery capability: the never-brick guarantee covers the window between
|
|
81
81
|
* "snapshot taken" and "DDL committed", and that window has closed.
|
|
82
82
|
*
|
|
83
|
-
* **A failed migration keeps its snapshot**, deliberately — the catch path
|
|
84
|
-
*
|
|
85
|
-
*
|
|
83
|
+
* **A failed migration keeps its snapshot**, deliberately — the catch path marks the entry
|
|
84
|
+
* `ROLLED_BACK` (terminal; see `recordFailurePhase` in `data-module.ts`, which writes `COMMITTED`
|
|
85
|
+
* instead when the DDL had already committed) and never deletes the snapshot file, so §9's
|
|
86
|
+
* operator forensics still has it. The next boot does not restore from it: a terminal entry is not
|
|
87
|
+
* an incomplete journal entry.
|
|
86
88
|
*
|
|
87
89
|
* `_plugin_migrations.snapshot_path` still records which snapshot guarded each committed DDL. That
|
|
88
90
|
* row is history — it says what protected the change at the time, which stays true — so a path
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Kysely } from "kysely";
|
|
2
2
|
import type { StorageKernel } from "@jini-ai/core/contracts/storage";
|
|
3
|
-
import type {
|
|
3
|
+
import type { AttributedDomainEvent, NewChangeSetRecord, ChangeSetItemRecord, ChangeSetRecord, ChangeSetRepoPort, ChangeSetWithItems } from "@jini-ai/core/contracts/events";
|
|
4
|
+
import { type OutboxEventPreparation } from "./outbox-repo.sql.js";
|
|
5
|
+
import { type ActorKindColumn } from "./repo.rows.js";
|
|
4
6
|
/**
|
|
5
7
|
* @file Phase 1 — THE `ChangeSetRepoPort` adapter: one Kysely query body for every
|
|
6
8
|
* dialect (storage plan). Rule-of-two "second adapter" half;
|
|
@@ -38,21 +40,32 @@ export interface ChangeSetSqlRequired {
|
|
|
38
40
|
kernel: StorageKernel<Kysely<unknown>, unknown>;
|
|
39
41
|
tables: ChangeSetTables;
|
|
40
42
|
}
|
|
41
|
-
|
|
43
|
+
/**
|
|
44
|
+
* `actorKindColumn` (default off): set it only once the host schema has `change_sets.actor_kind`,
|
|
45
|
+
* so a rolling host never selects or inserts a column its database does not have yet.
|
|
46
|
+
*/
|
|
47
|
+
export type ChangeSetSqlOptional = ActorKindColumn;
|
|
42
48
|
export declare class SqlChangeSetRepo implements ChangeSetRepoPort {
|
|
43
49
|
protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
|
|
44
50
|
protected readonly tables: ChangeSetTables;
|
|
45
|
-
|
|
51
|
+
private readonly preparation;
|
|
52
|
+
private readonly columns;
|
|
53
|
+
/**
|
|
54
|
+
* @param optional.actorKindColumn read/write `change_sets.actor_kind` (see `ChangeSetSqlOptional`).
|
|
55
|
+
* @param optional.prepareOutboxEvent host hook preparing the co-persisted event for this repo's one transaction.
|
|
56
|
+
*/
|
|
57
|
+
constructor({ kernel, tables }: ChangeSetSqlRequired, { actorKindColumn, ...preparation }?: ChangeSetSqlOptional & OutboxEventPreparation);
|
|
58
|
+
private read;
|
|
46
59
|
private sets;
|
|
47
60
|
private items;
|
|
48
61
|
/** Header + items + (when supplied) the outbox event land as one atomic transaction — never a
|
|
49
62
|
* partial write (the "transaction participation" requirement, and the
|
|
50
63
|
* resolution for the outbox event specifically; see this file's header). */
|
|
51
64
|
insert({ record, items }: {
|
|
52
|
-
record:
|
|
65
|
+
record: NewChangeSetRecord;
|
|
53
66
|
items: ChangeSetItemRecord[];
|
|
54
67
|
}, { event }?: {
|
|
55
|
-
event?:
|
|
68
|
+
event?: AttributedDomainEvent | undefined;
|
|
56
69
|
}): Promise<void>;
|
|
57
70
|
findById(required: {
|
|
58
71
|
workspaceId: string;
|
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
import { outboxEventValues } from "./outbox-repo.sql.js";
|
|
1
|
+
import { outboxEventValues, preparedOutboxEvent } from "./outbox-repo.sql.js";
|
|
2
2
|
import { toItemRecord, toItemRow, toRecord, toRow, } from "./repo.rows.js";
|
|
3
3
|
export class SqlChangeSetRepo {
|
|
4
4
|
kernel;
|
|
5
5
|
tables;
|
|
6
|
-
|
|
6
|
+
preparation;
|
|
7
|
+
columns;
|
|
8
|
+
/**
|
|
9
|
+
* @param optional.actorKindColumn read/write `change_sets.actor_kind` (see `ChangeSetSqlOptional`).
|
|
10
|
+
* @param optional.prepareOutboxEvent host hook preparing the co-persisted event for this repo's one transaction.
|
|
11
|
+
*/
|
|
12
|
+
constructor({ kernel, tables }, { actorKindColumn = false, ...preparation } = {}) {
|
|
7
13
|
this.kernel = kernel;
|
|
8
14
|
this.tables = tables;
|
|
15
|
+
this.preparation = preparation;
|
|
16
|
+
this.columns = { actorKindColumn };
|
|
17
|
+
}
|
|
18
|
+
read(row) {
|
|
19
|
+
return toRecord(row, this.columns);
|
|
9
20
|
}
|
|
10
21
|
// Host-owned table names need an explicit column schema, as in the settings adapter.
|
|
11
22
|
sets(db) {
|
|
@@ -18,12 +29,18 @@ export class SqlChangeSetRepo {
|
|
|
18
29
|
* partial write (the "transaction participation" requirement, and the
|
|
19
30
|
* resolution for the outbox event specifically; see this file's header). */
|
|
20
31
|
async insert({ record, items }, { event } = {}) {
|
|
32
|
+
// Build every row first so conflicting attribution is refused before the transaction opens.
|
|
33
|
+
if (event && (record.actor.id !== event.actor.id || record.actor.kind !== event.actor.kind || record.actorId !== event.actorId))
|
|
34
|
+
throw new Error("Change-set and event actor attribution must match.");
|
|
35
|
+
const header = toRow(record, this.columns);
|
|
36
|
+
// Preparation preserves the writer's actor while preparing the envelope that is actually stored.
|
|
37
|
+
const eventRow = event ? outboxEventValues(preparedOutboxEvent({ event }, this.preparation)) : undefined;
|
|
21
38
|
await this.kernel.transaction(async () => this.kernel.run(async (db) => {
|
|
22
|
-
await this.sets(db).insertInto(this.tables.changeSets).values(
|
|
39
|
+
await this.sets(db).insertInto(this.tables.changeSets).values(header).execute();
|
|
23
40
|
for (const item of items)
|
|
24
41
|
await this.items(db).insertInto(this.tables.changeSetItems).values(toItemRow(item)).execute();
|
|
25
|
-
if (
|
|
26
|
-
await db.withTables().insertInto(this.tables.outboxEvents).values(
|
|
42
|
+
if (eventRow)
|
|
43
|
+
await db.withTables().insertInto(this.tables.outboxEvents).values(eventRow).execute();
|
|
27
44
|
}));
|
|
28
45
|
}
|
|
29
46
|
async findById(required, _optional = {}) {
|
|
@@ -43,7 +60,7 @@ export class SqlChangeSetRepo {
|
|
|
43
60
|
.where("change_set_id", "=", row.id)
|
|
44
61
|
.orderBy("position")
|
|
45
62
|
.execute();
|
|
46
|
-
return { changeSet:
|
|
63
|
+
return { changeSet: this.read(row), items: itemRows.map(toItemRecord) };
|
|
47
64
|
});
|
|
48
65
|
}
|
|
49
66
|
async findByIdempotencyKey(required, _optional = {}) {
|
|
@@ -54,11 +71,11 @@ export class SqlChangeSetRepo {
|
|
|
54
71
|
.where("idempotency_key", "=", required.idempotencyKey)
|
|
55
72
|
.limit(1)
|
|
56
73
|
.executeTakeFirst());
|
|
57
|
-
return row ?
|
|
74
|
+
return row ? this.read(row) : null;
|
|
58
75
|
}
|
|
59
76
|
async listByWorkspace(required, _optional = {}) {
|
|
60
77
|
const rows = await this.kernel.run((db) => this.sets(db).selectFrom(this.tables.changeSets).selectAll().where("workspace_id", "=", required.workspaceId).orderBy("created_at").execute());
|
|
61
|
-
return rows.map(
|
|
78
|
+
return rows.map((row) => this.read(row));
|
|
62
79
|
}
|
|
63
80
|
async save(record) {
|
|
64
81
|
await this.kernel.run((db) => this.sets(db)
|
package/dist/events/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { SqlChangeSetRepo, type ChangeSetSqlOptional, type ChangeSetSqlRequired, type ChangeSetTables } from "./change-set-repo.sql.js";
|
|
2
|
-
export { SqlOutboxAdapter, outboxEventValues, type OutboxSqlOptional, type OutboxSqlRequired, type OutboxTables } from "./outbox-repo.sql.js";
|
|
2
|
+
export { SqlOutboxAdapter, outboxEventValues, type OutboxEventPreparation, type OutboxSqlOptional, type PrepareOutboxEvent, type OutboxSqlRequired, type OutboxTables } from "./outbox-repo.sql.js";
|
|
3
3
|
export type { ChangeSetItemsTable, ChangeSetsTable, OutboxEventsTable } from "./repo.rows.js";
|
|
4
4
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -33,6 +33,15 @@ export interface OutboxSqlRequired {
|
|
|
33
33
|
claimLeaseMs: number;
|
|
34
34
|
}
|
|
35
35
|
export type OutboxSqlOptional = Record<string, never>;
|
|
36
|
+
/** Host hook returning the envelope to persist (for example with producer trace context in
|
|
37
|
+
* `metadata`). It must return a new envelope rather than modify the one it is given. */
|
|
38
|
+
export type PrepareOutboxEvent = (required: {
|
|
39
|
+
event: DomainEvent;
|
|
40
|
+
}, _optional?: Record<string, never>) => DomainEvent;
|
|
41
|
+
/** Constructor options shared by both outbox writers: the direct enqueue and the co-persisted change-set write. */
|
|
42
|
+
export interface OutboxEventPreparation {
|
|
43
|
+
prepareOutboxEvent?: PrepareOutboxEvent;
|
|
44
|
+
}
|
|
36
45
|
/** The `outbox_events` row for a freshly-produced event (snake_case). Shared by enqueue
|
|
37
46
|
* and transactional callers so an audit event can be inserted atomically with its domain
|
|
38
47
|
* writes, using the identical row shape rather than a copy or an independent enqueue.
|
|
@@ -46,16 +55,32 @@ export declare function outboxEventValues(event: DomainEvent<object>): {
|
|
|
46
55
|
next_attempt_at: string;
|
|
47
56
|
created_at: string;
|
|
48
57
|
};
|
|
58
|
+
/**
|
|
59
|
+
* The envelope an outbox writer serializes, prepared inside the caller's existing write. Correlation
|
|
60
|
+
* is captured here, while the producer is still running, because the asynchronous delivery cannot
|
|
61
|
+
* inherit the producer's request-local state and must not depend on when this transaction commits.
|
|
62
|
+
* The prepared envelope keeps the original's id, workspace and occurrence time, so the dedupe key
|
|
63
|
+
* (`ON CONFLICT (id)`) and the first due time cannot move. A failing or malformed preparation
|
|
64
|
+
* persists the original envelope and the write still succeeds: losing correlation is preferable to
|
|
65
|
+
* losing the event or rolling back the domain write it belongs to.
|
|
66
|
+
* @example const stored = preparedOutboxEvent({ event }, { prepareOutboxEvent });
|
|
67
|
+
* @complexity O(1) beyond the injected hook.
|
|
68
|
+
*/
|
|
69
|
+
export declare function preparedOutboxEvent(required: {
|
|
70
|
+
event: DomainEvent;
|
|
71
|
+
}, optional?: OutboxEventPreparation): DomainEvent;
|
|
49
72
|
export declare class SqlOutboxAdapter implements OutboxPort {
|
|
50
73
|
protected readonly kernel: StorageKernel<Kysely<unknown>, unknown>;
|
|
51
74
|
protected readonly tables: OutboxTables;
|
|
52
75
|
private readonly claimLeaseMs;
|
|
76
|
+
private readonly preparation;
|
|
53
77
|
/**
|
|
54
78
|
* @param required.kernel the database holding the outbox table.
|
|
55
79
|
* @param required.tables.outboxEvents the host's outbox table name.
|
|
56
80
|
* @param required.claimLeaseMs claim lease length.
|
|
81
|
+
* @param optional.prepareOutboxEvent host hook preparing each envelope inside the enqueue write.
|
|
57
82
|
*/
|
|
58
|
-
constructor({ kernel, tables, claimLeaseMs }: OutboxSqlRequired,
|
|
83
|
+
constructor({ kernel, tables, claimLeaseMs }: OutboxSqlRequired, optional?: OutboxEventPreparation);
|
|
59
84
|
/** Host-owned table name needs an explicit column schema, as in the settings adapter. */
|
|
60
85
|
private table;
|
|
61
86
|
/** A repeated `event.id` is a no-op, never a primary-key error: ids are deterministic per event
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertConsistentActor } from "./repo.rows.js";
|
|
1
2
|
function toRecord(row) {
|
|
2
3
|
return {
|
|
3
4
|
id: row.id,
|
|
@@ -24,6 +25,8 @@ const UNSETTLED_STATUSES = ["pending", "processing"];
|
|
|
24
25
|
* writes, using the identical row shape rather than a copy or an independent enqueue.
|
|
25
26
|
*/
|
|
26
27
|
export function outboxEventValues(event) {
|
|
28
|
+
// The actor (id and kind) rides inside the existing `event_json`, so no outbox column is added.
|
|
29
|
+
assertConsistentActor(event);
|
|
27
30
|
return {
|
|
28
31
|
id: event.id,
|
|
29
32
|
workspace_id: event.workspaceId,
|
|
@@ -34,19 +37,50 @@ export function outboxEventValues(event) {
|
|
|
34
37
|
created_at: event.occurredAt,
|
|
35
38
|
};
|
|
36
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* The envelope an outbox writer serializes, prepared inside the caller's existing write. Correlation
|
|
42
|
+
* is captured here, while the producer is still running, because the asynchronous delivery cannot
|
|
43
|
+
* inherit the producer's request-local state and must not depend on when this transaction commits.
|
|
44
|
+
* The prepared envelope keeps the original's id, workspace and occurrence time, so the dedupe key
|
|
45
|
+
* (`ON CONFLICT (id)`) and the first due time cannot move. A failing or malformed preparation
|
|
46
|
+
* persists the original envelope and the write still succeeds: losing correlation is preferable to
|
|
47
|
+
* losing the event or rolling back the domain write it belongs to.
|
|
48
|
+
* @example const stored = preparedOutboxEvent({ event }, { prepareOutboxEvent });
|
|
49
|
+
* @complexity O(1) beyond the injected hook.
|
|
50
|
+
*/
|
|
51
|
+
export function preparedOutboxEvent(required, optional = {}) {
|
|
52
|
+
const { event } = required;
|
|
53
|
+
if (!optional.prepareOutboxEvent)
|
|
54
|
+
return event;
|
|
55
|
+
const { id, workspaceId, occurredAt, actorId } = event;
|
|
56
|
+
const actor = event.actor === undefined ? undefined : { ...event.actor };
|
|
57
|
+
try {
|
|
58
|
+
const prepared = optional.prepareOutboxEvent({ event: { ...event, ...(actor === undefined ? {} : { actor: { ...actor } }) } });
|
|
59
|
+
if (typeof prepared !== "object" || prepared === null)
|
|
60
|
+
return event;
|
|
61
|
+
const { actor: _preparedActor, actorId: _preparedActorId, ...envelope } = prepared;
|
|
62
|
+
return { ...envelope, id, workspaceId, occurredAt, ...(actor === undefined ? {} : { actor }), ...(actorId === undefined ? {} : { actorId }) };
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return event;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
37
68
|
export class SqlOutboxAdapter {
|
|
38
69
|
kernel;
|
|
39
70
|
tables;
|
|
40
71
|
claimLeaseMs;
|
|
72
|
+
preparation;
|
|
41
73
|
/**
|
|
42
74
|
* @param required.kernel the database holding the outbox table.
|
|
43
75
|
* @param required.tables.outboxEvents the host's outbox table name.
|
|
44
76
|
* @param required.claimLeaseMs claim lease length.
|
|
77
|
+
* @param optional.prepareOutboxEvent host hook preparing each envelope inside the enqueue write.
|
|
45
78
|
*/
|
|
46
|
-
constructor({ kernel, tables, claimLeaseMs },
|
|
79
|
+
constructor({ kernel, tables, claimLeaseMs }, optional = {}) {
|
|
47
80
|
this.kernel = kernel;
|
|
48
81
|
this.tables = tables;
|
|
49
82
|
this.claimLeaseMs = claimLeaseMs;
|
|
83
|
+
this.preparation = optional;
|
|
50
84
|
}
|
|
51
85
|
/** Host-owned table name needs an explicit column schema, as in the settings adapter. */
|
|
52
86
|
table(db) {
|
|
@@ -57,7 +91,7 @@ export class SqlOutboxAdapter {
|
|
|
57
91
|
* scheduled go-live), so the same id is the same event, and the post go-live sweep
|
|
58
92
|
* (`features/post/go-live.ts`) relies on this to announce each go-live exactly once. */
|
|
59
93
|
async enqueue(event) {
|
|
60
|
-
await this.kernel.run((db) => this.table(db).insertInto(this.tables.outboxEvents).values(outboxEventValues(event)).onConflict((oc) => oc.column("id").doNothing()).execute());
|
|
94
|
+
await this.kernel.run((db) => this.table(db).insertInto(this.tables.outboxEvents).values(outboxEventValues(preparedOutboxEvent({ event }, this.preparation))).onConflict((oc) => oc.column("id").doNothing()).execute());
|
|
61
95
|
}
|
|
62
96
|
/** Selects due rows (pending, or processing under an expired claim lease) and marks them
|
|
63
97
|
* `processing` under a fresh lease in one kernel transaction — the select-then-update is never
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Generated, Insertable, Selectable } from "kysely";
|
|
2
|
-
import type { ChangeSetItemRecord, ChangeSetRecord } from "@jini-ai/core/contracts/events";
|
|
2
|
+
import type { ChangeSetItemRecord, ChangeSetRecord, MutationActor } from "@jini-ai/core/contracts/events";
|
|
3
3
|
/** Stored column shapes, copied without schema changes; the table names are host-owned (see `ChangeSetTables`, `OutboxTables`). */
|
|
4
4
|
export interface ChangeSetItemsTable {
|
|
5
5
|
id: string;
|
|
@@ -17,6 +17,8 @@ export interface ChangeSetsTable {
|
|
|
17
17
|
id: string;
|
|
18
18
|
workspace_id: string;
|
|
19
19
|
actor_id: string | null;
|
|
20
|
+
/** Present only once the host has migrated; read and written only under `ActorKindColumn`. */
|
|
21
|
+
actor_kind?: string | null;
|
|
20
22
|
status: string;
|
|
21
23
|
summary: string;
|
|
22
24
|
idempotency_key: string | null;
|
|
@@ -35,10 +37,26 @@ export interface OutboxEventsTable {
|
|
|
35
37
|
last_error: string | null;
|
|
36
38
|
created_at: string;
|
|
37
39
|
}
|
|
38
|
-
|
|
40
|
+
/** Whether the host's `change_sets` table has the `actor_kind` column yet; off means it is never named. */
|
|
41
|
+
export interface ActorKindColumn {
|
|
42
|
+
actorKindColumn?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Refuses a record or event whose compatibility `actorId` names someone other than its `actor`,
|
|
46
|
+
* so the two attribution fields can never be persisted disagreeing.
|
|
47
|
+
*
|
|
48
|
+
* @param required - The record or event's `actorId` and `actor`.
|
|
49
|
+
* @throws {Error} When both are present and the ids differ.
|
|
50
|
+
* @complexity O(1).
|
|
51
|
+
*/
|
|
52
|
+
export declare function assertConsistentActor({ actorId, actor }: {
|
|
53
|
+
actorId?: string | undefined;
|
|
54
|
+
actor?: MutationActor | undefined;
|
|
55
|
+
}, _optional?: Record<string, never>): void;
|
|
56
|
+
export declare function toRecord(row: Selectable<ChangeSetsTable>, options?: ActorKindColumn): ChangeSetRecord;
|
|
39
57
|
export declare function toItemRecord(row: Selectable<ChangeSetItemsTable>): ChangeSetItemRecord;
|
|
40
|
-
/** `toRecord`'s inverse: every absent optional field is written as SQL NULL
|
|
41
|
-
export declare function toRow(record: ChangeSetRecord): Insertable<ChangeSetsTable>;
|
|
58
|
+
/** `toRecord`'s inverse: every absent optional field is written as SQL NULL; `actor_kind` only under `ActorKindColumn`. */
|
|
59
|
+
export declare function toRow(record: ChangeSetRecord, options?: ActorKindColumn): Insertable<ChangeSetsTable>;
|
|
42
60
|
/** `toItemRecord`'s inverse: absent optionals as SQL NULL, the inverse payload as JSON text. */
|
|
43
61
|
export declare function toItemRow(item: ChangeSetItemRecord): Insertable<ChangeSetItemsTable>;
|
|
44
62
|
//# sourceMappingURL=repo.rows.d.ts.map
|
package/dist/events/repo.rows.js
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
|
-
|
|
1
|
+
const ACTOR_KINDS = new Set(["user", "agent", "system"]);
|
|
2
|
+
/**
|
|
3
|
+
* Refuses a record or event whose compatibility `actorId` names someone other than its `actor`,
|
|
4
|
+
* so the two attribution fields can never be persisted disagreeing.
|
|
5
|
+
*
|
|
6
|
+
* @param required - The record or event's `actorId` and `actor`.
|
|
7
|
+
* @throws {Error} When both are present and the ids differ.
|
|
8
|
+
* @complexity O(1).
|
|
9
|
+
*/
|
|
10
|
+
export function assertConsistentActor({ actorId, actor }, _optional = {}) {
|
|
11
|
+
if (actor && actorId !== undefined && actorId !== actor.id) {
|
|
12
|
+
throw new Error("The actor id does not match the recorded actor; refusing to write conflicting attribution.");
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** The stored provenance as an actor, or nothing: a missing or unrecognised kind is unknown, never guessed. */
|
|
16
|
+
function storedActor(row, { actorKindColumn = false }) {
|
|
17
|
+
const kind = actorKindColumn ? row.actor_kind : null;
|
|
18
|
+
if (!row.actor_id || !kind || !ACTOR_KINDS.has(kind))
|
|
19
|
+
return {};
|
|
20
|
+
return { actor: { id: row.actor_id, kind: kind } };
|
|
21
|
+
}
|
|
22
|
+
export function toRecord(row, options = {}) {
|
|
2
23
|
return {
|
|
24
|
+
...storedActor(row, options),
|
|
3
25
|
id: row.id,
|
|
4
26
|
workspaceId: row.workspace_id,
|
|
5
27
|
actorId: row.actor_id ?? undefined,
|
|
@@ -26,12 +48,18 @@ export function toItemRecord(row) {
|
|
|
26
48
|
position: row.position,
|
|
27
49
|
};
|
|
28
50
|
}
|
|
29
|
-
/**
|
|
30
|
-
|
|
51
|
+
/** The attribution columns of a record, refusing conflicting ids; `actor_kind` is named only under `ActorKindColumn`. */
|
|
52
|
+
function actorColumns(record, { actorKindColumn = false }) {
|
|
53
|
+
assertConsistentActor(record);
|
|
54
|
+
const actorId = record.actorId ?? record.actor?.id ?? null;
|
|
55
|
+
return actorKindColumn ? { actor_id: actorId, actor_kind: record.actor?.kind ?? null } : { actor_id: actorId };
|
|
56
|
+
}
|
|
57
|
+
/** `toRecord`'s inverse: every absent optional field is written as SQL NULL; `actor_kind` only under `ActorKindColumn`. */
|
|
58
|
+
export function toRow(record, options = {}) {
|
|
31
59
|
return {
|
|
60
|
+
...actorColumns(record, options),
|
|
32
61
|
id: record.id,
|
|
33
62
|
workspace_id: record.workspaceId,
|
|
34
|
-
actor_id: record.actorId ?? null,
|
|
35
63
|
status: record.status,
|
|
36
64
|
summary: record.summary,
|
|
37
65
|
idempotency_key: record.idempotencyKey ?? null,
|