Storage (packages/storage, packages/storage-sqlite)
Durable state for the remote modes: users, instances, credentials, workspaces, grants, device tokens, the audit log,
settings and short-lived kv records (ADR-0006,
ARCHITECTURE §4). stdio keeps no database.
| Piece | Where | Runtime |
|---|---|---|
Storage interface, records, errors |
packages/storage/src/types.ts, errors.ts |
web |
| Column rules shared by every adapter | packages/storage/src/fields.ts, kv-rules.ts |
web |
| Drizzle schema (SQLite dialect) | packages/storage/src/schema.ts |
web |
| Embedded migrations and the runner | packages/storage/src/migrations/, sql/migrate.ts |
web |
SQL implementation over a SqlDriver |
packages/storage/src/sql/storage.ts |
web |
memory adapter |
packages/storage/src/memory.ts |
web |
| Read-only view | packages/storage/src/read-only.ts |
web |
node:sqlite driver |
packages/storage-sqlite/src/driver.ts |
Node |
| D1 driver | P3-02 | Workers |
Repository semantics
Section titled “Repository semantics”Every adapter behaves identically, and the contract suite (packages/storage/test/contract.ts) proves it: the memory
adapter runs it in packages/storage, the SQLite one in packages/storage-sqlite, D1 joins in P3-02.
| Situation | Result |
|---|---|
get / getBy… of a missing row |
null |
update / delete of a missing row |
NotFoundError |
| A duplicate id or unique value (email, IdP identity, instance URL, slug, token hash) | ConflictError |
| Deleting a row that others still reference | ConflictError (“revoke or disable it instead”) |
| A bad value, an unknown or fixed field, a missing parent, a cross-row rule | InvalidInputError |
A write through readOnlyStorage(…) |
ReadOnlyStorageError |
| A database newer than the binary, or with a different migration history | MigrationError |
All of them extend StorageError (with a code). Messages name tables and columns, never values.
- Ids are generated by the caller;
createdAtandupdatedAtcome from the storage clock (now, injectable). - Records are copies: changing a returned object changes nothing stored.
- Fixed after creation (not patchable): ids, a credential’s instance, owner and secret material, a workspace’s
instance, a grant’s workspace and user, a token’s grant, hash and
lastUsedAt(written only bytouch). - Lists of ids and tools are JSON arrays of 1–256-character strings (at most 1,000); objects are JSON objects of at most 64 KiB; labels at most 200 characters without control characters.
Cross-row rules (ADR-0008)
Section titled “Cross-row rules (ADR-0008)”Enforced by triggers in SQL, so raw SQL writers are held to them too, and mirrored by the memory adapter:
-
A workspace’s default credential is a shared credential of the workspace’s instance.
-
A grant’s credential belongs to the workspace’s instance and is shared or the grant user’s own; a service grant (no user, label required) can only use shared credentials (L-065).
-
An instance’s
baseUrlandtlscannot change while it has credentials that are not revoked (THREAT_MODEL A14). -
audit_logrows are never updated (THREAT_MODEL T17); retention deletes whole rows. Reads are keyset pages (querywithafter, newest first, 1,000 rows at most) andstats, one aggregate over at most the newestSTATS_SCAN_CAP(10,000)tool_callrows of a window (L-097; no OFFSET, no index beyond(ts, id)and(workspace_id, ts, id): an index costs a written row per audit append, D-37). -
Device tokens are read in keyset pages too:
accessTokens.page({ grantIds?, after?, limit }), newest first by(createdAt, id)over theaccess_tokens_createdindex (migration 0002, P4-31).grantIdsnarrows to some grants (the SQL adapters query it in chunks of 50 because D1 binds at most 100 values per statement and merge the chunks); the admin API asks forlimit + 1rows to know whether a next page exists and loads only the grants on the page. -
A credential validation is recorded with
credentials.recordValidation(id, expectedSealedToken, patch): one conditionalUPDATE ... WHERE id = ? AND token_ciphertext = ? AND token_iv = ? AND key_version = ?,falsewhen the token was replaced or re-encrypted since it was checked (P4-37, THREAT_MODEL T14, A5). Only the validation fields can be set.
Deletion rules
Section titled “Deletion rules”| Delete | Effect |
|---|---|
| workspace | removes its grants and their device tokens |
| grant | removes its device tokens |
| credential | refused while a grant or a workspace default uses it |
| instance | refused while credentials or workspaces use it |
| user | refused while they own credentials or have grants |
Audit rows have no foreign keys and outlive what they describe.
Opaque string values with an optional absolute expiry (epoch ms); expired entries read as absent and are removed by
purgeExpired. Keys are 1–512 printable ASCII characters without spaces.
| Operation | Atomic guarantee |
|---|---|
setIfAbsent(key, value) |
of concurrent callers, exactly one stores (an expired entry counts as absent) |
take(key) |
of concurrent callers, exactly one gets the value (L-073); an expired entry is removed and not returned |
increment(key, { by, max, expiresAt }) |
no lost updates; refused (null) when the result would pass max; expiresAt applies to a new or restarted counter |
Conditional writes (L-072, L-161)
Section titled “Conditional writes (L-072, L-161)”Every conditional write is one statement whose outcome is read from its RETURNING rows: UPDATE … WHERE … RETURNING, INSERT … ON CONFLICT DO UPDATE … WHERE … RETURNING, DELETE … RETURNING. Never read-decide-write in
application code, and never decide on driver change counters (D1 counts cascaded rows, node:sqlite does not). The
memory adapter performs each operation without an await between its read and its write.
Bind integers in SQL arithmetic with CAST(? AS INTEGER): node:sqlite binds JavaScript numbers as REAL, so
value + ? turns '2' into '3.0' (L-173).
Migrations (L-071)
Section titled “Migrations (L-071)”-
Embedded TypeScript modules in
packages/storage/src/migrations/, one SQL statement per array entry (D1 batches cannot split scripts; triggers contain semicolons). The DDL is written by hand: STRICT tables, CHECK constraints and triggers are beyond Drizzle’s generator.packages/storage-sqlite/test/sqlite.test.tschecks that the migrated columns matchschema.tsexactly. -
migrate(driver)(andopenSqlStorage, which migrates first) applies each pending migration with itsschema_migrationsrow in one batch: all or nothing. Two processes migrating at once end on the same history. -
Refused: a database with a version newer than the binary, a gap, or a checksum that differs (SHA-256 over version, name and statements). Released checksums are frozen in
packages/storage/test/migrations.test.ts: fix a mistake with a new migration, never by editing a released one. -
Database fixtures: one SQL dump per released minor in
packages/storage-sqlite/test/fixtures/databases/(synthetic rows in every table), loaded, migrated and exercised byfixtures.test.ts. Before a minor that changes the schema is released, generate its fixture once and never regenerate it:Terminal window pnpm storage:fixture 0.30.2.sqlis the first; until v0.2.0 ships it may be regenerated together with migration 0001.
Adding a migration
Section titled “Adding a migration”- Add
src/migrations/NNNN-name.tswith the next version and append it toMIGRATIONS. - Update
schema.ts, the records intypes.tsand the rules infields.ts, then both adapters; add contract tests. - Add its checksum to
FROZENonce the release that ships it is cut. - Keep D1 limits in mind (P0-09): no interactive transactions, 100 bound parameters per statement.
D1 on Cloudflare Workers (createD1Driver)
Section titled “D1 on Cloudflare Workers (createD1Driver)”createD1Driver(binding) (packages/storage/src/sql/d1.ts, P3-01/P3-02) is the SqlDriver over a D1 binding; the
Worker opens storage with openSqlStorage(createD1Driver(env.DB)), which migrates at the first request.
- Statements run with
prepare(sql).bind(…); rows come back as arrays (raw()), likenode:sqlite’ssetReturnArrays. Booleans bind as0/1,undefinedasNULL. D1 enforces foreign keys itself. batch()is D1’s atomic batch. Rows read in a batch come back as objects and are turned into arrays in column order, so a batched SELECT must not repeat a column name (single-table SELECTs, as in the access bundle).- Errors carry SQLite’s text (with a
D1_ERROR:prefix and a: SQLITE_…suffix);classifySqlErrormaps them likenode:sqlite’s. - Tested: the whole contract suite runs on local D1 (
apps/worker/test/d1-contract.test.ts, Miniflare’s binding driven from Node, an empty database per test), plus concurrent first boots of one database (one history, no error) and the refusal of a newer database.
Access bundle — accessTokens.bundleByHash(hash) returns the token and the grant, workspace, user, instance and
credential its access reads (the grant’s credential or the workspace default), null for whatever is missing. On SQL
it is one batch() of six single-table SELECTs keyed by subqueries on the token hash: one D1 round trip instead of four
sequential ones on every access-cache miss. The contract suite checks it equals the sequential reads, revoked,
disabled and missing rows included.
SQLite on Node (packages/storage-sqlite)
Section titled “SQLite on Node (packages/storage-sqlite)”openSqliteStorage({ path, now?, busyTimeoutMs?, onWarning? }) opens the database of agility-bridge serve and
migrates it (ADR-0006, L-076):
- The directory is created with mode
0700(parents too); an existing one writable by others produces a warning throughonWarning, because whoever can write there can swap files. - The file is created with
O_CREAT | O_EXCL | O_NOFOLLOWand mode0600. An existing file is opened withO_NOFOLLOW, must be a regular file, and is tightened to0600through the opened handle (fchmod). A symbolic link, dangling or not, is refused (UnsafeFileError) and its target is left untouched. node:sqlitecannot open withO_NOFOLLOW, so after SQLite opens the path the adapter checks that it still names the file it checked (same device and inode, not a link) before using it.- WAL mode (
synchronous = NORMAL), a busy timeout (default 5 s) and foreign keys on. SQLite creates the-waland-shmfiles with the database’s mode, so they are0600too (tested). createSqliteDriver(db)wraps one connection: foreign keys on (refused if that fails), cached prepared statements, values only as bound parameters, batches asBEGIN IMMEDIATE … COMMITrolled back on any error.
Backups — storage.backup(target) writes a consistent copy with VACUUM INTO while the server keeps running, into
a new file created exclusively with mode 0600 (directory 0700). An existing target or a symbolic link is refused;
a failed backup removes its partial file.
Restore — restoreSqliteBackup(backup, target) checks the backup (SQLite integrity check, an agility-bridge
database, not written by a newer release) and copies it into a new 0600 file; it never overwrites. Stop the server,
restore to a new path, point AB_DB_PATH at it (or move it into place) and start: the open migrates it. Backups made
by backup are self-contained (no -wal file to copy).
Permission and symbolic-link tests run on Linux and macOS; Windows runs the rest, including the contract suite on a real file (L-104).
agility-bridge is an unofficial, community project. It is not affiliated with, endorsed by, or supported by Digital.ai. Digital.ai, Agility and VersionOne are trademarks of their respective owners.