@vrtmrz/livesync-commonlib 0.6.1 → 0.8.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.
- package/README.md +29 -19
- package/dist/common/models/shared.definition.d.ts +10 -1
- package/dist/common/models/shared.definition.js +4 -3
- package/dist/events/coreEvents.d.ts +3 -0
- package/dist/events/coreEvents.js +2 -0
- package/dist/interfaces/FileReflectionProvenance.js +1 -0
- package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManager.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManager.js +2 -2
- package/dist/managers/EntryManager/EntryManagerImpls.d.ts +1 -1
- package/dist/managers/EntryManager/EntryManagerImpls.js +80 -8
- package/dist/managers/StorageEventManager/admission.d.ts +16 -3
- package/dist/managers/StorageEventManager/admission.js +18 -4
- package/dist/managers/StorageEventManager/processing.d.ts +2 -2
- package/dist/managers/StorageEventManager/processing.js +3 -3
- package/dist/managers/StorageEventManager/queue.d.ts +23 -14
- package/dist/managers/StorageEventManager/queue.js +70 -30
- package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
- package/dist/managers/StorageEventManager/snapshot.js +74 -0
- package/dist/managers/StorageEventManager/state.d.ts +27 -5
- package/dist/managers/StorageEventManager/state.js +9 -7
- package/dist/managers/StorageEventManager.d.ts +8 -0
- package/dist/managers/StorageEventManager.js +136 -18
- package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
- package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
- package/dist/managers/adapters/index.d.ts +1 -1
- package/dist/pouchdb/LiveSyncLocalDB.d.ts +1 -1
- package/dist/pouchdb/LiveSyncLocalDB.js +2 -2
- package/dist/replication/LiveSyncAbstractReplicator.d.ts +7 -0
- package/dist/replication/LiveSyncAbstractReplicator.js +5 -2
- package/dist/replication/ReplicatorInstance.d.ts +3 -0
- package/dist/replication/ReplicatorProvider.d.ts +23 -2
- package/dist/replication/ReplicatorProvider.js +10 -0
- package/dist/replication/SyncParamsHandler.js +26 -25
- package/dist/replication/couchdb/LiveSyncReplicator.d.ts +14 -2
- package/dist/replication/couchdb/LiveSyncReplicator.js +247 -122
- package/dist/replication/index.d.ts +4 -2
- package/dist/replication/index.js +6 -0
- package/dist/replication/remoteTransportFailure.d.ts +24 -0
- package/dist/replication/remoteTransportFailure.js +80 -0
- package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -1
- package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +2 -2
- package/dist/replication/trystero/TrysteroRpcRoom.d.ts +14 -0
- package/dist/replication/trystero/TrysteroRpcRoom.js +168 -0
- package/dist/replication/trystero/rpcCompat.d.ts +1 -0
- package/dist/replication/trystero/rpcCompat.js +15 -0
- package/dist/rpc/RpcRoom.d.ts +1 -0
- package/dist/rpc/RpcRoom.js +21 -9
- package/dist/rpc/RpcSession.d.ts +8 -13
- package/dist/rpc/RpcSession.js +14 -35
- package/dist/rpc/commonlibRpcRoom.d.ts +1 -0
- package/dist/rpc/commonlibRpcRoom.js +4 -0
- package/dist/rpc/errors.d.ts +9 -3
- package/dist/rpc/errors.js +13 -16
- package/dist/rpc/index.d.ts +10 -1
- package/dist/rpc/index.js +2 -1
- package/dist/rpc/pouchdb/RpcPouchDBProxy.d.ts +1 -1
- package/dist/rpc/pouchdb/RpcPouchDBServer.d.ts +1 -1
- package/dist/serviceFeatures/targetFilter.d.ts +3 -1
- package/dist/serviceFeatures/targetFilter.js +2 -2
- package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
- package/dist/services/base/IService.d.ts +9 -6
- package/dist/services/base/KeyValueDBService.d.ts +6 -6
- package/dist/services/base/ReadinessEvaluator.d.ts +7 -6
- package/dist/services/base/ReadinessEvaluator.js +4 -2
- package/dist/services/base/RemoteConnection.d.ts +4 -0
- package/dist/services/base/RemoteService.d.ts +5 -3
- package/dist/services/base/RemoteService.js +85 -33
- package/dist/services/base/ReplicationService.d.ts +10 -2
- package/dist/services/base/ReplicationService.js +13 -7
- package/dist/services/base/ReplicationService.readiness.d.ts +14 -4
- package/dist/services/base/ReplicationService.readiness.js +29 -2
- package/dist/services/base/ReplicationService.typedReplication.d.ts +5 -2
- package/dist/services/base/ReplicationService.typedReplication.js +67 -6
- package/dist/services/base/ReplicationStaticsOwner.d.ts +18 -0
- package/dist/services/base/ReplicationStaticsOwner.js +33 -0
- package/dist/services/base/ReplicatorService.d.ts +2 -10
- package/dist/services/base/ReplicatorService.js +6 -3
- package/dist/services/base/VaultService.d.ts +1 -0
- package/dist/string_and_binary/chunks.d.ts +1 -1
- package/dist/string_and_binary/chunks.js +63 -50
- package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
- package/dist/worker/WorkerPushStreamProducer.js +299 -0
- package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
- package/dist/worker/WorkerPushStreamReader.js +179 -0
- package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
- package/dist/worker/backgroundWorkerRpcContract.js +24 -0
- package/dist/worker/bg.worker.js +2 -14
- package/dist/worker/bg.worker.splitting.d.ts +3 -6
- package/dist/worker/bg.worker.splitting.js +65 -30
- package/dist/worker/bgWorker.d.ts +9 -11
- package/dist/worker/bgWorker.direct.d.ts +5 -28
- package/dist/worker/bgWorker.direct.js +32 -2
- package/dist/worker/bgWorker.errors.d.ts +1 -0
- package/dist/worker/bgWorker.errors.js +12 -0
- package/dist/worker/bgWorker.js +718 -268
- package/dist/worker/bgWorker.splitting.d.ts +12 -27
- package/dist/worker/bgWorker.splitting.js +114 -110
- package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
- package/dist/worker/outOfBandCancelIterator.js +8 -0
- package/dist/worker/serveBackgroundWorker.d.ts +3 -0
- package/dist/worker/serveBackgroundWorker.js +35 -0
- package/dist/worker/splitConnectionTracker.d.ts +25 -0
- package/dist/worker/splitConnectionTracker.js +73 -0
- package/dist/worker/splitGate.d.ts +19 -0
- package/dist/worker/splitGate.js +71 -0
- package/dist/worker/universalTypes.d.ts +1 -19
- package/dist/worker/universalTypes.js +0 -4
- package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
- package/dist/worker/workerPushStreamProtocol.js +143 -0
- package/docs/development.md +75 -32
- package/docs/p2p-transport-lifecycle.md +2 -3
- package/docs/storage-events-and-reflection.md +40 -5
- package/package.json +3 -2
- package/dist/worker/bg.common.d.ts +0 -2
- package/dist/worker/bg.common.js +0 -6
- package/dist/worker/bg.worker.encryption.d.ts +0 -7
- package/dist/worker/bg.worker.encryption.js +0 -30
- package/dist/worker/bgWorker.encryption.d.ts +0 -22
- package/dist/worker/bgWorker.encryption.js +0 -40
package/README.md
CHANGED
|
@@ -14,9 +14,10 @@ This package is primarily for maintainers of those clients and for integrations
|
|
|
14
14
|
|
|
15
15
|
## Status and versioning
|
|
16
16
|
|
|
17
|
-
Commonlib [
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
Stable Commonlib releases are available from [npm](https://www.npmjs.com/package/@vrtmrz/livesync-commonlib)
|
|
18
|
+
under `latest`. Release candidates are available under `next`.
|
|
19
|
+
See [GitHub Releases](https://github.com/vrtmrz/livesync-commonlib/releases) for
|
|
20
|
+
stable release notes.
|
|
20
21
|
|
|
21
22
|
Self-hosted LiveSync
|
|
22
23
|
[1.0.44](https://github.com/vrtmrz/obsidian-livesync/releases/tag/1.0.44)
|
|
@@ -43,7 +44,7 @@ ordinary replication before resuming local writers. Existing hosts can omit
|
|
|
43
44
|
this optimisation. Resume cursors retain their existing meaning; this resource
|
|
44
45
|
does not provide an arbitrary-time checkpoint jump or On Demand repair.
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
Commonlib 0.3.1 separates encrypted CouchDB HTTP responses by Security Seed
|
|
47
48
|
while retaining conditional revalidation within a Seed. See
|
|
48
49
|
[CouchDB response caching](docs/couchdb-http-cache.md) for the request,
|
|
49
50
|
replication-preparation, and host-adapter boundaries.
|
|
@@ -63,11 +64,11 @@ the receive, skip, and replay boundaries.
|
|
|
63
64
|
| Entry point | Intended use | Current contract status |
|
|
64
65
|
| -------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
65
66
|
| `@vrtmrz/livesync-commonlib` | `DirectFileManipulator` for integrations which access CouchDB directly | Deliberately small, but its high-level lifecycle and file-operation semantics are not final |
|
|
66
|
-
| `@vrtmrz/livesync-commonlib/conflicts`
|
|
67
|
+
| `@vrtmrz/livesync-commonlib/conflicts` | Keyed conflict-check scheduling with bounded concurrency and explicit completion | Focused, package-tested pre-1.0 contract |
|
|
67
68
|
| `@vrtmrz/livesync-commonlib/context` | Instance-owned events, translation injection, and host-neutral standard-I/O types | Focused, package-tested pre-1.0 contract |
|
|
68
|
-
| `@vrtmrz/livesync-commonlib/diagnostics`
|
|
69
|
-
| `@vrtmrz/livesync-commonlib/storage`
|
|
70
|
-
| `@vrtmrz/livesync-commonlib/hashing` | Chunk ID calculation and exact file-content hashing
|
|
69
|
+
| `@vrtmrz/livesync-commonlib/diagnostics` | Read-only Usage and integrity inspection, name projection, and reports | Focused pre-1.0 diagnostic contract |
|
|
70
|
+
| `@vrtmrz/livesync-commonlib/storage` | Path types, namespace and comparison helpers, and strict Unicode path resolution | Available since 0.3.1. Host integration remains explicit. |
|
|
71
|
+
| `@vrtmrz/livesync-commonlib/hashing` | Chunk ID calculation and exact file-content hashing | Focused, package-tested pre-1.0 contract |
|
|
71
72
|
| `@vrtmrz/livesync-commonlib/browser` | Rooted File System Access API storage | Focused, package-tested pre-1.0 contract |
|
|
72
73
|
| `@vrtmrz/livesync-commonlib/node` | Rooted Node storage, Node standard I/O, and selected Node capabilities | Supported platform façade; keeps Node-only dependencies behind an explicit boundary |
|
|
73
74
|
| `@vrtmrz/livesync-commonlib/p2p` | Host-composed P2P service views and composition helpers | Focused, package-tested pre-1.0 contract with a temporary compatibility façade |
|
|
@@ -76,8 +77,8 @@ the receive, skip, and replay boundaries.
|
|
|
76
77
|
| `@vrtmrz/livesync-commonlib/remote-configurations` | Multiple-remote profile creation, naming, and selection | Focused, package-tested pre-1.0 contract |
|
|
77
78
|
| `@vrtmrz/livesync-commonlib/settings` | New-Vault defaults, stored-setting fallbacks, and settings migration results | Focused, package-tested pre-1.0 contract |
|
|
78
79
|
| `@vrtmrz/livesync-commonlib/setup-uri` | Encrypted Setup URI generation, availability, and import | Focused, package-tested pre-1.0 contract |
|
|
79
|
-
| `@vrtmrz/livesync-commonlib/ui-commands`
|
|
80
|
-
| `@vrtmrz/livesync-commonlib/compat/*` | Exact legacy imports still required by existing clients | Migration-only; retained within 0.2.x, with removals treated as 0.3.0 breaking changes
|
|
80
|
+
| `@vrtmrz/livesync-commonlib/ui-commands` | Instance-owned typed UI command declarations and handlers | Focused, package-tested contract |
|
|
81
|
+
| `@vrtmrz/livesync-commonlib/compat/*` | Exact legacy imports still required by existing clients | Migration-only; retained within 0.2.x, with removals treated as 0.3.0 breaking changes |
|
|
81
82
|
| `@vrtmrz/livesync-commonlib/package.json` | Package metadata for tooling | Metadata export, not a runtime API |
|
|
82
83
|
|
|
83
84
|
The existing `compat/services/lib` boundary retains `bindableFunction` and `lazyBindableFunction` for current clients. Their `setHandler()` methods return an `UnregisterFunction` which removes only its own current assignment; stale removers, including after an override with the same callback, and repeated removals are no-ops. Existing callers may ignore the return value. These helpers remain a migration boundary, not a general-purpose SDK integration surface.
|
|
@@ -94,7 +95,12 @@ Import only the entry point required by the current runtime. Browser code must n
|
|
|
94
95
|
|
|
95
96
|
The Node and browser entries are platform façades. They keep platform-specific adapters and capabilities behind package-owned boundaries, so a consumer does not have to reproduce those imports or their build and review exceptions. The Node entry's selected built-in-module exports are deliberate parts of that façade. Package checks ensure that the root, context, and browser entries do not load the Node implementation.
|
|
96
97
|
|
|
97
|
-
|
|
98
|
+
Starting with [Commonlib 0.7.0](updates.md#070), the hosted P2P service uses
|
|
99
|
+
the published `@vrtmrz/rpc/p2p` room. The
|
|
100
|
+
transitional Commonlib `/rpc` entry retains the existing room and session
|
|
101
|
+
constructors and the PouchDB bridge. Hosted rooms and sessions pass
|
|
102
|
+
`instanceof` checks against those exports. New consumers can use the focused
|
|
103
|
+
`/p2p` entry to compose a LiveSync host or Fancy Kit for general RPC.
|
|
98
104
|
|
|
99
105
|
The P2P entry exposes eight focused views over one service owner, together with the maintained host-composition helpers. New consumers select only the lifecycle, peer-directory, peer-admission, targeted-transfer, change-relay, configuration-exchange, diagnostic, or connection-probe-admission view which they need. The composition result still carries a deprecated concrete Replicator façade while existing panes migrate; new consumers must not depend on that property or reach through it to a raw room or host.
|
|
100
106
|
|
|
@@ -176,10 +182,10 @@ Import `declareUICommand` and `UICommandRegistry` from `@vrtmrz/livesync-commonl
|
|
|
176
182
|
```ts
|
|
177
183
|
import { declareUICommand } from "@vrtmrz/livesync-commonlib/ui-commands";
|
|
178
184
|
|
|
179
|
-
const showDevices = declareUICommand<void,
|
|
185
|
+
const showDevices = declareUICommand<void, "closed">("example:show-devices");
|
|
180
186
|
const unregister = services.UI.commands.register(showDevices, async () => {
|
|
181
187
|
await openHostDeviceDialogue();
|
|
182
|
-
return
|
|
188
|
+
return "closed";
|
|
183
189
|
});
|
|
184
190
|
const result = await services.UI.commands.invoke(showDevices, undefined);
|
|
185
191
|
// result is { status: 'handled', value: 'closed' } or { status: 'unavailable' }.
|
|
@@ -200,7 +206,12 @@ Hosts can read the latest `services.replicator.replicationStatics.value` and
|
|
|
200
206
|
subscribe to that reactive source. The focused `/replication` entry exports
|
|
201
207
|
`ReplicationStatics`, `CouchDBReplicationProgress`, and
|
|
202
208
|
`ReplicationCheckpointProgress`. Existing transfer counters and `syncStatus`
|
|
203
|
-
retain their meanings.
|
|
209
|
+
retain their meanings. Starting with [Commonlib 0.7.0](updates.md#070), the
|
|
210
|
+
initial snapshot has `syncStatus: 'NOT_CONNECTED'` and `statsUpdatedAt: null`.
|
|
211
|
+
When the provider publishes statistics,
|
|
212
|
+
`statsUpdatedAt` records the publication time in Unix epoch milliseconds.
|
|
213
|
+
Replacing the provider restores the initial snapshot until new statistics
|
|
214
|
+
are published.
|
|
204
215
|
|
|
205
216
|
The optional `couchDB` snapshot describes the ordinary CouchDB replication
|
|
206
217
|
attempt. Other providers omit it. Its `phase` distinguishes `one-shot`,
|
|
@@ -307,12 +318,12 @@ import {
|
|
|
307
318
|
formatUsageTSV,
|
|
308
319
|
parseDiagnosticPathToken,
|
|
309
320
|
projectUsageReport,
|
|
310
|
-
} from
|
|
321
|
+
} from "@vrtmrz/livesync-commonlib/diagnostics";
|
|
311
322
|
|
|
312
323
|
const result = await analyseDatabaseUsage({ source: createLocalDiagnosticSource(localPouchDB) });
|
|
313
|
-
const mapper = createDiagnosticNameMapper(
|
|
324
|
+
const mapper = createDiagnosticNameMapper("pseudonym");
|
|
314
325
|
const report = projectUsageReport(result, mapper);
|
|
315
|
-
if (report.status ===
|
|
326
|
+
if (report.status === "complete") {
|
|
316
327
|
const tsv = formatUsageTSV(report);
|
|
317
328
|
// Present the report through the host's own UI or output stream.
|
|
318
329
|
}
|
|
@@ -324,7 +335,7 @@ Path pseudonyms include the report salt. A consumer can parse that token and sup
|
|
|
324
335
|
const pathToken = report.rows[0]?.path;
|
|
325
336
|
const parsed = pathToken === undefined ? undefined : parseDiagnosticPathToken(pathToken);
|
|
326
337
|
if (parsed) {
|
|
327
|
-
const followUpMapper = createDiagnosticNameMapper(
|
|
338
|
+
const followUpMapper = createDiagnosticNameMapper("pseudonym", parsed.salt);
|
|
328
339
|
const candidateToken = followUpMapper.path(storedVaultRelativePath);
|
|
329
340
|
// Compare this token with the path pseudonym on this device.
|
|
330
341
|
}
|
|
@@ -393,7 +404,6 @@ See [Maintained-host examples and evidence](docs/proven-in-use.md) for compositi
|
|
|
393
404
|
|
|
394
405
|
MIT
|
|
395
406
|
|
|
396
|
-
|
|
397
407
|
## Shared value helper migration
|
|
398
408
|
|
|
399
409
|
The shared formatter displays positive infinity as `∞y`, including through the existing `timeDeltaToHumanReadable` entry. Other duration formatting cases retain their previous behaviour.
|
|
@@ -28,6 +28,10 @@ export type CouchDBReplicationProgress = {
|
|
|
28
28
|
readonly pull?: ReplicationCheckpointProgress;
|
|
29
29
|
readonly push?: ReplicationCheckpointProgress;
|
|
30
30
|
};
|
|
31
|
+
/**
|
|
32
|
+
* Raw statistics accepted by the publication boundary. The optional timestamp
|
|
33
|
+
* is retained for compatibility and replaced when a value is published.
|
|
34
|
+
*/
|
|
31
35
|
export type ReplicationStatics = {
|
|
32
36
|
sent: number;
|
|
33
37
|
arrived: number;
|
|
@@ -36,7 +40,12 @@ export type ReplicationStatics = {
|
|
|
36
40
|
lastSyncPullSeq: number;
|
|
37
41
|
lastSyncPushSeq: number;
|
|
38
42
|
syncStatus: DatabaseConnectingStatus;
|
|
43
|
+
statsUpdatedAt?: number | null;
|
|
39
44
|
/** Present only when the provider supplies CouchDB checkpoint observations. */
|
|
40
45
|
couchDB?: CouchDBReplicationProgress;
|
|
41
46
|
};
|
|
42
|
-
|
|
47
|
+
/** Statistics as observed after publication; the timestamp is always present. */
|
|
48
|
+
export type PublishedReplicationStatics = Readonly<Omit<ReplicationStatics, "statsUpdatedAt"> & {
|
|
49
|
+
statsUpdatedAt: number | null;
|
|
50
|
+
}>;
|
|
51
|
+
export declare const DEFAULT_REPLICATION_STATICS: PublishedReplicationStatics;
|
|
@@ -9,15 +9,16 @@ const DatabaseConnectingStatuses = {
|
|
|
9
9
|
JOURNAL_SEND: "JOURNAL_SEND",
|
|
10
10
|
JOURNAL_RECEIVE: "JOURNAL_RECEIVE"
|
|
11
11
|
};
|
|
12
|
-
const DEFAULT_REPLICATION_STATICS = {
|
|
12
|
+
const DEFAULT_REPLICATION_STATICS = Object.freeze({
|
|
13
13
|
sent: 0,
|
|
14
14
|
arrived: 0,
|
|
15
15
|
maxPullSeq: 0,
|
|
16
16
|
maxPushSeq: 0,
|
|
17
17
|
lastSyncPullSeq: 0,
|
|
18
18
|
lastSyncPushSeq: 0,
|
|
19
|
-
syncStatus: DatabaseConnectingStatuses.
|
|
20
|
-
|
|
19
|
+
syncStatus: DatabaseConnectingStatuses.NOT_CONNECTED,
|
|
20
|
+
statsUpdatedAt: null
|
|
21
|
+
});
|
|
21
22
|
export {
|
|
22
23
|
DEFAULT_REPLICATION_STATICS,
|
|
23
24
|
DatabaseConnectingStatuses
|
|
@@ -7,6 +7,8 @@ export declare const EVENT_FILE_RENAMED = "file-renamed";
|
|
|
7
7
|
export declare const EVENT_FILE_SAVED = "file-saved";
|
|
8
8
|
export declare const EVENT_LEAF_ACTIVE_CHANGED = "leaf-active-changed";
|
|
9
9
|
export declare const EVENT_DATABASE_REBUILT = "database-rebuilt";
|
|
10
|
+
/** The replication service has received an explicit transfer stop request. */
|
|
11
|
+
export declare const EVENT_REPLICATION_ABORT_REQUESTED = "replication-abort-requested";
|
|
10
12
|
/** Emitted by `AppLifecycleService.markIsReady()` each time it establishes application readiness. */
|
|
11
13
|
export declare const EVENT_APPLICATION_READY = "application-ready";
|
|
12
14
|
export declare const EVENT_LOG_ADDED = "log-added";
|
|
@@ -40,6 +42,7 @@ declare global {
|
|
|
40
42
|
};
|
|
41
43
|
[EVENT_DATABASE_REBUILT]: undefined;
|
|
42
44
|
[EVENT_APPLICATION_READY]: undefined;
|
|
45
|
+
[EVENT_REPLICATION_ABORT_REQUESTED]: undefined;
|
|
43
46
|
[EVENT_REQUEST_OPEN_P2P_SETTINGS]: undefined;
|
|
44
47
|
[EVENT_LEAF_ACTIVE_CHANGED]: undefined;
|
|
45
48
|
[EVENT_REQUEST_OPEN_SETUP_URI]: undefined;
|
|
@@ -6,6 +6,7 @@ const EVENT_FILE_RENAMED = "file-renamed";
|
|
|
6
6
|
const EVENT_FILE_SAVED = "file-saved";
|
|
7
7
|
const EVENT_LEAF_ACTIVE_CHANGED = "leaf-active-changed";
|
|
8
8
|
const EVENT_DATABASE_REBUILT = "database-rebuilt";
|
|
9
|
+
const EVENT_REPLICATION_ABORT_REQUESTED = "replication-abort-requested";
|
|
9
10
|
const EVENT_APPLICATION_READY = "application-ready";
|
|
10
11
|
const EVENT_LOG_ADDED = "log-added";
|
|
11
12
|
const EVENT_REQUEST_OPEN_SETUP_URI = "request-open-setup-uri";
|
|
@@ -35,6 +36,7 @@ export {
|
|
|
35
36
|
EVENT_PLATFORM_UNLOADED,
|
|
36
37
|
EVENT_PLUGIN_LOADED,
|
|
37
38
|
EVENT_PLUGIN_UNLOADED,
|
|
39
|
+
EVENT_REPLICATION_ABORT_REQUESTED,
|
|
38
40
|
EVENT_REQUEST_CHECK_REMOTE_SIZE,
|
|
39
41
|
EVENT_REQUEST_CLOSE_P2P,
|
|
40
42
|
EVENT_REQUEST_COPY_SETUP_URI,
|
|
@@ -8,4 +8,4 @@ export interface KeyValueDatabase {
|
|
|
8
8
|
destroy(): Promise<void>;
|
|
9
9
|
}
|
|
10
10
|
/** Opens the key-value database owned by one service composition. */
|
|
11
|
-
export type KeyValueDatabaseFactory = (databaseKey: string) => Promise<
|
|
11
|
+
export type KeyValueDatabaseFactory<TDatabase extends KeyValueDatabase = KeyValueDatabase> = (databaseKey: string) => Promise<TDatabase>;
|
|
@@ -34,7 +34,7 @@ export declare class EntryManager {
|
|
|
34
34
|
serviceModules: {};
|
|
35
35
|
};
|
|
36
36
|
get isOnDemandChunkEnabled(): boolean;
|
|
37
|
-
isTargetFile(filenameSrc: string): boolean;
|
|
37
|
+
isTargetFile(filenameSrc: string, internalFileEvent?: boolean): boolean;
|
|
38
38
|
prepareChunk(piece: string): Promise<GeneratedChunk>;
|
|
39
39
|
getDBEntryMeta(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, includeDeleted?: boolean): Promise<false | LoadedEntry>;
|
|
40
40
|
getDBEntry(path: FilePathWithPrefix | FilePath, opt?: PouchDB.Core.GetOptions, dump?: boolean, waitForReady?: boolean, includeDeleted?: boolean, localOnly?: boolean): Promise<false | LoadedEntry>;
|
|
@@ -56,8 +56,8 @@ class EntryManager {
|
|
|
56
56
|
}
|
|
57
57
|
return true;
|
|
58
58
|
}
|
|
59
|
-
isTargetFile(filenameSrc) {
|
|
60
|
-
return isTargetFile(this.serviceHost, filenameSrc);
|
|
59
|
+
isTargetFile(filenameSrc, internalFileEvent = false) {
|
|
60
|
+
return isTargetFile(this.serviceHost, filenameSrc, internalFileEvent);
|
|
61
61
|
}
|
|
62
62
|
async prepareChunk(piece) {
|
|
63
63
|
return await prepareChunk(this, piece);
|
|
@@ -31,7 +31,7 @@ export declare function putDBEntryWithLiveBaseRevision(host: NecessaryServicesIn
|
|
|
31
31
|
* Return the Metadata write result, or `false` when the entry cannot be stored.
|
|
32
32
|
*/
|
|
33
33
|
export declare function putDBEntryAsIndependentRoot(host: NecessaryServicesInterfaces<"path" | "setting", never>, managers: NecessaryManagers<"localDatabase" | "chunkManager" | "hashManager" | "splitter">, note: SavingEntry): Promise<false | PouchDB.Core.Response>;
|
|
34
|
-
export declare function isTargetFile(host: NecessaryServicesInterfaces<"setting", never>, filenameSrc: string): boolean;
|
|
34
|
+
export declare function isTargetFile(host: NecessaryServicesInterfaces<"setting", never>, filenameSrc: string, internalFileEvent?: boolean): boolean;
|
|
35
35
|
export declare function prepareChunk({ chunkManager, hashManager }: NecessaryManagers<"chunkManager" | "hashManager">, piece: string): Promise<GeneratedChunk>;
|
|
36
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>;
|
|
37
37
|
export declare function isLegacyNote(meta: LoadedEntry | MetaEntry): boolean;
|
|
@@ -11,9 +11,57 @@ import { isErrorOfMissingDoc } from "../../pouchdb/utils_couchdb.js";
|
|
|
11
11
|
import { stripAllPrefixes } from "../../string_and_binary/path.js";
|
|
12
12
|
import { ICHeader, ICXHeader, PSCHeader } from "../../common/models/fileaccess.const.js";
|
|
13
13
|
import { ContentReadError } from "../../common/LSError.js";
|
|
14
|
+
import { isOutOfBandCancellableIterator } from "../../worker/outOfBandCancelIterator.js";
|
|
15
|
+
const MAX_WRITE_SIZE = 2048e3;
|
|
14
16
|
function readFromDatabase(readScope, operation) {
|
|
15
17
|
return readScope ? readScope.run(operation) : operation();
|
|
16
18
|
}
|
|
19
|
+
function createChunkWritePipeline(pieces, flushBufferedChunks, onWriteError) {
|
|
20
|
+
let pendingWrite;
|
|
21
|
+
let writeFailure = false;
|
|
22
|
+
let closing;
|
|
23
|
+
function closePieces() {
|
|
24
|
+
closing ??= (async () => {
|
|
25
|
+
try {
|
|
26
|
+
await pieces.return?.();
|
|
27
|
+
} catch {
|
|
28
|
+
}
|
|
29
|
+
})();
|
|
30
|
+
return closing;
|
|
31
|
+
}
|
|
32
|
+
function failWrite(rejected, error) {
|
|
33
|
+
if (!writeFailure) {
|
|
34
|
+
writeFailure = true;
|
|
35
|
+
if (rejected) {
|
|
36
|
+
onWriteError(error);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
void closePieces();
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
async function waitForWrite() {
|
|
43
|
+
if (pendingWrite !== void 0) {
|
|
44
|
+
const ok = await pendingWrite;
|
|
45
|
+
pendingWrite = void 0;
|
|
46
|
+
return ok && !writeFailure;
|
|
47
|
+
}
|
|
48
|
+
return !writeFailure;
|
|
49
|
+
}
|
|
50
|
+
async function startWrite() {
|
|
51
|
+
if (pendingWrite !== void 0 && !await waitForWrite()) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
if (writeFailure) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
pendingWrite = flushBufferedChunks().then(
|
|
58
|
+
(ok) => ok ? true : failWrite(false),
|
|
59
|
+
(error) => failWrite(true, error)
|
|
60
|
+
);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
return { startWrite, waitForWrite, closePieces, failed: () => writeFailure };
|
|
64
|
+
}
|
|
17
65
|
async function createChunks(managers, dispFilename, note) {
|
|
18
66
|
const { chunkManager, splitter, log = Logger } = managers;
|
|
19
67
|
let bufferedChunk = [];
|
|
@@ -25,7 +73,6 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
25
73
|
let duplicatedCount = 0;
|
|
26
74
|
let totalWritingCount = 0;
|
|
27
75
|
let createChunkCount = 0;
|
|
28
|
-
const MAX_WRITE_SIZE = 1e3 * 1024 * 2;
|
|
29
76
|
const chunks = [];
|
|
30
77
|
let writeChars = 0;
|
|
31
78
|
const flushBufferedChunks = async () => {
|
|
@@ -33,7 +80,7 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
33
80
|
log(`No chunks to flush for ${dispFilename}`, LOG_LEVEL_VERBOSE);
|
|
34
81
|
return true;
|
|
35
82
|
}
|
|
36
|
-
const writeBuf =
|
|
83
|
+
const writeBuf = bufferedChunk;
|
|
37
84
|
bufferedSize = 0;
|
|
38
85
|
bufferedChunk = [];
|
|
39
86
|
const result = await chunkManager.write(
|
|
@@ -56,9 +103,15 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
56
103
|
log(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE);
|
|
57
104
|
return true;
|
|
58
105
|
};
|
|
106
|
+
const pieces = await splitter.splitContent(note);
|
|
107
|
+
const pipeline = isOutOfBandCancellableIterator(pieces) ? createChunkWritePipeline(pieces, flushBufferedChunks, (error) => {
|
|
108
|
+
log(`Error processing pieces for ${dispFilename}`);
|
|
109
|
+
log(error, LOG_LEVEL_VERBOSE);
|
|
110
|
+
}) : void 0;
|
|
59
111
|
const flushIfNeeded = async () => {
|
|
60
112
|
if (bufferedSize > MAX_WRITE_SIZE) {
|
|
61
|
-
|
|
113
|
+
const ok = pipeline ? await pipeline.startWrite() : await flushBufferedChunks();
|
|
114
|
+
if (!ok) {
|
|
62
115
|
log(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);
|
|
63
116
|
return false;
|
|
64
117
|
}
|
|
@@ -76,28 +129,47 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
76
129
|
bufferedSize += chunk.data.length;
|
|
77
130
|
return await flushIfNeeded();
|
|
78
131
|
};
|
|
79
|
-
const pieces = await splitter.splitContent(note);
|
|
80
132
|
let totalChunkCount = 0;
|
|
133
|
+
let complete = false;
|
|
81
134
|
try {
|
|
82
135
|
for await (const piece of pieces) {
|
|
136
|
+
if (pipeline?.failed()) {
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
83
139
|
totalChunkCount++;
|
|
84
140
|
if (piece.length === 0) {
|
|
85
141
|
continue;
|
|
86
142
|
}
|
|
87
143
|
createChunkCount++;
|
|
88
144
|
const chunk = await prepareChunk(managers, piece);
|
|
145
|
+
if (pipeline?.failed()) {
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
89
148
|
cachedCount += chunk.isNew ? 0 : 1;
|
|
90
149
|
newCount += chunk.isNew ? 1 : 0;
|
|
91
150
|
if (!await addBuffer(chunk.id, chunk.piece)) {
|
|
92
151
|
return false;
|
|
93
152
|
}
|
|
94
153
|
}
|
|
154
|
+
if (pipeline && (!await pipeline.startWrite() || !await pipeline.waitForWrite())) {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
complete = true;
|
|
95
158
|
} catch (ex) {
|
|
96
159
|
log(`Error processing pieces for ${dispFilename}`);
|
|
97
160
|
log(ex, LOG_LEVEL_VERBOSE);
|
|
98
161
|
return false;
|
|
162
|
+
} finally {
|
|
163
|
+
if (pipeline) {
|
|
164
|
+
if (!complete) {
|
|
165
|
+
bufferedChunk = [];
|
|
166
|
+
bufferedSize = 0;
|
|
167
|
+
await pipeline.closePieces();
|
|
168
|
+
}
|
|
169
|
+
await pipeline.waitForWrite();
|
|
170
|
+
}
|
|
99
171
|
}
|
|
100
|
-
if (!await flushBufferedChunks()) {
|
|
172
|
+
if (!pipeline && !await flushBufferedChunks()) {
|
|
101
173
|
return false;
|
|
102
174
|
}
|
|
103
175
|
const dataSize = note.data.size;
|
|
@@ -211,7 +283,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
|
|
|
211
283
|
log(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE);
|
|
212
284
|
return result;
|
|
213
285
|
}
|
|
214
|
-
function isTargetFile(host, filenameSrc) {
|
|
286
|
+
function isTargetFile(host, filenameSrc, internalFileEvent = false) {
|
|
215
287
|
const settings = host.services.setting.currentSettings();
|
|
216
288
|
const isInternalFile = filenameSrc.startsWith(ICHeader);
|
|
217
289
|
const file = isInternalFile ? filenameSrc.substring(ICHeader.length) : filenameSrc;
|
|
@@ -220,12 +292,12 @@ function isTargetFile(host, filenameSrc) {
|
|
|
220
292
|
if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) {
|
|
221
293
|
return false;
|
|
222
294
|
}
|
|
223
|
-
if (!settings.syncInternalFiles) {
|
|
295
|
+
if (!internalFileEvent && !settings.syncInternalFiles) {
|
|
224
296
|
if (file.startsWith(".")) {
|
|
225
297
|
return false;
|
|
226
298
|
}
|
|
227
299
|
}
|
|
228
|
-
if (!isInternalFile && settings.syncOnlyRegEx) {
|
|
300
|
+
if (!internalFileEvent && !isInternalFile && settings.syncOnlyRegEx) {
|
|
229
301
|
const syncOnly = getFileRegExp(settings, "syncOnlyRegEx");
|
|
230
302
|
if (syncOnly.length > 0 && !syncOnly.some((e) => e.test(file))) return false;
|
|
231
303
|
}
|
|
@@ -5,8 +5,8 @@ import { type FileEventItem, type ObsidianLiveSyncSettings } from "../../common/
|
|
|
5
5
|
import type { FileEvent } from "../../interfaces/StorageEventManager.js";
|
|
6
6
|
import type { IStorageAccessManager } from "../../interfaces/StorageAccess.js";
|
|
7
7
|
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
8
|
-
import type { StorageEventState } from "./state.js";
|
|
9
|
-
import type { PendingFileEvent } from "./operations.js";
|
|
8
|
+
import type { EventAdmission, StorageEventState } from "./state.js";
|
|
9
|
+
import type { FileEventAttempt, PendingFileEvent } from "./operations.js";
|
|
10
10
|
/**
|
|
11
11
|
* Inject host settings, path and file checks, queue actions, and diagnostics into admission.
|
|
12
12
|
* @remarks
|
|
@@ -18,6 +18,7 @@ export interface StorageEventAdmissionEffects {
|
|
|
18
18
|
isFolder(file: FileEvent["file"]): boolean;
|
|
19
19
|
isFile(file: FileEvent["file"]): boolean;
|
|
20
20
|
isTarget(path: string): Promise<boolean>;
|
|
21
|
+
isTargetInternal?(path: string): Promise<boolean>;
|
|
21
22
|
isTooLarge(size: number): boolean;
|
|
22
23
|
recentlyTouched: IStorageAccessManager["recentlyTouched"];
|
|
23
24
|
onStorageFileEvent(): void;
|
|
@@ -37,14 +38,26 @@ type SelectedFileEvent = Pick<FileEventItem, "type" | "args">;
|
|
|
37
38
|
* @remarks The source-only case asserts that `oldPath` and file `stat` are present; `selectRename` establishes those preconditions.
|
|
38
39
|
*/
|
|
39
40
|
export declare function selectRenameFileEvent(param: FileEvent, oldSelected: boolean, newSelected: boolean): SelectedFileEvent | null;
|
|
41
|
+
/**
|
|
42
|
+
* Enqueue a selected item and associate its operation with the admission boundary.
|
|
43
|
+
* @param state - Mutable operation ownership state.
|
|
44
|
+
* @param admission - The batch admission record receiving this operation.
|
|
45
|
+
* @param item - The selected event to enqueue.
|
|
46
|
+
* @param effects - Queue and release actions supplied by the facade.
|
|
47
|
+
* @returns Nothing; a found operation receives admission time, failure boundary, and attempt tracking.
|
|
48
|
+
*/
|
|
49
|
+
export declare function registerAdmission(state: StorageEventState, admission: EventAdmission, item: FileEventItem, effects: StorageEventAdmissionEffects): FileEventAttempt | undefined;
|
|
40
50
|
/**
|
|
41
51
|
* Start and track a batch of host events through filtering and queue admission.
|
|
42
52
|
* @param state - Mutable state which owns admission and operation boundaries.
|
|
43
53
|
* @param params - Host watcher events to select.
|
|
44
54
|
* @param ctx - Optional host context forwarded to admitted items.
|
|
45
55
|
* @param effects - Host services used during selection and enqueueing.
|
|
56
|
+
* @param ready - Load ordered buffers before filtering, if initial loading is still needed.
|
|
46
57
|
* @returns A promise for admission completion, not handler completion; rejected admission is reported and remains rejected.
|
|
47
58
|
* @remarks When the manager no longer accepts events, this returns an already-fulfilled promise without admitting them.
|
|
48
59
|
*/
|
|
49
|
-
export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects): Promise<void>;
|
|
60
|
+
export declare function admitStorageEvents(state: StorageEventState, params: readonly FileEvent[], ctx: unknown, effects: StorageEventAdmissionEffects, ready?: () => Promise<unknown> | undefined): Promise<void>;
|
|
61
|
+
/** Register an admission synchronously, including when it must wait for the saved buffers to load. */
|
|
62
|
+
export declare function trackStorageEventAdmission(state: StorageEventState, effects: StorageEventAdmissionEffects, start: (admission: EventAdmission) => Promise<void>): Promise<void>;
|
|
50
63
|
export {};
|
|
@@ -53,7 +53,11 @@ async function selectRename(param, settings, effects) {
|
|
|
53
53
|
return selectRenameFileEvent(param, oldSelected, newSelected);
|
|
54
54
|
}
|
|
55
55
|
async function selectOrdinaryEvent(param, settings, effects) {
|
|
56
|
-
|
|
56
|
+
const path = param.file.path;
|
|
57
|
+
const selected = param.type === "INTERNAL" && effects.isTargetInternal ? !shouldBeIgnored(path) && await effects.isTargetInternal(path) : await isSelectedPath(path, settings, effects);
|
|
58
|
+
if (!selected) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
57
61
|
if (param.type !== "INTERNAL") {
|
|
58
62
|
const size = param.file.stat.size;
|
|
59
63
|
if (effects.isTooLarge(size) && (param.type === "CREATE" || param.type === "CHANGED")) {
|
|
@@ -93,6 +97,7 @@ function registerAdmission(state, admission, item, effects) {
|
|
|
93
97
|
operation.failureBoundary = admission.failureBoundary;
|
|
94
98
|
if (admission.flushRequested) effects.release([operation]);
|
|
95
99
|
admission.operations.set(operation, operation.attempt);
|
|
100
|
+
return operation.attempt;
|
|
96
101
|
}
|
|
97
102
|
async function appendStorageEvents(state, params, ctx, admission, effects) {
|
|
98
103
|
const settings = effects.settings();
|
|
@@ -103,7 +108,14 @@ async function appendStorageEvents(state, params, ctx, admission, effects) {
|
|
|
103
108
|
if (item) registerAdmission(state, admission, item, effects);
|
|
104
109
|
}
|
|
105
110
|
}
|
|
106
|
-
function admitStorageEvents(state, params, ctx, effects) {
|
|
111
|
+
function admitStorageEvents(state, params, ctx, effects, ready) {
|
|
112
|
+
return trackStorageEventAdmission(state, effects, (admission) => {
|
|
113
|
+
const loading = ready?.();
|
|
114
|
+
const append = () => appendStorageEvents(state, params, ctx, admission, effects);
|
|
115
|
+
return loading ? loading.then(append) : append();
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function trackStorageEventAdmission(state, effects, start) {
|
|
107
119
|
if (!state.acceptingEvents) return Promise.resolve();
|
|
108
120
|
const admission = {
|
|
109
121
|
acceptedAt: Date.now(),
|
|
@@ -113,7 +125,7 @@ function admitStorageEvents(state, params, ctx, effects) {
|
|
|
113
125
|
flushRequested: false
|
|
114
126
|
};
|
|
115
127
|
state.admissions.add(admission);
|
|
116
|
-
admission.completion =
|
|
128
|
+
admission.completion = start(admission);
|
|
117
129
|
void admission.completion.then(
|
|
118
130
|
() => state.admissions.delete(admission),
|
|
119
131
|
(error) => {
|
|
@@ -125,5 +137,7 @@ function admitStorageEvents(state, params, ctx, effects) {
|
|
|
125
137
|
}
|
|
126
138
|
export {
|
|
127
139
|
admitStorageEvents,
|
|
128
|
-
|
|
140
|
+
registerAdmission,
|
|
141
|
+
selectRenameFileEvent,
|
|
142
|
+
trackStorageEventAdmission
|
|
129
143
|
};
|
|
@@ -38,8 +38,8 @@ export interface StorageEventAttemptEffects extends StorageEventNotifications {
|
|
|
38
38
|
* @param effects - Host callbacks for snapshots, dependencies, processing, failure, and status.
|
|
39
39
|
* @returns A promise which resolves after the attempt's completion-snapshot step and success settlement, or after
|
|
40
40
|
* a joined attempt settles successfully; rejects with the attempt failure otherwise.
|
|
41
|
-
* @remarks
|
|
42
|
-
*
|
|
41
|
+
* @remarks An ordered entry awaiting commit is observed through its current attempt. Dispatch starts that attempt
|
|
42
|
+
* after commit. For legacy entries, the new attempt starts before the initial intent snapshot. On failure, its batch wait
|
|
43
43
|
* is cancelled, the attempt is failed, and the error is rethrown. Status is refreshed in either case.
|
|
44
44
|
*/
|
|
45
45
|
export declare function processStorageEventAttempt(state: StorageEventState, operation: PendingFileEvent, attempt: FileEventAttempt, effects: StorageEventAttemptEffects): Promise<void>;
|
|
@@ -38,15 +38,15 @@ async function executeAttempt(state, operation, attempt, canProceed, effects) {
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
async function processStorageEventAttempt(state, operation, attempt, effects) {
|
|
41
|
-
|
|
41
|
+
const entry = state.pendingSnapshot.get(operation.event);
|
|
42
|
+
if (attempt.started || attempt.result || state.ordered && !entry.savedBuffer) {
|
|
42
43
|
assertSuccessfulFileEvents([await attempt.completion.promise]);
|
|
43
44
|
return;
|
|
44
45
|
}
|
|
45
46
|
attempt.started = true;
|
|
46
|
-
const entry = state.pendingSnapshot.get(operation.event);
|
|
47
47
|
try {
|
|
48
48
|
const gate = prepareAttempt(state, operation, attempt, effects);
|
|
49
|
-
await effects.takeSnapshot();
|
|
49
|
+
if (!state.ordered) await effects.takeSnapshot();
|
|
50
50
|
assertFileEventAdmission(attempt);
|
|
51
51
|
const canProceed = await gate;
|
|
52
52
|
assertFileEventAdmission(attempt);
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Coordinate
|
|
3
|
-
*
|
|
2
|
+
* Coordinate in-memory dispatch for both the legacy snapshot and the ordered buffer store.
|
|
3
|
+
* The in-memory queue advances dispatch. Persistence retains intent until acknowledgement.
|
|
4
4
|
*/
|
|
5
5
|
import type { FileEventItem } from "../../common/types.js";
|
|
6
6
|
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
7
|
+
import type { PendingStorageEventBuffer } from "../adapters/index.js";
|
|
7
8
|
import { type FileEventAttempt, type OperationResult, type PendingFileEvent } from "./operations.js";
|
|
8
|
-
import { type QueuedFileEvent, type RunQueuedEventsOptions, type StorageEventBuffer, type StorageEventNotifications, type StorageEventState } from "./state.js";
|
|
9
|
+
import { type PendingSnapshotEntry, type QueuedFileEvent, type RunQueuedEventsOptions, type StorageEventBuffer, type StorageEventNotifications, type StorageEventState } from "./state.js";
|
|
9
10
|
/** Host callbacks used by queue ownership, dispatch, finite flush, and restoration. */
|
|
10
11
|
export interface StorageEventQueueEffects extends StorageEventNotifications {
|
|
11
12
|
/** Host-owned event buffer used by admission, dispatch, and retry. */
|
|
@@ -14,6 +15,8 @@ export interface StorageEventQueueEffects extends StorageEventNotifications {
|
|
|
14
15
|
log: LogFunction;
|
|
15
16
|
/** Persist the current intent snapshot. */
|
|
16
17
|
takeSnapshot(): Promise<void>;
|
|
18
|
+
/** Mark the sentinel complete after its predecessors settle. A partially completed array remains replayable. */
|
|
19
|
+
acknowledgeSentinel?(entry: PendingSnapshotEntry): Promise<void>;
|
|
17
20
|
/** Load the prior runtime's saved event intent, if any. */
|
|
18
21
|
loadSnapshot(): Promise<QueuedFileEvent[] | null>;
|
|
19
22
|
/** Enter the host event-processing route for one file event. */
|
|
@@ -30,28 +33,27 @@ export interface StorageEventQueueEffects extends StorageEventNotifications {
|
|
|
30
33
|
fail(operation: PendingFileEvent, error: unknown, attempt: FileEventAttempt): void;
|
|
31
34
|
}
|
|
32
35
|
/**
|
|
33
|
-
*
|
|
34
|
-
* @
|
|
35
|
-
*
|
|
36
|
-
* @param effects - Host buffer, persistence, dispatch, status, and failure callbacks.
|
|
37
|
-
* @returns Nothing; appends a sentinel before DELETE/RENAME, appends the event, and refreshes status synchronously.
|
|
38
|
-
* @remarks Persistence and dispatch run in a background task whose failures are handled here rather than returned.
|
|
39
|
-
* If that task fails while a handler is active, its error is recorded on that attempt and its operation is released
|
|
40
|
-
* so the handler can settle before retry ownership changes; otherwise the attempt is failed immediately.
|
|
36
|
+
* Retain an accepted event and schedule persistence.
|
|
37
|
+
* @remarks Ordered storage stages the event and its marker together. The append owner publishes them to dispatch
|
|
38
|
+
* after commit and settles their attempts on failure. Legacy storage publishes before its background snapshot.
|
|
41
39
|
*/
|
|
42
40
|
export declare function enqueueStorageEvent(state: StorageEventState, event: FileEventItem, effects: StorageEventQueueEffects): void;
|
|
41
|
+
/** Publish a committed array in arrival order and start dispatch. */
|
|
42
|
+
export declare function publishCommittedStorageEvents(state: StorageEventState, events: readonly QueuedFileEvent[], effects: StorageEventQueueEffects): void;
|
|
43
43
|
/**
|
|
44
44
|
* Flush the finite set of operations and admissions visible at entry.
|
|
45
45
|
* @param state - The manager state containing active admissions, retained operations, and the current failure sequence.
|
|
46
46
|
* @param effects - Callbacks for capturing attempts, releasing gates, dispatching, waiting, and reporting failures.
|
|
47
|
+
* @param loading - A pending initial load already requested at this flush boundary.
|
|
47
48
|
* @returns A promise which settles after captured admissions and attempts; rejects with the first rejected admission
|
|
48
49
|
* or, when admissions succeeded, the first failed operation result.
|
|
49
50
|
* @remarks Flush intent is signalled before awaiting active admissions. Current buffered work is retained and batch
|
|
50
51
|
* gates are released before the failure sequence is read for capture; attempts later registered by those admissions
|
|
51
|
-
* are merged without replacing earlier captures.
|
|
52
|
-
*
|
|
52
|
+
* are merged without replacing earlier captures. A load already in progress also contributes its restored
|
|
53
|
+
* operations. Dispatch is then started in the background. Work admitted after the initial capture can remain
|
|
54
|
+
* outside this finite wait.
|
|
53
55
|
*/
|
|
54
|
-
export declare function flushStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects): Promise<void>;
|
|
56
|
+
export declare function flushStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects, loading?: Promise<readonly PendingFileEvent[]>): Promise<void>;
|
|
55
57
|
/**
|
|
56
58
|
* Share queue dispatch and optionally wait for the operations visible at call time.
|
|
57
59
|
* @param state - The manager state providing retained operations and this manager's stable dispatch key.
|
|
@@ -71,3 +73,10 @@ export declare function runBufferedStorageEvents(state: StorageEventState, effec
|
|
|
71
73
|
* failed attempt results are reported by the queue callback.
|
|
72
74
|
*/
|
|
73
75
|
export declare function restoreStorageEvents(effects: StorageEventQueueEffects): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* Register already committed arrays in replay order before exposing their events to dispatch.
|
|
78
|
+
* @remarks Each array shares one remaining-entry count. The last acknowledgement removes its key. A partial
|
|
79
|
+
* failure leaves the original array available for reconciliation by the next runtime.
|
|
80
|
+
* @returns The restored file operations, which callers can include in a flush already in progress.
|
|
81
|
+
*/
|
|
82
|
+
export declare function restoreOrderedStorageEvents(state: StorageEventState, effects: StorageEventQueueEffects, buffers: readonly PendingStorageEventBuffer[]): PendingFileEvent[];
|