or3-provider-sqlite 0.0.26 → 0.0.27

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
@@ -13,6 +13,11 @@ Requires **Node.js 24.22.1 or newer on the 24.x line**, matching OR3 Chat. Devel
13
13
  - **Admin stores** (`sqlite`) — workspace access/lifecycle, workspace settings, user search, and deployment-admin grants (local, Bun, and Turso runtimes)
14
14
  - **RateLimitProvider** (`sqlite`) — durable rate-limit counters
15
15
 
16
+ OR3 Chat checks SQLite deployment-admin grants against the canonical user on
17
+ cached sessions. A granted account can manage settings only for a workspace it
18
+ owns; instance administration still requires the super-admin login. D1 does
19
+ not provide the deployment-admin grant store.
20
+
16
21
  SSR-authenticated deployments also activate SQLite when it is selected only by
17
22
  `OR3_LIMITS_ENABLED=true` and `OR3_LIMITS_STORAGE_PROVIDER=sqlite`, independently
18
23
  of the account workspace backend.
@@ -425,3 +430,10 @@ Migrations 030–031 resume safely after interrupted startup and reject incompat
425
430
  Migration 031 adds the dormant upload ledger and restore tickets. The optional coordinator remains unregistered. See [upload, restore, and recovery invariants](docs/storage-generation-uploads.md).
426
431
 
427
432
  Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
433
+
434
+ The dormant generation coordinator now exposes `retainedGenerationQuotaVersion: 1`.
435
+ It charges allocations and Trash through the existing retained ledger and only
436
+ releases enrolled-object charges after confirmed removal acknowledgement. Restores
437
+ reuse their retained charge; replacement waits for confirmed deletion. Legacy
438
+ retained objects cannot be implicitly adopted. This adds no schema migration,
439
+ registration or production cleanup activation.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
3
  "configKey": "or3-provider-sqlite",
4
- "version": "0.0.26",
4
+ "version": "0.0.27",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -58,5 +58,10 @@ export declare class SqliteExternalStorageGenerationCoordinator implements Exter
58
58
  status: 'deleted' | 'replayed';
59
59
  generation: ExternalStorageGenerationRecord;
60
60
  }>;
61
+ /** Runs under the same guarded transaction as removal acknowledgement.
62
+ * Only permanently enrolled targets may release a retained hash charge;
63
+ * legacy objects and any successor/pending generation keep their charge.
64
+ */
65
+ protected releaseManagedRetainedCharge(key: ExternalStorageGenerationKey): void;
61
66
  }
62
67
  export {};
@@ -12,7 +12,7 @@ import {
12
12
  generationReferencesSql,
13
13
  validGenerationReferencesSql
14
14
  } from "../db/storage-generation-guards.js";
15
- import { generationUploadGuardTriggers } from "../db/storage-generation-upload-guards.js";
15
+ import { generationUploadGuardTriggers, GENERATION_UPLOAD_TABLE } from "../db/storage-generation-upload-guards.js";
16
16
  export function assertGenerationIdentifier(value, name, max = 256) {
17
17
  if (typeof value !== "string" || !value || value.length > max || value !== value.trim() || [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)) {
18
18
  throw new Error(`Invalid storage generation ${name}`);
@@ -213,11 +213,33 @@ export class SqliteExternalStorageGenerationCoordinator {
213
213
  return this.mutate(() => {
214
214
  const row = this.find(key);
215
215
  if (!row || row.claim_id !== input.claimId || row.state === "verified") throw new Error("Storage generation claim mismatch");
216
- if (row.state === "deleted") return { status: "replayed", generation: generationRecord(row) };
216
+ if (row.state === "deleted") {
217
+ this.releaseManagedRetainedCharge(key);
218
+ return { status: "replayed", generation: generationRecord(row) };
219
+ }
217
220
  const now = this.now();
218
221
  if (row.claimed_at === null || now < row.claimed_at) throw new Error("Storage generation server clock regressed");
219
222
  this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'deleted', deleted_at = ? WHERE generation_id = ?`).run(now, key.generationId);
223
+ this.releaseManagedRetainedCharge(key);
220
224
  return { status: "deleted", generation: generationRecord(this.find(key)) };
221
225
  });
222
226
  }
227
+ /** Runs under the same guarded transaction as removal acknowledgement.
228
+ * Only permanently enrolled targets may release a retained hash charge;
229
+ * legacy objects and any successor/pending generation keep their charge.
230
+ */
231
+ releaseManagedRetainedCharge(key) {
232
+ const origins = this.raw.prepare(`SELECT generation_id, state, published_generation_id FROM ${GENERATION_UPLOAD_TABLE}
233
+ WHERE workspace_id = ? AND hash = ? AND purpose = 'upload' LIMIT ?`).all(key.workspaceId, key.hash, GENERATION_PROOF_ROWS + 1);
234
+ if (!origins.length || origins.length > GENERATION_PROOF_ROWS) return;
235
+ if (this.raw.prepare(`SELECT 1 FROM ${GENERATION_TABLE} WHERE workspace_id = ? AND hash = ? AND state <> 'deleted' LIMIT 1`).get(key.workspaceId, key.hash)) return;
236
+ if (origins.some((row) => row.state !== "abandoned" && !(row.state === "materialized" && row.published_generation_id === row.generation_id))) return;
237
+ if (this.raw.prepare(`SELECT 1 FROM upload_intents WHERE workspace_id = ? AND hash = ? AND status = 'active' LIMIT 1`).get(key.workspaceId, key.hash)) return;
238
+ const retained = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(key.workspaceId, key.hash);
239
+ if (!retained) return;
240
+ if (!Number.isSafeInteger(retained.size_bytes) || retained.size_bytes < 0) throw new Error("Invalid retained storage charge");
241
+ const result = this.raw.prepare("UPDATE storage_usage SET used_bytes=used_bytes-? WHERE workspace_id=? AND used_bytes>=?").run(retained.size_bytes, key.workspaceId, retained.size_bytes);
242
+ if (result.changes !== 1) throw new Error("Retained storage accounting mismatch");
243
+ this.raw.prepare("DELETE FROM retained_storage WHERE workspace_id=? AND hash=?").run(key.workspaceId, key.hash);
244
+ }
223
245
  }
@@ -25,6 +25,9 @@ type RestoreInput = ExternalStorageGenerationUploadKey & {
25
25
  /** Optional trusted-server factory input only. No adapter or route registers it. */
26
26
  export declare class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExternalStorageGenerationCoordinator implements ExternalStorageGenerationUploadCoordinatorV1 {
27
27
  readonly uploadVersion: 1;
28
+ /** Allocation/Trash/claimed bytes remain in the canonical retained ledger
29
+ * until independently verified removal is acknowledged. */
30
+ readonly retainedGenerationQuotaVersion: 1;
28
31
  private uploadKey;
29
32
  private claimKey;
30
33
  private upload;
@@ -32,6 +35,8 @@ export declare class SqliteExternalStorageGenerationUploadCoordinator extends Sq
32
35
  private mustUpload;
33
36
  private activeIntents;
34
37
  private quotaUsed;
38
+ private retainedBytes;
39
+ private chargedBytes;
35
40
  private sum;
36
41
  reserveGenerationUpload(input: ReserveInput): Promise<{
37
42
  status: 'reserved' | 'replayed';
@@ -3,7 +3,7 @@ import {
3
3
  assertGenerationIdentifier,
4
4
  generationRecord
5
5
  } from "./sqlite-generation-coordinator.js";
6
- import { GENERATION_TABLE, HEAD_TABLE, GENERATION_PROOF_ROWS, generationHashSql, validGenerationHashSql, validGenerationObjectSql } from "../db/storage-generation-guards.js";
6
+ import { GENERATION_TABLE, HEAD_TABLE, GENERATION_PROOF_ROWS, generationHashSql, validGenerationHashSql } from "../db/storage-generation-guards.js";
7
7
  import {
8
8
  GENERATION_UPLOAD_TABLE as UPLOADS,
9
9
  GENERATION_UPLOAD_HOLD_EXPIRY,
@@ -38,6 +38,9 @@ function intent(row) {
38
38
  }
39
39
  export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExternalStorageGenerationCoordinator {
40
40
  uploadVersion = 1;
41
+ /** Allocation/Trash/claimed bytes remain in the canonical retained ledger
42
+ * until independently verified removal is acknowledged. */
43
+ retainedGenerationQuotaVersion = 1;
41
44
  uploadKey(input) {
42
45
  assertGenerationIdentifier(input.intentId, "upload intent");
43
46
  assertGenerationIdentifier(input.userId, "upload owner");
@@ -98,22 +101,29 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
98
101
  return rows;
99
102
  }
100
103
  quotaUsed(workspaceId) {
101
- const rows = this.raw.prepare(`SELECT deleted, data_json, ${validGenerationObjectSql("data_json")} AS valid
102
- FROM s_file_meta WHERE workspace_id = ? LIMIT ?`).all(workspaceId, GENERATION_PROOF_ROWS + 1);
103
- if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: metadata budget");
104
+ const rows = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? LIMIT ?").all(workspaceId, GENERATION_PROOF_ROWS + 1);
105
+ if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: retained budget");
104
106
  let used = 0;
105
107
  for (const row of rows) {
106
- if (row.deleted !== 0) continue;
107
- if (row.valid !== 1) throw new Error("Storage upload invalid canonical metadata");
108
- const data = JSON.parse(row.data_json);
109
- const size = data.size_bytes ?? data.sizeBytes;
110
- if ("size_bytes" in data && "sizeBytes" in data || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
111
- throw new Error("Storage upload invalid canonical file size");
112
- }
113
- used = this.sum(used, size);
108
+ used = this.sum(used, row.size_bytes);
114
109
  }
115
110
  return used;
116
111
  }
112
+ retainedBytes(workspaceId, hash) {
113
+ const row = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(workspaceId, hash);
114
+ return this.sum(0, row?.size_bytes ?? 0);
115
+ }
116
+ chargedBytes(workspaceId, hash, now) {
117
+ let charged = this.quotaUsed(workspaceId);
118
+ const pending = /* @__PURE__ */ new Map();
119
+ for (const row of this.activeIntents(workspaceId)) {
120
+ if (row.expires_at <= now) continue;
121
+ if (row.hash === hash) throw new Error("Storage upload already has an active reservation");
122
+ pending.set(row.hash, Math.max(pending.get(row.hash) ?? 0, row.reserved_bytes));
123
+ }
124
+ for (const [digest, size] of pending) charged = this.sum(charged, Math.max(0, size - this.retainedBytes(workspaceId, digest)));
125
+ return charged;
126
+ }
117
127
  sum(left, right) {
118
128
  const value = left + right;
119
129
  if (!Number.isSafeInteger(value) || value < 0) throw new Error("Storage upload quota accounting overflow");
@@ -148,10 +158,13 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
148
158
  throw new Error("Storage generation identity or target cannot be reused");
149
159
  }
150
160
  const head = this.head(key);
151
- if (head && (head.storage_provider_id !== this.storageProviderId || head.state === "verified")) {
152
- throw new Error("Current storage generation must be irreversibly claimed before replacement");
161
+ if (head && (head.storage_provider_id !== this.storageProviderId || head.state !== "deleted")) {
162
+ throw new Error("Current storage generation must have confirmed removal before replacement");
153
163
  }
154
164
  const enrolled = Boolean(this.raw.prepare(`SELECT 1 FROM ${UPLOADS} WHERE workspace_id = ? AND hash = ? LIMIT 1`).get(key.workspaceId, key.hash));
165
+ if (!enrolled && this.raw.prepare("SELECT 1 FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(key.workspaceId, key.hash)) {
166
+ throw new Error("Storage generation cannot adopt legacy retained bytes");
167
+ }
155
168
  const proof = this.metadataProof(key, !head && !enrolled, input.storageId) ?? this.referenceProof(key, !head && !enrolled);
156
169
  if (proof) throw new Error(`Legacy storage adoption or upload proof failed: ${proof}`);
157
170
  const pending = this.raw.prepare(`SELECT count(*) AS count FROM ${UPLOADS} WHERE workspace_id = ?
@@ -159,12 +172,7 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
159
172
  if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage upload pending allocation limit");
160
173
  const now = this.now();
161
174
  const expires = this.sum(now, input.expiresInSeconds);
162
- let charged = this.quotaUsed(key.workspaceId);
163
- for (const row of this.activeIntents(key.workspaceId)) {
164
- if (row.expires_at <= now) continue;
165
- if (row.hash === key.hash) throw new Error("Storage upload already has an active reservation");
166
- charged = this.sum(charged, row.reserved_bytes);
167
- }
175
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
168
176
  const projectedBytes = this.sum(charged, input.sizeBytes);
169
177
  if (input.workspaceQuotaBytes !== void 0 && projectedBytes > input.workspaceQuotaBytes) {
170
178
  throw new Error("Workspace storage quota exceeded");
@@ -202,6 +210,8 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
202
210
  input.storageId,
203
211
  now
204
212
  );
213
+ this.raw.prepare(`INSERT INTO retained_storage(workspace_id,hash,size_bytes) VALUES (?,?,?)
214
+ ON CONFLICT(workspace_id,hash) DO UPDATE SET size_bytes=MAX(size_bytes,excluded.size_bytes)`).run(key.workspaceId, key.hash, input.sizeBytes);
205
215
  return { status: "reserved", intent: intent(this.mustUpload(key)) };
206
216
  });
207
217
  }
@@ -241,13 +251,8 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
241
251
  if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage restore pending allocation limit");
242
252
  const now = this.now();
243
253
  if (now < generation.last_activity_at) throw new Error("Storage restore server clock regressed");
244
- let charged = this.quotaUsed(key.workspaceId);
245
- for (const row of this.activeIntents(key.workspaceId)) {
246
- if (row.expires_at <= now) continue;
247
- if (row.hash === key.hash) throw new Error("Storage restore already has an active reservation");
248
- charged = this.sum(charged, row.reserved_bytes);
249
- }
250
- const projected = this.sum(charged, origin.size_bytes);
254
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
255
+ const projected = this.sum(charged, Math.max(0, origin.size_bytes - this.retainedBytes(key.workspaceId, key.hash)));
251
256
  if (input.workspaceQuotaBytes !== void 0 && projected > input.workspaceQuotaBytes) throw new Error("Workspace storage quota exceeded");
252
257
  this.raw.prepare(`INSERT INTO ${UPLOADS}
253
258
  (intent_id,workspace_id,hash,generation_id,user_id,storage_provider_id,namespace_id,storage_id,mime_type,
@@ -396,11 +401,15 @@ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExte
396
401
  return this.mutate(() => {
397
402
  const row = this.claimedUpload(key);
398
403
  if (!row) throw new Error("Storage upload abandonment claim mismatch");
399
- if (row.state === "abandoned") return { status: "replayed", intent: intent(row) };
404
+ if (row.state === "abandoned") {
405
+ this.releaseManagedRetainedCharge(key);
406
+ return { status: "replayed", intent: intent(row) };
407
+ }
400
408
  const now = this.now();
401
409
  if (row.claimed_at === null || now < row.claimed_at) throw new Error("Storage upload server clock regressed");
402
410
  if (row.published_generation_id !== null) this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'deleted', deleted_at = ? WHERE generation_id = ? AND state = 'claimed'`).run(now, key.generationId);
403
411
  this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'abandoned', deleted_at = ? WHERE intent_id = ?`).run(now, key.intentId);
412
+ this.releaseManagedRetainedCharge(key);
404
413
  return { status: "abandoned", intent: intent(this.upload(key)) };
405
414
  });
406
415
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.26",
3
+ "version": "0.0.27",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"