durable-db 0.13.2 → 0.14.0

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.
@@ -1,9 +1,8 @@
1
1
  import "./index-bUUlOWfP.js";
2
- import { t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
+ import { n as Outbox } from "./outbox-DpyNU99x.js";
3
3
  import { type } from "arktype";
4
4
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
5
- import { AliasNode, AliasedExpression, Expression, ExpressionBuilder, Kysely, KyselyPlugin, OperationNode, Selectable, SqlBool } from "kysely";
6
- import { Kyselify } from "drizzle-orm/kysely";
5
+ import { AliasNode, AliasedExpression, ColumnType, Expression, ExpressionBuilder, Kysely, KyselyPlugin, OperationNode, Selectable, SqlBool } from "kysely";
7
6
  //#region src/db/relations.d.ts
8
7
  type AnySchema = Record<string, SQLiteTableWithColumns<any>>;
9
8
  type RefOf<Col> = Col extends {
@@ -16,7 +15,7 @@ type TableNameOf<Col> = Col extends {
16
15
  tableName: infer N;
17
16
  };
18
17
  } ? N : never;
19
- type ColumnsOf<T> = T extends {
18
+ type ColumnsOf$1<T> = T extends {
20
19
  _: {
21
20
  columns: infer C;
22
21
  };
@@ -29,16 +28,16 @@ type NameOf<T> = T extends {
29
28
  type KeyOf<S, Name> = { [K in keyof S & string]: NameOf<S[K]> extends Name ? K : never; }[keyof S & string];
30
29
  type TargetOf$1<S, Col> = [RefOf<Col>] extends [never] ? never : string extends TableNameOf<RefOf<Col>> ? never : KeyOf<S, TableNameOf<RefOf<Col>>>;
31
30
  /** Every foreign key of a schema the types know: the table and column that hold it, the table it points at. */
32
- type Edge<S> = { [TK in keyof S & string]: { [CK in keyof ColumnsOf<S[TK]> & string]: [TargetOf$1<S, ColumnsOf<S[TK]>[CK]>] extends [never] ? never : {
31
+ type Edge<S> = { [TK in keyof S & string]: { [CK in keyof ColumnsOf$1<S[TK]> & string]: [TargetOf$1<S, ColumnsOf$1<S[TK]>[CK]>] extends [never] ? never : {
33
32
  table: TK;
34
33
  column: CK;
35
- target: TargetOf$1<S, ColumnsOf<S[TK]>[CK]>;
36
- nullable: ColumnsOf<S[TK]>[CK] extends {
34
+ target: TargetOf$1<S, ColumnsOf$1<S[TK]>[CK]>;
35
+ nullable: ColumnsOf$1<S[TK]>[CK] extends {
37
36
  _: {
38
37
  notNull: true;
39
38
  };
40
39
  } ? false : true;
41
- }; }[keyof ColumnsOf<S[TK]> & string]; }[keyof S & string];
40
+ }; }[keyof ColumnsOf$1<S[TK]> & string]; }[keyof S & string];
42
41
  type AnyEdge = {
43
42
  table: string;
44
43
  column: string;
@@ -239,7 +238,44 @@ interface DatabaseConfig<TSchema extends Record<string, SQLiteTableWithColumns<a
239
238
  /**
240
239
  * Convert a Drizzle schema to Kysely database types using drizzle-kysely
241
240
  */
242
- type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: TSchema[K] extends SQLiteTableWithColumns<any> ? Kyselify<TSchema[K]> : never; };
241
+ type DrizzleToKysely<TSchema extends Record<string, SQLiteTableWithColumns<any>>> = { [K in keyof TSchema]: KyselyTable<TSchema[K]>; };
242
+ type ColumnsOf<T> = T extends {
243
+ _: {
244
+ columns: infer C;
245
+ };
246
+ } ? C : never;
247
+ type KyselyTable<T> = { [C in keyof ColumnsOf<T> & string as DbNameOf<C, ColumnsOf<T>[C]>]: KyselyColumn<ColumnsOf<T>[C]>; };
248
+ type DbNameOf<Key, Col> = Col extends {
249
+ _: {
250
+ name: infer N extends string;
251
+ };
252
+ } ? N : Key;
253
+ /** A column's value as a row holds it: null where it may be. */
254
+ type ColumnValue<Col> = Col extends {
255
+ _: {
256
+ notNull: true;
257
+ data: infer D;
258
+ };
259
+ } ? D : Col extends {
260
+ _: {
261
+ data: infer D;
262
+ };
263
+ } ? D | null : never;
264
+ type KyselyColumn<Col> = Col extends {
265
+ _: {
266
+ notNull: true;
267
+ hasDefault: false;
268
+ };
269
+ } ? ColumnValue<Col> : Col extends {
270
+ _: {
271
+ generated: undefined;
272
+ identity: undefined;
273
+ };
274
+ } ? Col extends {
275
+ _: {
276
+ notNull: true;
277
+ };
278
+ } ? ColumnType<ColumnValue<Col>, ColumnValue<Col> | undefined, ColumnValue<Col> | undefined> : ColumnValue<Col> : ColumnType<ColumnValue<Col>, never, never>;
243
279
  /**
244
280
  * ArkType helpers – mirror Ark's own API:
245
281
  * - arkType.validate<Def> → definition shape with DSL validation/autocomplete
@@ -1172,7 +1172,8 @@ function defineDatabase(config) {
1172
1172
  args: actionConfig.args,
1173
1173
  handler: actionConfig.handler,
1174
1174
  validator,
1175
- schema
1175
+ schema,
1176
+ instance: config?.instance ?? "per-tenant"
1176
1177
  },
1177
1178
  enumerable: false,
1178
1179
  configurable: true
@@ -1,5 +1,5 @@
1
- import "./defineDatabase-DlgYfwhP.js";
2
- import { i as OutboxSink, t as Outbox } from "./outbox-D3Q9n7Rt.js";
1
+ import "./defineDatabase-Dj5DOPUM.js";
2
+ import { n as Outbox, o as OutboxSink } from "./outbox-DpyNU99x.js";
3
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
4
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
5
5
  import { DurableObject } from "cloudflare:workers";
@@ -158,6 +158,20 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
158
158
  * best-effort name derived from its class name (`<PascalCase(name)>DatabaseDO`).
159
159
  */
160
160
  protected databaseName?: string;
161
+ /**
162
+ * The database's `instance` (`defineDatabase({ instance })`): the generated
163
+ * Durable Object sets it. A global database's instance has no tenant,
164
+ * whatever its key; a hand-written subclass that sets none is per-tenant,
165
+ * `defineDatabase()`'s default.
166
+ */
167
+ protected databaseInstance?: 'per-tenant' | 'global';
168
+ /**
169
+ * What the build appends to this database's instance keys —
170
+ * `applyDevEpoch('', name)`: `__dev_<epoch>` in dev, `''` in production. The
171
+ * generated Durable Object sets it; a key's tenant is the key without
172
+ * exactly this.
173
+ */
174
+ protected devEpochSuffix: string;
161
175
  /**
162
176
  * Whether migrations have been run for this instance
163
177
  */
@@ -181,33 +195,117 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
181
195
  */
182
196
  private pitrUnavailableReason;
183
197
  constructor(ctx: DurableObjectState, env: Env);
198
+ /**
199
+ * The name an outbox envelope gives this database: `databaseName`, else
200
+ * one derived from the class name, else the class name.
201
+ */
202
+ private knownDatabaseName;
203
+ /**
204
+ * The tenant of an instance key of this database: null for a global
205
+ * database, else the key without exactly the dev epoch the build applied
206
+ * (`devEpochSuffix`) — never cut anywhere else, so a tenant id containing
207
+ * `__dev_` is kept whole. What `getTenantId()` answers in an action
208
+ * (the generated `rpc` hands it to the action's context) and an outbox
209
+ * envelope's `tenantId`.
210
+ */
211
+ protected tenantOf(instanceKey: string): string | null;
184
212
  /**
185
213
  * Where the outbox delivers (`./outbox`): the generated class sets it from
186
214
  * `durableDb({ outbox })`. Null: `ctx.outbox.push()` refuses, naming the option.
187
215
  */
188
216
  protected outboxSink: OutboxSink | null;
217
+ /**
218
+ * How many counted failures move a message to `__outbox_dead`
219
+ * (`durableDb({ outbox: { maxAttempts } })`, which the generated class sets).
220
+ */
221
+ protected outboxMaxAttempts: number;
189
222
  private outboxReady;
223
+ /**
224
+ * Which storage this instance is on: `resetMigrationState()` (after
225
+ * `deleteAll()`) counts it up, so an alarm whose sink was still running
226
+ * when the storage was wiped settles nothing on the storage that replaced it.
227
+ */
228
+ private storageGeneration;
190
229
  private ensureOutboxTable;
230
+ /** What the outbox knows of its sink (one row by its key; both 0 before it was written). */
231
+ private outboxSinkState;
232
+ /** Writes the sink's row when it changed. */
233
+ private writeOutboxSinkState;
191
234
  /**
192
235
  * Runs an action with `ctx.outbox`. The messages it pushed are written when
193
236
  * it resolves — in the same synchronous block as its last writes, which the
194
237
  * Durable Object commits together — and the alarm that delivers them is set
195
- * with them. A handler that throws records nothing. An action called from
196
- * another action of this database runs on the caller's context, and so on
197
- * its outbox.
238
+ * with them: now, or, while the sink is taken for down, its next try, so a
239
+ * message recorded during an outage adds no alarm (the try still makes at
240
+ * most two sink calls). A handler that throws records nothing. An action
241
+ * called from another action of this database runs on the caller's context,
242
+ * and so on its outbox.
198
243
  */
199
244
  protected runWithOutbox<T>(ctx: {
200
245
  instanceKey: string;
201
246
  outbox?: Outbox;
202
247
  }, run: () => Promise<T>): Promise<T>;
203
248
  /**
204
- * Delivers the outbox: up to OUTBOX_DELIVERY_SIZE messages, oldest first, to
205
- * the sink; what was delivered is deleted, and the alarm comes back while
206
- * more are waiting. A delivery that throws stays in the table and is retried
207
- * with backoff (5 s, doubling, at most 5 minutes), so a message arrives at
208
- * least once. A subclass with an alarm of its own calls `super.alarm()`.
249
+ * Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
250
+ * A failure is judged only by what the sink did in the same alarm.
251
+ *
252
+ * While the sink is taken for down (`down_until` later than now) nothing is
253
+ * read or called, and the alarm is set to that time. Its next try hands it
254
+ * the newest message alone and, if the sink does not take it, the one tried
255
+ * or recorded longest ago alone (`max(tried_at, recorded_at)`), their own
256
+ * clocks ignored. A message a try handed that the sink neither delivered nor
257
+ * answered in `{ dead }` gets `tried_at` and its `last_error`, nothing else:
258
+ * no count, no clock. One it answered in `{ dead }` is moved to
259
+ * `__outbox_dead`, and is no delivery. When the sink takes one, it is up and
260
+ * the alarm goes on; else the next try backs off (5 s, doubling, at most 5
261
+ * minutes).
262
+ *
263
+ * Then it reads the oldest due messages, by id, at most 100, and hands them
264
+ * to the sink in one call. What a call did not deliver — all of it when the
265
+ * sink threw or answered malformed — is halved, and both halves are tried
266
+ * next, the first first. The one message of a call not delivered fails
267
+ * alone: it waits on its own backoff (`tries`), and the failure counts
268
+ * toward `outboxMaxAttempts` (`counted`) only when the sink delivered
269
+ * another message in this alarm, in that call or earlier; at the cap it is
270
+ * moved to `__outbox_dead`. A failure alone before anything was delivered in
271
+ * the alarm cannot be told from an outage: it counts nothing, and the sink is
272
+ * taken for down until its next try, in 5 s. A message the sink answers in
273
+ * `{ dead }` is moved to `__outbox_dead` at once, and is no delivery. The
274
+ * alarm is then set to the earliest message waiting — now, when one is due.
275
+ *
276
+ * After every awaited sink call the alarm checks that the storage is still
277
+ * the one it read, and writes nothing more when `destroyDatabase()` wiped it
278
+ * meanwhile. A message arrives at least once. A subclass with an alarm of its
279
+ * own calls `super.alarm()`.
209
280
  */
210
281
  alarm(): Promise<void>;
282
+ /**
283
+ * Takes the sink for down until its next try, for its `rounds`-th round in a
284
+ * row (1 when an alarm takes it down, one more for each try that finds it
285
+ * down): nothing is read or called before then (5 s, doubling, at most 5
286
+ * minutes), and the alarm is set to that time.
287
+ */
288
+ private takeOutboxSinkForDown;
289
+ /**
290
+ * One sink call: `rows` handed to the sink as envelopes, in a frozen list of
291
+ * its own. What it delivered is deleted and what it gave up on (`{ dead }`)
292
+ * buried, in the synchronous block after the call. Null when the storage was
293
+ * wiped while the sink ran (`storageGeneration` moved on from `generation`):
294
+ * nothing is written then — the rows are gone, and an id now names another
295
+ * row.
296
+ */
297
+ private callOutboxSink;
298
+ /**
299
+ * A message that failed alone: `tries` moves on, and with it its backoff
300
+ * (`next_attempt_at`). When it `counts` — the sink delivered another message
301
+ * in this alarm, in its call or earlier — `counted` moves on too, and at
302
+ * `outboxMaxAttempts` the message is moved to `__outbox_dead`.
303
+ */
304
+ private failOutboxRowAlone;
305
+ /** What the alarm logs of its failures: one line for those retried (or for the sink taken for down), one for those buried. */
306
+ private logOutboxFailures;
307
+ /** A row to `__outbox_dead`, as it was in `__outbox` (its id kept), with its counted failures and last error. */
308
+ private buryOutboxRow;
211
309
  /**
212
310
  * Check if PITR is available on this DO's storage.
213
311
  * Result is cached after the first call.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-DlgYfwhP.js";
3
- import { a as OutboxSinkContext, i as OutboxSink, n as OutboxEnvelope, o as OutboxSinkModule, r as OutboxMessage, t as Outbox } from "./outbox-D3Q9n7Rt.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-Dj5DOPUM.js";
3
+ import { a as OutboxMessage, c as OutboxSinkModule, i as OutboxEnvelope, n as Outbox, o as OutboxSink, r as OutboxDelivery, s as OutboxSinkContext, t as InstanceKeyOrigin } from "./outbox-DpyNU99x.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
6
6
  import { Kysely } from "kysely";
@@ -20,4 +20,4 @@ interface ActionDescription {
20
20
  /** The description of an action, or undefined for anything that is not one. */
21
21
  export declare function describeAction(action: unknown): ActionDescription | undefined;
22
22
  //#endregion
23
- export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type Kysely, type Outbox, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
23
+ export { type Action, type ActionConfig, type ActionContext, type ActionDescription, type AnyRelated, type AnySQLiteColumn, type AnySchema, type DatabaseConfig, type DatabaseDefinition, type DrizzleToKysely, type InferArgs, type InstanceKeyOrigin, type Kysely, type Outbox, type OutboxDelivery, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, blob, createRelated, defineDatabase, foreignKey, getTenantId, hasTenantId, index, integer, numeric, primaryKey, real, relationOf, relationsOf, setTenantIdResolver, table, text, type, uniqueIndex };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-B1pKzO-V.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-_AusJf3r.js";
2
2
  import { r as type } from "./type-pAQ37iEL.js";
3
3
  import "./actionArgs-oUWwX6Xn.js";
4
4
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";