@pramen/server 0.0.59 → 0.0.60

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.
@@ -0,0 +1,256 @@
1
+ // Data migrations — the imperative, recorded half of schema evolution.
2
+ //
3
+ // `migrate()` (runtime/migrate.ts) is declarative: it diffs the live table shape against
4
+ // the declared schema and enacts the structural delta. A diff between two SHAPES can only
5
+ // ever express structure, never TRANSFORMATION — it cannot split `name` into
6
+ // `firstName`/`lastName`, backfill the nullable column `ADD COLUMN` just created (SQLite
7
+ // can't add NOT NULL to a populated table, so every new column starts as a hole), rewrite
8
+ // `priceHalers` → `priceCzk`, or normalize a `t.json()` blob whose shape changed.
9
+ //
10
+ // So: structure stays declarative, data becomes imperative, ordered, and RECORDED. Each
11
+ // `app.migrations` entry runs at most once per `(id, partition)`, its ledger row written in
12
+ // `_pramen_migrations` in the SAME transaction as the work. That is what makes a
13
+ // non-idempotent transformation safe, and it is precisely why `app.bootstrap` cannot be
14
+ // stretched to cover this (bootstrap runs on EVERY boot, must be idempotent, and swallows
15
+ // its errors).
16
+ //
17
+ // Fail closed. A throwing migration records no ledger row, does not let the boot complete,
18
+ // and propagates — the tenant's request fails and the migration is retried on the next
19
+ // fetch. This mirrors migrate()'s "withhold the schema hash on a skip" invariant: the store
20
+ // is never marked as having reached a state it did not reach.
21
+ //
22
+ // CLAIM FIRST, UNDER A LEASE. The ledger row is taken BEFORE the work — one atomic upsert
23
+ // that inserts a pending row, or steals one whose lease has expired, or does nothing — and
24
+ // the migration runs only if that statement won the row. On the DO this is merely bookkeeping
25
+ // order inside one transaction. On D1 it is what makes the once-only contract hold at all:
26
+ // there is no single writer and no interactive transaction, `d1Ready` is per-isolate, so two
27
+ // cold isolates racing a `SET n = n * 2` backfill would each read an empty ledger, each run
28
+ // it, and quadruple the data. The conflicting upsert is the lock.
29
+ //
30
+ // The row therefore has two states, distinguished by `leaseUntil`: IN FLIGHT (non-NULL — a
31
+ // runner holds it until that instant) and APPLIED (NULL). Only an applied row counts as
32
+ // applied, so an in-flight migration reads as pending everywhere, including the admin ledger.
33
+ //
34
+ // A runner that finds a LIVE lease does not skip — skipping would let it serve traffic
35
+ // against half-migrated data, and would strand the migration entirely if the holder then
36
+ // failed. It waits for the holder, up to WAIT_BUDGET_MS, and then either proceeds (the holder
37
+ // committed), takes the row (the holder released it), or fails closed. A holder that dies
38
+ // without releasing — an isolate evicted mid-backfill, which no compensating DELETE can
39
+ // cover — is recovered by the lease simply expiring.
40
+ //
41
+ // Written against the `Driver`/`Dialect` seam only (no `cloudflare:workers`), so the same
42
+ // runner drives the DO boot path and the D1/Worker path.
43
+ import { DEFAULT_PARTITION, partitionsOf } from "../sdk/schema";
44
+ export const MIGRATIONS_TABLE = "_pramen_migrations";
45
+ /** Create the ledger if absent. Idempotent — run on every boot before the runner and from
46
+ * the /__migrations endpoint (a DO that has never applied one still answers). Internal
47
+ * table (`_pramen_` prefix), so `isInternalTable()` keeps the migrator's hands off it.
48
+ *
49
+ * `partition` is a reserved-ish word in some engines, so every identifier goes through
50
+ * `dialect.id(...)` (the single `quoteIdent` source of truth) rather than being interpolated
51
+ * bare — here and in every query below. */
52
+ export async function ensureMigrationsTable(driver) {
53
+ const d = driver.dialect;
54
+ const t = d.id(MIGRATIONS_TABLE);
55
+ await driver.exec(`CREATE TABLE IF NOT EXISTS ${t} (` +
56
+ `${d.id("id")} TEXT NOT NULL, ${d.id("partition")} TEXT NOT NULL, ${d.id("appliedAt")} TEXT NOT NULL, ` +
57
+ `${d.id("leaseUntil")} INTEGER, PRIMARY KEY (${d.id("id")}, ${d.id("partition")}))`, []);
58
+ // `leaseUntil` was added after the table's first shape. Probe for it with a zero-row SELECT
59
+ // rather than PRAGMA table_info: the PRAGMA is what workerd's DO SQLite authorizer starts
60
+ // rejecting (SQLITE_AUTH) once the alarm API has run in the object, and this runs on every
61
+ // boot. Adding a nullable column is a plain ALTER — no rebuild, and existing rows read as
62
+ // applied, which is what they are.
63
+ const hasLease = await driver
64
+ .exec(`SELECT ${d.id("leaseUntil")} FROM ${t} LIMIT 0`, [])
65
+ .then(() => true)
66
+ .catch(() => false);
67
+ if (!hasLease)
68
+ await driver.exec(`ALTER TABLE ${t} ADD COLUMN ${d.id("leaseUntil")} INTEGER`, []);
69
+ }
70
+ /** Ledger rows for one partition — or every partition when `partition` is omitted (the D1
71
+ * store, which holds one shared ledger for all of them). Oldest first. */
72
+ export async function appliedMigrations(driver, partition) {
73
+ const d = driver.dialect;
74
+ // `leaseUntil IS NULL` is the definition of applied: a row a runner is still holding is
75
+ // in flight, and must read as PENDING everywhere — the admin ledger and the CLI included.
76
+ const scope = partition === undefined ? "" : ` AND ${d.id("partition")} = ${d.placeholder(1)}`;
77
+ const where = ` WHERE ${d.id("leaseUntil")} IS NULL${scope}`;
78
+ const rows = await driver.exec(`SELECT ${d.id("id")}, ${d.id("partition")}, ${d.id("appliedAt")} FROM ${d.id(MIGRATIONS_TABLE)}${where} ` +
79
+ `ORDER BY ${d.id("appliedAt")}, ${d.id("id")}`, partition === undefined ? [] : [d.encode(partition)]);
80
+ return rows.map((r) => ({ id: String(r.id), partition: String(r.partition), appliedAt: String(r.appliedAt) }));
81
+ }
82
+ /** The migrations that belong to `partition`: an entry with no declared partition belongs
83
+ * to the default one. Both boot paths select through this, so "which partition owns this
84
+ * migration" is answered in exactly one place. */
85
+ export function migrationsForPartition(migrations, partition) {
86
+ return migrations.filter((m) => (m.partition ?? DEFAULT_PARTITION) === partition);
87
+ }
88
+ export const DEFAULT_LEASE = { ttlMs: 60_000, waitMs: 5_000, pollMs: 100 };
89
+ /** Run every pending migration, in DECLARATION order, each inside its own
90
+ * `driver.transaction()`, CLAIMING its ledger row before it runs the work — so "the work
91
+ * happened" and "the work is recorded" cannot come apart on a substrate with real
92
+ * transactions (the DO), and cannot double-run on one without (D1). A migration whose claim
93
+ * loses the race (another isolate holds it, or a previous boot applied it) is skipped.
94
+ *
95
+ * D1 CAVEAT: `D1Driver.transaction(fn)` is `fn()` (D1 has no interactive transactions), so
96
+ * there the claim and the work do NOT commit together. A throw therefore RELEASES the claim
97
+ * explicitly (a compensating DELETE, issued inside the transaction so the DO simply rolls it
98
+ * back with everything else) — otherwise a failed migration would stay marked as applied,
99
+ * which is the one outcome the fail-closed contract exists to prevent. A holder that dies
100
+ * without reaching that DELETE is covered by the lease expiring instead. Prefer SQL that
101
+ * tolerates a re-run (`WHERE col IS NULL`) when the D1 store is in play: a mid-flight failure
102
+ * leaves the partial writes behind.
103
+ *
104
+ * Fails CLOSED: the first throw aborts the run, so migrations declared after it do not run
105
+ * either (order is a contract — a later one may depend on an earlier one's output). */
106
+ export async function runDataMigrations(driver, migrations, opts) {
107
+ const applied = [];
108
+ const skipped = [];
109
+ const pending = opts.partition === undefined ? migrations : migrationsForPartition(migrations, opts.partition);
110
+ if (pending.length === 0)
111
+ return { applied, skipped };
112
+ const lease = { ...DEFAULT_LEASE, ...opts.lease };
113
+ await ensureMigrationsTable(driver);
114
+ const done = new Set((await appliedMigrations(driver, opts.partition)).map((r) => ledgerKey(r.id, r.partition)));
115
+ for (const m of pending) {
116
+ const partition = m.partition ?? DEFAULT_PARTITION;
117
+ // The cheap pre-check: skip without opening a transaction for what a previous boot
118
+ // already applied (the common case — every boot after the first). `claim` is what
119
+ // actually decides; this only keeps the steady state free of no-op transactions.
120
+ if (done.has(ledgerKey(m.id, partition))) {
121
+ skipped.push(m.id);
122
+ continue;
123
+ }
124
+ let ran = false;
125
+ try {
126
+ await driver.transaction(async () => {
127
+ // Take the row, waiting out any live lease. "applied" means another runner finished
128
+ // it while we waited — nothing left to do, and we now know the data IS migrated.
129
+ if ((await acquire(driver, m.id, partition, lease)) === "applied")
130
+ return;
131
+ ran = true;
132
+ try {
133
+ await m.up(opts.makeContext(partition));
134
+ await complete(driver, m.id, partition);
135
+ }
136
+ catch (e) {
137
+ await release(driver, m.id, partition); // no-op on the DO (rolled back anyway)
138
+ throw e;
139
+ }
140
+ });
141
+ }
142
+ catch (e) {
143
+ // Name the migration in the message: the raw SQL error alone gives no clue WHICH of
144
+ // an ordered list failed, and the boot it aborted is the tenant's first request.
145
+ throw new Error(`[pramen] data migration ${JSON.stringify(m.id)} failed (partition=${partition}): ` +
146
+ `${e instanceof Error ? e.message : String(e)}`, { cause: e });
147
+ }
148
+ if (!ran) {
149
+ skipped.push(m.id);
150
+ continue;
151
+ }
152
+ console.log(`[pramen] data migration ${JSON.stringify(m.id)} applied (partition=${partition})`);
153
+ applied.push(m.id);
154
+ }
155
+ return { applied, skipped };
156
+ }
157
+ /** The ledger is keyed by (id, partition) — the same reason the schema hash is
158
+ * `schema_hash:<partition>`: partitions are independent DOs and must not thrash each
159
+ * other's state. NUL-joined, so no (id, partition) pair can collide with another. */
160
+ const ledgerKey = (id, partition) => `${id}\u0000${partition}`;
161
+ /** ONE atomic statement that does all three things a claim must: insert the row when the
162
+ * migration is pending, STEAL it when a previous holder's lease has expired (that holder is
163
+ * presumed dead — an isolate evicted mid-backfill releases nothing), and do nothing when the
164
+ * row is applied or a live lease holds it. `RETURNING` fires only when a row was actually
165
+ * written, so it reports which happened. The upsert's `WHERE` is what confines the steal to
166
+ * an expired lease: without it this would be a plain overwrite and two live runners would
167
+ * both "win". */
168
+ async function tryClaim(driver, id, partition, now, ttlMs) {
169
+ const d = driver.dialect;
170
+ const t = d.id(MIGRATIONS_TABLE);
171
+ const params = [id, partition, new Date(now).toISOString(), now + ttlMs, now];
172
+ const rows = await driver.exec(`INSERT INTO ${t} (${d.id("id")}, ${d.id("partition")}, ${d.id("appliedAt")}, ${d.id("leaseUntil")}) ` +
173
+ `VALUES (${d.placeholder(1)}, ${d.placeholder(2)}, ${d.placeholder(3)}, ${d.placeholder(4)}) ` +
174
+ `ON CONFLICT (${d.id("id")}, ${d.id("partition")}) DO UPDATE SET ` +
175
+ `${d.id("appliedAt")} = excluded.${d.id("appliedAt")}, ${d.id("leaseUntil")} = excluded.${d.id("leaseUntil")} ` +
176
+ `WHERE ${t}.${d.id("leaseUntil")} IS NOT NULL AND ${t}.${d.id("leaseUntil")} <= ${d.placeholder(5)} ` +
177
+ `RETURNING ${d.id("id")}`, params.map((v) => d.encode(v)));
178
+ if (rows.length > 0)
179
+ return "claimed";
180
+ // Nothing written — so the row exists and we did not qualify. Which of the two is it?
181
+ const [row] = await driver.exec(`SELECT ${d.id("leaseUntil")} FROM ${t} WHERE ${d.id("id")} = ${d.placeholder(1)} AND ${d.id("partition")} = ${d.placeholder(2)}`, [id, partition].map((v) => d.encode(v)));
182
+ // Gone between the two statements (a holder released it) — contended, not applied.
183
+ if (!row)
184
+ return "held";
185
+ return row.leaseUntil == null ? "applied" : "held";
186
+ }
187
+ /** Take the row, waiting out a live lease. Returns "applied" when someone else finished it
188
+ * while we waited — in which case the caller must NOT run the migration, but CAN proceed
189
+ * knowing the data is migrated. That distinction is the point: skipping a live lease outright
190
+ * (the previous behavior) let a runner serve traffic against half-migrated data, and stranded
191
+ * the migration on that isolate entirely if the holder then failed.
192
+ *
193
+ * On the DO this never waits — one Durable Object is a single writer and the migration runs
194
+ * inside `blockConcurrencyWhile`, so a second concurrent first-fetch is queued by the platform
195
+ * rather than contending here. The wait exists for D1, where nothing serializes isolates. */
196
+ async function acquire(driver, id, partition, lease) {
197
+ const deadline = Date.now() + lease.waitMs;
198
+ for (;;) {
199
+ const outcome = await tryClaim(driver, id, partition, Date.now(), lease.ttlMs);
200
+ if (outcome !== "held")
201
+ return outcome;
202
+ if (Date.now() >= deadline) {
203
+ // Fail closed rather than guess. Another runner is mid-flight; the request retries and
204
+ // will usually find it applied. Serving on through a migration we know is unfinished is
205
+ // the one thing that must not happen.
206
+ throw new Error(`another runner holds the lease and did not finish within ${lease.waitMs}ms`);
207
+ }
208
+ await new Promise((r) => setTimeout(r, lease.pollMs));
209
+ }
210
+ }
211
+ /** Mark the migration applied: drop the lease (NULL is the definition of applied) and stamp
212
+ * the instant the work actually committed rather than the one the claim was taken. */
213
+ async function complete(driver, id, partition) {
214
+ const d = driver.dialect;
215
+ await driver.exec(`UPDATE ${d.id(MIGRATIONS_TABLE)} SET ${d.id("appliedAt")} = ${d.placeholder(1)}, ${d.id("leaseUntil")} = NULL ` +
216
+ `WHERE ${d.id("id")} = ${d.placeholder(2)} AND ${d.id("partition")} = ${d.placeholder(3)}`, [new Date().toISOString(), id, partition].map((v) => d.encode(v)));
217
+ }
218
+ /** Give the claim back after a failed `up()`, so the next runner retries immediately instead
219
+ * of waiting out the lease. Only observable where `transaction()` does not roll back (D1); on
220
+ * the DO the enclosing transaction discards this along with the claim itself. Guarded on
221
+ * `leaseUntil IS NOT NULL` so it can only ever delete an IN-FLIGHT row — never an applied one,
222
+ * whatever else has happened to the ledger in between. */
223
+ async function release(driver, id, partition) {
224
+ const d = driver.dialect;
225
+ await driver.exec(`DELETE FROM ${d.id(MIGRATIONS_TABLE)} WHERE ${d.id("id")} = ${d.placeholder(1)} AND ${d.id("partition")} = ${d.placeholder(2)} ` +
226
+ `AND ${d.id("leaseUntil")} IS NOT NULL`, [id, partition].map((v) => d.encode(v)));
227
+ }
228
+ /** Static validation, called from `createPramen` next to `validateTriggerTasks` — these are
229
+ * declaration bugs, and the only honest time to surface them is before a single tenant has
230
+ * booted. Throws on the first violation:
231
+ *
232
+ * - an empty id (the ledger key would be meaningless);
233
+ * - a duplicate id — ids are GLOBALLY unique across the array, not per partition, so a
234
+ * copy-pasted id can never quietly mark a different migration as already applied;
235
+ * - a declared `partition` no entity lives in — the migration would be dead code on the
236
+ * DO path (no DO serves that partition) while still running on D1. */
237
+ export function validateMigrations(schema, migrations) {
238
+ if (!migrations?.length)
239
+ return;
240
+ const known = new Set(partitionsOf(schema));
241
+ known.add(DEFAULT_PARTITION); // always addressable, even for a schema with no entities
242
+ const seen = new Set();
243
+ for (const m of migrations) {
244
+ if (!m.id)
245
+ throw new Error("app.migrations: every migration needs a non-empty, stable `id` (it is the ledger key).");
246
+ if (seen.has(m.id)) {
247
+ throw new Error(`app.migrations: duplicate id ${JSON.stringify(m.id)}. Ids are the ledger key and must be globally ` +
248
+ `unique — a reused id makes one of the two silently a no-op.`);
249
+ }
250
+ seen.add(m.id);
251
+ if (m.partition !== undefined && !known.has(m.partition)) {
252
+ throw new Error(`app.migrations: migration ${JSON.stringify(m.id)} declares partition ${JSON.stringify(m.partition)}, ` +
253
+ `which no entity lives in. Known partitions: ${[...known].join(", ")}.`);
254
+ }
255
+ }
256
+ }
package/dist/sdk/acl.d.ts CHANGED
@@ -44,11 +44,19 @@ export interface NowMarker {
44
44
  * future timestamp is non-null, so a scheduled row would be readable the moment it
45
45
  * is saved.
46
46
  *
47
- * Comparison is lexicographic TEXT, which is exact for ISO-8601 UTC but NOT
48
- * cross-format: `expr.now()` defaults store `'YYYY-MM-DD HH:MM:SS'` (space, no `Z`)
49
- * and will not compare correctly against this. Store the column with
50
- * `toISOString()` as the CMS `publish` field does or compare it against
51
- * `expr.now()`-shaped values only. */
47
+ * Comparison is lexicographic TEXT, which is exact WITHIN one format and wrong across two.
48
+ * Both `'YYYY-MM-DD HH:MM:SS'` and the ISO form open with the same date, so values on
49
+ * different dates still order correctly it is the SAME date that breaks, where index 10
50
+ * decides and a space (0x20) always sorts below `T` (0x54). A space-form value dated today
51
+ * therefore compares as less than this marker whatever its time-of-day, so a row scheduled
52
+ * for later today reads as already past. The column must hold ISO-8601 UTC —
53
+ * `new Date().toISOString()`.
54
+ *
55
+ * `expr.now()` produces exactly that, so a column defaulted with it is directly comparable
56
+ * here. It did NOT always: it emitted the `datetime('now')` space form, and a policy over
57
+ * such a column was a time boundary that silently did not hold. A store written by a build
58
+ * from before that change still holds space-form values until
59
+ * `isoTimestampBackfill()` rewrites them. */
52
60
  export declare function $now(): NowMarker;
53
61
  export declare function isNowMarker(v: WhereValue): v is NowMarker;
54
62
  export interface AllowMarker {
package/dist/sdk/acl.js CHANGED
@@ -40,11 +40,19 @@ const NOW_MARKER = Symbol.for("pramen.nowMarker");
40
40
  * future timestamp is non-null, so a scheduled row would be readable the moment it
41
41
  * is saved.
42
42
  *
43
- * Comparison is lexicographic TEXT, which is exact for ISO-8601 UTC but NOT
44
- * cross-format: `expr.now()` defaults store `'YYYY-MM-DD HH:MM:SS'` (space, no `Z`)
45
- * and will not compare correctly against this. Store the column with
46
- * `toISOString()` as the CMS `publish` field does or compare it against
47
- * `expr.now()`-shaped values only. */
43
+ * Comparison is lexicographic TEXT, which is exact WITHIN one format and wrong across two.
44
+ * Both `'YYYY-MM-DD HH:MM:SS'` and the ISO form open with the same date, so values on
45
+ * different dates still order correctly it is the SAME date that breaks, where index 10
46
+ * decides and a space (0x20) always sorts below `T` (0x54). A space-form value dated today
47
+ * therefore compares as less than this marker whatever its time-of-day, so a row scheduled
48
+ * for later today reads as already past. The column must hold ISO-8601 UTC —
49
+ * `new Date().toISOString()`.
50
+ *
51
+ * `expr.now()` produces exactly that, so a column defaulted with it is directly comparable
52
+ * here. It did NOT always: it emitted the `datetime('now')` space form, and a policy over
53
+ * such a column was a time boundary that silently did not hold. A store written by a build
54
+ * from before that change still holds space-form values until
55
+ * `isoTimestampBackfill()` rewrites them. */
48
56
  export function $now() {
49
57
  return { [NOW_MARKER]: true };
50
58
  }
@@ -73,6 +73,47 @@ export interface BootstrapContext<S extends SchemaDef = SchemaDef> {
73
73
  * blind-insert. A thrown error is logged and swallowed so a broken reconcile can't brick a
74
74
  * tenant's boot; it simply retries on the next boot. Set as `app.bootstrap`. */
75
75
  export type BootstrapFn = (ctx: BootstrapContext) => void | Promise<void>;
76
+ /** Context handed to a data migration's `up()`. Same privileged, SYSTEM-scoped shape as
77
+ * `BootstrapContext` (ACL bypassed, triggers suppressed) but scoped to the migration's
78
+ * own `partition` — each partition-DO runs its own partition's migrations, so `db`/`driver`
79
+ * here address exactly that DO's tables. */
80
+ export interface MigrationContext<S extends SchemaDef = SchemaDef> {
81
+ /** System-scoped Db (ACL bypassed), triggers suppressed, scoped to `partition`. */
82
+ readonly db: Db<S>;
83
+ /** Raw driver — a bulk `UPDATE`/`INSERT … SELECT` is usually the right tool for a
84
+ * backfill; going row-by-row through `db` on a large table is what blows the DO's
85
+ * wall-clock budget. */
86
+ readonly driver: Driver;
87
+ readonly schema: S;
88
+ /** The partition this migration is running (and being recorded) under. */
89
+ readonly partition: string;
90
+ }
91
+ /** One imperative, ORDERED, recorded-once transformation of existing DATA — the half a
92
+ * declarative diff cannot express: split a column, backfill the nullable column `ADD COLUMN`
93
+ * just created, rewrite units, normalize a `t.json()` blob after its shape changed.
94
+ *
95
+ * The deliberate inverse of `BootstrapFn` on every axis that matters: it runs ONCE ever
96
+ * (recorded in `_pramen_migrations` keyed by `(id, partition)`), so it need NOT be
97
+ * idempotent — a backfill that would double a value on a second run is exactly what this
98
+ * exists for; and a throw is NOT swallowed. It fails CLOSED: no ledger row, the boot does
99
+ * not complete, the request fails, and the migration is retried on the tenant's next fetch.
100
+ * Silently marking a half-finished backfill as done is the one outcome worth bricking a
101
+ * boot to avoid.
102
+ *
103
+ * Runs after `migrate()` (so the column exists) and before `app.bootstrap`. There are no
104
+ * DOWN migrations. Set as `app.migrations`. */
105
+ export interface DataMigration {
106
+ /** Stable, unique, never reused — this is the ledger key. Deleting an id from the array
107
+ * does NOT un-apply it; and a cold tenant is unmigrated until touched, so an id can only
108
+ * be pruned once EVERY live tenant reports it applied (`pramen migrations status
109
+ * --all-tenants`). */
110
+ id: string;
111
+ /** Restrict to one partition; default = the default partition. Only that partition's DO
112
+ * runs it (its tables live in no other DO). The D1 store is one shared database with no
113
+ * partition split, so there every migration runs — still recorded under this key. */
114
+ partition?: string;
115
+ up(ctx: MigrationContext): void | Promise<void>;
116
+ }
76
117
  /** The deferred-side-effects facade handed to handlers as `ctx.tasks`. */
77
118
  export interface Tasks {
78
119
  /** Enqueue a task to run after commit. `kind` selects the `app.tasks` handler;
@@ -0,0 +1,54 @@
1
+ import type { DataMigration } from "./handlers";
2
+ import type { SchemaDef } from "./schema";
3
+ /** The old default's SQL, for recognizing a column that carried it. */
4
+ export declare const LEGACY_NOW_SQL = "datetime('now')";
5
+ /** Columns to rewrite beyond the ones the schema identifies, as `{ table: [column, …] }`.
6
+ *
7
+ * The schema can only find columns whose DEFAULT is `expr.now()`. A column written by
8
+ * HANDLER code in the same space form — `@pramen/cms` stamped `cms_pages.publishedAt` that
9
+ * way — has no marker on it at all, so the app has to name it. `@pramen/cms` exports its
10
+ * own set as `CMS_LEGACY_TIMESTAMP_COLUMNS`. */
11
+ export type ExtraTimestampColumns = Readonly<Record<string, readonly string[]>>;
12
+ export interface IsoTimestampBackfillOpts {
13
+ /** Ledger id. Defaults to `pramen:iso-timestamps`. Override only if you have already
14
+ * used that id for something else — it is the key that makes this run once. */
15
+ id?: string;
16
+ /** Partition to run in. A partition-DO only sees its own tables, so an app with several
17
+ * partitions declares one of these per partition, each with its own id. */
18
+ partition?: string;
19
+ /** Columns the schema cannot identify — see {@link ExtraTimestampColumns}. */
20
+ extraColumns?: ExtraTimestampColumns;
21
+ }
22
+ /**
23
+ * A `DataMigration` that rewrites space-form timestamps to ISO-8601 in place.
24
+ *
25
+ * ```ts
26
+ * import { isoTimestampBackfill } from "@pramen/server";
27
+ * import { CMS_LEGACY_TIMESTAMP_COLUMNS } from "@pramen/cms";
28
+ *
29
+ * export const app = {
30
+ * migrations: [isoTimestampBackfill({ extraColumns: CMS_LEGACY_TIMESTAMP_COLUMNS })],
31
+ * // …
32
+ * };
33
+ * ```
34
+ *
35
+ * A **new** deployment can declare it too and pay nothing: every `UPDATE` matches no rows.
36
+ * Declaring it unconditionally is the cheaper habit, because "was this store ever written
37
+ * by an older build?" is not a question the code can answer later.
38
+ *
39
+ * It is not idempotent-by-accident, it is idempotent-by-shape: the `WHERE` matches only the
40
+ * space form, and what it writes is not the space form. That matters because a data
41
+ * migration is not required to be idempotent (it is recorded once) but this one runs over
42
+ * columns an app may also be writing, and a second pass must not corrupt a converted value.
43
+ */
44
+ export declare function isoTimestampBackfill(opts?: IsoTimestampBackfillOpts): DataMigration;
45
+ /**
46
+ * Which `(table, column)` pairs this migration touches — the schema's `expr.now()` columns
47
+ * in `partition`, plus whatever the app named.
48
+ *
49
+ * Exported for the tests and for anyone who wants to see the list before running it. An
50
+ * extra column naming a table or column that is not in the schema is IGNORED rather than
51
+ * throwing: the list is a hand-written constant an app may keep across a schema change, and
52
+ * failing the whole boot over a stale entry in it would be a worse outcome than skipping it.
53
+ */
54
+ export declare function timestampColumns(schema: SchemaDef, partition?: string, extra?: ExtraTimestampColumns): Map<string, string[]>;
@@ -0,0 +1,119 @@
1
+ // Rewriting timestamps written before `expr.now()` emitted ISO-8601.
2
+ //
3
+ // `expr.now()` used to emit `datetime('now')` — the `CURRENT_TIMESTAMP` space form,
4
+ // `'2026-09-03 21:33:07'`. It now emits `'2026-09-03T21:33:07.222Z'`. Changing a column's
5
+ // DEFAULT is a MODIFIER change, so `migrate()` rebuilds the table — and a rebuild copies
6
+ // existing values through untouched. New rows would get the new shape and old rows would
7
+ // keep the old one, in the same column.
8
+ //
9
+ // That is worse than either format alone, and the failure is narrower and nastier than
10
+ // "the column is inconsistent". Both forms open with the same `YYYY-MM-DD`, so for values
11
+ // on DIFFERENT dates the date prefix decides and ordering is still correct. It is values on
12
+ // the SAME date that break: index 10 is ` ` (0x20) in the space form and `T` (0x54) in ISO,
13
+ // so a same-day space-form value always sorts BEFORE a same-day ISO one whatever the
14
+ // time-of-day — 23:00 in the old shape sorts below 01:00 in the new.
15
+ //
16
+ // Which makes the deploy window itself the blast radius: the rows written just before and
17
+ // just after the change are exactly the same-day pairs that invert. And a `{ lte: $now() }`
18
+ // policy is the sharp version, because `$now()` is ISO: a space-form value dated today
19
+ // always compares as less than it, so a row scheduled for later TODAY reads as already
20
+ // published until midnight. Nothing reports any of it.
21
+ //
22
+ // So the format change comes with a rewrite, and the rewrite is a DATA migration: it is
23
+ // imperative, it must run exactly once, and it must fail closed. Declaring it is the app's
24
+ // job — this builds it.
25
+ import { DEFAULT_PARTITION, ISO_NOW_SQL, entitiesInPartition } from "./schema";
26
+ /** The old default's SQL, for recognizing a column that carried it. */
27
+ export const LEGACY_NOW_SQL = "datetime('now')";
28
+ /**
29
+ * A `DataMigration` that rewrites space-form timestamps to ISO-8601 in place.
30
+ *
31
+ * ```ts
32
+ * import { isoTimestampBackfill } from "@pramen/server";
33
+ * import { CMS_LEGACY_TIMESTAMP_COLUMNS } from "@pramen/cms";
34
+ *
35
+ * export const app = {
36
+ * migrations: [isoTimestampBackfill({ extraColumns: CMS_LEGACY_TIMESTAMP_COLUMNS })],
37
+ * // …
38
+ * };
39
+ * ```
40
+ *
41
+ * A **new** deployment can declare it too and pay nothing: every `UPDATE` matches no rows.
42
+ * Declaring it unconditionally is the cheaper habit, because "was this store ever written
43
+ * by an older build?" is not a question the code can answer later.
44
+ *
45
+ * It is not idempotent-by-accident, it is idempotent-by-shape: the `WHERE` matches only the
46
+ * space form, and what it writes is not the space form. That matters because a data
47
+ * migration is not required to be idempotent (it is recorded once) but this one runs over
48
+ * columns an app may also be writing, and a second pass must not corrupt a converted value.
49
+ */
50
+ export function isoTimestampBackfill(opts = {}) {
51
+ const partition = opts.partition ?? DEFAULT_PARTITION;
52
+ return {
53
+ id: opts.id ?? "pramen:iso-timestamps",
54
+ partition,
55
+ async up(ctx) {
56
+ for (const [table, columns] of timestampColumns(ctx.schema, partition, opts.extraColumns)) {
57
+ for (const column of columns) {
58
+ // A bulk UPDATE, not a walk: this runs inside `blockConcurrencyWhile` on a
59
+ // tenant's first fetch, so a row-by-row rewrite of a large table is what stalls
60
+ // that request and risks the DO's wall-clock limit.
61
+ //
62
+ // The predicate is deliberately exact rather than "does not look like ISO":
63
+ // length 19 with a space at index 11 (SQLite's `substr` is 1-based) is the space
64
+ // form and nothing else. A column holding some third format an app wrote by hand
65
+ // is left alone, because guessing at it would be a silent rewrite of data this
66
+ // migration does not understand.
67
+ await ctx.driver.exec(`UPDATE ${q(table)} SET ${q(column)} = replace(${q(column)}, ' ', 'T') || '.000Z' ` +
68
+ `WHERE ${q(column)} IS NOT NULL AND length(${q(column)}) = 19 AND substr(${q(column)}, 11, 1) = ' '`, []);
69
+ }
70
+ }
71
+ },
72
+ };
73
+ }
74
+ /**
75
+ * Which `(table, column)` pairs this migration touches — the schema's `expr.now()` columns
76
+ * in `partition`, plus whatever the app named.
77
+ *
78
+ * Exported for the tests and for anyone who wants to see the list before running it. An
79
+ * extra column naming a table or column that is not in the schema is IGNORED rather than
80
+ * throwing: the list is a hand-written constant an app may keep across a schema change, and
81
+ * failing the whole boot over a stale entry in it would be a worse outcome than skipping it.
82
+ */
83
+ export function timestampColumns(schema, partition = DEFAULT_PARTITION, extra = {}) {
84
+ const out = new Map();
85
+ const inPartition = new Set(entitiesInPartition(schema, partition));
86
+ for (const table of inPartition) {
87
+ const fields = schema[table]?.fields;
88
+ if (!fields)
89
+ continue;
90
+ const cols = Object.entries(fields)
91
+ // Both spellings: a store written by an older build has the legacy default recorded
92
+ // in its own DDL, and `migrate()` may not have rebuilt the table yet when this runs
93
+ // (it does — migrations run after — but the check costs nothing and makes the set
94
+ // independent of that ordering).
95
+ .filter(([, f]) => f.defaultExpr === ISO_NOW_SQL || f.defaultExpr === LEGACY_NOW_SQL)
96
+ .map(([name]) => name);
97
+ if (cols.length > 0)
98
+ out.set(table, cols);
99
+ }
100
+ for (const [table, columns] of Object.entries(extra)) {
101
+ if (!inPartition.has(table))
102
+ continue;
103
+ const fields = schema[table]?.fields;
104
+ if (!fields)
105
+ continue;
106
+ const existing = out.get(table) ?? [];
107
+ for (const column of columns) {
108
+ if (fields[column] && !existing.includes(column))
109
+ existing.push(column);
110
+ }
111
+ if (existing.length > 0)
112
+ out.set(table, existing);
113
+ }
114
+ return out;
115
+ }
116
+ /** Double-quote an identifier for SQLite. Table and column names here come from the app's
117
+ * own schema, never from a request — but the SQL is built by concatenation, so they are
118
+ * quoted rather than trusted to be quote-free. */
119
+ const q = (ident) => `"${ident.replace(/"/g, '""')}"`;
@@ -242,9 +242,45 @@ export declare class ExprDefault {
242
242
  readonly sql: string;
243
243
  constructor(sql: string);
244
244
  }
245
- /** SQL-expression defaults for `defaultTo(field, expr.now())`. `now()` is the current
246
- * UTC timestamp as TEXT (`'YYYY-MM-DD HH:MM:SS'`, like `CURRENT_TIMESTAMP`) pair it
247
- * with `t.text()`. `raw(sql)` is an escape hatch for any other SQLite default expression. */
245
+ /**
246
+ * The SQL `expr.now()` emits: the current UTC instant as **ISO-8601 TEXT with
247
+ * milliseconds and a `Z`** `'2026-09-03T21:33:07.222Z'`, byte-for-byte what
248
+ * `new Date().toISOString()` produces.
249
+ *
250
+ * Exported because three things have to agree on it and none of them can see the others:
251
+ * the DDL that writes the default, {@link isoTimestampBackfill} which rewrites rows
252
+ * written before this format, and the migration diff that decides a column's DEFAULT
253
+ * changed at all.
254
+ */
255
+ export declare const ISO_NOW_SQL = "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
256
+ /**
257
+ * SQL-expression defaults for `defaultTo(field, expr.now())`.
258
+ *
259
+ * `now()` is the current UTC instant as ISO-8601 TEXT (`'2026-09-03T21:33:07.222Z'`) —
260
+ * pair it with `t.text()`.
261
+ *
262
+ * **It used to emit `datetime('now')`**, the `CURRENT_TIMESTAMP` space form
263
+ * (`'2026-09-03 21:33:07'`). That form is wrong for this codebase in two ways that both
264
+ * fail silently:
265
+ *
266
+ * - It does not compare against `$now()`, which is an ISO string. Lexicographic TEXT
267
+ * comparison is exact within one format and wrong across two: both open with
268
+ * `YYYY-MM-DD`, so values on different dates still order correctly, but on the SAME
269
+ * date index 10 decides — a space (0x20) always sorts below `T` (0x54), whatever the
270
+ * time-of-day. So `{ publishedAt: { lte: $now() } }` over a space-form column matches
271
+ * any row dated today, including one scheduled for later today. A time boundary that
272
+ * silently does not hold, for a day at a time.
273
+ * - It is second-resolution, so two writes in the same second are indistinguishable and
274
+ * `ORDER BY createdAt` falls back to an arbitrary tiebreak. `%f` gives milliseconds.
275
+ *
276
+ * Changing it means a column's stored values change shape, so **existing rows must be
277
+ * rewritten** — a rebuild copies values through untouched and would leave the two formats
278
+ * mixed in one column, which is worse than either alone. {@link isoTimestampBackfill} is
279
+ * that rewrite; declare it in `app.migrations`.
280
+ *
281
+ * `raw(sql)` remains the escape hatch for any other SQLite default expression, including
282
+ * `expr.raw("datetime('now')")` if you deliberately want the old shape.
283
+ */
248
284
  export declare const expr: {
249
285
  now: () => ExprDefault;
250
286
  raw: (sql: string) => ExprDefault;
@@ -112,11 +112,47 @@ export class ExprDefault {
112
112
  this.sql = sql;
113
113
  }
114
114
  }
115
- /** SQL-expression defaults for `defaultTo(field, expr.now())`. `now()` is the current
116
- * UTC timestamp as TEXT (`'YYYY-MM-DD HH:MM:SS'`, like `CURRENT_TIMESTAMP`) pair it
117
- * with `t.text()`. `raw(sql)` is an escape hatch for any other SQLite default expression. */
115
+ /**
116
+ * The SQL `expr.now()` emits: the current UTC instant as **ISO-8601 TEXT with
117
+ * milliseconds and a `Z`** `'2026-09-03T21:33:07.222Z'`, byte-for-byte what
118
+ * `new Date().toISOString()` produces.
119
+ *
120
+ * Exported because three things have to agree on it and none of them can see the others:
121
+ * the DDL that writes the default, {@link isoTimestampBackfill} which rewrites rows
122
+ * written before this format, and the migration diff that decides a column's DEFAULT
123
+ * changed at all.
124
+ */
125
+ export const ISO_NOW_SQL = "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
126
+ /**
127
+ * SQL-expression defaults for `defaultTo(field, expr.now())`.
128
+ *
129
+ * `now()` is the current UTC instant as ISO-8601 TEXT (`'2026-09-03T21:33:07.222Z'`) —
130
+ * pair it with `t.text()`.
131
+ *
132
+ * **It used to emit `datetime('now')`**, the `CURRENT_TIMESTAMP` space form
133
+ * (`'2026-09-03 21:33:07'`). That form is wrong for this codebase in two ways that both
134
+ * fail silently:
135
+ *
136
+ * - It does not compare against `$now()`, which is an ISO string. Lexicographic TEXT
137
+ * comparison is exact within one format and wrong across two: both open with
138
+ * `YYYY-MM-DD`, so values on different dates still order correctly, but on the SAME
139
+ * date index 10 decides — a space (0x20) always sorts below `T` (0x54), whatever the
140
+ * time-of-day. So `{ publishedAt: { lte: $now() } }` over a space-form column matches
141
+ * any row dated today, including one scheduled for later today. A time boundary that
142
+ * silently does not hold, for a day at a time.
143
+ * - It is second-resolution, so two writes in the same second are indistinguishable and
144
+ * `ORDER BY createdAt` falls back to an arbitrary tiebreak. `%f` gives milliseconds.
145
+ *
146
+ * Changing it means a column's stored values change shape, so **existing rows must be
147
+ * rewritten** — a rebuild copies values through untouched and would leave the two formats
148
+ * mixed in one column, which is worse than either alone. {@link isoTimestampBackfill} is
149
+ * that rewrite; declare it in `app.migrations`.
150
+ *
151
+ * `raw(sql)` remains the escape hatch for any other SQLite default expression, including
152
+ * `expr.raw("datetime('now')")` if you deliberately want the old shape.
153
+ */
118
154
  export const expr = {
119
- now: () => new ExprDefault("datetime('now')"),
155
+ now: () => new ExprDefault(ISO_NOW_SQL),
120
156
  raw: (sql) => new ExprDefault(sql),
121
157
  };
122
158
  export function defaultTo(field, value) {