@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,8 +1,10 @@
1
+ import { ContentReadError } from "../common/LSError.js";
1
2
  import { getUnencryptedContentRejectionMessage } from "../replication/unencryptedContentMessages.js";
2
3
  import {
3
4
  getUnencryptedContentRejection,
4
5
  isUnencryptedContentRejectedError
5
6
  } from "../replication/UnencryptedContentRejectedError.js";
7
+ import { withScope } from "octagonal-wheels/resource/scope";
6
8
  import { delay, promiseWithResolvers } from "octagonal-wheels/promises";
7
9
  import { unique } from "octagonal-wheels/collection";
8
10
  import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE, Logger } from "../common/logger.js";
@@ -18,12 +20,14 @@ import {
18
20
  const EVENT_MISSING_CHUNKS = "missingChunks";
19
21
  const EVENT_MISSING_CHUNK_REMOTE = "missingChunkRemote";
20
22
  const EVENT_CHUNK_FETCHED = "chunkFetched";
23
+ const EVENT_CHUNK_FAILED = "chunkFailed";
21
24
  const BATCH_SIZE = 100;
22
25
  function canFetchRemoteChunks(replicator) {
23
26
  return "fetchRemoteChunks" in replicator && typeof replicator.fetchRemoteChunks === "function";
24
27
  }
25
28
  class ChunkFetcher {
26
29
  options;
30
+ log;
27
31
  get chunkManager() {
28
32
  return this.options.chunkManager;
29
33
  }
@@ -48,6 +52,7 @@ class ChunkFetcher {
48
52
  abort = new AbortController();
49
53
  constructor(options) {
50
54
  this.options = options;
55
+ this.log = options.log ?? Logger;
51
56
  this.finiteActivityWasActive = this.chunkManager.deliveryCoordinator.isFiniteReplicationActive();
52
57
  this.stopObservingDelivery = this.chunkManager.deliveryCoordinator.onChanged(() => {
53
58
  const active = this.chunkManager.deliveryCoordinator.isFiniteReplicationActive();
@@ -144,8 +149,8 @@ class ChunkFetcher {
144
149
  pending.resolveActivityBoundary(false);
145
150
  this.removePendingDelivery(pending, abandonedIds);
146
151
  claim.release();
147
- Logger("The chunk-delivery activity runner rejected before the claim settled.", LOG_LEVEL_VERBOSE);
148
- Logger(error, LOG_LEVEL_VERBOSE);
152
+ this.log("The chunk-delivery activity runner rejected before the claim settled.", LOG_LEVEL_VERBOSE);
153
+ this.log(error, LOG_LEVEL_VERBOSE);
149
154
  });
150
155
  return unclaimedIds;
151
156
  }
@@ -183,7 +188,7 @@ class ChunkFetcher {
183
188
  onClaimStalled(pending, stalledIds) {
184
189
  pending.resolveActivityBoundary(false);
185
190
  this.removePendingDelivery(pending, stalledIds);
186
- Logger(`Chunk delivery stalled for the following IDs: ${stalledIds.join(", ")}`, LOG_LEVEL_VERBOSE);
191
+ this.log(`Chunk delivery stalled for the following IDs: ${stalledIds.join(", ")}`, LOG_LEVEL_VERBOSE);
187
192
  }
188
193
  settleClaim(id, pending) {
189
194
  if (!pending || this.pendingClaims.get(id) !== pending) return;
@@ -215,24 +220,34 @@ class ChunkFetcher {
215
220
  this.touchClaims(ids, claims);
216
221
  while (!this.destroyed) {
217
222
  const activeIds = this.getActiveClaimIds(ids, claims);
218
- if (activeIds.length === 0) return [];
223
+ if (activeIds.length === 0) {
224
+ return [];
225
+ }
219
226
  if (localCheckCompletionVersion !== this.finiteCompletionVersion) {
220
227
  localCheckCompletionVersion = this.finiteCompletionVersion;
221
228
  await this.resolveLocallyAvailableRetries(claims);
222
229
  continue;
223
230
  }
224
- const now = Date.now();
225
- const timeToWait = this.previousRequestTime + this.interval - now;
226
- if (timeToWait > 0) {
227
- await delay(timeToWait);
231
+ const waitMs = this.reserveRequestInterval();
232
+ if (waitMs > 0) {
233
+ await delay(waitMs);
228
234
  continue;
229
235
  }
230
- this.previousRequestTime = now;
231
236
  this.touchClaims(activeIds, claims);
232
237
  return activeIds;
233
238
  }
234
239
  return [];
235
240
  }
241
+ /** Return the remaining delay, or reserve the request start synchronously. */
242
+ reserveRequestInterval() {
243
+ const now = Date.now();
244
+ const waitMs = this.previousRequestTime + this.interval - now;
245
+ if (waitMs > 0) {
246
+ return waitMs;
247
+ }
248
+ this.previousRequestTime = now;
249
+ return 0;
250
+ }
236
251
  async resolveLocallyAvailableRetries(claims) {
237
252
  const retryIds = this.getActiveClaimIds([...claims.keys()], claims).filter(
238
253
  (id) => claims.get(id).missingResponses > 0
@@ -251,20 +266,20 @@ class ChunkFetcher {
251
266
  }
252
267
  logFetchedChunks(requestedIds, { chunks, invalidChunks }) {
253
268
  if (invalidChunks.length > 0) {
254
- Logger(
269
+ this.log(
255
270
  `Some fetched chunks are invalid and will be ignored: (${invalidChunks.length} / ${chunks.length + invalidChunks.length}).`,
256
271
  LOG_LEVEL_VERBOSE
257
272
  );
258
273
  for (const chunk of invalidChunks) {
259
274
  const id = typeof chunk === "object" && chunk !== null && "_id" in chunk && typeof chunk._id === "string" ? chunk._id : void 0;
260
- Logger(
275
+ this.log(
261
276
  id === void 0 ? "Invalid chunk without a string document ID." : `Invalid chunk document: ${JSON.stringify(id)}`,
262
277
  LOG_LEVEL_VERBOSE
263
278
  );
264
279
  }
265
280
  }
266
281
  if (chunks.length === 0) {
267
- Logger(`No valid chunks were found for the following IDs: ${requestedIds.join(", ")}`);
282
+ this.log(`No valid chunks were found for the following IDs: ${requestedIds.join(", ")}`);
268
283
  }
269
284
  }
270
285
  applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion) {
@@ -284,7 +299,7 @@ class ChunkFetcher {
284
299
  pending.inFlight = false;
285
300
  pending.nextRequestAt = Date.now() + action.delayMs;
286
301
  this.queue.push(chunkID);
287
- Logger(
302
+ this.log(
288
303
  `Remote chunk is not available yet; retrying ${chunkID} in ${action.delayMs} ms.`,
289
304
  LOG_LEVEL_VERBOSE
290
305
  );
@@ -316,124 +331,187 @@ class ChunkFetcher {
316
331
  }
317
332
  let requestIDs = [];
318
333
  const requestClaims = /* @__PURE__ */ new Map();
319
- try {
334
+ await withScope(requestClaims, async (scope) => {
320
335
  this.currentProcessing++;
321
- requestIDs = unique(this.queue.filter((id) => this.isReady(id))).slice(0, BATCH_SIZE);
322
- const selectedIds = new Set(requestIDs);
323
- this.queue = this.queue.filter((id) => !selectedIds.has(id));
324
- this.ensureClaims(requestIDs);
325
- for (const id of requestIDs) {
326
- const pending = this.pendingClaims.get(id);
327
- if (pending) {
328
- pending.inFlight = true;
329
- requestClaims.set(id, pending);
336
+ scope.defer(() => this.cleanupRequestBatch(requestClaims));
337
+ try {
338
+ requestIDs = unique(this.queue.filter((id) => this.isReady(id))).slice(0, BATCH_SIZE);
339
+ this.admitRequestBatch(requestIDs, requestClaims);
340
+ requestIDs = await this.waitForActivityBoundary(requestClaims);
341
+ if (requestIDs.length === 0) {
342
+ return;
330
343
  }
331
- }
332
- this.scheduleRequest();
333
- requestIDs = await this.waitForActivityBoundary(requestClaims);
334
- if (requestIDs.length === 0) return;
335
- const localCheckCompletionVersion = this.finiteCompletionVersion;
336
- await this.resolveLocallyAvailableRetries(requestClaims);
337
- let pendingIDs = await this.waitBeforeRemoteRequest(requestIDs, requestClaims, localCheckCompletionVersion);
338
- if (pendingIDs.length === 0) return;
339
- const requestCompletionVersion = this.finiteCompletionVersion;
340
- let fetched;
341
- if (this.options.source) {
342
- fetched = await this.options.source.fetchChunks(pendingIDs);
343
- } else {
344
- const replicator = this.options.replicatorService.getActiveReplicator();
345
- if (!replicator) {
346
- Logger("No active replicator was found to request missing chunks.");
344
+ const localCheckCompletionVersion = this.finiteCompletionVersion;
345
+ await this.resolveLocallyAvailableRetries(requestClaims);
346
+ const pendingIDs = await this.waitBeforeRemoteRequest(
347
+ requestIDs,
348
+ requestClaims,
349
+ localCheckCompletionVersion
350
+ );
351
+ if (pendingIDs.length === 0) {
347
352
  return;
348
353
  }
349
- if (!canFetchRemoteChunks(replicator)) {
350
- Logger("The active replicator does not support fetching individual remote chunks.");
351
- for (const chunkID of pendingIDs) {
352
- this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
353
- }
354
+ const requestCompletionVersion = this.finiteCompletionVersion;
355
+ const fetchResult = this.fetchRemoteChunks(pendingIDs);
356
+ if (!fetchResult) {
354
357
  return;
355
358
  }
356
- fetched = await replicator.fetchRemoteChunks(pendingIDs, false);
359
+ const fetched = await fetchResult;
360
+ await this.acceptFetchedChunks(pendingIDs, requestClaims, requestCompletionVersion, fetched);
361
+ } catch (error) {
362
+ this.publishRequestFailure(requestIDs, requestClaims, error);
357
363
  }
358
- pendingIDs = this.getActiveClaimIds(pendingIDs, requestClaims);
359
- this.touchClaims(pendingIDs, requestClaims);
360
- if (!fetched) {
361
- Logger(`No chunks were found for the following IDs: ${pendingIDs.join(", ")}`);
362
- for (const chunkID of pendingIDs) {
363
- this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
364
- }
365
- return;
364
+ });
365
+ }
366
+ admitRequestBatch(requestIDs, requestClaims) {
367
+ const selectedIds = new Set(requestIDs);
368
+ this.queue = this.queue.filter((id) => !selectedIds.has(id));
369
+ this.ensureClaims(requestIDs);
370
+ for (const id of requestIDs) {
371
+ const pending = this.pendingClaims.get(id);
372
+ if (pending) {
373
+ pending.inFlight = true;
374
+ requestClaims.set(id, pending);
366
375
  }
367
- const classification = classifyFetchedChunks(pendingIDs, fetched);
368
- this.logFetchedChunks(pendingIDs, classification);
369
- const { chunks, missingIds, invalidIds } = classification;
370
- try {
371
- if (chunks.length > 0 && this.options.source) {
372
- await this.options.source.storeChunks(chunks);
373
- } else if (chunks.length > 0) {
374
- Logger(`Writing fetched chunks (${chunks.length}) to the database...`);
375
- const result = await this.chunkManager.write(
376
- chunks,
377
- {
378
- skipCache: true,
379
- force: true
380
- // Force writing to ensure the chunks with existing _rev.
381
- },
382
- "ChunkFetcher"
383
- );
384
- this.touchClaims(pendingIDs, requestClaims);
385
- if (result.result === true) {
386
- Logger(`Fetched chunks were stored successfully: ${chunks.length}`, LOG_LEVEL_VERBOSE);
387
- } else {
388
- Logger(
389
- `Fetched chunks could not be stored: ${chunks.map((chunk) => chunk._id).join(", ")}`,
390
- LOG_LEVEL_VERBOSE
391
- );
392
- }
393
- }
394
- } catch (error) {
395
- Logger(`An error occurred while storing fetched chunks!`, LOG_LEVEL_VERBOSE);
396
- Logger(error, LOG_LEVEL_VERBOSE);
397
- } finally {
398
- for (const chunk of chunks) {
399
- this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);
400
- this.settleClaim(chunk._id, requestClaims.get(chunk._id));
401
- }
402
- for (const invalidID of this.getActiveClaimIds(invalidIds, requestClaims)) {
403
- this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, invalidID);
404
- this.settleClaim(invalidID, requestClaims.get(invalidID));
405
- }
376
+ }
377
+ this.scheduleRequest();
378
+ }
379
+ cleanupRequestBatch(requestClaims) {
380
+ for (const [id, pending] of requestClaims) {
381
+ if (pending.inFlight) {
382
+ this.settleClaim(id, pending);
406
383
  }
407
- this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);
384
+ }
385
+ this.currentProcessing--;
386
+ this.previousRequestTime = Date.now();
387
+ this.scheduleRequest();
388
+ }
389
+ fetchRemoteChunks(ids) {
390
+ const source = this.options.source;
391
+ if (source) {
392
+ return this.fetchWithRemoteError(ids, () => source.fetchChunks(ids));
393
+ }
394
+ const replicator = this.options.replicatorService.getActiveReplicator();
395
+ if (!replicator) {
396
+ this.log("No active replicator was found to request missing chunks.");
397
+ return void 0;
398
+ }
399
+ if (!canFetchRemoteChunks(replicator)) {
400
+ this.log("The active replicator does not support fetching individual remote chunks.");
401
+ this.publishUnsupportedReplicatorResult(ids);
402
+ return void 0;
403
+ }
404
+ return this.fetchWithRemoteError(ids, () => replicator.fetchRemoteChunks(ids, false));
405
+ }
406
+ async fetchWithRemoteError(ids, fetch) {
407
+ try {
408
+ return await fetch();
408
409
  } catch (error) {
409
410
  if (isUnencryptedContentRejectedError(error)) {
410
- Logger(
411
- getUnencryptedContentRejectionMessage("on-demand"),
412
- LOG_LEVEL_NOTICE,
413
- "unencrypted-content-rejected"
414
- );
415
- const rejection = getUnencryptedContentRejection(error);
416
- const identifiers = rejection ? [rejection.documentId] : requestIDs;
417
- Logger(
418
- `On-demand retrieval rejected unencrypted content: ${identifiers.join(", ")}`,
419
- LOG_LEVEL_VERBOSE
420
- );
421
- } else {
422
- Logger("An error occurred while fetching remote chunks.", LOG_LEVEL_VERBOSE);
423
- Logger(error, LOG_LEVEL_VERBOSE);
411
+ throw error;
412
+ }
413
+ throw new ContentReadError({ documentId: ids[0], resources: ["remote"], cause: error });
414
+ }
415
+ }
416
+ async acceptFetchedChunks(requestedIds, requestClaims, requestCompletionVersion, fetched) {
417
+ const activeIds = this.getActiveClaimIds(requestedIds, requestClaims);
418
+ this.touchClaims(activeIds, requestClaims);
419
+ if (!fetched) {
420
+ this.log(`No chunks were found for the following IDs: ${activeIds.join(", ")}`);
421
+ for (const chunkID of activeIds) {
422
+ this.chunkManager.emitEvent(EVENT_CHUNK_FAILED, {
423
+ id: chunkID,
424
+ failure: { resources: ["remote"], cause: false }
425
+ });
426
+ }
427
+ return;
428
+ }
429
+ const classification = classifyFetchedChunks(activeIds, fetched);
430
+ this.logFetchedChunks(activeIds, classification);
431
+ const { chunks, missingIds, invalidIds } = classification;
432
+ try {
433
+ if (chunks.length > 0) {
434
+ await this.storeFetchedChunks(chunks, activeIds, requestClaims);
424
435
  }
425
436
  } finally {
426
- for (const [id, pending] of requestClaims) {
427
- if (pending.inFlight) this.settleClaim(id, pending);
437
+ this.publishAcceptedChunks(chunks, invalidIds, requestClaims);
438
+ }
439
+ this.applyMissingChunkResults(missingIds, requestClaims, requestCompletionVersion);
440
+ }
441
+ async storeFetchedChunks(chunks, requestedIds, requestClaims) {
442
+ try {
443
+ if (this.options.source) {
444
+ await this.options.source.storeChunks(chunks);
445
+ } else {
446
+ this.log(`Writing fetched chunks (${chunks.length}) to the database...`);
447
+ const result = await this.chunkManager.write(
448
+ chunks,
449
+ {
450
+ skipCache: true,
451
+ force: true
452
+ // Force writing to ensure the chunks with existing _rev.
453
+ },
454
+ "ChunkFetcher"
455
+ );
456
+ this.touchClaims(requestedIds, requestClaims);
457
+ if (result.result === true) {
458
+ this.log(`Fetched chunks were stored successfully: ${chunks.length}`, LOG_LEVEL_VERBOSE);
459
+ } else {
460
+ this.log(
461
+ `Fetched chunks could not be stored: ${chunks.map((chunk) => chunk._id).join(", ")}`,
462
+ LOG_LEVEL_VERBOSE
463
+ );
464
+ }
428
465
  }
429
- this.currentProcessing--;
430
- this.previousRequestTime = Date.now();
431
- this.scheduleRequest();
466
+ } catch (error) {
467
+ this.log(`An error occurred while storing fetched chunks!`, LOG_LEVEL_VERBOSE);
468
+ this.log(error, LOG_LEVEL_VERBOSE);
469
+ }
470
+ }
471
+ publishAcceptedChunks(chunks, invalidIds, requestClaims) {
472
+ for (const chunk of chunks) {
473
+ this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED, chunk);
474
+ this.settleClaim(chunk._id, requestClaims.get(chunk._id));
475
+ }
476
+ for (const invalidID of this.getActiveClaimIds(invalidIds, requestClaims)) {
477
+ this.chunkManager.emitEvent(EVENT_CHUNK_FAILED, {
478
+ id: invalidID,
479
+ failure: { resources: [], cause: new Error("Invalid remote Chunk") }
480
+ });
481
+ this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, invalidID);
482
+ this.settleClaim(invalidID, requestClaims.get(invalidID));
483
+ }
484
+ }
485
+ publishUnsupportedReplicatorResult(requestedIds) {
486
+ for (const chunkID of requestedIds) {
487
+ this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE, chunkID);
488
+ }
489
+ }
490
+ publishRequestFailure(requestIDs, requestClaims, error) {
491
+ for (const id of this.getActiveClaimIds(requestIDs, requestClaims)) {
492
+ this.chunkManager.emitEvent(EVENT_CHUNK_FAILED, {
493
+ id,
494
+ failure: error instanceof ContentReadError ? { resources: error.failure.resources, cause: error.failure.cause } : { resources: [], cause: error }
495
+ });
496
+ }
497
+ if (isUnencryptedContentRejectedError(error)) {
498
+ this.log(
499
+ getUnencryptedContentRejectionMessage("on-demand"),
500
+ LOG_LEVEL_NOTICE,
501
+ "unencrypted-content-rejected"
502
+ );
503
+ const rejection = getUnencryptedContentRejection(error);
504
+ const identifiers = rejection ? [rejection.documentId] : requestIDs;
505
+ this.log(`On-demand retrieval rejected unencrypted content: ${identifiers.join(", ")}`, LOG_LEVEL_VERBOSE);
506
+ } else {
507
+ this.log("An error occurred while fetching remote chunks.", LOG_LEVEL_VERBOSE);
508
+ this.log(error, LOG_LEVEL_VERBOSE);
432
509
  }
433
510
  }
434
511
  }
435
512
  export {
436
513
  ChunkFetcher,
514
+ EVENT_CHUNK_FAILED,
437
515
  EVENT_CHUNK_FETCHED,
438
516
  EVENT_MISSING_CHUNKS,
439
517
  EVENT_MISSING_CHUNK_REMOTE
@@ -1,21 +1,28 @@
1
+ import type { LocalDatabaseReadScope } from "../../pouchdb/LocalDatabaseReadScope.js";
1
2
  import { type FilePathWithPrefix, type FilePath, type LoadedEntry, type EntryDoc, type SavingEntry, type MetaEntry } from "../../common/types.js";
2
3
  import type { ChunkManager } from "../ChunkManager.js";
3
4
  import type { ContentSplitter } from "../../ContentSplitter/ContentSplitters.js";
4
5
  import type { HashManager } from "../HashManager/HashManager.js";
5
6
  import type { GeneratedChunk } from "../../pouchdb/LiveSyncLocalDB.js";
6
7
  import type { IPathService, ISettingService } from "../../services/base/IService.js";
8
+ import type { LogFunction } from "../../services/lib/logUtils.js";
7
9
  export interface EntryManagerOptions {
8
10
  hashManager: HashManager;
9
11
  chunkManager: ChunkManager;
10
12
  splitter: ContentSplitter;
11
13
  database: PouchDB.Database<EntryDoc>;
14
+ readScope?: LocalDatabaseReadScope;
12
15
  settingService: ISettingService;
13
16
  pathService: IPathService;
17
+ /** Host-owned logger; standalone instances default to the global logger. */
18
+ log?: LogFunction;
14
19
  }
15
20
  export declare class EntryManager {
16
21
  options: EntryManagerOptions;
22
+ readonly log: LogFunction;
17
23
  constructor(options: EntryManagerOptions);
18
24
  get localDatabase(): PouchDB.Database<EntryDoc>;
25
+ get readScope(): LocalDatabaseReadScope | undefined;
19
26
  get hashManager(): HashManager;
20
27
  get chunkManager(): ChunkManager;
21
28
  get splitter(): ContentSplitter;
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  REMOTE_COUCHDB
3
3
  } from "../../common/types.js";
4
+ import { Logger } from "octagonal-wheels/common/logger";
4
5
  import { assertDatabasePathIdentity } from "../../pouchdb/pathIdentityCompatibility.js";
5
6
  import {
6
7
  deleteDBEntryByPath,
@@ -16,12 +17,17 @@ import {
16
17
  } from "./EntryManagerImpls.js";
17
18
  class EntryManager {
18
19
  options;
20
+ log;
19
21
  constructor(options) {
20
22
  this.options = options;
23
+ this.log = options.log ?? Logger;
21
24
  }
22
25
  get localDatabase() {
23
26
  return this.options.database;
24
27
  }
28
+ get readScope() {
29
+ return this.options.readScope;
30
+ }
25
31
  get hashManager() {
26
32
  return this.options.hashManager;
27
33
  }
@@ -1,16 +1,20 @@
1
+ import type { LocalDatabaseReadScope } from "../../pouchdb/LocalDatabaseReadScope.js";
1
2
  import { type SavingEntry, type DocumentID, type EntryDoc, type EntryBase, type FilePath, type FilePathWithPrefix, type LoadedEntry, type ObsidianLiveSyncSettings, type MetaEntry } from "../../common/types.js";
2
3
  import type { ContentSplitter } from "../../ContentSplitter/ContentSplitters.js";
3
4
  import type { HashManager } from "../HashManager/HashManager.js";
4
5
  import type { LayeredChunkManager as ChunkManager } from "../LayeredChunkManager.js";
5
6
  import type { NecessaryServicesInterfaces } from "../../interfaces/ServiceModule.js";
6
7
  import type { GeneratedChunk } from "../../pouchdb/LiveSyncLocalDB.js";
8
+ import type { LogFunction } from "../../services/lib/logUtils.js";
7
9
  type Managers = {
10
+ log?: LogFunction;
8
11
  hashManager: HashManager;
9
12
  chunkManager: ChunkManager;
10
13
  splitter: ContentSplitter;
11
14
  localDatabase: PouchDB.Database<EntryDoc>;
15
+ readScope?: LocalDatabaseReadScope;
12
16
  };
13
- type NecessaryManagers<T extends keyof Managers> = Pick<Managers, T>;
17
+ type NecessaryManagers<T extends keyof Managers> = Pick<Managers, T | "log" | "readScope">;
14
18
  export declare function createChunks(managers: NecessaryManagers<"chunkManager" | "hashManager" | "splitter">, dispFilename: string, note: SavingEntry): Promise<false | DocumentID[]>;
15
19
  export declare function putDBEntry(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager" | "hashManager" | "splitter">, note: SavingEntry, onlyChunks?: boolean, conflictBaseRev?: string): Promise<false | PouchDB.Core.Response>;
16
20
  /**
@@ -29,7 +33,7 @@ export declare function putDBEntryWithLiveBaseRevision(host: NecessaryServicesIn
29
33
  export declare function putDBEntryAsIndependentRoot(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager" | "hashManager" | "splitter">, note: SavingEntry): Promise<false | PouchDB.Core.Response>;
30
34
  export declare function isTargetFile(host: NecessaryServicesInterfaces<"setting", never>, filenameSrc: string): boolean;
31
35
  export declare function prepareChunk({ chunkManager, hashManager }: NecessaryManagers<"chunkManager" | "hashManager">, piece: string): Promise<GeneratedChunk>;
32
- export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
36
+ export declare function getDBEntryMetaByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase, readScope }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
33
37
  export declare function isLegacyNote(meta: LoadedEntry | MetaEntry): boolean;
34
38
  export declare function canUseOnDemandChunking(settings: ObsidianLiveSyncSettings): boolean;
35
39
  /**
@@ -41,7 +45,7 @@ export declare function computeChunkRetrievalMethod(waitForReady: boolean, setti
41
45
  waitForDelivery: boolean;
42
46
  preventRemoteRequest: boolean;
43
47
  };
44
- export declare function getDBEntryFromMeta(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase, chunkManager }: NecessaryManagers<"localDatabase" | "chunkManager">, meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | (import("../../common/types.js").DatabaseEntry & EntryBase & import("../../common/types.js").EntryWithEden & {
48
+ export declare function getDBEntryFromMeta(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager">, meta: LoadedEntry | MetaEntry, dump?: boolean, waitForReady?: boolean, localOnly?: boolean): Promise<false | (import("../../common/types.js").DatabaseEntry & EntryBase & import("../../common/types.js").EntryWithEden & {
45
49
  path: FilePathWithPrefix;
46
50
  data: string | string[];
47
51
  type: import("../../common/models/db.type.js").EntryTypes["NOTE_LEGACY"];
@@ -85,6 +89,6 @@ export declare function getDBEntryByPath(host: NecessaryServicesInterfaces<"path
85
89
  data: string | string[];
86
90
  datatype: import("../../common/types.js").EntryTypeNotes;
87
91
  } & PouchDB.Core.IdMeta)>;
88
- export declare function deleteDBEntryByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean>;
89
- export declare function storeDeletionByPathAtRevision(host: NecessaryServicesInterfaces<"path" | "setting", never>, { localDatabase }: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, baseRevision: string): Promise<PouchDB.Core.Response | false>;
92
+ export declare function deleteDBEntryByPath(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions): Promise<boolean>;
93
+ export declare function storeDeletionByPathAtRevision(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase">, path: FilePathWithPrefix | FilePath, baseRevision: string): Promise<PouchDB.Core.Response | false>;
90
94
  export {};