@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
|
@@ -10,8 +10,12 @@ import { compatGlobal } from "../../common/coreEnvFunctions.js";
|
|
|
10
10
|
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
|
+
import { ContentReadError } from "../../common/LSError.js";
|
|
14
|
+
function readFromDatabase(readScope, operation) {
|
|
15
|
+
return readScope ? readScope.run(operation) : operation();
|
|
16
|
+
}
|
|
13
17
|
async function createChunks(managers, dispFilename, note) {
|
|
14
|
-
const { chunkManager, splitter } = managers;
|
|
18
|
+
const { chunkManager, splitter, log = Logger } = managers;
|
|
15
19
|
let bufferedChunk = [];
|
|
16
20
|
let bufferedSize = 0;
|
|
17
21
|
let writeCount = 0;
|
|
@@ -26,7 +30,7 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
26
30
|
let writeChars = 0;
|
|
27
31
|
const flushBufferedChunks = async () => {
|
|
28
32
|
if (bufferedChunk.length === 0) {
|
|
29
|
-
|
|
33
|
+
log(`No chunks to flush for ${dispFilename}`, LOG_LEVEL_VERBOSE);
|
|
30
34
|
return true;
|
|
31
35
|
}
|
|
32
36
|
const writeBuf = [...bufferedChunk];
|
|
@@ -41,7 +45,7 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
41
45
|
note._id
|
|
42
46
|
);
|
|
43
47
|
if (result.result === false) {
|
|
44
|
-
|
|
48
|
+
log(`Failed to write buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);
|
|
45
49
|
return false;
|
|
46
50
|
}
|
|
47
51
|
totalWritingCount++;
|
|
@@ -49,13 +53,13 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
49
53
|
resultCachedCount += result.processed.cached;
|
|
50
54
|
duplicatedCount += result.processed.duplicated;
|
|
51
55
|
writeChars += writeBuf.map((e) => e.data.length).reduce((a, b) => a + b, 0);
|
|
52
|
-
|
|
56
|
+
log(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`, LOG_LEVEL_VERBOSE);
|
|
53
57
|
return true;
|
|
54
58
|
};
|
|
55
59
|
const flushIfNeeded = async () => {
|
|
56
60
|
if (bufferedSize > MAX_WRITE_SIZE) {
|
|
57
61
|
if (!await flushBufferedChunks()) {
|
|
58
|
-
|
|
62
|
+
log(`Failed to flush buffered chunks for ${dispFilename}`, LOG_LEVEL_NOTICE);
|
|
59
63
|
return false;
|
|
60
64
|
}
|
|
61
65
|
}
|
|
@@ -89,8 +93,8 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
89
93
|
}
|
|
90
94
|
}
|
|
91
95
|
} catch (ex) {
|
|
92
|
-
|
|
93
|
-
|
|
96
|
+
log(`Error processing pieces for ${dispFilename}`);
|
|
97
|
+
log(ex, LOG_LEVEL_VERBOSE);
|
|
94
98
|
return false;
|
|
95
99
|
}
|
|
96
100
|
if (!await flushBufferedChunks()) {
|
|
@@ -98,12 +102,12 @@ async function createChunks(managers, dispFilename, note) {
|
|
|
98
102
|
}
|
|
99
103
|
const dataSize = note.data.size;
|
|
100
104
|
const stats = `(\u2728: ${newCount}, \u{1F5C3}\uFE0F: ${cachedCount} (${resultCachedCount}) / \u{1F5C4}\uFE0F: ${writeCount}, \u267B:${duplicatedCount})`;
|
|
101
|
-
|
|
105
|
+
log(
|
|
102
106
|
`Chunks processed for ${dispFilename} (${dataSize}): \u{1F4DA}:${totalChunkCount} (${createChunkCount}) , \u{1F4E5}:${totalWritingCount} ${stats}`,
|
|
103
107
|
LOG_LEVEL_VERBOSE
|
|
104
108
|
);
|
|
105
109
|
if (dataSize > 0 && totalWritingCount === 0) {
|
|
106
|
-
|
|
110
|
+
log(
|
|
107
111
|
`No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,
|
|
108
112
|
LOG_LEVEL_NOTICE
|
|
109
113
|
);
|
|
@@ -131,12 +135,12 @@ async function putDBEntryAsIndependentRoot(host, managers, note) {
|
|
|
131
135
|
return await putDBEntryInternal(host, managers, note, false, { mode: "independent-root" });
|
|
132
136
|
}
|
|
133
137
|
async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarget) {
|
|
134
|
-
const { localDatabase, chunkManager, splitter } = managers;
|
|
138
|
+
const { localDatabase, readScope, chunkManager, splitter, log = Logger } = managers;
|
|
135
139
|
const filename = host.services.path.id2path(note._id, note);
|
|
136
140
|
const dispFilename = stripAllPrefixes(filename);
|
|
137
141
|
if (!note.eden) note.eden = {};
|
|
138
142
|
if (!isTargetFile(host, filename)) {
|
|
139
|
-
|
|
143
|
+
log(`File skipped:${dispFilename}`, LOG_LEVEL_VERBOSE);
|
|
140
144
|
return false;
|
|
141
145
|
}
|
|
142
146
|
const data = note.data instanceof Blob ? note.data : createTextBlob(note.data);
|
|
@@ -171,7 +175,7 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
|
|
|
171
175
|
newDoc._rev = revisionTarget.baseRevision;
|
|
172
176
|
} else if (revisionTarget.mode === "latest") {
|
|
173
177
|
try {
|
|
174
|
-
const old = await localDatabase.get(newDoc._id);
|
|
178
|
+
const old = await readFromDatabase(readScope, () => localDatabase.get(newDoc._id));
|
|
175
179
|
newDoc._rev = old._rev;
|
|
176
180
|
} catch (ex) {
|
|
177
181
|
if (isErrorOfMissingDoc(ex)) {
|
|
@@ -186,7 +190,10 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
|
|
|
186
190
|
newDoc._rev = `1-${rootId}`;
|
|
187
191
|
const imported = { ...newDoc, _revisions: { start: 1, ids: [rootId] } };
|
|
188
192
|
await localDatabase.bulkDocs([imported], { new_edits: false });
|
|
189
|
-
const stored = await
|
|
193
|
+
const stored = await readFromDatabase(
|
|
194
|
+
readScope,
|
|
195
|
+
() => localDatabase.get(newDoc._id, { rev: newDoc._rev })
|
|
196
|
+
);
|
|
190
197
|
return stored._rev === newDoc._rev ? { id: newDoc._id, ok: true, rev: newDoc._rev } : false;
|
|
191
198
|
}
|
|
192
199
|
const r = revisionTarget.mode === "live-base" ? await localDatabase.put(newDoc) : await localDatabase.put(newDoc, { force: true });
|
|
@@ -198,10 +205,10 @@ async function putDBEntryInternal(host, managers, note, onlyChunks, revisionTarg
|
|
|
198
205
|
}) ?? false;
|
|
199
206
|
});
|
|
200
207
|
if (result === false) {
|
|
201
|
-
|
|
208
|
+
log(`Failed to write document ${dispFilename}`, LOG_LEVEL_NOTICE);
|
|
202
209
|
return false;
|
|
203
210
|
}
|
|
204
|
-
|
|
211
|
+
log(`Document saved: ${dispFilename} (${result.id.substring(0, 8)}-${result.rev})`, LOG_LEVEL_VERBOSE);
|
|
205
212
|
return result;
|
|
206
213
|
}
|
|
207
214
|
function isTargetFile(host, filenameSrc) {
|
|
@@ -241,7 +248,7 @@ async function prepareChunk({ chunkManager, hashManager }, piece) {
|
|
|
241
248
|
const chunkId = await hashManager.computeHash(piece);
|
|
242
249
|
return { isNew: true, id: `${IDPrefixes.Chunk}${chunkId}`, piece };
|
|
243
250
|
}
|
|
244
|
-
async function getDBEntryMetaByPath(host, { localDatabase }, path, opt, includeDeleted = false) {
|
|
251
|
+
async function getDBEntryMetaByPath(host, { localDatabase, readScope }, path, opt, includeDeleted = false) {
|
|
245
252
|
if (!isTargetFile(host, path)) {
|
|
246
253
|
return false;
|
|
247
254
|
}
|
|
@@ -250,18 +257,21 @@ async function getDBEntryMetaByPath(host, { localDatabase }, path, opt, includeD
|
|
|
250
257
|
let obj = null;
|
|
251
258
|
try {
|
|
252
259
|
if (opt) {
|
|
253
|
-
obj = await localDatabase.get(id, opt);
|
|
260
|
+
obj = await readFromDatabase(readScope, () => localDatabase.get(id, opt));
|
|
254
261
|
} else {
|
|
255
|
-
obj = await localDatabase.get(id);
|
|
262
|
+
obj = await readFromDatabase(readScope, () => localDatabase.get(id));
|
|
256
263
|
}
|
|
257
264
|
} catch (ex) {
|
|
258
265
|
if (!includeDeleted || opt?.rev !== void 0 || !isErrorOfMissingDoc(ex)) throw ex;
|
|
259
266
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
260
|
-
const result = await localDatabase.allDocs({ keys: [id] });
|
|
267
|
+
const result = await readFromDatabase(readScope, () => localDatabase.allDocs({ keys: [id] }));
|
|
261
268
|
const row = result.rows[0];
|
|
262
269
|
if (!row || !("value" in row) || !row.value.rev) return false;
|
|
263
|
-
const candidate = await
|
|
264
|
-
|
|
270
|
+
const candidate = await readFromDatabase(
|
|
271
|
+
readScope,
|
|
272
|
+
() => localDatabase.get(id, { ...opt, rev: row.value.rev })
|
|
273
|
+
);
|
|
274
|
+
const current = (await readFromDatabase(readScope, () => localDatabase.allDocs({ keys: [id] }))).rows[0];
|
|
265
275
|
if (!current || !("value" in current) || !current.value.rev) return false;
|
|
266
276
|
if (current.value.rev === candidate._rev) {
|
|
267
277
|
obj = candidate;
|
|
@@ -307,7 +317,7 @@ async function getDBEntryMetaByPath(host, { localDatabase }, path, opt, includeD
|
|
|
307
317
|
if (isErrorOfMissingDoc(ex)) {
|
|
308
318
|
return false;
|
|
309
319
|
}
|
|
310
|
-
throw ex;
|
|
320
|
+
throw new ContentReadError({ documentId: id, revision: opt?.rev, resources: ["local-database"], cause: ex });
|
|
311
321
|
}
|
|
312
322
|
return false;
|
|
313
323
|
}
|
|
@@ -334,11 +344,11 @@ function complementEntryMeta(note) {
|
|
|
334
344
|
};
|
|
335
345
|
return doc;
|
|
336
346
|
}
|
|
337
|
-
function respondOldFashionedEntry(note, dump
|
|
347
|
+
function respondOldFashionedEntry(note, dump, log) {
|
|
338
348
|
const doc = complementEntryMeta(note);
|
|
339
349
|
if (dump) {
|
|
340
|
-
|
|
341
|
-
|
|
350
|
+
log(`--Old fashioned document--`);
|
|
351
|
+
log(doc);
|
|
342
352
|
}
|
|
343
353
|
return doc;
|
|
344
354
|
}
|
|
@@ -382,24 +392,36 @@ function computeChunkRetrievalMethod(waitForReady, settings, localOnly = false)
|
|
|
382
392
|
preventRemoteRequest: !isOnDemandFetchEnabled
|
|
383
393
|
};
|
|
384
394
|
}
|
|
385
|
-
async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, filename, meta, dump, waitForReady, localOnly = false) {
|
|
386
|
-
const dispFilename = stripAllPrefixes(filename);
|
|
395
|
+
async function respondEntryFromMeta({ localDatabase, readScope, chunkManager, log = Logger }, settings, filename, meta, dump, waitForReady, localOnly = false) {
|
|
387
396
|
const deleted = meta.deleted ?? meta._deleted ?? void 0;
|
|
388
397
|
if (dump) {
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
conflicts
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
+
let conflicts;
|
|
399
|
+
try {
|
|
400
|
+
conflicts = await readFromDatabase(
|
|
401
|
+
readScope,
|
|
402
|
+
() => localDatabase.get(meta._id, {
|
|
403
|
+
rev: meta._rev,
|
|
404
|
+
conflicts: true,
|
|
405
|
+
revs_info: true
|
|
406
|
+
})
|
|
407
|
+
);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw new ContentReadError({
|
|
410
|
+
documentId: meta._id,
|
|
411
|
+
revision: meta._rev,
|
|
412
|
+
resources: ["local-database"],
|
|
413
|
+
cause: error
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
log("-- Conflicts --");
|
|
417
|
+
log(conflicts._conflicts ?? "No conflicts");
|
|
418
|
+
log("-- Revs info -- ");
|
|
419
|
+
log(conflicts._revs_info);
|
|
398
420
|
}
|
|
399
421
|
try {
|
|
400
422
|
if (dump) {
|
|
401
|
-
|
|
402
|
-
|
|
423
|
+
log(`--Bare document--`);
|
|
424
|
+
log(meta);
|
|
403
425
|
}
|
|
404
426
|
let edenChunks = {};
|
|
405
427
|
if (meta.eden && Object.keys(meta.eden).length > 0) {
|
|
@@ -425,8 +447,14 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
|
|
|
425
447
|
},
|
|
426
448
|
edenChunks
|
|
427
449
|
);
|
|
428
|
-
|
|
429
|
-
|
|
450
|
+
const unavailableCount = chunks.filter((entry) => entry === false).length;
|
|
451
|
+
if (unavailableCount > 0) {
|
|
452
|
+
throw new ContentReadError({
|
|
453
|
+
documentId: meta._id,
|
|
454
|
+
revision: meta._rev,
|
|
455
|
+
resources: [],
|
|
456
|
+
cause: new Error("Required Chunks are unavailable")
|
|
457
|
+
});
|
|
430
458
|
}
|
|
431
459
|
const doc = {
|
|
432
460
|
data: chunks.map((e) => e.data),
|
|
@@ -444,27 +472,27 @@ async function respondEntryFromMeta({ localDatabase, chunkManager }, settings, f
|
|
|
444
472
|
type: meta.type
|
|
445
473
|
};
|
|
446
474
|
if (dump) {
|
|
447
|
-
|
|
448
|
-
|
|
475
|
+
log(`--Loaded Document--`);
|
|
476
|
+
log(doc);
|
|
449
477
|
}
|
|
450
478
|
return doc;
|
|
451
|
-
} catch (
|
|
452
|
-
if (
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
479
|
+
} catch (error) {
|
|
480
|
+
if (error instanceof ContentReadError) {
|
|
481
|
+
if (error.failure.documentId === meta._id && error.failure.revision === meta._rev) {
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
throw new ContentReadError({
|
|
485
|
+
documentId: meta._id,
|
|
486
|
+
revision: meta._rev,
|
|
487
|
+
resources: error.failure.resources,
|
|
488
|
+
cause: error
|
|
489
|
+
});
|
|
458
490
|
}
|
|
459
|
-
|
|
460
|
-
`Something went wrong on reading ${dispFilename}(${meta._id.substring(0, 8)}) from database:`,
|
|
461
|
-
LOG_LEVEL_NOTICE
|
|
462
|
-
);
|
|
463
|
-
Logger(ex);
|
|
491
|
+
throw new ContentReadError({ documentId: meta._id, revision: meta._rev, resources: [], cause: error });
|
|
464
492
|
}
|
|
465
|
-
return false;
|
|
466
493
|
}
|
|
467
|
-
async function getDBEntryFromMeta(host,
|
|
494
|
+
async function getDBEntryFromMeta(host, managers, meta, dump = false, waitForReady = true, localOnly = false) {
|
|
495
|
+
const log = managers.log ?? Logger;
|
|
468
496
|
const filename = host.services.path.id2path(meta._id, meta);
|
|
469
497
|
if (!isTargetFile(host, filename)) {
|
|
470
498
|
return false;
|
|
@@ -472,18 +500,10 @@ async function getDBEntryFromMeta(host, { localDatabase, chunkManager }, meta, d
|
|
|
472
500
|
const settings = host.services.setting.currentSettings();
|
|
473
501
|
if (isLegacyNote(meta)) {
|
|
474
502
|
const note = meta;
|
|
475
|
-
return respondOldFashionedEntry(note, dump);
|
|
503
|
+
return respondOldFashionedEntry(note, dump, log);
|
|
476
504
|
}
|
|
477
505
|
if (meta.type == "newnote" || meta.type == "plain") {
|
|
478
|
-
return await respondEntryFromMeta(
|
|
479
|
-
{ localDatabase, chunkManager },
|
|
480
|
-
settings,
|
|
481
|
-
filename,
|
|
482
|
-
meta,
|
|
483
|
-
dump,
|
|
484
|
-
waitForReady,
|
|
485
|
-
localOnly
|
|
486
|
-
);
|
|
506
|
+
return await respondEntryFromMeta(managers, settings, filename, meta, dump, waitForReady, localOnly);
|
|
487
507
|
}
|
|
488
508
|
return false;
|
|
489
509
|
}
|
|
@@ -495,7 +515,9 @@ async function getDBEntryByPath(host, managers, path, opt, dump = false, waitFor
|
|
|
495
515
|
return false;
|
|
496
516
|
}
|
|
497
517
|
}
|
|
498
|
-
async function deleteDBEntryByPath(host,
|
|
518
|
+
async function deleteDBEntryByPath(host, managers, path, opt) {
|
|
519
|
+
const { localDatabase, readScope } = managers;
|
|
520
|
+
const log = managers.log ?? Logger;
|
|
499
521
|
if (!isTargetFile(host, path)) {
|
|
500
522
|
return false;
|
|
501
523
|
}
|
|
@@ -505,9 +527,9 @@ async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
|
|
|
505
527
|
const settings = host.services.setting.currentSettings();
|
|
506
528
|
let obj = null;
|
|
507
529
|
if (opt) {
|
|
508
|
-
obj = await localDatabase.get(id, opt);
|
|
530
|
+
obj = await readFromDatabase(readScope, () => localDatabase.get(id, opt));
|
|
509
531
|
} else {
|
|
510
|
-
obj = await localDatabase.get(id);
|
|
532
|
+
obj = await readFromDatabase(readScope, () => localDatabase.get(id));
|
|
511
533
|
}
|
|
512
534
|
const revDeletion = opt && ("rev" in opt ? opt.rev : "") != "";
|
|
513
535
|
if (obj.type && obj.type == "leaf") {
|
|
@@ -516,7 +538,7 @@ async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
|
|
|
516
538
|
if (!obj.type || obj.type && obj.type == "notes") {
|
|
517
539
|
obj._deleted = true;
|
|
518
540
|
const r = await localDatabase.put(obj, { force: !revDeletion });
|
|
519
|
-
|
|
541
|
+
log(`Entry removed: ${path} (${obj._id.substring(0, 8)}-${r.rev}) `);
|
|
520
542
|
return true;
|
|
521
543
|
}
|
|
522
544
|
if (obj.type == "newnote" || obj.type == "plain") {
|
|
@@ -530,7 +552,7 @@ async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
|
|
|
530
552
|
}
|
|
531
553
|
}
|
|
532
554
|
const r = await localDatabase.put(obj, { force: !revDeletion });
|
|
533
|
-
|
|
555
|
+
log(
|
|
534
556
|
`Entry removed: [${revDeletion ? "REV" : "DEL"}] ${path} (${obj._id.substring(0, 8)}-${r.rev})`
|
|
535
557
|
);
|
|
536
558
|
return true;
|
|
@@ -545,16 +567,21 @@ async function deleteDBEntryByPath(host, { localDatabase }, path, opt) {
|
|
|
545
567
|
throw ex;
|
|
546
568
|
}
|
|
547
569
|
}
|
|
548
|
-
async function storeDeletionByPathAtRevision(host,
|
|
570
|
+
async function storeDeletionByPathAtRevision(host, managers, path, baseRevision) {
|
|
571
|
+
const { localDatabase, readScope } = managers;
|
|
572
|
+
const log = managers.log ?? Logger;
|
|
549
573
|
if (!isTargetFile(host, path)) {
|
|
550
574
|
return false;
|
|
551
575
|
}
|
|
552
576
|
const id = await host.services.path.path2id(path);
|
|
553
577
|
try {
|
|
554
578
|
return await serialized("file:" + path, async () => {
|
|
555
|
-
const obj = await
|
|
556
|
-
|
|
557
|
-
|
|
579
|
+
const obj = await readFromDatabase(
|
|
580
|
+
readScope,
|
|
581
|
+
() => localDatabase.get(id, {
|
|
582
|
+
rev: baseRevision
|
|
583
|
+
})
|
|
584
|
+
);
|
|
558
585
|
if (obj.type === "leaf") {
|
|
559
586
|
return false;
|
|
560
587
|
}
|
|
@@ -562,7 +589,7 @@ async function storeDeletionByPathAtRevision(host, { localDatabase }, path, base
|
|
|
562
589
|
obj.deleted = true;
|
|
563
590
|
obj.mtime = Date.now();
|
|
564
591
|
const result = await localDatabase.put(obj, { force: true });
|
|
565
|
-
|
|
592
|
+
log(`Entry soft-deleted from revision: ${path} (${obj._id.substring(0, 8)}-${result.rev})`);
|
|
566
593
|
return result;
|
|
567
594
|
}) ?? false;
|
|
568
595
|
} catch (ex) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { DocumentID, EntryLeaf } from "../../common/types.js";
|
|
2
2
|
import type { IReadLayer } from "./ChunkLayerInterfaces.js";
|
|
3
|
-
import type { ChunkReadOptions } from "./types.js";
|
|
3
|
+
import type { ChunkReadOptions, ChunkDeliveryFailure } from "./types.js";
|
|
4
4
|
import { ChunkDeliveryCoordinator } from "../ChunkDeliveryCoordinator.js";
|
|
5
|
+
import type { LogFunction } from "../../services/lib/logUtils.js";
|
|
5
6
|
export type ChunkAvailabilityRecheck = (ids: readonly DocumentID[]) => Promise<readonly (EntryLeaf | false)[]>;
|
|
6
7
|
/**
|
|
7
8
|
* Waits only for a delivery lifecycle which is already observable when the
|
|
@@ -9,19 +10,22 @@ export type ChunkAvailabilityRecheck = (ids: readonly DocumentID[]) => Promise<r
|
|
|
9
10
|
*/
|
|
10
11
|
export declare class ArrivalWaitLayer implements IReadLayer {
|
|
11
12
|
private readonly recheckAvailability?;
|
|
13
|
+
private readonly log;
|
|
12
14
|
private readonly waitingMap;
|
|
13
15
|
private readonly eventEmitter;
|
|
14
16
|
private readonly deliveryCoordinator;
|
|
15
17
|
private readonly ownsDeliveryCoordinator;
|
|
16
18
|
private readonly stopObservingActivity;
|
|
17
|
-
constructor(eventEmitter: (eventName: string, data: DocumentID[]) => void, deliveryCoordinator?: ChunkDeliveryCoordinator, recheckAvailability?: ChunkAvailabilityRecheck);
|
|
19
|
+
constructor(eventEmitter: (eventName: string, data: DocumentID[]) => void, deliveryCoordinator?: ChunkDeliveryCoordinator, recheckAvailability?: ChunkAvailabilityRecheck, log?: LogFunction);
|
|
18
20
|
private enqueueWaiting;
|
|
19
21
|
private settle;
|
|
20
22
|
private settleAfterObservedActivity;
|
|
21
23
|
private refreshActivity;
|
|
22
24
|
/** Handle a chunk document becoming available. */
|
|
23
25
|
onChunkArrived(doc: EntryLeaf, deleted?: boolean): void;
|
|
24
|
-
/**
|
|
26
|
+
/** Adapt the shared producer event into the waiting read's eventual rejection. */
|
|
27
|
+
onChunkFailed(id: DocumentID, failure: ChunkDeliveryFailure): void;
|
|
28
|
+
/** A missing response cannot end another finite producer's opportunity to deliver. */
|
|
25
29
|
onMissingChunk(id: DocumentID): void;
|
|
26
30
|
read(ids: DocumentID[], options: ChunkReadOptions, next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>): Promise<(EntryLeaf | false)[]>;
|
|
27
31
|
clearWaiting(): void;
|
|
@@ -1,15 +1,27 @@
|
|
|
1
1
|
import { promiseWithResolvers } from "octagonal-wheels/promises";
|
|
2
|
+
import { ContentReadError } from "../../common/LSError.js";
|
|
2
3
|
import { ChunkDeliveryCoordinator } from "../ChunkDeliveryCoordinator.js";
|
|
3
4
|
import { LOG_LEVEL_VERBOSE, Logger } from "../../common/logger.js";
|
|
5
|
+
function combineDeliveryFailures(previous, current) {
|
|
6
|
+
if (!previous) {
|
|
7
|
+
return current;
|
|
8
|
+
}
|
|
9
|
+
return {
|
|
10
|
+
resources: previous.resources.length === 0 || current.resources.length === 0 ? [] : [.../* @__PURE__ */ new Set([...previous.resources, ...current.resources])],
|
|
11
|
+
cause: new AggregateError([previous.cause, current.cause], "Chunk delivery failed")
|
|
12
|
+
};
|
|
13
|
+
}
|
|
4
14
|
class ArrivalWaitLayer {
|
|
5
|
-
constructor(eventEmitter, deliveryCoordinator, recheckAvailability) {
|
|
15
|
+
constructor(eventEmitter, deliveryCoordinator, recheckAvailability, log = Logger) {
|
|
6
16
|
this.recheckAvailability = recheckAvailability;
|
|
17
|
+
this.log = log;
|
|
7
18
|
this.eventEmitter = eventEmitter;
|
|
8
19
|
this.deliveryCoordinator = deliveryCoordinator ?? new ChunkDeliveryCoordinator();
|
|
9
20
|
this.ownsDeliveryCoordinator = deliveryCoordinator === void 0;
|
|
10
21
|
this.stopObservingActivity = this.deliveryCoordinator.onChanged((ids) => this.refreshActivity(ids));
|
|
11
22
|
}
|
|
12
23
|
recheckAvailability;
|
|
24
|
+
log;
|
|
13
25
|
waitingMap = /* @__PURE__ */ new Map();
|
|
14
26
|
eventEmitter;
|
|
15
27
|
deliveryCoordinator;
|
|
@@ -17,37 +29,62 @@ class ArrivalWaitLayer {
|
|
|
17
29
|
stopObservingActivity;
|
|
18
30
|
enqueueWaiting(id) {
|
|
19
31
|
const previous = this.waitingMap.get(id);
|
|
20
|
-
if (previous)
|
|
32
|
+
if (previous) {
|
|
33
|
+
return previous.resolver.promise;
|
|
34
|
+
}
|
|
21
35
|
const resolver = promiseWithResolvers();
|
|
22
|
-
this.waitingMap.set(id, {
|
|
36
|
+
this.waitingMap.set(id, {
|
|
37
|
+
activityVersion: 0,
|
|
38
|
+
observedActivity: false,
|
|
39
|
+
resolver
|
|
40
|
+
});
|
|
23
41
|
return resolver.promise;
|
|
24
42
|
}
|
|
25
|
-
settle(id, value) {
|
|
43
|
+
settle(id, value, failure) {
|
|
26
44
|
const queue = this.waitingMap.get(id);
|
|
27
|
-
if (!queue)
|
|
45
|
+
if (!queue) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
28
48
|
this.waitingMap.delete(id);
|
|
29
|
-
queue.
|
|
49
|
+
const terminalFailure = failure ?? queue.failure;
|
|
50
|
+
if (!value && terminalFailure) {
|
|
51
|
+
queue.resolver.reject(new ContentReadError({ documentId: id, ...terminalFailure }));
|
|
52
|
+
} else {
|
|
53
|
+
queue.resolver.resolve(value);
|
|
54
|
+
}
|
|
30
55
|
}
|
|
31
56
|
async settleAfterObservedActivity(ids) {
|
|
32
57
|
const candidates = ids.flatMap((id) => {
|
|
33
58
|
const queue = this.waitingMap.get(id);
|
|
34
59
|
if (!queue?.observedActivity || this.deliveryCoordinator.isActivityActiveFor(id)) return [];
|
|
35
60
|
const version = ++queue.activityVersion;
|
|
36
|
-
return [{ id, version }];
|
|
61
|
+
return [{ id, version, queue }];
|
|
37
62
|
});
|
|
38
63
|
if (candidates.length === 0) return;
|
|
39
64
|
let results;
|
|
40
65
|
try {
|
|
41
66
|
results = this.recheckAvailability ? await this.recheckAvailability(candidates.map(({ id }) => id)) : candidates.map(() => false);
|
|
42
67
|
} catch (error) {
|
|
43
|
-
|
|
44
|
-
|
|
68
|
+
this.log(
|
|
69
|
+
"Could not recheck chunk availability after finite delivery activity completed.",
|
|
70
|
+
LOG_LEVEL_VERBOSE
|
|
71
|
+
);
|
|
72
|
+
this.log(error, LOG_LEVEL_VERBOSE);
|
|
73
|
+
for (const { id, version, queue } of candidates) {
|
|
74
|
+
if (this.waitingMap.get(id) === queue && queue.activityVersion === version) {
|
|
75
|
+
queue.failure = combineDeliveryFailures(queue.failure, {
|
|
76
|
+
resources: error instanceof ContentReadError ? error.failure.resources : ["local-database"],
|
|
77
|
+
cause: error
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
}
|
|
45
81
|
results = candidates.map(() => false);
|
|
46
82
|
}
|
|
47
83
|
for (let index = 0; index < candidates.length; index++) {
|
|
48
|
-
const { id, version } = candidates[index];
|
|
49
|
-
|
|
50
|
-
|
|
84
|
+
const { id, version, queue } = candidates[index];
|
|
85
|
+
if (this.waitingMap.get(id) !== queue || queue.activityVersion !== version) {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
51
88
|
const result = results[index] ?? false;
|
|
52
89
|
if (result) {
|
|
53
90
|
this.settle(id, result);
|
|
@@ -80,19 +117,49 @@ class ArrivalWaitLayer {
|
|
|
80
117
|
onChunkArrived(doc, deleted = false) {
|
|
81
118
|
this.settle(doc._id, doc._deleted || deleted ? false : doc);
|
|
82
119
|
}
|
|
83
|
-
/**
|
|
120
|
+
/** Adapt the shared producer event into the waiting read's eventual rejection. */
|
|
121
|
+
onChunkFailed(id, failure) {
|
|
122
|
+
const queue = this.waitingMap.get(id);
|
|
123
|
+
if (!queue) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
queue.failure = combineDeliveryFailures(queue.failure, failure);
|
|
127
|
+
queue.observedActivity = true;
|
|
128
|
+
queue.activityVersion++;
|
|
129
|
+
this.refreshActivity([id]);
|
|
130
|
+
}
|
|
131
|
+
/** A missing response cannot end another finite producer's opportunity to deliver. */
|
|
84
132
|
onMissingChunk(id) {
|
|
85
|
-
this.
|
|
133
|
+
this.refreshActivity([id]);
|
|
86
134
|
}
|
|
87
135
|
async read(ids, options, next) {
|
|
88
136
|
const waitForDelivery = options.waitForDelivery ?? (options.timeout === void 0 || options.timeout > 0);
|
|
89
|
-
if (
|
|
137
|
+
if (ids.length === 0) {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
if (!waitForDelivery) {
|
|
141
|
+
return ids.map(() => false);
|
|
142
|
+
}
|
|
90
143
|
const tasks = ids.map((id) => this.enqueueWaiting(id));
|
|
91
144
|
if (!options.preventRemoteRequest) {
|
|
92
145
|
this.eventEmitter("missingChunks", ids);
|
|
93
146
|
}
|
|
94
147
|
this.refreshActivity(ids);
|
|
95
|
-
|
|
148
|
+
const results = await Promise.allSettled(tasks);
|
|
149
|
+
const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
150
|
+
const unclassifiedAbsence = results.some((result) => result.status === "fulfilled" && result.value === false);
|
|
151
|
+
if (errors.length === 1 && errors[0] instanceof ContentReadError && !unclassifiedAbsence) {
|
|
152
|
+
throw errors[0];
|
|
153
|
+
}
|
|
154
|
+
if (errors.length > 0) {
|
|
155
|
+
const resources = unclassifiedAbsence || errors.some((error) => !(error instanceof ContentReadError) || error.failure.resources.length === 0) ? [] : errors.flatMap((error) => error instanceof ContentReadError ? error.failure.resources : []);
|
|
156
|
+
throw new ContentReadError({
|
|
157
|
+
documentId: ids[0],
|
|
158
|
+
resources: [...new Set(resources)],
|
|
159
|
+
cause: errors.length === 1 ? errors[0] : new AggregateError(errors, "Required Chunks are unavailable")
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return results.map((result) => result.status === "fulfilled" ? result.value : false);
|
|
96
163
|
}
|
|
97
164
|
clearWaiting() {
|
|
98
165
|
for (const id of [...this.waitingMap.keys()]) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { LocalDatabaseReadScope } from "../../pouchdb/LocalDatabaseReadScope.js";
|
|
1
2
|
import type { EntryLeaf, DocumentID, EntryDoc } from "../../common/types.js";
|
|
2
3
|
import type { IReadLayer } from "./ChunkLayerInterfaces.js";
|
|
3
4
|
import type { ChunkReadOptions } from "./types.js";
|
|
@@ -6,9 +7,9 @@ import type { ChunkReadOptions } from "./types.js";
|
|
|
6
7
|
*/
|
|
7
8
|
export declare class DatabaseReadLayer implements IReadLayer {
|
|
8
9
|
private database;
|
|
9
|
-
|
|
10
|
+
private readonly readScope?;
|
|
11
|
+
constructor(database: PouchDB.Database<EntryDoc>, readScope?: LocalDatabaseReadScope);
|
|
10
12
|
private isChunkDoc;
|
|
11
|
-
private getError;
|
|
12
13
|
private isMissingError;
|
|
13
14
|
read(ids: DocumentID[], options: ChunkReadOptions, next: (remaining: DocumentID[]) => Promise<(EntryLeaf | false)[]>): Promise<(EntryLeaf | false)[]>;
|
|
14
15
|
}
|