@yarkivaev/scada 2.14.0 → 2.15.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/charts/scada/templates/processes.yaml +6 -1
- package/charts/scada/values.schema.json +1 -0
- package/package.json +1 -1
- package/src/application/control/agent.js +8 -14
- package/src/application/control/executionSnapshot.js +4 -5
- package/src/application/runtime/deliveryOperations.js +6 -3
- package/src/application/runtime/deliveryPublications.js +13 -11
- package/src/application/runtime/deliveryQueue.js +5 -4
- package/src/application/runtime/index.js +0 -1
- package/src/application/runtime/queuedDelivery.js +6 -5
- package/src/application/runtime/runCollector.js +8 -6
- package/src/application/runtime/runtime.js +1 -0
- package/src/application/runtime/runtimeServices.js +6 -26
- package/src/infrastructure/persistence/runtime/memoryDeliveryStore.js +186 -0
- package/src/infrastructure/persistence/runtime/spoolCodec.js +0 -27
- package/src/infrastructure/persistence/runtime/taskStateMemory.js +40 -0
- package/src/application/control/snapshotFile.js +0 -24
- package/src/infrastructure/persistence/runtime/deliverySpool.js +0 -86
- package/src/infrastructure/persistence/runtime/spoolCheckpoints.js +0 -65
- package/src/infrastructure/persistence/runtime/spoolDatabase.js +0 -69
- package/src/infrastructure/persistence/runtime/spoolFormat.js +0 -63
- package/src/infrastructure/persistence/runtime/spoolLimits.js +0 -8
- package/src/infrastructure/persistence/runtime/spoolMigration.js +0 -66
- package/src/infrastructure/persistence/runtime/spoolMutations.js +0 -19
- package/src/infrastructure/persistence/runtime/spoolProcess.js +0 -89
- package/src/infrastructure/persistence/runtime/spoolProcessChild.js +0 -32
- package/src/infrastructure/persistence/runtime/spoolRecords.js +0 -56
- package/src/infrastructure/persistence/runtime/spoolReplay.js +0 -55
- package/src/infrastructure/persistence/runtime/taskStateSqlite.js +0 -37
|
@@ -101,9 +101,14 @@ spec:
|
|
|
101
101
|
{{- toYaml . | nindent 12 }}
|
|
102
102
|
{{- end }}
|
|
103
103
|
{{- end }}
|
|
104
|
-
{{- if .hostDevices }}
|
|
104
|
+
{{- if or .hostDevices .readOnlyRootFilesystem }}
|
|
105
105
|
securityContext:
|
|
106
|
+
{{- if .hostDevices }}
|
|
106
107
|
privileged: true
|
|
108
|
+
{{- end }}
|
|
109
|
+
{{- if .readOnlyRootFilesystem }}
|
|
110
|
+
readOnlyRootFilesystem: true
|
|
111
|
+
{{- end }}
|
|
107
112
|
{{- end }}
|
|
108
113
|
{{- if or .hostDevices .volumeMounts }}
|
|
109
114
|
volumeMounts:
|
package/package.json
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import executionSnapshot, { remoteSnapshot, remoteStatus } from './executionSnapshot.js';
|
|
2
2
|
import localAssignment from './localAssignment.js';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { checkSnapshot, loadSnapshot, saveSnapshot } from './snapshotFile.js';
|
|
5
4
|
async function applyTasks(runtime,snapshot,nodeId,onError) {
|
|
6
5
|
const ids=new Set(snapshot.assignments.map((row)=>{return row.taskId;}));
|
|
7
6
|
const removals=runtime.status().tasks.filter((row)=>{return !ids.has(row.taskId);});
|
|
@@ -15,22 +14,19 @@ async function applyTasks(runtime,snapshot,nodeId,onError) {
|
|
|
15
14
|
}
|
|
16
15
|
return applied;
|
|
17
16
|
}
|
|
18
|
-
/**
|
|
19
|
-
export default function assignmentAgent({ nodeId,
|
|
17
|
+
/** Keep reconciling the current assignment when the controller is unavailable. */
|
|
18
|
+
export default function assignmentAgent({ nodeId, store, runtime, validate, intervalMs = 5000, onError = () => {
|
|
20
19
|
// Optional diagnostic sink.
|
|
21
20
|
} }) {
|
|
22
|
-
if (!nodeId
|
|
21
|
+
if (!nodeId) { throw new TypeError('Control node id required'); }
|
|
23
22
|
const state = { desired: null, appliedGeneration: null, stopped: false, timer: null, pending: null, sequence: 0, bootId: randomUUID() };
|
|
24
23
|
// Serialized by tick and startup; mutations cannot overlap.
|
|
25
24
|
/* eslint-disable require-atomic-updates */
|
|
26
|
-
async function reconcile(input
|
|
27
|
-
|
|
28
|
-
await validate(
|
|
29
|
-
const snapshot = executionSnapshot(
|
|
30
|
-
|
|
31
|
-
await saveSnapshot(file, snapshot);
|
|
32
|
-
state.desired = snapshot;
|
|
33
|
-
}
|
|
25
|
+
async function reconcile(input) {
|
|
26
|
+
const remote = remoteSnapshot(input);
|
|
27
|
+
await validate(remote);
|
|
28
|
+
const snapshot = executionSnapshot(remote, state.desired, runtime.status().tasks);
|
|
29
|
+
state.desired = snapshot;
|
|
34
30
|
const applied=await applyTasks(runtime,snapshot,nodeId,onError);
|
|
35
31
|
state.appliedGeneration=applied?snapshot.generation:null;
|
|
36
32
|
}
|
|
@@ -51,8 +47,6 @@ export default function assignmentAgent({ nodeId, file, store, runtime, validate
|
|
|
51
47
|
tick,
|
|
52
48
|
status() { return { hasAssignment: Boolean(state.desired), appliedGeneration: state.appliedGeneration }; },
|
|
53
49
|
async start({ waitForInitialTick = true } = {}) {
|
|
54
|
-
const saved = await loadSnapshot(file);
|
|
55
|
-
if (saved) { await reconcile(saved, true); }
|
|
56
50
|
if (waitForInitialTick) { await tick(); } else { void tick().catch(onError); }
|
|
57
51
|
state.timer = setInterval(() => { void tick(); }, intervalMs);
|
|
58
52
|
},
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { checkSnapshot } from './snapshotFile.js';
|
|
2
1
|
export function remoteSnapshot(snapshot) {
|
|
2
|
+
if (!snapshot || !Number.isSafeInteger(snapshot.generation) || snapshot.generation < 0 || !Array.isArray(snapshot.assignments)) {
|
|
3
|
+
throw new TypeError('Invalid assignment snapshot');
|
|
4
|
+
}
|
|
3
5
|
const remote = { ...snapshot };
|
|
4
6
|
delete remote.localGeneration;
|
|
5
7
|
delete remote.executionGenerations;
|
|
@@ -7,15 +9,12 @@ export function remoteSnapshot(snapshot) {
|
|
|
7
9
|
}
|
|
8
10
|
function epoch(snapshot) { return snapshot?.controlEpoch ?? 'initial'; }
|
|
9
11
|
/** Local runtime generations remain monotonic even when an operator restores etcd. */
|
|
10
|
-
export default function executionSnapshot(
|
|
11
|
-
checkSnapshot(snapshot);
|
|
12
|
-
const remote = remoteSnapshot(snapshot);
|
|
12
|
+
export default function executionSnapshot(remote, previous, tasks) {
|
|
13
13
|
if (previous && epoch(previous) === epoch(remote)) {
|
|
14
14
|
if (remote.generation < previous.generation) { throw new Error('Stale assignment snapshot'); }
|
|
15
15
|
if (remote.generation === previous.generation && JSON.stringify(remote) !== JSON.stringify(remoteSnapshot(previous))) { throw new Error('Conflicting assignment snapshot'); }
|
|
16
16
|
if (remote.generation === previous.generation) { return previous; }
|
|
17
17
|
}
|
|
18
|
-
if (restored && Number.isSafeInteger(snapshot.localGeneration) && snapshot.executionGenerations) { return snapshot; }
|
|
19
18
|
const localGeneration = Math.max(previous?.localGeneration ?? 0, remote.generation, ...tasks.map((row) => { return row.generation ?? 0; })) + 1;
|
|
20
19
|
const executionGenerations = Object.fromEntries(remote.assignments.map((row) => {
|
|
21
20
|
const prior = previous?.assignments.find((item) => { return item.taskId === row.taskId; });
|
|
@@ -5,7 +5,7 @@ function settings(options) {
|
|
|
5
5
|
if (options.groupCommit !== undefined && (!options.groupCommit || typeof options.groupCommit !== 'object' || Array.isArray(options.groupCommit))) {
|
|
6
6
|
throw new TypeError('groupCommit must be an object');
|
|
7
7
|
}
|
|
8
|
-
const { maxRecords = 64, maxBytes = 1048576, maxDelayMs =
|
|
8
|
+
const { maxRecords = 64, maxBytes = 1048576, maxDelayMs = 0 } = options.groupCommit ?? {};
|
|
9
9
|
const group = { maxRecords, maxBytes, maxDelayMs };
|
|
10
10
|
const config = { ...group, maxOperations: options.maxOperations ?? 128, maxPendingBytes: options.maxPendingBytes ?? 4194304 };
|
|
11
11
|
Object.entries(config).forEach(([name, value]) => { positive(value, name, name === 'maxDelayMs'); });
|
|
@@ -27,7 +27,10 @@ export default function deliveryOperations(apply, options = {}) {
|
|
|
27
27
|
state.operations += 1;
|
|
28
28
|
return true;
|
|
29
29
|
}
|
|
30
|
-
function wait() {
|
|
30
|
+
function wait() {
|
|
31
|
+
if (waiters.length >= config.maxOperations) { return Promise.reject(new Error('Delivery operation capacity exceeded')); }
|
|
32
|
+
return new Promise((resolve) => { waiters.push(resolve); });
|
|
33
|
+
}
|
|
31
34
|
function notifyIdle() {
|
|
32
35
|
if (!state.operations && !state.running && !waiters.length) { state.wake?.(); Object.assign(state, { idle: null, wake: null }); }
|
|
33
36
|
}
|
|
@@ -117,7 +120,7 @@ export default function deliveryOperations(apply, options = {}) {
|
|
|
117
120
|
if (occupy()) {
|
|
118
121
|
try { return hold(build).commit(); } catch (error) { return Promise.reject(error); }
|
|
119
122
|
}
|
|
120
|
-
return
|
|
123
|
+
return Promise.reject(new Error('Delivery operation capacity exceeded'));
|
|
121
124
|
},
|
|
122
125
|
barrier(action) {
|
|
123
126
|
if (occupy()) { return enqueue({ kind: 'barrier', action, bytes: 0 }); }
|
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
/** A slot and its prospective
|
|
1
|
+
/** A slot and its prospective receipt stay reserved until the actual writer settles. */
|
|
2
2
|
/* eslint max-lines-per-function: ["error", 80], max-statements: ["error", 25] */
|
|
3
3
|
export default function deliveryPublications(commands, sessions, options) {
|
|
4
4
|
const limit = options.maxInFlight ?? 32;
|
|
5
5
|
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError('Positive safe maxInFlight required'); }
|
|
6
|
-
const active = new
|
|
6
|
+
const active = new Set();
|
|
7
|
+
function keyOf(record, id) { return JSON.stringify([record.event.eventId, id, record.admission]); }
|
|
7
8
|
function publish(record, id) {
|
|
8
|
-
const key =
|
|
9
|
+
const key = keyOf(record, id);
|
|
9
10
|
if (active.has(key) || active.size >= limit) { throw new Error('Delivery publication capacity exceeded'); }
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
active.add(key);
|
|
12
|
+
let started = false;
|
|
13
|
+
return Promise.resolve(commands.prepare((checkBytes) => {
|
|
14
|
+
const operation = { kind: 'ack', eventId: record.event.eventId, recipient: id, ...(record.admission !== undefined && { admission: record.admission }) };
|
|
12
15
|
const bytes = Buffer.byteLength(JSON.stringify(operation));
|
|
13
16
|
const retainedBytes = Buffer.byteLength(JSON.stringify(record.event));
|
|
14
17
|
checkBytes(bytes, retainedBytes); return { operation, bytes, retainedBytes };
|
|
@@ -19,18 +22,17 @@ export default function deliveryPublications(commands, sessions, options) {
|
|
|
19
22
|
const event = record.event.observation;
|
|
20
23
|
write = sessions.write(descriptor, { ...event, options: { ...event.options, persistent: true, mandatory: true, messageId: event.eventId } });
|
|
21
24
|
} catch (error) { receipt.cancel(); throw error; }
|
|
25
|
+
started = true;
|
|
22
26
|
const receiptLife = write.settled.then(() => { return receipt.commit(); }, (error) => { receipt.cancel(); throw error; })
|
|
23
27
|
.finally(() => { active.delete(key); });
|
|
24
28
|
void receiptLife.catch(() => {
|
|
25
29
|
// The caller reports failures; late rejection still releases only the actual reservation.
|
|
26
30
|
});
|
|
27
31
|
return write.result.then(() => { return receiptLife; });
|
|
32
|
+
}).catch((error) => {
|
|
33
|
+
if (!started) { active.delete(key); }
|
|
34
|
+
throw error;
|
|
28
35
|
});
|
|
29
|
-
active.set(key, settled);
|
|
30
|
-
void settled.catch(() => {
|
|
31
|
-
// Prepare admission failures still release the publication slot.
|
|
32
|
-
});
|
|
33
|
-
return settled.finally(() => { active.delete(key); });
|
|
34
36
|
}
|
|
35
|
-
return { publish, limit };
|
|
37
|
+
return { publish, limit, available(record, id) { return active.size < limit && !active.has(keyOf(record, id)); } };
|
|
36
38
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import memoryDeliveryStore from '../../infrastructure/persistence/runtime/memoryDeliveryStore.js';
|
|
2
2
|
import deliverySessions from './deliverySessions.js';
|
|
3
3
|
import deliveryOperations from './deliveryOperations.js';
|
|
4
4
|
import deliveryPublications from './deliveryPublications.js';
|
|
@@ -10,8 +10,8 @@ function snapshot(operation, checkBytes) {
|
|
|
10
10
|
return { operation: frozen, bytes: Buffer.byteLength(JSON.stringify(frozen)) };
|
|
11
11
|
}
|
|
12
12
|
/* eslint max-lines-per-function: ["error", 125], max-statements: ["error", 25] */
|
|
13
|
-
/** Node-owned
|
|
14
|
-
export default function deliveryQueue(
|
|
13
|
+
/** Node-owned delivery using an injectable store and bounded publication sessions. */
|
|
14
|
+
export default function deliveryQueue(options, spool = memoryDeliveryStore(options)) {
|
|
15
15
|
const commands = deliveryOperations((operations) => { return spool.mutateMany(operations); }, options);
|
|
16
16
|
const sessions = deliverySessions(options.factory, options.writeTimeoutMs);
|
|
17
17
|
const batchSize = options.batchSize ?? 100;
|
|
@@ -45,7 +45,8 @@ export default function deliveryQueue(directory, options, spool = spoolProcess(d
|
|
|
45
45
|
receipts.add(receipt);
|
|
46
46
|
}
|
|
47
47
|
async function advance(row, id) {
|
|
48
|
-
if (!state.closed && (blocked.get(row.targets[id]) ?? -Infinity) <= clock()
|
|
48
|
+
if (!state.closed && publications.available(row, id) && (blocked.get(row.targets[id]) ?? -Infinity) <= clock()
|
|
49
|
+
&& (spool.hasAdmission?.(row.event.eventId, row.admission, id) ?? true)) { receive(row, id); }
|
|
49
50
|
if (receipts.size >= receiptWindow) { await Promise.race(receipts); }
|
|
50
51
|
}
|
|
51
52
|
try {
|
|
@@ -8,5 +8,4 @@ export { default as taskQueue } from './taskQueue.js';
|
|
|
8
8
|
export { default as createRegistry } from './createRegistry.js';
|
|
9
9
|
export { default as resolveSecrets } from './resolveSecrets.js';
|
|
10
10
|
export { default as taskStatePg } from '../../infrastructure/persistence/runtime/taskStatePg.js';
|
|
11
|
-
export { default as taskStateSqlite } from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
|
|
12
11
|
export { default as spooledOutput, amqpDestinations } from './spooledOutput.js';
|
|
@@ -2,15 +2,16 @@ import deliveryQueue from './deliveryQueue.js';
|
|
|
2
2
|
import { sinks } from './streamPorts.js';
|
|
3
3
|
|
|
4
4
|
/** Configured once per node; queue draining outlives any individual assignment. */
|
|
5
|
-
export default function queuedDelivery(env, secrets, supplied) {
|
|
5
|
+
export default function queuedDelivery(env, secrets, supplied, store) {
|
|
6
6
|
let timer;
|
|
7
7
|
let stopped = false;
|
|
8
8
|
let burst = 0;
|
|
9
|
-
const queue = supplied ??
|
|
10
|
-
maxBytes: Number(env.
|
|
11
|
-
|
|
9
|
+
const queue = supplied ?? deliveryQueue({
|
|
10
|
+
maxBytes: Number(env.COLLECTOR_QUEUE_MAX_BYTES ?? 16 * 1024 * 1024),
|
|
11
|
+
maxRecords: Number(env.COLLECTOR_QUEUE_MAX_RECORDS ?? 4096),
|
|
12
|
+
factory(spec) { return sinks().get(spec.type)(spec, { secrets }); },
|
|
12
13
|
onError(error) { process.stderr.write(`Collector delivery delayed: ${error.message}\n`); }
|
|
13
|
-
}
|
|
14
|
+
}, store);
|
|
14
15
|
function nextDelay(result) {
|
|
15
16
|
const status = queue.status?.();
|
|
16
17
|
if (result?.delivered > 0 && status?.ready !== false && status?.drainFull && status.pending > 0) {
|
|
@@ -22,10 +22,11 @@ async function apply(runtime, document) {
|
|
|
22
22
|
await runtime.apply(input);
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
function healthView(runtime, state) {
|
|
25
|
+
function healthView(runtime, state, queue) {
|
|
26
26
|
return { status() {
|
|
27
27
|
const status = runtime.status();
|
|
28
|
-
|
|
28
|
+
const { pending, bytes, maxBytes, recordLimit, droppedRecords, droppedBytes } = queue?.status?.() ?? {};
|
|
29
|
+
return { ...status, delivery: { pending, bytes, maxBytes, recordLimit, droppedRecords, droppedBytes }, stopping: status.stopping || state.stopped, fatal: status.fatal || state.failed,
|
|
29
30
|
initialized: state.initialized && (!state.agent || state.agent.status().appliedGeneration !== null) };
|
|
30
31
|
} };
|
|
31
32
|
}
|
|
@@ -35,7 +36,7 @@ async function initialize(collector, owned, state, { env, registry, store }) {
|
|
|
35
36
|
await owned.open?.();
|
|
36
37
|
if (state.stopped) { throw new Error('Collector stopped during recovery'); }
|
|
37
38
|
if (store) {
|
|
38
|
-
state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID,
|
|
39
|
+
state.agent = assignmentAgent({ nodeId: env.COLLECTOR_NODE_ID, store, runtime,
|
|
39
40
|
validate(document) { return validateManifest(document, registry); },
|
|
40
41
|
onError(error) { process.stderr.write(`collector control: ${error.name}\n`); } });
|
|
41
42
|
await state.agent.start({ waitForInitialTick: false });
|
|
@@ -76,7 +77,7 @@ export default async function runCollector({ registry, env = process.env, argv =
|
|
|
76
77
|
const host = env.COLLECTOR_HEALTH_HOST ?? '127.0.0.1';
|
|
77
78
|
const store = env.COLLECTOR_CONTROL_ENDPOINTS
|
|
78
79
|
? controlStore(clientFromEnv(env, 'COLLECTOR_CONTROL'), env.COLLECTOR_CONTROL_PREFIX) : null;
|
|
79
|
-
const owned = runtimeServices(env,
|
|
80
|
+
const owned = runtimeServices(env, services);
|
|
80
81
|
let runtime;
|
|
81
82
|
try { runtime = createRuntime({ registry, ...owned }); }
|
|
82
83
|
catch (error) {
|
|
@@ -103,9 +104,10 @@ export default async function runCollector({ registry, env = process.env, argv =
|
|
|
103
104
|
if (signals) { state.detach = collectorSignals(collector); }
|
|
104
105
|
try {
|
|
105
106
|
if (env.COLLECTOR_HEALTH_PORT) {
|
|
106
|
-
Object.assign(state, { health: runtimeHealth(healthView(runtime, state), {
|
|
107
|
+
Object.assign(state, { health: runtimeHealth(healthView(runtime, state, owned.deliveryQueue), {
|
|
107
108
|
port: Number(env.COLLECTOR_HEALTH_PORT), host,
|
|
108
|
-
handle: spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN, services.spoolMachine)
|
|
109
|
+
handle: env.STATE_HTTP_TOKEN ? spoolSurface(owned.deliveryQueue, env.STATE_HTTP_TOKEN, services.spoolMachine) : null,
|
|
110
|
+
staleMs: Number(env.COLLECTOR_LIVE_STALE_MS ?? 30000) }) });
|
|
109
111
|
await state.health;
|
|
110
112
|
}
|
|
111
113
|
const recoveryMs = Number(env.COLLECTOR_RECOVERY_TIMEOUT_MS ?? 900000);
|
|
@@ -1,37 +1,17 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { mkdirSync } from 'node:fs';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import taskStatePg from '../../infrastructure/persistence/runtime/taskStatePg.js';
|
|
5
|
-
import taskStateSqlite from '../../infrastructure/persistence/runtime/taskStateSqlite.js';
|
|
6
|
-
import deadline from './deadline.js';
|
|
1
|
+
import taskStateMemory from '../../infrastructure/persistence/runtime/taskStateMemory.js';
|
|
7
2
|
import queuedDelivery from './queuedDelivery.js';
|
|
8
3
|
|
|
9
|
-
|
|
10
|
-
if (!supplied.localTaskState || supplied.stateStore || env.COLLECTOR_STATE_URL || !env.COLLECTOR_SPOOL_DIR) {
|
|
11
|
-
return undefined;
|
|
12
|
-
}
|
|
13
|
-
mkdirSync(env.COLLECTOR_SPOOL_DIR, { recursive: true });
|
|
14
|
-
return taskStateSqlite(join(env.COLLECTOR_SPOOL_DIR, 'task-state.sqlite'));
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
/** Storage is optional for live-only tasks and mandatory for durable adapters. */
|
|
4
|
+
/** Collector-owned observations and task state are volatile. */
|
|
18
5
|
export default function runtimeServices(env, supplied) {
|
|
19
|
-
const pool = !supplied.stateStore && env.COLLECTOR_STATE_URL ? new pg.Pool({
|
|
20
|
-
connectionString: env.COLLECTOR_STATE_URL, max: 4, connectionTimeoutMillis: 5000,
|
|
21
|
-
query_timeout: 10000, statement_timeout: 10000, idleTimeoutMillis: 30000
|
|
22
|
-
}) : null;
|
|
23
6
|
const secrets = supplied.secrets ?? { get(name) { return env[name]; } };
|
|
24
|
-
const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue);
|
|
25
|
-
const local =
|
|
7
|
+
const delivery = queuedDelivery(env, secrets, supplied.deliveryQueue, supplied.deliveryStore);
|
|
8
|
+
const local = supplied.stateStore ? undefined : taskStateMemory();
|
|
26
9
|
return { ...supplied, secrets, deliveryQueue: delivery.queue,
|
|
27
10
|
open() { return delivery.open(); },
|
|
28
|
-
stateStore: supplied.stateStore ??
|
|
11
|
+
stateStore: supplied.stateStore ?? local,
|
|
29
12
|
async close() {
|
|
30
13
|
try { await delivery.stop(); }
|
|
31
|
-
finally {
|
|
32
|
-
local?.close();
|
|
33
|
-
if (pool) { await deadline(() => { return pool.end(); }, 10000); }
|
|
34
|
-
}
|
|
14
|
+
finally { local?.close(); }
|
|
35
15
|
}
|
|
36
16
|
};
|
|
37
17
|
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/* eslint max-lines-per-function: ["error", 120], max-statements: ["error", 24] */
|
|
2
|
+
import { digest, revive, validate } from './spoolCodec.js';
|
|
3
|
+
|
|
4
|
+
const replayPageBytes = 4 * 1024 * 1024;
|
|
5
|
+
const remainingKeyBytes = Buffer.byteLength(',"remaining":');
|
|
6
|
+
|
|
7
|
+
function recordOf(event, recipients) {
|
|
8
|
+
const json = JSON.stringify(event) ?? 'null';
|
|
9
|
+
const snapshot = JSON.parse(json);
|
|
10
|
+
validate(snapshot, recipients);
|
|
11
|
+
const descriptorHashes = Array.isArray(snapshot.destinations)
|
|
12
|
+
? snapshot.destinations.map(item => { return digest(JSON.stringify(item)); }) : [];
|
|
13
|
+
const destinations = new Map(recipients.map((id, index) => {
|
|
14
|
+
return [id, descriptorHashes[index] ?? `legacy:${id}`];
|
|
15
|
+
}));
|
|
16
|
+
const recipientJson = JSON.stringify(recipients);
|
|
17
|
+
const identity = `{"event":${json},"recipients":${recipientJson}}`;
|
|
18
|
+
return { id: snapshot.eventId, json, fingerprint: digest(identity), destinations, pending: new Map(),
|
|
19
|
+
bytes: Buffer.byteLength(identity) + remainingKeyBytes + Buffer.byteLength(recipientJson) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function limitOf(limit, operation) {
|
|
23
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) { throw new TypeError(`Positive ${operation} limit required`); }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function pagesOf(targets, limit, blocked) {
|
|
27
|
+
const pages = [];
|
|
28
|
+
for (const [target, pairs] of targets) {
|
|
29
|
+
if (!blocked.has(target)) { pages.push({ target, pairs, cursor: pairs.values() }); }
|
|
30
|
+
if (pages.length >= Math.min(limit, 64)) { break; }
|
|
31
|
+
}
|
|
32
|
+
return pages;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function select(pages, limit) {
|
|
36
|
+
const selected = new Map();
|
|
37
|
+
let bytes = 0;
|
|
38
|
+
function add(pair) {
|
|
39
|
+
const { record } = pair;
|
|
40
|
+
if (!selected.has(record)) {
|
|
41
|
+
// Always admit the first row so a large record can make progress alone.
|
|
42
|
+
if (selected.size >= limit || (selected.size && bytes + record.bytes > replayPageBytes)) { return; }
|
|
43
|
+
selected.set(record, []);
|
|
44
|
+
bytes += record.bytes;
|
|
45
|
+
}
|
|
46
|
+
selected.get(record).push(pair);
|
|
47
|
+
}
|
|
48
|
+
for (let offset = 0; offset < limit; offset += 1) {
|
|
49
|
+
let advanced = false;
|
|
50
|
+
for (const page of pages) {
|
|
51
|
+
const { value: pair } = page.cursor.next();
|
|
52
|
+
if (pair) { advanced = true; add(pair); }
|
|
53
|
+
}
|
|
54
|
+
if (!advanced) { break; }
|
|
55
|
+
}
|
|
56
|
+
return selected;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function decoded(record, remaining) {
|
|
60
|
+
return { event: JSON.parse(record.json, revive), remaining };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function visibleRecords(records, limit) {
|
|
64
|
+
limitOf(limit, 'peek');
|
|
65
|
+
const output = [];
|
|
66
|
+
let bytes = 0;
|
|
67
|
+
for (const record of records.values()) {
|
|
68
|
+
if (output.length && bytes + record.bytes > replayPageBytes) { break; }
|
|
69
|
+
bytes += record.bytes;
|
|
70
|
+
output.push(decoded(record, [...record.pending.keys()]));
|
|
71
|
+
if (output.length === limit) { break; }
|
|
72
|
+
}
|
|
73
|
+
return output;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The FIFO is independent of per-target replay order. Accepted observations live only in this process. */
|
|
77
|
+
export default function memoryDeliveryStore({ maxBytes, maxRecords = 100000 } = {}) {
|
|
78
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) { throw new TypeError('Explicit positive spool maxBytes required'); }
|
|
79
|
+
if (!Number.isSafeInteger(maxRecords) || maxRecords <= 0) { throw new TypeError('Positive safe spool maxRecords required'); }
|
|
80
|
+
const records = new Map();
|
|
81
|
+
const targets = new Map();
|
|
82
|
+
const state = { ready: false, bytes: 0, sequence: 0n, droppedRecords: 0, droppedBytes: 0 };
|
|
83
|
+
function forget(pair) {
|
|
84
|
+
const { recipient, record, target } = pair;
|
|
85
|
+
record.pending.delete(recipient);
|
|
86
|
+
const group = targets.get(target);
|
|
87
|
+
group.delete(pair);
|
|
88
|
+
if (!group.size) { targets.delete(target); }
|
|
89
|
+
}
|
|
90
|
+
function remove(record) {
|
|
91
|
+
for (const pair of record.pending.values()) { forget(pair); }
|
|
92
|
+
records.delete(record.id);
|
|
93
|
+
state.bytes -= record.bytes;
|
|
94
|
+
}
|
|
95
|
+
function evict() {
|
|
96
|
+
const oldest = records.values().next().value;
|
|
97
|
+
state.droppedRecords += 1;
|
|
98
|
+
state.droppedBytes += oldest.bytes;
|
|
99
|
+
remove(oldest);
|
|
100
|
+
}
|
|
101
|
+
function append(event, recipients) {
|
|
102
|
+
const incoming = recordOf(event, recipients);
|
|
103
|
+
const existing = records.get(incoming.id);
|
|
104
|
+
if (existing) {
|
|
105
|
+
if (existing.fingerprint !== incoming.fingerprint) { throw new Error('Conflicting event identity'); }
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (incoming.bytes > maxBytes) { throw new Error('Spool capacity exceeded'); }
|
|
109
|
+
while (records.size >= maxRecords || incoming.bytes > maxBytes - state.bytes) { evict(); }
|
|
110
|
+
state.sequence += 1n;
|
|
111
|
+
Object.assign(incoming, { admission: state.sequence.toString() });
|
|
112
|
+
for (const [recipient, target] of incoming.destinations) {
|
|
113
|
+
const group = targets.get(target) ?? new Set();
|
|
114
|
+
const pair = { recipient, target, record: incoming };
|
|
115
|
+
group.add(pair);
|
|
116
|
+
targets.set(target, group);
|
|
117
|
+
incoming.pending.set(recipient, pair);
|
|
118
|
+
}
|
|
119
|
+
records.set(incoming.id, incoming);
|
|
120
|
+
state.bytes += incoming.bytes;
|
|
121
|
+
}
|
|
122
|
+
function acknowledge({ eventId, recipient, admission }) {
|
|
123
|
+
const record = records.get(eventId);
|
|
124
|
+
if (!record || (admission !== undefined && admission !== record.admission)) { return; }
|
|
125
|
+
if (!record.destinations.has(recipient)) { throw new Error('Unknown recipient'); }
|
|
126
|
+
const pair = record.pending.get(recipient);
|
|
127
|
+
if (!pair) { return; }
|
|
128
|
+
if (record.pending.size === 1) { remove(record); return; }
|
|
129
|
+
forget(pair);
|
|
130
|
+
const removedBytes = Buffer.byteLength(JSON.stringify(recipient)) + 1;
|
|
131
|
+
record.bytes -= removedBytes;
|
|
132
|
+
state.bytes -= removedBytes;
|
|
133
|
+
}
|
|
134
|
+
function ready(action) {
|
|
135
|
+
try {
|
|
136
|
+
if (!state.ready) { throw new Error('Spool not opened'); }
|
|
137
|
+
return Promise.resolve(action());
|
|
138
|
+
} catch (error) { return Promise.reject(error); }
|
|
139
|
+
}
|
|
140
|
+
function mutation(operation) {
|
|
141
|
+
try {
|
|
142
|
+
if (operation?.kind === 'append') { append(operation.event, operation.recipients); }
|
|
143
|
+
else if (operation?.kind === 'ack') { acknowledge(operation); }
|
|
144
|
+
else { throw new TypeError('Unknown spool mutation'); }
|
|
145
|
+
return { ok: true };
|
|
146
|
+
} catch (error) { return { ok: false, error }; }
|
|
147
|
+
}
|
|
148
|
+
function pendingFair(limit, blocked) {
|
|
149
|
+
limitOf(limit, 'pending');
|
|
150
|
+
const pages = pagesOf(targets, limit, new Set(blocked));
|
|
151
|
+
const selected = select(pages, limit);
|
|
152
|
+
for (const { target, pairs } of pages) { targets.delete(target); targets.set(target, pairs); }
|
|
153
|
+
return [...selected].map(([record, pairs]) => {
|
|
154
|
+
for (const pair of pairs) {
|
|
155
|
+
const group = targets.get(pair.target);
|
|
156
|
+
group.delete(pair); group.add(pair);
|
|
157
|
+
}
|
|
158
|
+
return { ...decoded(record, pairs.map(({ recipient }) => { return recipient; })), admission: record.admission,
|
|
159
|
+
targets: Object.fromEntries(pairs.map(({ recipient, target }) => { return [recipient, target]; })) };
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
open() { state.ready = true; return Promise.resolve(); },
|
|
164
|
+
mutateMany(operations) {
|
|
165
|
+
return ready(() => {
|
|
166
|
+
if (!Array.isArray(operations) || !operations.length) { throw new TypeError('Nonempty spool mutations required'); }
|
|
167
|
+
return operations.map(mutation);
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
pendingFair(limit = 100, blocked = []) { return ready(() => { return pendingFair(limit, blocked); }); },
|
|
171
|
+
hasAdmission(eventId, admission, recipient) {
|
|
172
|
+
const record = records.get(eventId);
|
|
173
|
+
return record?.admission === admission && Boolean(record?.pending.has(recipient));
|
|
174
|
+
},
|
|
175
|
+
peek(limit = 1000) { return ready(() => { return visibleRecords(records, limit); }); },
|
|
176
|
+
close() {
|
|
177
|
+
records.clear(); targets.clear();
|
|
178
|
+
Object.assign(state, { ready: false, bytes: 0 });
|
|
179
|
+
return Promise.resolve();
|
|
180
|
+
},
|
|
181
|
+
status() {
|
|
182
|
+
return { bytes: state.bytes, maxBytes, recordLimit: maxRecords, pending: records.size, ready: state.ready,
|
|
183
|
+
droppedRecords: state.droppedRecords, droppedBytes: state.droppedBytes };
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { deflateSync, inflateSync } from 'node:zlib';
|
|
3
2
|
|
|
4
3
|
export function digest(value) { return createHash('sha256').update(value).digest('hex'); }
|
|
5
4
|
export function revive(key, value) {
|
|
@@ -13,29 +12,3 @@ export function validate(event, recipients, remaining = recipients) {
|
|
|
13
12
|
throw new TypeError('Event identity and unique recipients required; corrupt spool record');
|
|
14
13
|
}
|
|
15
14
|
}
|
|
16
|
-
export function encoded(event, recipients, remaining = recipients) {
|
|
17
|
-
validate(event, recipients, remaining);
|
|
18
|
-
const original = JSON.stringify(event);
|
|
19
|
-
const snapshot = JSON.parse(original);
|
|
20
|
-
const destinations = Array.isArray(snapshot.destinations) ? snapshot.destinations.map((item) => {
|
|
21
|
-
const json = JSON.stringify(item); return { id: digest(json), json };
|
|
22
|
-
}) : null;
|
|
23
|
-
if (destinations) { snapshot.destinations = []; }
|
|
24
|
-
return {
|
|
25
|
-
id: event.eventId, fingerprint: digest(JSON.stringify({ event, recipients })),
|
|
26
|
-
payload: deflateSync(JSON.stringify(snapshot)), destinations,
|
|
27
|
-
recipients: JSON.stringify(recipients), remaining: JSON.stringify(remaining),
|
|
28
|
-
bytes: Buffer.byteLength(JSON.stringify({ event, recipients, remaining }))
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
export function decoded(row, db) {
|
|
32
|
-
const event = JSON.parse(inflateSync(row.payload).toString(), revive);
|
|
33
|
-
if (row.destinations !== null) {
|
|
34
|
-
event.destinations = JSON.parse(row.destinations).map((id) => {
|
|
35
|
-
const descriptor = db.prepare('SELECT json FROM destinations WHERE id = ?').get(id);
|
|
36
|
-
if (!descriptor) { throw new Error('Corrupt spool destination'); }
|
|
37
|
-
return JSON.parse(descriptor.json, revive);
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
return { event, remaining: JSON.parse(row.remaining) };
|
|
41
|
-
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Process-local compare-and-swap state with a shared byte and record limit. */
|
|
2
|
+
export default function taskStateMemory({ maxBytes = 4 * 1024 * 1024, maxRecords = 1024 } = {}) {
|
|
3
|
+
if (![maxBytes, maxRecords].every(value => { return Number.isSafeInteger(value) && value > 0; })) {
|
|
4
|
+
throw new TypeError('Positive task state limits required');
|
|
5
|
+
}
|
|
6
|
+
const entries = new Map();
|
|
7
|
+
let used = 0;
|
|
8
|
+
let version = 0;
|
|
9
|
+
function remove(taskId) {
|
|
10
|
+
used -= entries.get(taskId).bytes;
|
|
11
|
+
entries.delete(taskId);
|
|
12
|
+
}
|
|
13
|
+
function save(taskId, json, bytes) {
|
|
14
|
+
if (entries.has(taskId)) { remove(taskId); }
|
|
15
|
+
version += 1;
|
|
16
|
+
entries.set(taskId, { json, bytes, version });
|
|
17
|
+
used += bytes;
|
|
18
|
+
return version;
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
load(taskId) {
|
|
22
|
+
const item = entries.get(taskId);
|
|
23
|
+
return Promise.resolve(item ? { ...JSON.parse(item.json), version: item.version } : null);
|
|
24
|
+
},
|
|
25
|
+
commit({ taskId, expectedVersion, ownership, stateVersion, compatibilityKey, checkpoint, pending }) {
|
|
26
|
+
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0) { throw new TypeError('Invalid expectedVersion'); }
|
|
27
|
+
if (ownership !== undefined) { throw new Error('This store has no external ownership integration'); }
|
|
28
|
+
const current = entries.get(taskId);
|
|
29
|
+
if (expectedVersion !== (current?.version ?? 0)) { throw new Error('Task state conflict'); }
|
|
30
|
+
const json = JSON.stringify({ taskId, stateVersion, compatibilityKey, checkpoint, pending });
|
|
31
|
+
const bytes = Buffer.byteLength(json);
|
|
32
|
+
if ((!current && entries.size >= maxRecords) || used - (current?.bytes ?? 0) + bytes > maxBytes) {
|
|
33
|
+
throw new Error('Task state capacity exceeded');
|
|
34
|
+
}
|
|
35
|
+
return Promise.resolve(save(taskId, json, bytes));
|
|
36
|
+
},
|
|
37
|
+
forget(taskId) { if (entries.has(taskId)) { remove(taskId); } },
|
|
38
|
+
close() { entries.clear(); used = 0; }
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
export function checkSnapshot(value) {
|
|
5
|
-
if (!value || !Number.isSafeInteger(value.generation) || value.generation < 0 || !Array.isArray(value.assignments)) { throw new TypeError('Invalid assignment snapshot'); }
|
|
6
|
-
return value;
|
|
7
|
-
}
|
|
8
|
-
export async function loadSnapshot(file) {
|
|
9
|
-
try { return checkSnapshot(JSON.parse(await readFile(file, 'utf8'))); } catch (error) { if (error.code === 'ENOENT') { return null; } throw error; }
|
|
10
|
-
}
|
|
11
|
-
export async function saveSnapshot(file, snapshot) {
|
|
12
|
-
checkSnapshot(snapshot);
|
|
13
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
14
|
-
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
15
|
-
try {
|
|
16
|
-
const handle = await open(temporary, 'wx', 0o600);
|
|
17
|
-
try { await handle.writeFile(JSON.stringify(snapshot)); await handle.sync(); } finally { await handle.close(); }
|
|
18
|
-
await rename(temporary, file);
|
|
19
|
-
const directory = await open(path.dirname(file), 'r');
|
|
20
|
-
try { await directory.sync(); } finally { await directory.close(); }
|
|
21
|
-
} finally { await unlink(temporary).catch(() => {
|
|
22
|
-
// Rename may already have consumed the temporary file.
|
|
23
|
-
}); }
|
|
24
|
-
}
|