@rocicorp/zero 1.11.0-canary.15 → 1.11.0-canary.16

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.
Files changed (107) hide show
  1. package/out/replicache/src/bg-interval.d.ts +2 -1
  2. package/out/replicache/src/bg-interval.d.ts.map +1 -1
  3. package/out/replicache/src/bg-interval.js +13 -4
  4. package/out/replicache/src/bg-interval.js.map +1 -1
  5. package/out/replicache/src/dag/lazy-store.d.ts +17 -4
  6. package/out/replicache/src/dag/lazy-store.d.ts.map +1 -1
  7. package/out/replicache/src/dag/lazy-store.js +35 -9
  8. package/out/replicache/src/dag/lazy-store.js.map +1 -1
  9. package/out/replicache/src/dag/store-impl.d.ts.map +1 -1
  10. package/out/replicache/src/dag/store-impl.js +7 -1
  11. package/out/replicache/src/dag/store-impl.js.map +1 -1
  12. package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
  13. package/out/replicache/src/kv/sqlite-store.js +4 -6
  14. package/out/replicache/src/kv/sqlite-store.js.map +1 -1
  15. package/out/replicache/src/persist/client-gc.d.ts +2 -1
  16. package/out/replicache/src/persist/client-gc.d.ts.map +1 -1
  17. package/out/replicache/src/persist/client-gc.js +2 -2
  18. package/out/replicache/src/persist/client-gc.js.map +1 -1
  19. package/out/replicache/src/persist/client-group-gc.d.ts +2 -1
  20. package/out/replicache/src/persist/client-group-gc.d.ts.map +1 -1
  21. package/out/replicache/src/persist/client-group-gc.js +2 -2
  22. package/out/replicache/src/persist/client-group-gc.js.map +1 -1
  23. package/out/replicache/src/persist/collect-idb-databases.d.ts +2 -1
  24. package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
  25. package/out/replicache/src/persist/collect-idb-databases.js +2 -2
  26. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
  27. package/out/replicache/src/persist/heartbeat.d.ts +2 -1
  28. package/out/replicache/src/persist/heartbeat.d.ts.map +1 -1
  29. package/out/replicache/src/persist/heartbeat.js +2 -2
  30. package/out/replicache/src/persist/heartbeat.js.map +1 -1
  31. package/out/replicache/src/replicache-impl.d.ts +34 -3
  32. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  33. package/out/replicache/src/replicache-impl.js +104 -27
  34. package/out/replicache/src/replicache-impl.js.map +1 -1
  35. package/out/zero/package.js +1 -1
  36. package/out/zero/package.js.map +1 -1
  37. package/out/zero-cache/src/config/zero-config.d.ts +23 -0
  38. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  39. package/out/zero-cache/src/config/zero-config.js +67 -16
  40. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  41. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +1 -1
  42. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  43. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +4 -1
  44. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  45. package/out/zero-cache/src/services/plannerz.d.ts +5 -1
  46. package/out/zero-cache/src/services/plannerz.d.ts.map +1 -1
  47. package/out/zero-cache/src/services/plannerz.js +8 -4
  48. package/out/zero-cache/src/services/plannerz.js.map +1 -1
  49. package/out/zero-cache/src/services/profz.d.ts +24 -1
  50. package/out/zero-cache/src/services/profz.d.ts.map +1 -1
  51. package/out/zero-cache/src/services/profz.js +43 -3
  52. package/out/zero-cache/src/services/profz.js.map +1 -1
  53. package/out/zero-cache/src/services/statz.d.ts +4 -0
  54. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  55. package/out/zero-cache/src/services/statz.js +22 -5
  56. package/out/zero-cache/src/services/statz.js.map +1 -1
  57. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/view-syncer/snapshotter.js +21 -2
  59. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  60. package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
  61. package/out/zero-client/src/client/mutator-proxy.js +3 -1
  62. package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
  63. package/out/zero-client/src/client/options.d.ts +2 -1
  64. package/out/zero-client/src/client/options.d.ts.map +1 -1
  65. package/out/zero-client/src/client/options.js.map +1 -1
  66. package/out/zero-client/src/client/version.js +1 -1
  67. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  68. package/out/zero-client/src/client/zero.js +2 -1
  69. package/out/zero-client/src/client/zero.js.map +1 -1
  70. package/out/zero-server/src/logging.d.ts +2 -2
  71. package/out/zero-server/src/logging.d.ts.map +1 -1
  72. package/out/zero-server/src/logging.js +2 -2
  73. package/out/zero-server/src/logging.js.map +1 -1
  74. package/out/zero-server/src/process-mutations.d.ts +12 -3
  75. package/out/zero-server/src/process-mutations.d.ts.map +1 -1
  76. package/out/zero-server/src/process-mutations.js +13 -8
  77. package/out/zero-server/src/process-mutations.js.map +1 -1
  78. package/out/zero-server/src/push-processor.d.ts +8 -2
  79. package/out/zero-server/src/push-processor.d.ts.map +1 -1
  80. package/out/zero-server/src/push-processor.js +12 -4
  81. package/out/zero-server/src/push-processor.js.map +1 -1
  82. package/out/zql/src/ivm/cap.d.ts.map +1 -1
  83. package/out/zql/src/ivm/cap.js +1 -0
  84. package/out/zql/src/ivm/cap.js.map +1 -1
  85. package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
  86. package/out/zql/src/ivm/flipped-join.js +1 -0
  87. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  88. package/out/zql/src/ivm/join-utils.d.ts +1 -0
  89. package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
  90. package/out/zql/src/ivm/join-utils.js.map +1 -1
  91. package/out/zql/src/ivm/join.d.ts.map +1 -1
  92. package/out/zql/src/ivm/join.js +1 -0
  93. package/out/zql/src/ivm/join.js.map +1 -1
  94. package/out/zql/src/ivm/memory-storage.d.ts +1 -0
  95. package/out/zql/src/ivm/memory-storage.d.ts.map +1 -1
  96. package/out/zql/src/ivm/memory-storage.js +1 -0
  97. package/out/zql/src/ivm/memory-storage.js.map +1 -1
  98. package/out/zql/src/ivm/operator.d.ts +6 -0
  99. package/out/zql/src/ivm/operator.d.ts.map +1 -1
  100. package/out/zql/src/ivm/operator.js.map +1 -1
  101. package/out/zql/src/ivm/take.d.ts.map +1 -1
  102. package/out/zql/src/ivm/take.js +1 -0
  103. package/out/zql/src/ivm/take.js.map +1 -1
  104. package/out/zqlite/src/database-storage.d.ts.map +1 -1
  105. package/out/zqlite/src/database-storage.js +9 -1
  106. package/out/zqlite/src/database-storage.js.map +1 -1
  107. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-store.js","names":["#filename","#entry","#kind","#closed","#release","#preparedStatements","#pendingHasKeys","#pendingHasCallbacks","#scheduleLookup","#pendingGetKeys","#pendingGetCallbacks","#scheduled","#dbDelegate","#committed"],"sources":["../../../../../replicache/src/kv/sqlite-store.ts"],"sourcesContent":["import {RWLock} from '@rocicorp/lock';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\nimport {deepFreeze} from '../frozen-json.ts';\nimport {\n StorageFailureError,\n type StorageFailureKind,\n} from '../storage-failure.ts';\nimport type {Read, Store, Write} from './store.ts';\nimport {\n maybeTransactionIsClosedRejection,\n throwIfStoreClosed,\n transactionError,\n} from './throw-if-closed.ts';\nimport {deleteSentinel, WriteImplBase} from './write-impl-base.ts';\n\n/**\n * A SQLite prepared statement.\n *\n * `SQLiteStore` prepares one statement per SQL and shares it across all\n * concurrent readers, so implementations must make each call atomic with\n * respect to other callers of the same statement: `all()` must not let another\n * `exec()`/`all()` rebind or reset the underlying statement between executing\n * it and fetching its rows. Delegates whose native API splits execute and fetch\n * into separate round trips (e.g. expo-sqlite) must serialize per statement.\n */\nexport interface PreparedStatement {\n exec(params: string[]): Promise<void>;\n all(params: string[]): Promise<unknown[][]>;\n}\n\nexport interface SQLiteDatabase {\n /**\n * Close the database connection.\n */\n close(): void;\n\n /**\n * Destroy or delete the database (e.g. delete file).\n */\n destroy(): void;\n\n /**\n * Prepare a SQL string, returning a statement you can execute.\n * E.g. `const stmt = db.prepare(\"SELECT * FROM todos WHERE id=?\");`\n */\n prepare(sql: string): PreparedStatement;\n\n // for PRAGMA statements, schema creation and transaction control.\n execSync(sql: string): void;\n}\n\nexport type CreateSQLiteDatabase = (\n filename: string,\n opts?: SQLiteStoreOptions,\n) => SQLiteDatabase;\n\n/**\n * SQLite-based implementation of the Store interface using a configurable delegate.\n * Supports shared connections between multiple store instances with the same name,\n * providing efficient resource utilization and proper transaction isolation.\n * Uses parameterized queries for safety and performance.\n */\nexport class SQLiteStore implements Store {\n readonly #filename: string;\n readonly #entry: StoreEntry;\n readonly #kind: string;\n\n #closed = false;\n\n constructor(\n name: string,\n create: CreateSQLiteDatabase,\n opts?: SQLiteStoreOptions,\n kind = 'sqlite',\n ) {\n this.#filename = resolveFilename(name, opts);\n this.#entry = getOrCreateEntry(this.#filename, create, opts);\n this.#kind = kind;\n }\n\n get kind(): string {\n return this.#kind;\n }\n\n async read(): Promise<Read> {\n throwIfStoreClosed(this);\n\n const entry = this.#entry;\n const {db, lock, preparedStatements} = entry;\n const release = await lock.read();\n\n // Start shared read transaction if this is the first reader\n // This ensures consistent reads across all concurrent readers\n try {\n if (entry.activeReaders === 0) {\n db.execSync('BEGIN');\n }\n } catch (e) {\n // The lock was acquired above; without this every later read() and\n // write() on the store waits for a release that never comes.\n release();\n throw e;\n }\n entry.activeReaders++;\n\n return new SQLiteStoreRead(() => {\n entry.activeReaders--;\n // Commit shared read transaction when last reader finishes. SQLite may\n // already have rolled the transaction back on its own (an I/O error\n // inside any reader's statement does that), in which case COMMIT\n // throws \"cannot commit - no transaction is active\". The error is\n // reported to the releasing reader, but the RWLock must be released\n // regardless or the store hangs for the rest of the process.\n try {\n if (entry.activeReaders === 0) {\n db.execSync('COMMIT');\n }\n } finally {\n release();\n }\n }, preparedStatements);\n }\n\n async write(): Promise<Write> {\n throwIfStoreClosed(this);\n\n const {lock, db, preparedStatements} = this.#entry;\n const release = await lock.write();\n\n // At this point, RWLock guarantees no active readers\n // The last reader would have already committed the shared transaction\n\n try {\n db.execSync('BEGIN IMMEDIATE');\n } catch (e) {\n // SQLITE_BUSY once busy_timeout expires, or an I/O error. The caller\n // gets the error; the write lock must not stay held.\n release();\n throw e;\n }\n\n return new SQLiteWrite(release, db, preparedStatements);\n }\n\n async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n\n const {lock, db} = this.#entry;\n // Wait for all readers and writers to finish.\n const writeRelease = await lock.write();\n\n // Handle reference counting for shared stores - only close database\n // when this is the last store instance using it\n decrementStoreRefCount(this.#filename, db);\n\n this.#closed = true;\n writeRelease();\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\nexport function safeFilename(name: string): string {\n return name.replace(/[^a-zA-Z0-9]/g, '_');\n}\n\nfunction resolveFilename(name: string, opts?: SQLiteStoreOptions): string {\n const safe = safeFilename(name);\n const dir = opts?.directory;\n return dir ? `${dir}/${safe}` : safe;\n}\n\nexport type PreparedStatements = {\n has: PreparedStatement;\n get: PreparedStatement;\n hasMany: PreparedStatement;\n getMany: PreparedStatement;\n put: PreparedStatement;\n del: PreparedStatement;\n /** Multi-row INSERT with the values bound as parameters, n rows wide. */\n putN: (n: number) => PreparedStatement;\n /** Multi-key DELETE with the keys bound as parameters, n keys wide. */\n delN: (n: number) => PreparedStatement;\n};\n\n/**\n * Widest batch we bind in one statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is\n * 32766, and a put costs two parameters per row, so this is far below the cap;\n * it exists to bound how many distinct statements we prepare and cache.\n */\nconst MAX_BATCH = 128;\n\n/** `repeatList('?', 3)` -> `'?,?,?'`. */\nfunction repeatList(item: string, n: number): string {\n return `${item},`.repeat(n).slice(0, -1);\n}\n\n/**\n * Prepares (and caches) a statement of each width on demand. Callers only ever\n * ask for powers of two, so the cache holds at most log2(MAX_BATCH)+1 entries\n * however many rows a commit turns out to have.\n */\nfunction batchStatements(\n delegate: SQLiteDatabase,\n sqlFor: (n: number) => string,\n): (n: number) => PreparedStatement {\n const cache = new Map<number, PreparedStatement>();\n return (n: number) =>\n getOrInsertComputed(cache, n, () => delegate.prepare(sqlFor(n)));\n}\n\n/**\n * Runs `items` through `getStatement` in power-of-two sized batches, so any\n * length is covered by a handful of cached statement widths.\n */\nasync function execInBatches<T>(\n items: readonly T[],\n getStatement: (n: number) => PreparedStatement,\n toParams: (item: T, out: string[]) => void,\n): Promise<void> {\n for (let i = 0; i < items.length;) {\n const remaining = Math.min(MAX_BATCH, items.length - i);\n const n = 1 << (31 - Math.clz32(remaining));\n const params: string[] = [];\n for (let j = 0; j < n; j++) {\n toParams(items[i + j], params);\n }\n await getStatement(n).exec(params);\n i += n;\n }\n}\n\nexport interface SQLiteStoreOptions {\n // Common options\n busyTimeout?: number;\n journalMode?: 'WAL' | 'DELETE';\n synchronous?: 'NORMAL' | 'FULL';\n readUncommitted?: boolean;\n /** Directory in which to create the SQLite file. Defaults to the process CWD. */\n directory?: string | undefined;\n}\n\n/**\n * Replicache's rows are B-tree chunks, which `BTreeWrite` targets at 8-16KB, so\n * most of them are larger than a page and spill into overflow pages at either\n * page size. 8192 does not avoid overflow; it halves the number of pages each\n * chunk is split across.\n *\n * Measured with `replicache-perf/rn`, 4096 vs 8192 + mmap, change in time:\n *\n * | device | persist 1024x10000 | startup read (expo / op) |\n * | ---------------------- | ------------------ | ------------------------ |\n * | iOS simulator | -6% | -12% / -14% |\n * | Android emulator, 2GB | -1% to -2% | -19% / -8% |\n * | Pixel 6 | ~0% | ~-40% / ~0% |\n *\n * Split by pragma on iOS, page_size carries the write win (~6%) and mmap most\n * of the read win. Neither regressed anything on any device.\n */\nconst PAGE_SIZE = 8192;\n\n/** 256MB, matching op-sqlite's own key-value store. */\nconst MMAP_SIZE = 268435456;\n\n/**\n * Common database setup logic shared between expo-sqlite and op-sqlite implementations.\n * Configures SQLite pragmas, creates the entry table, and prepares common statements.\n */\n\nexport function setupDatabase(\n delegate: SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): PreparedStatements {\n // Configure SQLite pragmas for optimal performance.\n //\n // page_size MUST come first. SQLite silently ignores it once the database\n // has content or a journal mode has been set — no error, no warning, the\n // pragma just does nothing and you are left on the 4096 default. Verified:\n // issuing it after `journal_mode = WAL`, or after CREATE TABLE, leaves\n // `PRAGMA page_size` reporting 4096. Do not reorder these.\n delegate.execSync(`PRAGMA page_size = ${PAGE_SIZE}`);\n delegate.execSync(`PRAGMA busy_timeout = ${opts?.busyTimeout ?? 200}`);\n delegate.execSync(`PRAGMA journal_mode = '${opts?.journalMode ?? 'WAL'}'`);\n delegate.execSync(`PRAGMA synchronous = '${opts?.synchronous ?? 'NORMAL'}'`);\n delegate.execSync(\n `PRAGMA read_uncommitted = ${Boolean(opts?.readUncommitted)}`,\n );\n // Reads served from the mmap window rather than the pager account for most\n // of the startup-read win measured in the PAGE_SIZE comment.\n delegate.execSync(`PRAGMA mmap_size = ${MMAP_SIZE}`);\n\n // Create the entry table.\n //\n // This is deliberately a rowid table, not `WITHOUT ROWID`. A `WITHOUT ROWID`\n // table stores whole rows in an index B-tree, which keeps at most ~1/4 of a\n // page inline, and SQLite recommends it only for rows under ~1/20 of a page.\n // Our rows are 8-16KB chunks. As a rowid table the key gets a small separate\n // index and the values live in the table B-tree. On a Pixel 6 (5 rounds, on\n // top of the pragmas above) that cut startup read by 24% on both expo and\n // op, expo startup scan by 10%, and persist 1024x10000 by 4-7%.\n //\n // `key` needs an explicit NOT NULL: in a rowid table a non-INTEGER primary key\n // is only a UNIQUE index, and SQLite (a bug kept for compatibility) lets it\n // hold NULLs, several of them. `WITHOUT ROWID` enforced this implicitly.\n //\n // `IF NOT EXISTS` leaves an existing database's table as it was created, so\n // stores created before this change stay `WITHOUT ROWID` until recreated.\n delegate.execSync(`\n CREATE TABLE IF NOT EXISTS entry (\n key TEXT PRIMARY KEY NOT NULL,\n value TEXT NOT NULL\n )\n `);\n\n // Prepare common statements\n return {\n has: delegate.prepare(`SELECT 1 FROM entry WHERE key = ? LIMIT 1`),\n get: delegate.prepare('SELECT value FROM entry WHERE key = ?'),\n hasMany: delegate.prepare(\n `SELECT key FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n getMany: delegate.prepare(\n `SELECT key, value FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n put: delegate.prepare(\n `INSERT OR REPLACE INTO entry (key, value)\n SELECT e.value->>0, e.value->1 FROM json_each(?) e`,\n ),\n del: delegate.prepare(\n `DELETE FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n putN: batchStatements(\n delegate,\n n =>\n `INSERT OR REPLACE INTO entry (key, value) VALUES ${repeatList('(?,?)', n)}`,\n ),\n delN: batchStatements(\n delegate,\n n => `DELETE FROM entry WHERE key IN (${repeatList('?', n)})`,\n ),\n };\n}\n\n// Callbacks are stored as striped pairs: [resolve, reject, resolve, reject, ...]\nconst CB_STRIDE = 2;\nconst CB_RESOLVE = 0;\nconst CB_REJECT = 1;\n\ntype GetResolve = (v: ReadonlyJSONValue | undefined) => void;\ntype HasResolve = (v: boolean) => void;\ntype Reject = (e: unknown) => void;\n\nfunction rejectAll(callbacks: unknown[], e: unknown): void {\n for (let i = CB_REJECT; i < callbacks.length; i += CB_STRIDE) {\n (callbacks[i] as Reject)(e);\n }\n}\n\nfunction parseRawValue(raw: string | undefined): ReadonlyJSONValue | undefined {\n return raw === undefined\n ? undefined\n : deepFreeze(JSON.parse(raw) as ReadonlyJSONValue);\n}\n\nfunction resolveGet(\n resolve: GetResolve,\n reject: Reject,\n raw: string | undefined,\n): void {\n try {\n resolve(parseRawValue(raw));\n } catch (e) {\n reject(e);\n }\n}\n\nasync function flushGets(\n keys: string[],\n callbacks: unknown[],\n ps: PreparedStatements,\n): Promise<void> {\n let rows: unknown[][];\n try {\n rows =\n keys.length === 1\n ? await ps.get.all([keys[0]])\n : await ps.getMany.all([JSON.stringify(keys)]);\n } catch (e) {\n rejectAll(callbacks, e);\n return;\n }\n if (keys.length === 1) {\n resolveGet(\n callbacks[CB_RESOLVE] as GetResolve,\n callbacks[CB_REJECT] as Reject,\n rows[0]?.[0] as string | undefined,\n );\n return;\n }\n const resultMap = new Map(rows as [string, string][]);\n for (let i = 0; i < keys.length; i++) {\n resolveGet(\n callbacks[i * CB_STRIDE + CB_RESOLVE] as GetResolve,\n callbacks[i * CB_STRIDE + CB_REJECT] as Reject,\n resultMap.get(keys[i]),\n );\n }\n}\n\nasync function flushHas(\n keys: string[],\n callbacks: unknown[],\n ps: PreparedStatements,\n): Promise<void> {\n let rows: unknown[][];\n try {\n rows =\n keys.length === 1\n ? await ps.has.all([keys[0]])\n : await ps.hasMany.all([JSON.stringify(keys)]);\n } catch (e) {\n rejectAll(callbacks, e);\n return;\n }\n if (keys.length === 1) {\n (callbacks[CB_RESOLVE] as HasResolve)(rows.length > 0);\n return;\n }\n const existingKeys = new Set(rows.map(row => row[0] as string));\n for (let i = 0; i < keys.length; i++) {\n (callbacks[i * CB_STRIDE + CB_RESOLVE] as HasResolve)(\n existingKeys.has(keys[i]),\n );\n }\n}\n\nexport class SQLiteStoreRead implements Read {\n readonly #release: () => void;\n readonly #preparedStatements: PreparedStatements;\n #closed = false;\n #pendingGetKeys: string[] = [];\n #pendingGetCallbacks: unknown[] = [];\n #pendingHasKeys: string[] = [];\n #pendingHasCallbacks: unknown[] = [];\n #scheduled = false;\n\n constructor(release: () => void, preparedStatements: PreparedStatements) {\n this.#release = release;\n this.#preparedStatements = preparedStatements;\n }\n\n has(key: string): Promise<boolean> {\n return (\n maybeTransactionIsClosedRejection(this) ??\n new Promise((resolve, reject) => {\n this.#pendingHasKeys.push(key);\n this.#pendingHasCallbacks.push(resolve, reject);\n this.#scheduleLookup();\n })\n );\n }\n\n get(key: string): Promise<ReadonlyJSONValue | undefined> {\n return (\n maybeTransactionIsClosedRejection(this) ??\n new Promise((resolve, reject) => {\n this.#pendingGetKeys.push(key);\n this.#pendingGetCallbacks.push(resolve, reject);\n this.#scheduleLookup();\n })\n );\n }\n\n #scheduleLookup(): void {\n if (!this.#scheduled) {\n this.#scheduled = true;\n queueMicrotask(() => {\n this.#scheduled = false;\n\n const ps = this.#preparedStatements;\n const getKeys = this.#pendingGetKeys;\n this.#pendingGetKeys = [];\n const getCallbacks = this.#pendingGetCallbacks;\n this.#pendingGetCallbacks = [];\n const hasKeys = this.#pendingHasKeys;\n this.#pendingHasKeys = [];\n const hasCallbacks = this.#pendingHasCallbacks;\n this.#pendingHasCallbacks = [];\n\n if (this.#closed) {\n const e = transactionError();\n rejectAll(getCallbacks, e);\n rejectAll(hasCallbacks, e);\n return;\n }\n\n if (getKeys.length > 0) {\n void flushGets(getKeys, getCallbacks, ps);\n }\n if (hasKeys.length > 0) {\n void flushHas(hasKeys, hasCallbacks, ps);\n }\n });\n }\n }\n\n release(): void {\n if (!this.#closed) {\n this.#closed = true;\n this.#release();\n }\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\nexport class SQLiteWrite extends WriteImplBase implements Write {\n readonly #release: () => void;\n readonly #dbDelegate: SQLiteDatabase;\n readonly #preparedStatements: PreparedStatements;\n #committed = false;\n #closed = false;\n\n constructor(\n release: () => void,\n dbDelegate: SQLiteDatabase,\n preparedStatements: PreparedStatements,\n ) {\n super(new SQLiteStoreRead(() => undefined, preparedStatements));\n this.#release = release;\n this.#dbDelegate = dbDelegate;\n this.#preparedStatements = preparedStatements;\n }\n\n async commit(): Promise<void> {\n if (this.#closed) {\n throw transactionError();\n }\n\n const deleteKeys: string[] = [];\n for (const entry of this._pending) {\n if (entry[1] === deleteSentinel) {\n deleteKeys.push(entry[0]);\n this._pending.delete(entry[0]);\n }\n }\n\n // Bind real parameters rather than serializing the whole pending set into\n // one JSON document for json_each() to parse back out. Serializing it, and\n // pushing the resulting (often megabyte-scale) string across the native\n // bridge, measured as roughly a quarter of persist on device.\n //\n // Puts and deletes use different statements over disjoint keys (deletes\n // were removed from _pending above), so they overlap. The batches *within*\n // each must not: the power-of-two split reuses a width when a commit is\n // wide enough (300 rows -> 128, 128, 32, 8, 4), and running two of those\n // concurrently would have two callers on one prepared statement — the\n // rebind-during-execute hazard described in kv/expo-sqlite/store.ts, which\n // op-sqlite has no per-statement lock to absorb.\n const putP =\n this._pending.size > 0\n ? execInBatches(\n [...this._pending] as [string, ReadonlyJSONValue][],\n this.#preparedStatements.putN,\n ([key, value], out) => {\n out.push(key, JSON.stringify(value));\n },\n )\n : undefined;\n const delP =\n deleteKeys.length > 0\n ? execInBatches(\n deleteKeys,\n this.#preparedStatements.delN,\n (key, out) => {\n out.push(key);\n },\n )\n : undefined;\n\n if (putP) await putP;\n if (delP) await delP;\n\n this.#dbDelegate.execSync('COMMIT');\n this._pending.clear();\n this.#committed = true;\n }\n\n release(): void {\n if (!this.#closed) {\n this.#closed = true;\n super.release();\n let rollbackError: unknown;\n if (!this.#committed) {\n try {\n this.#dbDelegate.execSync('ROLLBACK');\n } catch (e) {\n rollbackError = e;\n }\n }\n this.#release();\n if (rollbackError !== undefined) {\n throw rollbackError;\n }\n }\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\ntype StoreEntry = {\n readonly lock: RWLock;\n readonly db: SQLiteDatabase;\n refCount: number;\n activeReaders: number;\n preparedStatements: PreparedStatements;\n};\n\n// Global map to share database connections between multiple store instances with the same name\nconst stores = new Map<string, StoreEntry>();\n\n/**\n * Gets an existing store entry or creates a new one if it doesn't exist.\n * This implements the shared connection pattern where multiple stores with the same\n * name share the same database connection, lock, and delegate.\n */\nfunction getOrCreateEntry(\n filename: string,\n create: (filename: string, opts?: SQLiteStoreOptions) => SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): StoreEntry {\n const entry = stores.get(filename);\n\n if (entry) {\n entry.refCount++;\n return entry;\n }\n\n const dbDelegate = reportingStorageFailures(\n rethrowingStorageFailures(() => create(filename, opts)),\n );\n let preparedStatements: PreparedStatements;\n try {\n preparedStatements = setupDatabase(dbDelegate, opts);\n } catch (e) {\n // Not in `stores` yet, so nothing else would close this connection.\n try {\n dbDelegate.close();\n } catch {\n // The setup error is the one to report.\n }\n throw e;\n }\n\n const lock = new RWLock();\n\n const newEntry: StoreEntry = {\n lock,\n db: dbDelegate,\n refCount: 1,\n activeReaders: 0,\n preparedStatements,\n };\n stores.set(filename, newEntry);\n return newEntry;\n}\n\nconst STORAGE_FAILURE_SIGNATURES = [\n [/database or disk is full|SQLITE_FULL/, 'full'],\n [/unable to open database file|SQLITE_CANTOPEN/, 'cannot-open'],\n [/disk I\\/O error|SQLITE_IOERR/, 'io-error'],\n] as const;\n\n/**\n * The storage failure a SQLite error reports, if any. Matched on SQLite's own\n * `sqlite3_errmsg` text (or its symbolic code), which expo-sqlite, op-sqlite\n * and zero-sqlite all surface inside whatever wrapper they add.\n * `SQLITE_BUSY` is deliberately not one: it is contention, and `busy_timeout`\n * plus a retry is the right answer to it.\n */\nexport function classifySQLiteError(\n error: unknown,\n): StorageFailureKind | undefined {\n const message =\n error instanceof Error\n ? `${error.name}: ${error.message}`\n : typeof error === 'string'\n ? error\n : '';\n for (const [signature, kind] of STORAGE_FAILURE_SIGNATURES) {\n if (signature.test(message)) {\n return kind;\n }\n }\n return undefined;\n}\n\nfunction toStorageFailure(error: unknown): unknown {\n const kind = classifySQLiteError(error);\n return kind === undefined\n ? error\n : new StorageFailureError(\n kind,\n error instanceof Error ? error.message : String(error),\n {cause: error},\n );\n}\n\nfunction rethrowingStorageFailures<T>(f: () => T): T {\n try {\n return f();\n } catch (e) {\n throw toStorageFailure(e);\n }\n}\n\n/**\n * Wraps the driver so every SQLite error that reports a storage failure\n * reaches the store's callers as a {@link StorageFailureError}, whichever\n * statement or transaction step it came from.\n */\nfunction reportingStorageFailures(db: SQLiteDatabase): SQLiteDatabase {\n return {\n close: () => db.close(),\n destroy: () => db.destroy(),\n execSync: sql => rethrowingStorageFailures(() => db.execSync(sql)),\n prepare: sql => {\n const statement = rethrowingStorageFailures(() => db.prepare(sql));\n return {\n exec: async params => {\n try {\n return await statement.exec(params);\n } catch (e) {\n throw toStorageFailure(e);\n }\n },\n all: async params => {\n try {\n return await statement.all(params);\n } catch (e) {\n throw toStorageFailure(e);\n }\n },\n };\n },\n };\n}\n\n/**\n * Decrements the reference count for a shared store and cleans up resources\n * when the last reference is released.\n */\n\nfunction decrementStoreRefCount(\n filename: string,\n dbDelegate: SQLiteDatabase,\n): void {\n const entry = stores.get(filename);\n if (entry) {\n entry.refCount--;\n if (entry.refCount <= 0) {\n dbDelegate.close();\n stores.delete(filename);\n }\n }\n}\nexport function clearAllNamedStoresForTesting(): void {\n for (const entry of stores.values()) {\n entry.db.close();\n }\n stores.clear();\n}\n\nexport function dropStore(\n name: string,\n createDelegate: (\n filename: string,\n opts?: SQLiteStoreOptions,\n ) => SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): Promise<void> {\n const filename = resolveFilename(name, opts);\n const entry = stores.get(filename);\n if (entry) {\n try {\n entry.db.close();\n } catch {\n // Ignore close errors\n }\n stores.delete(filename);\n }\n\n // Create a temporary delegate to handle database deletion\n const tempDelegate = createDelegate(filename, opts);\n try {\n // we close the db before destroying it - this\n // caused an issue with expo-sqlite since it requires this\n tempDelegate.close();\n } catch {\n // Ignore close errors\n }\n try {\n tempDelegate.destroy();\n } catch {\n // Destroy errors shouldn't be fatal; the file may already be gone or locked\n }\n\n return Promise.resolve();\n}\n"],"mappings":";;;;;;;;;;;;;AA+DA,IAAa,cAAb,MAA0C;CACxC;CACA;CACA;CAEA,UAAU;CAEV,YACE,MACA,QACA,MACA,OAAO,UACP;EACA,KAAKA,YAAY,gBAAgB,MAAM,IAAI;EAC3C,KAAKC,SAAS,iBAAiB,KAAKD,WAAW,QAAQ,IAAI;EAC3D,KAAKE,QAAQ;CACf;CAEA,IAAI,OAAe;EACjB,OAAO,KAAKA;CACd;CAEA,MAAM,OAAsB;EAC1B,mBAAmB,IAAI;EAEvB,MAAM,QAAQ,KAAKD;EACnB,MAAM,EAAC,IAAI,MAAM,uBAAsB;E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
1
+ {"version":3,"file":"sqlite-store.js","names":["#filename","#entry","#kind","#closed","#release","#preparedStatements","#pendingHasKeys","#pendingHasCallbacks","#scheduleLookup","#pendingGetKeys","#pendingGetCallbacks","#scheduled","#dbDelegate","#committed"],"sources":["../../../../../replicache/src/kv/sqlite-store.ts"],"sourcesContent":["import {RWLock} from '@rocicorp/lock';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\nimport {deepFreeze} from '../frozen-json.ts';\nimport {\n StorageFailureError,\n type StorageFailureKind,\n} from '../storage-failure.ts';\nimport type {Read, Store, Write} from './store.ts';\nimport {\n maybeTransactionIsClosedRejection,\n throwIfStoreClosed,\n transactionError,\n} from './throw-if-closed.ts';\nimport {deleteSentinel, WriteImplBase} from './write-impl-base.ts';\n\n/**\n * A SQLite prepared statement.\n *\n * `SQLiteStore` prepares one statement per SQL and shares it across all\n * concurrent readers, so implementations must make each call atomic with\n * respect to other callers of the same statement: `all()` must not let another\n * `exec()`/`all()` rebind or reset the underlying statement between executing\n * it and fetching its rows. Delegates whose native API splits execute and fetch\n * into separate round trips (e.g. expo-sqlite) must serialize per statement.\n */\nexport interface PreparedStatement {\n exec(params: string[]): Promise<void>;\n all(params: string[]): Promise<unknown[][]>;\n}\n\nexport interface SQLiteDatabase {\n /**\n * Close the database connection.\n */\n close(): void;\n\n /**\n * Destroy or delete the database (e.g. delete file).\n */\n destroy(): void;\n\n /**\n * Prepare a SQL string, returning a statement you can execute.\n * E.g. `const stmt = db.prepare(\"SELECT * FROM todos WHERE id=?\");`\n */\n prepare(sql: string): PreparedStatement;\n\n // for PRAGMA statements, schema creation and transaction control.\n execSync(sql: string): void;\n}\n\nexport type CreateSQLiteDatabase = (\n filename: string,\n opts?: SQLiteStoreOptions,\n) => SQLiteDatabase;\n\n/**\n * SQLite-based implementation of the Store interface using a configurable delegate.\n * Supports shared connections between multiple store instances with the same name,\n * providing efficient resource utilization and proper transaction isolation.\n * Uses parameterized queries for safety and performance.\n */\nexport class SQLiteStore implements Store {\n readonly #filename: string;\n readonly #entry: StoreEntry;\n readonly #kind: string;\n\n #closed = false;\n\n constructor(\n name: string,\n create: CreateSQLiteDatabase,\n opts?: SQLiteStoreOptions,\n kind = 'sqlite',\n ) {\n this.#filename = resolveFilename(name, opts);\n this.#entry = getOrCreateEntry(this.#filename, create, opts);\n this.#kind = kind;\n }\n\n get kind(): string {\n return this.#kind;\n }\n\n async read(): Promise<Read> {\n throwIfStoreClosed(this);\n\n const entry = this.#entry;\n const {db, lock, preparedStatements} = entry;\n const release = await lock.read();\n\n // Start shared read transaction if this is the first reader\n // This ensures consistent reads across all concurrent readers\n try {\n if (entry.activeReaders === 0) {\n db.execSync('BEGIN');\n }\n } catch (e) {\n // The lock was acquired above; without this every later read() and\n // write() on the store waits for a release that never comes.\n release();\n throw e;\n }\n entry.activeReaders++;\n\n return new SQLiteStoreRead(() => {\n entry.activeReaders--;\n // Commit shared read transaction when last reader finishes. SQLite may\n // already have rolled the transaction back on its own (an I/O error\n // inside any reader's statement does that), in which case COMMIT\n // throws \"cannot commit - no transaction is active\". The error is\n // reported to the releasing reader, but the RWLock must be released\n // regardless or the store hangs for the rest of the process.\n try {\n if (entry.activeReaders === 0) {\n db.execSync('COMMIT');\n }\n } finally {\n release();\n }\n }, preparedStatements);\n }\n\n async write(): Promise<Write> {\n throwIfStoreClosed(this);\n\n const {lock, db, preparedStatements} = this.#entry;\n const release = await lock.write();\n\n // At this point, RWLock guarantees no active readers\n // The last reader would have already committed the shared transaction\n\n try {\n db.execSync('BEGIN IMMEDIATE');\n } catch (e) {\n // SQLITE_BUSY once busy_timeout expires, or an I/O error. The caller\n // gets the error; the write lock must not stay held.\n release();\n throw e;\n }\n\n return new SQLiteWrite(release, db, preparedStatements);\n }\n\n async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n\n const {lock, db} = this.#entry;\n // Wait for all readers and writers to finish.\n const writeRelease = await lock.write();\n\n // Handle reference counting for shared stores - only close database\n // when this is the last store instance using it\n decrementStoreRefCount(this.#filename, db);\n\n this.#closed = true;\n writeRelease();\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\nexport function safeFilename(name: string): string {\n return name.replace(/[^a-zA-Z0-9]/g, '_');\n}\n\nfunction resolveFilename(name: string, opts?: SQLiteStoreOptions): string {\n const safe = safeFilename(name);\n const dir = opts?.directory;\n return dir ? `${dir}/${safe}` : safe;\n}\n\nexport type PreparedStatements = {\n has: PreparedStatement;\n get: PreparedStatement;\n hasMany: PreparedStatement;\n getMany: PreparedStatement;\n put: PreparedStatement;\n del: PreparedStatement;\n /** Multi-row INSERT with the values bound as parameters, n rows wide. */\n putN: (n: number) => PreparedStatement;\n /** Multi-key DELETE with the keys bound as parameters, n keys wide. */\n delN: (n: number) => PreparedStatement;\n};\n\n/**\n * Widest batch we bind in one statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is\n * 32766, and a put costs two parameters per row, so this is far below the cap;\n * it exists to bound how many distinct statements we prepare and cache.\n */\nconst MAX_BATCH = 128;\n\n/** `repeatList('?', 3)` -> `'?,?,?'`. */\nfunction repeatList(item: string, n: number): string {\n return `${item},`.repeat(n).slice(0, -1);\n}\n\n/**\n * Prepares (and caches) a statement of each width on demand. Callers only ever\n * ask for powers of two, so the cache holds at most log2(MAX_BATCH)+1 entries\n * however many rows a commit turns out to have.\n */\nfunction batchStatements(\n delegate: SQLiteDatabase,\n sqlFor: (n: number) => string,\n): (n: number) => PreparedStatement {\n const cache = new Map<number, PreparedStatement>();\n return (n: number) =>\n getOrInsertComputed(cache, n, () => delegate.prepare(sqlFor(n)));\n}\n\n/**\n * Runs `items` through `getStatement` in power-of-two sized batches, so any\n * length is covered by a handful of cached statement widths.\n */\nasync function execInBatches<T>(\n items: readonly T[],\n getStatement: (n: number) => PreparedStatement,\n toParams: (item: T, out: string[]) => void,\n): Promise<void> {\n for (let i = 0; i < items.length;) {\n const remaining = Math.min(MAX_BATCH, items.length - i);\n const n = 1 << (31 - Math.clz32(remaining));\n const params: string[] = [];\n for (let j = 0; j < n; j++) {\n toParams(items[i + j], params);\n }\n await getStatement(n).exec(params);\n i += n;\n }\n}\n\nexport interface SQLiteStoreOptions {\n // Common options\n busyTimeout?: number;\n journalMode?: 'WAL' | 'DELETE';\n synchronous?: 'NORMAL' | 'FULL';\n readUncommitted?: boolean;\n /** Directory in which to create the SQLite file. Defaults to the process CWD. */\n directory?: string | undefined;\n}\n\n/**\n * Replicache's rows are B-tree chunks, which `BTreeWrite` targets at 8-16KB, so\n * most of them are larger than a page and spill into overflow pages at either\n * page size. 8192 does not avoid overflow; it halves the number of pages each\n * chunk is split across.\n *\n * Measured with `replicache-perf/rn`, 4096 vs 8192 + mmap, change in time:\n *\n * | device | persist 1024x10000 | startup read (expo / op) |\n * | ---------------------- | ------------------ | ------------------------ |\n * | iOS simulator | -6% | -12% / -14% |\n * | Android emulator, 2GB | -1% to -2% | -19% / -8% |\n * | Pixel 6 | ~0% | ~-40% / ~0% |\n *\n * Split by pragma on iOS, page_size carries the write win (~6%) and mmap most\n * of the read win. Neither regressed anything on any device.\n */\nconst PAGE_SIZE = 8192;\n\n/** 256MB, matching op-sqlite's own key-value store. */\nconst MMAP_SIZE = 268435456;\n\n/**\n * Common database setup logic shared between expo-sqlite and op-sqlite implementations.\n * Configures SQLite pragmas, creates the entry table, and prepares common statements.\n */\n\nexport function setupDatabase(\n delegate: SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): PreparedStatements {\n // Configure SQLite pragmas for optimal performance.\n //\n // page_size MUST come first. SQLite silently ignores it once the database\n // has content or a journal mode has been set — no error, no warning, the\n // pragma just does nothing and you are left on the 4096 default. Verified:\n // issuing it after `journal_mode = WAL`, or after CREATE TABLE, leaves\n // `PRAGMA page_size` reporting 4096. Do not reorder these.\n delegate.execSync(`PRAGMA page_size = ${PAGE_SIZE}`);\n delegate.execSync(`PRAGMA busy_timeout = ${opts?.busyTimeout ?? 200}`);\n delegate.execSync(`PRAGMA journal_mode = '${opts?.journalMode ?? 'WAL'}'`);\n delegate.execSync(`PRAGMA synchronous = '${opts?.synchronous ?? 'NORMAL'}'`);\n delegate.execSync(\n `PRAGMA read_uncommitted = ${Boolean(opts?.readUncommitted)}`,\n );\n // Reads served from the mmap window rather than the pager account for most\n // of the startup-read win measured in the PAGE_SIZE comment.\n delegate.execSync(`PRAGMA mmap_size = ${MMAP_SIZE}`);\n\n // Create the entry table.\n //\n // This is deliberately a rowid table, not `WITHOUT ROWID`. A `WITHOUT ROWID`\n // table stores whole rows in an index B-tree, which keeps at most ~1/4 of a\n // page inline, and SQLite recommends it only for rows under ~1/20 of a page.\n // Our rows are 8-16KB chunks. As a rowid table the key gets a small separate\n // index and the values live in the table B-tree. On a Pixel 6 (5 rounds, on\n // top of the pragmas above) that cut startup read by 24% on both expo and\n // op, expo startup scan by 10%, and persist 1024x10000 by 4-7%.\n //\n // `key` needs an explicit NOT NULL: in a rowid table a non-INTEGER primary key\n // is only a UNIQUE index, and SQLite (a bug kept for compatibility) lets it\n // hold NULLs, several of them. `WITHOUT ROWID` enforced this implicitly.\n //\n // `IF NOT EXISTS` leaves an existing database's table as it was created, so\n // stores created before this change stay `WITHOUT ROWID` until recreated.\n delegate.execSync(`\n CREATE TABLE IF NOT EXISTS entry (\n key TEXT PRIMARY KEY NOT NULL,\n value TEXT NOT NULL\n )\n `);\n\n // Prepare common statements\n return {\n has: delegate.prepare(`SELECT 1 FROM entry WHERE key = ? LIMIT 1`),\n get: delegate.prepare('SELECT value FROM entry WHERE key = ?'),\n hasMany: delegate.prepare(\n `SELECT key FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n getMany: delegate.prepare(\n `SELECT key, value FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n put: delegate.prepare(\n `INSERT OR REPLACE INTO entry (key, value)\n SELECT e.value->>0, e.value->1 FROM json_each(?) e`,\n ),\n del: delegate.prepare(\n `DELETE FROM entry WHERE key IN (SELECT value FROM json_each(?))`,\n ),\n putN: batchStatements(\n delegate,\n n =>\n `INSERT OR REPLACE INTO entry (key, value) VALUES ${repeatList('(?,?)', n)}`,\n ),\n delN: batchStatements(\n delegate,\n n => `DELETE FROM entry WHERE key IN (${repeatList('?', n)})`,\n ),\n };\n}\n\n// Callbacks are stored as striped pairs: [resolve, reject, resolve, reject, ...]\nconst CB_STRIDE = 2;\nconst CB_RESOLVE = 0;\nconst CB_REJECT = 1;\n\ntype GetResolve = (v: ReadonlyJSONValue | undefined) => void;\ntype HasResolve = (v: boolean) => void;\ntype Reject = (e: unknown) => void;\n\nfunction rejectAll(callbacks: unknown[], e: unknown): void {\n for (let i = CB_REJECT; i < callbacks.length; i += CB_STRIDE) {\n (callbacks[i] as Reject)(e);\n }\n}\n\nfunction parseRawValue(raw: string | undefined): ReadonlyJSONValue | undefined {\n return raw === undefined\n ? undefined\n : deepFreeze(JSON.parse(raw) as ReadonlyJSONValue);\n}\n\nfunction resolveGet(\n resolve: GetResolve,\n reject: Reject,\n raw: string | undefined,\n): void {\n try {\n resolve(parseRawValue(raw));\n } catch (e) {\n reject(e);\n }\n}\n\nasync function flushGets(\n keys: string[],\n callbacks: unknown[],\n ps: PreparedStatements,\n): Promise<void> {\n let rows: unknown[][];\n try {\n rows =\n keys.length === 1\n ? await ps.get.all([keys[0]])\n : await ps.getMany.all([JSON.stringify(keys)]);\n } catch (e) {\n rejectAll(callbacks, e);\n return;\n }\n if (keys.length === 1) {\n resolveGet(\n callbacks[CB_RESOLVE] as GetResolve,\n callbacks[CB_REJECT] as Reject,\n rows[0]?.[0] as string | undefined,\n );\n return;\n }\n const resultMap = new Map(rows as [string, string][]);\n for (let i = 0; i < keys.length; i++) {\n resolveGet(\n callbacks[i * CB_STRIDE + CB_RESOLVE] as GetResolve,\n callbacks[i * CB_STRIDE + CB_REJECT] as Reject,\n resultMap.get(keys[i]),\n );\n }\n}\n\nasync function flushHas(\n keys: string[],\n callbacks: unknown[],\n ps: PreparedStatements,\n): Promise<void> {\n let rows: unknown[][];\n try {\n rows =\n keys.length === 1\n ? await ps.has.all([keys[0]])\n : await ps.hasMany.all([JSON.stringify(keys)]);\n } catch (e) {\n rejectAll(callbacks, e);\n return;\n }\n if (keys.length === 1) {\n (callbacks[CB_RESOLVE] as HasResolve)(rows.length > 0);\n return;\n }\n const existingKeys = new Set(rows.map(row => row[0] as string));\n for (let i = 0; i < keys.length; i++) {\n (callbacks[i * CB_STRIDE + CB_RESOLVE] as HasResolve)(\n existingKeys.has(keys[i]),\n );\n }\n}\n\nexport class SQLiteStoreRead implements Read {\n readonly #release: () => void;\n readonly #preparedStatements: PreparedStatements;\n #closed = false;\n #pendingGetKeys: string[] = [];\n #pendingGetCallbacks: unknown[] = [];\n #pendingHasKeys: string[] = [];\n #pendingHasCallbacks: unknown[] = [];\n #scheduled = false;\n\n constructor(release: () => void, preparedStatements: PreparedStatements) {\n this.#release = release;\n this.#preparedStatements = preparedStatements;\n }\n\n has(key: string): Promise<boolean> {\n return (\n maybeTransactionIsClosedRejection(this) ??\n new Promise((resolve, reject) => {\n this.#pendingHasKeys.push(key);\n this.#pendingHasCallbacks.push(resolve, reject);\n this.#scheduleLookup();\n })\n );\n }\n\n get(key: string): Promise<ReadonlyJSONValue | undefined> {\n return (\n maybeTransactionIsClosedRejection(this) ??\n new Promise((resolve, reject) => {\n this.#pendingGetKeys.push(key);\n this.#pendingGetCallbacks.push(resolve, reject);\n this.#scheduleLookup();\n })\n );\n }\n\n #scheduleLookup(): void {\n if (!this.#scheduled) {\n this.#scheduled = true;\n queueMicrotask(() => {\n this.#scheduled = false;\n\n const ps = this.#preparedStatements;\n const getKeys = this.#pendingGetKeys;\n this.#pendingGetKeys = [];\n const getCallbacks = this.#pendingGetCallbacks;\n this.#pendingGetCallbacks = [];\n const hasKeys = this.#pendingHasKeys;\n this.#pendingHasKeys = [];\n const hasCallbacks = this.#pendingHasCallbacks;\n this.#pendingHasCallbacks = [];\n\n if (this.#closed) {\n const e = transactionError();\n rejectAll(getCallbacks, e);\n rejectAll(hasCallbacks, e);\n return;\n }\n\n if (getKeys.length > 0) {\n void flushGets(getKeys, getCallbacks, ps);\n }\n if (hasKeys.length > 0) {\n void flushHas(hasKeys, hasCallbacks, ps);\n }\n });\n }\n }\n\n release(): void {\n if (!this.#closed) {\n this.#closed = true;\n this.#release();\n }\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\nexport class SQLiteWrite extends WriteImplBase implements Write {\n readonly #release: () => void;\n readonly #dbDelegate: SQLiteDatabase;\n readonly #preparedStatements: PreparedStatements;\n #committed = false;\n #closed = false;\n\n constructor(\n release: () => void,\n dbDelegate: SQLiteDatabase,\n preparedStatements: PreparedStatements,\n ) {\n super(new SQLiteStoreRead(() => undefined, preparedStatements));\n this.#release = release;\n this.#dbDelegate = dbDelegate;\n this.#preparedStatements = preparedStatements;\n }\n\n async commit(): Promise<void> {\n if (this.#closed) {\n throw transactionError();\n }\n\n const deleteKeys: string[] = [];\n for (const entry of this._pending) {\n if (entry[1] === deleteSentinel) {\n deleteKeys.push(entry[0]);\n this._pending.delete(entry[0]);\n }\n }\n\n // Bind real parameters rather than serializing the whole pending set into\n // one JSON document for json_each() to parse back out. Serializing it, and\n // pushing the resulting (often megabyte-scale) string across the native\n // bridge, measured as roughly a quarter of persist on device.\n //\n // Puts and deletes go out SEQUENTIALLY, and so do the batches within each.\n // Puts and deletes used to overlap, on the grounds that they use different\n // statements over disjoint keys (deletes were removed from _pending above).\n // That is true of the happy path and not of a failing one:\n //\n // A commit is several statements and its COMMIT runs only after the last\n // one. SQLite rolls a transaction back ITSELF on an I/O error — that is what\n // `cannot rollback - no transaction is active` reports at release() — and a\n // statement reaching the connection after that runs in autocommit mode. So\n // while two statements of one commit are in flight together, a failure in\n // one leaves the other to land OUTSIDE the transaction and persist on its\n // own: the commit half-applies, durably, while the caller is told it failed.\n // For a dag write that is a head kept while the chunks it reaches are\n // deleted, or a chunk's refcount row dropped while the chunk and its\n // referrer remain — a count that no longer counts what is there, which\n // computeRefCountUpdates() accepts when it reaches zero (it rejects only a\n // negative) and #applyRefCountUpdates() then acts on by deleting a live\n // chunk, inside a transaction that commits cleanly.\n //\n // Awaiting both promises would not be enough: by the time one rejects the\n // other is already at the driver and cannot be recalled. Nothing may be in\n // flight beside a statement that can fail. Sequencing also means no batch is\n // left unawaited, which `if (putP) await putP; if (delP) await delP;` did\n // whenever the puts rejected first — an unhandled rejection on that commit.\n //\n // The batches *within* each kind could never overlap anyway: the\n // power-of-two split reuses a width when a commit is wide enough (300 rows\n // -> 128, 128, 32, 8, 4), and running two of those concurrently would have\n // two callers on one prepared statement — the rebind-during-execute hazard\n // described in kv/expo-sqlite/store.ts, which op-sqlite has no\n // per-statement lock to absorb.\n if (this._pending.size > 0) {\n await execInBatches(\n [...this._pending] as [string, ReadonlyJSONValue][],\n this.#preparedStatements.putN,\n ([key, value], out) => {\n out.push(key, JSON.stringify(value));\n },\n );\n }\n if (deleteKeys.length > 0) {\n await execInBatches(\n deleteKeys,\n this.#preparedStatements.delN,\n (key, out) => {\n out.push(key);\n },\n );\n }\n\n this.#dbDelegate.execSync('COMMIT');\n this._pending.clear();\n this.#committed = true;\n }\n\n release(): void {\n if (!this.#closed) {\n this.#closed = true;\n super.release();\n let rollbackError: unknown;\n if (!this.#committed) {\n try {\n this.#dbDelegate.execSync('ROLLBACK');\n } catch (e) {\n rollbackError = e;\n }\n }\n this.#release();\n if (rollbackError !== undefined) {\n throw rollbackError;\n }\n }\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n}\n\ntype StoreEntry = {\n readonly lock: RWLock;\n readonly db: SQLiteDatabase;\n refCount: number;\n activeReaders: number;\n preparedStatements: PreparedStatements;\n};\n\n// Global map to share database connections between multiple store instances with the same name\nconst stores = new Map<string, StoreEntry>();\n\n/**\n * Gets an existing store entry or creates a new one if it doesn't exist.\n * This implements the shared connection pattern where multiple stores with the same\n * name share the same database connection, lock, and delegate.\n */\nfunction getOrCreateEntry(\n filename: string,\n create: (filename: string, opts?: SQLiteStoreOptions) => SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): StoreEntry {\n const entry = stores.get(filename);\n\n if (entry) {\n entry.refCount++;\n return entry;\n }\n\n const dbDelegate = reportingStorageFailures(\n rethrowingStorageFailures(() => create(filename, opts)),\n );\n let preparedStatements: PreparedStatements;\n try {\n preparedStatements = setupDatabase(dbDelegate, opts);\n } catch (e) {\n // Not in `stores` yet, so nothing else would close this connection.\n try {\n dbDelegate.close();\n } catch {\n // The setup error is the one to report.\n }\n throw e;\n }\n\n const lock = new RWLock();\n\n const newEntry: StoreEntry = {\n lock,\n db: dbDelegate,\n refCount: 1,\n activeReaders: 0,\n preparedStatements,\n };\n stores.set(filename, newEntry);\n return newEntry;\n}\n\nconst STORAGE_FAILURE_SIGNATURES = [\n [/database or disk is full|SQLITE_FULL/, 'full'],\n [/unable to open database file|SQLITE_CANTOPEN/, 'cannot-open'],\n [/disk I\\/O error|SQLITE_IOERR/, 'io-error'],\n] as const;\n\n/**\n * The storage failure a SQLite error reports, if any. Matched on SQLite's own\n * `sqlite3_errmsg` text (or its symbolic code), which expo-sqlite, op-sqlite\n * and zero-sqlite all surface inside whatever wrapper they add.\n * `SQLITE_BUSY` is deliberately not one: it is contention, and `busy_timeout`\n * plus a retry is the right answer to it.\n */\nexport function classifySQLiteError(\n error: unknown,\n): StorageFailureKind | undefined {\n const message =\n error instanceof Error\n ? `${error.name}: ${error.message}`\n : typeof error === 'string'\n ? error\n : '';\n for (const [signature, kind] of STORAGE_FAILURE_SIGNATURES) {\n if (signature.test(message)) {\n return kind;\n }\n }\n return undefined;\n}\n\nfunction toStorageFailure(error: unknown): unknown {\n const kind = classifySQLiteError(error);\n return kind === undefined\n ? error\n : new StorageFailureError(\n kind,\n error instanceof Error ? error.message : String(error),\n {cause: error},\n );\n}\n\nfunction rethrowingStorageFailures<T>(f: () => T): T {\n try {\n return f();\n } catch (e) {\n throw toStorageFailure(e);\n }\n}\n\n/**\n * Wraps the driver so every SQLite error that reports a storage failure\n * reaches the store's callers as a {@link StorageFailureError}, whichever\n * statement or transaction step it came from.\n */\nfunction reportingStorageFailures(db: SQLiteDatabase): SQLiteDatabase {\n return {\n close: () => db.close(),\n destroy: () => db.destroy(),\n execSync: sql => rethrowingStorageFailures(() => db.execSync(sql)),\n prepare: sql => {\n const statement = rethrowingStorageFailures(() => db.prepare(sql));\n return {\n exec: async params => {\n try {\n return await statement.exec(params);\n } catch (e) {\n throw toStorageFailure(e);\n }\n },\n all: async params => {\n try {\n return await statement.all(params);\n } catch (e) {\n throw toStorageFailure(e);\n }\n },\n };\n },\n };\n}\n\n/**\n * Decrements the reference count for a shared store and cleans up resources\n * when the last reference is released.\n */\n\nfunction decrementStoreRefCount(\n filename: string,\n dbDelegate: SQLiteDatabase,\n): void {\n const entry = stores.get(filename);\n if (entry) {\n entry.refCount--;\n if (entry.refCount <= 0) {\n dbDelegate.close();\n stores.delete(filename);\n }\n }\n}\nexport function clearAllNamedStoresForTesting(): void {\n for (const entry of stores.values()) {\n entry.db.close();\n }\n stores.clear();\n}\n\nexport function dropStore(\n name: string,\n createDelegate: (\n filename: string,\n opts?: SQLiteStoreOptions,\n ) => SQLiteDatabase,\n opts?: SQLiteStoreOptions,\n): Promise<void> {\n const filename = resolveFilename(name, opts);\n const entry = stores.get(filename);\n if (entry) {\n try {\n entry.db.close();\n } catch {\n // Ignore close errors\n }\n stores.delete(filename);\n }\n\n // Create a temporary delegate to handle database deletion\n const tempDelegate = createDelegate(filename, opts);\n try {\n // we close the db before destroying it - this\n // caused an issue with expo-sqlite since it requires this\n tempDelegate.close();\n } catch {\n // Ignore close errors\n }\n try {\n tempDelegate.destroy();\n } catch {\n // Destroy errors shouldn't be fatal; the file may already be gone or locked\n }\n\n return Promise.resolve();\n}\n"],"mappings":";;;;;;;;;;;;;AA+DA,IAAa,cAAb,MAA0C;CACxC;CACA;CACA;CAEA,UAAU;CAEV,YACE,MACA,QACA,MACA,OAAO,UACP;EACA,KAAKA,YAAY,gBAA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AO,QAAQ;CACxB;CAGA,MAAM,eAAe,eAAe,UAAU,IAAI;CAClD,IAAI;EAGF,aAAa,MAAM;CACrB,QAAQ,CAER;CACA,IAAI;EACF,aAAa,QAAQ;CACvB,QAAQ,CAER;CAEA,OAAO,QAAQ,QAAQ;AACzB"}
@@ -1,5 +1,6 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Store } from '../dag/store.ts';
3
+ import type { StorageFailureError } from '../storage-failure.ts';
3
4
  import type { ClientID } from '../sync/ids.ts';
4
5
  import type { OnClientsDeleted } from './clients.ts';
5
6
  import { type ClientMap } from './clients.ts';
@@ -14,5 +15,5 @@ export declare const CLIENT_MAX_INACTIVE_TIME: number;
14
15
  */
15
16
  export declare const GC_INTERVAL: number;
16
17
  export declare function getLatestGCUpdate(): Promise<ClientMap> | undefined;
17
- export declare function initClientGC(clientID: ClientID, dagStore: Store, clientMaxInactiveTime: number, gcInterval: number, onClientsDeleted: OnClientsDeleted, lc: LogContext, signal: AbortSignal): void;
18
+ export declare function initClientGC(clientID: ClientID, dagStore: Store, clientMaxInactiveTime: number, gcInterval: number, onClientsDeleted: OnClientsDeleted, lc: LogContext, signal: AbortSignal, onStorageFailure?: ((failure: StorageFailureError) => void) | undefined): void;
18
19
  //# sourceMappingURL=client-gc.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-gc.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/client-gc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAE7C,OAAO,KAAK,EAAS,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAC,KAAK,SAAS,EAAyB,MAAM,cAAc,CAAC;AAEpE;;;;GAIG;AACH,eAAO,MAAM,w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KAAK,IAAI,CAAC,GAAG,SAAS,GACtE,IAAI,CAiBN"}
@@ -14,11 +14,11 @@ var CLIENT_MAX_INACTIVE_TIME = 1440 * 60 * 1e3;
14
14
  */
15
15
  var GC_INTERVAL = 300 * 1e3;
16
16
  var latestGCUpdate;
17
- function initClientGC(clientID, dagStore, clientMaxInactiveTime, gcInterval, onClientsDeleted, lc, signal) {
17
+ function initClientGC(clientID, dagStore, clientMaxInactiveTime, gcInterval, onClientsDeleted, lc, signal, onStorageFailure) {
18
18
  initBgIntervalProcess("ClientGC", () => {
19
19
  latestGCUpdate = gcClients(clientID, dagStore, clientMaxInactiveTime, onClientsDeleted);
20
20
  return latestGCUpdate;
21
- }, () => gcInterval, lc, signal);
21
+ }, () => gcInterval, lc, signal, onStorageFailure);
22
22
  }
23
23
  function gcClients(clientID, dagStore, clientMaxInactiveTime, onClientsDeleted) {
24
24
  return withWrite(dagStore, async (dagWrite) => {
@@ -1 +1 @@
1
- {"version":3,"file":"client-gc.js","names":[],"sources":["../../../../../replicache/src/persist/client-gc.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport {\n addDeletedClients,\n type WritableDeletedClients,\n} from '../deleted-clients.ts';\nimport type {ClientID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport type {Client, OnClientsDeleted} from './clients.ts';\nimport {type ClientMap, getClients, setClients} from './clients.ts';\n\n/**\n * The maximum time a client can be inactive before it is garbage collected.\n * This means that this is the maximum time a tab can be in the background\n * (frozen) and still be able to sync when it comes back to the foreground.\n */\nexport const CLIENT_MAX_INACTIVE_TIME = 24 * 60 * 60 * 1000; // 24 hours\n\n/**\n * How frequently to try to garbage collect clients.\n */\nexport const GC_INTERVAL = 5 * 60 * 1000; // 5 minutes\n\nlet latestGCUpdate: Promise<ClientMap> | undefined;\nexport function getLatestGCUpdate(): Promise<ClientMap> | undefined {\n return latestGCUpdate;\n}\n\nexport function initClientGC(\n clientID: ClientID,\n dagStore: Store,\n clientMaxInactiveTime: number,\n gcInterval: number,\n onClientsDeleted: OnClientsDeleted,\n lc: LogContext,\n signal: AbortSignal,\n): void {\n initBgIntervalProcess(\n 'ClientGC',\n () => {\n latestGCUpdate = gcClients(\n clientID,\n dagStore,\n clientMaxInactiveTime,\n onClientsDeleted,\n );\n return latestGCUpdate;\n },\n () => gcInterval,\n lc,\n signal,\n );\n}\n\nfunction gcClients(\n clientID: ClientID,\n dagStore: Store,\n clientMaxInactiveTime: number,\n onClientsDeleted: OnClientsDeleted,\n): Promise<ClientMap> {\n return withWrite(dagStore, async dagWrite => {\n const now = Date.now();\n const clients = await getClients(dagWrite);\n const deletedClients: WritableDeletedClients = [];\n const newClients: Map<ClientID, Client> = new Map();\n for (const [id, client] of clients) {\n if (\n id === clientID /* never collect ourself */ ||\n now - client.heartbeatTimestampMs <= clientMaxInactiveTime\n ) {\n newClients.set(id, client);\n } else {\n deletedClients.push({\n clientGroupID: client.clientGroupID,\n clientID: id,\n });\n }\n }\n\n if (newClients.size === clients.size) {\n return clients;\n }\n await setClients(newClients, dagWrite);\n const normalizedDeletedClients = await addDeletedClients(\n dagWrite,\n deletedClients,\n );\n await onClientsDeleted(normalizedDeletedClients);\n return newClients;\n });\n}\n"],"mappings":";;;;;;;;;;AAiBA,IAAa,2BAA2B,OAAU,KAAK;;;;AAKvD,IAAa,cAAc,MAAS;AAEpC,IAAI;AAKJ,SAAgB,aACd,UACA,UACA,uBACA,YACA,kBACA,IACA,QACM;CACN,sBACE,kBACM;EACJ,iBAAiB,UACf,UACA,UACA,uBACA,gBACF;EACA,OAAO;CACT,SACM,YACN,IACA,MACF;AACF;AAEA,SAAS,UACP,UACA,UACA,uBACA,kBACoB;CACpB,OAAO,UAAU,UAAU,OAAM,aAAY;EAC3C,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,UAAU,MAAM,WAAW,QAAQ;EACzC,MAAM,iBAAyC,CAAC;EAChD,MAAM,6BAAoC,IAAI,IAAI;EAClD,KAAK,MAAM,CAAC,IAAI,WAAW,SACzB,IACE,OAAO,YACP,MAAM,OAAO,wBAAwB,uBAErC,WAAW,IAAI,IAAI,MAAM;OAEzB,eAAe,KAAK;GAClB,eAAe,OAAO;GACtB,UAAU;EACZ,CAAC;EAIL,IAAI,WAAW,SAAS,QAAQ,MAC9B,OAAO;EAET,MAAM,WAAW,YAAY,QAAQ;EAKrC,MAAM,iBAAiB,MAJgB,kBACrC,UACA,cACF,CAC+C;EAC/C,OAAO;CACT,CAAC;AACH"}
1
+ {"version":3,"file":"client-gc.js","names":[],"sources":["../../../../../replicache/src/persist/client-gc.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport {\n addDeletedClients,\n type WritableDeletedClients,\n} from '../deleted-clients.ts';\nimport type {StorageFailureError} from '../storage-failure.ts';\nimport type {ClientID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport type {Client, OnClientsDeleted} from './clients.ts';\nimport {type ClientMap, getClients, setClients} from './clients.ts';\n\n/**\n * The maximum time a client can be inactive before it is garbage collected.\n * This means that this is the maximum time a tab can be in the background\n * (frozen) and still be able to sync when it comes back to the foreground.\n */\nexport const CLIENT_MAX_INACTIVE_TIME = 24 * 60 * 60 * 1000; // 24 hours\n\n/**\n * How frequently to try to garbage collect clients.\n */\nexport const GC_INTERVAL = 5 * 60 * 1000; // 5 minutes\n\nlet latestGCUpdate: Promise<ClientMap> | undefined;\nexport function getLatestGCUpdate(): Promise<ClientMap> | undefined {\n return latestGCUpdate;\n}\n\nexport function initClientGC(\n clientID: ClientID,\n dagStore: Store,\n clientMaxInactiveTime: number,\n gcInterval: number,\n onClientsDeleted: OnClientsDeleted,\n lc: LogContext,\n signal: AbortSignal,\n onStorageFailure?: ((failure: StorageFailureError) => void) | undefined,\n): void {\n initBgIntervalProcess(\n 'ClientGC',\n () => {\n latestGCUpdate = gcClients(\n clientID,\n dagStore,\n clientMaxInactiveTime,\n onClientsDeleted,\n );\n return latestGCUpdate;\n },\n () => gcInterval,\n lc,\n signal,\n onStorageFailure,\n );\n}\n\nfunction gcClients(\n clientID: ClientID,\n dagStore: Store,\n clientMaxInactiveTime: number,\n onClientsDeleted: OnClientsDeleted,\n): Promise<ClientMap> {\n return withWrite(dagStore, async dagWrite => {\n const now = Date.now();\n const clients = await getClients(dagWrite);\n const deletedClients: WritableDeletedClients = [];\n const newClients: Map<ClientID, Client> = new Map();\n for (const [id, client] of clients) {\n if (\n id === clientID /* never collect ourself */ ||\n now - client.heartbeatTimestampMs <= clientMaxInactiveTime\n ) {\n newClients.set(id, client);\n } else {\n deletedClients.push({\n clientGroupID: client.clientGroupID,\n clientID: id,\n });\n }\n }\n\n if (newClients.size === clients.size) {\n return clients;\n }\n await setClients(newClients, dagWrite);\n const normalizedDeletedClients = await addDeletedClients(\n dagWrite,\n deletedClients,\n );\n await onClientsDeleted(normalizedDeletedClients);\n return newClients;\n });\n}\n"],"mappings":";;;;;;;;;;AAkBA,IAAa,2BAA2B,OAAU,KAAK;;;;AAKvD,IAAa,cAAc,MAAS;AAEpC,IAAI;AAKJ,SAAgB,aACd,UACA,UACA,uBACA,YACA,kBACA,IACA,QACA,kBACM;CACN,sBACE,kBACM;EACJ,iBAAiB,UACf,UACA,UACA,uBACA,gBACF;EACA,OAAO;CACT,SACM,YACN,IACA,QACA,gBACF;AACF;AAEA,SAAS,UACP,UACA,UACA,uBACA,kBACoB;CACpB,OAAO,UAAU,UAAU,OAAM,aAAY;EAC3C,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,UAAU,MAAM,WAAW,QAAQ;EACzC,MAAM,iBAAyC,CAAC;EAChD,MAAM,6BAAoC,IAAI,IAAI;EAClD,KAAK,MAAM,CAAC,IAAI,WAAW,SACzB,IACE,OAAO,YACP,MAAM,OAAO,wBAAwB,uBAErC,WAAW,IAAI,IAAI,MAAM;OAEzB,eAAe,KAAK;GAClB,eAAe,OAAO;GACtB,UAAU;EACZ,CAAC;EAIL,IAAI,WAAW,SAAS,QAAQ,MAC9B,OAAO;EAET,MAAM,WAAW,YAAY,QAAQ;EAKrC,MAAM,iBAAiB,MAJgB,kBACrC,UACA,cACF,CAC+C;EAC/C,OAAO;CACT,CAAC;AACH"}
@@ -1,8 +1,9 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Store } from '../dag/store.ts';
3
+ import type { StorageFailureError } from '../storage-failure.ts';
3
4
  import { type ClientGroupMap } from './client-groups.ts';
4
5
  export declare function getLatestGCUpdate(): Promise<ClientGroupMap> | undefined;
5
- export declare function initClientGroupGC(dagStore: Store, enableMutationRecovery: boolean, lc: LogContext, signal: AbortSignal): void;
6
+ export declare function initClientGroupGC(dagStore: Store, enableMutationRecovery: boolean, lc: LogContext, signal: AbortSignal, onStorageFailure?: ((failure: StorageFailureError) => void) | undefined): void;
6
7
  /**
7
8
  * This removes client groups that have no clients and no pending mutations.
8
9
  * If {@linkcode enableMutationRecovery} is true, it will keep client groups with
@@ -1 +1 @@
1
- {"version":3,"file":"client-group-gc.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/client-group-gc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAG3C,OAAO,EAIL,KAAK,cAAc,EACpB,MAAM,oBAAoB,CAAC;AAM5B,wBAAgB,iBAAiB,IAAI,OAAO,CAAC,cAAc,CAAC,GAAG,SAAS,CAEvE;AAED,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,KAAK,EACf,sBAAsB,EAAE,OAAO,EAC/B,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,WAAW,GAClB,IAAI,CAWN;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,KAAK,EACf,sBAAsB,EAAE,OAAO,GAC9B,OAAO,CAAC,cAAc,CAAC,CAuBzB"}
1
+ {"version":3,"file":"client-group-gc.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/client-group-gc.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,uBAAuB,CAAC;AAG/D,OAAO,EAIL,KAAK,cAAc,EACpB,MAAM,oBAAoB,CAAC;AAM5B,wBAAgB,iBAAiB,IAAI,OAAO,CAAC,cAAc,CAAC,GAAG,SAAS,CAEvE;AAED,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,KAAK,EACf,sBAAsB,EAAE,OAAO,EAC/B,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,WAAW,EACnB,gBAAgB,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,mBAAmB,KAAK,IAAI,CAAC,GAAG,SAAS,GACtE,IAAI,CAYN;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,KAAK,EACf,sBAAsB,EAAE,OAAO,GAC9B,OAAO,CAAC,cAAc,CAAC,CAuBzB"}
@@ -5,11 +5,11 @@ import { getClients } from "./clients.js";
5
5
  //#region ../replicache/src/persist/client-group-gc.ts
6
6
  var GC_INTERVAL_MS = 300 * 1e3;
7
7
  var latestGCUpdate;
8
- function initClientGroupGC(dagStore, enableMutationRecovery, lc, signal) {
8
+ function initClientGroupGC(dagStore, enableMutationRecovery, lc, signal, onStorageFailure) {
9
9
  initBgIntervalProcess("ClientGroupGC", () => {
10
10
  latestGCUpdate = gcClientGroups(dagStore, enableMutationRecovery);
11
11
  return latestGCUpdate;
12
- }, () => GC_INTERVAL_MS, lc, signal);
12
+ }, () => GC_INTERVAL_MS, lc, signal, onStorageFailure);
13
13
  }
14
14
  /**
15
15
  * This removes client groups that have no clients and no pending mutations.
@@ -1 +1 @@
1
- {"version":3,"file":"client-group-gc.js","names":[],"sources":["../../../../../replicache/src/persist/client-group-gc.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport type {ClientGroupID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport {\n clientGroupHasPendingMutations,\n getClientGroups,\n setClientGroups,\n type ClientGroupMap,\n} from './client-groups.ts';\nimport {getClients} from './clients.ts';\n\nconst GC_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n\nlet latestGCUpdate: Promise<ClientGroupMap> | undefined;\nexport function getLatestGCUpdate(): Promise<ClientGroupMap> | undefined {\n return latestGCUpdate;\n}\n\nexport function initClientGroupGC(\n dagStore: Store,\n enableMutationRecovery: boolean,\n lc: LogContext,\n signal: AbortSignal,\n): void {\n initBgIntervalProcess(\n 'ClientGroupGC',\n () => {\n latestGCUpdate = gcClientGroups(dagStore, enableMutationRecovery);\n return latestGCUpdate;\n },\n () => GC_INTERVAL_MS,\n lc,\n signal,\n );\n}\n\n/**\n * This removes client groups that have no clients and no pending mutations.\n * If {@linkcode enableMutationRecovery} is true, it will keep client groups with\n * pending mutations. If it is false, it will remove client groups even when they\n * have pending mutations.\n */\nexport function gcClientGroups(\n dagStore: Store,\n enableMutationRecovery: boolean,\n): Promise<ClientGroupMap> {\n return withWrite(dagStore, async tx => {\n const clients = await getClients(tx);\n const clientGroupIDs = new Set();\n for (const client of clients.values()) {\n clientGroupIDs.add(client.clientGroupID);\n }\n const clientGroups = new Map();\n const removeClientGroups: Set<ClientGroupID> = new Set();\n for (const [clientGroupID, clientGroup] of await getClientGroups(tx)) {\n if (\n clientGroupIDs.has(clientGroupID) ||\n (enableMutationRecovery && clientGroupHasPendingMutations(clientGroup))\n ) {\n clientGroups.set(clientGroupID, clientGroup);\n } else {\n removeClientGroups.add(clientGroupID);\n }\n }\n await setClientGroups(clientGroups, tx);\n // Client group GC doesn't delete individual clients, so we don't call onClientsDeleted\n return clientGroups;\n });\n}\n"],"mappings":";;;;;AAaA,IAAM,iBAAiB,MAAS;AAEhC,IAAI;AAKJ,SAAgB,kBACd,UACA,wBACA,IACA,QACM;CACN,sBACE,uBACM;EACJ,iBAAiB,eAAe,UAAU,sBAAsB;EAChE,OAAO;CACT,SACM,gBACN,IACA,MACF;AACF;;;;;;;AAQA,SAAgB,eACd,UACA,wBACyB;CACzB,OAAO,UAAU,UAAU,OAAM,OAAM;EACrC,MAAM,UAAU,MAAM,WAAW,EAAE;EACnC,MAAM,iCAAiB,IAAI,IAAI;EAC/B,KAAK,MAAM,UAAU,QAAQ,OAAO,GAClC,eAAe,IAAI,OAAO,aAAa;EAEzC,MAAM,+BAAe,IAAI,IAAI;EAC7B,MAAM,qCAAyC,IAAI,IAAI;EACvD,KAAK,MAAM,CAAC,eAAe,gBAAgB,MAAM,gBAAgB,EAAE,GACjE,IACE,eAAe,IAAI,aAAa,KAC/B,0BAA0B,+BAA+B,WAAW,GAErE,aAAa,IAAI,eAAe,WAAW;OAE3C,mBAAmB,IAAI,aAAa;EAGxC,MAAM,gBAAgB,cAAc,EAAE;EAEtC,OAAO;CACT,CAAC;AACH"}
1
+ {"version":3,"file":"client-group-gc.js","names":[],"sources":["../../../../../replicache/src/persist/client-group-gc.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport type {StorageFailureError} from '../storage-failure.ts';\nimport type {ClientGroupID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport {\n clientGroupHasPendingMutations,\n getClientGroups,\n setClientGroups,\n type ClientGroupMap,\n} from './client-groups.ts';\nimport {getClients} from './clients.ts';\n\nconst GC_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n\nlet latestGCUpdate: Promise<ClientGroupMap> | undefined;\nexport function getLatestGCUpdate(): Promise<ClientGroupMap> | undefined {\n return latestGCUpdate;\n}\n\nexport function initClientGroupGC(\n dagStore: Store,\n enableMutationRecovery: boolean,\n lc: LogContext,\n signal: AbortSignal,\n onStorageFailure?: ((failure: StorageFailureError) => void) | undefined,\n): void {\n initBgIntervalProcess(\n 'ClientGroupGC',\n () => {\n latestGCUpdate = gcClientGroups(dagStore, enableMutationRecovery);\n return latestGCUpdate;\n },\n () => GC_INTERVAL_MS,\n lc,\n signal,\n onStorageFailure,\n );\n}\n\n/**\n * This removes client groups that have no clients and no pending mutations.\n * If {@linkcode enableMutationRecovery} is true, it will keep client groups with\n * pending mutations. If it is false, it will remove client groups even when they\n * have pending mutations.\n */\nexport function gcClientGroups(\n dagStore: Store,\n enableMutationRecovery: boolean,\n): Promise<ClientGroupMap> {\n return withWrite(dagStore, async tx => {\n const clients = await getClients(tx);\n const clientGroupIDs = new Set();\n for (const client of clients.values()) {\n clientGroupIDs.add(client.clientGroupID);\n }\n const clientGroups = new Map();\n const removeClientGroups: Set<ClientGroupID> = new Set();\n for (const [clientGroupID, clientGroup] of await getClientGroups(tx)) {\n if (\n clientGroupIDs.has(clientGroupID) ||\n (enableMutationRecovery && clientGroupHasPendingMutations(clientGroup))\n ) {\n clientGroups.set(clientGroupID, clientGroup);\n } else {\n removeClientGroups.add(clientGroupID);\n }\n }\n await setClientGroups(clientGroups, tx);\n // Client group GC doesn't delete individual clients, so we don't call onClientsDeleted\n return clientGroups;\n });\n}\n"],"mappings":";;;;;AAcA,IAAM,iBAAiB,MAAS;AAEhC,IAAI;AAKJ,SAAgB,kBACd,UACA,wBACA,IACA,QACA,kBACM;CACN,sBACE,uBACM;EACJ,iBAAiB,eAAe,UAAU,sBAAsB;EAChE,OAAO;CACT,SACM,gBACN,IACA,QACA,gBACF;AACF;;;;;;;AAQA,SAAgB,eACd,UACA,wBACyB;CACzB,OAAO,UAAU,UAAU,OAAM,OAAM;EACrC,MAAM,UAAU,MAAM,WAAW,EAAE;EACnC,MAAM,iCAAiB,IAAI,IAAI;EAC/B,KAAK,MAAM,UAAU,QAAQ,OAAO,GAClC,eAAe,IAAI,OAAO,aAAa;EAEzC,MAAM,+BAAe,IAAI,IAAI;EAC7B,MAAM,qCAAyC,IAAI,IAAI;EACvD,KAAK,MAAM,CAAC,eAAe,gBAAgB,MAAM,gBAAgB,EAAE,GACjE,IACE,eAAe,IAAI,aAAa,KAC/B,0BAA0B,+BAA+B,WAAW,GAErE,aAAa,IAAI,eAAe,WAAW;OAE3C,mBAAmB,IAAI,aAAa;EAGxC,MAAM,gBAAgB,cAAc,EAAE;EAEtC,OAAO;CACT,CAAC;AACH"}
@@ -1,6 +1,7 @@
1
1
  import type { LogContext, LogLevel, LogSink } from '@rocicorp/logger';
2
2
  import type { Store } from '../dag/store.ts';
3
3
  import type { CreateStore, DropStore, StoreProvider } from '../kv/store.ts';
4
+ import type { StorageFailureError } from '../storage-failure.ts';
4
5
  import type { OnClientsDeleted } from './clients.ts';
5
6
  import type { IndexedDBDatabase } from './idb-databases-store.ts';
6
7
  import { IDBDatabasesStore } from './idb-databases-store.ts';
@@ -12,7 +13,7 @@ export declare const COLLECT_IDB_INTERVAL: number;
12
13
  * We delay the initial collection to prevent doing it at startup.
13
14
  */
14
15
  export declare const INITIAL_COLLECT_IDB_DELAY: number;
15
- export declare function initCollectIDBDatabases(idbDatabasesStore: IDBDatabasesStore, kvStoreProvider: StoreProvider, collectInterval: number, initialCollectDelay: number, maxAge: number, enableMutationRecovery: boolean, onClientsDeleted: OnClientsDeleted, lc: LogContext, signal: AbortSignal, newDagStore?: NewDagStore): void;
16
+ export declare function initCollectIDBDatabases(idbDatabasesStore: IDBDatabasesStore, kvStoreProvider: StoreProvider, collectInterval: number, initialCollectDelay: number, maxAge: number, enableMutationRecovery: boolean, onClientsDeleted: OnClientsDeleted, lc: LogContext, signal: AbortSignal, newDagStore?: NewDagStore, onStorageFailure?: ((failure: StorageFailureError) => void) | undefined): void;
16
17
  /**
17
18
  * Collects IDB databases that are no longer needed.
18
19
  */
@@ -1 +1 @@
1
- {"version":3,"file":"collect-idb-databases.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/collect-idb-databases.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAC,MAAM,kBAAkB,CAAC;AAMpE,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAgB3C,OAAO,KAAK,EAAC,WAAW,EAAE,SAAS,EAAE,aAAa,EAAC,MAAM,gBAAgB,CAAC;AAO1E,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,cAAc,CAAC;AAGnD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAC,iBAAiB,EAAC,MAAM,0BAA0B,CAAC;AAE3D;;GAEG;AACH,eAAO,MAAM,oBAAoB,QAAsB,CAAC;AAExD;;GAEG;AACH,eAAO,MAAM,yBAAyB,QAAgB,CAAC;AAEvD,wBAAgB,uBAAuB,CACrC,iBAAiB,EAAE,iBAAiB,EACpC,eAAe,EAAE,aAAa,EAC9B,eAAe,EAAE,MAAM,EACvB,mBAAmB,EAAE,MAAM,EAC3B,MAAM,EAAE,MAAM,EACd,sBAAsB,EAAE,OAAO,EAC/B,gBAAgB,EAAE,gBAAgB,EAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,WAAW,EACnB,WAAW,GAAE,WAAgC,GAC5C,IAAI,CAyBN;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CACvC,iBAAiB,EAAE,iBAAiB,EACpC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,aAAa,EAC9B,sBAAsB,EAAE,OAAO,EAC/B,gBAAgB,EAAE,gBAAgB,EAClC,WAAW,GAAE,WAAgC,GAC5C,OAAO,CAAC,IAAI,CAAC,CAyEf;AAED,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,MAAM,EACZ,iBAAiB,EAAE,iBAAiB,EACpC,WAAW,EAAE,SAAS,iBAIvB;AA6BD;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,WAAW,KAAK,KAAK,CAAC;AA0C9E;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC;;;OAGG;IACH,OAAO,CAAC,EAAE,KAAK,GAAG,KAAK,GAAG,aAAa,GAAG,SAAS,CAAC;IACpD;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAC;IAChC;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC;CAClC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,mBAAmB,iBAe5E;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC;IACpE,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB,CAAC,CAED;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CACzC,SAAS,EAAE,CAAC,EAAE,EAAE,iBAAiB,KAAK,OAAO,EAC7C,IAAI,CAAC,EAAE,mBAAmB,GACzB,OAAO,CAAC;IACT,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB,CAAC,CAqBD;AA0CD;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,CAAC,EAAE,mBAAmB;aAvFvD,MAAM,EAAE;YACT,OAAO,EAAE;GAwFlB"}
1
+ {"version":3,"file":"collect-idb-databases.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/collect-idb-databases.ts"],"names":[],"mappings":"AAAA,OAAO,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B_DELAY = 300 * 1e3;
24
- function initCollectIDBDatabases(idbDatabasesStore, kvStoreProvider, collectInterval, initialCollectDelay, maxAge, enableMutationRecovery, onClientsDeleted, lc, signal, newDagStore = defaultNewDagStore) {
24
+ function initCollectIDBDatabases(idbDatabasesStore, kvStoreProvider, collectInterval, initialCollectDelay, maxAge, enableMutationRecovery, onClientsDeleted, lc, signal, newDagStore = defaultNewDagStore, onStorageFailure) {
25
25
  let initial = true;
26
26
  initBgIntervalProcess("CollectIDBDatabases", async () => {
27
27
  await collectIDBDatabases(idbDatabasesStore, Date.now(), maxAge, kvStoreProvider, enableMutationRecovery, onClientsDeleted, newDagStore);
@@ -31,7 +31,7 @@ function initCollectIDBDatabases(idbDatabasesStore, kvStoreProvider, collectInte
31
31
  return initialCollectDelay;
32
32
  }
33
33
  return collectInterval;
34
- }, lc, signal);
34
+ }, lc, signal, onStorageFailure);
35
35
  }
36
36
  /**
37
37
  * Collects IDB databases that are no longer needed.
@@ -1 +1 @@
1
- {"version":3,"file":"collect-idb-databases.js","names":[],"sources":["../../../../../replicache/src/persist/collect-idb-databases.ts"],"sourcesContent":["import type {LogContext, LogLevel, LogSink} from '@rocicorp/logger';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {MaybePromise} from '../../../shared/src/types.ts';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport {InvalidRefCountError} from '../dag/invalid-ref-count-error.ts';\nimport {StoreImpl} from '../dag/store-impl.ts';\nimport type {Store} from '../dag/store.ts';\nimport {\n addDeletedClients,\n getDeletedClients,\n mergeDeletedClients,\n normalizeDeletedClients,\n type DeletedClients,\n type WritableDeletedClients,\n} from '../deleted-clients.ts';\nimport * as FormatVersion from '../format-version-enum.ts';\nimport {getKVStoreProvider} from '../get-kv-store-provider.ts';\nimport {assertHash, newRandomHash} from '../hash.ts';\nimport {\n fallbackStoreProvider,\n isFallbackStore,\n} from '../kv/mem-fallback-store.ts';\nimport type {CreateStore, DropStore, StoreProvider} from '../kv/store.ts';\nimport {createLogContext} from '../log-options.ts';\nimport {withRead, withWrite} from '../with-transactions.ts';\nimport {\n clientGroupHasPendingMutations,\n getClientGroups,\n} from './client-groups.ts';\nimport type {OnClientsDeleted} from './clients.ts';\nimport {getClients} from './clients.ts';\nimport {getIDBDatabasesDBName} from './idb-databases-store-db-name.ts';\nimport type {IndexedDBDatabase} from './idb-databases-store.ts';\nimport {IDBDatabasesStore} from './idb-databases-store.ts';\n\n/**\n * How frequently to try to collect\n */\nexport const COLLECT_IDB_INTERVAL = 12 * 60 * 60 * 1000; // 12 hours\n\n/**\n * We delay the initial collection to prevent doing it at startup.\n */\nexport const INITIAL_COLLECT_IDB_DELAY = 5 * 60 * 1000; // 5 minutes\n\nexport function initCollectIDBDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n kvStoreProvider: StoreProvider,\n collectInterval: number,\n initialCollectDelay: number,\n maxAge: number,\n enableMutationRecovery: boolean,\n onClientsDeleted: OnClientsDeleted,\n lc: LogContext,\n signal: AbortSignal,\n newDagStore: NewDagStore = defaultNewDagStore,\n): void {\n let initial = true;\n initBgIntervalProcess(\n 'CollectIDBDatabases',\n async () => {\n await collectIDBDatabases(\n idbDatabasesStore,\n Date.now(),\n maxAge,\n kvStoreProvider,\n enableMutationRecovery,\n onClientsDeleted,\n newDagStore,\n );\n },\n () => {\n if (initial) {\n initial = false;\n return initialCollectDelay;\n }\n return collectInterval;\n },\n lc,\n signal,\n );\n}\n\n/**\n * Collects IDB databases that are no longer needed.\n */\nexport async function collectIDBDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n now: number,\n maxAge: number,\n kvStoreProvider: StoreProvider,\n enableMutationRecovery: boolean,\n onClientsDeleted: OnClientsDeleted,\n newDagStore: NewDagStore = defaultNewDagStore,\n): Promise<void> {\n const databases = await idbDatabasesStore.getDatabases();\n\n const dbs = Object.values(databases);\n const collectResults = await Promise.all(\n dbs.map(\n async db =>\n [\n db.name,\n await gatherDatabaseInfoForCollect(\n db,\n now,\n maxAge,\n enableMutationRecovery,\n kvStoreProvider.create,\n newDagStore,\n ),\n ] as const,\n ),\n );\n\n const dbNamesToRemove: string[] = [];\n const dbNamesToKeep: string[] = [];\n const deletedClientsToRemove: WritableDeletedClients = [];\n for (const [dbName, [canCollect, deletedClients]] of collectResults) {\n if (canCollect) {\n dbNamesToRemove.push(dbName);\n deletedClientsToRemove.push(...deletedClients);\n } else {\n dbNamesToKeep.push(dbName);\n }\n }\n\n const {errors} = await dropDatabases(\n idbDatabasesStore,\n dbNamesToRemove,\n kvStoreProvider.drop,\n );\n if (errors.length) {\n throw errors[0];\n }\n\n if (deletedClientsToRemove.length > 0) {\n // Add the deleted clients to all the dbs that survived the collection.\n let newDeletedClients: DeletedClients = deletedClientsToRemove;\n for (const name of dbNamesToKeep) {\n let dbDeletedClients: DeletedClients;\n try {\n dbDeletedClients = await withWrite(\n newDagStore(name, kvStoreProvider.create),\n dagWrite => addDeletedClients(dagWrite, deletedClientsToRemove),\n );\n } catch (e) {\n if (!(e instanceof InvalidRefCountError)) {\n throw e;\n }\n // This database is corrupt. Its own instance will find out and\n // recover the next time it writes to it; here, just skip it and keep\n // collecting into the others, instead of letting one corrupt\n // database break every collection run forever.\n continue;\n }\n newDeletedClients = mergeDeletedClients(\n newDeletedClients,\n dbDeletedClients,\n );\n }\n // normalize and dedupe\n const normalizedDeletedClients = normalizeDeletedClients(newDeletedClients);\n\n // Call the callback with the normalized deleted clients\n await onClientsDeleted(normalizedDeletedClients);\n }\n}\n\nexport async function dropDatabaseInternal(\n name: string,\n idbDatabasesStore: IDBDatabasesStore,\n kvDropStore: DropStore,\n) {\n await kvDropStore(name);\n await idbDatabasesStore.deleteDatabases([name]);\n}\n\nasync function dropDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n namesToRemove: string[],\n kvDropStore: DropStore,\n): Promise<{dropped: string[]; errors: unknown[]}> {\n // Try to remove the databases in parallel. Don't let a single reject fail the\n // other ones. We will check for failures afterwards.\n const dropStoreResults = await Promise.allSettled(\n namesToRemove.map(async name => {\n await dropDatabaseInternal(name, idbDatabasesStore, kvDropStore);\n return name;\n }),\n );\n\n const dropped: string[] = [];\n const errors: unknown[] = [];\n for (const result of dropStoreResults) {\n if (result.status === 'fulfilled') {\n dropped.push(result.value);\n } else {\n errors.push(result.reason);\n }\n }\n\n return {dropped, errors};\n}\n\n/**\n * Creates the dag store used to inspect and update a database during\n * collection. Callers can override it to install store hooks, for example so\n * a corrupt ref count found while writing deleted clients is recovered from.\n */\nexport type NewDagStore = (name: string, kvCreateStore: CreateStore) => Store;\n\nfunction defaultNewDagStore(name: string, kvCreateStore: CreateStore): Store {\n const perKvStore = kvCreateStore(name);\n return new StoreImpl(perKvStore, newRandomHash, assertHash);\n}\n\n/**\n * If any client has a recent heartbeat or there are pending mutations we\n * return `[false]`. Otherwise we return `[true, deletedClients]`.\n */\nfunction gatherDatabaseInfoForCollect(\n db: IndexedDBDatabase,\n now: number,\n maxAge: number,\n enableMutationRecovery: boolean,\n kvCreateStore: CreateStore,\n newDagStore: NewDagStore,\n): MaybePromise<\n [canCollect: false] | [canCollect: true, deletedClients: DeletedClients]\n> {\n if (db.replicacheFormatVersion > FormatVersion.Latest) {\n return [false];\n }\n\n // If increase the format version we need to decide how to deal with this\n // logic.\n assert(\n db.replicacheFormatVersion === FormatVersion.DD31 ||\n db.replicacheFormatVersion === FormatVersion.V6 ||\n db.replicacheFormatVersion === FormatVersion.V7,\n () =>\n `Expected replicacheFormatVersion to be DD31, V6, or V7, got ${db.replicacheFormatVersion}`,\n );\n return canDatabaseBeCollectedAndGetDeletedClientIDs(\n enableMutationRecovery,\n newDagStore(db.name, kvCreateStore),\n now,\n maxAge,\n );\n}\n\n/**\n * Options for `dropDatabase` and `dropAllDatabases`.\n */\nexport type DropDatabaseOptions = {\n /**\n * Allows providing a custom implementation of the underlying storage layer.\n * Default is `'idb'`.\n */\n kvStore?: 'idb' | 'mem' | StoreProvider | undefined;\n /**\n * Determines how much logging to do. When this is set to `'debug'`,\n * Replicache will also log `'info'` and `'error'` messages. When set to\n * `'info'` we log `'info'` and `'error'` but not `'debug'`. When set to\n * `'error'` we only log `'error'` messages.\n * Default is `'info'`.\n */\n logLevel?: LogLevel | undefined;\n /**\n * Enables custom handling of logs.\n *\n * By default logs are logged to the console. If you would like logs to be\n * sent elsewhere (e.g. to a cloud logging service like DataDog) you can\n * provide an array of {@link LogSink}s. Logs at or above\n * {@link DropDatabaseOptions.logLevel} are sent to each of these {@link LogSink}s.\n * If you would still like logs to go to the console, include\n * `consoleLogSink` in the array.\n *\n * ```ts\n * logSinks: [consoleLogSink, myCloudLogSink],\n * ```\n * Default is `[consoleLogSink]`.\n */\n logSinks?: LogSink[] | undefined;\n};\n\n/**\n * Drops the specified database, from memory as well as from the configured\n * store (see `onStorageFailure`). Rejects if the configured store cannot be\n * opened or dropped.\n * @param dbName The name of the database to drop.\n * @param opts Options for dropping the database.\n */\nexport async function dropDatabase(dbName: string, opts?: DropDatabaseOptions) {\n const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {\n dropDatabase: undefined,\n });\n for (const {provider, drops} of dropTargets(logContext, opts)) {\n if (!drops(dbName)) {\n continue;\n }\n const store = new IDBDatabasesStore(provider.create);\n try {\n await dropDatabaseInternal(dbName, store, provider.drop);\n } finally {\n await closeIgnoringErrors(store);\n }\n }\n}\n\n/**\n * Deletes all IndexedDB data associated with Replicache, and the in-memory\n * databases instances ran on after a storage failure (see\n * `onStorageFailure`).\n *\n * Returns an object with the names of the successfully dropped databases\n * and any errors encountered while dropping. Rejects if the configured store\n * cannot be opened.\n */\nexport function dropAllDatabases(opts?: DropDatabaseOptions): Promise<{\n dropped: string[];\n errors: unknown[];\n}> {\n return dropMatchingDatabases(() => true, opts);\n}\n\n/**\n * Like {@link dropAllDatabases}, for the databases whose registry record\n * matches `predicate`.\n */\nexport async function dropMatchingDatabases(\n predicate: (db: IndexedDBDatabase) => boolean,\n opts?: DropDatabaseOptions,\n): Promise<{\n dropped: string[];\n errors: unknown[];\n}> {\n const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {\n dropDatabases: undefined,\n });\n const dropped = new Set<string>();\n const errors: unknown[] = [];\n for (const {provider, drops} of dropTargets(logContext, opts)) {\n const store = new IDBDatabasesStore(provider.create);\n try {\n const databases = await store.getDatabases();\n const dbNames = Object.values(databases)\n .filter(db => predicate(db) && drops(db.name))\n .map(db => db.name);\n const result = await dropDatabases(store, dbNames, provider.drop);\n result.dropped.forEach(name => dropped.add(name));\n errors.push(...result.errors);\n } finally {\n await closeIgnoringErrors(store);\n }\n }\n return {dropped: [...dropped], errors};\n}\n\ntype DropTarget = {\n provider: StoreProvider;\n /** Whether a database of this name is dropped from `provider`. */\n drops: (name: string) => boolean;\n};\n\n/**\n * The memory stores instances fell back to first, then the configured store.\n * An instance whose store failed to open runs on memory stores of the same\n * names (see `onStorageFailure`), and memory stores outlive the instance for\n * the life of the process, so a drop clears them whatever the configured\n * store is. Only those: the memory stores of `kvStore: 'mem'` instances are\n * left alone unless `'mem'` is the store being dropped from. The configured\n * store is still dropped, and its failure is reported: it may hold data on\n * disk.\n */\nfunction dropTargets(\n lc: LogContext,\n opts: DropDatabaseOptions | undefined,\n): DropTarget[] {\n const all = () => true;\n if (opts?.kvStore === 'mem') {\n return [{provider: getKVStoreProvider(lc, 'mem'), drops: all}];\n }\n const targets: DropTarget[] = [];\n if (isFallbackStore(getIDBDatabasesDBName())) {\n targets.push({provider: fallbackStoreProvider, drops: isFallbackStore});\n }\n targets.push({provider: getKVStoreProvider(lc, opts?.kvStore), drops: all});\n return targets;\n}\n\n/**\n * A store that failed to open may also fail to close; the drop's own result\n * is what the caller needs.\n */\nfunction closeIgnoringErrors(store: IDBDatabasesStore): Promise<void> {\n return store.close().catch(() => undefined);\n}\n\n/**\n * Deletes all IndexedDB data associated with Replicache.\n *\n * Returns an object with the names of the successfully dropped databases\n * and any errors encountered while dropping.\n *\n * @deprecated Use `dropAllDatabases` instead.\n */\nexport function deleteAllReplicacheData(opts?: DropDatabaseOptions) {\n return dropAllDatabases(opts);\n}\n\n/**\n * If there are pending mutations in any of the clients in this db we return\n * `[false]`. If any client has a recent heartbeat we also return `[false]`.\n * Otherwise we return `[true, deletedClients]`.\n */\nfunction canDatabaseBeCollectedAndGetDeletedClientIDs(\n enableMutationRecovery: boolean,\n perdag: Store,\n now: number,\n maxAge: number,\n): Promise<\n [canCollect: false] | [canCollect: true, deletedClients: DeletedClients]\n> {\n return withRead(perdag, async read => {\n // If mutation recovery is disabled we do not care if there are pending\n // mutations when we decide if we can collect the database.\n if (enableMutationRecovery) {\n const clientGroups = await getClientGroups(read);\n for (const clientGroup of clientGroups.values()) {\n if (clientGroupHasPendingMutations(clientGroup)) {\n return [false];\n }\n }\n }\n\n const clients = await getClients(read);\n\n // Don't collect if any client has a recent heartbeat (is still active).\n // This is defense in depth - normally lastOpenedTimestampMS is kept fresh\n // by the heartbeat, but this check protects against edge cases.\n for (const [, client] of clients) {\n if (now - client.heartbeatTimestampMs < maxAge) {\n return [false];\n }\n }\n\n const existingDeletedClients = await getDeletedClients(read);\n const deletedClients: WritableDeletedClients = [...existingDeletedClients];\n\n // Add all current clients to the deleted clients list\n for (const [clientID, client] of clients) {\n deletedClients.push({\n clientID,\n clientGroupID: client.clientGroupID,\n });\n }\n\n // The normalization (deduping and sorting) will be done when storing\n return [true, deletedClients];\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,IAAa,uBAAuB,MAAU,KAAK;;;;AAKnD,IAAa,4BAA4B,MAAS;AAElD,SAAgB,wBACd,mBACA,iBACA,iBACA,qBACA,QACA,wBACA,kBACA,IACA,QACA,cAA2B,oBACrB;CACN,IAAI,UAAU;CACd,sBACE,uBACA,YAAY;EACV,MAAM,oBACJ,mBACA,KAAK,IAAI,GACT,QACA,iBACA,wBACA,kBACA,WACF;CACF,SACM;EACJ,IAAI,SAAS;GACX,UAAU;GACV,OAAO;EACT;EACA,OAAO;CACT,GACA,IACA,MACF;AACF;;;;AAKA,eAAsB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AAM,WAAW,IAAI;EAKrC,KAAK,MAAM,GAAG,WAAW,SACvB,IAAI,MAAM,OAAO,uBAAuB,QACtC,OAAO,CAAC,KAAK;EAKjB,MAAM,iBAAyC,CAAC,GAAG,MADd,kBAAkB,IAAI,CACc;EAGzE,KAAK,MAAM,CAAC,UAAU,WAAW,SAC/B,eAAe,KAAK;GAClB;GACA,eAAe,OAAO;EACxB,CAAC;EAIH,OAAO,CAAC,MAAM,cAAc;CAC9B,CAAC;AACH"}
1
+ {"version":3,"file":"collect-idb-databases.js","names":[],"sources":["../../../../../replicache/src/persist/collect-idb-databases.ts"],"sourcesContent":["import type {LogContext, LogLevel, LogSink} from '@rocicorp/logger';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {MaybePromise} from '../../../shared/src/types.ts';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport {InvalidRefCountError} from '../dag/invalid-ref-count-error.ts';\nimport {StoreImpl} from '../dag/store-impl.ts';\nimport type {Store} from '../dag/store.ts';\nimport {\n addDeletedClients,\n getDeletedClients,\n mergeDeletedClients,\n normalizeDeletedClients,\n type DeletedClients,\n type WritableDeletedClients,\n} from '../deleted-clients.ts';\nimport * as FormatVersion from '../format-version-enum.ts';\nimport {getKVStoreProvider} from '../get-kv-store-provider.ts';\nimport {assertHash, newRandomHash} from '../hash.ts';\nimport {\n fallbackStoreProvider,\n isFallbackStore,\n} from '../kv/mem-fallback-store.ts';\nimport type {CreateStore, DropStore, StoreProvider} from '../kv/store.ts';\nimport {createLogContext} from '../log-options.ts';\nimport type {StorageFailureError} from '../storage-failure.ts';\nimport {withRead, withWrite} from '../with-transactions.ts';\nimport {\n clientGroupHasPendingMutations,\n getClientGroups,\n} from './client-groups.ts';\nimport type {OnClientsDeleted} from './clients.ts';\nimport {getClients} from './clients.ts';\nimport {getIDBDatabasesDBName} from './idb-databases-store-db-name.ts';\nimport type {IndexedDBDatabase} from './idb-databases-store.ts';\nimport {IDBDatabasesStore} from './idb-databases-store.ts';\n\n/**\n * How frequently to try to collect\n */\nexport const COLLECT_IDB_INTERVAL = 12 * 60 * 60 * 1000; // 12 hours\n\n/**\n * We delay the initial collection to prevent doing it at startup.\n */\nexport const INITIAL_COLLECT_IDB_DELAY = 5 * 60 * 1000; // 5 minutes\n\nexport function initCollectIDBDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n kvStoreProvider: StoreProvider,\n collectInterval: number,\n initialCollectDelay: number,\n maxAge: number,\n enableMutationRecovery: boolean,\n onClientsDeleted: OnClientsDeleted,\n lc: LogContext,\n signal: AbortSignal,\n newDagStore: NewDagStore = defaultNewDagStore,\n onStorageFailure?: ((failure: StorageFailureError) => void) | undefined,\n): void {\n let initial = true;\n initBgIntervalProcess(\n 'CollectIDBDatabases',\n async () => {\n await collectIDBDatabases(\n idbDatabasesStore,\n Date.now(),\n maxAge,\n kvStoreProvider,\n enableMutationRecovery,\n onClientsDeleted,\n newDagStore,\n );\n },\n () => {\n if (initial) {\n initial = false;\n return initialCollectDelay;\n }\n return collectInterval;\n },\n lc,\n signal,\n onStorageFailure,\n );\n}\n\n/**\n * Collects IDB databases that are no longer needed.\n */\nexport async function collectIDBDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n now: number,\n maxAge: number,\n kvStoreProvider: StoreProvider,\n enableMutationRecovery: boolean,\n onClientsDeleted: OnClientsDeleted,\n newDagStore: NewDagStore = defaultNewDagStore,\n): Promise<void> {\n const databases = await idbDatabasesStore.getDatabases();\n\n const dbs = Object.values(databases);\n const collectResults = await Promise.all(\n dbs.map(\n async db =>\n [\n db.name,\n await gatherDatabaseInfoForCollect(\n db,\n now,\n maxAge,\n enableMutationRecovery,\n kvStoreProvider.create,\n newDagStore,\n ),\n ] as const,\n ),\n );\n\n const dbNamesToRemove: string[] = [];\n const dbNamesToKeep: string[] = [];\n const deletedClientsToRemove: WritableDeletedClients = [];\n for (const [dbName, [canCollect, deletedClients]] of collectResults) {\n if (canCollect) {\n dbNamesToRemove.push(dbName);\n deletedClientsToRemove.push(...deletedClients);\n } else {\n dbNamesToKeep.push(dbName);\n }\n }\n\n const {errors} = await dropDatabases(\n idbDatabasesStore,\n dbNamesToRemove,\n kvStoreProvider.drop,\n );\n if (errors.length) {\n throw errors[0];\n }\n\n if (deletedClientsToRemove.length > 0) {\n // Add the deleted clients to all the dbs that survived the collection.\n let newDeletedClients: DeletedClients = deletedClientsToRemove;\n for (const name of dbNamesToKeep) {\n let dbDeletedClients: DeletedClients;\n try {\n dbDeletedClients = await withWrite(\n newDagStore(name, kvStoreProvider.create),\n dagWrite => addDeletedClients(dagWrite, deletedClientsToRemove),\n );\n } catch (e) {\n if (!(e instanceof InvalidRefCountError)) {\n throw e;\n }\n // This database is corrupt. Its own instance will find out and\n // recover the next time it writes to it; here, just skip it and keep\n // collecting into the others, instead of letting one corrupt\n // database break every collection run forever.\n continue;\n }\n newDeletedClients = mergeDeletedClients(\n newDeletedClients,\n dbDeletedClients,\n );\n }\n // normalize and dedupe\n const normalizedDeletedClients = normalizeDeletedClients(newDeletedClients);\n\n // Call the callback with the normalized deleted clients\n await onClientsDeleted(normalizedDeletedClients);\n }\n}\n\nexport async function dropDatabaseInternal(\n name: string,\n idbDatabasesStore: IDBDatabasesStore,\n kvDropStore: DropStore,\n) {\n await kvDropStore(name);\n await idbDatabasesStore.deleteDatabases([name]);\n}\n\nasync function dropDatabases(\n idbDatabasesStore: IDBDatabasesStore,\n namesToRemove: string[],\n kvDropStore: DropStore,\n): Promise<{dropped: string[]; errors: unknown[]}> {\n // Try to remove the databases in parallel. Don't let a single reject fail the\n // other ones. We will check for failures afterwards.\n const dropStoreResults = await Promise.allSettled(\n namesToRemove.map(async name => {\n await dropDatabaseInternal(name, idbDatabasesStore, kvDropStore);\n return name;\n }),\n );\n\n const dropped: string[] = [];\n const errors: unknown[] = [];\n for (const result of dropStoreResults) {\n if (result.status === 'fulfilled') {\n dropped.push(result.value);\n } else {\n errors.push(result.reason);\n }\n }\n\n return {dropped, errors};\n}\n\n/**\n * Creates the dag store used to inspect and update a database during\n * collection. Callers can override it to install store hooks, for example so\n * a corrupt ref count found while writing deleted clients is recovered from.\n */\nexport type NewDagStore = (name: string, kvCreateStore: CreateStore) => Store;\n\nfunction defaultNewDagStore(name: string, kvCreateStore: CreateStore): Store {\n const perKvStore = kvCreateStore(name);\n return new StoreImpl(perKvStore, newRandomHash, assertHash);\n}\n\n/**\n * If any client has a recent heartbeat or there are pending mutations we\n * return `[false]`. Otherwise we return `[true, deletedClients]`.\n */\nfunction gatherDatabaseInfoForCollect(\n db: IndexedDBDatabase,\n now: number,\n maxAge: number,\n enableMutationRecovery: boolean,\n kvCreateStore: CreateStore,\n newDagStore: NewDagStore,\n): MaybePromise<\n [canCollect: false] | [canCollect: true, deletedClients: DeletedClients]\n> {\n if (db.replicacheFormatVersion > FormatVersion.Latest) {\n return [false];\n }\n\n // If increase the format version we need to decide how to deal with this\n // logic.\n assert(\n db.replicacheFormatVersion === FormatVersion.DD31 ||\n db.replicacheFormatVersion === FormatVersion.V6 ||\n db.replicacheFormatVersion === FormatVersion.V7,\n () =>\n `Expected replicacheFormatVersion to be DD31, V6, or V7, got ${db.replicacheFormatVersion}`,\n );\n return canDatabaseBeCollectedAndGetDeletedClientIDs(\n enableMutationRecovery,\n newDagStore(db.name, kvCreateStore),\n now,\n maxAge,\n );\n}\n\n/**\n * Options for `dropDatabase` and `dropAllDatabases`.\n */\nexport type DropDatabaseOptions = {\n /**\n * Allows providing a custom implementation of the underlying storage layer.\n * Default is `'idb'`.\n */\n kvStore?: 'idb' | 'mem' | StoreProvider | undefined;\n /**\n * Determines how much logging to do. When this is set to `'debug'`,\n * Replicache will also log `'info'` and `'error'` messages. When set to\n * `'info'` we log `'info'` and `'error'` but not `'debug'`. When set to\n * `'error'` we only log `'error'` messages.\n * Default is `'info'`.\n */\n logLevel?: LogLevel | undefined;\n /**\n * Enables custom handling of logs.\n *\n * By default logs are logged to the console. If you would like logs to be\n * sent elsewhere (e.g. to a cloud logging service like DataDog) you can\n * provide an array of {@link LogSink}s. Logs at or above\n * {@link DropDatabaseOptions.logLevel} are sent to each of these {@link LogSink}s.\n * If you would still like logs to go to the console, include\n * `consoleLogSink` in the array.\n *\n * ```ts\n * logSinks: [consoleLogSink, myCloudLogSink],\n * ```\n * Default is `[consoleLogSink]`.\n */\n logSinks?: LogSink[] | undefined;\n};\n\n/**\n * Drops the specified database, from memory as well as from the configured\n * store (see `onStorageFailure`). Rejects if the configured store cannot be\n * opened or dropped.\n * @param dbName The name of the database to drop.\n * @param opts Options for dropping the database.\n */\nexport async function dropDatabase(dbName: string, opts?: DropDatabaseOptions) {\n const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {\n dropDatabase: undefined,\n });\n for (const {provider, drops} of dropTargets(logContext, opts)) {\n if (!drops(dbName)) {\n continue;\n }\n const store = new IDBDatabasesStore(provider.create);\n try {\n await dropDatabaseInternal(dbName, store, provider.drop);\n } finally {\n await closeIgnoringErrors(store);\n }\n }\n}\n\n/**\n * Deletes all IndexedDB data associated with Replicache, and the in-memory\n * databases instances ran on after a storage failure (see\n * `onStorageFailure`).\n *\n * Returns an object with the names of the successfully dropped databases\n * and any errors encountered while dropping. Rejects if the configured store\n * cannot be opened.\n */\nexport function dropAllDatabases(opts?: DropDatabaseOptions): Promise<{\n dropped: string[];\n errors: unknown[];\n}> {\n return dropMatchingDatabases(() => true, opts);\n}\n\n/**\n * Like {@link dropAllDatabases}, for the databases whose registry record\n * matches `predicate`.\n */\nexport async function dropMatchingDatabases(\n predicate: (db: IndexedDBDatabase) => boolean,\n opts?: DropDatabaseOptions,\n): Promise<{\n dropped: string[];\n errors: unknown[];\n}> {\n const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {\n dropDatabases: undefined,\n });\n const dropped = new Set<string>();\n const errors: unknown[] = [];\n for (const {provider, drops} of dropTargets(logContext, opts)) {\n const store = new IDBDatabasesStore(provider.create);\n try {\n const databases = await store.getDatabases();\n const dbNames = Object.values(databases)\n .filter(db => predicate(db) && drops(db.name))\n .map(db => db.name);\n const result = await dropDatabases(store, dbNames, provider.drop);\n result.dropped.forEach(name => dropped.add(name));\n errors.push(...result.errors);\n } finally {\n await closeIgnoringErrors(store);\n }\n }\n return {dropped: [...dropped], errors};\n}\n\ntype DropTarget = {\n provider: StoreProvider;\n /** Whether a database of this name is dropped from `provider`. */\n drops: (name: string) => boolean;\n};\n\n/**\n * The memory stores instances fell back to first, then the configured store.\n * An instance whose store failed to open runs on memory stores of the same\n * names (see `onStorageFailure`), and memory stores outlive the instance for\n * the life of the process, so a drop clears them whatever the configured\n * store is. Only those: the memory stores of `kvStore: 'mem'` instances are\n * left alone unless `'mem'` is the store being dropped from. The configured\n * store is still dropped, and its failure is reported: it may hold data on\n * disk.\n */\nfunction dropTargets(\n lc: LogContext,\n opts: DropDatabaseOptions | undefined,\n): DropTarget[] {\n const all = () => true;\n if (opts?.kvStore === 'mem') {\n return [{provider: getKVStoreProvider(lc, 'mem'), drops: all}];\n }\n const targets: DropTarget[] = [];\n if (isFallbackStore(getIDBDatabasesDBName())) {\n targets.push({provider: fallbackStoreProvider, drops: isFallbackStore});\n }\n targets.push({provider: getKVStoreProvider(lc, opts?.kvStore), drops: all});\n return targets;\n}\n\n/**\n * A store that failed to open may also fail to close; the drop's own result\n * is what the caller needs.\n */\nfunction closeIgnoringErrors(store: IDBDatabasesStore): Promise<void> {\n return store.close().catch(() => undefined);\n}\n\n/**\n * Deletes all IndexedDB data associated with Replicache.\n *\n * Returns an object with the names of the successfully dropped databases\n * and any errors encountered while dropping.\n *\n * @deprecated Use `dropAllDatabases` instead.\n */\nexport function deleteAllReplicacheData(opts?: DropDatabaseOptions) {\n return dropAllDatabases(opts);\n}\n\n/**\n * If there are pending mutations in any of the clients in this db we return\n * `[false]`. If any client has a recent heartbeat we also return `[false]`.\n * Otherwise we return `[true, deletedClients]`.\n */\nfunction canDatabaseBeCollectedAndGetDeletedClientIDs(\n enableMutationRecovery: boolean,\n perdag: Store,\n now: number,\n maxAge: number,\n): Promise<\n [canCollect: false] | [canCollect: true, deletedClients: DeletedClients]\n> {\n return withRead(perdag, async read => {\n // If mutation recovery is disabled we do not care if there are pending\n // mutations when we decide if we can collect the database.\n if (enableMutationRecovery) {\n const clientGroups = await getClientGroups(read);\n for (const clientGroup of clientGroups.values()) {\n if (clientGroupHasPendingMutations(clientGroup)) {\n return [false];\n }\n }\n }\n\n const clients = await getClients(read);\n\n // Don't collect if any client has a recent heartbeat (is still active).\n // This is defense in depth - normally lastOpenedTimestampMS is kept fresh\n // by the heartbeat, but this check protects against edge cases.\n for (const [, client] of clients) {\n if (now - client.heartbeatTimestampMs < maxAge) {\n return [false];\n }\n }\n\n const existingDeletedClients = await getDeletedClients(read);\n const deletedClients: WritableDeletedClients = [...existingDeletedClients];\n\n // Add all current clients to the deleted clients list\n for (const [clientID, client] of clients) {\n deletedClients.push({\n clientID,\n clientGroupID: client.clientGroupID,\n });\n }\n\n // The normalization (deduping and sorting) will be done when storing\n return [true, deletedClients];\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuCA,IAAa,uBAAuB,MAAU,KAAK;;;;AAKnD,IAAa,4BAA4B,MAAS;AAElD,SAAgB,wBACd,mBACA,iBACA,iBACA,qBACA,QACA,wBACA,kBACA,IACA,QACA,cAA2B,oBAC3B,kBACM;CACN,IAAI,UAAU;CACd,sBACE,uBACA,YAAY;EACV,MAAM,oBACJ,mBACA,KAAK,IAAI,GACT,QACA,iBACA,wBACA,kBACA,WACF;CACF,SACM;EACJ,IAAI,SAAS;GACX,UAAU;GACV,OAAO;EACT;EACA,OAAO;CACT,GACA,IACA,QACA,gBACF;AACF;;;;AAKA,eAAsB,oBACpB,mBACA,KACA,QACA,iBACA,wBACA,kBACA,cAA2B,oBACZ;CACf,MAAM,YAAY,MAAM,kBAAkB,aAAa;CAEvD,MAAM,MAAM,OAAO,OAAO,SAAS;CACnC,MAAM,iBAAiB,MAAM,QAAQ,IACnC,IAAI,IACF,OAAM,OACJ,CACE,GAAG,MACH,MAA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KAAK;GAClB;GACA,eAAe,OAAO;EACxB,CAAC;EAIH,OAAO,CAAC,MAAM,cAAc;CAC9B,CAAC;AACH"}
@@ -1,9 +1,10 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Store } from '../dag/store.ts';
3
+ import type { StorageFailureError } from '../storage-failure.ts';
3
4
  import type { ClientID } from '../sync/ids.ts';
4
5
  import { type ClientMap } from './clients.ts';
5
6
  export declare const HEARTBEAT_INTERVAL: number;
6
7
  export declare let latestHeartbeatUpdate: Promise<ClientMap> | undefined;
7
- export declare function startHeartbeats(clientID: ClientID, dagStore: Store, onClientStateNotFound: () => void, heartbeatIntervalMs: number, lc: LogContext, signal: AbortSignal): void;
8
+ export declare function startHeartbeats(clientID: ClientID, dagStore: Store, onClientStateNotFound: () => void, heartbeatIntervalMs: number, lc: LogContext, signal: AbortSignal, onStorageFailure?: ((failure: StorageFailureError) => void) | undefined): void;
8
9
  export declare function writeHeartbeat(clientID: ClientID, dagStore: Store): Promise<ClientMap>;
9
10
  //# sourceMappingURL=heartbeat.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"heartbeat.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/heartbeat.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAE7C,OAAO,EACL,KAAK,SAAS,EAIf,MAAM,cAAc,CAAC;AAEtB,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAE5C,eAAO,IAAI,qBAAqB,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;AAEjE,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,KAAK,EACf,qBAAqB,EAAE,MAAM,IAAI,EACjC,mBAAmB,EAAE,MAAM,EAC3B,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,WAAW,GAClB,IAAI,CAmBN;AAED,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,KAAK,GACd,OAAO,CAAC,SAAS,CAAC,CAiBpB"}
1
+ {"version":3,"file":"heartbeat.d.ts","sourceRoot":"","sources":["../../../../../replicache/src/persist/heartbeat.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,KAAK,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAC,mBAAmB,EAAC,MAAM,uBAAuB,CAAC;AAC/D,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,gBAAgB,CAAC;AAE7C,OAAO,EACL,KAAK,SAAS,EAIf,MAAM,cAAc,CAAC;AAEtB,eAAO,MAAM,kBAAkB,QAAY,CAAC;AAE5C,eAAO,IAAI,qBAAqB,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;AAEjE,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,KAAK,EACf,qBAAqB,EAAE,MAAM,IAAI,EACjC,mBAAmB,EAAE,MAAM,EAC3B,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,WAAW,EACnB,gBAAgB,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,mBAAmB,KAAK,IAAI,CAAC,GAAG,SAAS,GACtE,IAAI,CAoBN;AAED,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,QAAQ,EAClB,QAAQ,EAAE,KAAK,GACd,OAAO,CAAC,SAAS,CAAC,CAiBpB"}
@@ -4,7 +4,7 @@ import { ClientStateNotFoundError, getClients, setClients } from "./clients.js";
4
4
  //#region ../replicache/src/persist/heartbeat.ts
5
5
  var HEARTBEAT_INTERVAL = 60 * 1e3;
6
6
  var latestHeartbeatUpdate;
7
- function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatIntervalMs, lc, signal) {
7
+ function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatIntervalMs, lc, signal, onStorageFailure) {
8
8
  initBgIntervalProcess("Heartbeat", async () => {
9
9
  latestHeartbeatUpdate = writeHeartbeat(clientID, dagStore);
10
10
  try {
@@ -16,7 +16,7 @@ function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatInt
16
16
  }
17
17
  throw e;
18
18
  }
19
- }, () => heartbeatIntervalMs, lc, signal);
19
+ }, () => heartbeatIntervalMs, lc, signal, onStorageFailure);
20
20
  }
21
21
  function writeHeartbeat(clientID, dagStore) {
22
22
  return withWrite(dagStore, async (dagWrite) => {
@@ -1 +1 @@
1
- {"version":3,"file":"heartbeat.js","names":[],"sources":["../../../../../replicache/src/persist/heartbeat.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport type {ClientID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport {\n type ClientMap,\n ClientStateNotFoundError,\n getClients,\n setClients,\n} from './clients.ts';\n\nexport const HEARTBEAT_INTERVAL = 60 * 1000;\n\nexport let latestHeartbeatUpdate: Promise<ClientMap> | undefined;\n\nexport function startHeartbeats(\n clientID: ClientID,\n dagStore: Store,\n onClientStateNotFound: () => void,\n heartbeatIntervalMs: number,\n lc: LogContext,\n signal: AbortSignal,\n): void {\n initBgIntervalProcess(\n 'Heartbeat',\n async () => {\n latestHeartbeatUpdate = writeHeartbeat(clientID, dagStore);\n try {\n return await latestHeartbeatUpdate;\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n onClientStateNotFound();\n return;\n }\n throw e;\n }\n },\n () => heartbeatIntervalMs,\n lc,\n signal,\n );\n}\n\nexport function writeHeartbeat(\n clientID: ClientID,\n dagStore: Store,\n): Promise<ClientMap> {\n return withWrite(dagStore, async dagWrite => {\n const clients = await getClients(dagWrite);\n const client = clients.get(clientID);\n if (!client) {\n throw new ClientStateNotFoundError(clientID);\n }\n\n const newClient = {\n ...client,\n heartbeatTimestampMs: Date.now(),\n };\n const newClients = new Map(clients).set(clientID, newClient);\n\n await setClients(newClients, dagWrite);\n return newClients;\n });\n}\n"],"mappings":";;;;AAYA,IAAa,qBAAqB,KAAK;AAEvC,IAAW;AAEX,SAAgB,gBACd,UACA,UACA,uBACA,qBACA,IACA,QACM;CACN,sBACE,aACA,YAAY;EACV,wBAAwB,eAAe,UAAU,QAAQ;EACzD,IAAI;GACF,OAAO,MAAM;EACf,SAAS,GAAG;GACV,IAAI,aAAa,0BAA0B;IACzC,sBAAsB;IACtB;GACF;GACA,MAAM;EACR;CACF,SACM,qBACN,IACA,MACF;AACF;AAEA,SAAgB,eACd,UACA,UACoB;CACpB,OAAO,UAAU,UAAU,OAAM,aAAY;EAC3C,MAAM,UAAU,MAAM,WAAW,QAAQ;EACzC,MAAM,SAAS,QAAQ,IAAI,QAAQ;EACnC,IAAI,CAAC,QACH,MAAM,IAAI,yBAAyB,QAAQ;EAG7C,MAAM,YAAY;GAChB,GAAG;GACH,sBAAsB,KAAK,IAAI;EACjC;EACA,MAAM,aAAa,IAAI,IAAI,OAAO,EAAE,IAAI,UAAU,SAAS;EAE3D,MAAM,WAAW,YAAY,QAAQ;EACrC,OAAO;CACT,CAAC;AACH"}
1
+ {"version":3,"file":"heartbeat.js","names":[],"sources":["../../../../../replicache/src/persist/heartbeat.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {initBgIntervalProcess} from '../bg-interval.ts';\nimport type {Store} from '../dag/store.ts';\nimport type {StorageFailureError} from '../storage-failure.ts';\nimport type {ClientID} from '../sync/ids.ts';\nimport {withWrite} from '../with-transactions.ts';\nimport {\n type ClientMap,\n ClientStateNotFoundError,\n getClients,\n setClients,\n} from './clients.ts';\n\nexport const HEARTBEAT_INTERVAL = 60 * 1000;\n\nexport let latestHeartbeatUpdate: Promise<ClientMap> | undefined;\n\nexport function startHeartbeats(\n clientID: ClientID,\n dagStore: Store,\n onClientStateNotFound: () => void,\n heartbeatIntervalMs: number,\n lc: LogContext,\n signal: AbortSignal,\n onStorageFailure?: ((failure: StorageFailureError) => void) | undefined,\n): void {\n initBgIntervalProcess(\n 'Heartbeat',\n async () => {\n latestHeartbeatUpdate = writeHeartbeat(clientID, dagStore);\n try {\n return await latestHeartbeatUpdate;\n } catch (e) {\n if (e instanceof ClientStateNotFoundError) {\n onClientStateNotFound();\n return;\n }\n throw e;\n }\n },\n () => heartbeatIntervalMs,\n lc,\n signal,\n onStorageFailure,\n );\n}\n\nexport function writeHeartbeat(\n clientID: ClientID,\n dagStore: Store,\n): Promise<ClientMap> {\n return withWrite(dagStore, async dagWrite => {\n const clients = await getClients(dagWrite);\n const client = clients.get(clientID);\n if (!client) {\n throw new ClientStateNotFoundError(clientID);\n }\n\n const newClient = {\n ...client,\n heartbeatTimestampMs: Date.now(),\n };\n const newClients = new Map(clients).set(clientID, newClient);\n\n await setClients(newClients, dagWrite);\n return newClients;\n });\n}\n"],"mappings":";;;;AAaA,IAAa,qBAAqB,KAAK;AAEvC,IAAW;AAEX,SAAgB,gBACd,UACA,UACA,uBACA,qBACA,IACA,QACA,kBACM;CACN,sBACE,aACA,YAAY;EACV,wBAAwB,eAAe,UAAU,QAAQ;EACzD,IAAI;GACF,OAAO,MAAM;EACf,SAAS,GAAG;GACV,IAAI,aAAa,0BAA0B;IACzC,sBAAsB;IACtB;GACF;GACA,MAAM;EACR;CACF,SACM,qBACN,IACA,QACA,gBACF;AACF;AAEA,SAAgB,eACd,UACA,UACoB;CACpB,OAAO,UAAU,UAAU,OAAM,aAAY;EAC3C,MAAM,UAAU,MAAM,WAAW,QAAQ;EACzC,MAAM,SAAS,QAAQ,IAAI,QAAQ;EACnC,IAAI,CAAC,QACH,MAAM,IAAI,yBAAyB,QAAQ;EAG7C,MAAM,YAAY;GAChB,GAAG;GACH,sBAAsB,KAAK,IAAI;EACjC;EACA,MAAM,aAAa,IAAI,IAAI,OAAO,EAAE,IAAI,UAAU,SAAS;EAE3D,MAAM,WAAW,YAAY,QAAQ;EACrC,OAAO;CACT,CAAC;AACH"}
@@ -169,7 +169,8 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
169
169
  * instance. A read that needs a chunk the in-memory dag has not loaded from
170
170
  * the store yet, or has since evicted from its cache, still goes to the
171
171
  * store and fails the way any store read does; that failure reaches its
172
- * caller and is not reclassified here. An invalid ref count reported while
172
+ * caller, and is reported here as well, whichever caller it was (a query,
173
+ * a mutation, a poke, a background process). An invalid ref count reported while
173
174
  * the store is failing with `cannot-open` or `io-error` is NOT treated as
174
175
  * corruption (the database is not dropped and {@link onClientStateNotFound}
175
176
  * is not called), because a store that cannot complete a read or write is
@@ -179,8 +180,10 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
179
180
  *
180
181
  * After the open, the failure is detected when a transaction on the store
181
182
  * fails to begin or to commit, whichever caller ran it (`persist()`, the
182
- * heartbeat, garbage collection, ...), and when `persist()` or `refresh()`
183
- * fails. The background maintenance processes (heartbeat, client and
183
+ * heartbeat, garbage collection, ...), when `persist()` or `refresh()`
184
+ * fails, when the in-memory dag fails to load a chunk from the store for
185
+ * any caller, and when a background process fails on a store read inside
186
+ * its transaction. The background maintenance processes (heartbeat, client and
184
187
  * client-group GC, database collection, mutation recovery) stop on it
185
188
  * instead of retrying against the store at their interval.
186
189
  *
@@ -311,6 +314,34 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
311
314
  beginPull(): Promise<BeginPullResult>;
312
315
  persist(): Promise<void>;
313
316
  refresh(): Promise<void>;
317
+ /**
318
+ * Stops every write to the local store, for an instance whose database is
319
+ * about to be dropped from under it: the store-writing background
320
+ * processes (heartbeat, GC, collection, mutation recovery) are aborted, a
321
+ * `persist()` already in flight is waited for, and every later `persist()`
322
+ * — scheduled or explicit — is a no-op. Mutations keep running against the in-memory
323
+ * dag until the app replaces the instance (see `onClientStateNotFound`).
324
+ *
325
+ * Use together with {@link stopRefresh} before dropping the database, so
326
+ * the drop's own footprint — `database is closed` from the next scheduled
327
+ * persist and the background processes — is not logged as errors against a
328
+ * store that was deleted on purpose.
329
+ */
330
+ stopPersist(): Promise<void>;
331
+ /**
332
+ * Stops every refresh from the local store, for an instance whose database
333
+ * is about to be dropped from under it: the store-reading background
334
+ * process (the new-client channel) is aborted, a `refresh()` already in
335
+ * flight is waited for, and every later `refresh()` / `runRefresh()` —
336
+ * scheduled or explicit — is a no-op. Queries keep running against the
337
+ * in-memory dag until the app replaces the instance (see
338
+ * `onClientStateNotFound`).
339
+ *
340
+ * Use together with {@link stopPersist} before dropping the database, so
341
+ * the run loop's refresh after a connect error does not run into the
342
+ * dropped store and log `database is closed` as an error.
343
+ */
344
+ stopRefresh(): Promise<void>;
314
345
  disableClientGroup(): Promise<void>;
315
346
  /**
316
347
  * Runs a refresh as soon as possible through the refresh scheduler.
@@ -1 +1 @@
1
- {"version":3,"file":"replicache-impl.d.ts","sourceRoot":"","sources":["../../../../replicache/src/replicache-impl.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAUjD,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,2BAA2B,CAAC;AAG5D,OAAO,EAAe,KAAK,MAAM,EAAC,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAC,SAAS,EAAC,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAsC,KAAK,KAAK,EAAC,MAAM,gBAAgB,CAAC;AAoB/E,OAAO,EAAwB,KAAK,IAAI,EAAgB,MAAM,WAAW,CAAC;AAQ1E,OAAO,KAAK,EAAC,KAAK,IAAI,OAAO,EAAC,MAAM,eAAe,CAAC;AAUpD,OAAO,EACL,KAAK,eAAe,EAErB,MAAM,wBAAwB,CAAC;AAQhC,OAAO,EAGL,KAAK,gBAAgB,EAEtB,MAAM,sBAAsB,CA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