@vrtmrz/livesync-commonlib 0.4.3 → 0.5.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 (60) hide show
  1. package/README.md +2 -2
  2. package/dist/interfaces/StorageAccess.d.ts +8 -2
  3. package/dist/platform/FilePathIndex.d.ts +110 -0
  4. package/dist/platform/FilePathIndex.js +146 -0
  5. package/dist/replication/trystero/LiveSyncTrysteroReplicator.d.ts +3 -3
  6. package/dist/replication/trystero/P2PAutomationCoordinator.d.ts +1 -1
  7. package/dist/replication/trystero/P2PReplicationWire.d.ts +1 -1
  8. package/dist/replication/trystero/TrysteroReplicator/changeRelay.d.ts +133 -0
  9. package/dist/replication/trystero/TrysteroReplicator/changeRelay.js +176 -0
  10. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.d.ts +55 -0
  11. package/dist/replication/trystero/TrysteroReplicator/configurationExchange.js +99 -0
  12. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.d.ts +83 -0
  13. package/dist/replication/trystero/TrysteroReplicator/configuredTargets.js +121 -0
  14. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.d.ts +75 -0
  15. package/dist/replication/trystero/TrysteroReplicator/peerAgreement.js +131 -0
  16. package/dist/replication/trystero/TrysteroReplicator/progress.d.ts +57 -0
  17. package/dist/replication/trystero/TrysteroReplicator/progress.js +84 -0
  18. package/dist/replication/trystero/TrysteroReplicator/relayControl.d.ts +20 -0
  19. package/dist/replication/trystero/TrysteroReplicator/relayControl.js +25 -0
  20. package/dist/replication/trystero/TrysteroReplicator/transfers.d.ts +125 -0
  21. package/dist/replication/trystero/TrysteroReplicator/transfers.js +278 -0
  22. package/dist/replication/trystero/TrysteroReplicator.d.ts +65 -483
  23. package/dist/replication/trystero/TrysteroReplicator.js +240 -673
  24. package/dist/replication/trystero/TrysteroReplicatorP2PClient.d.ts +19 -6
  25. package/dist/replication/trystero/TrysteroReplicatorP2PClient.js +29 -25
  26. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.d.ts +66 -0
  27. package/dist/replication/trystero/TrysteroReplicatorP2PServer/peerAdmission.js +142 -0
  28. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +19 -16
  29. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +33 -93
  30. package/dist/replication/trystero/p2pReplicationDiagnostics.d.ts +1 -1
  31. package/dist/replication/trystero/p2pReplicationProgress.d.ts +2 -11
  32. package/dist/replication/trystero/replicationTypes.d.ts +88 -0
  33. package/dist/replication/trystero/replicationTypes.js +0 -0
  34. package/dist/replication/trystero/rpcSessionProvider.d.ts +13 -0
  35. package/dist/replication/trystero/rpcSessionProvider.js +0 -0
  36. package/dist/rpc/RpcRoom/pendingInvocations.d.ts +141 -0
  37. package/dist/rpc/RpcRoom/pendingInvocations.js +225 -0
  38. package/dist/rpc/RpcRoom.d.ts +9 -4
  39. package/dist/rpc/RpcRoom.js +73 -118
  40. package/dist/rpc/RpcSession.d.ts +6 -0
  41. package/dist/rpc/RpcSession.js +11 -0
  42. package/dist/rpc/types.d.ts +2 -0
  43. package/dist/serviceFeatures/targetFilter.d.ts +1 -1
  44. package/dist/serviceFeatures/targetFilter.js +8 -38
  45. package/dist/serviceModules/FileAccessBase.d.ts +4 -0
  46. package/dist/serviceModules/FileAccessBase.js +10 -0
  47. package/dist/serviceModules/Rebuilder.js +1 -1
  48. package/dist/serviceModules/ServiceFileAccessBase/fileNames.d.ts +54 -0
  49. package/dist/serviceModules/ServiceFileAccessBase/fileNames.js +57 -0
  50. package/dist/serviceModules/ServiceFileAccessBase.d.ts +5 -1
  51. package/dist/serviceModules/ServiceFileAccessBase.js +18 -3
  52. package/dist/serviceModules/adapters/IFileSystemAdapter.d.ts +3 -0
  53. package/dist/storage.d.ts +2 -0
  54. package/dist/storage.js +2 -0
  55. package/docs/development.md +103 -0
  56. package/docs/p2p-transport-lifecycle.md +24 -0
  57. package/docs/platform-storage.md +22 -0
  58. package/docs/releasing.md +6 -0
  59. package/docs/settings-lifecycle.md +4 -2
  60. package/package.json +1 -1
package/README.md CHANGED
@@ -14,9 +14,9 @@ This package is primarily for maintainers of those clients and for integrations
14
14
 
15
15
  ## Status and versioning
16
16
 
17
- Commonlib [0.4.2](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib/v/0.4.2)
17
+ Commonlib [0.4.3](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib/v/0.4.3)
18
18
  is published on npm through `latest` and `next`
19
- ([release notes](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.2)).
19
+ ([release notes](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.3)).
20
20
 
21
21
  Self-hosted LiveSync
22
22
  [1.0.44](https://github.com/vrtmrz/obsidian-livesync/releases/tag/1.0.44)
@@ -1,6 +1,7 @@
1
1
  import type { FilePath, FilePathWithPrefix, UXDataWriteOptions, UXFileInfo, UXFileInfoStub, UXFolderInfo, UXStat } from "../common/types.js";
2
2
  import type { CustomRegExp } from "../common/utils.js";
3
3
  import type { FileWithFileStat, FileWithStatAsProp } from "../common/models/fileaccess.type.js";
4
+ import type { FileNameLookup } from "../platform/FilePathIndex.js";
4
5
  export interface IStorageAccessManager {
5
6
  processWriteFile<T>(file: UXFileInfoStub | FilePathWithPrefix, proc: () => Promise<T>): Promise<T>;
6
7
  processReadFile<T>(file: UXFileInfoStub | FilePathWithPrefix, proc: () => Promise<T>): Promise<T>;
@@ -9,7 +10,13 @@ export interface IStorageAccessManager {
9
10
  touch(file: FileWithStatAsProp | FileWithFileStat): void;
10
11
  clearTouched(): void;
11
12
  }
12
- export interface StorageAccess {
13
+ /**
14
+ * Storage facade with the shared name-query contract available on every host.
15
+ *
16
+ * An adapter can omit its indexed lookup capability; the service facade supplies
17
+ * the base fallback while retaining the FileNameLookup method contract.
18
+ */
19
+ export interface StorageAccess extends FileNameLookup {
13
20
  normalisePath(path: string): string;
14
21
  restoreState(): Promise<void>;
15
22
  /** Includes queued, running, and failed work; absence requires a conservative content check. */
@@ -36,7 +43,6 @@ export interface StorageAccess {
36
43
  readStubContent(stub: UXFileInfoStub): Promise<UXFileInfo | false>;
37
44
  getStub(path: string): Promise<UXFileInfoStub | UXFolderInfo | null>;
38
45
  getFiles(): Promise<UXFileInfoStub[]>;
39
- getFileNames(): Promise<FilePathWithPrefix[]>;
40
46
  touched(file: UXFileInfoStub | FilePathWithPrefix): Promise<void>;
41
47
  recentlyTouched(file: UXFileInfoStub | FilePathWithPrefix): Promise<boolean>;
42
48
  clearTouched(): void;
@@ -0,0 +1,110 @@
1
+ import type { FilePath, PathComparisonSettings } from "./pathTypes.js";
2
+ /**
3
+ * Original file paths removed and added by one synchronous membership change.
4
+ *
5
+ * @remarks
6
+ * Repeated additions and absent removals are harmless. A path present in both
7
+ * lists remains present, including when it was absent before the change.
8
+ * Hosts expand folder renames into file-path deltas before applying them.
9
+ */
10
+ export interface FilePathDelta {
11
+ readonly removed: readonly FilePath[];
12
+ readonly added: readonly FilePath[];
13
+ }
14
+ /** Controls whether a name read can reuse the host's maintained inventory. */
15
+ export interface FileNameReadOptions {
16
+ /**
17
+ * Ask the host's listing authority again instead of reusing the name index.
18
+ *
19
+ * @remarks
20
+ * Freshness follows that host's existing listing contract. For example,
21
+ * Obsidian supplies its Vault listing rather than an independent disk walk.
22
+ */
23
+ readonly fresh?: boolean;
24
+ }
25
+ /** Host-owned name reads and candidate selection for one storage root. */
26
+ export interface FileNameLookup {
27
+ /**
28
+ * Read the host's supported original file paths.
29
+ *
30
+ * @param options - Whether to ask the listing authority for a fresh view.
31
+ * @returns A copy of the complete supported inventory, preserving spelling.
32
+ * @throws Rejects unavailable or failed inventory reads rather than reporting
33
+ * a successful empty inventory. Host-specific listing exclusions still apply.
34
+ */
35
+ getFileNames(options?: FileNameReadOptions): Promise<FilePath[]>;
36
+ /**
37
+ * Find original paths which match the requested path-identity comparison key.
38
+ *
39
+ * @param path - Original file path to compare within this storage root.
40
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
41
+ * @returns Every matching original path in diagnostic order, including the
42
+ * requested spelling when present. An empty result means no supported match.
43
+ * @throws Rejects unavailable coverage and host validation or read failures.
44
+ * @remarks
45
+ * The host establishes read readiness and physical-path safety. The caller
46
+ * decides whether multiple candidates constitute a collision; this operation
47
+ * neither chooses a preferred spelling nor compares file contents.
48
+ */
49
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): Promise<readonly FilePath[]>;
50
+ }
51
+ /**
52
+ * Maintains original file-path membership and lazily materialised identity buckets.
53
+ *
54
+ * @remarks
55
+ * The host owns supported-path validation, observation, and query readiness.
56
+ * This class stores original spellings and performs no I/O. Membership changes
57
+ * update every materialised policy map; at most four policy maps are retained.
58
+ * Queries return copies and leave file contents and physical names untouched.
59
+ *
60
+ * A first query for a policy derives its buckets in one pass over the retained
61
+ * paths. Subsequent queries select and sort only the matching candidates.
62
+ */
63
+ export declare class FilePathIndex {
64
+ private paths;
65
+ private indexes;
66
+ /**
67
+ * Replace the complete inventory and all materialised policy maps together.
68
+ *
69
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
70
+ * into one membership without normalising their spelling.
71
+ * @throws Propagates invalid runtime members or iterable failures before
72
+ * replacing the current inventory or any existing policy map.
73
+ * @remarks
74
+ * Validation checks string members; filesystem admission remains the host's
75
+ * responsibility. Callers use this after a successful initial or fresh read.
76
+ */
77
+ replaceAll(paths: Iterable<FilePath>): void;
78
+ /**
79
+ * Apply one membership delta to the inventory and every cached policy map.
80
+ *
81
+ * @param delta - Original paths removed and added by the same change.
82
+ * @throws Propagates invalid runtime members before changing retained state.
83
+ * @remarks
84
+ * Inputs and comparison keys are prepared before mutation. The synchronous
85
+ * update publishes no intermediate rename state. Repeated notifications do
86
+ * not create duplicate memberships, and content-only edits need no delta.
87
+ */
88
+ apply(delta: FilePathDelta): void;
89
+ /**
90
+ * Copy the current in-memory membership without refreshing the host listing.
91
+ *
92
+ * @returns Original spellings in an independent array. Full-list ordering is
93
+ * unspecified; changing the returned array cannot change this index.
94
+ */
95
+ getFileNames(): FilePath[];
96
+ /**
97
+ * Select every indexed path with the requested storage comparison key.
98
+ *
99
+ * @param path - Path whose identity selects a candidate bucket.
100
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
101
+ * @returns A sorted copy of all matching original paths, or an empty array
102
+ * when no indexed path matches. Multiple paths remain separate candidates.
103
+ * @throws Rejects a non-string path or unsupported comparison settings.
104
+ * @remarks
105
+ * The first query for each policy materialises its buckets. Later membership
106
+ * deltas maintain those buckets incrementally. Host readiness, existence,
107
+ * physical alias checks, and the final collision decision are external.
108
+ */
109
+ findPathIdentityCandidates(path: FilePath, policy: PathComparisonSettings): readonly FilePath[];
110
+ }
@@ -0,0 +1,146 @@
1
+ import { getStoragePathComparisonKey } from "./pathComparison.js";
2
+ function validatePath(path) {
3
+ if (typeof path !== "string") {
4
+ throw new TypeError("File paths must be strings");
5
+ }
6
+ return path;
7
+ }
8
+ function snapshotPolicy(policy) {
9
+ const { pathNormalizationVersion, handleFilenameCaseSensitive } = policy;
10
+ if (pathNormalizationVersion !== 0 && pathNormalizationVersion !== 1) {
11
+ throw new Error(`Unsupported path normalisation version: ${pathNormalizationVersion}`);
12
+ }
13
+ if (typeof handleFilenameCaseSensitive !== "boolean") {
14
+ throw new TypeError("Filename case handling must be explicit");
15
+ }
16
+ return { pathNormalizationVersion, handleFilenameCaseSensitive };
17
+ }
18
+ function getPolicyKey(policy) {
19
+ return `${policy.pathNormalizationVersion}:${policy.handleFilenameCaseSensitive ? "sensitive" : "insensitive"}`;
20
+ }
21
+ function createIdentityBuckets(paths, policy) {
22
+ const buckets = /* @__PURE__ */ new Map();
23
+ for (const path of paths) {
24
+ const key = getStoragePathComparisonKey(path, policy);
25
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
26
+ bucket.add(path);
27
+ buckets.set(key, bucket);
28
+ }
29
+ return buckets;
30
+ }
31
+ class FilePathIndex {
32
+ paths = /* @__PURE__ */ new Set();
33
+ indexes = /* @__PURE__ */ new Map();
34
+ /**
35
+ * Replace the complete inventory and all materialised policy maps together.
36
+ *
37
+ * @param paths - Host-enumerated original file paths. Duplicate paths collapse
38
+ * into one membership without normalising their spelling.
39
+ * @throws Propagates invalid runtime members or iterable failures before
40
+ * replacing the current inventory or any existing policy map.
41
+ * @remarks
42
+ * Validation checks string members; filesystem admission remains the host's
43
+ * responsibility. Callers use this after a successful initial or fresh read.
44
+ */
45
+ replaceAll(paths) {
46
+ const nextPaths = /* @__PURE__ */ new Set();
47
+ for (const path of paths) {
48
+ nextPaths.add(validatePath(path));
49
+ }
50
+ const nextIndexes = /* @__PURE__ */ new Map();
51
+ for (const [key, { policy }] of this.indexes) {
52
+ nextIndexes.set(key, { policy, buckets: createIdentityBuckets(nextPaths, policy) });
53
+ }
54
+ this.paths = nextPaths;
55
+ this.indexes = nextIndexes;
56
+ }
57
+ /**
58
+ * Apply one membership delta to the inventory and every cached policy map.
59
+ *
60
+ * @param delta - Original paths removed and added by the same change.
61
+ * @throws Propagates invalid runtime members before changing retained state.
62
+ * @remarks
63
+ * Inputs and comparison keys are prepared before mutation. The synchronous
64
+ * update publishes no intermediate rename state. Repeated notifications do
65
+ * not create duplicate memberships, and content-only edits need no delta.
66
+ */
67
+ apply(delta) {
68
+ const removed = new Set(delta.removed.map(validatePath));
69
+ const added = new Set(delta.added.map(validatePath));
70
+ for (const path of added) {
71
+ if (removed.has(path)) {
72
+ removed.delete(path);
73
+ if (this.paths.has(path)) {
74
+ added.delete(path);
75
+ }
76
+ }
77
+ }
78
+ const actualRemoved = [...removed].filter((path) => this.paths.has(path));
79
+ const actualAdded = [...added].filter((path) => !this.paths.has(path));
80
+ if (actualRemoved.length === 0 && actualAdded.length === 0) {
81
+ return;
82
+ }
83
+ const indexUpdates = [...this.indexes.values()].map(({ buckets, policy }) => ({
84
+ buckets,
85
+ removed: actualRemoved.map((path) => [getStoragePathComparisonKey(path, policy), path]),
86
+ added: actualAdded.map((path) => [getStoragePathComparisonKey(path, policy), path])
87
+ }));
88
+ for (const path of actualRemoved) {
89
+ this.paths.delete(path);
90
+ }
91
+ for (const path of actualAdded) {
92
+ this.paths.add(path);
93
+ }
94
+ for (const { buckets, removed: removedKeys, added: addedKeys } of indexUpdates) {
95
+ for (const [key, path] of removedKeys) {
96
+ const bucket = buckets.get(key);
97
+ bucket?.delete(path);
98
+ if (bucket?.size === 0) {
99
+ buckets.delete(key);
100
+ }
101
+ }
102
+ for (const [key, path] of addedKeys) {
103
+ const bucket = buckets.get(key) ?? /* @__PURE__ */ new Set();
104
+ bucket.add(path);
105
+ buckets.set(key, bucket);
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Copy the current in-memory membership without refreshing the host listing.
111
+ *
112
+ * @returns Original spellings in an independent array. Full-list ordering is
113
+ * unspecified; changing the returned array cannot change this index.
114
+ */
115
+ getFileNames() {
116
+ return [...this.paths];
117
+ }
118
+ /**
119
+ * Select every indexed path with the requested storage comparison key.
120
+ *
121
+ * @param path - Path whose identity selects a candidate bucket.
122
+ * @param policy - Explicit Unicode normalisation and case comparison rules.
123
+ * @returns A sorted copy of all matching original paths, or an empty array
124
+ * when no indexed path matches. Multiple paths remain separate candidates.
125
+ * @throws Rejects a non-string path or unsupported comparison settings.
126
+ * @remarks
127
+ * The first query for each policy materialises its buckets. Later membership
128
+ * deltas maintain those buckets incrementally. Host readiness, existence,
129
+ * physical alias checks, and the final collision decision are external.
130
+ */
131
+ findPathIdentityCandidates(path, policy) {
132
+ const validatedPath = validatePath(path);
133
+ const policySnapshot = snapshotPolicy(policy);
134
+ const policyKey = getPolicyKey(policySnapshot);
135
+ let index = this.indexes.get(policyKey);
136
+ if (!index) {
137
+ index = { policy: policySnapshot, buckets: createIdentityBuckets(this.paths, policySnapshot) };
138
+ this.indexes.set(policyKey, index);
139
+ }
140
+ const key = getStoragePathComparisonKey(validatedPath, policySnapshot);
141
+ return [...index.buckets.get(key) ?? []].sort();
142
+ }
143
+ }
144
+ export {
145
+ FilePathIndex
146
+ };
@@ -36,12 +36,12 @@ export declare class LiveSyncTrysteroReplicator extends LiveSyncAbstractReplicat
36
36
  onNewPeer(peer: Advertisement): Promise<void>;
37
37
  onPeerLeaved(peerId: string): void;
38
38
  replicateFromCommand(showResult?: boolean): Promise<boolean>;
39
- replicateFrom(peerId: string, showNotice?: boolean, skipOrdinaryReplicationPolicy?: boolean): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
40
- requestSynchroniseToPeer(peerId: string): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
39
+ replicateFrom(peerId: string, showNotice?: boolean, skipOrdinaryReplicationPolicy?: boolean): Promise<import("./replicationTypes.js").P2PReplicationResult>;
40
+ requestSynchroniseToPeer(peerId: string): Promise<import("./replicationTypes.js").P2PReplicationResult>;
41
41
  getRemoteConfig(peerId: string): Promise<false | import("../../common/types.js").ObsidianLiveSyncSettings>;
42
42
  watchPeer(peerId: string): void;
43
43
  unwatchPeer(peerId: string): void;
44
- sync(peerId: string, showNotice?: boolean): Promise<import("./TrysteroReplicator.js").P2PReplicationResult>;
44
+ sync(peerId: string, showNotice?: boolean): Promise<import("./replicationTypes.js").P2PReplicationResult>;
45
45
  setOnSetup(): void;
46
46
  clearOnSetup(): void;
47
47
  makeDecision(decision: AcceptanceDecision): Promise<void>;
@@ -1,4 +1,4 @@
1
- import type { P2PReplicationResult } from "./TrysteroReplicator.js";
1
+ import type { P2PReplicationResult } from "./replicationTypes.js";
2
2
  /**
3
3
  * Stable de-duplication state for automatic baseline transfers.
4
4
  *
@@ -1,5 +1,5 @@
1
1
  import { type RpcErrorShape } from "../../rpc/index.js";
2
- import type { P2PReplicationResult } from "./TrysteroReplicator.js";
2
+ import type { P2PReplicationResult } from "./replicationTypes.js";
3
3
  /** JSON-safe representation used only while a replication result crosses RPC. */
4
4
  export type P2PReplicationWireResult = {
5
5
  readonly status: "completed";
@@ -0,0 +1,133 @@
1
+ import type { EntryDoc } from "../../../common/types.js";
2
+ import type { P2PDiagnosticInput } from "../../../p2p/p2pDiagnostics.js";
3
+ /**
4
+ * One host/room binding captured before admission is awaited.
5
+ * isCurrent must still identify that binding when admission settles; a
6
+ * replacement room must not receive work authorised for the previous room.
7
+ */
8
+ export interface PeerNotificationTarget {
9
+ isAccepted(): Promise<boolean>;
10
+ isCurrent(): boolean;
11
+ send(): Promise<void>;
12
+ }
13
+ /**
14
+ * Capabilities supplied by the replicator. The relay owns notification policy
15
+ * and feed state; the host retains the database, transport, and transfer lifetime.
16
+ */
17
+ export interface ChangeRelayDependencies<TPullResult> {
18
+ /** Open the database feed using the relay's existing selection policy. */
19
+ createChangesFeed(options: PouchDB.Core.ChangesOptions): PouchDB.Core.Changes<EntryDoc>;
20
+ hasHost(): boolean;
21
+ peerIds(): readonly string[];
22
+ /** Capture identity and operations together, before asynchronous admission. */
23
+ captureNotificationTarget(peerId: string): PeerNotificationTarget | undefined;
24
+ isDisposed(): boolean;
25
+ /** Retain the host notification entry point, including overrides and observers. */
26
+ announceChanges(): void | Promise<void>;
27
+ /** Run a pull through the host's existing finite-operation owner. */
28
+ pullPeer(peerId: string): Promise<TPullResult>;
29
+ dispatchStatus(): void;
30
+ reportDiagnostic(input: P2PDiagnosticInput): void;
31
+ }
32
+ interface ChangeRelayState {
33
+ /** The feed handle remains here until its terminal cleanup clears it. */
34
+ changes: PouchDB.Core.Changes<EntryDoc> | undefined;
35
+ /** Local announcement policy, rather than evidence of peer delivery. */
36
+ isBroadcasting: boolean;
37
+ /** Sources whose progress notifications may start a pull. */
38
+ watchingPeers: Set<string>;
39
+ /** Opaque database sequence; the relay records it without ordering it. */
40
+ lastSeq: string | number;
41
+ }
42
+ /** Change-relay state exposed through the existing replicator facade. */
43
+ export interface ChangeRelay<TPullResult> extends ChangeRelayState {
44
+ enableBroadcastChanges(): void;
45
+ disableBroadcastChanges(): void;
46
+ notifyProgress(excludePeerId?: string): Promise<void> | undefined;
47
+ watchPeer(peerId: string): void;
48
+ unwatchPeer(peerId: string): void;
49
+ onUpdateDatabase(peerId: string): Promise<TPullResult | false>;
50
+ }
51
+ type OnChangeContext = {
52
+ deps: Pick<ChangeRelayDependencies<unknown>, "announceChanges">;
53
+ relay: Pick<ChangeRelayState, "lastSeq">;
54
+ };
55
+ type CloseChangesContext = {
56
+ deps: Pick<ChangeRelayDependencies<unknown>, "dispatchStatus" | "reportDiagnostic">;
57
+ relay: Pick<ChangeRelayState, "changes" | "isBroadcasting">;
58
+ };
59
+ type DisableBroadcastChangesContext = CloseChangesContext;
60
+ type EnableBroadcastChangesContext = {
61
+ deps: Pick<ChangeRelayDependencies<unknown>, "createChangesFeed" | "dispatchStatus" | "reportDiagnostic" | "announceChanges">;
62
+ relay: Pick<ChangeRelayState, "changes" | "isBroadcasting">;
63
+ onChange(change: PouchDB.Core.ChangesResponseChange<EntryDoc>): Promise<void>;
64
+ closeChanges(reason?: unknown): void;
65
+ };
66
+ type NotifyProgressContext = {
67
+ deps: Pick<ChangeRelayDependencies<unknown>, "hasHost" | "peerIds">;
68
+ relay: Pick<ChangeRelayState, "isBroadcasting">;
69
+ notifyPeerProgress(peerId: string): Promise<void>;
70
+ };
71
+ type NotifyPeerProgressContext = {
72
+ deps: Pick<ChangeRelayDependencies<unknown>, "captureNotificationTarget" | "isDisposed" | "reportDiagnostic">;
73
+ relay: Pick<ChangeRelayState, "isBroadcasting">;
74
+ };
75
+ type WatchPeerContext = {
76
+ deps: Pick<ChangeRelayDependencies<unknown>, "dispatchStatus" | "reportDiagnostic">;
77
+ relay: Pick<ChangeRelayState, "watchingPeers">;
78
+ };
79
+ type UnwatchPeerContext = WatchPeerContext;
80
+ type OnUpdateDatabaseContext<TPullResult> = {
81
+ deps: Pick<ChangeRelayDependencies<TPullResult>, "pullPeer" | "reportDiagnostic">;
82
+ relay: Pick<ChangeRelayState, "watchingPeers">;
83
+ };
84
+ /**
85
+ * Record a feed sequence before forwarding the host's existing notification
86
+ * entry point. The sequence is opaque and is not compared or normalised.
87
+ */
88
+ export declare function onChange({ deps, relay }: OnChangeContext, change: Pick<PouchDB.Core.ChangesResponseChange<EntryDoc>, "seq">): Promise<void>;
89
+ /**
90
+ * Close a completed or failed changes feed and report its terminal transition.
91
+ * Feed errors retain their existing diagnostic and log classification.
92
+ */
93
+ export declare function closeChanges({ deps, relay }: CloseChangesContext, reason?: unknown): void;
94
+ /**
95
+ * Stop announcements immediately and request cancellation of the live feed.
96
+ * A synchronous completion callback may already have reported the transition.
97
+ */
98
+ export declare function disableBroadcastChanges({ deps, relay }: DisableBroadcastChangesContext): void;
99
+ /**
100
+ * Enable one live feed and announce its start through the host entry point.
101
+ * Repeated enable calls retain the current feed. Feed callbacks are composed
102
+ * from the separately testable change and close operations.
103
+ */
104
+ export declare function enableBroadcastChanges({ deps, relay, onChange: handleChange, closeChanges: handleClose, }: EnableBroadcastChangesContext): void;
105
+ /**
106
+ * Schedule notifications using the existing per-peer serialisation keys.
107
+ * The returned promise means scheduling finished; it does not await peer sends
108
+ * or remote acquisition. Disabled broadcasting or a missing host returns early.
109
+ */
110
+ export declare function notifyProgress({ deps, relay, notifyPeerProgress: notifyPeer }: NotifyProgressContext, excludePeerId?: string): Promise<void> | undefined;
111
+ /** Send only while the captured host/room remains usable after admission. */
112
+ export declare function notifyPeerProgress({ deps, relay }: NotifyPeerProgressContext, peerId: string): Promise<void>;
113
+ /** Enable pulls from this source; repeated calls still refresh host status. */
114
+ export declare function watchPeer({ deps, relay }: WatchPeerContext, peerId: string): void;
115
+ /** Refuse new progress-triggered pulls without changing an active transfer. */
116
+ export declare function unwatchPeer({ deps, relay }: UnwatchPeerContext, peerId: string): void;
117
+ /**
118
+ * Admit a watched source to the existing serial pull path and retain its result.
119
+ * Follow policy is checked before queueing, as in the replicator facade. The
120
+ * host owns transfer cancellation; removing Follow does not cancel queued work.
121
+ * An unwatched source returns false without starting a pull.
122
+ */
123
+ export declare function onUpdateDatabase<TPullResult>({ deps, relay }: OnUpdateDatabaseContext<TPullResult>, peerId: string): Promise<TPullResult | false>;
124
+ /**
125
+ * Construct one relay without opening a feed or starting transport work.
126
+ *
127
+ * The returned facade and the bound operations share one state object. Existing
128
+ * replicator accessors may replace its fields without creating a second owner.
129
+ * The feed outlives each synchronous operation and closes at an explicit stop
130
+ * or terminal feed event; it does not belong to a short asynchronous scope.
131
+ */
132
+ export declare function createChangeRelay<TPullResult>(deps: ChangeRelayDependencies<TPullResult>): ChangeRelay<TPullResult>;
133
+ export {};
@@ -0,0 +1,176 @@
1
+ import { bindContext } from "octagonal-wheels/context";
2
+ import { serialized } from "octagonal-wheels/concurrency/lock_v2";
3
+ import { fireAndForget } from "octagonal-wheels/promises";
4
+ import { LOG_LEVEL_INFO, LOG_LEVEL_VERBOSE, Logger } from "octagonal-wheels/common/logger";
5
+ import { notificationFailureDiagnostic } from "../p2pReplicationDiagnostics.js";
6
+ async function onChange({ deps, relay }, change) {
7
+ relay.lastSeq = change.seq;
8
+ await deps.announceChanges();
9
+ }
10
+ function closeChanges({ deps, relay }, reason) {
11
+ const wasBroadcasting = relay.isBroadcasting;
12
+ if (reason) {
13
+ if (reason instanceof Error) {
14
+ Logger("Error while broadcasting the changes", LOG_LEVEL_INFO);
15
+ Logger(reason, LOG_LEVEL_VERBOSE);
16
+ } else {
17
+ Logger("Broadcasting the changes has been finished", LOG_LEVEL_INFO);
18
+ Logger(reason, LOG_LEVEL_VERBOSE);
19
+ }
20
+ }
21
+ void relay.changes?.cancel();
22
+ void relay.changes?.removeAllListeners();
23
+ relay.changes = void 0;
24
+ relay.isBroadcasting = false;
25
+ deps.dispatchStatus();
26
+ if (wasBroadcasting) {
27
+ deps.reportDiagnostic({
28
+ category: "sync",
29
+ code: "broadcast-disabled",
30
+ ...reason instanceof Error ? { reason: "replication-error" } : {}
31
+ });
32
+ }
33
+ }
34
+ function disableBroadcastChanges({ deps, relay }) {
35
+ const wasBroadcasting = relay.isBroadcasting;
36
+ relay.changes?.cancel();
37
+ const needsDiagnostic = wasBroadcasting && relay.isBroadcasting;
38
+ relay.isBroadcasting = false;
39
+ deps.dispatchStatus();
40
+ if (needsDiagnostic) {
41
+ deps.reportDiagnostic({ category: "sync", code: "broadcast-disabled" });
42
+ }
43
+ }
44
+ function enableBroadcastChanges({
45
+ deps,
46
+ relay,
47
+ onChange: handleChange,
48
+ closeChanges: handleClose
49
+ }) {
50
+ if (relay.isBroadcasting) {
51
+ return;
52
+ }
53
+ relay.isBroadcasting = true;
54
+ deps.dispatchStatus();
55
+ if (relay.changes) {
56
+ void relay.changes.cancel();
57
+ void relay.changes.removeAllListeners();
58
+ }
59
+ relay.changes = deps.createChangesFeed({
60
+ since: "now",
61
+ live: true,
62
+ include_docs: false,
63
+ selector: { _id: { $gt: "_local/" } }
64
+ });
65
+ void relay.changes.on("change", handleChange);
66
+ void relay.changes.on("error", handleClose);
67
+ void relay.changes.on("complete", handleClose);
68
+ deps.reportDiagnostic({ category: "sync", code: "broadcast-enabled" });
69
+ fireAndForget(async () => await deps.announceChanges());
70
+ }
71
+ function notifyProgress({ deps, relay, notifyPeerProgress: notifyPeer }, excludePeerId) {
72
+ if (!relay.isBroadcasting || !deps.hasHost()) {
73
+ return;
74
+ }
75
+ for (const peerId of deps.peerIds()) {
76
+ if (peerId === excludePeerId) {
77
+ continue;
78
+ }
79
+ void serialized("notifyProgress-" + peerId, () => notifyPeer(peerId));
80
+ }
81
+ return Promise.resolve();
82
+ }
83
+ async function notifyPeerProgress({ deps, relay }, peerId) {
84
+ const target = deps.captureNotificationTarget(peerId);
85
+ if (!target || deps.isDisposed() || !relay.isBroadcasting) {
86
+ return;
87
+ }
88
+ const isAcceptable = await target.isAccepted();
89
+ if (!isAcceptable) {
90
+ deps.reportDiagnostic({
91
+ category: "sync",
92
+ code: "change-notification-ignored",
93
+ peerId,
94
+ reason: "not-accepted"
95
+ });
96
+ Logger("Peer " + peerId + " is not acceptable to notify progress", LOG_LEVEL_VERBOSE);
97
+ return;
98
+ }
99
+ try {
100
+ if (deps.isDisposed() || !relay.isBroadcasting || !target.isCurrent()) {
101
+ return;
102
+ }
103
+ await target.send();
104
+ deps.reportDiagnostic({ category: "sync", code: "change-notification-sent", peerId });
105
+ } catch (error) {
106
+ deps.reportDiagnostic(notificationFailureDiagnostic(peerId, error));
107
+ Logger("Error while notifying progress to " + peerId, LOG_LEVEL_VERBOSE);
108
+ Logger(error, LOG_LEVEL_VERBOSE);
109
+ }
110
+ }
111
+ function watchPeer({ deps, relay }, peerId) {
112
+ const watchingPeers = relay.watchingPeers;
113
+ if (!watchingPeers.has(peerId)) {
114
+ deps.reportDiagnostic({ category: "sync", code: "watch-enabled", peerId });
115
+ }
116
+ watchingPeers.add(peerId);
117
+ deps.dispatchStatus();
118
+ }
119
+ function unwatchPeer({ deps, relay }, peerId) {
120
+ const watchingPeers = relay.watchingPeers;
121
+ if (watchingPeers.has(peerId)) {
122
+ deps.reportDiagnostic({ category: "sync", code: "watch-disabled", peerId });
123
+ }
124
+ watchingPeers.delete(peerId);
125
+ deps.dispatchStatus();
126
+ }
127
+ async function onUpdateDatabase({ deps, relay }, peerId) {
128
+ const watchingPeers = relay.watchingPeers;
129
+ if (watchingPeers.has(peerId)) {
130
+ deps.reportDiagnostic({ category: "sync", code: "change-notification-received", peerId });
131
+ Logger("Progress notification from " + peerId, LOG_LEVEL_VERBOSE);
132
+ return await serialized("onProgress-" + peerId, async () => await deps.pullPeer(peerId));
133
+ }
134
+ deps.reportDiagnostic({
135
+ category: "sync",
136
+ code: "change-notification-ignored",
137
+ peerId,
138
+ reason: "not-watching"
139
+ });
140
+ return false;
141
+ }
142
+ function createChangeRelay(deps) {
143
+ const relay = {
144
+ changes: void 0,
145
+ isBroadcasting: false,
146
+ watchingPeers: /* @__PURE__ */ new Set(),
147
+ lastSeq: ""
148
+ };
149
+ const onChangeForRelay = bindContext({ deps, relay }, onChange);
150
+ const closeChangesForRelay = bindContext({ deps, relay }, closeChanges);
151
+ const enableBroadcastChangesForRelay = bindContext(
152
+ { deps, relay, onChange: onChangeForRelay, closeChanges: closeChangesForRelay },
153
+ enableBroadcastChanges
154
+ );
155
+ const notifyPeerProgressForRelay = bindContext({ deps, relay }, notifyPeerProgress);
156
+ return Object.assign(relay, {
157
+ enableBroadcastChanges: enableBroadcastChangesForRelay,
158
+ disableBroadcastChanges: bindContext({ deps, relay }, disableBroadcastChanges),
159
+ notifyProgress: bindContext({ deps, relay, notifyPeerProgress: notifyPeerProgressForRelay }, notifyProgress),
160
+ watchPeer: bindContext({ deps, relay }, watchPeer),
161
+ unwatchPeer: bindContext({ deps, relay }, unwatchPeer),
162
+ onUpdateDatabase: bindContext({ deps, relay }, onUpdateDatabase)
163
+ });
164
+ }
165
+ export {
166
+ closeChanges,
167
+ createChangeRelay,
168
+ disableBroadcastChanges,
169
+ enableBroadcastChanges,
170
+ notifyPeerProgress,
171
+ notifyProgress,
172
+ onChange,
173
+ onUpdateDatabase,
174
+ unwatchPeer,
175
+ watchPeer
176
+ };