@vrtmrz/livesync-commonlib 0.7.0 → 0.8.1

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 (93) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -8,7 +8,14 @@ import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
8
8
  import { promiseWithResolvers } from "octagonal-wheels/promises";
9
9
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
10
10
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
11
- import { admitStorageEvents } from "./StorageEventManager/admission.js";
11
+ import {
12
+ assertSuccessfulFileEvents
13
+ } from "./StorageEventManager/operations.js";
14
+ import {
15
+ admitStorageEvents,
16
+ registerAdmission,
17
+ trackStorageEventAdmission
18
+ } from "./StorageEventManager/admission.js";
12
19
  import {
13
20
  forwardVaultEvent,
14
21
  hasEditorChangePath,
@@ -23,6 +30,8 @@ import {
23
30
  import {
24
31
  enqueueStorageEvent,
25
32
  flushStorageEvents,
33
+ publishCommittedStorageEvents,
34
+ restoreOrderedStorageEvents,
26
35
  restoreStorageEvents,
27
36
  runBufferedStorageEvents
28
37
  } from "./StorageEventManager/queue.js";
@@ -30,7 +39,12 @@ import {
30
39
  captureFileEventAttempts,
31
40
  waitForFileEventAttempts
32
41
  } from "./StorageEventManager/retry.js";
33
- import { persistFileEventSnapshot } from "./StorageEventManager/snapshot.js";
42
+ import {
43
+ acknowledgeEmptyOrderedBuffer,
44
+ acknowledgeOrderedEntry,
45
+ appendPendingEventBuffer,
46
+ persistFileEventSnapshot
47
+ } from "./StorageEventManager/snapshot.js";
34
48
  import {
35
49
  handleStorageFileEvent,
36
50
  processStorageEventAttempt
@@ -52,7 +66,9 @@ class StorageEventManagerBase extends StorageEventManager {
52
66
  concurrentProcessing = Semaphore(5);
53
67
  _waitingMap = /* @__PURE__ */ new Map();
54
68
  processingCount = 0;
55
- eventState = createStorageEventState();
69
+ eventState;
70
+ orderedStoreLoaded = false;
71
+ orderedStoreLoad;
56
72
  dispatchPaused = false;
57
73
  dispatchResumeSignal;
58
74
  activeDispatches = /* @__PURE__ */ new Set();
@@ -64,7 +80,14 @@ class StorageEventManagerBase extends StorageEventManager {
64
80
  append: (event) => {
65
81
  this.bufferedQueuedItems.push(event);
66
82
  },
67
- shift: () => this.bufferedQueuedItems.shift()
83
+ peek: () => this.bufferedQueuedItems[0],
84
+ takeHead: (expected) => {
85
+ if (this.bufferedQueuedItems[0] !== expected) {
86
+ return false;
87
+ }
88
+ this.bufferedQueuedItems.shift();
89
+ return true;
90
+ }
68
91
  };
69
92
  notifications = {
70
93
  updateStatus: () => this.updateStatus(),
@@ -107,6 +130,17 @@ class StorageEventManagerBase extends StorageEventManager {
107
130
  wait: (attempts) => this.waitForAttempts(attempts),
108
131
  fail: (operation, error, attempt) => this.failOperation(operation, error, attempt)
109
132
  };
133
+ orderedAppend = {
134
+ publish: (events) => publishCommittedStorageEvents(this.eventState, events, this.queue),
135
+ reportAppendFailure: (error) => {
136
+ this._log(
137
+ "Some local file changes could not be queued for sync. Once file activity settles, rescan the Vault to check the current files.",
138
+ LOG_LEVEL_NOTICE
139
+ );
140
+ this._log(error, LOG_LEVEL_VERBOSE);
141
+ this.updateStatus();
142
+ }
143
+ };
110
144
  admission = {
111
145
  settings: () => this.settings,
112
146
  isFolder: (file) => this.isFolder(file),
@@ -155,6 +189,11 @@ class StorageEventManagerBase extends StorageEventManager {
155
189
  constructor(adapter, dependencies) {
156
190
  super();
157
191
  this.adapter = adapter;
192
+ this.eventState = createStorageEventState(adapter.pendingEventStore);
193
+ const ordered = this.eventState.ordered;
194
+ if (ordered) {
195
+ this.queue.acknowledgeSentinel = (entry) => acknowledgeOrderedEntry(this.eventState, ordered, entry, this.notifications.updateStatus);
196
+ }
158
197
  this.setting = dependencies.setting;
159
198
  this.vaultService = dependencies.vaultService;
160
199
  this.admission.isTargetInternal = dependencies.isTargetInternalFile?.bind(dependencies);
@@ -238,9 +277,7 @@ class StorageEventManagerBase extends StorageEventManager {
238
277
  this.adapter.status.updateStatus({
239
278
  batched: this._waitingMap.size,
240
279
  processing: this.processingCount,
241
- totalQueued: [...this.eventState.pendingSnapshot.values()].filter(
242
- (entry) => entry.operation && !entry.completed
243
- ).length
280
+ totalQueued: this.eventState.ordered?.pendingOperations ?? [...this.eventState.pendingSnapshot.values()].filter((entry) => entry.operation && !entry.completed).length
244
281
  });
245
282
  }
246
283
  /** Completes restored operations before the host starts watching. */
@@ -250,8 +287,16 @@ class StorageEventManagerBase extends StorageEventManager {
250
287
  * @returns A promise fulfilled after restoration and replay attempts settle; snapshot or dispatch errors reject it, while failed operation results are reported and retained.
251
288
  */
252
289
  restoreState() {
253
- this.snapShotRestored = this._restoreFromSnapshot();
254
- return this.snapShotRestored;
290
+ if (this.eventState.ordered && this.snapShotRestored) return this.snapShotRestored;
291
+ const restore = this._restoreFromSnapshot();
292
+ this.snapShotRestored = restore;
293
+ if (this.eventState.ordered) {
294
+ const clear = () => {
295
+ this.snapShotRestored = null;
296
+ };
297
+ void restore.then(clear, clear);
298
+ }
299
+ return restore;
255
300
  }
256
301
  /**
257
302
  * Filter and admit host watcher events into the operation queue.
@@ -261,14 +306,18 @@ class StorageEventManagerBase extends StorageEventManager {
261
306
  * @remarks The promise may resolve while admitted handlers are still pending. Use `waitForIdle` for the captured processing boundary.
262
307
  */
263
308
  appendQueue(params, ctx) {
264
- return admitStorageEvents(this.eventState, params, ctx, this.admission);
309
+ return admitStorageEvents(this.eventState, params, ctx, this.admission, () => this.loadOrderedEvents());
265
310
  }
266
311
  /**
267
312
  * Add an already selected event to the buffer and start background snapshotting and dispatch.
268
313
  * @param event - The event which has already passed host admission checks.
269
314
  * @returns Nothing; processing and persistence failures are reported through manager effects.
315
+ * @remarks Ordered stores must have completed their initial load. Append watcher events through `appendQueue`.
270
316
  */
271
317
  enqueue(event) {
318
+ if (this.eventState.ordered && !this.orderedStoreLoaded) {
319
+ throw new Error("Load the pending storage events before enqueueing an event");
320
+ }
272
321
  enqueueStorageEvent(this.eventState, event, this.queue);
273
322
  }
274
323
  /**
@@ -277,7 +326,7 @@ class StorageEventManagerBase extends StorageEventManager {
277
326
  * @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
278
327
  */
279
328
  async waitForIdle() {
280
- await flushStorageEvents(this.eventState, this.queue);
329
+ await flushStorageEvents(this.eventState, this.queue, this.orderedStoreLoad);
281
330
  }
282
331
  /**
283
332
  * Pause new file-handler dispatch and wait for dispatches already in progress.
@@ -311,8 +360,13 @@ class StorageEventManagerBase extends StorageEventManager {
311
360
  try {
312
361
  await this.waitForIdle();
313
362
  } catch (error) {
314
- this.reportOperationFailure(error);
363
+ if (!this.eventState.ordered) {
364
+ this.reportOperationFailure(error);
365
+ } else {
366
+ this._log(error, LOG_LEVEL_VERBOSE);
367
+ }
315
368
  }
369
+ if (this.eventState.ordered) await this.runQueuedEvents().catch(this.notifications.reportFailure);
316
370
  await this._takeSnapshot();
317
371
  }
318
372
  /**
@@ -456,8 +510,22 @@ class StorageEventManagerBase extends StorageEventManager {
456
510
  * @returns A promise fulfilled when the attempt completes; a failed attempt rejects it.
457
511
  */
458
512
  async processFileEvent(event) {
459
- const operation = this.retainEvent(event).operation;
460
- await this.processOperation(operation, operation.attempt);
513
+ if (!this.eventState.ordered) {
514
+ const operation = this.retainEvent(event).operation;
515
+ await this.processOperation(operation, operation.attempt);
516
+ return;
517
+ }
518
+ const existing = this.operations.get(event);
519
+ if (existing) {
520
+ await this.processOperation(existing, existing.attempt);
521
+ return;
522
+ }
523
+ let attempt;
524
+ await trackStorageEventAdmission(this.eventState, this.admission, async (admission) => {
525
+ await this.loadOrderedEvents();
526
+ attempt = this.operations.get(event)?.attempt ?? registerAdmission(this.eventState, admission, event, this.admission);
527
+ });
528
+ if (attempt) assertSuccessfulFileEvents([await attempt.completion.promise]);
461
529
  }
462
530
  /**
463
531
  * Persist the manager snapshot and optionally acknowledge one attempt in that snapshot.
@@ -465,7 +533,16 @@ class StorageEventManagerBase extends StorageEventManager {
465
533
  * @returns A promise for the serialised save; snapshot I/O failures reject it.
466
534
  */
467
535
  persistSnapshot(completion) {
468
- return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
536
+ const ordered = this.eventState.ordered;
537
+ if (!ordered) return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
538
+ if (!completion) return appendPendingEventBuffer(this.eventState, ordered, this.orderedAppend);
539
+ return acknowledgeOrderedEntry(
540
+ this.eventState,
541
+ ordered,
542
+ completion.entry,
543
+ this.notifications.updateStatus,
544
+ completion
545
+ );
469
546
  }
470
547
  /**
471
548
  * Wait for the next serialised snapshot write.
@@ -479,7 +556,41 @@ class StorageEventManagerBase extends StorageEventManager {
479
556
  * @returns A promise for restoration; storage or dispatch errors reject it, while failed attempt results are reported and retained.
480
557
  */
481
558
  async _restoreFromSnapshot() {
482
- await restoreStorageEvents(this.queue);
559
+ if (!this.eventState.ordered) {
560
+ await restoreStorageEvents(this.queue);
561
+ return;
562
+ }
563
+ if (!this.eventState.acceptingEvents) return;
564
+ await this.loadOrderedEvents();
565
+ await this.runQueuedEvents({ waitForProcessing: true });
566
+ }
567
+ /** Join the initial load without waiting for restored handlers. */
568
+ loadOrderedEvents() {
569
+ const ordered = this.eventState.ordered;
570
+ if (!ordered || this.orderedStoreLoaded) return;
571
+ if (this.orderedStoreLoad) return this.orderedStoreLoad;
572
+ const load = Promise.resolve().then(async () => {
573
+ const buffers = await ordered.store.load();
574
+ for (const { key, events } of buffers) {
575
+ if (events.length === 0) {
576
+ await acknowledgeEmptyOrderedBuffer(this.eventState, ordered, key).catch(
577
+ this.notifications.reportFailure
578
+ );
579
+ }
580
+ }
581
+ const operations = restoreOrderedStorageEvents(this.eventState, this.queue, buffers);
582
+ this.orderedStoreLoaded = true;
583
+ if (this.eventState.acceptingEvents) {
584
+ fireAndForget(this.runQueuedEvents().catch(this.notifications.reportFailure));
585
+ }
586
+ return operations;
587
+ });
588
+ this.orderedStoreLoad = load;
589
+ const clear = () => {
590
+ this.orderedStoreLoad = void 0;
591
+ };
592
+ void load.then(clear, clear);
593
+ return load;
483
594
  }
484
595
  /**
485
596
  * Dispatch events in the buffer and optionally wait for captured processing attempts.
@@ -494,7 +605,8 @@ class StorageEventManagerBase extends StorageEventManager {
494
605
  * @returns Nothing; the write is deliberately not awaited by the caller.
495
606
  */
496
607
  _triggerTakeSnapshot() {
497
- fireAndForget(() => this._takeSnapshot().catch((error) => this.reportOperationFailure(error)));
608
+ const snapshot = this._takeSnapshot();
609
+ fireAndForget(this.eventState.ordered ? snapshot : snapshot.catch(this.notifications.reportFailure));
498
610
  }
499
611
  /**
500
612
  * Throttled callback for requesting a background snapshot write.
@@ -538,7 +650,12 @@ class StorageEventManagerBase extends StorageEventManager {
538
650
  * @returns A promise fulfilled when watcher registration finishes; a restoration failure prevents registration and rejects it.
539
651
  */
540
652
  async beginWatch() {
541
- await this.snapShotRestored;
653
+ if (this.eventState.ordered) {
654
+ await this.restoreState();
655
+ } else {
656
+ await this.snapShotRestored;
657
+ }
658
+ if (this.eventState.ordered && !this.eventState.acceptingEvents) return;
542
659
  await this.adapter.watch.beginWatch({
543
660
  onCreate: (file, ctx) => this.watchVaultCreate(file, ctx),
544
661
  onChange: (file, ctx) => this.watchVaultChange(file, ctx),
@@ -1,5 +1,5 @@
1
1
  import type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- import type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ import type { IStorageEventPersistenceAdapter, PendingStorageEventStore } from "./IStorageEventPersistenceAdapter.js";
3
3
  import type { IStorageEventWatchAdapter } from "./IStorageEventWatchAdapter.js";
4
4
  import type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -12,6 +12,8 @@ import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdap
12
12
  export interface IStorageEventManagerAdapter<TFile, TFolder> {
13
13
  readonly typeGuard: IStorageEventTypeGuardAdapter<TFile, TFolder>;
14
14
  readonly persistence: IStorageEventPersistenceAdapter;
15
+ /** Select the ordered store when the host can persist separate event buffers. */
16
+ readonly pendingEventStore?: PendingStorageEventStore;
15
17
  readonly watch: IStorageEventWatchAdapter<TFile, unknown>;
16
18
  readonly status: IStorageEventStatusAdapter;
17
19
  readonly converter: IStorageEventConverterAdapter<TFile>;
@@ -1,5 +1,21 @@
1
1
  import type { FileEventItem } from "../../common/types.js";
2
2
  import type { FileEventItemSentinel } from "../StorageEventManager.js";
3
+ export interface PendingStorageEventBuffer {
4
+ readonly key: string;
5
+ readonly events: readonly (FileEventItem | FileEventItemSentinel)[];
6
+ }
7
+ /** Store immutable buffers of pending event intents. */
8
+ export interface PendingStorageEventStore {
9
+ /** Load buffers in replay order, with any legacy snapshot first. */
10
+ load(): Promise<readonly PendingStorageEventBuffer[]>;
11
+ /**
12
+ * Save the whole buffer atomically and return its unique key after the write commits.
13
+ * A rejected append leaves the store unchanged.
14
+ */
15
+ append(events: PendingStorageEventBuffer["events"]): Promise<string>;
16
+ /** Remove the buffer under the supplied key after all of its entries have completed. */
17
+ remove(key: string): Promise<void>;
18
+ }
3
19
  /**
4
20
  * Adapter interface for snapshot persistence operations
5
21
  */
@@ -1,5 +1,5 @@
1
1
  export type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- export type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ export type { IStorageEventPersistenceAdapter, PendingStorageEventBuffer, PendingStorageEventStore, } from "./IStorageEventPersistenceAdapter.js";
3
3
  export type { IStorageEventWatchAdapter, IStorageEventWatchHandlers } from "./IStorageEventWatchAdapter.js";
4
4
  export type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  export type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -5,6 +5,7 @@ import {
5
5
  SuffixDatabaseName
6
6
  } from "../common/types.js";
7
7
  import { isErrorOfMissingDoc } from "./utils_couchdb.js";
8
+ import { isTombstoneRevision } from "../common/utils.doc.js";
8
9
  import { EVENT_CHUNK_FETCHED } from "../managers/ChunkFetcher.js";
9
10
  import { FallbackWeakRef } from "octagonal-wheels/common/polyfill";
10
11
  import { LocalDatabaseReadScope } from "./LocalDatabaseReadScope.js";
@@ -288,10 +289,8 @@ class LiveSyncLocalDB {
288
289
  for (const change of changes.results) {
289
290
  const doc = change.doc;
290
291
  if (doc.type == "leaf") {
291
- if (doc._deleted) {
292
- if (!includeDeleted) {
293
- continue;
294
- }
292
+ if (isTombstoneRevision(doc) && !includeDeleted) {
293
+ continue;
295
294
  }
296
295
  existing.set(doc._id, doc);
297
296
  }
@@ -24,3 +24,5 @@ export type { JoinedDevice, JoinedDevicesSnapshot, ForgetJoinedDeviceResult } fr
24
24
  export type { ReplicationStatics, CouchDBReplicationPhase, CouchDBReplicationProgress, ReplicationCheckpointProgress, } from "../common/models/shared.definition.js";
25
25
  export { inspectDatabasePathIdentity } from "../pouchdb/pathIdentityCompatibility.js";
26
26
  export type { PathIdentityInspection } from "../pouchdb/pathIdentityCompatibility.js";
27
+ export { createReplicationResultQueueStore } from "./replicationResultQueueStore.js";
28
+ export type { ReplicationResultQueueBacking, ReplicationResultQueueDelta, ReplicationResultQueueRow, ReplicationResultQueueStore, ReplicationResultQueueWrite, } from "./replicationResultQueueStore.js";
@@ -60,6 +60,7 @@ import {
60
60
  usesEncryptedInternalMetadata
61
61
  } from "../pouchdb/remoteFeatureCompatibility.js";
62
62
  import { inspectDatabasePathIdentity } from "../pouchdb/pathIdentityCompatibility.js";
63
+ import { createReplicationResultQueueStore } from "./replicationResultQueueStore.js";
63
64
  export {
64
65
  CAPABILITY_NOT_APPLICABLE,
65
66
  CAPABILITY_NOT_IMPLEMENTED,
@@ -94,6 +95,7 @@ export {
94
95
  assessRemoteFeatureDocument,
95
96
  centralRemoteAdministrationVerificationFailed,
96
97
  centralRemoteAdministrationVerified,
98
+ createReplicationResultQueueStore,
97
99
  defineReplicatorProviderDefinitions,
98
100
  describeRemoteFeatureRejection,
99
101
  getReplicationNetworkFailure,
@@ -0,0 +1,101 @@
1
+ declare const ROW_KINDS: readonly ["processing", "queued", "pendingReflection", "recoveryAttempt"];
2
+ type RowKind = (typeof ROW_KINDS)[number];
3
+ type Row<Kind extends RowKind, Payload> = {
4
+ readonly kind: Kind;
5
+ /** An occurrence ID shared across phase changes. Reserve the 'legacy:' prefix for migration. */
6
+ readonly id: string;
7
+ /** Non-negative safe integer used to order rows within this kind. */
8
+ readonly order: number;
9
+ readonly payload: Payload;
10
+ };
11
+ export type ReplicationResultQueueRow<D, P, A> = Row<"queued", D> | Row<"processing", D> | Row<"pendingReflection", P> | Row<"recoveryAttempt", A>;
12
+ export type ReplicationResultQueueDelta<D, P, A> = {
13
+ readonly kind: "upsert";
14
+ readonly row: ReplicationResultQueueRow<D, P, A>;
15
+ } | {
16
+ readonly kind: "delete";
17
+ readonly id: string;
18
+ };
19
+ type StoredRow = ReplicationResultQueueRow<unknown, unknown, unknown>;
20
+ export type ReplicationResultQueueWrite = {
21
+ readonly kind: "upsert";
22
+ readonly key: string;
23
+ readonly value: StoredRow;
24
+ } | {
25
+ readonly kind: "delete";
26
+ readonly key: string;
27
+ };
28
+ /** Storage for one database and vault scope. The host supplies value encoding and decoding. */
29
+ export interface ReplicationResultQueueBacking {
30
+ /** Return undefined for an absent key and reject on any read or decoding failure. */
31
+ read(key: string): Promise<unknown>;
32
+ /** List every key with the literal prefix exactly once, in any order. */
33
+ listKeys(prefix: string): Promise<readonly string[]>;
34
+ /** Apply the entire ordered batch atomically and resolve after it commits. Deleting absent keys succeeds. */
35
+ writeBatch(operations: readonly ReplicationResultQueueWrite[]): Promise<void>;
36
+ }
37
+ /**
38
+ * The host serialises all calls and excludes other writers to the queue keys.
39
+ * The host owns payload validation, replay policy, and occurrence IDs. Keep an ID
40
+ * for the lifetime of the same occurrence and issue fresh IDs even across resets.
41
+ */
42
+ export interface ReplicationResultQueueStore<D, P, A> {
43
+ /**
44
+ * Migrate a legacy snapshot if present, then return rows by kind in replay
45
+ * order and by ascending order within each kind. Ties use ascending ID.
46
+ * Payloads require host validation before use.
47
+ */
48
+ load(): Promise<readonly StoredRow[]>;
49
+ /** Apply only these changes, in order, after a successful load or discard. Keep payloads stable until the call settles. */
50
+ commit(delta: readonly ReplicationResultQueueDelta<D, P, A>[]): Promise<void>;
51
+ /** Atomically delete queue rows and the legacy snapshot. May be called before load to skip replay. */
52
+ discard(): Promise<void>;
53
+ }
54
+ /**
55
+ * Convert a legacy snapshot to rows in replay order. Each array index determines
56
+ * the row's order and forms part of its migrated occurrence ID.
57
+ *
58
+ * @param snapshot - The decoded value of the legacy snapshot key.
59
+ * @returns Rows carrying their original payloads for the host to validate.
60
+ * @throws If the snapshot, a queue array, or an entry has an invalid storage format.
61
+ */
62
+ export declare function rowsFromLegacyReplicationResultSnapshot(snapshot: unknown): StoredRow[];
63
+ /**
64
+ * Compare rows by kind in replay order, then by ascending order within that
65
+ * kind and ascending occurrence ID using string comparison.
66
+ *
67
+ * @returns A negative number when `left` comes first, zero when the sort keys
68
+ * match, and a positive number when `right` comes first.
69
+ */
70
+ export declare function compareReplicationResultQueueRows(left: StoredRow, right: StoredRow): number;
71
+ /**
72
+ * Read stored rows in replay order. When a legacy snapshot is present, write
73
+ * its rows and delete the legacy key in the same atomic batch before returning.
74
+ *
75
+ * @param backing - Storage for one queue scope. Exclude other writers to its
76
+ * queue keys while this operation runs.
77
+ * @returns Rows with payloads that require host validation before use.
78
+ * @throws If stored data is invalid, both formats exist, or a backing operation fails.
79
+ */
80
+ export declare function loadReplicationResultQueueRows(backing: ReplicationResultQueueBacking): Promise<StoredRow[]>;
81
+ /**
82
+ * Validate row storage fields and translate queue changes to versioned key
83
+ * operations. Payloads pass through for the backing to encode.
84
+ *
85
+ * @param delta - Changes to translate in the order supplied by the host.
86
+ * @returns The corresponding writes in input order, ready for one atomic batch.
87
+ * @throws {@link TypeError} If a change has an invalid row, occurrence ID, or kind.
88
+ */
89
+ export declare function toReplicationResultQueueWrites(delta: readonly ReplicationResultQueueDelta<unknown, unknown, unknown>[]): ReplicationResultQueueWrite[];
90
+ /**
91
+ * Create a store for a single replication result queue. Construction performs
92
+ * no I/O. Call `load()` or `discard()` successfully before calling `commit()`.
93
+ *
94
+ * @typeParam D - Document payload written for queued and processing items.
95
+ * @typeParam P - Payload written for retained reflection failures.
96
+ * @typeParam A - Payload written for recovery attempts.
97
+ * @param backing - Host-owned storage that can commit an ordered batch atomically.
98
+ * @returns A queue store whose operations the host must serialise.
99
+ */
100
+ export declare function createReplicationResultQueueStore<D, P, A>(backing: ReplicationResultQueueBacking): ReplicationResultQueueStore<D, P, A>;
101
+ export {};
@@ -0,0 +1,140 @@
1
+ const LEGACY_KEY = "replicationResultProcessorSnapshot";
2
+ const QUEUE_PREFIX = "replication-result-queue:";
3
+ const ROW_PREFIX = `${QUEUE_PREFIX}v1:`;
4
+ const ROW_KINDS = ["processing", "queued", "pendingReflection", "recoveryAttempt"];
5
+ const LEGACY_FIELDS = {
6
+ processing: "processing",
7
+ queued: "queued",
8
+ pendingReflection: "pendingReflections",
9
+ recoveryAttempt: "recoveryAttempts"
10
+ };
11
+ function isRecord(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ function isStoredRow(value) {
15
+ return isRecord(value) && ROW_KINDS.some((kind) => kind === value.kind) && typeof value.id === "string" && value.id.length > 0 && typeof value.order === "number" && Number.isSafeInteger(value.order) && value.order >= 0 && Object.hasOwn(value, "payload") && value.payload !== void 0;
16
+ }
17
+ function rowKey(id) {
18
+ if (typeof id !== "string" || id.length === 0) {
19
+ throw new TypeError("A replication result queue row requires a non-empty ID.");
20
+ }
21
+ return `${ROW_PREFIX}${id}`;
22
+ }
23
+ function upsertRow(value) {
24
+ return { kind: "upsert", key: rowKey(value.id), value };
25
+ }
26
+ function rowsFromLegacyReplicationResultSnapshot(snapshot) {
27
+ if (!isRecord(snapshot)) {
28
+ throw new Error("Invalid legacy replication result queue snapshot.");
29
+ }
30
+ const rows = [];
31
+ for (const kind of ROW_KINDS) {
32
+ const field = LEGACY_FIELDS[kind];
33
+ const records = snapshot[field];
34
+ const optional = kind === "pendingReflection" || kind === "recoveryAttempt";
35
+ if (optional && (records === void 0 || records === null)) {
36
+ continue;
37
+ }
38
+ if (!Array.isArray(records)) {
39
+ throw new Error(`Invalid '${field}' array in the legacy replication result queue snapshot.`);
40
+ }
41
+ for (const [order, payload] of records.entries()) {
42
+ const validPayload = optional ? payload !== void 0 && (kind === "pendingReflection" || payload !== null) : isRecord(payload);
43
+ if (!validPayload) {
44
+ throw new Error(`Invalid '${field}' entry in the legacy replication result queue snapshot.`);
45
+ }
46
+ rows.push({ kind, id: `legacy:${kind}:${order}`, order, payload });
47
+ }
48
+ }
49
+ return rows;
50
+ }
51
+ function compareReplicationResultQueueRows(left, right) {
52
+ const order = ROW_KINDS.indexOf(left.kind) - ROW_KINDS.indexOf(right.kind) || left.order - right.order;
53
+ if (order !== 0 || left.id === right.id) {
54
+ return order;
55
+ }
56
+ return left.id < right.id ? -1 : 1;
57
+ }
58
+ async function listQueueKeys(backing) {
59
+ const keys = await backing.listKeys(QUEUE_PREFIX);
60
+ if (keys.some((key) => !key.startsWith(QUEUE_PREFIX))) {
61
+ throw new Error("The replication result queue backing returned keys outside the queue namespace.");
62
+ }
63
+ return keys;
64
+ }
65
+ async function loadReplicationResultQueueRows(backing) {
66
+ const keys = await listQueueKeys(backing);
67
+ const legacySnapshot = await backing.read(LEGACY_KEY);
68
+ if (legacySnapshot !== void 0) {
69
+ if (keys.length > 0) {
70
+ throw new Error("The replication result queue contains both a legacy snapshot and queue rows.");
71
+ }
72
+ const rows2 = rowsFromLegacyReplicationResultSnapshot(legacySnapshot);
73
+ await backing.writeBatch([...rows2.map(upsertRow), { kind: "delete", key: LEGACY_KEY }]);
74
+ return rows2;
75
+ }
76
+ const rows = [];
77
+ for (const key of keys) {
78
+ if (!key.startsWith(ROW_PREFIX)) {
79
+ throw new Error("Unsupported replication result queue row version.");
80
+ }
81
+ const value = await backing.read(key);
82
+ if (!isStoredRow(value) || key !== rowKey(value.id)) {
83
+ throw new Error("Invalid replication result queue row or missing listed value.");
84
+ }
85
+ rows.push(value);
86
+ }
87
+ return rows.sort(compareReplicationResultQueueRows);
88
+ }
89
+ function toReplicationResultQueueWrites(delta) {
90
+ return delta.map((change) => {
91
+ switch (change.kind) {
92
+ case "upsert":
93
+ if (!isStoredRow(change.row)) {
94
+ throw new TypeError("Invalid replication result queue row.");
95
+ }
96
+ return upsertRow(change.row);
97
+ case "delete":
98
+ return { kind: "delete", key: rowKey(change.id) };
99
+ default:
100
+ throw new TypeError("Invalid replication result queue change.");
101
+ }
102
+ });
103
+ }
104
+ function createReplicationResultQueueStore(backing) {
105
+ let ready = false;
106
+ return {
107
+ async load() {
108
+ ready = false;
109
+ const rows = await loadReplicationResultQueueRows(backing);
110
+ ready = true;
111
+ return rows;
112
+ },
113
+ async commit(delta) {
114
+ if (!ready) {
115
+ throw new Error("Load or discard the replication result queue before committing changes.");
116
+ }
117
+ if (delta.length === 0) {
118
+ return;
119
+ }
120
+ await backing.writeBatch(toReplicationResultQueueWrites(delta));
121
+ },
122
+ async discard() {
123
+ ready = false;
124
+ const keys = await listQueueKeys(backing);
125
+ const operations = [...keys, LEGACY_KEY].map((key) => ({
126
+ kind: "delete",
127
+ key
128
+ }));
129
+ await backing.writeBatch(operations);
130
+ ready = true;
131
+ }
132
+ };
133
+ }
134
+ export {
135
+ compareReplicationResultQueueRows,
136
+ createReplicationResultQueueStore,
137
+ loadReplicationResultQueueRows,
138
+ rowsFromLegacyReplicationResultSnapshot,
139
+ toReplicationResultQueueWrites
140
+ };
@@ -1,4 +1,5 @@
1
1
  import { isReflectionCompleted } from "../../interfaces/FileHandler.js";
2
+ import { isDeletedEntry } from "../../common/utils.doc.js";
2
3
  import {
3
4
  LOG_LEVEL_DEBUG,
4
5
  LOG_LEVEL_INFO,
@@ -6,11 +7,20 @@ import {
6
7
  LOG_LEVEL_VERBOSE,
7
8
  isMetaEntry
8
9
  } from "../../common/types.js";
10
+ import { getPathNormalizationVersion } from "../../common/pathNormalization.js";
11
+ import { hasSameParentFilenameCaseConflict } from "../../conflicts/filenameCaseConflict.js";
9
12
  import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
10
13
  import { shouldBeIgnored, stripAllPrefixes } from "../../string_and_binary/path.js";
11
14
  import { inspectMetadataDocumentIdentity } from "./metadata.js";
12
15
  import { getPathFromEntry, convertCase } from "./paths.js";
13
16
  import { FilePairProcessResults, MetadataDocumentIdentityStatuses } from "./types.js";
17
+ function shouldCheckFilenameCaseBeforeFreshness(filePath, documentPath, document, services) {
18
+ if (filePath === documentPath || isDeletedEntry(document)) {
19
+ return false;
20
+ }
21
+ const settings = services.setting.currentSettings();
22
+ return !!settings && !settings.handleFilenameCaseSensitive && hasSameParentFilenameCaseConflict(filePath, documentPath, getPathNormalizationVersion(settings));
23
+ }
14
24
  async function reflectScannedEntry(host, entry, file, force, options) {
15
25
  const target = entry._rev ? { documentId: entry._id, revision: entry._rev } : void 0;
16
26
  try {
@@ -33,7 +43,8 @@ async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
33
43
  if (!doc) {
34
44
  throw new Error(`Missing doc:${docPath}`);
35
45
  }
36
- const compareResult = host.services.path.compareFileFreshness(file, doc);
46
+ const compareFilename = shouldCheckFilenameCaseBeforeFreshness(file.path, docPath, doc, host.services);
47
+ const compareResult = compareFilename ? TARGET_IS_NEW : host.services.path.compareFileFreshness(file, doc);
37
48
  switch (compareResult) {
38
49
  case BASE_IS_NEW:
39
50
  if (!host.services.vault.isFileSizeTooLarge(file.stat.size)) {
@@ -47,9 +58,10 @@ async function syncFileBetweenDBandStorage(host, log, file, doc, scanOptions) {
47
58
  return FilePairProcessResults.SKIPPED;
48
59
  }
49
60
  case TARGET_IS_NEW:
50
- if (!host.services.vault.isFileSizeTooLarge(doc.size)) {
61
+ if (!host.services.vault.isFileSizeTooLarge(doc.size) && (!compareFilename || !host.services.vault.isFileSizeTooLarge(file.stat.size))) {
51
62
  log("STORAGE <- DB :" + docPath);
52
- const reflection = await reflectScannedEntry(host, doc, stripAllPrefixes(docPath), false, scanOptions);
63
+ const observed = compareFilename ? file : stripAllPrefixes(docPath);
64
+ const reflection = await reflectScannedEntry(host, doc, observed, false, scanOptions);
53
65
  if (reflection === FilePairProcessResults.COMPLETED) {
54
66
  host.services.context.events.emitEvent("event-file-changed", {
55
67
  file: file.path,