@vrtmrz/livesync-commonlib 0.7.0 → 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.
Files changed (62) hide show
  1. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  2. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  3. package/dist/managers/EntryManager/EntryManagerImpls.js +76 -4
  4. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  5. package/dist/managers/StorageEventManager/admission.js +13 -3
  6. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  7. package/dist/managers/StorageEventManager/processing.js +3 -3
  8. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  9. package/dist/managers/StorageEventManager/queue.js +70 -30
  10. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  11. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  12. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  13. package/dist/managers/StorageEventManager/state.js +9 -7
  14. package/dist/managers/StorageEventManager.d.ts +6 -0
  15. package/dist/managers/StorageEventManager.js +135 -18
  16. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  17. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  18. package/dist/managers/adapters/index.d.ts +1 -1
  19. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  20. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  21. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  22. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  23. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  24. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  25. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  26. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  27. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  28. package/dist/worker/WorkerPushStreamReader.js +179 -0
  29. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  30. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  31. package/dist/worker/bg.worker.js +2 -16
  32. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  33. package/dist/worker/bg.worker.splitting.js +46 -47
  34. package/dist/worker/bgWorker.d.ts +8 -14
  35. package/dist/worker/bgWorker.direct.d.ts +5 -28
  36. package/dist/worker/bgWorker.direct.js +32 -2
  37. package/dist/worker/bgWorker.errors.d.ts +1 -0
  38. package/dist/worker/bgWorker.errors.js +12 -0
  39. package/dist/worker/bgWorker.js +716 -296
  40. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  41. package/dist/worker/bgWorker.splitting.js +115 -107
  42. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  43. package/dist/worker/outOfBandCancelIterator.js +8 -0
  44. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  45. package/dist/worker/serveBackgroundWorker.js +35 -0
  46. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  47. package/dist/worker/splitConnectionTracker.js +73 -0
  48. package/dist/worker/splitGate.d.ts +19 -0
  49. package/dist/worker/splitGate.js +71 -0
  50. package/dist/worker/universalTypes.d.ts +0 -30
  51. package/dist/worker/universalTypes.js +0 -4
  52. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  53. package/dist/worker/workerPushStreamProtocol.js +143 -0
  54. package/docs/development.md +6 -0
  55. package/docs/storage-events-and-reflection.md +30 -2
  56. package/package.json +1 -1
  57. package/dist/worker/bg.common.d.ts +0 -2
  58. package/dist/worker/bg.common.js +0 -6
  59. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  60. package/dist/worker/bg.worker.encryption.js +0 -30
  61. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  62. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -0,0 +1,143 @@
1
+ import {
2
+ RpcError,
3
+ serialiseRpcError
4
+ } from "@vrtmrz/rpc";
5
+ import { OUT_OF_BAND_CANCEL_ITERATOR } from "./outOfBandCancelIterator.js";
6
+ const VERSION = 1;
7
+ const DEFAULT_BATCH_TARGET_BYTES = 128 * 1024;
8
+ const DEFAULT_MAX_BATCH_ITEMS = 256;
9
+ const DEFAULT_INITIAL_CREDIT_BYTES = 512 * 1024;
10
+ const DEFAULT_CLAIM_TIMEOUT_MS = 3e4;
11
+ const ITEM_OVERHEAD_BYTES = 64;
12
+ const measureStringItem = (item) => ITEM_OVERHEAD_BYTES + 2 * item.length;
13
+ const isStringItem = (item) => typeof item === "string";
14
+ const STREAM_ERROR_CODES = /* @__PURE__ */ new Set([
15
+ "aborted",
16
+ "disconnected",
17
+ "timeout",
18
+ "stream-protocol-error",
19
+ "remote-error"
20
+ ]);
21
+ function isRecord(value) {
22
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23
+ }
24
+ function isWireError(value) {
25
+ return isRecord(value) && typeof value.code === "string" && STREAM_ERROR_CODES.has(value.code) && typeof value.message === "string" && (value.remoteName === void 0 || typeof value.remoteName === "string");
26
+ }
27
+ function serialiseError(error) {
28
+ try {
29
+ const wire = serialiseRpcError(error);
30
+ const streamError = STREAM_ERROR_CODES.has(wire.code) ? wire : { ...wire, code: "remote-error" };
31
+ if (isWireError(streamError)) {
32
+ return streamError;
33
+ }
34
+ } catch {
35
+ }
36
+ return { code: "remote-error", message: "Worker stream failed." };
37
+ }
38
+ function deserialiseError(error) {
39
+ return new RpcError(error.code, error.message, { remoteName: error.remoteName });
40
+ }
41
+ function protocolError(message) {
42
+ return new RpcError("stream-protocol-error", message);
43
+ }
44
+ function isPositiveSafeInteger(value) {
45
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
46
+ }
47
+ function measureItem(options, item) {
48
+ try {
49
+ if (options.isItem(item)) {
50
+ const charge = options.chargeItem(item);
51
+ if (isPositiveSafeInteger(charge) && charge <= options.maxItemBytes) {
52
+ return charge;
53
+ }
54
+ }
55
+ } catch (cause) {
56
+ throw new RpcError("stream-protocol-error", "Could not measure Worker stream item.", { cause });
57
+ }
58
+ throw protocolError("Invalid Worker stream item or item charge.");
59
+ }
60
+ function canSend(chargeBytes, inFlightBytes, initialGrant) {
61
+ return inFlightBytes === 0 || chargeBytes <= initialGrant - inFlightBytes;
62
+ }
63
+ function checkLimits(...limits) {
64
+ if (!limits.every(isPositiveSafeInteger)) {
65
+ throw new RangeError("Worker stream limits must be positive safe integers.");
66
+ }
67
+ }
68
+ function disconnected(signal) {
69
+ return signal.reason ?? new RpcError("disconnected", "Worker stream connection ended.");
70
+ }
71
+ const asyncDispose = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol("workerStreamAsyncDispose");
72
+ function stopGeneratorOnReturn(iterator, stop) {
73
+ const wrapped = {
74
+ // Interrupt pending reads before the generator queues return or throw.
75
+ [OUT_OF_BAND_CANCEL_ITERATOR]: true,
76
+ next: (...args) => iterator.next(...args),
77
+ return(value) {
78
+ stop();
79
+ return iterator.return(value);
80
+ },
81
+ throw(error) {
82
+ stop();
83
+ return iterator.throw(error);
84
+ },
85
+ [Symbol.asyncIterator]() {
86
+ return this;
87
+ },
88
+ async [asyncDispose]() {
89
+ await this.return(void 0);
90
+ }
91
+ };
92
+ return wrapped;
93
+ }
94
+ function cancelWorkerPushStream(port, failure) {
95
+ try {
96
+ const message = failure ? { version: VERSION, type: "cancel", error: serialiseError(failure.error) } : { version: VERSION, type: "cancel" };
97
+ port.postMessage(message);
98
+ } catch {
99
+ } finally {
100
+ port.close();
101
+ }
102
+ }
103
+ function validateBatch(options, data, maxBatchItems, inFlightBytes, initialCreditBytes) {
104
+ const { items, chargeBytes } = data;
105
+ if (!Array.isArray(items) || items.length === 0 || items.length > maxBatchItems || !isPositiveSafeInteger(chargeBytes) || !canSend(chargeBytes, inFlightBytes, initialCreditBytes) || chargeBytes > initialCreditBytes - inFlightBytes && items.length !== 1) {
106
+ throw protocolError("Invalid Worker stream batch or credit usage.");
107
+ }
108
+ let measured = 0;
109
+ for (const item of items) {
110
+ const charge = measureItem(options, item);
111
+ if (charge > chargeBytes - measured) {
112
+ throw protocolError("Worker stream batch charge does not match its items.");
113
+ }
114
+ measured += charge;
115
+ }
116
+ if (measured !== chargeBytes) {
117
+ throw protocolError("Worker stream batch charge does not match its items.");
118
+ }
119
+ return { items, chargeBytes };
120
+ }
121
+ export {
122
+ DEFAULT_BATCH_TARGET_BYTES,
123
+ DEFAULT_CLAIM_TIMEOUT_MS,
124
+ DEFAULT_INITIAL_CREDIT_BYTES,
125
+ DEFAULT_MAX_BATCH_ITEMS,
126
+ ITEM_OVERHEAD_BYTES,
127
+ VERSION,
128
+ canSend,
129
+ cancelWorkerPushStream,
130
+ checkLimits,
131
+ deserialiseError,
132
+ disconnected,
133
+ isPositiveSafeInteger,
134
+ isRecord,
135
+ isStringItem,
136
+ isWireError,
137
+ measureItem,
138
+ measureStringItem,
139
+ protocolError,
140
+ serialiseError,
141
+ stopGeneratorOnReturn,
142
+ validateBatch
143
+ };
@@ -251,6 +251,12 @@ npm run test:package
251
251
 
252
252
  `test:package` builds the compiled package, packs it, installs the tarball into a clean consumer fixture, exercises Node imports, type-checks public entry points, and creates representative browser bundles. It also verifies that browser and context entry points do not pull in Node-only code, Svelte, or the complete language catalogue unintentionally.
253
253
 
254
+ The browser Worker bundle uses one RPC pool for chunking, encryption, and decryption. The Self-hosted LiveSync plug-in initialises it with the event hub for its own lifecycle. The package check exercises the existing compatibility entry and verifies that it and Commonlib's internal alias resolve to the same implementation for each runtime. Both runtimes return a synchronous factory for each Worker splitter. Node consumers can still `await` the factory and should use `await` when migrating a call that chained `.then()` on the former direct V1 or V2 result.
255
+
256
+ Browser splitters send ordered arrays of whole chunks over a dedicated `MessagePort` transferred by RPC. The consumer returns byte credit when it advances past each array. A chunk larger than the initial grant travels alone once all earlier batches have been refunded. The public split iterator still yields individual chunks.
257
+
258
+ The browser pool permits as many active splits as it has Worker slots, and encryption and decryption RPCs bypass this limit.
259
+
254
260
  `test:contracts` runs the host-neutral result contracts which are intended to be reusable while implementations move:
255
261
 
256
262
  - `test:contract:context` verifies event delivery, default instance isolation, translation results, and host extension of `ServiceContextContract`;
@@ -244,8 +244,8 @@ waiting, or already in a handler. It waits for each actual handler result and
244
244
  for the ordered snapshot update which records that result; releasing a timer is
245
245
  not completion. Later events do not extend that captured boundary. A newer
246
246
  coalesced operation satisfies an earlier one only when its successful result
247
- covers the earlier intent. A failed handler or snapshot update is reported to
248
- the caller and leaves unresolved work in the snapshot. This boundary covers
247
+ covers the earlier intent. A failed handler or acknowledgement is reported to
248
+ the caller and leaves the saved work pending. This boundary covers
249
249
  local completion under the selected handler contract only; it does not prove replication or receipt by another
250
250
  Vault.
251
251
 
@@ -259,6 +259,34 @@ timers do not occupy a processing slot, and time spent waiting for a slot does
259
259
  not restart the maximum delay. Once due, the operation acquires a slot and reads
260
260
  current content for processing.
261
261
 
262
+ ### Ordered pending buffers
263
+
264
+ This option is available in Commonlib 0.8.0.
265
+
266
+ A host can supply `pendingEventStore` on its storage-event manager adapter to
267
+ store ordered arrays of new event intents. The store returns buffers in replay
268
+ order, including any legacy snapshot as the first buffer. `append()` returns a
269
+ distinct key after commit. The manager groups requests for the next buffer and
270
+ waits for the append before handling its events. If the append fails, the
271
+ manager reports the failure once, discards that unsaved array, and lets later
272
+ arrays proceed. Calls already waiting for that array receive the failure.
273
+ Previously saved buffers remain available for replay.
274
+
275
+ The next full Vault scan compares selected paths with the local database. It
276
+ can recover the current contents of a renamed file. If the rename was never
277
+ saved, the scan evaluates the old and new paths independently. Without
278
+ sufficient evidence of an offline deletion, it may restore a live database
279
+ entry at the old path.
280
+
281
+ A saved array remains intact until every entry in it has completed. Each
282
+ successful operation releases its in-process dependants as soon as its own
283
+ local effect completes. The final successful operation deletes the whole
284
+ buffer. If an operation fails, other work can proceed where its dependencies
285
+ allow, and the failed buffer remains recoverable. A later application instance
286
+ loads that whole array and revalidates ordinary file events against current
287
+ storage and database state. Hosts must surface store failures to the manager
288
+ and resolve deletion only once the supplied key has been durably removed.
289
+
262
290
  ## Retrying ordinary file operations
263
291
 
264
292
  The following extension is available in Commonlib 0.4.1. A failed ordinary
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Shared data, storage, and replication primitives for Self-hosted LiveSync clients.",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
@@ -1,2 +0,0 @@
1
- import type { END_OF_DATA } from "./universalTypes.js";
2
- export declare function postBack(key: number, seq: number, data: string | END_OF_DATA): void;
@@ -1,6 +0,0 @@
1
- function postBack(key, seq, data) {
2
- self.postMessage({ key, seq, result: data });
3
- }
4
- export {
5
- postBack
6
- };
@@ -1,7 +0,0 @@
1
- import type { EncryptHKDFArguments } from "./universalTypes.js";
2
- import type { EncryptArguments } from "./universalTypes.js";
3
- /**
4
- * Processes the encryption of data.
5
- * @param data The data to be encrypted or decrypted.
6
- */
7
- export declare function processEncryption(data: EncryptArguments | EncryptHKDFArguments): Promise<void>;
@@ -1,30 +0,0 @@
1
- import { encrypt, decrypt } from "octagonal-wheels/encryption";
2
- import { encrypt as encryptHKDF, decrypt as decryptHKDF } from "octagonal-wheels/encryption/hkdf";
3
- async function processEncryption(data) {
4
- const key = data.key;
5
- const { type, input, passphrase } = data;
6
- try {
7
- if (type == "encrypt") {
8
- const autoCalculateIterations = data.autoCalculateIterations;
9
- const result = await encrypt(input, passphrase, autoCalculateIterations);
10
- self.postMessage({ key, result });
11
- } else if (type == "decrypt") {
12
- const autoCalculateIterations = data.autoCalculateIterations;
13
- const result = await decrypt(input, passphrase, autoCalculateIterations);
14
- self.postMessage({ key, result });
15
- } else if (type == "encryptHKDF") {
16
- const pbkdf2Salt = data.pbkdf2Salt;
17
- const result = await encryptHKDF(input, passphrase, pbkdf2Salt);
18
- self.postMessage({ key, result });
19
- } else if (type == "decryptHKDF") {
20
- const pbkdf2Salt = data.pbkdf2Salt;
21
- const result = await decryptHKDF(input, passphrase, pbkdf2Salt);
22
- self.postMessage({ key, result });
23
- }
24
- } catch (ex) {
25
- self.postMessage({ key, error: ex });
26
- }
27
- }
28
- export {
29
- processEncryption
30
- };
@@ -1,22 +0,0 @@
1
- import { type EncryptHKDFProcessItem, type ResultPayload } from "./universalTypes.js";
2
- import { type EncryptProcessItem } from "./universalTypes.js";
3
- import { type EncryptHKDFArguments } from "./universalTypes.js";
4
- import { type EncryptArguments } from "./universalTypes.js";
5
- /**
6
- * Offloads encryption to a web worker.
7
- * @param data The data to be encrypted.
8
- * @returns A promise that resolves with the encryption result.
9
- */
10
- export declare function encryptionOnWorker(data: Omit<EncryptArguments, "key">): Promise<string>;
11
- /**
12
- * Offloads HKDF encryption to a web worker.
13
- * @param data The data to be encrypted.
14
- * @returns A promise that resolves with the encryption result.
15
- */
16
- export declare function encryptionHKDFOnWorker(data: Omit<EncryptHKDFArguments, "key">): Promise<string>;
17
- /**
18
- * Handles the encryption callbacks
19
- * @param process The process item associated with the task.
20
- * @param data The data to be processed.
21
- */
22
- export declare function handleTaskEncrypt(process: EncryptProcessItem | EncryptHKDFProcessItem, data: ResultPayload): void;
@@ -1,40 +0,0 @@
1
- import { startWorker, removeTask } from "./bgWorker.js";
2
- import {} from "./universalTypes.js";
3
- import {} from "./universalTypes.js";
4
- import {} from "./universalTypes.js";
5
- import {} from "./universalTypes.js";
6
- function encryptionOnWorker(data) {
7
- const process = startWorker(data);
8
- return (async () => {
9
- const ret = await process.task.promise;
10
- process.finalize();
11
- return ret;
12
- })();
13
- }
14
- function encryptionHKDFOnWorker(data) {
15
- const process = startWorker(data);
16
- return (async () => {
17
- const ret = await process.task.promise;
18
- process.finalize();
19
- return ret;
20
- })();
21
- }
22
- function handleTaskEncrypt(process, data) {
23
- const key = data.key;
24
- const task = process.task;
25
- if ("result" in data) {
26
- task.resolve(data.result);
27
- } else {
28
- if (data.error) {
29
- task.reject(data.error);
30
- } else {
31
- task.reject(new Error("Unknown error in background encryption"));
32
- }
33
- }
34
- removeTask(key);
35
- }
36
- export {
37
- encryptionHKDFOnWorker,
38
- encryptionOnWorker,
39
- handleTaskEncrypt
40
- };