@vrtmrz/livesync-commonlib 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/common/LSError.d.ts +13 -0
  2. package/dist/common/LSError.js +19 -1
  3. package/dist/diagnostics/local.d.ts +7 -2
  4. package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
  5. package/dist/interfaces/FileHandler.d.ts +67 -1
  6. package/dist/interfaces/FileHandler.js +16 -0
  7. package/dist/interfaces/StorageEventManager.d.ts +7 -0
  8. package/dist/managers/ChunkFetcher.d.ts +16 -0
  9. package/dist/managers/ChunkFetcher.js +190 -112
  10. package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
  11. package/dist/managers/EntryManager/EntryManager.js +6 -0
  12. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
  13. package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
  14. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
  15. package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
  16. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
  17. package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
  18. package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
  19. package/dist/managers/LayeredChunkManager.d.ts +4 -0
  20. package/dist/managers/LayeredChunkManager.js +19 -6
  21. package/dist/managers/LiveSyncManagers.d.ts +2 -0
  22. package/dist/managers/LiveSyncManagers.js +6 -0
  23. package/dist/managers/StorageEventManager.d.ts +22 -0
  24. package/dist/managers/StorageEventManager.js +48 -1
  25. package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
  26. package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
  27. package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
  28. package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
  29. package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
  30. package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
  31. package/dist/replication/contentRead.d.ts +3 -0
  32. package/dist/replication/contentRead.js +4 -0
  33. package/dist/replication/couchdb/LiveSyncReplicator.d.ts +8 -1
  34. package/dist/replication/couchdb/LiveSyncReplicator.js +187 -119
  35. package/dist/replication/index.d.ts +5 -1
  36. package/dist/replication/index.js +18 -1
  37. package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
  38. package/dist/serviceFeatures/offlineScanner/files.js +27 -7
  39. package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
  40. package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
  41. package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
  42. package/dist/serviceFeatures/offlineScanner.js +10 -2
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
  45. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
  46. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
  47. package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
  48. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
  49. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
  51. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
  52. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
  53. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
  54. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
  56. package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
  57. package/dist/services/base/ControlService.js +1 -5
  58. package/dist/services/base/DatabaseEventService.d.ts +3 -0
  59. package/dist/services/base/DatabaseEventService.js +3 -0
  60. package/dist/services/base/DatabaseService.d.ts +15 -0
  61. package/dist/services/base/DatabaseService.js +85 -4
  62. package/dist/services/base/IService.d.ts +18 -1
  63. package/dist/services/base/KeyValueDBService.d.ts +5 -4
  64. package/dist/services/base/KeyValueDBService.js +46 -48
  65. package/dist/services/base/ReplicationService.d.ts +3 -1
  66. package/dist/services/base/ReplicationService.js +3 -1
  67. package/dist/services/base/VaultScanResult.d.ts +5 -0
  68. package/dist/services/lib/HandlerUtils.d.ts +40 -5
  69. package/dist/services/lib/HandlerUtils.js +52 -4
  70. package/docs/development.md +8 -0
  71. package/docs/offline-scanner.md +46 -0
  72. package/docs/releasing.md +42 -0
  73. package/package.json +1 -1
@@ -1,22 +1,14 @@
1
- import { Logger, LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
2
- import { LiveSyncError } from "../../common/LSError.js";
1
+ import { ContentReadError } from "../../common/LSError.js";
3
2
  class DatabaseReadLayer {
4
- constructor(database) {
3
+ constructor(database, readScope) {
5
4
  this.database = database;
5
+ this.readScope = readScope;
6
6
  }
7
7
  database;
8
+ readScope;
8
9
  isChunkDoc(doc) {
9
10
  return doc && typeof doc._id === "string" && doc.type === "leaf";
10
11
  }
11
- getError(error) {
12
- if (error instanceof Error) {
13
- return error;
14
- }
15
- if (typeof error === "object" && error !== null && "error" in error && error.error instanceof Error) {
16
- return error.error;
17
- }
18
- return void 0;
19
- }
20
12
  isMissingError(error) {
21
13
  if (typeof error !== "object" || error === null) {
22
14
  return false;
@@ -27,9 +19,6 @@ class DatabaseReadLayer {
27
19
  if ("error" in error && error.error === "not_found") {
28
20
  return true;
29
21
  }
30
- if ("error" in error) {
31
- return this.isMissingError(error.error);
32
- }
33
22
  return false;
34
23
  }
35
24
  async read(ids, options, next) {
@@ -38,31 +27,44 @@ class DatabaseReadLayer {
38
27
  }
39
28
  const resultMap = /* @__PURE__ */ new Map();
40
29
  const remainingIds = [];
30
+ let results;
41
31
  try {
42
- const results = await this.database.allDocs({ keys: ids, include_docs: true });
43
- for (const row of results.rows) {
44
- if ("doc" in row && row.doc && this.isChunkDoc(row.doc)) {
45
- const chunk = row.doc;
46
- resultMap.set(chunk._id, chunk);
47
- } else if (!this.isMissingError(row)) {
48
- throw new LiveSyncError(`Failed to read chunk ${row.key}`, {
49
- status: 404,
50
- cause: this.getError(row)
51
- });
52
- } else {
53
- const idFromRow = typeof row.key === "string" ? row.key : void 0;
54
- if (idFromRow) {
55
- remainingIds.push(idFromRow);
56
- }
32
+ const read = () => this.database.allDocs({ keys: ids, include_docs: true });
33
+ results = await (this.readScope ? this.readScope.run(read) : read());
34
+ } catch (error) {
35
+ const localFailure = new ContentReadError({
36
+ documentId: ids[0],
37
+ resources: ["local-database"],
38
+ cause: error
39
+ });
40
+ if (this.readScope?.isClosed) throw localFailure;
41
+ try {
42
+ const fallback = await next(ids);
43
+ if (fallback.every(Boolean)) {
44
+ return fallback;
57
45
  }
46
+ } catch (fallbackError) {
47
+ const resources = fallbackError instanceof ContentReadError ? fallbackError.failure.resources : [];
48
+ throw new ContentReadError({
49
+ documentId: ids[0],
50
+ resources: resources.length === 0 ? [] : [.../* @__PURE__ */ new Set(["local-database", ...resources])],
51
+ cause: new AggregateError([error, fallbackError], "Local and fallback Chunk reads failed")
52
+ });
58
53
  }
59
- } catch (error) {
60
- if (error instanceof LiveSyncError) {
61
- throw error;
54
+ throw localFailure;
55
+ }
56
+ for (const row of results.rows) {
57
+ if ("doc" in row && row.doc && this.isChunkDoc(row.doc)) {
58
+ const chunk = row.doc;
59
+ resultMap.set(chunk._id, chunk);
60
+ } else if (!this.isMissingError(row)) {
61
+ throw new ContentReadError({ documentId: row.key, resources: [], cause: row });
62
+ } else {
63
+ const idFromRow = typeof row.key === "string" ? row.key : void 0;
64
+ if (idFromRow) {
65
+ remainingIds.push(idFromRow);
66
+ }
62
67
  }
63
- Logger(`Database read error!`, LOG_LEVEL_VERBOSE);
64
- Logger(error, LOG_LEVEL_VERBOSE);
65
- return ids.map(() => false);
66
68
  }
67
69
  if (remainingIds.length === 0) {
68
70
  return ids.map((id) => resultMap.get(id) ?? false);
@@ -1,11 +1,21 @@
1
+ import type { LocalDatabaseReadScope } from "../../pouchdb/LocalDatabaseReadScope.js";
1
2
  import type { EntryDoc } from "../../common/models/db.definition.js";
2
3
  import type { DocumentID, EntryLeaf } from "../../common/models/db.type.js";
3
4
  import type { ISettingService } from "../../services/base/IService.js";
4
5
  import type { ChangeManager } from "../ChangeManager.js";
5
- import type { EVENT_CHUNK_FETCHED, EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS } from "../ChunkFetcher.js";
6
+ import type { EVENT_CHUNK_FAILED, EVENT_CHUNK_FETCHED, EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS } from "../ChunkFetcher.js";
6
7
  import type { ActivityCountSource } from "../ChunkDeliveryCoordinator.js";
8
+ import type { ContentReadResource } from "../../interfaces/DatabaseFileAccess.js";
9
+ import type { LogFunction } from "../../services/lib/logUtils.js";
10
+ export type ChunkDeliveryFailure = {
11
+ resources: readonly ContentReadResource[];
12
+ cause: unknown;
13
+ };
7
14
  export type ChunkManagerOptions = {
15
+ /** Host-owned logger; standalone instances default to the global logger. */
16
+ log?: LogFunction;
8
17
  database: PouchDB.Database<EntryDoc>;
18
+ readScope?: LocalDatabaseReadScope;
9
19
  changeManager: ChangeManager<EntryDoc>;
10
20
  settingService: ISettingService;
11
21
  /** Finite replication which may still deliver a requested chunk. */
@@ -36,4 +46,8 @@ export type ChunkManagerEventMap = {
36
46
  [EVENT_MISSING_CHUNK_REMOTE]: DocumentID;
37
47
  [EVENT_MISSING_CHUNKS]: DocumentID[];
38
48
  [EVENT_CHUNK_FETCHED]: EntryLeaf;
49
+ [EVENT_CHUNK_FAILED]: {
50
+ id: DocumentID;
51
+ failure: ChunkDeliveryFailure;
52
+ };
39
53
  };
@@ -1,5 +1,6 @@
1
1
  import type { DocumentID, EntryDoc, EntryLeaf } from "../common/types.js";
2
2
  import type { ChangeManager } from "./ChangeManager.js";
3
+ import { EVENT_CHUNK_FAILED } from "./ChunkFetcher.js";
3
4
  import type { ChunkManagerEventMap, ChunkManagerOptions, ChunkReadOptions, ChunkWriteOptions, WriteResult } from "./LayeredChunkManager/types.js";
4
5
  import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
5
6
  /**
@@ -8,6 +9,7 @@ import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
8
9
  */
9
10
  export declare class LayeredChunkManager {
10
11
  protected options: ChunkManagerOptions;
12
+ private readonly log;
11
13
  protected eventTarget: EventTarget;
12
14
  private cacheLayer;
13
15
  private databaseReadLayer;
@@ -45,6 +47,8 @@ export declare class LayeredChunkManager {
45
47
  protected onChangeHandler: (change: PouchDB.Core.ChangesResponseChange<EntryDoc>) => void;
46
48
  onMissingChunkRemote(id: DocumentID): void;
47
49
  protected onMissingChunkRemoteHandler: (id: DocumentID) => void;
50
+ private onChunkFailed;
51
+ protected onChunkFailedHandler: ({ id, failure }: ChunkManagerEventMap[typeof EVENT_CHUNK_FAILED]) => void;
48
52
  protected concurrentTransactions: number;
49
53
  protected stabilised: Promise<void>;
50
54
  transaction<T>(callback: () => Promise<T>): Promise<T>;
@@ -1,6 +1,11 @@
1
1
  import { LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
2
2
  import { promiseWithResolvers } from "octagonal-wheels/promises";
3
- import { EVENT_MISSING_CHUNK_REMOTE, EVENT_MISSING_CHUNKS, EVENT_CHUNK_FETCHED } from "./ChunkFetcher.js";
3
+ import {
4
+ EVENT_MISSING_CHUNK_REMOTE,
5
+ EVENT_MISSING_CHUNKS,
6
+ EVENT_CHUNK_FETCHED,
7
+ EVENT_CHUNK_FAILED
8
+ } from "./ChunkFetcher.js";
4
9
  import { DatabaseReadLayer } from "./LayeredChunkManager/DatabaseReadLayer.js";
5
10
  import { CacheLayer } from "./LayeredChunkManager/CacheLayer.js";
6
11
  import { ArrivalWaitLayer } from "./LayeredChunkManager/ArrivalWaitLayer.js";
@@ -9,6 +14,7 @@ import { unique } from "octagonal-wheels/collection";
9
14
  import { ChunkDeliveryCoordinator } from "./ChunkDeliveryCoordinator.js";
10
15
  class LayeredChunkManager {
11
16
  options;
17
+ log;
12
18
  eventTarget = new EventTarget();
13
19
  // Middleware layers
14
20
  cacheLayer;
@@ -46,15 +52,16 @@ class LayeredChunkManager {
46
52
  // initialisation promise to ensure the manager is ready before processing transactions
47
53
  initialised = Promise.resolve();
48
54
  async _initialise() {
49
- Logger("ChunkManager initialised", LOG_LEVEL_VERBOSE);
55
+ this.log("ChunkManager initialised", LOG_LEVEL_VERBOSE);
50
56
  return await Promise.resolve();
51
57
  }
52
58
  constructor(options) {
53
59
  this.options = options;
60
+ this.log = options.log ?? Logger;
54
61
  const settings = options.settingService.currentSettings();
55
62
  const maxCacheSize = settings.hashCacheMaxCount * 10;
56
63
  this.cacheLayer = new CacheLayer(maxCacheSize);
57
- this.databaseReadLayer = new DatabaseReadLayer(this.database);
64
+ this.databaseReadLayer = new DatabaseReadLayer(this.database, options.readScope);
58
65
  this.deliveryCoordinator = new ChunkDeliveryCoordinator(options.finiteReplicationActivity);
59
66
  this.arrivalWaitLayer = new ArrivalWaitLayer(
60
67
  (eventName, data) => {
@@ -67,7 +74,8 @@ class LayeredChunkManager {
67
74
  [...ids],
68
75
  { preventRemoteRequest: true, skipCache: true, waitForDelivery: false },
69
76
  (remaining) => Promise.resolve(remaining.map(() => false))
70
- )
77
+ ),
78
+ this.log
71
79
  );
72
80
  this.readLayers = [this.cacheLayer, this.databaseReadLayer, this.arrivalWaitLayer];
73
81
  this.writeLayers = [
@@ -78,6 +86,7 @@ class LayeredChunkManager {
78
86
  this.offChangeHandler = this.changeManager.addCallback(this.onChangeHandler);
79
87
  this.addListener(EVENT_CHUNK_FETCHED, this.onChunkArrivedHandler, { signal: this.abort.signal });
80
88
  this.addListener(EVENT_MISSING_CHUNK_REMOTE, this.onMissingChunkRemoteHandler, { signal: this.abort.signal });
89
+ this.addListener(EVENT_CHUNK_FAILED, this.onChunkFailedHandler, { signal: this.abort.signal });
81
90
  this.initialised = this._initialise();
82
91
  }
83
92
  destroy() {
@@ -202,6 +211,10 @@ class LayeredChunkManager {
202
211
  this.arrivalWaitLayer.onMissingChunk(id);
203
212
  }
204
213
  onMissingChunkRemoteHandler = this.onMissingChunkRemote.bind(this);
214
+ onChunkFailed({ id, failure }) {
215
+ this.arrivalWaitLayer.onChunkFailed(id, failure);
216
+ }
217
+ onChunkFailedHandler = this.onChunkFailed.bind(this);
205
218
  // Transaction management
206
219
  concurrentTransactions = 0;
207
220
  stabilised = Promise.resolve();
@@ -215,10 +228,10 @@ class LayeredChunkManager {
215
228
  } finally {
216
229
  this.concurrentTransactions--;
217
230
  if (this.concurrentTransactions === 0) {
218
- Logger(`All transactions completed. Performing stabilisation.`, LOG_LEVEL_VERBOSE);
231
+ this.log(`All transactions completed. Performing stabilisation.`, LOG_LEVEL_VERBOSE);
219
232
  await this._stabilise();
220
233
  } else {
221
- Logger(`Transaction completed. Remaining: ${this.concurrentTransactions}`, LOG_LEVEL_VERBOSE);
234
+ this.log(`Transaction completed. Remaining: ${this.concurrentTransactions}`, LOG_LEVEL_VERBOSE);
222
235
  }
223
236
  }
224
237
  }
@@ -1,3 +1,4 @@
1
+ import type { LocalDatabaseReadScope } from "../pouchdb/LocalDatabaseReadScope.js";
1
2
  import { type EntryDoc } from "../common/types.js";
2
3
  import { ContentSplitter } from "../ContentSplitter/ContentSplitters.js";
3
4
  import { ChangeManager } from "./ChangeManager.js";
@@ -11,6 +12,7 @@ import type { IAPIService, IDatabaseService, IPathService, IReplicatorService, I
11
12
  import { type LogFunction } from "../services/lib/logUtils.js";
12
13
  export interface LiveSyncManagersOptions<TSettingService extends ISettingService = ISettingService> {
13
14
  database: PouchDB.Database<EntryDoc>;
15
+ readScope?: LocalDatabaseReadScope;
14
16
  databaseService: IDatabaseService;
15
17
  settingService: TSettingService;
16
18
  pathService: IPathService;
@@ -59,6 +59,7 @@ class LiveSyncManagers {
59
59
  getManagerMembers() {
60
60
  this.log("Creating LiveSync Managers...");
61
61
  const database = this.options.database;
62
+ const readScope = this.options.readScope;
62
63
  const changeManager = new ChangeManager({
63
64
  database
64
65
  });
@@ -69,19 +70,24 @@ class LiveSyncManagers {
69
70
  settingService: this.options.settingService
70
71
  });
71
72
  const chunkManager = new ChunkManager({
73
+ log: createInstanceLogFunction("ChunkManager", this._APIService),
72
74
  changeManager,
73
75
  database,
76
+ readScope,
74
77
  settingService: this.options.settingService,
75
78
  finiteReplicationActivity: this.options.replicatorService.finiteReplicationActivityCount
76
79
  });
77
80
  const chunkFetcher = new ChunkFetcher({
81
+ log: createInstanceLogFunction("ChunkFetcher", this._APIService),
78
82
  chunkManager,
79
83
  source: this.options.chunkFetchSource,
80
84
  replicatorService: this.options.replicatorService,
81
85
  settingService: this.options.settingService
82
86
  });
83
87
  const entryManager = new EntryManager({
88
+ log: createInstanceLogFunction("EntryManager", this._APIService),
84
89
  database,
90
+ readScope,
85
91
  hashManager,
86
92
  chunkManager,
87
93
  splitter,
@@ -57,6 +57,9 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
57
57
  protected _waitingMap: Map<string, WaitInfo>;
58
58
  protected processingCount: number;
59
59
  private readonly eventState;
60
+ private dispatchPaused;
61
+ private dispatchResumeSignal;
62
+ private readonly activeDispatches;
60
63
  private readonly buffer;
61
64
  private readonly notifications;
62
65
  private readonly log;
@@ -156,6 +159,18 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
156
159
  * @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
157
160
  */
158
161
  waitForIdle(): Promise<void>;
162
+ /**
163
+ * Pause new file-handler dispatch and wait for dispatches already in progress.
164
+ * @returns A promise fulfilled after processing that had started at the call settles; queued and not-yet-started work is not awaited.
165
+ * @remarks Event admission, buffering, and snapshotting continue while paused. Repeated calls are safe.
166
+ */
167
+ pauseDispatch(): Promise<void>;
168
+ /**
169
+ * Resume file-handler dispatch after a temporary pause.
170
+ * @returns Nothing; waiting dispatches are released and the existing queue scheduler is asked to continue.
171
+ * @remarks Repeated calls are safe.
172
+ */
173
+ resumeDispatch(): void;
159
174
  /**
160
175
  * Stop accepting events, flush current work, and persist the remaining snapshot.
161
176
  * @returns A promise fulfilled after the final snapshot write; a flush failure is logged, while a final snapshot failure rejects it.
@@ -247,6 +262,13 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
247
262
  * @returns A promise fulfilled on successful completion; attempt failures are recorded and rethrown.
248
263
  */
249
264
  private processOperation;
265
+ /**
266
+ * Hold a file-handler request while dispatch is paused and track requests which have started.
267
+ * @param event - The event passed to the host processing hook after the pause is released.
268
+ * @returns A promise fulfilled when the host processing hook completes.
269
+ * @remarks The pause check and active registration happen synchronously together, preventing a request from starting after a pause.
270
+ */
271
+ private dispatchFileEvent;
250
272
  /**
251
273
  * Retain an event and await its current processing attempt.
252
274
  * @param event - The already selected event to process.
@@ -5,6 +5,7 @@ import {
5
5
  } from "../common/types.js";
6
6
  import { fireAndForget, throttle } from "../common/utils.js";
7
7
  import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
8
+ import { promiseWithResolvers } from "octagonal-wheels/promises";
8
9
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
9
10
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
10
11
  import { admitStorageEvents } from "./StorageEventManager/admission.js";
@@ -52,6 +53,9 @@ class StorageEventManagerBase extends StorageEventManager {
52
53
  _waitingMap = /* @__PURE__ */ new Map();
53
54
  processingCount = 0;
54
55
  eventState = createStorageEventState();
56
+ dispatchPaused = false;
57
+ dispatchResumeSignal;
58
+ activeDispatches = /* @__PURE__ */ new Set();
55
59
  buffer = {
56
60
  read: () => this.bufferedQueuedItems,
57
61
  replace: (events) => {
@@ -125,7 +129,7 @@ class StorageEventManagerBase extends StorageEventManager {
125
129
  takeSnapshot: this.queue.takeSnapshot,
126
130
  completeSnapshot: (completion) => this.persistSnapshot(completion),
127
131
  semaphore: () => this.concurrentProcessing,
128
- requestProcessQueue: (event) => this.requestProcessQueue(event),
132
+ requestProcessQueue: (event) => this.dispatchFileEvent(event),
129
133
  cancelWaiting: (event) => {
130
134
  const path = event.args.file.path;
131
135
  if (this._waitingMap.get(path)?.event === event) this._cancelWaiting(path);
@@ -274,6 +278,29 @@ class StorageEventManagerBase extends StorageEventManager {
274
278
  async waitForIdle() {
275
279
  await flushStorageEvents(this.eventState, this.queue);
276
280
  }
281
+ /**
282
+ * Pause new file-handler dispatch and wait for dispatches already in progress.
283
+ * @returns A promise fulfilled after processing that had started at the call settles; queued and not-yet-started work is not awaited.
284
+ * @remarks Event admission, buffering, and snapshotting continue while paused. Repeated calls are safe.
285
+ */
286
+ async pauseDispatch() {
287
+ this.dispatchPaused = true;
288
+ await Promise.all([...this.activeDispatches]);
289
+ }
290
+ /**
291
+ * Resume file-handler dispatch after a temporary pause.
292
+ * @returns Nothing; waiting dispatches are released and the existing queue scheduler is asked to continue.
293
+ * @remarks Repeated calls are safe.
294
+ */
295
+ resumeDispatch() {
296
+ if (!this.dispatchPaused) {
297
+ return;
298
+ }
299
+ this.dispatchPaused = false;
300
+ this.dispatchResumeSignal?.resolve();
301
+ this.dispatchResumeSignal = void 0;
302
+ fireAndForget(() => this.runQueuedEvents().catch((error) => this.reportOperationFailure(error)));
303
+ }
277
304
  /**
278
305
  * Stop accepting events, flush current work, and persist the remaining snapshot.
279
306
  * @returns A promise fulfilled after the final snapshot write; a flush failure is logged, while a final snapshot failure rejects it.
@@ -402,6 +429,26 @@ class StorageEventManagerBase extends StorageEventManager {
402
429
  async processOperation(operation, attempt) {
403
430
  await processStorageEventAttempt(this.eventState, operation, attempt, this.attempts);
404
431
  }
432
+ /**
433
+ * Hold a file-handler request while dispatch is paused and track requests which have started.
434
+ * @param event - The event passed to the host processing hook after the pause is released.
435
+ * @returns A promise fulfilled when the host processing hook completes.
436
+ * @remarks The pause check and active registration happen synchronously together, preventing a request from starting after a pause.
437
+ */
438
+ async dispatchFileEvent(event) {
439
+ while (this.dispatchPaused) {
440
+ this.dispatchResumeSignal ??= promiseWithResolvers();
441
+ await this.dispatchResumeSignal.promise;
442
+ }
443
+ const activeDispatch = promiseWithResolvers();
444
+ this.activeDispatches.add(activeDispatch.promise);
445
+ try {
446
+ await this.requestProcessQueue(event);
447
+ } finally {
448
+ this.activeDispatches.delete(activeDispatch.promise);
449
+ activeDispatch.resolve();
450
+ }
451
+ }
405
452
  /**
406
453
  * Retain an event and await its current processing attempt.
407
454
  * @param event - The already selected event to process.
@@ -36,6 +36,8 @@ export type GeneratedChunk = {
36
36
  };
37
37
  /** Optional host IO bound afresh to each prepared database instance. */
38
38
  export interface LiveSyncLocalDBRuntimeOptions {
39
+ /** Physical database selection captured by the owning service before asynchronous retirement. */
40
+ createPouchDBInstance?: LiveSyncLocalDBEnv["services"]["database"]["createPouchDBInstance"];
39
41
  createChunkFetchSource?: (database: PouchDB.Database<EntryDoc>) => ChunkFetchSource;
40
42
  }
41
43
  export declare class LiveSyncLocalDB {
@@ -43,8 +45,22 @@ export declare class LiveSyncLocalDB {
43
45
  auth: Credential;
44
46
  dbname: string;
45
47
  settings: RemoteDBSettings;
48
+ /**
49
+ * The raw PouchDB handle for replication, changes feeds, and maintenance.
50
+ *
51
+ * Direct reads bypass this owner's caller-wait retirement. Use
52
+ * {@link readDBEntry} for file contents, {@link getRaw} or {@link allDocsRaw}
53
+ * for raw documents, and {@link readFromDatabase} for other read-only Pouch
54
+ * operations. These entry points end caller waits when the owner retires;
55
+ * they do not cancel native I/O or automatically retry a failed operation.
56
+ *
57
+ * Integrations which require this handle must own their operation's
58
+ * retirement and completion. Keep writes and mixed read/write workflows
59
+ * outside {@link readFromDatabase}; started writes must actually finish.
60
+ */
46
61
  localDatabase: PouchDB.Database<EntryDoc>;
47
62
  _log: LogFunction;
63
+ private readScope;
48
64
  private _managers?;
49
65
  get managers(): LiveSyncManagers;
50
66
  isReady: boolean;
@@ -62,6 +78,18 @@ export declare class LiveSyncLocalDB {
62
78
  /** Notify dependent services at most once for each physical database lifecycle. */
63
79
  private notifyDatabaseUnload;
64
80
  onunload(): void;
81
+ /** End caller read waits before lifecycle hooks drain their owners; native IO is not cancelled. */
82
+ stopReads(): void;
83
+ /**
84
+ * Run a read on the captured Pouch and end its caller wait when this owner retires.
85
+ *
86
+ * Use {@link getRaw} or {@link allDocsRaw} for document reads with known IDs.
87
+ * This callback also supports other read-only operations, including inspection
88
+ * of unvalidated stored IDs. It can continue after the caller wait rejects,
89
+ * so it must not perform writes or change application state after a read.
90
+ * No connection-health conclusion, recovery request, or retry is implied.
91
+ */
92
+ readFromDatabase<T>(operation: (database: PouchDB.Database<EntryDoc>) => Promise<T>): Promise<T>;
65
93
  close(): Promise<void>;
66
94
  private closeActiveReplication;
67
95
  private teardownDatabaseDependencies;
@@ -195,15 +223,19 @@ export declare class LiveSyncLocalDB {
195
223
  datatype: import("../common/types.js").EntryTypeNotes;
196
224
  } & PouchDB.Core.AllDocsMeta & PouchDB.Core.IdMeta & PouchDB.Core.RevisionIdMeta), void, unknown>;
197
225
  removeRevision(docId: DocumentID, revision: string): Promise<boolean>;
226
+ /** Read a raw document by its known ID, with caller-wait retirement owned by this database. */
198
227
  getRaw<T extends EntryDoc>(docId: DocumentID, options?: PouchDB.Core.GetOptions): Promise<T & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta>;
199
228
  removeRaw(docId: DocumentID, revision: string, options?: PouchDB.Core.Options): Promise<PouchDB.Core.Response>;
200
229
  putRaw<T extends EntryDoc>(doc: T, options?: PouchDB.Core.PutOptions): Promise<PouchDB.Core.Response>;
230
+ /** Read a raw document listing with caller-wait retirement owned by this database. */
201
231
  allDocsRaw<T extends EntryDoc | DatabaseEntry>(options?: PouchDB.Core.AllDocsWithKeyOptions | PouchDB.Core.AllDocsWithKeysOptions | PouchDB.Core.AllDocsWithinRangeOptions | PouchDB.Core.AllDocsOptions): Promise<PouchDB.Core.AllDocsResponse<T>>;
202
232
  bulkDocsRaw<T extends EntryDoc>(docs: Array<PouchDB.Core.PutDocument<T>>, options?: PouchDB.Core.BulkDocsOptions): Promise<Array<PouchDB.Core.Response | PouchDB.Core.Error>>;
203
233
  isTargetFile(filenameSrc: string): boolean;
204
234
  getDBEntryMeta(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
205
235
  getDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
236
+ readDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
206
237
  getDBEntryFromMeta(meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
238
+ readDBEntryFromMeta(meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
207
239
  deleteDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean>;
208
240
  storeDeletionAtRevision(path: FilePathWithPrefix | FilePath, baseRevision: string): Promise<false | PouchDB.Core.Response>;
209
241
  putDBEntry(note: SavingEntry, onlyChunks?: boolean, conflictBaseRev?: string): Promise<false | PouchDB.Core.Response>;