@rexezuge/d1 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/BaseDAO.d.ts CHANGED
@@ -83,11 +83,26 @@ declare abstract class BaseDAO {
83
83
  protected readonly meter: SubrequestMeter;
84
84
  private readonly options;
85
85
  /**
86
+ * Public, and deliberately so.
87
+ *
88
+ * A composition root instantiates concrete DAOs directly — that is the whole
89
+ * point of a DI container, which binds `() => new UserDAO(db)` rather than
90
+ * handing the container a factory that hides the construction. A `protected`
91
+ * constructor blocks that and buys nothing: the class is `abstract`, so nobody
92
+ * can instantiate `BaseDAO` itself regardless, and the access modifier
93
+ * prevented exactly zero illegal constructions while forcing every concrete
94
+ * DAO to redeclare a pass-through constructor that added no invariant.
95
+ *
96
+ * It was `protected` to keep `database` from being reached as
97
+ * `BaseDAO.database` — but every field below carries its own `protected`, so
98
+ * the field's own modifier is what enforces that, and making the constructor
99
+ * public does not weaken it.
100
+ *
86
101
  * @param database The binding.
87
102
  * @param meter The invocation's subrequest counter, or an unmetered default.
88
103
  * @param options `billedRowsForTable` supplies the schema's write cost.
89
104
  */
90
- protected constructor(database: D1Queryable, meter?: SubrequestMeter, options?: {
105
+ constructor(database: D1Queryable, meter?: SubrequestMeter, options?: {
91
106
  billedRowsForTable?: BilledRowsForTable;
92
107
  });
93
108
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"BaseDAO.d.ts","sourceRoot":"","sources":["../src/BaseDAO.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,EAAE,iBAAiB,EAAoB,MAAM,cAAc,CAAC;AACnE,OAAO,KAAK,EAAE,mBAAmB,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAU/E;;;;;;;;;GASG;AACH,UAAU,gBAAgB;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE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AC,YAAY;IAOpB;;;;;OAKG;qBACoB,eAAe,CACpC,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC;IAsBlB;;MAEE;IACF,SAAS,CAAC,MAAM,KAAK,aAAa,IAAI,OAAO,iBAAiB,CAE7D;CACF;AAED;;;;GAIG;AACH,iBAAS,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAI/D;AAMD;;;;;;;;;;GAUG;AACH,iBAAS,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqBlD;AAUD,OAAO,EAAE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,WAAW,EAAE,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/BaseDAO.ts"],
4
- "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { SubrequestBudgetExhaustedError } from '@rexezuge/errors';\nimport { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * A prepared statement with the SQL that produced it.\n *\n * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that\n * needs to know *what* it is about to run — to account for a write, to assert a\n * table's billing multiplier, to log a rejected statement in terms a reader can\n * act on — has nowhere to read it from. Carrying it beside the statement is\n * that place, and `bind()` returns a new pair for the same reason the platform's\n * does: bindings are immutable on a prepared statement.\n */\ninterface TrackedStatement {\n sql: string;\n statement: D1PreparedStatement;\n bind(...bindings: unknown[]): TrackedStatement;\n}\n\n/**\n * How many rows a write to `table` costs.\n *\n * A **port, not an implementation**, because the answer is a property of the\n * schema rather than of this layer: D1 bills a write as the table row *plus\n * every index entry it rewrote*, so the multiplier belongs to whoever owns the\n * migrations. This package owns the accounting *shape* — carrying the figure\n * beside `changes` on every write result — and the consumer supplies the table.\n *\n * Returning `null` means \"I do not know this table\", which is a different answer\n * from \"this costs one row\" and must not collapse into it: an unknown table\n * errs toward the worst case, because an under-count costs the outage.\n */\ntype BilledRowsForTable = (table: string, logicalRows: number) => number | null;\n\n/**\n * What a write cost, and what it changed.\n *\n * `changes` is progress — how many table rows the statement touched — and\n * `billedRows` is cost. They are not the same number and neither replaces the\n * other: `changes` is what a convergence test measures, `billedRows` is what a\n * daily-allowance budget must be spent against. A caller that reads only\n * `changes` believes it has roughly an order of magnitude more headroom than it\n * does on an indexed table.\n *\n * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}\n * port is configured, so the type forces the caller to notice that nothing is\n * being accounted rather than reporting a confident `0`.\n */\ninterface WriteResult {\n changes: number;\n billedRows: number | null;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * ### Every statement is charged\n *\n * D1 counts its own queries against the Workers per-invocation subrequest\n * ceiling, so a statement that spends one without telling anybody makes every\n * number that budgets work wrong — and it has **no symptom** until the platform\n * terminates the invocation, by which point the rows were right and the suite\n * was green. The meter is therefore a constructor dependency rather than a\n * module singleton, and the charge happens here because this is the one path\n * every statement takes; a charge at each call site is a hundred chances to\n * forget one.\n *\n * The charge is **per logical statement, not per attempt**: a retried statement\n * is one statement that the platform refused once and then answered. Charging\n * per attempt would make the ceiling track the fault rate instead of the work.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one\n * classifier, one place the `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n /**\n * @param database The binding.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param options `billedRowsForTable` supplies the schema's write cost.\n */\n protected constructor(\n protected readonly database: D1Queryable,\n protected readonly meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n private readonly options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {}\n\n /**\n * The invocation's meter, for a DAO that constructs another DAO.\n *\n * A `protected get` rather than a public field, because handing the meter out\n * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`\n * drops it, and the charge that goes missing has no symptom.\n */\n protected get subrequests(): SubrequestMeter {\n return this.meter;\n }\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * The same statement, carrying the SQL beside it.\n *\n * Use this wherever the SQL matters downstream — a write whose cost is\n * accounted, a statement named in an error — and {@link statement} for reads,\n * where nothing reads the SQL back and the pair is one allocation of waste.\n */\n protected tracked(sql: string, bindings: unknown[] = []): TrackedStatement {\n const make = (prepared: D1PreparedStatement): TrackedStatement => ({\n sql,\n statement: prepared,\n bind: (...next: unknown[]): TrackedStatement => make(prepared.bind(...next)),\n });\n return make(this.statement(sql, bindings));\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n this.meter.charge(1, 'd1');\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n Read one row. A `null` result is \"no row\", a success, not an error; only a\n rejected statement is retried and normalized.\n\n `null` rather than `undefined` because that is what the platform says\n (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n what it was given. It also makes this layer agree with `KvCache`, which has\n always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n this.meter.charge(1, 'd1');\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Run one write and report what it cost.\n *\n * Takes a {@link TrackedStatement} rather than SQL because the cost is read off\n * the table the SQL names, and the SQL is only available if it was carried.\n * `billedRows` is `null` when no port is configured.\n */\n protected async runTracked(tracked: TrackedStatement): Promise<WriteResult> {\n const result = await executeWithRetry((): Promise<D1Result> => tracked.statement.run(), 'run a write');\n return this.accountWrite(tracked.sql, result);\n }\n\n /**\n * Run a batch of writes and report what the whole batch cost.\n *\n * Billed rows are **summed across the batch**, and an unaccountable statement\n * poisons the total to `null` rather than being skipped: a partial figure next\n * to a real one is the one that reads as complete.\n */\n protected async runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult> {\n const results = await this.batch(tracked.map((entry) => entry.statement));\n let billedRows = 0;\n let accounted = this.options.billedRowsForTable !== undefined;\n for (const [index, result] of results.entries()) {\n const entry = tracked[index];\n if (!entry) {\n accounted = false;\n break;\n }\n const one = this.accountWrite(entry.sql, result);\n if (one.billedRows === null) {\n accounted = false;\n break;\n }\n billedRows += one.billedRows;\n }\n const changes = results.reduce((total, result) => total + changesOf(result), 0);\n return { changes, billedRows: accounted ? billedRows : null };\n }\n\n /**\n * The writes these statements fit into the invocation's remaining budget.\n *\n * \"How many may I issue\", as distinct from {@link assertSubrequestBudget}'s\n * \"may I issue all of these\" — a caller truncating a work list needs the\n * number, and a caller that must not truncate needs the refusal. An unmetered\n * counter answers `Infinity`, so a deployment that does not meter is never\n * clamped by a budget it does not have.\n */\n protected fitToSubrequestBudget(requested: number): number {\n const remaining = this.meter.remaining;\n return Number.isFinite(remaining) ? Math.max(0, Math.min(requested, Math.floor(remaining))) : Math.max(0, requested);\n }\n\n /**\n * Refuse a set of statements the invocation's remaining budget cannot carry.\n *\n * For a write with no partial form — a play queue, a playlist's count, a\n * backfill — because half a queue is a _shorter_ queue, which is a wrong\n * answer rather than an unfinished one. A caller that may truncate uses\n * {@link fitToSubrequestBudget} instead and reports that it did.\n *\n * @param statements How many statements the work needs.\n * @param context Named in the refusal, because this reaches a client as a 413.\n */\n protected assertSubrequestBudget(statements: number, context = 'this request'): void {\n if (this.meter.canAfford(statements)) return;\n throw new SubrequestBudgetExhaustedError(\n `${context} needs ${statements} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`,\n );\n }\n\n /**\n * Charge the meter and account a completed write against the schema's cost.\n */\n private accountWrite(sql: string, result: D1Result): WriteResult {\n const changes = changesOf(result);\n const port = this.options.billedRowsForTable;\n if (!port) return { changes, billedRows: null };\n return { changes, billedRows: port(statementTable(sql) ?? '', changes) };\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nfunction changesOf(result: D1Result): number {\n return (result.meta as { changes?: number })?.changes ?? 0;\n}\n\n/**\n * The write verb's table name, or `null` when the SQL does not name one.\n *\n * The verb is anchored at the **start** of the statement, after leading\n * whitespace and comments — a bare `/\\bINSERT\\s+INTO\\s+(\\w+)/` also matches a\n * verb quoted inside a string literal, and a table read out of a `SELECT`'s\n * projection is worse than no answer at all. An unreadable statement returns\n * `null` for the caller to charge the worst case against, rather than throwing:\n * accounting must not be the thing that turns a failed write into a crashed\n * request.\n */\nfunction statementTable(sql: string): string | null {\n if (typeof sql !== 'string') return null;\n let rest = sql.replace(/^\\s+/, '');\n // A `while` rather than a repeated strip: comments are the only noise, and a\n // bounded loop cannot be made quadratic by a statement full of them.\n while (rest.startsWith('--')) {\n const newline = rest.indexOf('\\n');\n if (newline === -1) return null;\n rest = rest.slice(newline + 1).replace(/^\\s+/, '');\n }\n const verb = /^(?:INSERT|REPLACE|UPDATE|DELETE)\\b/i.exec(rest);\n if (!verb) return null;\n rest = consume(rest.slice(verb[0].length));\n\n // `INSERT OR REPLACE`, `UPDATE OR IGNORE` — a conflict clause between the verb and\n // the table. This is why the parse is stepwise rather than one anchored pattern:\n // a single pattern either grows a nested quantifier the complexity gate rejects,\n // or drops the clause and reads `REPLACE` as a table name.\n rest = consume(rest, /^(?:OR\\s+[A-Z_]+\\s+)?/i);\n rest = consume(rest, /^(?:INTO\\s+|FROM\\s+)?/i);\n return /^[\"`[]?([A-Z_]\\w*)/i.exec(rest)?.[1] ?? null;\n}\n\n/**\n * Drop a leading match and the whitespace after it.\n */\nfunction consume(sql: string, pattern?: RegExp): string {\n const matched = pattern?.exec(sql)?.[0] ?? '';\n return sql.slice(matched.length).replace(/^\\s+/, '');\n}\n\nexport { BaseDAO, assertSqlIdentifier, statementTable };\nexport type { BilledRowsForTable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5B,MAAM,IAAI,MAAM,6BAA6BC,CAAK,KAAK,KAAK,UAAUD,CAAK,CAAC,EAAE,CAElF,CAJSlC,EAAAiC,EAAA,uBAMT,SAASb,EAAUR,EAAgB,CACjC,OAAQA,EAAO,MAA+B,SAAW,CAC3D,CAFSZ,EAAAoB,EAAA,aAeT,SAASM,EAAetB,EAAW,CACjC,GAAI,OAAOA,GAAQ,SAAU,OAAO,KACpC,IAAIgC,EAAOhC,EAAI,QAAQ,OAAQ,EAAE,EAGjC,KAAOgC,EAAK,WAAW,IAAI,GAAG,CAC5B,MAAMC,EAAUD,EAAK,QAAQ;CAAI,EACjC,GAAIC,IAAY,GAAI,OAAO,KAC3BD,EAAOA,EAAK,MAAMC,EAAU,CAAC,EAAE,QAAQ,OAAQ,EAAE,CACnD,CACA,MAAMC,EAAO,uCAAuC,KAAKF,CAAI,EAC7D,OAAKE,GACLF,EAAOG,EAAQH,EAAK,MAAME,EAAK,CAAC,EAAE,MAAM,CAAC,EAMzCF,EAAOG,EAAQH,EAAM,wBAAwB,EAC7CA,EAAOG,EAAQH,EAAM,wBAAwB,EACtC,sBAAsB,KAAKA,CAAI,IAAI,CAAC,GAAK,MAT9B,IAUpB,CArBSpC,EAAA0B,EAAA,kBA0BT,SAASa,EAAQnC,EAAaoC,EAAgB,CAC5C,MAAMC,EAAUD,GAAS,KAAKpC,CAAG,IAAI,CAAC,GAAK,GAC3C,OAAOA,EAAI,MAAMqC,EAAQ,MAAM,EAAE,QAAQ,OAAQ,EAAE,CACrD,CAHSzC,EAAAuC,EAAA",
4
+ "sourcesContent": ["import { UNMETERED_SUBREQUESTS } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { SubrequestBudgetExhaustedError } from '@rexezuge/errors';\nimport { DatabaseError } from '@rexezuge/errors';\nimport { D1_RETRY_DEFAULTS, executeWithRetry } from './D1Retry.ts';\nimport type { D1PreparedStatement, D1Queryable, D1Result } from './D1Types.ts';\n\n/**\n * A statement result plus the payload it produced, so the retry engine (which\n * inspects `success`) also handles wrapped results like batch arrays.\n */\ninterface StatementEnvelope<T> extends D1Result {\n value: T;\n}\n\n/**\n * A prepared statement with the SQL that produced it.\n *\n * The platform's `D1PreparedStatement` carries no `sql` member, so a layer that\n * needs to know *what* it is about to run — to account for a write, to assert a\n * table's billing multiplier, to log a rejected statement in terms a reader can\n * act on — has nowhere to read it from. Carrying it beside the statement is\n * that place, and `bind()` returns a new pair for the same reason the platform's\n * does: bindings are immutable on a prepared statement.\n */\ninterface TrackedStatement {\n sql: string;\n statement: D1PreparedStatement;\n bind(...bindings: unknown[]): TrackedStatement;\n}\n\n/**\n * How many rows a write to `table` costs.\n *\n * A **port, not an implementation**, because the answer is a property of the\n * schema rather than of this layer: D1 bills a write as the table row *plus\n * every index entry it rewrote*, so the multiplier belongs to whoever owns the\n * migrations. This package owns the accounting *shape* — carrying the figure\n * beside `changes` on every write result — and the consumer supplies the table.\n *\n * Returning `null` means \"I do not know this table\", which is a different answer\n * from \"this costs one row\" and must not collapse into it: an unknown table\n * errs toward the worst case, because an under-count costs the outage.\n */\ntype BilledRowsForTable = (table: string, logicalRows: number) => number | null;\n\n/**\n * What a write cost, and what it changed.\n *\n * `changes` is progress — how many table rows the statement touched — and\n * `billedRows` is cost. They are not the same number and neither replaces the\n * other: `changes` is what a convergence test measures, `billedRows` is what a\n * daily-allowance budget must be spent against. A caller that reads only\n * `changes` believes it has roughly an order of magnitude more headroom than it\n * does on an indexed table.\n *\n * `billedRows` is `null` — absent, not zero — when no {@link BilledRowsForTable}\n * port is configured, so the type forces the caller to notice that nothing is\n * being accounted rather than reporting a confident `0`.\n */\ninterface WriteResult {\n changes: number;\n billedRows: number | null;\n}\n\n/**\n * Canonical DAO base: retry is a policy, methods are a promise.\n *\n * Converged from the nine consumer repos' BaseDAOs. The API is the **sql-first**\n * shape CalDAV-Bridge and ChordDHT-Tracker used, not the closure-first shape\n * Durable-DAV's family used: a DAO states its SQL and bindings directly, and\n * the retry/normalization wrapper is invisible at the call site. The closure\n * form made every read site pay for a wrapper 90% of them never needed, and\n * each of the two shapes drifted its own method names (`withRetry` vs\n * `run(sql, bindings)`); the sql-first form is what survived.\n *\n * ### Every statement is charged\n *\n * D1 counts its own queries against the Workers per-invocation subrequest\n * ceiling, so a statement that spends one without telling anybody makes every\n * number that budgets work wrong — and it has **no symptom** until the platform\n * terminates the invocation, by which point the rows were right and the suite\n * was green. The meter is therefore a constructor dependency rather than a\n * module singleton, and the charge happens here because this is the one path\n * every statement takes; a charge at each call site is a hundred chances to\n * forget one.\n *\n * The charge is **per logical statement, not per attempt**: a retried statement\n * is one statement that the platform refused once and then answered. Charging\n * per attempt would make the ceiling track the fault rate instead of the work.\n *\n * Non-DAO concerns stay out: cursor pagination lives in `@rexezuge/shared`\n * (`CursorCodec`). Retry policy lives in `D1Retry` — one schedule, one\n * classifier, one place the `Failed to <context>` prefix is added.\n */\nabstract class BaseDAO {\n /**\n * Public, and deliberately so.\n *\n * A composition root instantiates concrete DAOs directly — that is the whole\n * point of a DI container, which binds `() => new UserDAO(db)` rather than\n * handing the container a factory that hides the construction. A `protected`\n * constructor blocks that and buys nothing: the class is `abstract`, so nobody\n * can instantiate `BaseDAO` itself regardless, and the access modifier\n * prevented exactly zero illegal constructions while forcing every concrete\n * DAO to redeclare a pass-through constructor that added no invariant.\n *\n * It was `protected` to keep `database` from being reached as\n * `BaseDAO.database` — but every field below carries its own `protected`, so\n * the field's own modifier is what enforces that, and making the constructor\n * public does not weaken it.\n *\n * @param database The binding.\n * @param meter The invocation's subrequest counter, or an unmetered default.\n * @param options `billedRowsForTable` supplies the schema's write cost.\n */\n constructor(\n protected readonly database: D1Queryable,\n protected readonly meter: SubrequestMeter = UNMETERED_SUBREQUESTS,\n private readonly options: { billedRowsForTable?: BilledRowsForTable } = {},\n ) {}\n\n /**\n * The invocation's meter, for a DAO that constructs another DAO.\n *\n * A `protected get` rather than a public field, because handing the meter out\n * is how a DAO builds a collaborator correctly: `new SongIdLookupDAO(this.database)`\n * drops it, and the charge that goes missing has no symptom.\n */\n protected get subrequests(): SubrequestMeter {\n return this.meter;\n }\n\n /**\n A prepared statement with its bindings applied. Bindings are always parameters, never interpolation.\n */\n protected statement(sql: string, bindings: unknown[] = []): D1PreparedStatement {\n return bindings.length > 0 ? this.database.prepare(sql).bind(...bindings) : this.database.prepare(sql);\n }\n\n /**\n * The same statement, carrying the SQL beside it.\n *\n * Use this wherever the SQL matters downstream — a write whose cost is\n * accounted, a statement named in an error — and {@link statement} for reads,\n * where nothing reads the SQL back and the pair is one allocation of waste.\n */\n protected tracked(sql: string, bindings: unknown[] = []): TrackedStatement {\n const make = (prepared: D1PreparedStatement): TrackedStatement => ({\n sql,\n statement: prepared,\n bind: (...next: unknown[]): TrackedStatement => make(prepared.bind(...next)),\n });\n return make(this.statement(sql, bindings));\n }\n\n /**\n * Run a statement. D1 reports a constraint violation or a missing table by\n * returning `success: false` rather than by throwing, so both forms are\n * normalized to a `DatabaseError` here — ignoring the result form is what\n * let a `UNIQUE` failure reach a caller as an opaque 500.\n */\n protected async run(sql: string, bindings: unknown[] = []): Promise<D1Result> {\n this.meter.charge(1, 'd1');\n return executeWithRetry((): Promise<D1Result> => this.statement(sql, bindings).run(), 'run statement');\n }\n\n /**\n Read one row. A `null` result is \"no row\", a success, not an error; only a\n rejected statement is retried and normalized.\n\n `null` rather than `undefined` because that is what the platform says\n (`D1Result.first<T>()` returns `T | null`) and an adapter should hand back\n what it was given. It also makes this layer agree with `KvCache`, which has\n always returned `null` for a miss, so one convention covers both.\n */\n protected async first<T>(sql: string, bindings: unknown[] = []): Promise<T | null> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T | null>> => {\n const row: T | null = await this.statement(sql, bindings).first<T>();\n return { success: true, value: row };\n }, 'read a row');\n return envelope.value;\n }\n\n /**\n A list read. `.all()` returning `[]` is a success like `first()`'s null.\n */\n protected async all<T>(sql: string, bindings: unknown[] = []): Promise<T[]> {\n this.meter.charge(1, 'd1');\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<T[]>> => {\n const rows = await this.statement(sql, bindings).all<T>();\n return { success: true, value: rows.results ?? [] };\n }, 'read rows');\n return envelope.value;\n }\n\n /**\n A scalar count from a `SELECT count(*)` row; 0 when absent.\n */\n protected async count(sql: string, bindings: unknown[] = []): Promise<number> {\n const row = await this.first<{ count: number }>(sql, bindings);\n return row?.count ?? 0;\n }\n\n /**\n * A batch of prepared statements — one transaction and one subrequest,\n * however many statements it carries. Each result is checked, so a single\n * failure inside the batch raises rather than passing silently.\n */\n protected async batch(statements: D1PreparedStatement[]): Promise<D1Result[]> {\n if (statements.length === 0) return [];\n this.meter.charge(1, 'd1');\n if (this.database.batch === undefined) {\n throw new DatabaseError('The D1 binding exposes no batch() — a multi-statement transaction is not available here');\n }\n const envelope = await executeWithRetry(async (): Promise<StatementEnvelope<D1Result[]>> => {\n const results: D1Result[] = await (this.database.batch as NonNullable<D1Queryable['batch']>)(statements);\n const failed: D1Result | undefined = results.find((result): boolean => !result.success);\n return { success: failed === undefined, error: failed?.error, value: results };\n }, 'run a batch');\n return envelope.value;\n }\n\n /**\n * Run one write and report what it cost.\n *\n * Takes a {@link TrackedStatement} rather than SQL because the cost is read off\n * the table the SQL names, and the SQL is only available if it was carried.\n * `billedRows` is `null` when no port is configured.\n */\n protected async runTracked(tracked: TrackedStatement): Promise<WriteResult> {\n const result = await executeWithRetry((): Promise<D1Result> => tracked.statement.run(), 'run a write');\n return this.accountWrite(tracked.sql, result);\n }\n\n /**\n * Run a batch of writes and report what the whole batch cost.\n *\n * Billed rows are **summed across the batch**, and an unaccountable statement\n * poisons the total to `null` rather than being skipped: a partial figure next\n * to a real one is the one that reads as complete.\n */\n protected async runTrackedBatch(tracked: readonly TrackedStatement[]): Promise<WriteResult> {\n const results = await this.batch(tracked.map((entry) => entry.statement));\n let billedRows = 0;\n let accounted = this.options.billedRowsForTable !== undefined;\n for (const [index, result] of results.entries()) {\n const entry = tracked[index];\n if (!entry) {\n accounted = false;\n break;\n }\n const one = this.accountWrite(entry.sql, result);\n if (one.billedRows === null) {\n accounted = false;\n break;\n }\n billedRows += one.billedRows;\n }\n const changes = results.reduce((total, result) => total + changesOf(result), 0);\n return { changes, billedRows: accounted ? billedRows : null };\n }\n\n /**\n * The writes these statements fit into the invocation's remaining budget.\n *\n * \"How many may I issue\", as distinct from {@link assertSubrequestBudget}'s\n * \"may I issue all of these\" — a caller truncating a work list needs the\n * number, and a caller that must not truncate needs the refusal. An unmetered\n * counter answers `Infinity`, so a deployment that does not meter is never\n * clamped by a budget it does not have.\n */\n protected fitToSubrequestBudget(requested: number): number {\n const remaining = this.meter.remaining;\n return Number.isFinite(remaining) ? Math.max(0, Math.min(requested, Math.floor(remaining))) : Math.max(0, requested);\n }\n\n /**\n * Refuse a set of statements the invocation's remaining budget cannot carry.\n *\n * For a write with no partial form — a play queue, a playlist's count, a\n * backfill — because half a queue is a _shorter_ queue, which is a wrong\n * answer rather than an unfinished one. A caller that may truncate uses\n * {@link fitToSubrequestBudget} instead and reports that it did.\n *\n * @param statements How many statements the work needs.\n * @param context Named in the refusal, because this reaches a client as a 413.\n */\n protected assertSubrequestBudget(statements: number, context = 'this request'): void {\n if (this.meter.canAfford(statements)) return;\n throw new SubrequestBudgetExhaustedError(\n `${context} needs ${statements} database operations and this invocation has ${this.meter.remaining} left. Send fewer items at once.`,\n );\n }\n\n /**\n * Charge the meter and account a completed write against the schema's cost.\n */\n private accountWrite(sql: string, result: D1Result): WriteResult {\n const changes = changesOf(result);\n const port = this.options.billedRowsForTable;\n if (!port) return { changes, billedRows: null };\n return { changes, billedRows: port(statementTable(sql) ?? '', changes) };\n }\n\n /**\n * Generic batched delete of rows older than a cutoff, in ID order, with\n * retry. Mirrors the per-DAO `DELETE ... WHERE id IN (SELECT ... LIMIT ?)`\n * pattern that every repo re-implemented per table. The cutoff is exclusive:\n * a delete never touches a row at exactly the boundary timestamp.\n */\n protected static async deleteOlderThan(\n db: D1Queryable,\n table: string,\n timeColumn: string,\n cutoff: number | string,\n limit: number,\n idColumn: string,\n ): Promise<number> {\n assertSqlIdentifier(table, 'table');\n assertSqlIdentifier(timeColumn, 'timeColumn');\n assertSqlIdentifier(idColumn, 'idColumn');\n const result: D1Result = await executeWithRetry(\n (): Promise<D1Result> =>\n db\n .prepare(\n `DELETE FROM ${table}\n WHERE ${idColumn} IN (\n SELECT ${idColumn} FROM ${table}\n WHERE ${timeColumn} < ?\n LIMIT ?\n )`,\n )\n .bind(cutoff, limit)\n .run(),\n `delete old rows from ${table}`,\n );\n return (result.meta as { changes?: number })?.changes ?? 0;\n }\n\n /**\n The retry schedule, for callers that surface it (health checks, tests).\n */\n protected static get retryDefaults(): typeof D1_RETRY_DEFAULTS {\n return D1_RETRY_DEFAULTS;\n }\n}\n\n/**\n * Allow-list one SQL identifier segment. Values never go through this — they\n * are always bound; this exists purely for the table/column names that\n * parameter binding cannot express.\n */\nfunction assertSqlIdentifier(value: string, label: string): void {\n if (!/^[A-Z_]\\w*$/i.test(value)) {\n throw new Error(`Unsafe SQL identifier for ${label}: ${JSON.stringify(value)}`);\n }\n}\n\nfunction changesOf(result: D1Result): number {\n return (result.meta as { changes?: number })?.changes ?? 0;\n}\n\n/**\n * The write verb's table name, or `null` when the SQL does not name one.\n *\n * The verb is anchored at the **start** of the statement, after leading\n * whitespace and comments — a bare `/\\bINSERT\\s+INTO\\s+(\\w+)/` also matches a\n * verb quoted inside a string literal, and a table read out of a `SELECT`'s\n * projection is worse than no answer at all. An unreadable statement returns\n * `null` for the caller to charge the worst case against, rather than throwing:\n * accounting must not be the thing that turns a failed write into a crashed\n * request.\n */\nfunction statementTable(sql: string): string | null {\n if (typeof sql !== 'string') return null;\n let rest = sql.replace(/^\\s+/, '');\n // A `while` rather than a repeated strip: comments are the only noise, and a\n // bounded loop cannot be made quadratic by a statement full of them.\n while (rest.startsWith('--')) {\n const newline = rest.indexOf('\\n');\n if (newline === -1) return null;\n rest = rest.slice(newline + 1).replace(/^\\s+/, '');\n }\n const verb = /^(?:INSERT|REPLACE|UPDATE|DELETE)\\b/i.exec(rest);\n if (!verb) return null;\n rest = consume(rest.slice(verb[0].length));\n\n // `INSERT OR REPLACE`, `UPDATE OR IGNORE` — a conflict clause between the verb and\n // the table. This is why the parse is stepwise rather than one anchored pattern:\n // a single pattern either grows a nested quantifier the complexity gate rejects,\n // or drops the clause and reads `REPLACE` as a table name.\n rest = consume(rest, /^(?:OR\\s+[A-Z_]+\\s+)?/i);\n rest = consume(rest, /^(?:INTO\\s+|FROM\\s+)?/i);\n return /^[\"`[]?([A-Z_]\\w*)/i.exec(rest)?.[1] ?? null;\n}\n\n/**\n * Drop a leading match and the whitespace after it.\n */\nfunction consume(sql: string, pattern?: RegExp): string {\n const matched = pattern?.exec(sql)?.[0] ?? '';\n return sql.slice(matched.length).replace(/^\\s+/, '');\n}\n\nexport { BaseDAO, assertSqlIdentifier, statementTable };\nexport type { BilledRowsForTable, TrackedStatement, WriteResult };\n"],
5
+ "mappings": "+EAAA,OAAS,yBAAAA,MAA6B,mBAEtC,OAAS,kCAAAC,MAAsC,mBAC/C,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,qBAAAC,EAAmB,oBAAAC,MAAwB,eA2FpD,MAAeC,CAAO,CA/FtB,MA+FsB,CAAAC,EAAA,gBAsBC,SACA,MACF,QAHnB,YACqBC,EACAC,EAAyBR,EAC3BS,EAAuD,CAAA,EAAE,CAFvD,KAAA,SAAAF,EACA,KAAA,MAAAC,EACF,KAAA,QAAAC,CAChB,CASH,IAAc,aAAW,CACvB,OAAO,KAAK,KACd,CAKU,UAAUC,EAAaC,EAAsB,CAAA,EAAE,CACvD,OAAOA,EAAS,OAAS,EAAI,KAAK,SAAS,QAAQD,CAAG,EAAE,KAAK,GAAGC,CAAQ,EAAI,KAAK,SAAS,QAAQD,CAAG,CACvG,CASU,QAAQA,EAAaC,EAAsB,CAAA,EAAE,CACrD,MAAMC,EAAON,EAACO,IAAqD,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QH,EAAM,wBAAwB,EAC7CA,EAAOG,EAAQH,EAAM,wBAAwB,EACtC,sBAAsB,KAAKA,CAAI,IAAI,CAAC,GAAK,MAT9B,IAUpB,CArBSpC,EAAA0B,EAAA,kBA0BT,SAASa,EAAQnC,EAAaoC,EAAgB,CAC5C,MAAMC,EAAUD,GAAS,KAAKpC,CAAG,IAAI,CAAC,GAAK,GAC3C,OAAOA,EAAI,MAAMqC,EAAQ,MAAM,EAAE,QAAQ,OAAQ,EAAE,CACrD,CAHSzC,EAAAuC,EAAA",
6
6
  "names": ["UNMETERED_SUBREQUESTS", "SubrequestBudgetExhaustedError", "DatabaseError", "D1_RETRY_DEFAULTS", "executeWithRetry", "BaseDAO", "__name", "database", "meter", "options", "sql", "bindings", "make", "prepared", "next", "statements", "results", "failed", "result", "tracked", "entry", "billedRows", "accounted", "index", "one", "total", "changesOf", "requested", "remaining", "context", "changes", "port", "statementTable", "db", "table", "timeColumn", "cutoff", "limit", "idColumn", "assertSqlIdentifier", "value", "label", "rest", "newline", "verb", "consume", "pattern", "matched"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/d1",
3
- "version": "1.7.0",
3
+ "version": "1.7.1",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,8 +25,8 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@rexezuge/errors": "1.7.0",
29
- "@rexezuge/shared": "1.7.0"
28
+ "@rexezuge/errors": "1.7.1",
29
+ "@rexezuge/shared": "1.7.1"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/node": "26.6.4",