@vrtmrz/livesync-commonlib 0.5.0 → 0.6.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.
- package/dist/common/LSError.d.ts +13 -0
- package/dist/common/LSError.js +19 -1
- package/dist/diagnostics/local.d.ts +7 -2
- package/dist/interfaces/DatabaseFileAccess.d.ts +20 -4
- package/dist/interfaces/FileHandler.d.ts +67 -1
- package/dist/interfaces/FileHandler.js +16 -0
- package/dist/interfaces/StorageEventManager.d.ts +7 -0
- package/dist/managers/ChunkFetcher.d.ts +16 -0
- package/dist/managers/ChunkFetcher.js +190 -112
- package/dist/managers/EntryManager/EntryManager.d.ts +7 -0
- package/dist/managers/EntryManager/EntryManager.js +6 -0
- package/dist/managers/EntryManager/EntryManagerImpls.d.ts +9 -5
- package/dist/managers/EntryManager/EntryManagerImpls.js +103 -76
- package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.d.ts +7 -3
- package/dist/managers/LayeredChunkManager/ArrivalWaitLayer.js +83 -16
- package/dist/managers/LayeredChunkManager/DatabaseReadLayer.d.ts +3 -2
- package/dist/managers/LayeredChunkManager/DatabaseReadLayer.js +38 -36
- package/dist/managers/LayeredChunkManager/types.d.ts +15 -1
- package/dist/managers/LayeredChunkManager.d.ts +4 -0
- package/dist/managers/LayeredChunkManager.js +19 -6
- package/dist/managers/LiveSyncManagers.d.ts +2 -0
- package/dist/managers/LiveSyncManagers.js +6 -0
- package/dist/managers/StorageEventManager.d.ts +22 -0
- package/dist/managers/StorageEventManager.js +48 -1
- package/dist/pouchdb/LiveSyncLocalDB.d.ts +32 -0
- package/dist/pouchdb/LiveSyncLocalDB.js +72 -18
- package/dist/pouchdb/LocalDatabaseReadScope.d.ts +24 -0
- package/dist/pouchdb/LocalDatabaseReadScope.js +62 -0
- package/dist/pouchdb/encryption.policy.js +2 -1
- package/dist/pouchdb/pathIdentityCompatibility.d.ts +6 -2
- package/dist/pouchdb/pathIdentityCompatibility.js +15 -10
- package/dist/replication/UnsupportedEncryptedDocumentFormatError.d.ts +13 -0
- package/dist/replication/UnsupportedEncryptedDocumentFormatError.js +28 -0
- package/dist/replication/contentRead.d.ts +3 -0
- package/dist/replication/contentRead.js +4 -0
- package/dist/replication/couchdb/LiveSyncReplicator.d.ts +11 -2
- package/dist/replication/couchdb/LiveSyncReplicator.js +207 -131
- package/dist/replication/index.d.ts +6 -1
- package/dist/replication/index.js +20 -1
- package/dist/serviceFeatures/offlineScanner/files.d.ts +1 -1
- package/dist/serviceFeatures/offlineScanner/files.js +27 -7
- package/dist/serviceFeatures/offlineScanner/scan.d.ts +5 -1
- package/dist/serviceFeatures/offlineScanner/scan.js +2 -1
- package/dist/serviceFeatures/offlineScanner.d.ts +1 -1
- package/dist/serviceFeatures/offlineScanner.js +10 -2
- package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +13 -0
- package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +190 -123
- package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +17 -7
- package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +3 -2
- package/dist/serviceModules/ServiceFileHandlerBase/events.js +9 -9
- package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -9
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +10 -0
- package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +28 -4
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +11 -5
- package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +144 -58
- package/dist/serviceModules/ServiceFileHandlerBase/saving.js +16 -2
- package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +1 -0
- package/dist/serviceModules/ServiceFileHandlerBase.d.ts +7 -2
- package/dist/serviceModules/ServiceFileHandlerBase.js +13 -4
- package/dist/services/base/ControlService.js +1 -5
- package/dist/services/base/DatabaseEventService.d.ts +3 -0
- package/dist/services/base/DatabaseEventService.js +3 -0
- package/dist/services/base/DatabaseService.d.ts +15 -0
- package/dist/services/base/DatabaseService.js +85 -4
- package/dist/services/base/IService.d.ts +18 -1
- package/dist/services/base/KeyValueDBService.d.ts +5 -4
- package/dist/services/base/KeyValueDBService.js +46 -48
- package/dist/services/base/ReplicationService.d.ts +4 -1
- package/dist/services/base/ReplicationService.js +8 -1
- package/dist/services/base/VaultScanResult.d.ts +5 -0
- package/dist/services/lib/HandlerUtils.d.ts +40 -5
- package/dist/services/lib/HandlerUtils.js +52 -4
- package/docs/development.md +8 -0
- package/docs/offline-scanner.md +57 -3
- package/docs/releasing.md +43 -0
- package/package.json +1 -1
|
@@ -4,6 +4,9 @@ import { ServiceBase, type ServiceContext } from "./ServiceBase.js";
|
|
|
4
4
|
* The DatabaseEventService provides methods for handling database lifecycle events.
|
|
5
5
|
*/
|
|
6
6
|
export declare abstract class DatabaseEventService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IDatabaseEventService {
|
|
7
|
+
readonly onBeforeDatabaseResume: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
|
|
8
|
+
readonly onBeforeDatabaseRecovery: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
|
|
9
|
+
readonly onAfterDatabaseRecovery: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
|
|
7
10
|
/**
|
|
8
11
|
* Event triggered when the database is about to be unloaded.
|
|
9
12
|
*/
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { handlers } from "../lib/HandlerUtils.js";
|
|
2
2
|
import { ServiceBase } from "./ServiceBase.js";
|
|
3
3
|
class DatabaseEventService extends ServiceBase {
|
|
4
|
+
onBeforeDatabaseResume = handlers().bailFirstFailure("onBeforeDatabaseResume");
|
|
5
|
+
onBeforeDatabaseRecovery = handlers().bailFirstFailure("onBeforeDatabaseRecovery");
|
|
6
|
+
onAfterDatabaseRecovery = handlers().bailFirstFailure("onAfterDatabaseRecovery");
|
|
4
7
|
/**
|
|
5
8
|
* Event triggered when the database is about to be unloaded.
|
|
6
9
|
*/
|
|
@@ -21,6 +21,11 @@ export declare abstract class DatabaseService<T extends ServiceContext = Service
|
|
|
21
21
|
_log: (msg: unknown, level?: import("octagonal-wheels/common/logger").LOG_LEVEL, key?: string) => void;
|
|
22
22
|
constructor(context: T, dependencies: DatabaseServiceDependencies);
|
|
23
23
|
protected _localDatabase: LiveSyncLocalDB | null;
|
|
24
|
+
private readonly databaseLock;
|
|
25
|
+
private closingRequested;
|
|
26
|
+
private databaseSelection;
|
|
27
|
+
/** Observes a failed local operation; handlers must not retry that operation. */
|
|
28
|
+
readonly onLocalDatabaseError: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(database: LiveSyncLocalDB, error: unknown) => Promise<boolean>>;
|
|
24
29
|
protected services: DatabaseServiceDependencies;
|
|
25
30
|
onOpenDatabase: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(vaultName: string) => Promise<boolean>>;
|
|
26
31
|
/** Called after the active database has been reset and successfully reinitialised. */
|
|
@@ -32,10 +37,20 @@ export declare abstract class DatabaseService<T extends ServiceContext = Service
|
|
|
32
37
|
options: PouchDB.Configuration.DatabaseConfiguration;
|
|
33
38
|
};
|
|
34
39
|
createPouchDBInstance<T extends object>(name?: string, options?: PouchDB.Configuration.DatabaseConfiguration): PouchDB.Database<T>;
|
|
40
|
+
private selectDatabase;
|
|
41
|
+
private isSelectedDatabase;
|
|
35
42
|
openDatabase(params: openDatabaseParameters): Promise<boolean>;
|
|
43
|
+
/** Replace only the failed lifetime; a queued duplicate cannot close its replacement. */
|
|
44
|
+
reopenDatabase(database: LiveSyncLocalDB, params: openDatabaseParameters): Promise<boolean>;
|
|
45
|
+
/** Check only an initialised, currently owned Pouch. This does not construct a Pouch instance. */
|
|
46
|
+
canReadCurrentDatabaseInfo(): Promise<boolean>;
|
|
47
|
+
/** Closing participates in the same owner lock as opening and recovery. */
|
|
48
|
+
closeDatabase(): Promise<void>;
|
|
49
|
+
private openDatabaseUnlocked;
|
|
36
50
|
isDatabaseReady(): boolean;
|
|
37
51
|
private discardFailedActiveDatabase;
|
|
38
52
|
resetDatabase(): Promise<boolean>;
|
|
53
|
+
private resetDatabaseUnlocked;
|
|
39
54
|
/**
|
|
40
55
|
* Reset the database selected by the current settings.
|
|
41
56
|
*
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { withLock } from "octagonal-wheels/concurrency/lock";
|
|
1
2
|
import { ServiceBase } from "./ServiceBase.js";
|
|
2
3
|
import { LiveSyncLocalDB } from "../../pouchdb/LiveSyncLocalDB.js";
|
|
3
4
|
import { handlers } from "../lib/HandlerUtils.js";
|
|
4
5
|
import { createInstanceLogFunction } from "../lib/logUtils.js";
|
|
5
|
-
import { ExtraSuffixIndexedDB } from "../../common/models/shared.const.js";
|
|
6
|
+
import { ExtraSuffixIndexedDB, SuffixDatabaseName } from "../../common/models/shared.const.js";
|
|
6
7
|
import { LOG_LEVEL_VERBOSE } from "../../common/logger.js";
|
|
7
8
|
class DatabaseService extends ServiceBase {
|
|
8
9
|
_log = createInstanceLogFunction("InjectableDatabaseService");
|
|
@@ -11,6 +12,11 @@ class DatabaseService extends ServiceBase {
|
|
|
11
12
|
this.services = dependencies;
|
|
12
13
|
}
|
|
13
14
|
_localDatabase = null;
|
|
15
|
+
databaseLock = /* @__PURE__ */ Symbol("local-database-lifecycle");
|
|
16
|
+
closingRequested = false;
|
|
17
|
+
databaseSelection;
|
|
18
|
+
/** Observes a failed local operation; handlers must not retry that operation. */
|
|
19
|
+
onLocalDatabaseError = handlers().allSettled("onLocalDatabaseError");
|
|
14
20
|
services;
|
|
15
21
|
// Additional process when opening database, such as initialising managers or local database instance.
|
|
16
22
|
onOpenDatabase = handlers().bailFirstFailure("onOpenDatabase");
|
|
@@ -45,11 +51,74 @@ class DatabaseService extends ServiceBase {
|
|
|
45
51
|
const optionPass = this.modifyDatabaseOptions(settings, name ?? "", options ?? {});
|
|
46
52
|
return new this.services.pouchDB(optionPass.name, optionPass.options);
|
|
47
53
|
}
|
|
54
|
+
selectDatabase() {
|
|
55
|
+
const vaultName = this.services.vault.getVaultName();
|
|
56
|
+
const resolved = this.modifyDatabaseOptions(
|
|
57
|
+
this.services.setting.currentSettings(),
|
|
58
|
+
vaultName + SuffixDatabaseName,
|
|
59
|
+
{}
|
|
60
|
+
);
|
|
61
|
+
return { vaultName, ...resolved };
|
|
62
|
+
}
|
|
63
|
+
isSelectedDatabase(selection) {
|
|
64
|
+
const current = this.selectDatabase();
|
|
65
|
+
return current.name === selection.name && current.options.adapter === selection.options.adapter;
|
|
66
|
+
}
|
|
48
67
|
async openDatabase(params) {
|
|
68
|
+
return await withLock(this.databaseLock, async () => {
|
|
69
|
+
this.closingRequested = false;
|
|
70
|
+
return await this.openDatabaseUnlocked(params);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Replace only the failed lifetime; a queued duplicate cannot close its replacement. */
|
|
74
|
+
async reopenDatabase(database, params) {
|
|
75
|
+
return await withLock(this.databaseLock, async () => {
|
|
76
|
+
if (this.closingRequested || this._localDatabase !== database) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
const selection = this.databaseSelection;
|
|
80
|
+
if (!selection || !this.isSelectedDatabase(selection)) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
database.isReady = false;
|
|
84
|
+
database.stopReads();
|
|
85
|
+
if (params.databaseEvents?.onBeforeDatabaseRecovery && !await params.databaseEvents.onBeforeDatabaseRecovery()) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
if (this.closingRequested || this._localDatabase !== database || !this.isSelectedDatabase(selection)) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
return await this.openDatabaseUnlocked(params, selection);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/** Check only an initialised, currently owned Pouch. This does not construct a Pouch instance. */
|
|
95
|
+
async canReadCurrentDatabaseInfo() {
|
|
96
|
+
const database = this._localDatabase;
|
|
97
|
+
if (this.closingRequested || !database?.isReady || !database.localDatabase) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
await database.readFromDatabase((pouch) => pouch.info());
|
|
101
|
+
return !this.closingRequested && this._localDatabase === database && database.isReady;
|
|
102
|
+
}
|
|
103
|
+
/** Closing participates in the same owner lock as opening and recovery. */
|
|
104
|
+
async closeDatabase() {
|
|
105
|
+
this.closingRequested = true;
|
|
106
|
+
await withLock(this.databaseLock, async () => {
|
|
107
|
+
const database = this._localDatabase;
|
|
108
|
+
if (database) {
|
|
109
|
+
database.onunload();
|
|
110
|
+
await database.close();
|
|
111
|
+
if (this._localDatabase === database) {
|
|
112
|
+
this._localDatabase = null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
async openDatabaseUnlocked(params, selection = this.selectDatabase()) {
|
|
49
118
|
if (this._localDatabase != null) {
|
|
50
119
|
await this._localDatabase.close();
|
|
51
120
|
}
|
|
52
|
-
const vaultName =
|
|
121
|
+
const { vaultName } = selection;
|
|
53
122
|
this._log(this.context.translate("moduleLocalDatabase.logWaitingForReady"));
|
|
54
123
|
const env = {
|
|
55
124
|
services: {
|
|
@@ -59,7 +128,10 @@ class DatabaseService extends ServiceBase {
|
|
|
59
128
|
database: this
|
|
60
129
|
}
|
|
61
130
|
};
|
|
62
|
-
const selectedDatabase = new LiveSyncLocalDB(vaultName, env
|
|
131
|
+
const selectedDatabase = new LiveSyncLocalDB(vaultName, env, {
|
|
132
|
+
createPouchDBInstance: (_name, options) => new this.services.pouchDB(selection.name, { ...options, ...selection.options })
|
|
133
|
+
});
|
|
134
|
+
this.databaseSelection = selection;
|
|
63
135
|
this._localDatabase = selectedDatabase;
|
|
64
136
|
try {
|
|
65
137
|
await this.onOpenDatabase(vaultName);
|
|
@@ -76,7 +148,7 @@ class DatabaseService extends ServiceBase {
|
|
|
76
148
|
}
|
|
77
149
|
}
|
|
78
150
|
isDatabaseReady() {
|
|
79
|
-
return this._localDatabase != null && this._localDatabase.isReady;
|
|
151
|
+
return !this.closingRequested && this._localDatabase != null && this._localDatabase.isReady;
|
|
80
152
|
}
|
|
81
153
|
async discardFailedActiveDatabase(database) {
|
|
82
154
|
if (this._localDatabase === database) {
|
|
@@ -90,6 +162,15 @@ class DatabaseService extends ServiceBase {
|
|
|
90
162
|
}
|
|
91
163
|
}
|
|
92
164
|
async resetDatabase() {
|
|
165
|
+
const selected = this._localDatabase;
|
|
166
|
+
return await withLock(this.databaseLock, () => {
|
|
167
|
+
if (this._localDatabase !== selected) {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
return this.resetDatabaseUnlocked();
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
async resetDatabaseUnlocked() {
|
|
93
174
|
if (!this._localDatabase) {
|
|
94
175
|
return Promise.resolve(true);
|
|
95
176
|
}
|
|
@@ -17,6 +17,7 @@ import type { ActiveReplicatorContext, ContinuousReplicationRequest, Replication
|
|
|
17
17
|
import type { RemoteResourceKind, RemoteResourceMap } from "../../replication/RemoteResource.js";
|
|
18
18
|
import type { CentralRemoteAdministrationRequest, CentralRemoteAdministrationResult } from "../../replication/CentralRemoteAdministration.js";
|
|
19
19
|
import type { HandlerOutcome, MultipleHandlerFunction } from "../lib/HandlerUtils.js";
|
|
20
|
+
import type { FileReflectionResult, ReflectionOperationContext, ReflectionTarget } from "../../interfaces/FileHandler.js";
|
|
20
21
|
import type { VaultScanResult, VaultScanOptions } from "./VaultScanResult.js";
|
|
21
22
|
import type { UICommandRegistry } from "../../uiCommands.js";
|
|
22
23
|
declare global {
|
|
@@ -78,8 +79,14 @@ export interface openDatabaseParameters {
|
|
|
78
79
|
}
|
|
79
80
|
export interface IDatabaseService {
|
|
80
81
|
localDatabase: LiveSyncLocalDB;
|
|
82
|
+
/** Current physical owner, without constructing a database or throwing before open. */
|
|
83
|
+
readonly localDatabaseDirect: LiveSyncLocalDB | null;
|
|
81
84
|
createPouchDBInstance<T extends object>(name?: string, options?: PouchDB.Configuration.DatabaseConfiguration): PouchDB.Database<T>;
|
|
82
85
|
openDatabase(params: openDatabaseParameters): Promise<boolean>;
|
|
86
|
+
reopenDatabase(database: LiveSyncLocalDB, params: openDatabaseParameters): Promise<boolean>;
|
|
87
|
+
canReadCurrentDatabaseInfo(): Promise<boolean>;
|
|
88
|
+
closeDatabase(): Promise<void>;
|
|
89
|
+
onLocalDatabaseError?(database: LiveSyncLocalDB, error: unknown): Promise<boolean>;
|
|
83
90
|
resetDatabase(): Promise<boolean>;
|
|
84
91
|
resetDatabaseForCurrentSettings(params: openDatabaseParameters): Promise<boolean>;
|
|
85
92
|
onDatabaseReset: () => Promise<boolean>;
|
|
@@ -87,6 +94,12 @@ export interface IDatabaseService {
|
|
|
87
94
|
isDatabaseReady(): boolean;
|
|
88
95
|
}
|
|
89
96
|
export interface IDatabaseEventService {
|
|
97
|
+
/** Host foreground gate, before pending file work and replication resume. */
|
|
98
|
+
onBeforeDatabaseResume(): Promise<boolean>;
|
|
99
|
+
/** Stop dispatch and settle accepted host work before a connection is replaced. */
|
|
100
|
+
onBeforeDatabaseRecovery(): Promise<boolean>;
|
|
101
|
+
/** Continue held host work after the connection and pending local edits are ready. */
|
|
102
|
+
onAfterDatabaseRecovery(): Promise<boolean>;
|
|
90
103
|
onUnloadDatabase(db: LiveSyncLocalDB): Promise<boolean>;
|
|
91
104
|
onCloseDatabase(db: LiveSyncLocalDB): Promise<boolean>;
|
|
92
105
|
onDatabaseInitialisation(db: LiveSyncLocalDB): Promise<boolean>;
|
|
@@ -188,10 +201,14 @@ export interface IReplicatorService {
|
|
|
188
201
|
export type ReplicatorFactoryCallback = (settingOverride?: Partial<ObsidianLiveSyncSettings>) => Promise<ReplicatorInstance | undefined | false>;
|
|
189
202
|
export type ReplicatorFactoryHandler = MultipleHandlerFunction<ReplicatorFactoryCallback>;
|
|
190
203
|
export interface IReplicationService {
|
|
191
|
-
processSynchroniseResult(doc: MetaEntry): Promise<
|
|
204
|
+
processSynchroniseResult(doc: MetaEntry, operation?: ReflectionOperationContext): Promise<FileReflectionResult | undefined>;
|
|
192
205
|
processOptionalSynchroniseResult(doc: LoadedEntry): Promise<boolean>;
|
|
193
206
|
processVirtualDocument(docs: PouchDB.Core.ExistingDocument<EntryDoc>): Promise<boolean>;
|
|
194
207
|
onBeforeReplicate(showMessage: boolean): Promise<boolean>;
|
|
208
|
+
/** Notify hosts after a successful finite pull or sync, including zero-change completions. */
|
|
209
|
+
onFiniteReplicationCompleted(): Promise<boolean>;
|
|
210
|
+
/** Notify the owning startup scan that a file's content could not be read. */
|
|
211
|
+
onFileReflectionFailed(target: ReflectionTarget, error: unknown): Promise<boolean>;
|
|
195
212
|
/** Prepare provider state which exists only for the central remote. */
|
|
196
213
|
onPrepareCentralRemoteReplication(showMessage: boolean): Promise<boolean>;
|
|
197
214
|
checkConnectionFailure(failure: ReplicationAttemptFailure): Promise<boolean | "CHECKAGAIN" | undefined>;
|
|
@@ -17,6 +17,8 @@ export interface KeyValueDBDependencies<T extends ServiceContext = ServiceContex
|
|
|
17
17
|
*/
|
|
18
18
|
export declare abstract class KeyValueDBService<T extends ServiceContext = ServiceContext> extends ServiceBase<T> implements IKeyValueDBService {
|
|
19
19
|
private _kvDB;
|
|
20
|
+
private databaseKey;
|
|
21
|
+
private readonly lifecycleLock;
|
|
20
22
|
private _simpleStore;
|
|
21
23
|
get simpleStore(): SimpleStore<unknown, any>;
|
|
22
24
|
get kvDB(): KeyValueDatabase;
|
|
@@ -25,12 +27,11 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
|
|
|
25
27
|
private appLifecycle;
|
|
26
28
|
private openKeyValueDatabase;
|
|
27
29
|
private _log;
|
|
30
|
+
private selectedDatabaseKey;
|
|
28
31
|
private _everyOnResetDatabase;
|
|
29
|
-
private
|
|
32
|
+
private closeKeyValueDB;
|
|
33
|
+
private openSelectedDatabase;
|
|
30
34
|
private openKeyValueDB;
|
|
31
|
-
private _onOtherDatabaseUnload;
|
|
32
|
-
private _onOtherDatabaseClose;
|
|
33
|
-
private _everyOnInitializeDatabase;
|
|
34
35
|
private _everyOnloadAfterLoadSettings;
|
|
35
36
|
constructor(context: T, dependencies: KeyValueDBDependencies<T>);
|
|
36
37
|
/**
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { ServiceBase } from "./ServiceBase.js";
|
|
2
|
-
import {
|
|
2
|
+
import { withLock } from "octagonal-wheels/concurrency/lock";
|
|
3
3
|
import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "../../common/logger.js";
|
|
4
4
|
import { createInstanceLogFunction } from "../lib/logUtils.js";
|
|
5
5
|
class KeyValueDBService extends ServiceBase {
|
|
6
6
|
_kvDB;
|
|
7
|
+
databaseKey;
|
|
8
|
+
lifecycleLock = /* @__PURE__ */ Symbol("key-value-database-lifecycle");
|
|
7
9
|
_simpleStore;
|
|
8
10
|
get simpleStore() {
|
|
9
11
|
if (!this._simpleStore) {
|
|
@@ -22,63 +24,57 @@ class KeyValueDBService extends ServiceBase {
|
|
|
22
24
|
appLifecycle;
|
|
23
25
|
openKeyValueDatabase;
|
|
24
26
|
_log = createInstanceLogFunction("KeyValueDBService");
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
this._kvDB = await this.openKeyValueDatabase(this.vault.getVaultName() + "-livesync-kv");
|
|
32
|
-
await delay(100);
|
|
33
|
-
} catch (e) {
|
|
27
|
+
selectedDatabaseKey() {
|
|
28
|
+
return this.vault.getVaultName() + "-livesync-kv";
|
|
29
|
+
}
|
|
30
|
+
async _everyOnResetDatabase() {
|
|
31
|
+
return await withLock(this.lifecycleLock, async () => {
|
|
32
|
+
const previous = this._kvDB;
|
|
34
33
|
this._kvDB = void 0;
|
|
35
|
-
this.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
34
|
+
this.databaseKey = void 0;
|
|
35
|
+
try {
|
|
36
|
+
await previous?.destroy();
|
|
37
|
+
return await this.openSelectedDatabase();
|
|
38
|
+
} catch (error) {
|
|
39
|
+
this._log("Failed to reset KeyValueDB", LOG_LEVEL_NOTICE);
|
|
40
|
+
this._log(error, LOG_LEVEL_VERBOSE);
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
});
|
|
40
44
|
}
|
|
41
|
-
async
|
|
45
|
+
async closeKeyValueDB() {
|
|
46
|
+
const previous = this._kvDB;
|
|
47
|
+
this._kvDB = void 0;
|
|
48
|
+
this.databaseKey = void 0;
|
|
42
49
|
try {
|
|
43
|
-
await
|
|
50
|
+
await previous?.close();
|
|
44
51
|
return true;
|
|
45
|
-
} catch (
|
|
52
|
+
} catch (error) {
|
|
46
53
|
this._log("Failed to close KeyValueDB", LOG_LEVEL_VERBOSE);
|
|
47
|
-
this._log(
|
|
54
|
+
this._log(error, LOG_LEVEL_VERBOSE);
|
|
48
55
|
return false;
|
|
49
56
|
}
|
|
50
57
|
}
|
|
51
|
-
async
|
|
52
|
-
|
|
58
|
+
async openSelectedDatabase() {
|
|
59
|
+
const selectedKey = this.selectedDatabaseKey();
|
|
60
|
+
if (this._kvDB && this.databaseKey === selectedKey) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
if (!await this.closeKeyValueDB()) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
53
66
|
try {
|
|
54
|
-
await this.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
await yieldMicrotask();
|
|
59
|
-
await delay(100);
|
|
60
|
-
} catch (e) {
|
|
61
|
-
this._kvDB = void 0;
|
|
67
|
+
this._kvDB = await this.openKeyValueDatabase(selectedKey);
|
|
68
|
+
this.databaseKey = selectedKey;
|
|
69
|
+
return true;
|
|
70
|
+
} catch (error) {
|
|
62
71
|
this._log("Failed to open KeyValueDB", LOG_LEVEL_NOTICE);
|
|
63
|
-
this._log(
|
|
72
|
+
this._log(error, LOG_LEVEL_VERBOSE);
|
|
64
73
|
return false;
|
|
65
74
|
}
|
|
66
|
-
return true;
|
|
67
|
-
}
|
|
68
|
-
// Called when another database; LiveSyncLocalDB, is being unloaded.
|
|
69
|
-
// We need to close our KeyValueDB to avoid IndexedDB locking issues.
|
|
70
|
-
async _onOtherDatabaseUnload() {
|
|
71
|
-
if (this._kvDB) await this.tryCloseKvDB();
|
|
72
|
-
return Promise.resolve(true);
|
|
73
|
-
}
|
|
74
|
-
// Also, Called when another database; LiveSyncLocalDB, is being closed.
|
|
75
|
-
// We need to close our KeyValueDB to avoid IndexedDB locking issues.
|
|
76
|
-
async _onOtherDatabaseClose() {
|
|
77
|
-
if (this._kvDB) await this.tryCloseKvDB();
|
|
78
|
-
return Promise.resolve(true);
|
|
79
75
|
}
|
|
80
|
-
|
|
81
|
-
return this.
|
|
76
|
+
openKeyValueDB() {
|
|
77
|
+
return withLock(this.lifecycleLock, () => this.openSelectedDatabase());
|
|
82
78
|
}
|
|
83
79
|
async _everyOnloadAfterLoadSettings() {
|
|
84
80
|
if (!await this.openKeyValueDB()) {
|
|
@@ -96,9 +92,11 @@ class KeyValueDBService extends ServiceBase {
|
|
|
96
92
|
if (dependencies.registerLifecycleHandlers ?? true) {
|
|
97
93
|
this.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));
|
|
98
94
|
this.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));
|
|
99
|
-
this.databaseEvents.onDatabaseInitialisation.addHandler(this.
|
|
100
|
-
this.
|
|
101
|
-
|
|
95
|
+
this.databaseEvents.onDatabaseInitialisation.addHandler(() => this.openKeyValueDB());
|
|
96
|
+
this.appLifecycle.onUnload.addHandler(
|
|
97
|
+
() => withLock(this.lifecycleLock, () => this.closeKeyValueDB()),
|
|
98
|
+
100
|
|
99
|
+
);
|
|
102
100
|
}
|
|
103
101
|
}
|
|
104
102
|
/**
|
|
@@ -37,7 +37,7 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
|
|
|
37
37
|
/**
|
|
38
38
|
* Process a synchronisation result document.
|
|
39
39
|
*/
|
|
40
|
-
readonly processSynchroniseResult: import("../lib/HandlerUtils.js").
|
|
40
|
+
readonly processSynchroniseResult: import("../lib/HandlerUtils.js").FirstApplicableFunction<(doc: import("../../common/types.js").MetaEntry, operation?: import("../../interfaces/FileHandler.js").ReflectionOperationContext) => Promise<import("../../interfaces/FileHandler.js").FileReflectionResult | undefined>>;
|
|
41
41
|
/**
|
|
42
42
|
* Process a synchronisation result document for optional entries i.e., hidden files.
|
|
43
43
|
*/
|
|
@@ -55,6 +55,8 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
|
|
|
55
55
|
* An event triggered before starting replication.
|
|
56
56
|
*/
|
|
57
57
|
readonly onBeforeReplicate: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
|
|
58
|
+
readonly onFiniteReplicationCompleted: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<() => Promise<boolean>>;
|
|
59
|
+
readonly onFileReflectionFailed: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(target: import("../../interfaces/FileHandler.js").ReflectionTarget, error: unknown) => Promise<boolean>>;
|
|
58
60
|
/** Provider preparation which applies only to the central remote. */
|
|
59
61
|
readonly onPrepareCentralRemoteReplication: import("../lib/HandlerUtils.js").BooleanMultipleHandlerFunction<(showMessage: boolean) => Promise<boolean>>;
|
|
60
62
|
/**
|
|
@@ -135,6 +137,7 @@ export declare abstract class ReplicationService<T extends ServiceContext = Serv
|
|
|
135
137
|
*
|
|
136
138
|
* This concrete maintenance entry point is intentionally absent from `IReplicationService`;
|
|
137
139
|
* it is not a general application-readiness bypass.
|
|
140
|
+
* @throws {UnsupportedEncryptedDocumentFormatError} When the remote format prevents the download.
|
|
138
141
|
*/
|
|
139
142
|
replicateAllFromRemoteForRebuild(showingNotice?: boolean): Promise<boolean>;
|
|
140
143
|
private getActiveReplicatorFor;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { UnsupportedEncryptedDocumentFormatError } from "../../replication/UnsupportedEncryptedDocumentFormatError.js";
|
|
1
2
|
import {
|
|
2
3
|
LOG_LEVEL_INFO,
|
|
3
4
|
LOG_LEVEL_NOTICE,
|
|
@@ -152,7 +153,7 @@ class ReplicationService extends ServiceBase {
|
|
|
152
153
|
/**
|
|
153
154
|
* Process a synchronisation result document.
|
|
154
155
|
*/
|
|
155
|
-
processSynchroniseResult = handlers().
|
|
156
|
+
processSynchroniseResult = handlers().firstApplicable("processSynchroniseResult");
|
|
156
157
|
/**
|
|
157
158
|
* Process a synchronisation result document for optional entries i.e., hidden files.
|
|
158
159
|
*/
|
|
@@ -172,6 +173,8 @@ class ReplicationService extends ServiceBase {
|
|
|
172
173
|
* An event triggered before starting replication.
|
|
173
174
|
*/
|
|
174
175
|
onBeforeReplicate = handlers().bailFirstFailure("onBeforeReplicate");
|
|
176
|
+
onFiniteReplicationCompleted = handlers().allSettled("onFiniteReplicationCompleted");
|
|
177
|
+
onFileReflectionFailed = handlers().allOrThrow("onFileReflectionFailed");
|
|
175
178
|
/** Provider preparation which applies only to the central remote. */
|
|
176
179
|
onPrepareCentralRemoteReplication = handlers().bailFirstFailure(
|
|
177
180
|
"onPrepareCentralRemoteReplication"
|
|
@@ -354,6 +357,9 @@ class ReplicationService extends ServiceBase {
|
|
|
354
357
|
expectedContext ??= context;
|
|
355
358
|
return runDirectionalReplication(context, attemptSetting, direction, showingNotice);
|
|
356
359
|
});
|
|
360
|
+
if (direction === DIRECTIONAL_REPLICATION.DOWNLOAD && admission === DIRECTIONAL_REPLICATION_ADMISSION.EXPLICIT_REBUILD && admitted?.status === "failed" && admitted.error instanceof UnsupportedEncryptedDocumentFormatError) {
|
|
361
|
+
throw admitted.error;
|
|
362
|
+
}
|
|
357
363
|
if (admitted) return admitted;
|
|
358
364
|
this._log(`Active replicator not found during directional ${direction}`, LOG_LEVEL_NOTICE);
|
|
359
365
|
return replicationBlocked("no-active-replicator");
|
|
@@ -397,6 +403,7 @@ class ReplicationService extends ServiceBase {
|
|
|
397
403
|
*
|
|
398
404
|
* This concrete maintenance entry point is intentionally absent from `IReplicationService`;
|
|
399
405
|
* it is not a general application-readiness bypass.
|
|
406
|
+
* @throws {UnsupportedEncryptedDocumentFormatError} When the remote format prevents the download.
|
|
400
407
|
*/
|
|
401
408
|
async replicateAllFromRemoteForRebuild(showingNotice = false) {
|
|
402
409
|
if (!this.databaseService.isDatabaseReady()) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ReflectionOperationContext, ReflectionTarget } from "../../interfaces/FileHandler.js";
|
|
1
2
|
/**
|
|
2
3
|
* Outcome of scanning the Vault against the local database.
|
|
3
4
|
*
|
|
@@ -14,5 +15,9 @@ export declare const VaultScanResults: {
|
|
|
14
15
|
export interface VaultScanOptions {
|
|
15
16
|
/** False permits unchanged tracked files to be skipped using storage and revision metadata. */
|
|
16
17
|
strictContentCheck?: boolean;
|
|
18
|
+
/** Existing target scope borrowed by a retained scan retry, including its write checkpoint. */
|
|
19
|
+
reflectionOperation?: ReflectionOperationContext;
|
|
20
|
+
/** Await the owning host's response to an unsuccessful database-to-Vault content read. */
|
|
21
|
+
onReflectionFailed?: (target: ReflectionTarget, error: unknown) => void | Promise<void>;
|
|
17
22
|
}
|
|
18
23
|
export type VaultScanResult = (typeof VaultScanResults)[keyof typeof VaultScanResults];
|
|
@@ -147,7 +147,7 @@ export declare class MultiBinder<T extends (...args: any[]) => any> implements M
|
|
|
147
147
|
* Adds a handler function.
|
|
148
148
|
* Note: The same function is only added once.
|
|
149
149
|
* @param callback The handler function to add.
|
|
150
|
-
* @param priority
|
|
150
|
+
* @param priority Lower numbers run first; equal priorities retain registration order. Use integers.
|
|
151
151
|
* @returns A function to unregister the added handler.
|
|
152
152
|
*
|
|
153
153
|
*/
|
|
@@ -205,6 +205,10 @@ export declare class AllHandler<T extends unknown[]> extends BooleanHandlerBase<
|
|
|
205
205
|
*/
|
|
206
206
|
invoke(...args: T): Promise<boolean>;
|
|
207
207
|
}
|
|
208
|
+
/** Run handlers in order, stopping at false and propagating callback failures. */
|
|
209
|
+
export declare class AllOrThrowHandler<T extends unknown[]> extends BooleanHandlerBase<T> {
|
|
210
|
+
invoke(...args: T): Promise<boolean>;
|
|
211
|
+
}
|
|
208
212
|
/**
|
|
209
213
|
* A handler that preserves a non-boolean continuation result while continuing
|
|
210
214
|
* to give false results and exceptions veto power.
|
|
@@ -257,16 +261,29 @@ export declare class AnySuccessHandler<T extends unknown[]> extends BooleanHandl
|
|
|
257
261
|
invoke(...args: T): Promise<boolean>;
|
|
258
262
|
}
|
|
259
263
|
/**
|
|
260
|
-
*
|
|
264
|
+
* Invoke handlers sequentially until one returns a value other than `false` or `undefined`.
|
|
265
|
+
* Callback failures are logged and skipped; `0`, an empty string, and `null` are results.
|
|
261
266
|
*/
|
|
262
267
|
export declare class FirstResultHandler<T extends unknown[], U> extends MultiBinder<BooleanHandlerFunc<T, U>> {
|
|
263
268
|
/**
|
|
264
|
-
* Invokes handlers sequentially
|
|
269
|
+
* Invokes handlers sequentially, skipping `false`, `undefined`, and callback failures.
|
|
265
270
|
* @param args The arguments to pass to the handlers.
|
|
266
|
-
* @returns The first
|
|
271
|
+
* @returns The first result other than `false` or `undefined`, or `false` when none applies.
|
|
267
272
|
*/
|
|
268
273
|
invoke(...args: T): Promise<U | false>;
|
|
269
274
|
}
|
|
275
|
+
/**
|
|
276
|
+
* Invoke a registration snapshot in priority order until a handler returns a value.
|
|
277
|
+
*
|
|
278
|
+
* @remarks Lower numerical priorities run first, with registration order breaking
|
|
279
|
+
* ties. Returning `undefined` declines the invocation; `false`, `0`, and `null`
|
|
280
|
+
* are results and stop dispatch. Handlers run sequentially, so this is not a
|
|
281
|
+
* race between responses and does not require a single registered handler.
|
|
282
|
+
* Callback errors and rejections propagate unchanged without trying later handlers.
|
|
283
|
+
*/
|
|
284
|
+
export declare class FirstApplicableHandler<T extends unknown[], U> extends MultiBinder<HandlerFunc<T, U>> {
|
|
285
|
+
invoke(...args: T): Promise<Awaited<U> | undefined>;
|
|
286
|
+
}
|
|
270
287
|
/**
|
|
271
288
|
* Invokes registered handlers in priority and registration order until one
|
|
272
289
|
* completes or vetoes. Each invocation uses a snapshot of registrations.
|
|
@@ -343,6 +360,7 @@ export interface MultipleHandlerFunction<TFunc extends (...args: any[]) => U | P
|
|
|
343
360
|
*/
|
|
344
361
|
removeHandler: (callback: TFunc) => void;
|
|
345
362
|
}
|
|
363
|
+
export type FirstApplicableFunction<TFunc extends (...args: any[]) => Promise<unknown>> = ((...args: Parameters<TFunc>) => Promise<Awaited<ReturnType<TFunc>> | undefined>) & Pick<MultipleHandlerFunction<TFunc>, "addHandler" | "removeHandler">;
|
|
346
364
|
export type FirstHandledFunction<TFunc extends (...args: any[]) => AnyHandlerOutcome | Promise<AnyHandlerOutcome>> = ((...args: Parameters<TFunc>) => Promise<Awaited<ReturnType<TFunc>> | {
|
|
347
365
|
kind: "not-applicable";
|
|
348
366
|
}>) & Pick<MultipleHandlerFunction<TFunc>, "addHandler" | "removeHandler"> & {
|
|
@@ -396,12 +414,20 @@ export interface MultiBinderInstance<T extends unknown[], U> extends InvokableHa
|
|
|
396
414
|
export interface BooleanMultiBinderInstance<T extends unknown[]> extends InvokableBooleanHandler<T>, MultiRegisterHandler<T, boolean> {
|
|
397
415
|
}
|
|
398
416
|
export declare function allFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
417
|
+
export declare function allOrThrowFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
399
418
|
export declare function allSettledFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
400
419
|
export declare function bailFirstFailureFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
401
420
|
export declare function bailFirstFailureWithResultFunction<TFunc extends (...args: any[]) => Promise<boolean | string>>(name?: string): MultipleHandlerFunction<TFunc>;
|
|
402
421
|
export declare function allParallelFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
403
422
|
export declare function anySuccessFunction<TFunc extends (...args: any[]) => Promise<boolean>>(name?: string): BooleanMultipleHandlerFunction<TFunc>;
|
|
404
423
|
export declare function firstResultFunction<TFunc extends (...args: any[]) => Promise<unknown>>(name?: string): MultipleHandlerFunction<TFunc>;
|
|
424
|
+
/**
|
|
425
|
+
* Bind an ordered dispatcher which treats only `undefined` as a declined invocation.
|
|
426
|
+
* @param name - The diagnostic name of the handler registration owner.
|
|
427
|
+
* @returns A callable dispatcher with registration and removal methods.
|
|
428
|
+
* @remarks Dispatch order and failure handling follow {@link FirstApplicableHandler}.
|
|
429
|
+
*/
|
|
430
|
+
export declare function firstApplicableFunction<TFunc extends (...args: any[]) => Promise<unknown>>(name?: string): FirstApplicableFunction<TFunc>;
|
|
405
431
|
export declare function firstHandledFunction<TFunc extends (...args: any[]) => AnyHandlerOutcome | Promise<AnyHandlerOutcome>>(name?: string): FirstHandledFunction<TFunc>;
|
|
406
432
|
export declare function dispatchParallelFunction<TFunc extends (...args: any[]) => Promise<unknown[]>>(name?: string): CollectiveHandlerFunction<TFunc>;
|
|
407
433
|
export declare function bindableFunction<TFunc extends (...args: any[]) => any>(name?: string): HandlerFunction<TFunc>;
|
|
@@ -419,6 +445,8 @@ export declare function handlers<T extends object>(): {
|
|
|
419
445
|
* @returns
|
|
420
446
|
*/
|
|
421
447
|
all<K extends FunctionKeys<T>>(name: K): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>;
|
|
448
|
+
/** Stop at a false result; propagate callback errors and rejections unchanged. */
|
|
449
|
+
allOrThrow<K extends FunctionKeys<T>>(name: K): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>;
|
|
422
450
|
/**
|
|
423
451
|
* Create a handler that invokes every added handler sequentially and
|
|
424
452
|
* returns true only if all of them succeed.
|
|
@@ -453,11 +481,18 @@ export declare function handlers<T extends object>(): {
|
|
|
453
481
|
*/
|
|
454
482
|
anySuccess<K extends FunctionKeys<T>>(name: K): BooleanMultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<boolean>>>;
|
|
455
483
|
/**
|
|
456
|
-
* Create a handler
|
|
484
|
+
* Create a handler which skips `false`, `undefined`, and logged callback failures.
|
|
457
485
|
* @param name
|
|
458
486
|
* @returns
|
|
459
487
|
*/
|
|
460
488
|
firstResult<K extends FunctionKeys<T>>(name: K): MultipleHandlerFunction<Extract<T[K], (...args: any[]) => Promise<unknown>>>;
|
|
489
|
+
/**
|
|
490
|
+
* Try handlers in priority and registration order until one returns a value.
|
|
491
|
+
* @param name - The callback on `T` whose invocation a handler may decline with `undefined`.
|
|
492
|
+
* @returns The first non-`undefined` result, or `undefined` when every handler declines.
|
|
493
|
+
* @remarks All other values stop dispatch. Callback failures propagate unchanged.
|
|
494
|
+
*/
|
|
495
|
+
firstApplicable<K extends FunctionKeys<T>>(name: K): FirstApplicableFunction<Extract<T[K], (...args: any[]) => Promise<unknown>>>;
|
|
461
496
|
/**
|
|
462
497
|
* Create a handler that invokes registered handlers until one completes or vetoes.
|
|
463
498
|
* Callback errors and rejections propagate unchanged.
|