@gobing-ai/ts-db 0.8.8 → 0.8.9

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/README.md CHANGED
@@ -25,6 +25,7 @@ storage engine swappable and the query surface small and auditable. Two tiers, y
25
25
  | `Predicate` / `ListSpec` / `OrderTerm` | The drizzle-free query vocabulary |
26
26
  | `QueueJobDao` | Job queue persistence — `enqueue`, `claimReady`, `markCompleted`, `failExpiredJobs` |
27
27
  | `InboxMessageDao` | Durable inter-agent message persistence (`@gobing-ai/ts-db/inbox`) |
28
+ | `ResourceLeaseDao` | Cross-process resource admission — expiring lease rows, `tryAcquire`/`renew`/`release`/`listLive` |
28
29
  | `applyMigrations` | Drizzle migration runner (file-based + embedded fallback) |
29
30
  | `schema` helpers | `standardColumns`, `appendOnlyColumns`, soft-delete columns (`@gobing-ai/ts-db/schema`) |
30
31
  | `SpanContext` | Re-exported from `@gobing-ai/ts-runtime` for telemetry |
@@ -343,6 +344,37 @@ The `inbox_messages` table is additive and included in embedded migrations. It s
343
344
  `to_id`, `body`, `status`, optional reply linkage, delivery timestamp, injection attempts, and the
344
345
  last injection error. The indexed access path is `(to_id, status)` for efficient pending drains.
345
346
 
347
+ ### ResourceLeaseDao — cross-process resource admission
348
+
349
+ A lease is one held slot on a named resource. `(resource, holder)` is the row identity and
350
+ `expires_at` is the liveness fact, so a crashed holder's slot comes back on its own and no lock
351
+ server is involved.
352
+
353
+ ```ts
354
+ import { ResourceLeaseDao } from '@gobing-ai/ts-db';
355
+
356
+ const leases = new ResourceLeaseDao(adapter);
357
+
358
+ const seat = await leases.tryAcquire({ resource: 'colab-gpu', max: 1, holder: 'run-42', ttlMs: 30 * 60_000 });
359
+ if (!seat.admitted) {
360
+ console.log(`${seat.held}/${seat.max} held by ${seat.holders.join(', ')}`);
361
+ } else {
362
+ await leases.renew('colab-gpu', 'run-42', 30 * 60_000); // keep it live
363
+ await leases.release('colab-gpu', 'run-42'); // idempotent
364
+ }
365
+ ```
366
+
367
+ - `tryAcquire` renews the caller's own live row first, then reclaims expired rows, then attempts ONE
368
+ conditional `INSERT … SELECT … WHERE (live count) < max ON CONFLICT DO NOTHING RETURNING *`. The
369
+ single statement carries the bound on every adapter — no `BEGIN IMMEDIATE`, no in-process map, and
370
+ concurrent processes never exceed `max`.
371
+ - `max` and `ttlMs` must be positive integers; anything else throws `RangeError`.
372
+ - `renew` returns `false` when the lease was lost; `release` returns whether a live row was removed;
373
+ `releaseByOwner(ownerRef)` removes and counts an owner's live slots; `listLive({ resource? })` hides
374
+ expired rows.
375
+ - Liveness is evaluated against one `now` per call (injectable through `withClock` in tests).
376
+ - The table ships as embedded migration `0015_resource_leases`, indexed on `(resource, expires_at)`.
377
+
346
378
  ### Migrations
347
379
 
348
380
  ```ts
@@ -1 +1 @@
1
- {"version":3,"file":"embedded-migrations.d.ts","sourceRoot":"","sources":["../src/embedded-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,mFAAmF;AACnF,MAAM,WAAW,iBAAiB;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,uEAAuE;AACvE,eAAO,MAAM,kBAAkB,EAAE,iBAAiB,EAoCjD,CAAC"}
1
+ {"version":3,"file":"embedded-migrations.d.ts","sourceRoot":"","sources":["../src/embedded-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,mFAAmF;AACnF,MAAM,WAAW,iBAAiB;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CAChB;AAED,uEAAuE;AACvE,eAAO,MAAM,kBAAkB,EAAE,iBAAiB,EAyCjD,CAAC"}
@@ -43,4 +43,9 @@ export const embeddedMigrations = [
43
43
  sql: 'ALTER TABLE `inbox_messages` ADD `request_key` text;\nCREATE UNIQUE INDEX `idx_inbox_messages_request_key` ON `inbox_messages` (`request_key`) WHERE `request_key` IS NOT NULL;\n',
44
44
  hash: '7277e79f8339975b29565e7b33e04f0dbd50995b99b82048fd83079757334f71',
45
45
  },
46
+ {
47
+ tag: '0015_resource_leases',
48
+ sql: 'CREATE TABLE `resource_leases` (\n\t`resource` text NOT NULL,\n\t`holder` text NOT NULL,\n\t`owner_ref` text,\n\t`acquired_at` integer NOT NULL,\n\t`renewed_at` integer NOT NULL,\n\t`expires_at` integer NOT NULL,\n\tPRIMARY KEY(`resource`, `holder`)\n);\nCREATE INDEX `resource_leases_liveness_idx` ON `resource_leases` (`resource`,`expires_at`);\n',
49
+ hash: '136a05b580f715fcbc64ffdda98b94b548b515c887837f198c364846d92dc3da',
50
+ },
46
51
  ];
package/dist/index.d.ts CHANGED
@@ -6,5 +6,6 @@ export { type DeliveredMessageDetail, type EnqueuedMessageDetail, type FailedMes
6
6
  export { applyMigrations, type MigrationLogger, type MigrationOptions } from './migrate';
7
7
  export { type ColRef, type ComparisonOp, compileOrderBy, compilePredicate, type ListSpec, type OrderTerm, type Predicate, } from './query-spec';
8
8
  export { QueueJobDao, type QueueJobRecord, type QueueStats } from './queue-job-dao';
9
+ export { type ResourceLease, type ResourceLeaseAcquireInput, type ResourceLeaseAcquireResult, ResourceLeaseDao, } from './resource-lease-dao';
9
10
  export type { SpanContext } from './span-context';
10
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,SAAS,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,KAAK,UAAU,EAAE,MAAM,WAAW,CAAC;AACnH,OAAO,EAAE,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEpD,OAAO,EAAE,KAAK,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EACH,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,SAAS,EACT,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,kBAAkB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACH,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,YAAY,EACjB,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,uBAAuB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,WAAW,CAAC;AACzF,OAAO,EACH,KAAK,MAAM,EACX,KAAK,YAAY,EACjB,cAAc,EACd,gBAAgB,EAChB,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,SAAS,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACpF,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,SAAS,EAAE,KAAK,eAAe,EAAE,KAAK,SAAS,EAAE,KAAK,UAAU,EAAE,MAAM,WAAW,CAAC;AACnH,OAAO,EAAE,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEpD,OAAO,EAAE,KAAK,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACnF,OAAO,EACH,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,SAAS,EACT,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,kBAAkB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACH,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,YAAY,EACjB,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,uBAAuB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,eAAe,EAAE,KAAK,eAAe,EAAE,KAAK,gBAAgB,EAAE,MAAM,WAAW,CAAC;AACzF,OAAO,EACH,KAAK,MAAM,EACX,KAAK,YAAY,EACjB,cAAc,EACd,gBAAgB,EAChB,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,SAAS,GACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACpF,OAAO,EACH,KAAK,aAAa,EAClB,KAAK,yBAAyB,EAC9B,KAAK,0BAA0B,EAC/B,gBAAgB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -6,3 +6,4 @@ export { InboxMessageDao, RequestKeyConflictError, } from './inbox-message-dao.j
6
6
  export { applyMigrations } from './migrate.js';
7
7
  export { compileOrderBy, compilePredicate, } from './query-spec.js';
8
8
  export { QueueJobDao } from './queue-job-dao.js';
9
+ export { ResourceLeaseDao, } from './resource-lease-dao.js';
@@ -0,0 +1,84 @@
1
+ import type { DbAdapter } from './adapter';
2
+ import { BaseDao } from './base-dao';
3
+ /** One held lease row, epoch-ms times. */
4
+ export interface ResourceLease {
5
+ resource: string;
6
+ holder: string;
7
+ ownerRef: string | null;
8
+ acquiredAt: number;
9
+ renewedAt: number;
10
+ expiresAt: number;
11
+ }
12
+ /** Arguments for {@link ResourceLeaseDao.tryAcquire}. */
13
+ export interface ResourceLeaseAcquireInput {
14
+ /** Resource name the slot is admitted against. */
15
+ resource: string;
16
+ /** Maximum live slots for this resource. */
17
+ max: number;
18
+ /** Identity of the asking holder. */
19
+ holder: string;
20
+ /** Lease length in ms; the slot stops being live at `now + ttlMs` unless renewed. */
21
+ ttlMs: number;
22
+ /** Optional owner reference for bulk release. */
23
+ ownerRef?: string;
24
+ }
25
+ /** Result of {@link ResourceLeaseDao.tryAcquire}. */
26
+ export type ResourceLeaseAcquireResult = {
27
+ admitted: true;
28
+ lease: ResourceLease;
29
+ reclaimed: string[];
30
+ } | {
31
+ admitted: false;
32
+ held: number;
33
+ max: number;
34
+ holders: string[];
35
+ };
36
+ /**
37
+ * Cross-process resource admission through expiring lease rows (ts-libs task 1483 / ADR-156).
38
+ *
39
+ * The `max` bound is carried by ONE conditional `INSERT … SELECT … WHERE (live count) < ?max
40
+ * ON CONFLICT DO NOTHING RETURNING *`. A single statement is atomic on every adapter (bun-sqlite's
41
+ * WAL `busy_timeout` waits out a concurrent writer; D1 serializes statements), so no
42
+ * `BEGIN IMMEDIATE`, no in-process map and no count-then-insert in app code.
43
+ *
44
+ * Liveness is `expires_at > now`: an expired row is deleted lazily by the next acquire, which is how
45
+ * a crashed holder's slot comes back. `now` is read once per call and bound as a parameter so every
46
+ * statement in that call agrees on what "live" means.
47
+ *
48
+ * Extends `BaseDao`, not `EntityDao`: `EntityTable` requires `createdAt`/`updatedAt` columns, and the
49
+ * specified schema deliberately has neither (a lease is its timestamps, and none of the inherited
50
+ * CRUD applies to a row whose removal IS the release).
51
+ */
52
+ export declare class ResourceLeaseDao extends BaseDao {
53
+ /** Table name, exposed for callers that build their own statements. */
54
+ static readonly TABLE = "resource_leases";
55
+ /** Public constructor: `BaseDao`'s is protected, and consumers construct this DAO directly. */
56
+ constructor(adapter: DbAdapter);
57
+ /** Current epoch ms; injectable in tests through {@link ResourceLeaseDao.withClock}. */
58
+ private clock;
59
+ /** Test seam: replace the clock (chainable, returns the same DAO instance). */
60
+ withClock(clock: () => number): this;
61
+ /**
62
+ * Try to take a slot on `resource`.
63
+ *
64
+ * Order is load-bearing: renew the caller's own live row first (so a re-entrant caller never
65
+ * competes with itself), then reclaim expired rows, then attempt the single conditional insert.
66
+ */
67
+ tryAcquire(input: ResourceLeaseAcquireInput): Promise<ResourceLeaseAcquireResult>;
68
+ /** Extend a held slot. `false` means the row is gone or expired — the lease was lost. */
69
+ renew(resource: string, holder: string, ttlMs: number): Promise<boolean>;
70
+ /** Release one slot; idempotent. Returns whether a live row was removed. */
71
+ release(resource: string, holder: string): Promise<boolean>;
72
+ /** Release every live slot an owner reference holds; returns the number removed. */
73
+ releaseByOwner(ownerRef: string): Promise<number>;
74
+ /**
75
+ * List live slots, optionally for one resource. Expired rows are hidden, never returned.
76
+ *
77
+ * Named `listLive` rather than the design's `list`: `EntityDao` already owns `list(spec)` with a
78
+ * different shape (`EntityListSpec` → raw rows), and an incompatible override is not expressible.
79
+ */
80
+ listLive(filter?: {
81
+ resource?: string;
82
+ }): Promise<ResourceLease[]>;
83
+ }
84
+ //# sourceMappingURL=resource-lease-dao.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-lease-dao.d.ts","sourceRoot":"","sources":["../src/resource-lease-dao.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,0CAA0C;AAC1C,MAAM,WAAW,aAAa;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,yDAAyD;AACzD,MAAM,WAAW,yBAAyB;IACtC,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAC;IACZ,qCAAqC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,qFAAqF;IACrF,KAAK,EAAE,MAAM,CAAC;IACd,iDAAiD;IACjD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,qDAAqD;AACrD,MAAM,MAAM,0BAA0B,GAChC;IAAE,QAAQ,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,aAAa,CAAC;IAAC,SAAS,EAAE,MAAM,EAAE,CAAA;CAAE,GAC7D;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAgCxE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,gBAAiB,SAAQ,OAAO;IACzC,uEAAuE;IACvE,MAAM,CAAC,QAAQ,CAAC,KAAK,qBAAqB;IAE1C,+FAA+F;gBACnF,OAAO,EAAE,SAAS;IAI9B,wFAAwF;IACxF,OAAO,CAAC,KAAK,CAAkC;IAE/C,+EAA+E;IAC/E,SAAS,CAAC,KAAK,EAAE,MAAM,MAAM,GAAG,IAAI;IAKpC;;;;;OAKG;IACG,UAAU,CAAC,KAAK,EAAE,yBAAyB,GAAG,OAAO,CAAC,0BAA0B,CAAC;IAuDvF,yFAAyF;IACnF,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAe9E,4EAA4E;IACtE,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAUjE,oFAAoF;IAC9E,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IASvD;;;;;OAKG;IACG,QAAQ,CAAC,MAAM,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;CAgB/E"}
@@ -0,0 +1,119 @@
1
+ import { BaseDao } from './base-dao.js';
2
+ /** Map a raw row to the public record. */
3
+ function toLease(row) {
4
+ return {
5
+ resource: row.resource,
6
+ holder: row.holder,
7
+ ownerRef: row.owner_ref,
8
+ acquiredAt: row.acquired_at,
9
+ renewedAt: row.renewed_at,
10
+ expiresAt: row.expires_at,
11
+ };
12
+ }
13
+ /** Refuse a non-positive-integer bound; a silent coercion here would break the invariant. */
14
+ function assertPositiveInteger(value, label) {
15
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
16
+ throw new RangeError(`${label} must be a positive integer; received ${String(value)}`);
17
+ }
18
+ return value;
19
+ }
20
+ /**
21
+ * Cross-process resource admission through expiring lease rows (ts-libs task 1483 / ADR-156).
22
+ *
23
+ * The `max` bound is carried by ONE conditional `INSERT … SELECT … WHERE (live count) < ?max
24
+ * ON CONFLICT DO NOTHING RETURNING *`. A single statement is atomic on every adapter (bun-sqlite's
25
+ * WAL `busy_timeout` waits out a concurrent writer; D1 serializes statements), so no
26
+ * `BEGIN IMMEDIATE`, no in-process map and no count-then-insert in app code.
27
+ *
28
+ * Liveness is `expires_at > now`: an expired row is deleted lazily by the next acquire, which is how
29
+ * a crashed holder's slot comes back. `now` is read once per call and bound as a parameter so every
30
+ * statement in that call agrees on what "live" means.
31
+ *
32
+ * Extends `BaseDao`, not `EntityDao`: `EntityTable` requires `createdAt`/`updatedAt` columns, and the
33
+ * specified schema deliberately has neither (a lease is its timestamps, and none of the inherited
34
+ * CRUD applies to a row whose removal IS the release).
35
+ */
36
+ export class ResourceLeaseDao extends BaseDao {
37
+ /** Table name, exposed for callers that build their own statements. */
38
+ static TABLE = 'resource_leases';
39
+ /** Public constructor: `BaseDao`'s is protected, and consumers construct this DAO directly. */
40
+ constructor(adapter) {
41
+ super(adapter);
42
+ }
43
+ /** Current epoch ms; injectable in tests through {@link ResourceLeaseDao.withClock}. */
44
+ clock = () => Date.now();
45
+ /** Test seam: replace the clock (chainable, returns the same DAO instance). */
46
+ withClock(clock) {
47
+ this.clock = clock;
48
+ return this;
49
+ }
50
+ /**
51
+ * Try to take a slot on `resource`.
52
+ *
53
+ * Order is load-bearing: renew the caller's own live row first (so a re-entrant caller never
54
+ * competes with itself), then reclaim expired rows, then attempt the single conditional insert.
55
+ */
56
+ async tryAcquire(input) {
57
+ const max = assertPositiveInteger(input.max, 'max');
58
+ const ttlMs = assertPositiveInteger(input.ttlMs, 'ttlMs');
59
+ const now = this.clock();
60
+ const expiresAt = now + ttlMs;
61
+ const renewed = await this.adapter.queryAll(`UPDATE resource_leases SET renewed_at = ?1, expires_at = ?2
62
+ WHERE resource = ?3 AND holder = ?4 AND expires_at > ?1
63
+ RETURNING *`, now, expiresAt, input.resource, input.holder);
64
+ const own = renewed[0];
65
+ if (own !== undefined)
66
+ return { admitted: true, lease: toLease(own), reclaimed: [] };
67
+ const reclaimedRows = await this.adapter.queryAll(`DELETE FROM resource_leases WHERE resource = ?1 AND expires_at <= ?2 RETURNING holder`, input.resource, now);
68
+ const reclaimed = reclaimedRows.map((row) => row.holder);
69
+ const inserted = await this.adapter.queryAll(`INSERT INTO resource_leases (resource, holder, owner_ref, acquired_at, renewed_at, expires_at)
70
+ SELECT ?1, ?2, ?3, ?4, ?4, ?5
71
+ WHERE (SELECT COUNT(*) FROM resource_leases
72
+ WHERE resource = ?1 AND expires_at > ?4) < ?6
73
+ ON CONFLICT (resource, holder) DO NOTHING
74
+ RETURNING *`, input.resource, input.holder, input.ownerRef ?? null, now, expiresAt, max);
75
+ const taken = inserted[0];
76
+ if (taken !== undefined)
77
+ return { admitted: true, lease: toLease(taken), reclaimed };
78
+ const holders = await this.adapter.queryAll(`SELECT holder FROM resource_leases WHERE resource = ?1 AND expires_at > ?2 ORDER BY holder`, input.resource, now);
79
+ return {
80
+ admitted: false,
81
+ held: holders.length,
82
+ max,
83
+ holders: holders.map((row) => row.holder),
84
+ };
85
+ }
86
+ /** Extend a held slot. `false` means the row is gone or expired — the lease was lost. */
87
+ async renew(resource, holder, ttlMs) {
88
+ const ttl = assertPositiveInteger(ttlMs, 'ttlMs');
89
+ const now = this.clock();
90
+ const rows = await this.adapter.queryAll(`UPDATE resource_leases SET renewed_at = ?1, expires_at = ?2
91
+ WHERE resource = ?3 AND holder = ?4 AND expires_at > ?1
92
+ RETURNING holder`, now, now + ttl, resource, holder);
93
+ return rows.length > 0;
94
+ }
95
+ /** Release one slot; idempotent. Returns whether a live row was removed. */
96
+ async release(resource, holder) {
97
+ const rows = await this.adapter.queryAll(`DELETE FROM resource_leases WHERE resource = ?1 AND holder = ?2 AND expires_at > ?3 RETURNING holder`, resource, holder, this.clock());
98
+ return rows.length > 0;
99
+ }
100
+ /** Release every live slot an owner reference holds; returns the number removed. */
101
+ async releaseByOwner(ownerRef) {
102
+ const rows = await this.adapter.queryAll(`DELETE FROM resource_leases WHERE owner_ref = ?1 AND expires_at > ?2 RETURNING holder`, ownerRef, this.clock());
103
+ return rows.length;
104
+ }
105
+ /**
106
+ * List live slots, optionally for one resource. Expired rows are hidden, never returned.
107
+ *
108
+ * Named `listLive` rather than the design's `list`: `EntityDao` already owns `list(spec)` with a
109
+ * different shape (`EntityListSpec` → raw rows), and an incompatible override is not expressible.
110
+ */
111
+ async listLive(filter = {}) {
112
+ const now = this.clock();
113
+ const rows = filter.resource === undefined
114
+ ? await this.adapter.queryAll(`SELECT * FROM resource_leases WHERE expires_at > ?1 ORDER BY resource, holder`, now)
115
+ : await this.adapter.queryAll(`SELECT * FROM resource_leases WHERE resource = ?1 AND expires_at > ?2
116
+ ORDER BY holder`, filter.resource, now);
117
+ return rows.map(toLease);
118
+ }
119
+ }
@@ -4,4 +4,5 @@ export { generateCreateTableSql } from './ddl';
4
4
  export { type DefinedTable, defineTable } from './define-table';
5
5
  export { inboxMessages } from './inbox-messages';
6
6
  export { queueJobs } from './queue-jobs';
7
+ export { resourceLeases } from './resource-leases';
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/D,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,sBAAsB,EAAE,MAAM,OAAO,CAAC;AAC/C,OAAO,EAAE,KAAK,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schema/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/D,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,sBAAsB,EAAE,MAAM,OAAO,CAAC;AAC/C,OAAO,EAAE,KAAK,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC"}
@@ -4,3 +4,4 @@ export { generateCreateTableSql } from './ddl.js';
4
4
  export { defineTable } from './define-table.js';
5
5
  export { inboxMessages } from './inbox-messages.js';
6
6
  export { queueJobs } from './queue-jobs.js';
7
+ export { resourceLeases } from './resource-leases.js';
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Drizzle schema for the `resource_leases` table (ts-libs task 1483 / ADR-156).
3
+ *
4
+ * A lease is a cross-process admission slot for a named resource: `(resource, holder)` is the
5
+ * identity of one held slot, `expires_at` is the liveness fact, and a crashed holder's row simply
6
+ * stops being live. There is no `id` and no soft state — a row IS a held slot, so its removal is
7
+ * the release.
8
+ */
9
+ export declare const resourceLeases: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
10
+ name: "resource_leases";
11
+ schema: undefined;
12
+ columns: {
13
+ resource: import("drizzle-orm/sqlite-core").SQLiteColumn<{
14
+ name: "resource";
15
+ tableName: "resource_leases";
16
+ dataType: "string";
17
+ columnType: "SQLiteText";
18
+ data: string;
19
+ driverParam: string;
20
+ notNull: true;
21
+ hasDefault: false;
22
+ isPrimaryKey: false;
23
+ isAutoincrement: false;
24
+ hasRuntimeDefault: false;
25
+ enumValues: [string, ...string[]];
26
+ baseColumn: never;
27
+ identity: undefined;
28
+ generated: undefined;
29
+ }, {}, {
30
+ length: number | undefined;
31
+ }>;
32
+ holder: import("drizzle-orm/sqlite-core").SQLiteColumn<{
33
+ name: "holder";
34
+ tableName: "resource_leases";
35
+ dataType: "string";
36
+ columnType: "SQLiteText";
37
+ data: string;
38
+ driverParam: string;
39
+ notNull: true;
40
+ hasDefault: false;
41
+ isPrimaryKey: false;
42
+ isAutoincrement: false;
43
+ hasRuntimeDefault: false;
44
+ enumValues: [string, ...string[]];
45
+ baseColumn: never;
46
+ identity: undefined;
47
+ generated: undefined;
48
+ }, {}, {
49
+ length: number | undefined;
50
+ }>;
51
+ ownerRef: import("drizzle-orm/sqlite-core").SQLiteColumn<{
52
+ name: "owner_ref";
53
+ tableName: "resource_leases";
54
+ dataType: "string";
55
+ columnType: "SQLiteText";
56
+ data: string;
57
+ driverParam: string;
58
+ notNull: false;
59
+ hasDefault: false;
60
+ isPrimaryKey: false;
61
+ isAutoincrement: false;
62
+ hasRuntimeDefault: false;
63
+ enumValues: [string, ...string[]];
64
+ baseColumn: never;
65
+ identity: undefined;
66
+ generated: undefined;
67
+ }, {}, {
68
+ length: number | undefined;
69
+ }>;
70
+ acquiredAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
71
+ name: "acquired_at";
72
+ tableName: "resource_leases";
73
+ dataType: "number";
74
+ columnType: "SQLiteInteger";
75
+ data: number;
76
+ driverParam: number;
77
+ notNull: true;
78
+ hasDefault: false;
79
+ isPrimaryKey: false;
80
+ isAutoincrement: false;
81
+ hasRuntimeDefault: false;
82
+ enumValues: undefined;
83
+ baseColumn: never;
84
+ identity: undefined;
85
+ generated: undefined;
86
+ }, {}, {}>;
87
+ renewedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
88
+ name: "renewed_at";
89
+ tableName: "resource_leases";
90
+ dataType: "number";
91
+ columnType: "SQLiteInteger";
92
+ data: number;
93
+ driverParam: number;
94
+ notNull: true;
95
+ hasDefault: false;
96
+ isPrimaryKey: false;
97
+ isAutoincrement: false;
98
+ hasRuntimeDefault: false;
99
+ enumValues: undefined;
100
+ baseColumn: never;
101
+ identity: undefined;
102
+ generated: undefined;
103
+ }, {}, {}>;
104
+ expiresAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
105
+ name: "expires_at";
106
+ tableName: "resource_leases";
107
+ dataType: "number";
108
+ columnType: "SQLiteInteger";
109
+ data: number;
110
+ driverParam: number;
111
+ notNull: true;
112
+ hasDefault: false;
113
+ isPrimaryKey: false;
114
+ isAutoincrement: false;
115
+ hasRuntimeDefault: false;
116
+ enumValues: undefined;
117
+ baseColumn: never;
118
+ identity: undefined;
119
+ generated: undefined;
120
+ }, {}, {}>;
121
+ };
122
+ dialect: "sqlite";
123
+ }>;
124
+ //# sourceMappingURL=resource-leases.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-leases.d.ts","sourceRoot":"","sources":["../../src/schema/resource-leases.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAoB1B,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { index, integer, primaryKey, sqliteTable, text } from 'drizzle-orm/sqlite-core';
2
+ /**
3
+ * Drizzle schema for the `resource_leases` table (ts-libs task 1483 / ADR-156).
4
+ *
5
+ * A lease is a cross-process admission slot for a named resource: `(resource, holder)` is the
6
+ * identity of one held slot, `expires_at` is the liveness fact, and a crashed holder's row simply
7
+ * stops being live. There is no `id` and no soft state — a row IS a held slot, so its removal is
8
+ * the release.
9
+ */
10
+ export const resourceLeases = sqliteTable('resource_leases', {
11
+ /** Resource name the slot is admitted against (e.g. `replicate:4`, `colab-gpu:1`). */
12
+ resource: text('resource').notNull(),
13
+ /** Stable identity of the holder (a pid/run composite the caller chooses). */
14
+ holder: text('holder').notNull(),
15
+ /** Optional opaque owner reference, so a process can release all of its own slots. */
16
+ ownerRef: text('owner_ref'),
17
+ /** Epoch ms the slot was first acquired. */
18
+ acquiredAt: integer('acquired_at').notNull(),
19
+ /** Epoch ms the slot was last renewed (equals acquiredAt on a fresh acquire). */
20
+ renewedAt: integer('renewed_at').notNull(),
21
+ /** Epoch ms after which the slot is no longer live; reclaim happens lazily. */
22
+ expiresAt: integer('expires_at').notNull(),
23
+ }, (table) => [
24
+ primaryKey({ columns: [table.resource, table.holder] }),
25
+ index('resource_leases_liveness_idx').on(table.resource, table.expiresAt),
26
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gobing-ai/ts-db",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "description": "@gobing-ai/ts-db — a drizzle-free database facade: typed DAOs over Bun SQLite / Cloudflare D1, a small predicate query spec, single-source-of-truth tables, and migrations. Drizzle stays an internal detail.",
5
5
  "keywords": [
6
6
  "typescript",
@@ -66,8 +66,8 @@
66
66
  "release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-db-v<version> && git push --tags' && exit 1"
67
67
  },
68
68
  "dependencies": {
69
- "@gobing-ai/ts-runtime": "^0.8.8",
70
- "@gobing-ai/ts-utils": "^0.8.8"
69
+ "@gobing-ai/ts-runtime": "^0.8.9",
70
+ "@gobing-ai/ts-utils": "^0.8.9"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "drizzle-orm": ">=0.38.0",
@@ -51,4 +51,9 @@ export const embeddedMigrations: EmbeddedMigration[] = [
51
51
  sql: 'ALTER TABLE `inbox_messages` ADD `request_key` text;\nCREATE UNIQUE INDEX `idx_inbox_messages_request_key` ON `inbox_messages` (`request_key`) WHERE `request_key` IS NOT NULL;\n',
52
52
  hash: '7277e79f8339975b29565e7b33e04f0dbd50995b99b82048fd83079757334f71',
53
53
  },
54
+ {
55
+ tag: '0015_resource_leases',
56
+ sql: 'CREATE TABLE `resource_leases` (\n\t`resource` text NOT NULL,\n\t`holder` text NOT NULL,\n\t`owner_ref` text,\n\t`acquired_at` integer NOT NULL,\n\t`renewed_at` integer NOT NULL,\n\t`expires_at` integer NOT NULL,\n\tPRIMARY KEY(`resource`, `holder`)\n);\nCREATE INDEX `resource_leases_liveness_idx` ON `resource_leases` (`resource`,`expires_at`);\n',
57
+ hash: '136a05b580f715fcbc64ffdda98b94b548b515c887837f198c364846d92dc3da',
58
+ },
54
59
  ];
package/src/index.ts CHANGED
@@ -36,4 +36,10 @@ export {
36
36
  type Predicate,
37
37
  } from './query-spec';
38
38
  export { QueueJobDao, type QueueJobRecord, type QueueStats } from './queue-job-dao';
39
+ export {
40
+ type ResourceLease,
41
+ type ResourceLeaseAcquireInput,
42
+ type ResourceLeaseAcquireResult,
43
+ ResourceLeaseDao,
44
+ } from './resource-lease-dao';
39
45
  export type { SpanContext } from './span-context';
@@ -0,0 +1,217 @@
1
+ import type { DbAdapter } from './adapter';
2
+ import { BaseDao } from './base-dao';
3
+
4
+ /** One held lease row, epoch-ms times. */
5
+ export interface ResourceLease {
6
+ resource: string;
7
+ holder: string;
8
+ ownerRef: string | null;
9
+ acquiredAt: number;
10
+ renewedAt: number;
11
+ expiresAt: number;
12
+ }
13
+
14
+ /** Arguments for {@link ResourceLeaseDao.tryAcquire}. */
15
+ export interface ResourceLeaseAcquireInput {
16
+ /** Resource name the slot is admitted against. */
17
+ resource: string;
18
+ /** Maximum live slots for this resource. */
19
+ max: number;
20
+ /** Identity of the asking holder. */
21
+ holder: string;
22
+ /** Lease length in ms; the slot stops being live at `now + ttlMs` unless renewed. */
23
+ ttlMs: number;
24
+ /** Optional owner reference for bulk release. */
25
+ ownerRef?: string;
26
+ }
27
+
28
+ /** Result of {@link ResourceLeaseDao.tryAcquire}. */
29
+ export type ResourceLeaseAcquireResult =
30
+ | { admitted: true; lease: ResourceLease; reclaimed: string[] }
31
+ | { admitted: false; held: number; max: number; holders: string[] };
32
+
33
+ /** Row shape as it comes back from SQLite (snake_case, integers). */
34
+ interface ResourceLeaseRow {
35
+ resource: string;
36
+ holder: string;
37
+ owner_ref: string | null;
38
+ acquired_at: number;
39
+ renewed_at: number;
40
+ expires_at: number;
41
+ }
42
+
43
+ /** Map a raw row to the public record. */
44
+ function toLease(row: ResourceLeaseRow): ResourceLease {
45
+ return {
46
+ resource: row.resource,
47
+ holder: row.holder,
48
+ ownerRef: row.owner_ref,
49
+ acquiredAt: row.acquired_at,
50
+ renewedAt: row.renewed_at,
51
+ expiresAt: row.expires_at,
52
+ };
53
+ }
54
+
55
+ /** Refuse a non-positive-integer bound; a silent coercion here would break the invariant. */
56
+ function assertPositiveInteger(value: unknown, label: string): number {
57
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
58
+ throw new RangeError(`${label} must be a positive integer; received ${String(value)}`);
59
+ }
60
+ return value;
61
+ }
62
+
63
+ /**
64
+ * Cross-process resource admission through expiring lease rows (ts-libs task 1483 / ADR-156).
65
+ *
66
+ * The `max` bound is carried by ONE conditional `INSERT … SELECT … WHERE (live count) < ?max
67
+ * ON CONFLICT DO NOTHING RETURNING *`. A single statement is atomic on every adapter (bun-sqlite's
68
+ * WAL `busy_timeout` waits out a concurrent writer; D1 serializes statements), so no
69
+ * `BEGIN IMMEDIATE`, no in-process map and no count-then-insert in app code.
70
+ *
71
+ * Liveness is `expires_at > now`: an expired row is deleted lazily by the next acquire, which is how
72
+ * a crashed holder's slot comes back. `now` is read once per call and bound as a parameter so every
73
+ * statement in that call agrees on what "live" means.
74
+ *
75
+ * Extends `BaseDao`, not `EntityDao`: `EntityTable` requires `createdAt`/`updatedAt` columns, and the
76
+ * specified schema deliberately has neither (a lease is its timestamps, and none of the inherited
77
+ * CRUD applies to a row whose removal IS the release).
78
+ */
79
+ export class ResourceLeaseDao extends BaseDao {
80
+ /** Table name, exposed for callers that build their own statements. */
81
+ static readonly TABLE = 'resource_leases';
82
+
83
+ /** Public constructor: `BaseDao`'s is protected, and consumers construct this DAO directly. */
84
+ constructor(adapter: DbAdapter) {
85
+ super(adapter);
86
+ }
87
+
88
+ /** Current epoch ms; injectable in tests through {@link ResourceLeaseDao.withClock}. */
89
+ private clock: () => number = () => Date.now();
90
+
91
+ /** Test seam: replace the clock (chainable, returns the same DAO instance). */
92
+ withClock(clock: () => number): this {
93
+ this.clock = clock;
94
+ return this;
95
+ }
96
+
97
+ /**
98
+ * Try to take a slot on `resource`.
99
+ *
100
+ * Order is load-bearing: renew the caller's own live row first (so a re-entrant caller never
101
+ * competes with itself), then reclaim expired rows, then attempt the single conditional insert.
102
+ */
103
+ async tryAcquire(input: ResourceLeaseAcquireInput): Promise<ResourceLeaseAcquireResult> {
104
+ const max = assertPositiveInteger(input.max, 'max');
105
+ const ttlMs = assertPositiveInteger(input.ttlMs, 'ttlMs');
106
+ const now = this.clock();
107
+ const expiresAt = now + ttlMs;
108
+
109
+ const renewed = await this.adapter.queryAll<ResourceLeaseRow>(
110
+ `UPDATE resource_leases SET renewed_at = ?1, expires_at = ?2
111
+ WHERE resource = ?3 AND holder = ?4 AND expires_at > ?1
112
+ RETURNING *`,
113
+ now,
114
+ expiresAt,
115
+ input.resource,
116
+ input.holder,
117
+ );
118
+ const own = renewed[0];
119
+ if (own !== undefined) return { admitted: true, lease: toLease(own), reclaimed: [] };
120
+
121
+ const reclaimedRows = await this.adapter.queryAll<{ holder: string }>(
122
+ `DELETE FROM resource_leases WHERE resource = ?1 AND expires_at <= ?2 RETURNING holder`,
123
+ input.resource,
124
+ now,
125
+ );
126
+ const reclaimed = reclaimedRows.map((row) => row.holder);
127
+
128
+ const inserted = await this.adapter.queryAll<ResourceLeaseRow>(
129
+ `INSERT INTO resource_leases (resource, holder, owner_ref, acquired_at, renewed_at, expires_at)
130
+ SELECT ?1, ?2, ?3, ?4, ?4, ?5
131
+ WHERE (SELECT COUNT(*) FROM resource_leases
132
+ WHERE resource = ?1 AND expires_at > ?4) < ?6
133
+ ON CONFLICT (resource, holder) DO NOTHING
134
+ RETURNING *`,
135
+ input.resource,
136
+ input.holder,
137
+ input.ownerRef ?? null,
138
+ now,
139
+ expiresAt,
140
+ max,
141
+ );
142
+ const taken = inserted[0];
143
+ if (taken !== undefined) return { admitted: true, lease: toLease(taken), reclaimed };
144
+
145
+ const holders = await this.adapter.queryAll<{ holder: string }>(
146
+ `SELECT holder FROM resource_leases WHERE resource = ?1 AND expires_at > ?2 ORDER BY holder`,
147
+ input.resource,
148
+ now,
149
+ );
150
+ return {
151
+ admitted: false,
152
+ held: holders.length,
153
+ max,
154
+ holders: holders.map((row) => row.holder),
155
+ };
156
+ }
157
+
158
+ /** Extend a held slot. `false` means the row is gone or expired — the lease was lost. */
159
+ async renew(resource: string, holder: string, ttlMs: number): Promise<boolean> {
160
+ const ttl = assertPositiveInteger(ttlMs, 'ttlMs');
161
+ const now = this.clock();
162
+ const rows = await this.adapter.queryAll<{ holder: string }>(
163
+ `UPDATE resource_leases SET renewed_at = ?1, expires_at = ?2
164
+ WHERE resource = ?3 AND holder = ?4 AND expires_at > ?1
165
+ RETURNING holder`,
166
+ now,
167
+ now + ttl,
168
+ resource,
169
+ holder,
170
+ );
171
+ return rows.length > 0;
172
+ }
173
+
174
+ /** Release one slot; idempotent. Returns whether a live row was removed. */
175
+ async release(resource: string, holder: string): Promise<boolean> {
176
+ const rows = await this.adapter.queryAll<{ holder: string }>(
177
+ `DELETE FROM resource_leases WHERE resource = ?1 AND holder = ?2 AND expires_at > ?3 RETURNING holder`,
178
+ resource,
179
+ holder,
180
+ this.clock(),
181
+ );
182
+ return rows.length > 0;
183
+ }
184
+
185
+ /** Release every live slot an owner reference holds; returns the number removed. */
186
+ async releaseByOwner(ownerRef: string): Promise<number> {
187
+ const rows = await this.adapter.queryAll<{ holder: string }>(
188
+ `DELETE FROM resource_leases WHERE owner_ref = ?1 AND expires_at > ?2 RETURNING holder`,
189
+ ownerRef,
190
+ this.clock(),
191
+ );
192
+ return rows.length;
193
+ }
194
+
195
+ /**
196
+ * List live slots, optionally for one resource. Expired rows are hidden, never returned.
197
+ *
198
+ * Named `listLive` rather than the design's `list`: `EntityDao` already owns `list(spec)` with a
199
+ * different shape (`EntityListSpec` → raw rows), and an incompatible override is not expressible.
200
+ */
201
+ async listLive(filter: { resource?: string } = {}): Promise<ResourceLease[]> {
202
+ const now = this.clock();
203
+ const rows =
204
+ filter.resource === undefined
205
+ ? await this.adapter.queryAll<ResourceLeaseRow>(
206
+ `SELECT * FROM resource_leases WHERE expires_at > ?1 ORDER BY resource, holder`,
207
+ now,
208
+ )
209
+ : await this.adapter.queryAll<ResourceLeaseRow>(
210
+ `SELECT * FROM resource_leases WHERE resource = ?1 AND expires_at > ?2
211
+ ORDER BY holder`,
212
+ filter.resource,
213
+ now,
214
+ );
215
+ return rows.map(toLease);
216
+ }
217
+ }
@@ -4,3 +4,4 @@ export { generateCreateTableSql } from './ddl';
4
4
  export { type DefinedTable, defineTable } from './define-table';
5
5
  export { inboxMessages } from './inbox-messages';
6
6
  export { queueJobs } from './queue-jobs';
7
+ export { resourceLeases } from './resource-leases';
@@ -0,0 +1,31 @@
1
+ import { index, integer, primaryKey, sqliteTable, text } from 'drizzle-orm/sqlite-core';
2
+
3
+ /**
4
+ * Drizzle schema for the `resource_leases` table (ts-libs task 1483 / ADR-156).
5
+ *
6
+ * A lease is a cross-process admission slot for a named resource: `(resource, holder)` is the
7
+ * identity of one held slot, `expires_at` is the liveness fact, and a crashed holder's row simply
8
+ * stops being live. There is no `id` and no soft state — a row IS a held slot, so its removal is
9
+ * the release.
10
+ */
11
+ export const resourceLeases = sqliteTable(
12
+ 'resource_leases',
13
+ {
14
+ /** Resource name the slot is admitted against (e.g. `replicate:4`, `colab-gpu:1`). */
15
+ resource: text('resource').notNull(),
16
+ /** Stable identity of the holder (a pid/run composite the caller chooses). */
17
+ holder: text('holder').notNull(),
18
+ /** Optional opaque owner reference, so a process can release all of its own slots. */
19
+ ownerRef: text('owner_ref'),
20
+ /** Epoch ms the slot was first acquired. */
21
+ acquiredAt: integer('acquired_at').notNull(),
22
+ /** Epoch ms the slot was last renewed (equals acquiredAt on a fresh acquire). */
23
+ renewedAt: integer('renewed_at').notNull(),
24
+ /** Epoch ms after which the slot is no longer live; reclaim happens lazily. */
25
+ expiresAt: integer('expires_at').notNull(),
26
+ },
27
+ (table) => [
28
+ primaryKey({ columns: [table.resource, table.holder] }),
29
+ index('resource_leases_liveness_idx').on(table.resource, table.expiresAt),
30
+ ],
31
+ );