@jeffusion/bungee-core 6.11.3 → 6.13.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/dist/config-storage-worker.js +1575 -522
- package/dist/gateway/plugin.js +3 -1
- package/dist/main.js +4992 -3273
- package/dist/observability-worker.js +948 -175
- package/dist/plugin-state-worker.js +1 -0
- package/dist/plugins/anthropic-request-sanitizer/index.js.map +2 -2
- package/dist/plugins/anthropic-tool-name-transformer/index.js.map +2 -2
- package/dist/plugins/chatgpt-oauth/index.js.map +2 -2
- package/dist/plugins/chatgpt-oauth/manifest.json +0 -8
- package/dist/plugins/codex-router/index.js.map +2 -2
- package/dist/plugins/deepseek-reasoning-fix/index.js.map +2 -2
- package/dist/plugins/key-access/index.js.map +2 -2
- package/dist/plugins/key-rate-limit/index.js.map +2 -2
- package/dist/plugins/llm-protocol-adapter/index.js +4 -2
- package/dist/plugins/llm-protocol-adapter/index.js.map +4 -4
- package/dist/plugins/llm-tps/index.js.map +2 -2
- package/dist/plugins/model-mapping/index.js.map +2 -2
- package/dist/plugins/models-dev/index.js +6 -2
- package/dist/plugins/models-dev/index.js.map +4 -4
- package/dist/plugins/request-logs/index.js +1392 -0
- package/dist/plugins/request-logs/index.js.map +33 -0
- package/dist/plugins/request-logs/ingress.js +28 -0
- package/dist/plugins/request-logs/ingress.js.map +10 -0
- package/dist/plugins/request-logs/manifest.json +68 -0
- package/dist/plugins/request-logs/ui/RequestLogsPage.svelte +1130 -0
- package/dist/plugins/request-logs/ui/RequestLogsSettings.svelte +111 -0
- package/dist/plugins/signature-repair/index.js.map +2 -2
- package/dist/plugins/token-budget/index.js.map +2 -2
- package/dist/plugins/token-metering/index.js.map +2 -2
- package/dist/plugins/token-stats/index.js.map +2 -2
- package/dist/plugins/user-auth/index.js.map +2 -2
- package/package.json +2 -2
|
@@ -481,7 +481,9 @@ function hashConfigurationRequest(identity) {
|
|
|
481
481
|
|
|
482
482
|
// ../types/src/daemon-control.ts
|
|
483
483
|
var DAEMON_METADATA_MAX_BYTES = 4 * 1024;
|
|
484
|
+
|
|
484
485
|
// ../types/src/types.ts
|
|
486
|
+
var DEFAULT_BODY_LOG_MAX_BYTES = 64 * 1024;
|
|
485
487
|
var DEFAULT_WEBSOCKET_MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
486
488
|
var MAX_WEBSOCKET_MAX_MESSAGE_BYTES = 2147483647;
|
|
487
489
|
// ../types/src/rate-limit.ts
|
|
@@ -7947,8 +7949,9 @@ function freezePublicationRetirement(db, mutationId, generation, value, now) {
|
|
|
7947
7949
|
return prior;
|
|
7948
7950
|
}
|
|
7949
7951
|
const operation = sqliteGet(db, "SELECT state,drain_recovery_generation FROM configuration_operations WHERE mutation_id=?", mutationId);
|
|
7950
|
-
if (operation === null || operation.state === "converged" || operation.state === "degraded" || operation.drain_recovery_generation !== generation)
|
|
7952
|
+
if (operation === null || operation.state === "converged" || operation.state === "degraded" || operation.state === "superseded" || operation.drain_recovery_generation !== generation) {
|
|
7951
7953
|
invalid2("retirement must match the active publication generation");
|
|
7954
|
+
}
|
|
7952
7955
|
db.run("INSERT INTO configuration_retirements(mutation_id,generation,members_json,state,updated_at) VALUES(?,?,?,'pending',?)", [mutationId, generation, canonicalJson(members), now]);
|
|
7953
7956
|
for (const member of members)
|
|
7954
7957
|
db.run(`INSERT INTO configuration_retirement_evidence(mutation_id,member_id,exit_state,cleanup_state,updated_at)
|
|
@@ -8037,7 +8040,7 @@ function readRetirementDescriptorCleanupState(db, workerInstanceId) {
|
|
|
8037
8040
|
JOIN configuration_operations o USING(mutation_id) WHERE e.member_id=?`, workerInstanceId);
|
|
8038
8041
|
if (!rows.length)
|
|
8039
8042
|
return "absent";
|
|
8040
|
-
return rows.every((row) => row.state === "converged" || row.state === "degraded") ? "terminal" : "pending";
|
|
8043
|
+
return rows.every((row) => row.state === "converged" || row.state === "degraded" || row.state === "superseded") ? "terminal" : "pending";
|
|
8041
8044
|
}
|
|
8042
8045
|
function parseServingMembers(value) {
|
|
8043
8046
|
const input = snapshotJsonGraph(value);
|
|
@@ -8101,7 +8104,7 @@ function freezePublicationServingSet(db, mutationId, generation, input) {
|
|
|
8101
8104
|
return before;
|
|
8102
8105
|
}
|
|
8103
8106
|
const operation = sqliteGet(db, "SELECT state,committed_revision,target_worker_count,drain_recovery_generation FROM configuration_operations WHERE mutation_id=?", mutationId);
|
|
8104
|
-
if (!operation || operation.state === "converged" || operation.state === "degraded" || operation.drain_recovery_generation !== generation || workers.length !== operation.target_worker_count || workers.some((worker) => worker.revision !== operation.committed_revision || worker.publication?.mutation_id !== mutationId || worker.publication.drain_recovery_generation !== generation))
|
|
8107
|
+
if (!operation || operation.state === "converged" || operation.state === "degraded" || operation.state === "superseded" || operation.drain_recovery_generation !== generation || workers.length !== operation.target_worker_count || workers.some((worker) => worker.revision !== operation.committed_revision || worker.publication?.mutation_id !== mutationId || worker.publication.drain_recovery_generation !== generation))
|
|
8105
8108
|
invalid2("publication serving authority does not match the current attempt");
|
|
8106
8109
|
const attemptKey = currentServingAttemptKey(db, mutationId);
|
|
8107
8110
|
if (canonicalJson(workers.map((worker) => [worker.identity.worker_slot, worker.publication.attempt_no]).sort((a, b) => a[0] - b[0])) !== attemptKey) {
|
|
@@ -8259,7 +8262,7 @@ function requireOneOf(value, allowed, field) {
|
|
|
8259
8262
|
// src/config-storage/operation-records.ts
|
|
8260
8263
|
var OPERATION_SELECT = `SELECT mutation_id,request_hash,expected_revision,committed_revision,kind,state,
|
|
8261
8264
|
target_worker_count,result_status,error_code,error_detail,drain_recovery_generation,
|
|
8262
|
-
last_drain_recovery_previous_generation,created_at,updated_at
|
|
8265
|
+
last_drain_recovery_previous_generation,plugin_catalog_hash,cancel_requested,prepare_started,created_at,updated_at
|
|
8263
8266
|
FROM configuration_operations`;
|
|
8264
8267
|
var WORKER_SELECT = `SELECT mutation_id,worker_slot,target_revision,drain_recovery_generation,
|
|
8265
8268
|
attempt_no,last_begin_previous_attempt_no,last_begin_reason,state,applied_revision,last_error,updated_at
|
|
@@ -8285,6 +8288,12 @@ function operationFromRow(row) {
|
|
|
8285
8288
|
}
|
|
8286
8289
|
if (row.updated_at < row.created_at)
|
|
8287
8290
|
throw new ConfigRepositoryError("schema_corrupt", "operation timestamps are invalid");
|
|
8291
|
+
if (row.plugin_catalog_hash !== null && !validateDigest(row.plugin_catalog_hash)) {
|
|
8292
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation plugin catalog identity is invalid");
|
|
8293
|
+
}
|
|
8294
|
+
if (row.cancel_requested !== 0 && row.cancel_requested !== 1 || row.prepare_started !== 0 && row.prepare_started !== 1) {
|
|
8295
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation cancellation flags are invalid");
|
|
8296
|
+
}
|
|
8288
8297
|
const kind = row.kind === "config" ? "config" : "admin_state";
|
|
8289
8298
|
const base = {
|
|
8290
8299
|
mutation_id: row.mutation_id,
|
|
@@ -8295,10 +8304,18 @@ function operationFromRow(row) {
|
|
|
8295
8304
|
target_worker_count: row.target_worker_count,
|
|
8296
8305
|
drain_recovery_generation: row.drain_recovery_generation,
|
|
8297
8306
|
last_drain_recovery_previous_generation: row.last_drain_recovery_previous_generation,
|
|
8307
|
+
plugin_catalog_hash: row.plugin_catalog_hash,
|
|
8308
|
+
cancel_requested: row.cancel_requested === 1,
|
|
8309
|
+
prepare_started: row.prepare_started === 1,
|
|
8298
8310
|
created_at: row.created_at,
|
|
8299
8311
|
updated_at: row.updated_at
|
|
8300
8312
|
};
|
|
8301
8313
|
switch (row.state) {
|
|
8314
|
+
case "pending":
|
|
8315
|
+
if (row.result_status === null && row.error_code === null && row.error_detail === null && row.drain_recovery_generation === 0 && !base.cancel_requested && !base.prepare_started) {
|
|
8316
|
+
return { ...base, state: "pending", result_status: null, error_code: null, error_detail: null };
|
|
8317
|
+
}
|
|
8318
|
+
break;
|
|
8302
8319
|
case "committed":
|
|
8303
8320
|
case "publishing":
|
|
8304
8321
|
case "draining":
|
|
@@ -8306,6 +8323,17 @@ function operationFromRow(row) {
|
|
|
8306
8323
|
return { ...base, state: row.state, result_status: null, error_code: null, error_detail: null };
|
|
8307
8324
|
}
|
|
8308
8325
|
break;
|
|
8326
|
+
case "superseded":
|
|
8327
|
+
if (row.result_status === 409 && row.error_code === "revision_superseded" && row.drain_recovery_generation === 0 && !base.prepare_started && row.error_detail !== null && row.error_detail.length <= 512 && row.error_detail.trim().length > 0) {
|
|
8328
|
+
return {
|
|
8329
|
+
...base,
|
|
8330
|
+
state: "superseded",
|
|
8331
|
+
result_status: 409,
|
|
8332
|
+
error_code: "revision_superseded",
|
|
8333
|
+
error_detail: row.error_detail
|
|
8334
|
+
};
|
|
8335
|
+
}
|
|
8336
|
+
break;
|
|
8309
8337
|
case "converged":
|
|
8310
8338
|
if (row.drain_recovery_generation === 0 && row.result_status === 200 && row.error_code === null && row.error_detail === null) {
|
|
8311
8339
|
return { ...base, state: "converged", result_status: 200, error_code: null, error_detail: null };
|
|
@@ -8381,8 +8409,454 @@ function readAllWorkers(db) {
|
|
|
8381
8409
|
return sqliteAll(db, `${WORKER_SELECT} ORDER BY mutation_id,worker_slot`).map(workerFromRow);
|
|
8382
8410
|
}
|
|
8383
8411
|
|
|
8412
|
+
// src/config-storage/worker-launch-store.ts
|
|
8413
|
+
var INTENT_SELECT = `SELECT worker_instance_id,master_generation,worker_slot,
|
|
8414
|
+
allocation_mutation_id,allocation_worker_slot,allocation_attempt_no,guard_json,registered_at,
|
|
8415
|
+
EXISTS (SELECT 1 FROM configuration_worker_launch_capacity_reclaims reclaim
|
|
8416
|
+
WHERE reclaim.worker_instance_id=configuration_worker_launch_intents.worker_instance_id) AS capacity_reclaimed
|
|
8417
|
+
FROM configuration_worker_launch_intents`;
|
|
8418
|
+
function invalid3(message) {
|
|
8419
|
+
throw new ConfigRepositoryError("invalid_command", message);
|
|
8420
|
+
}
|
|
8421
|
+
function invalidOperation(message) {
|
|
8422
|
+
throw new ConfigRepositoryError("invalid_operation", message);
|
|
8423
|
+
}
|
|
8424
|
+
function natural2(value, minimum = 0) {
|
|
8425
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
|
|
8426
|
+
}
|
|
8427
|
+
function validateIdentity(identity) {
|
|
8428
|
+
if (typeof identity !== "object" || identity === null || !isLowercaseUuid(identity.master_generation) || !isLowercaseUuid(identity.worker_instance_id) || !natural2(identity.worker_slot)) {
|
|
8429
|
+
invalid3("worker launch identity is invalid");
|
|
8430
|
+
}
|
|
8431
|
+
}
|
|
8432
|
+
function validateAllocation(allocation, identity) {
|
|
8433
|
+
if (typeof allocation !== "object" || allocation === null || typeof allocation.mutation_id !== "string" || !validateMutationId(allocation.mutation_id) || !natural2(allocation.worker_slot) || allocation.worker_slot !== identity.worker_slot || !natural2(allocation.attempt_no, 1)) {
|
|
8434
|
+
invalid3("worker launch allocation is invalid");
|
|
8435
|
+
}
|
|
8436
|
+
}
|
|
8437
|
+
function validateAllocationInput(allocation) {
|
|
8438
|
+
if (typeof allocation !== "object" || allocation === null || typeof allocation.mutation_id !== "string" || !validateMutationId(allocation.mutation_id) || !natural2(allocation.worker_slot) || !natural2(allocation.attempt_no, 1)) {
|
|
8439
|
+
invalid3("worker launch allocation is invalid");
|
|
8440
|
+
}
|
|
8441
|
+
}
|
|
8442
|
+
function parseGuard(value) {
|
|
8443
|
+
try {
|
|
8444
|
+
return parseProcessLifetimeGuardFacts(value);
|
|
8445
|
+
} catch {
|
|
8446
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch guard facts are invalid");
|
|
8447
|
+
}
|
|
8448
|
+
}
|
|
8449
|
+
function parseInputGuard(value, identity) {
|
|
8450
|
+
let guard;
|
|
8451
|
+
try {
|
|
8452
|
+
guard = parseProcessLifetimeGuardFacts(value);
|
|
8453
|
+
} catch {
|
|
8454
|
+
invalid3("worker launch guard facts are invalid");
|
|
8455
|
+
}
|
|
8456
|
+
if (guard.process_instance_id !== identity.worker_instance_id) {
|
|
8457
|
+
invalid3("worker launch guard belongs to another process");
|
|
8458
|
+
}
|
|
8459
|
+
return guard;
|
|
8460
|
+
}
|
|
8461
|
+
function sameAllocation(left, right) {
|
|
8462
|
+
return left === null ? right === null : right !== null && left.mutation_id === right.mutation_id && left.worker_slot === right.worker_slot && left.attempt_no === right.attempt_no;
|
|
8463
|
+
}
|
|
8464
|
+
function allocationKey(allocation) {
|
|
8465
|
+
return `${allocation.mutation_id}\x00${allocation.worker_slot}\x00${allocation.attempt_no}`;
|
|
8466
|
+
}
|
|
8467
|
+
function rowAllocation(row) {
|
|
8468
|
+
if (row.allocation_mutation_id === null || row.allocation_worker_slot === null || row.allocation_attempt_no === null)
|
|
8469
|
+
return null;
|
|
8470
|
+
return {
|
|
8471
|
+
mutation_id: row.allocation_mutation_id,
|
|
8472
|
+
worker_slot: row.allocation_worker_slot,
|
|
8473
|
+
attempt_no: row.allocation_attempt_no
|
|
8474
|
+
};
|
|
8475
|
+
}
|
|
8476
|
+
function readFacts(db, instance, allocation) {
|
|
8477
|
+
const rows = allocation === null ? sqliteAll(db, `SELECT kind,recorded_at FROM configuration_worker_launch_facts WHERE worker_instance_id=?`, instance) : sqliteAll(db, `SELECT kind,recorded_at FROM configuration_worker_launch_facts
|
|
8478
|
+
WHERE worker_instance_id=? OR (mutation_id=? AND worker_slot=? AND attempt_no=?)`, instance, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8479
|
+
let admitted = false;
|
|
8480
|
+
let notStarted = false;
|
|
8481
|
+
let exited = false;
|
|
8482
|
+
let cleanup = false;
|
|
8483
|
+
let lastRecordedAt = 0;
|
|
8484
|
+
for (const row of rows) {
|
|
8485
|
+
if (row.kind === "admitted")
|
|
8486
|
+
admitted = true;
|
|
8487
|
+
else if (row.kind === "not_started")
|
|
8488
|
+
notStarted = true;
|
|
8489
|
+
else if (row.kind === "exited")
|
|
8490
|
+
exited = true;
|
|
8491
|
+
else if (row.kind === "cleanup")
|
|
8492
|
+
cleanup = true;
|
|
8493
|
+
lastRecordedAt = Math.max(lastRecordedAt, row.recorded_at);
|
|
8494
|
+
}
|
|
8495
|
+
return { admitted, not_started: notStarted, exited, cleanup_released: cleanup, last_recorded_at: lastRecordedAt };
|
|
8496
|
+
}
|
|
8497
|
+
function launchFromRow(db, row) {
|
|
8498
|
+
if (!isLowercaseUuid(row.worker_instance_id) || !isLowercaseUuid(row.master_generation) || !natural2(row.worker_slot) || !natural2(row.registered_at)) {
|
|
8499
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch intent is invalid");
|
|
8500
|
+
}
|
|
8501
|
+
const allocation = rowAllocation(row);
|
|
8502
|
+
if (row.allocation_mutation_id === null !== (row.allocation_worker_slot === null) || row.allocation_mutation_id === null !== (row.allocation_attempt_no === null) || allocation !== null && (!validateMutationId(allocation.mutation_id) || !natural2(allocation.worker_slot) || !natural2(allocation.attempt_no, 1) || allocation.worker_slot !== row.worker_slot)) {
|
|
8503
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch allocation is invalid");
|
|
8504
|
+
}
|
|
8505
|
+
let guardJson;
|
|
8506
|
+
try {
|
|
8507
|
+
guardJson = JSON.parse(row.guard_json);
|
|
8508
|
+
} catch {
|
|
8509
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch guard facts are invalid");
|
|
8510
|
+
}
|
|
8511
|
+
const guard = parseGuard(guardJson);
|
|
8512
|
+
if (guard.process_instance_id !== row.worker_instance_id) {
|
|
8513
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch guard identity is invalid");
|
|
8514
|
+
}
|
|
8515
|
+
const facts = readFacts(db, row.worker_instance_id, allocation);
|
|
8516
|
+
const capacityReclaimed = row.capacity_reclaimed === 1;
|
|
8517
|
+
if (capacityReclaimed && (!facts.admitted || !facts.exited || facts.not_started)) {
|
|
8518
|
+
throw new ConfigRepositoryError("schema_corrupt", "worker launch capacity reclaim has no admitted exit");
|
|
8519
|
+
}
|
|
8520
|
+
return Object.freeze({
|
|
8521
|
+
identity: Object.freeze({
|
|
8522
|
+
master_generation: row.master_generation,
|
|
8523
|
+
worker_instance_id: row.worker_instance_id,
|
|
8524
|
+
worker_slot: row.worker_slot
|
|
8525
|
+
}),
|
|
8526
|
+
guard,
|
|
8527
|
+
allocation: allocation === null ? null : Object.freeze(allocation),
|
|
8528
|
+
registered_at: row.registered_at,
|
|
8529
|
+
admitted: facts.admitted,
|
|
8530
|
+
not_started: facts.not_started,
|
|
8531
|
+
exited: facts.exited,
|
|
8532
|
+
cleanup_released: facts.cleanup_released,
|
|
8533
|
+
capacity_reclaimed: capacityReclaimed
|
|
8534
|
+
});
|
|
8535
|
+
}
|
|
8536
|
+
function requireIntentRow(db, workerInstanceId) {
|
|
8537
|
+
if (typeof workerInstanceId !== "string" || !isLowercaseUuid(workerInstanceId)) {
|
|
8538
|
+
invalid3("worker launch instance identity is invalid");
|
|
8539
|
+
}
|
|
8540
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?`, workerInstanceId);
|
|
8541
|
+
if (row === null)
|
|
8542
|
+
invalidOperation("worker launch intent was not registered");
|
|
8543
|
+
return row;
|
|
8544
|
+
}
|
|
8545
|
+
function requireTimestamp(updatedAt, minimum) {
|
|
8546
|
+
if (!natural2(updatedAt) || updatedAt < minimum) {
|
|
8547
|
+
invalidOperation("worker launch timestamp regressed or is unsafe");
|
|
8548
|
+
}
|
|
8549
|
+
}
|
|
8550
|
+
function hasFact(db, kind, allocation) {
|
|
8551
|
+
return sqliteGet(db, `SELECT fact_id FROM configuration_worker_launch_facts
|
|
8552
|
+
WHERE kind=? AND mutation_id=? AND worker_slot=? AND attempt_no=?`, kind, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no) !== null;
|
|
8553
|
+
}
|
|
8554
|
+
function insertAllocationFact(db, kind, allocation, updatedAt) {
|
|
8555
|
+
if (!natural2(updatedAt))
|
|
8556
|
+
invalid3("worker launch fact timestamp is invalid");
|
|
8557
|
+
if (hasFact(db, kind, allocation))
|
|
8558
|
+
return;
|
|
8559
|
+
db.run(`INSERT INTO configuration_worker_launch_facts
|
|
8560
|
+
(kind,mutation_id,worker_slot,attempt_no,recorded_at) VALUES (?,?,?,?,?)`, [kind, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no, updatedAt]);
|
|
8561
|
+
}
|
|
8562
|
+
function insertInstanceFact(db, kind, intent, updatedAt) {
|
|
8563
|
+
if (!natural2(updatedAt))
|
|
8564
|
+
invalid3("worker launch fact timestamp is invalid");
|
|
8565
|
+
const allocation = intent.allocation;
|
|
8566
|
+
db.run(`INSERT INTO configuration_worker_launch_facts
|
|
8567
|
+
(kind,mutation_id,worker_slot,attempt_no,worker_instance_id,recorded_at) VALUES (?,?,?,?,?,?)`, [
|
|
8568
|
+
kind,
|
|
8569
|
+
allocation?.mutation_id ?? null,
|
|
8570
|
+
allocation?.worker_slot ?? null,
|
|
8571
|
+
allocation?.attempt_no ?? null,
|
|
8572
|
+
intent.identity.worker_instance_id,
|
|
8573
|
+
updatedAt
|
|
8574
|
+
]);
|
|
8575
|
+
}
|
|
8576
|
+
function requireOpenAllocation(db, allocation, allowCancelled) {
|
|
8577
|
+
const authority = sqliteGet(db, `SELECT o.state,o.cancel_requested,w.attempt_no
|
|
8578
|
+
FROM configuration_operations o
|
|
8579
|
+
JOIN configuration_operation_workers w ON w.mutation_id=o.mutation_id
|
|
8580
|
+
WHERE o.mutation_id=? AND w.worker_slot=?`, allocation.mutation_id, allocation.worker_slot);
|
|
8581
|
+
if (authority === null || authority.state !== "committed" && authority.state !== "publishing" && authority.state !== "draining" || authority.attempt_no !== allocation.attempt_no || !allowCancelled && authority.cancel_requested === 1) {
|
|
8582
|
+
invalidOperation("worker launch allocation is not the current open attempt");
|
|
8583
|
+
}
|
|
8584
|
+
return authority;
|
|
8585
|
+
}
|
|
8586
|
+
function requireReservation(db, allocation) {
|
|
8587
|
+
const row = sqliteGet(db, `SELECT mutation_id,worker_slot,attempt_no,recorded_at FROM configuration_worker_launch_facts
|
|
8588
|
+
WHERE kind='reserved' AND mutation_id=? AND worker_slot=? AND attempt_no=?`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8589
|
+
if (row === null)
|
|
8590
|
+
invalidOperation("worker launch allocation was not reserved");
|
|
8591
|
+
return row;
|
|
8592
|
+
}
|
|
8593
|
+
function candidateEvidenceSettled(db, allocation) {
|
|
8594
|
+
return sqliteGet(db, `SELECT mutation_id FROM configuration_publication_candidate_evidence
|
|
8595
|
+
WHERE mutation_id=? AND worker_slot=? AND attempt_no=? AND
|
|
8596
|
+
(exit_kind='not_started' OR (exit_kind='exited' AND cleanup='released'))`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no) !== null;
|
|
8597
|
+
}
|
|
8598
|
+
function writeWorkerLaunchReservation(db, mutationId, workerSlot, attemptNo, updatedAt) {
|
|
8599
|
+
if (typeof mutationId !== "string" || !validateMutationId(mutationId) || !natural2(workerSlot) || !natural2(attemptNo, 1) || !natural2(updatedAt)) {
|
|
8600
|
+
throw new ConfigRepositoryError("invalid_operation", "worker launch reservation is invalid");
|
|
8601
|
+
}
|
|
8602
|
+
insertAllocationFact(db, "reserved", { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo }, updatedAt);
|
|
8603
|
+
}
|
|
8604
|
+
function fenceWorkerLaunchNotStarted(db, mutationId, workerSlot, attemptNo, updatedAt) {
|
|
8605
|
+
const allocation = { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo };
|
|
8606
|
+
if (typeof mutationId !== "string" || !validateMutationId(mutationId) || !natural2(workerSlot) || !natural2(attemptNo, 1)) {
|
|
8607
|
+
invalid3("worker launch allocation is invalid");
|
|
8608
|
+
}
|
|
8609
|
+
requireOpenAllocation(db, allocation, true);
|
|
8610
|
+
const reservation = requireReservation(db, allocation);
|
|
8611
|
+
if (sqliteGet(db, `SELECT worker_instance_id FROM configuration_worker_launch_intents
|
|
8612
|
+
WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=? LIMIT 1`, mutationId, workerSlot, attemptNo) !== null) {
|
|
8613
|
+
invalidOperation("worker launch intent already registered");
|
|
8614
|
+
}
|
|
8615
|
+
if (hasFact(db, "not_started", allocation))
|
|
8616
|
+
return;
|
|
8617
|
+
requireTimestamp(updatedAt, reservation.recorded_at);
|
|
8618
|
+
insertAllocationFact(db, "not_started", allocation, updatedAt);
|
|
8619
|
+
}
|
|
8620
|
+
function registerWorkerLaunch(db, identity, guard, allocation, updatedAt) {
|
|
8621
|
+
validateIdentity(identity);
|
|
8622
|
+
const parsedGuard = parseInputGuard(guard, identity);
|
|
8623
|
+
const guardJson = canonicalJson(parsedGuard);
|
|
8624
|
+
if (allocation !== null)
|
|
8625
|
+
validateAllocation(allocation, identity);
|
|
8626
|
+
if (!natural2(updatedAt))
|
|
8627
|
+
invalid3("worker launch registration timestamp is invalid");
|
|
8628
|
+
if (allocation !== null) {
|
|
8629
|
+
requireOpenAllocation(db, allocation, false);
|
|
8630
|
+
const reservation = requireReservation(db, allocation);
|
|
8631
|
+
requireTimestamp(updatedAt, reservation.recorded_at);
|
|
8632
|
+
if (hasFact(db, "not_started", allocation)) {
|
|
8633
|
+
invalidOperation("worker launch allocation is fenced not_started");
|
|
8634
|
+
}
|
|
8635
|
+
const byAllocation = sqliteGet(db, `${INTENT_SELECT} WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=?`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8636
|
+
if (byAllocation !== null) {
|
|
8637
|
+
const existing = launchFromRow(db, byAllocation);
|
|
8638
|
+
if (existing.identity.master_generation !== identity.master_generation || existing.identity.worker_instance_id !== identity.worker_instance_id || existing.identity.worker_slot !== identity.worker_slot || canonicalJson(existing.guard) !== guardJson || !sameAllocation(existing.allocation, allocation)) {
|
|
8639
|
+
throw new ConfigRepositoryError("cas_conflict", "worker launch allocation is already registered");
|
|
8640
|
+
}
|
|
8641
|
+
return existing;
|
|
8642
|
+
}
|
|
8643
|
+
}
|
|
8644
|
+
const byInstance = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?`, identity.worker_instance_id);
|
|
8645
|
+
if (byInstance !== null) {
|
|
8646
|
+
const existing = launchFromRow(db, byInstance);
|
|
8647
|
+
if (sameAllocation(existing.allocation, allocation) && existing.identity.master_generation === identity.master_generation && existing.identity.worker_slot === identity.worker_slot && canonicalJson(existing.guard) === guardJson) {
|
|
8648
|
+
return existing;
|
|
8649
|
+
}
|
|
8650
|
+
invalidOperation("worker instance identity was already registered with another launch");
|
|
8651
|
+
}
|
|
8652
|
+
db.run(`INSERT INTO configuration_worker_launch_intents
|
|
8653
|
+
(worker_instance_id,master_generation,worker_slot,allocation_mutation_id,allocation_worker_slot,
|
|
8654
|
+
allocation_attempt_no,guard_json,registered_at) VALUES (?,?,?,?,?,?,?,?)`, [
|
|
8655
|
+
identity.worker_instance_id,
|
|
8656
|
+
identity.master_generation,
|
|
8657
|
+
identity.worker_slot,
|
|
8658
|
+
allocation?.mutation_id ?? null,
|
|
8659
|
+
allocation?.worker_slot ?? null,
|
|
8660
|
+
allocation?.attempt_no ?? null,
|
|
8661
|
+
guardJson,
|
|
8662
|
+
updatedAt
|
|
8663
|
+
]);
|
|
8664
|
+
const saved = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?`, identity.worker_instance_id);
|
|
8665
|
+
if (saved === null)
|
|
8666
|
+
throw new ConfigRepositoryError("repository_failure", "worker launch intent was not persisted");
|
|
8667
|
+
return launchFromRow(db, saved);
|
|
8668
|
+
}
|
|
8669
|
+
function recordWorkerLaunchAdmitted(db, workerInstanceId, updatedAt) {
|
|
8670
|
+
const row = requireIntentRow(db, workerInstanceId);
|
|
8671
|
+
const launch = launchFromRow(db, row);
|
|
8672
|
+
if (launch.not_started || launch.exited) {
|
|
8673
|
+
invalidOperation("worker launch cannot be admitted after exit proof");
|
|
8674
|
+
}
|
|
8675
|
+
if (launch.admitted)
|
|
8676
|
+
return launch;
|
|
8677
|
+
requireTimestamp(updatedAt, Math.max(launch.registered_at, readFacts(db, workerInstanceId, launch.allocation).last_recorded_at));
|
|
8678
|
+
insertInstanceFact(db, "admitted", launch, updatedAt);
|
|
8679
|
+
return launchFromRow(db, row);
|
|
8680
|
+
}
|
|
8681
|
+
function recordWorkerLaunchExit(db, workerInstanceId, evidence, updatedAt) {
|
|
8682
|
+
if (typeof evidence !== "object" || evidence === null || evidence.kind !== "not_started" && (evidence.kind !== "exited" || evidence.cleanup !== "released" && evidence.cleanup !== "unknown")) {
|
|
8683
|
+
invalid3("worker launch exit evidence is invalid");
|
|
8684
|
+
}
|
|
8685
|
+
const row = requireIntentRow(db, workerInstanceId);
|
|
8686
|
+
const launch = launchFromRow(db, row);
|
|
8687
|
+
const candidate = launch.allocation === null ? null : sqliteGet(db, `SELECT exit_kind FROM configuration_publication_candidate_evidence
|
|
8688
|
+
WHERE mutation_id=? AND worker_slot=? AND attempt_no=?`, launch.allocation.mutation_id, launch.allocation.worker_slot, launch.allocation.attempt_no);
|
|
8689
|
+
if (candidate !== null && (evidence.kind === "not_started" && candidate.exit_kind === "exited" || evidence.kind === "exited" && candidate.exit_kind === "not_started")) {
|
|
8690
|
+
throw new ConfigRepositoryError("cas_conflict", "worker launch exit proof conflicts with candidate evidence");
|
|
8691
|
+
}
|
|
8692
|
+
if (evidence.kind === "not_started") {
|
|
8693
|
+
if (launch.exited || launch.cleanup_released) {
|
|
8694
|
+
invalidOperation("worker launch exit proof conflicts with not_started");
|
|
8695
|
+
}
|
|
8696
|
+
if (launch.admitted)
|
|
8697
|
+
invalidOperation("an admitted worker launch cannot be proven not started");
|
|
8698
|
+
if (launch.not_started)
|
|
8699
|
+
return launch;
|
|
8700
|
+
requireTimestamp(updatedAt, Math.max(launch.registered_at, readFacts(db, workerInstanceId, launch.allocation).last_recorded_at));
|
|
8701
|
+
insertInstanceFact(db, "not_started", launch, updatedAt);
|
|
8702
|
+
return launchFromRow(db, row);
|
|
8703
|
+
}
|
|
8704
|
+
if (launch.not_started)
|
|
8705
|
+
invalidOperation("worker launch was already proven not started");
|
|
8706
|
+
let { exited, cleanup_released: cleanupReleased, last_recorded_at: lastRecordedAt } = readFacts(db, workerInstanceId, launch.allocation);
|
|
8707
|
+
if (!exited) {
|
|
8708
|
+
requireTimestamp(updatedAt, Math.max(launch.registered_at, lastRecordedAt));
|
|
8709
|
+
insertInstanceFact(db, "exited", launch, updatedAt);
|
|
8710
|
+
exited = true;
|
|
8711
|
+
lastRecordedAt = updatedAt;
|
|
8712
|
+
}
|
|
8713
|
+
if (evidence.cleanup === "released" && !cleanupReleased) {
|
|
8714
|
+
requireTimestamp(updatedAt, Math.max(launch.registered_at, lastRecordedAt));
|
|
8715
|
+
insertInstanceFact(db, "cleanup", launch, updatedAt);
|
|
8716
|
+
cleanupReleased = true;
|
|
8717
|
+
}
|
|
8718
|
+
return launchFromRow(db, row);
|
|
8719
|
+
}
|
|
8720
|
+
function readWorkerLaunch(db, workerInstanceId) {
|
|
8721
|
+
if (typeof workerInstanceId !== "string" || !isLowercaseUuid(workerInstanceId)) {
|
|
8722
|
+
invalid3("worker launch instance identity is invalid");
|
|
8723
|
+
}
|
|
8724
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE worker_instance_id=?`, workerInstanceId);
|
|
8725
|
+
return row === null ? null : launchFromRow(db, row);
|
|
8726
|
+
}
|
|
8727
|
+
function recordWorkerLaunchCapacityReclaimed(db, workerInstanceId, guard, updatedAt) {
|
|
8728
|
+
const row = requireIntentRow(db, workerInstanceId);
|
|
8729
|
+
const launch = launchFromRow(db, row);
|
|
8730
|
+
if (canonicalJson(parseInputGuard(guard, launch.identity)) !== canonicalJson(launch.guard))
|
|
8731
|
+
invalidOperation("worker launch capacity guard does not match");
|
|
8732
|
+
if (launch.capacity_reclaimed)
|
|
8733
|
+
return;
|
|
8734
|
+
if (!launch.admitted || !launch.exited || launch.not_started || launch.cleanup_released) {
|
|
8735
|
+
invalidOperation("worker launch capacity reclaim requires admitted exit without successful cleanup");
|
|
8736
|
+
}
|
|
8737
|
+
requireTimestamp(updatedAt, Math.max(launch.registered_at, readFacts(db, workerInstanceId, launch.allocation).last_recorded_at));
|
|
8738
|
+
db.run("INSERT INTO configuration_worker_launch_capacity_reclaims (worker_instance_id,recorded_at) VALUES (?,?)", [workerInstanceId, updatedAt]);
|
|
8739
|
+
}
|
|
8740
|
+
function readWorkerLaunchAllocationFacts(db, allocation) {
|
|
8741
|
+
validateAllocationInput(allocation);
|
|
8742
|
+
const intent = sqliteGet(db, `${INTENT_SELECT} WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=?`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8743
|
+
const launch = intent === null ? null : launchFromRow(db, intent);
|
|
8744
|
+
const allocationFacts = sqliteAll(db, `SELECT kind,recorded_at FROM configuration_worker_launch_facts
|
|
8745
|
+
WHERE mutation_id=? AND worker_slot=? AND attempt_no=?`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8746
|
+
const instanceFacts = launch === null ? [] : sqliteAll(db, "SELECT kind,recorded_at FROM configuration_worker_launch_facts WHERE worker_instance_id=?", launch.identity.worker_instance_id);
|
|
8747
|
+
if (launch === null && allocationFacts.length === 0)
|
|
8748
|
+
return null;
|
|
8749
|
+
const times = new Map;
|
|
8750
|
+
for (const fact of [...allocationFacts, ...instanceFacts]) {
|
|
8751
|
+
times.set(fact.kind, Math.max(times.get(fact.kind) ?? 0, fact.recorded_at));
|
|
8752
|
+
}
|
|
8753
|
+
const notStartedAt = times.get("not_started") ?? null;
|
|
8754
|
+
const exitedAt = times.get("exited") ?? null;
|
|
8755
|
+
const cleanupReleasedAt = times.get("cleanup") ?? null;
|
|
8756
|
+
const settled = notStartedAt !== null || exitedAt !== null && cleanupReleasedAt !== null || candidateEvidenceSettled(db, allocation);
|
|
8757
|
+
return Object.freeze({
|
|
8758
|
+
allocation: Object.freeze({ ...allocation }),
|
|
8759
|
+
launch,
|
|
8760
|
+
reserved_at: times.get("reserved") ?? null,
|
|
8761
|
+
not_started_at: notStartedAt,
|
|
8762
|
+
admitted_at: times.get("admitted") ?? null,
|
|
8763
|
+
exited_at: exitedAt,
|
|
8764
|
+
cleanup_released_at: cleanupReleasedAt,
|
|
8765
|
+
settled
|
|
8766
|
+
});
|
|
8767
|
+
}
|
|
8768
|
+
function launchSettled(db, launch) {
|
|
8769
|
+
return launch.not_started || launch.exited && launch.cleanup_released || launch.allocation !== null && candidateEvidenceSettled(db, launch.allocation);
|
|
8770
|
+
}
|
|
8771
|
+
function assertWorkerAttemptLaunchSettled(db, mutationId, workerSlot, attemptNo) {
|
|
8772
|
+
if (attemptNo <= 0)
|
|
8773
|
+
return;
|
|
8774
|
+
const allocation = { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo };
|
|
8775
|
+
if (!hasFact(db, "reserved", allocation))
|
|
8776
|
+
return;
|
|
8777
|
+
if (hasFact(db, "not_started", allocation))
|
|
8778
|
+
return;
|
|
8779
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=?`, mutationId, workerSlot, attemptNo);
|
|
8780
|
+
if (row !== null && launchSettled(db, launchFromRow(db, row)))
|
|
8781
|
+
return;
|
|
8782
|
+
if (row === null && candidateEvidenceSettled(db, allocation))
|
|
8783
|
+
return;
|
|
8784
|
+
invalidOperation("previous worker launch attempt has no exit and cleanup proof");
|
|
8785
|
+
}
|
|
8786
|
+
function assertPublicationLaunchDebtSettled(db, mutationId) {
|
|
8787
|
+
const allocations = sqliteAll(db, `SELECT mutation_id,worker_slot,attempt_no,recorded_at FROM configuration_worker_launch_facts
|
|
8788
|
+
WHERE kind='reserved' AND mutation_id=? ORDER BY worker_slot,attempt_no`, mutationId);
|
|
8789
|
+
const seen = new Set;
|
|
8790
|
+
for (const reservation of allocations) {
|
|
8791
|
+
const allocation = {
|
|
8792
|
+
mutation_id: reservation.mutation_id,
|
|
8793
|
+
worker_slot: reservation.worker_slot,
|
|
8794
|
+
attempt_no: reservation.attempt_no
|
|
8795
|
+
};
|
|
8796
|
+
seen.add(allocationKey(allocation));
|
|
8797
|
+
if (hasFact(db, "not_started", allocation))
|
|
8798
|
+
continue;
|
|
8799
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=?`, mutationId, reservation.worker_slot, reservation.attempt_no);
|
|
8800
|
+
if (row === null) {
|
|
8801
|
+
invalidOperation("unregistered worker launch blocks degraded finalization");
|
|
8802
|
+
}
|
|
8803
|
+
const launch = launchFromRow(db, row);
|
|
8804
|
+
if (launch.admitted || launchSettled(db, launch))
|
|
8805
|
+
continue;
|
|
8806
|
+
invalidOperation("unsettled worker launch blocks degraded finalization");
|
|
8807
|
+
}
|
|
8808
|
+
const unallocated = sqliteAll(db, `${INTENT_SELECT} WHERE allocation_mutation_id=?`, mutationId);
|
|
8809
|
+
for (const row of unallocated) {
|
|
8810
|
+
const allocation = rowAllocation(row);
|
|
8811
|
+
if (allocation === null || seen.has(allocationKey(allocation)))
|
|
8812
|
+
continue;
|
|
8813
|
+
const launch = launchFromRow(db, row);
|
|
8814
|
+
if (launch.admitted || launchSettled(db, launch))
|
|
8815
|
+
continue;
|
|
8816
|
+
invalidOperation("unsettled worker launch blocks degraded finalization");
|
|
8817
|
+
}
|
|
8818
|
+
}
|
|
8819
|
+
function readWorkerLaunchInventory(db) {
|
|
8820
|
+
const result = [];
|
|
8821
|
+
const handled = new Set;
|
|
8822
|
+
const reservations = sqliteAll(db, `SELECT mutation_id,worker_slot,attempt_no,recorded_at FROM configuration_worker_launch_facts
|
|
8823
|
+
WHERE kind='reserved' ORDER BY mutation_id,worker_slot,attempt_no`);
|
|
8824
|
+
for (const reservation of reservations) {
|
|
8825
|
+
const allocation = {
|
|
8826
|
+
mutation_id: reservation.mutation_id,
|
|
8827
|
+
worker_slot: reservation.worker_slot,
|
|
8828
|
+
attempt_no: reservation.attempt_no
|
|
8829
|
+
};
|
|
8830
|
+
const key = allocationKey(allocation);
|
|
8831
|
+
const row = sqliteGet(db, `${INTENT_SELECT} WHERE allocation_mutation_id=? AND allocation_worker_slot=? AND allocation_attempt_no=?`, allocation.mutation_id, allocation.worker_slot, allocation.attempt_no);
|
|
8832
|
+
if (row !== null) {
|
|
8833
|
+
handled.add(key);
|
|
8834
|
+
const launch = launchFromRow(db, row);
|
|
8835
|
+
if (!launchSettled(db, launch))
|
|
8836
|
+
result.push({ kind: "launch", launch });
|
|
8837
|
+
continue;
|
|
8838
|
+
}
|
|
8839
|
+
if (hasFact(db, "not_started", allocation) || candidateEvidenceSettled(db, allocation))
|
|
8840
|
+
continue;
|
|
8841
|
+
result.push({ kind: "reservation", allocation });
|
|
8842
|
+
}
|
|
8843
|
+
const intents = sqliteAll(db, `${INTENT_SELECT} ORDER BY registered_at,worker_instance_id`);
|
|
8844
|
+
for (const row of intents) {
|
|
8845
|
+
const allocation = rowAllocation(row);
|
|
8846
|
+
if (allocation !== null && handled.has(allocationKey(allocation)))
|
|
8847
|
+
continue;
|
|
8848
|
+
const launch = launchFromRow(db, row);
|
|
8849
|
+
if (!launchSettled(db, launch))
|
|
8850
|
+
result.push({ kind: "launch", launch });
|
|
8851
|
+
}
|
|
8852
|
+
return Object.freeze(result);
|
|
8853
|
+
}
|
|
8854
|
+
function readUnsettledWorkerLaunches(db) {
|
|
8855
|
+
return Object.freeze(readWorkerLaunchInventory(db).filter((item) => item.kind === "reservation" || !item.launch.admitted));
|
|
8856
|
+
}
|
|
8857
|
+
|
|
8384
8858
|
// src/config-storage/operation-store.ts
|
|
8385
|
-
function
|
|
8859
|
+
function requireTimestamp2(updatedAt, operation) {
|
|
8386
8860
|
if (!Number.isSafeInteger(updatedAt) || updatedAt < operation.updated_at) {
|
|
8387
8861
|
throw new ConfigRepositoryError("invalid_operation", "operation timestamp regressed or is unsafe");
|
|
8388
8862
|
}
|
|
@@ -8393,9 +8867,25 @@ function requireOperation(db, mutationId) {
|
|
|
8393
8867
|
throw new ConfigRepositoryError("invalid_operation", "configuration operation was not found");
|
|
8394
8868
|
return operation;
|
|
8395
8869
|
}
|
|
8870
|
+
function finalizeOfflineOperation(db, mutationId, updatedAt) {
|
|
8871
|
+
const operation = requireOperation(db, mutationId);
|
|
8872
|
+
if (operation.state === "converged")
|
|
8873
|
+
return operation;
|
|
8874
|
+
if (operation.state !== "pending" || operation.target_worker_count !== 0) {
|
|
8875
|
+
throw new ConfigRepositoryError("invalid_operation", "offline operation must be an unstarted target-free change");
|
|
8876
|
+
}
|
|
8877
|
+
requireTimestamp2(updatedAt, operation);
|
|
8878
|
+
db.run(`UPDATE configuration_operations
|
|
8879
|
+
SET state='converged',result_status=200,error_code=NULL,error_detail=NULL,updated_at=?
|
|
8880
|
+
WHERE mutation_id=? AND state='pending'`, [updatedAt, mutationId]);
|
|
8881
|
+
const terminal = getOperation(db, mutationId);
|
|
8882
|
+
if (terminal === null)
|
|
8883
|
+
throw new ConfigRepositoryError("repository_failure", "offline operation finalization failed");
|
|
8884
|
+
return terminal;
|
|
8885
|
+
}
|
|
8396
8886
|
function beginPublication(db, mutationId, updatedAt) {
|
|
8397
8887
|
const operation = requireOperation(db, mutationId);
|
|
8398
|
-
|
|
8888
|
+
requireTimestamp2(updatedAt, operation);
|
|
8399
8889
|
if (operation.state === "publishing")
|
|
8400
8890
|
return operation;
|
|
8401
8891
|
if (operation.state !== "committed")
|
|
@@ -8405,7 +8895,7 @@ function beginPublication(db, mutationId, updatedAt) {
|
|
|
8405
8895
|
}
|
|
8406
8896
|
function beginWorkerAttempt(db, mutationId, workerSlot, previousAttemptNo, reason, updatedAt) {
|
|
8407
8897
|
const operation = requireOperation(db, mutationId);
|
|
8408
|
-
if (operation.state !== "publishing" && operation.state !== "draining" || !Number.isSafeInteger(workerSlot) || workerSlot < 0 || !Number.isSafeInteger(previousAttemptNo) || previousAttemptNo < 0 || previousAttemptNo >= Number.MAX_SAFE_INTEGER) {
|
|
8898
|
+
if (operation.state !== "publishing" && operation.state !== "draining" || operation.cancel_requested || !Number.isSafeInteger(workerSlot) || workerSlot < 0 || !Number.isSafeInteger(previousAttemptNo) || previousAttemptNo < 0 || previousAttemptNo >= Number.MAX_SAFE_INTEGER) {
|
|
8409
8899
|
throw new ConfigRepositoryError("invalid_operation", "worker begin command is invalid");
|
|
8410
8900
|
}
|
|
8411
8901
|
const row = sqliteGet(db, `${WORKER_SELECT} WHERE mutation_id=? AND worker_slot=?`, mutationId, workerSlot);
|
|
@@ -8417,13 +8907,15 @@ function beginWorkerAttempt(db, mutationId, workerSlot, previousAttemptNo, reaso
|
|
|
8417
8907
|
}
|
|
8418
8908
|
if (worker.attempt_no === previousAttemptNo + 1 && worker.last_begin_previous_attempt_no === previousAttemptNo && worker.last_begin_reason === reason)
|
|
8419
8909
|
return worker;
|
|
8420
|
-
|
|
8910
|
+
assertWorkerAttemptLaunchSettled(db, mutationId, workerSlot, previousAttemptNo);
|
|
8911
|
+
requireTimestamp2(updatedAt, operation);
|
|
8421
8912
|
const valid = worker.attempt_no === previousAttemptNo && (operation.state === "publishing" ? worker.state === "pending" && previousAttemptNo === 0 && reason === "initial" || worker.state === "failed" && reason === "retry" || reason === "master_recovery" : worker.state === "failed" && reason === "retry");
|
|
8422
8913
|
if (!valid)
|
|
8423
8914
|
throw new ConfigRepositoryError("invalid_operation", "worker begin transition is invalid");
|
|
8424
8915
|
const attemptNo = previousAttemptNo + 1;
|
|
8425
8916
|
db.run(`UPDATE configuration_operation_workers SET attempt_no=?,last_begin_previous_attempt_no=?,last_begin_reason=?,
|
|
8426
8917
|
state='pending',applied_revision=NULL,last_error=NULL,updated_at=? WHERE mutation_id=? AND worker_slot=?`, [attemptNo, previousAttemptNo, reason, updatedAt, mutationId, workerSlot]);
|
|
8918
|
+
writeWorkerLaunchReservation(db, mutationId, workerSlot, attemptNo, updatedAt);
|
|
8427
8919
|
db.run("UPDATE configuration_operations SET updated_at=? WHERE mutation_id=?", [updatedAt, mutationId]);
|
|
8428
8920
|
const updated = sqliteGet(db, `${WORKER_SELECT} WHERE mutation_id=? AND worker_slot=?`, mutationId, workerSlot);
|
|
8429
8921
|
if (updated === null)
|
|
@@ -8450,7 +8942,7 @@ function recordWorkerResult(db, mutationId, workerSlot, result, updatedAt) {
|
|
|
8450
8942
|
if (operation.state !== "publishing" && operation.state !== "draining") {
|
|
8451
8943
|
throw new ConfigRepositoryError("invalid_operation", "operation is not publishing or draining");
|
|
8452
8944
|
}
|
|
8453
|
-
|
|
8945
|
+
requireTimestamp2(updatedAt, operation);
|
|
8454
8946
|
if (result.kind === "converged") {
|
|
8455
8947
|
if (result.applied_revision !== worker.target_revision) {
|
|
8456
8948
|
throw new ConfigRepositoryError("invalid_operation", "worker applied revision does not match target");
|
|
@@ -8496,7 +8988,10 @@ function finalizePublication(db, mutationId, outcome, updatedAt) {
|
|
|
8496
8988
|
return operation;
|
|
8497
8989
|
throw new ConfigRepositoryError("invalid_operation", "terminal finalization conflicts with durable result");
|
|
8498
8990
|
}
|
|
8499
|
-
|
|
8991
|
+
if (operation.cancel_requested) {
|
|
8992
|
+
throw new ConfigRepositoryError("invalid_operation", "cancelled candidate must be superseded after exit proof");
|
|
8993
|
+
}
|
|
8994
|
+
requireTimestamp2(updatedAt, operation);
|
|
8500
8995
|
if (controlReadinessFailure) {
|
|
8501
8996
|
if (outcome.error_detail.length > 512 || outcome.error_detail.trim().length === 0) {
|
|
8502
8997
|
throw new ConfigRepositoryError("invalid_operation", "terminal error detail is invalid");
|
|
@@ -8544,9 +9039,10 @@ function markDraining(db, mutationId, updatedAt) {
|
|
|
8544
9039
|
const operation = requireOperation(db, mutationId);
|
|
8545
9040
|
if (operation.state === "draining")
|
|
8546
9041
|
return operation;
|
|
8547
|
-
|
|
8548
|
-
if (operation.state !== "publishing")
|
|
8549
|
-
throw new ConfigRepositoryError("invalid_operation", "operation is not
|
|
9042
|
+
requireTimestamp2(updatedAt, operation);
|
|
9043
|
+
if (operation.state !== "publishing" || operation.cancel_requested) {
|
|
9044
|
+
throw new ConfigRepositoryError("invalid_operation", "operation is not a running candidate");
|
|
9045
|
+
}
|
|
8550
9046
|
const workers = readOperationWorkers(db, mutationId);
|
|
8551
9047
|
if (workers.some(({ state, attempt_no }) => state !== "converged" || attempt_no === 0)) {
|
|
8552
9048
|
throw new ConfigRepositoryError("invalid_operation", "all frozen targets must converge before draining");
|
|
@@ -8559,12 +9055,12 @@ function beginDrainingRecovery(db, mutationId, previousGeneration, updatedAt) {
|
|
|
8559
9055
|
if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 0 || previousGeneration >= Number.MAX_SAFE_INTEGER || !Number.isSafeInteger(updatedAt) || updatedAt < 0) {
|
|
8560
9056
|
throw new ConfigRepositoryError("invalid_operation", "draining recovery command is invalid");
|
|
8561
9057
|
}
|
|
8562
|
-
if (operation.state !== "draining") {
|
|
9058
|
+
if (operation.state !== "draining" || operation.cancel_requested) {
|
|
8563
9059
|
throw new ConfigRepositoryError("invalid_operation", "operation is not draining");
|
|
8564
9060
|
}
|
|
8565
9061
|
if (operation.drain_recovery_generation === previousGeneration + 1 && operation.last_drain_recovery_previous_generation === previousGeneration)
|
|
8566
9062
|
return operation;
|
|
8567
|
-
|
|
9063
|
+
requireTimestamp2(updatedAt, operation);
|
|
8568
9064
|
if (operation.drain_recovery_generation !== previousGeneration) {
|
|
8569
9065
|
throw new ConfigRepositoryError("invalid_operation", "draining recovery generation is stale or future");
|
|
8570
9066
|
}
|
|
@@ -8574,6 +9070,7 @@ function beginDrainingRecovery(db, mutationId, previousGeneration, updatedAt) {
|
|
|
8574
9070
|
}
|
|
8575
9071
|
const nextGeneration = previousGeneration + 1;
|
|
8576
9072
|
for (const worker of workers) {
|
|
9073
|
+
assertWorkerAttemptLaunchSettled(db, mutationId, worker.worker_slot, worker.attempt_no);
|
|
8577
9074
|
db.run(`UPDATE configuration_operation_workers SET attempt_no=?,last_begin_previous_attempt_no=?,
|
|
8578
9075
|
last_begin_reason='master_recovery',drain_recovery_generation=?,state='pending',
|
|
8579
9076
|
applied_revision=NULL,last_error=NULL,updated_at=?
|
|
@@ -8585,6 +9082,7 @@ function beginDrainingRecovery(db, mutationId, previousGeneration, updatedAt) {
|
|
|
8585
9082
|
mutationId,
|
|
8586
9083
|
worker.worker_slot
|
|
8587
9084
|
]);
|
|
9085
|
+
writeWorkerLaunchReservation(db, mutationId, worker.worker_slot, worker.attempt_no + 1, updatedAt);
|
|
8588
9086
|
}
|
|
8589
9087
|
db.run(`UPDATE configuration_operations SET drain_recovery_generation=?,
|
|
8590
9088
|
last_drain_recovery_previous_generation=?,updated_at=? WHERE mutation_id=?`, [nextGeneration, previousGeneration, updatedAt, mutationId]);
|
|
@@ -8596,234 +9094,127 @@ function beginDrainingRecovery(db, mutationId, previousGeneration, updatedAt) {
|
|
|
8596
9094
|
};
|
|
8597
9095
|
}
|
|
8598
9096
|
|
|
8599
|
-
// src/config-storage/
|
|
8600
|
-
function
|
|
8601
|
-
|
|
8602
|
-
|
|
8603
|
-
|
|
8604
|
-
...readManagementRequestIdentity(db, operation.mutation_id),
|
|
8605
|
-
kind: operation.kind,
|
|
8606
|
-
expected_revision: operation.expected_revision,
|
|
8607
|
-
aggregate: snapshot.aggregate,
|
|
8608
|
-
target_worker_slots: workers.map((worker) => worker.worker_slot).sort((left, right) => left - right)
|
|
8609
|
-
})) {
|
|
8610
|
-
throw new ConfigRepositoryError("schema_corrupt", "active operation identity is incoherent");
|
|
8611
|
-
}
|
|
9097
|
+
// src/config-storage/consistent-read.ts
|
|
9098
|
+
function withConsistentRead(db, fn) {
|
|
9099
|
+
if (db.inTransaction)
|
|
9100
|
+
return fn();
|
|
9101
|
+
return db.transaction(fn).deferred();
|
|
8612
9102
|
}
|
|
8613
|
-
|
|
8614
|
-
|
|
8615
|
-
|
|
9103
|
+
|
|
9104
|
+
// src/config-storage/serving-snapshot.ts
|
|
9105
|
+
var MAX_AGGREGATE_BYTES = 1048576;
|
|
9106
|
+
function invalid4(message) {
|
|
9107
|
+
throw new ConfigRepositoryError("invalid_configuration", message);
|
|
9108
|
+
}
|
|
9109
|
+
function corrupt2(message) {
|
|
9110
|
+
throw new ConfigRepositoryError("serving_snapshot_corrupt", message);
|
|
9111
|
+
}
|
|
9112
|
+
function canonicalAggregate(aggregate) {
|
|
9113
|
+
const result = parseNormalizeCompileAggregate(aggregate, undefined);
|
|
9114
|
+
if (!result.ok)
|
|
9115
|
+
invalid4("configuration aggregate is invalid");
|
|
9116
|
+
const aggregateJson = canonicalJson(result.value);
|
|
9117
|
+
const bytes = new TextEncoder().encode(aggregateJson).byteLength;
|
|
9118
|
+
if (bytes < 2 || bytes > MAX_AGGREGATE_BYTES) {
|
|
9119
|
+
invalid4("configuration aggregate is too large");
|
|
8616
9120
|
}
|
|
8617
|
-
|
|
8618
|
-
|
|
9121
|
+
return { aggregateJson, contentHash: hashConfigurationContent(result.value) };
|
|
9122
|
+
}
|
|
9123
|
+
function writeServingSnapshot(db, snapshot, pluginCatalogHash) {
|
|
9124
|
+
if (!Number.isSafeInteger(snapshot?.revision) || snapshot.revision <= 0 || typeof snapshot.content_hash !== "string" || !validateDigest(snapshot.content_hash) || !validateDigest(pluginCatalogHash)) {
|
|
9125
|
+
invalid4("serving snapshot identity is invalid");
|
|
8619
9126
|
}
|
|
8620
|
-
|
|
8621
|
-
|
|
9127
|
+
const normalized = canonicalAggregate(snapshot.aggregate);
|
|
9128
|
+
if (normalized.contentHash !== snapshot.content_hash) {
|
|
9129
|
+
invalid4("configuration aggregate content hash does not match");
|
|
8622
9130
|
}
|
|
8623
|
-
|
|
8624
|
-
|
|
9131
|
+
const revision = sqliteGet(db, "SELECT revision,content_hash FROM configuration_revisions WHERE revision=?", snapshot.revision);
|
|
9132
|
+
if (revision === null || revision.content_hash !== snapshot.content_hash) {
|
|
9133
|
+
invalid4("serving snapshot revision does not match configuration history");
|
|
8625
9134
|
}
|
|
8626
|
-
|
|
8627
|
-
|
|
8628
|
-
|
|
8629
|
-
|
|
9135
|
+
const existing = sqliteGet(db, `SELECT revision,content_hash,plugin_catalog_hash,aggregate_json
|
|
9136
|
+
FROM configuration_serving_snapshots
|
|
9137
|
+
WHERE revision=? AND content_hash=? AND plugin_catalog_hash=?`, snapshot.revision, snapshot.content_hash, pluginCatalogHash);
|
|
9138
|
+
if (existing !== null) {
|
|
9139
|
+
if (existing.aggregate_json !== normalized.aggregateJson) {
|
|
9140
|
+
corrupt2("configuration serving snapshot is immutable and inconsistent");
|
|
8630
9141
|
}
|
|
9142
|
+
return;
|
|
8631
9143
|
}
|
|
8632
|
-
|
|
8633
|
-
|
|
8634
|
-
|
|
8635
|
-
|
|
8636
|
-
|
|
8637
|
-
|
|
8638
|
-
|
|
8639
|
-
|
|
9144
|
+
db.run(`INSERT INTO configuration_serving_snapshots
|
|
9145
|
+
(revision,content_hash,plugin_catalog_hash,aggregate_json) VALUES (?,?,?,?)`, [snapshot.revision, snapshot.content_hash, pluginCatalogHash, normalized.aggregateJson]);
|
|
9146
|
+
}
|
|
9147
|
+
function appendServingSnapshot(db, snapshot, pluginCatalogHash) {
|
|
9148
|
+
db.transaction(() => writeServingSnapshot(db, snapshot, pluginCatalogHash)).immediate();
|
|
9149
|
+
}
|
|
9150
|
+
function getServingSnapshot(db, key) {
|
|
9151
|
+
if (!Number.isSafeInteger(key?.revision) || key.revision <= 0 || typeof key.content_hash !== "string" || !validateDigest(key.content_hash) || typeof key.plugin_catalog_hash !== "string" || !validateDigest(key.plugin_catalog_hash)) {
|
|
9152
|
+
invalid4("serving snapshot lookup identity is invalid");
|
|
8640
9153
|
}
|
|
8641
|
-
|
|
8642
|
-
|
|
8643
|
-
|
|
9154
|
+
return withConsistentRead(db, () => {
|
|
9155
|
+
const row = sqliteGet(db, `SELECT revision,content_hash,plugin_catalog_hash,aggregate_json
|
|
9156
|
+
FROM configuration_serving_snapshots
|
|
9157
|
+
WHERE revision=? AND content_hash=? AND plugin_catalog_hash=?`, key.revision, key.content_hash, key.plugin_catalog_hash);
|
|
9158
|
+
if (row === null)
|
|
9159
|
+
return null;
|
|
9160
|
+
if (row.revision !== key.revision || row.content_hash !== key.content_hash || row.plugin_catalog_hash !== key.plugin_catalog_hash || !Number.isSafeInteger(row.revision) || row.revision <= 0 || !validateDigest(row.content_hash) || !validateDigest(row.plugin_catalog_hash)) {
|
|
9161
|
+
corrupt2("configuration serving snapshot identity is invalid");
|
|
8644
9162
|
}
|
|
8645
|
-
|
|
8646
|
-
|
|
9163
|
+
const bytes = new TextEncoder().encode(row.aggregate_json).byteLength;
|
|
9164
|
+
if (bytes < 2 || bytes > MAX_AGGREGATE_BYTES)
|
|
9165
|
+
corrupt2("configuration serving snapshot size is invalid");
|
|
9166
|
+
let parsed;
|
|
9167
|
+
try {
|
|
9168
|
+
parsed = JSON.parse(row.aggregate_json);
|
|
9169
|
+
} catch {
|
|
9170
|
+
corrupt2("configuration serving snapshot JSON is invalid");
|
|
8647
9171
|
}
|
|
8648
|
-
|
|
8649
|
-
|
|
9172
|
+
let canonical;
|
|
9173
|
+
try {
|
|
9174
|
+
canonical = canonicalJson(parsed);
|
|
9175
|
+
} catch {
|
|
9176
|
+
corrupt2("configuration serving snapshot JSON is invalid");
|
|
8650
9177
|
}
|
|
8651
|
-
if (
|
|
8652
|
-
|
|
9178
|
+
if (canonical !== row.aggregate_json)
|
|
9179
|
+
corrupt2("configuration serving snapshot JSON is not canonical");
|
|
9180
|
+
const normalized = parseNormalizeCompileAggregate(parsed, undefined);
|
|
9181
|
+
if (!normalized.ok) {
|
|
9182
|
+
if (normalized.errors.some((error) => error.code === "unknown_field" && /^logical_configuration\.routes\[\d+\]\.(service_id|service)$/.test(error.path))) {
|
|
9183
|
+
throw new ConfigRepositoryError("invalid_configuration", "historical serving snapshot does not use the current configuration schema and cannot be loaded");
|
|
9184
|
+
}
|
|
9185
|
+
corrupt2("configuration serving snapshot aggregate is invalid");
|
|
8653
9186
|
}
|
|
8654
|
-
|
|
8655
|
-
|
|
8656
|
-
|
|
8657
|
-
|
|
8658
|
-
|
|
8659
|
-
|
|
8660
|
-
|
|
8661
|
-
|
|
8662
|
-
|
|
8663
|
-
|
|
8664
|
-
|
|
8665
|
-
|
|
8666
|
-
case "degraded":
|
|
8667
|
-
throw new ConfigRepositoryError("schema_corrupt", "terminal operation matched active publication query");
|
|
8668
|
-
}
|
|
9187
|
+
if (canonicalJson(normalized.value) !== row.aggregate_json) {
|
|
9188
|
+
corrupt2("configuration serving snapshot aggregate normalization drifted");
|
|
9189
|
+
}
|
|
9190
|
+
if (hashConfigurationContent(normalized.value) !== key.content_hash) {
|
|
9191
|
+
corrupt2("configuration serving snapshot content hash is invalid");
|
|
9192
|
+
}
|
|
9193
|
+
const revision = sqliteGet(db, "SELECT revision,content_hash FROM configuration_revisions WHERE revision=?", key.revision);
|
|
9194
|
+
if (revision === null || revision.revision !== key.revision || revision.content_hash !== key.content_hash) {
|
|
9195
|
+
corrupt2("configuration serving snapshot revision is invalid");
|
|
9196
|
+
}
|
|
9197
|
+
return { revision: row.revision, content_hash: row.content_hash, aggregate: normalized.value };
|
|
9198
|
+
});
|
|
8669
9199
|
}
|
|
8670
|
-
function
|
|
8671
|
-
const
|
|
8672
|
-
|
|
8673
|
-
|
|
8674
|
-
const
|
|
8675
|
-
|
|
8676
|
-
|
|
8677
|
-
|
|
8678
|
-
|
|
8679
|
-
|
|
8680
|
-
|
|
8681
|
-
|
|
8682
|
-
|
|
8683
|
-
|
|
8684
|
-
|
|
8685
|
-
|
|
8686
|
-
|
|
8687
|
-
return null;
|
|
8688
|
-
const operation = requireActiveOperation(row);
|
|
8689
|
-
const targets = readOperationWorkers(db, operation.mutation_id);
|
|
8690
|
-
validateActiveOperationIdentity(db, operation, targets, snapshot);
|
|
8691
|
-
const uniqueSlots = new Set(targets.map(({ worker_slot }) => worker_slot));
|
|
8692
|
-
if (targets.length !== operation.target_worker_count || uniqueSlots.size !== targets.length) {
|
|
8693
|
-
throw new ConfigRepositoryError("schema_corrupt", "active publication target cardinality is incoherent");
|
|
8694
|
-
}
|
|
8695
|
-
if (snapshot.revision !== operation.committed_revision || targets.some(({ target_revision }) => target_revision !== snapshot.revision)) {
|
|
8696
|
-
throw new ConfigRepositoryError("schema_corrupt", "active publication revision is incoherent");
|
|
9200
|
+
function auditServingSnapshotHistory(db) {
|
|
9201
|
+
const rows = db.query(`SELECT s.revision,s.content_hash,s.plugin_catalog_hash,s.aggregate_json,
|
|
9202
|
+
r.content_hash AS revision_hash FROM configuration_serving_snapshots s
|
|
9203
|
+
LEFT JOIN configuration_revisions r ON r.revision=s.revision`).all();
|
|
9204
|
+
for (const row of rows) {
|
|
9205
|
+
if (row.revision_hash !== row.content_hash || !validateDigest(row.content_hash) || !validateDigest(row.plugin_catalog_hash)) {
|
|
9206
|
+
corrupt2("historical serving snapshot identity is invalid");
|
|
9207
|
+
}
|
|
9208
|
+
try {
|
|
9209
|
+
const parsed = JSON.parse(row.aggregate_json);
|
|
9210
|
+
if (new TextEncoder().encode(row.aggregate_json).byteLength > MAX_AGGREGATE_BYTES || canonicalJson(parsed) !== row.aggregate_json || hashConfigurationContent(parsed) !== row.content_hash)
|
|
9211
|
+
corrupt2("historical serving snapshot content is invalid");
|
|
9212
|
+
} catch (error) {
|
|
9213
|
+
if (error instanceof ConfigRepositoryError)
|
|
9214
|
+
throw error;
|
|
9215
|
+
corrupt2("historical serving snapshot JSON is invalid");
|
|
9216
|
+
}
|
|
8697
9217
|
}
|
|
8698
|
-
return { operation, snapshot, targets };
|
|
8699
|
-
}
|
|
8700
|
-
|
|
8701
|
-
// src/config-storage/materialize.ts
|
|
8702
|
-
function writeBindings(db, bindings, owner) {
|
|
8703
|
-
for (const binding of bindings) {
|
|
8704
|
-
db.run(`INSERT INTO plugin_bindings
|
|
8705
|
-
(id,scope_kind,scope_owner,service_id,route_id,upstream_id,position,plugin_name,options_json,enabled)
|
|
8706
|
-
VALUES (?,?,?,?,?,?,?,?,?,?)`, [
|
|
8707
|
-
binding.id,
|
|
8708
|
-
owner.kind,
|
|
8709
|
-
owner.id,
|
|
8710
|
-
owner.kind === "service" ? owner.id : null,
|
|
8711
|
-
owner.kind === "route" ? owner.id : null,
|
|
8712
|
-
owner.kind === "upstream" ? owner.id : null,
|
|
8713
|
-
binding.position,
|
|
8714
|
-
binding.name,
|
|
8715
|
-
binding.options === undefined ? null : canonicalJson(binding.options),
|
|
8716
|
-
binding.enabled ? 1 : 0
|
|
8717
|
-
]);
|
|
8718
|
-
}
|
|
8719
|
-
}
|
|
8720
|
-
function upstreamPolicy(upstream) {
|
|
8721
|
-
const { id, position, target, weight, priority, is_disabled, plugins, ...policy } = upstream;
|
|
8722
|
-
return policy;
|
|
8723
|
-
}
|
|
8724
|
-
function writeUpstreams(db, upstreams, owner) {
|
|
8725
|
-
for (const upstream of upstreams) {
|
|
8726
|
-
db.run(`INSERT INTO upstreams
|
|
8727
|
-
(id,owner_kind,service_id,route_id,position,target,weight,priority,is_disabled,policy_json)
|
|
8728
|
-
VALUES (?,?,?,?,?,?,?,?,?,?)`, [
|
|
8729
|
-
upstream.id,
|
|
8730
|
-
owner.kind,
|
|
8731
|
-
owner.kind === "service" ? owner.id : null,
|
|
8732
|
-
owner.kind === "route" ? owner.id : null,
|
|
8733
|
-
upstream.position,
|
|
8734
|
-
upstream.target,
|
|
8735
|
-
upstream.weight,
|
|
8736
|
-
upstream.priority,
|
|
8737
|
-
upstream.is_disabled ? 1 : 0,
|
|
8738
|
-
canonicalJson(upstreamPolicy(upstream))
|
|
8739
|
-
]);
|
|
8740
|
-
writeBindings(db, upstream.plugins, { kind: "upstream", id: upstream.id });
|
|
8741
|
-
}
|
|
8742
|
-
}
|
|
8743
|
-
function servicePolicy(service) {
|
|
8744
|
-
const { id, position, name, endpoints, service_references, plugins, ...policy } = service;
|
|
8745
|
-
return policy;
|
|
8746
|
-
}
|
|
8747
|
-
function routePolicy(route) {
|
|
8748
|
-
const { id, position, path, plugins, ...remainder } = route;
|
|
8749
|
-
const { endpoints, service_references, ...policy } = remainder;
|
|
8750
|
-
return policy;
|
|
8751
|
-
}
|
|
8752
|
-
function writeServices(db, services) {
|
|
8753
|
-
for (const service of services) {
|
|
8754
|
-
db.run("INSERT INTO services (id,position,name,policy_json) VALUES (?,?,?,?)", [
|
|
8755
|
-
service.id,
|
|
8756
|
-
service.position,
|
|
8757
|
-
service.name,
|
|
8758
|
-
canonicalJson(servicePolicy(service))
|
|
8759
|
-
]);
|
|
8760
|
-
writeUpstreams(db, service.endpoints, { kind: "service", id: service.id });
|
|
8761
|
-
writeBindings(db, service.plugins, { kind: "service", id: service.id });
|
|
8762
|
-
}
|
|
8763
|
-
}
|
|
8764
|
-
function writeRoutes(db, routes) {
|
|
8765
|
-
for (const route of routes) {
|
|
8766
|
-
db.run("INSERT INTO routes (id,position,path,policy_json) VALUES (?,?,?,?)", [
|
|
8767
|
-
route.id,
|
|
8768
|
-
route.position,
|
|
8769
|
-
route.path,
|
|
8770
|
-
canonicalJson(routePolicy(route))
|
|
8771
|
-
]);
|
|
8772
|
-
if (route.endpoints !== undefined)
|
|
8773
|
-
writeUpstreams(db, route.endpoints, { kind: "route", id: route.id });
|
|
8774
|
-
writeBindings(db, route.plugins, { kind: "route", id: route.id });
|
|
8775
|
-
}
|
|
8776
|
-
}
|
|
8777
|
-
function replaceActiveMaterialization(db, aggregate) {
|
|
8778
|
-
if (db.query("SELECT 1 FROM sqlite_schema WHERE name='service_references'").get())
|
|
8779
|
-
db.run("DELETE FROM service_references");
|
|
8780
|
-
db.run("DELETE FROM plugin_bindings");
|
|
8781
|
-
db.run("DELETE FROM plugin_activations");
|
|
8782
|
-
db.run("DELETE FROM upstreams");
|
|
8783
|
-
db.run("DELETE FROM routes");
|
|
8784
|
-
db.run("DELETE FROM services");
|
|
8785
|
-
db.run("DELETE FROM settings");
|
|
8786
|
-
const logical = aggregate.logical_configuration;
|
|
8787
|
-
const settingsColumns = new Set(db.query("PRAGMA table_info(settings)").all().map(({ name }) => name));
|
|
8788
|
-
const publicationColumn = settingsColumns.has("publication_json") ? ",publication_json" : "";
|
|
8789
|
-
const publicationValue = settingsColumns.has("publication_json") ? ",?" : "";
|
|
8790
|
-
const hasWebSocketLimit = settingsColumns.has("websocket_max_connections_json");
|
|
8791
|
-
const hasWebSocketMessageSize = settingsColumns.has("websocket_max_message_bytes");
|
|
8792
|
-
db.run(`INSERT INTO settings
|
|
8793
|
-
(id,log_level,body_parser_limit,auth_json,logging_json${publicationColumn}${hasWebSocketLimit ? ",websocket_max_connections_json" : ""}${hasWebSocketMessageSize ? ",websocket_max_message_bytes" : ""}) VALUES (1,?,?,?,?${publicationValue}${hasWebSocketLimit ? ",?" : ""}${hasWebSocketMessageSize ? ",?" : ""})`, [
|
|
8794
|
-
logical.log_level ?? null,
|
|
8795
|
-
logical.body_parser_limit ?? null,
|
|
8796
|
-
logical.auth === undefined ? null : canonicalJson(logical.auth),
|
|
8797
|
-
logical.logging === undefined ? null : canonicalJson(logical.logging),
|
|
8798
|
-
...settingsColumns.has("publication_json") ? [logical.publication === undefined ? null : canonicalJson(logical.publication)] : [],
|
|
8799
|
-
...hasWebSocketLimit ? [logical.websocket_max_connections === undefined ? null : canonicalJson(logical.websocket_max_connections)] : [],
|
|
8800
|
-
...hasWebSocketMessageSize ? [logical.websocket_max_message_bytes ?? null] : []
|
|
8801
|
-
]);
|
|
8802
|
-
writeServices(db, logical.services);
|
|
8803
|
-
writeRoutes(db, logical.routes);
|
|
8804
|
-
for (const service of logical.services)
|
|
8805
|
-
writeReferences(db, service.service_references ?? [], "service", service.id);
|
|
8806
|
-
for (const route of logical.routes)
|
|
8807
|
-
writeReferences(db, route.service_references ?? [], "route", route.id);
|
|
8808
|
-
writeBindings(db, logical.plugins, { kind: "global", id: "" });
|
|
8809
|
-
for (const activation of aggregate.plugin_activations) {
|
|
8810
|
-
db.run("INSERT INTO plugin_activations (plugin_name) VALUES (?)", [activation.plugin_name]);
|
|
8811
|
-
}
|
|
8812
|
-
}
|
|
8813
|
-
function writeReferences(db, references, ownerKind, ownerId) {
|
|
8814
|
-
for (const ref of references)
|
|
8815
|
-
db.run(`INSERT INTO service_references
|
|
8816
|
-
(id,owner_kind,owner_service_id,route_id,position,service_id,weight,priority,is_disabled) VALUES(?,?,?,?,?,?,?,?,?)`, [
|
|
8817
|
-
ref.id,
|
|
8818
|
-
ownerKind,
|
|
8819
|
-
ownerKind === "service" ? ownerId : null,
|
|
8820
|
-
ownerKind === "route" ? ownerId : null,
|
|
8821
|
-
ref.position,
|
|
8822
|
-
ref.service_id,
|
|
8823
|
-
ref.weight,
|
|
8824
|
-
ref.priority,
|
|
8825
|
-
ref.is_disabled ? 1 : 0
|
|
8826
|
-
]);
|
|
8827
9218
|
}
|
|
8828
9219
|
|
|
8829
9220
|
// src/config-storage/recovery-store.ts
|
|
@@ -8843,27 +9234,27 @@ var REASON_CODES = [
|
|
|
8843
9234
|
var RECOVERY_SELECT = `SELECT recovery_sequence,recovery_id,source_mutation_id,target_revision,trigger,state,
|
|
8844
9235
|
attempt_count,max_attempts,next_retry_at,final_reason_code,final_reason_detail,created_at,updated_at
|
|
8845
9236
|
FROM configuration_recoveries`;
|
|
8846
|
-
function
|
|
9237
|
+
function invalid5(message) {
|
|
8847
9238
|
throw new ConfigRepositoryError("invalid_operation", message);
|
|
8848
9239
|
}
|
|
8849
|
-
function
|
|
9240
|
+
function corrupt3(message) {
|
|
8850
9241
|
throw new ConfigRepositoryError("schema_corrupt", message);
|
|
8851
9242
|
}
|
|
8852
9243
|
function stringValue(value, field) {
|
|
8853
9244
|
if (typeof value !== "string")
|
|
8854
|
-
|
|
9245
|
+
corrupt3(`configuration_recoveries.${field} is invalid`);
|
|
8855
9246
|
return value;
|
|
8856
9247
|
}
|
|
8857
9248
|
function nullableStringValue(value, field) {
|
|
8858
9249
|
if (value !== null && typeof value !== "string")
|
|
8859
|
-
|
|
9250
|
+
corrupt3(`configuration_recoveries.${field} is invalid`);
|
|
8860
9251
|
return value;
|
|
8861
9252
|
}
|
|
8862
9253
|
function reasonCode(value) {
|
|
8863
9254
|
if (value === null)
|
|
8864
9255
|
return null;
|
|
8865
9256
|
if (typeof value !== "string" || !REASON_CODES.includes(value)) {
|
|
8866
|
-
|
|
9257
|
+
corrupt3("configuration_recoveries.final_reason_code is invalid");
|
|
8867
9258
|
}
|
|
8868
9259
|
return value;
|
|
8869
9260
|
}
|
|
@@ -8883,49 +9274,49 @@ function validateTerminalMatrix(state, attemptCount, finalReasonCode, fail) {
|
|
|
8883
9274
|
}
|
|
8884
9275
|
function recoveryFromRow(row) {
|
|
8885
9276
|
if (typeof row.recovery_sequence !== "number")
|
|
8886
|
-
|
|
9277
|
+
corrupt3("configuration_recoveries.recovery_sequence is invalid");
|
|
8887
9278
|
requireSafeInteger(row.recovery_sequence, "configuration_recoveries.recovery_sequence", 1);
|
|
8888
9279
|
const recoveryId = stringValue(row.recovery_id, "recovery_id");
|
|
8889
9280
|
const sourceMutationId = stringValue(row.source_mutation_id, "source_mutation_id");
|
|
8890
9281
|
if (!isLowercaseUuid(recoveryId) || sourceMutationId.length < 1 || sourceMutationId.length > 128) {
|
|
8891
|
-
|
|
9282
|
+
corrupt3("configuration_recoveries identifier bounds are invalid");
|
|
8892
9283
|
}
|
|
8893
|
-
const targetRevision = typeof row.target_revision === "number" ? requireSafeInteger(row.target_revision, "configuration_recoveries.target_revision", 1) :
|
|
9284
|
+
const targetRevision = typeof row.target_revision === "number" ? requireSafeInteger(row.target_revision, "configuration_recoveries.target_revision", 1) : corrupt3("configuration_recoveries.target_revision is invalid");
|
|
8894
9285
|
const trigger = stringValue(row.trigger, "trigger");
|
|
8895
9286
|
if (trigger !== "automatic" && trigger !== "manual")
|
|
8896
|
-
|
|
9287
|
+
corrupt3("configuration_recoveries.trigger is invalid");
|
|
8897
9288
|
const state = stringValue(row.state, "state");
|
|
8898
9289
|
if (state !== "scheduled" && state !== "running" && state !== "succeeded" && state !== "stopped") {
|
|
8899
|
-
|
|
9290
|
+
corrupt3("configuration_recoveries.state is invalid");
|
|
8900
9291
|
}
|
|
8901
|
-
const attemptCount = typeof row.attempt_count === "number" ? requireSafeInteger(row.attempt_count, "configuration_recoveries.attempt_count") :
|
|
8902
|
-
const maxAttempts = typeof row.max_attempts === "number" ? requireSafeInteger(row.max_attempts, "configuration_recoveries.max_attempts") :
|
|
9292
|
+
const attemptCount = typeof row.attempt_count === "number" ? requireSafeInteger(row.attempt_count, "configuration_recoveries.attempt_count") : corrupt3("configuration_recoveries.attempt_count is invalid");
|
|
9293
|
+
const maxAttempts = typeof row.max_attempts === "number" ? requireSafeInteger(row.max_attempts, "configuration_recoveries.max_attempts") : corrupt3("configuration_recoveries.max_attempts is invalid");
|
|
8903
9294
|
if (maxAttempts !== RECOVERY_MAX_ATTEMPTS || attemptCount > maxAttempts) {
|
|
8904
|
-
|
|
9295
|
+
corrupt3("configuration_recoveries attempt bounds are invalid");
|
|
8905
9296
|
}
|
|
8906
|
-
const nextRetryAt = row.next_retry_at === null ? null : typeof row.next_retry_at === "number" ? requireSafeInteger(row.next_retry_at, "configuration_recoveries.next_retry_at") :
|
|
9297
|
+
const nextRetryAt = row.next_retry_at === null ? null : typeof row.next_retry_at === "number" ? requireSafeInteger(row.next_retry_at, "configuration_recoveries.next_retry_at") : corrupt3("configuration_recoveries.next_retry_at is invalid");
|
|
8907
9298
|
const finalReasonCode = reasonCode(row.final_reason_code);
|
|
8908
9299
|
const finalReasonDetail = nullableStringValue(row.final_reason_detail, "final_reason_detail");
|
|
8909
9300
|
if (finalReasonDetail !== null && (finalReasonDetail.length > 512 || finalReasonDetail.trim().length === 0)) {
|
|
8910
|
-
|
|
9301
|
+
corrupt3("configuration_recoveries.final_reason_detail is invalid");
|
|
8911
9302
|
}
|
|
8912
|
-
const createdAt = typeof row.created_at === "number" ? requireSafeInteger(row.created_at, "configuration_recoveries.created_at") :
|
|
8913
|
-
const updatedAt = typeof row.updated_at === "number" ? requireSafeInteger(row.updated_at, "configuration_recoveries.updated_at", createdAt) :
|
|
9303
|
+
const createdAt = typeof row.created_at === "number" ? requireSafeInteger(row.created_at, "configuration_recoveries.created_at") : corrupt3("configuration_recoveries.created_at is invalid");
|
|
9304
|
+
const updatedAt = typeof row.updated_at === "number" ? requireSafeInteger(row.updated_at, "configuration_recoveries.updated_at", createdAt) : corrupt3("configuration_recoveries.updated_at is invalid");
|
|
8914
9305
|
if ((state === "scheduled" || state === "running") && (finalReasonCode !== null || finalReasonDetail !== null)) {
|
|
8915
|
-
|
|
9306
|
+
corrupt3("active recovery has a final reason");
|
|
8916
9307
|
}
|
|
8917
9308
|
if (state === "running" && (nextRetryAt !== null || attemptCount < 1))
|
|
8918
|
-
|
|
9309
|
+
corrupt3("running recovery fields are invalid");
|
|
8919
9310
|
if (state === "scheduled" && attemptCount >= RECOVERY_MAX_ATTEMPTS)
|
|
8920
|
-
|
|
9311
|
+
corrupt3("scheduled recovery attempt limit is invalid");
|
|
8921
9312
|
if (state === "scheduled" && nextRetryAt !== null && nextRetryAt <= updatedAt) {
|
|
8922
|
-
|
|
9313
|
+
corrupt3("scheduled recovery retry time is not in the future");
|
|
8923
9314
|
}
|
|
8924
9315
|
if ((state === "succeeded" || state === "stopped") && (finalReasonCode === null || nextRetryAt !== null)) {
|
|
8925
|
-
|
|
9316
|
+
corrupt3("terminal recovery fields are invalid");
|
|
8926
9317
|
}
|
|
8927
9318
|
if (state === "succeeded" || state === "stopped")
|
|
8928
|
-
validateTerminalMatrix(state, attemptCount, finalReasonCode,
|
|
9319
|
+
validateTerminalMatrix(state, attemptCount, finalReasonCode, corrupt3);
|
|
8929
9320
|
return {
|
|
8930
9321
|
recovery_id: recoveryId,
|
|
8931
9322
|
source_mutation_id: sourceMutationId,
|
|
@@ -8948,43 +9339,49 @@ function readRecovery(db, recoveryId) {
|
|
|
8948
9339
|
function readRecoveryRows(db, sql, ...params) {
|
|
8949
9340
|
return sqliteAll(db, sql, ...params).map(recoveryFromRow);
|
|
8950
9341
|
}
|
|
9342
|
+
function readPublicationRecoveryBarrier(db, excludeRecoveryId = null) {
|
|
9343
|
+
if (excludeRecoveryId !== null)
|
|
9344
|
+
requireRecoveryId(excludeRecoveryId);
|
|
9345
|
+
const exclusion = excludeRecoveryId === null ? "" : " AND recovery_id<>?";
|
|
9346
|
+
return readRecoveryRows(db, `${RECOVERY_SELECT}
|
|
9347
|
+
WHERE (state IN ('scheduled','running')
|
|
9348
|
+
OR (state='stopped' AND final_reason_code='safety_outcome_unknown'))${exclusion}
|
|
9349
|
+
ORDER BY CASE WHEN state IN ('scheduled','running') THEN 0 ELSE 1 END,
|
|
9350
|
+
recovery_sequence DESC LIMIT 1`, ...excludeRecoveryId === null ? [] : [excludeRecoveryId])[0] ?? null;
|
|
9351
|
+
}
|
|
8951
9352
|
function readLatestRecovery(db, targetRevision) {
|
|
8952
9353
|
return readRecoveryRows(db, `${RECOVERY_SELECT} WHERE target_revision=?
|
|
8953
9354
|
ORDER BY recovery_sequence DESC LIMIT 1`, targetRevision)[0] ?? null;
|
|
8954
9355
|
}
|
|
8955
|
-
function readCurrentRecovery(db
|
|
8956
|
-
return readRecoveryRows(db, `${RECOVERY_SELECT}
|
|
9356
|
+
function readCurrentRecovery(db) {
|
|
9357
|
+
return readRecoveryRows(db, `${RECOVERY_SELECT}
|
|
8957
9358
|
ORDER BY CASE WHEN state IN ('scheduled','running') THEN 0 ELSE 1 END,
|
|
8958
|
-
recovery_sequence DESC LIMIT 1
|
|
8959
|
-
}
|
|
8960
|
-
function readActiveRecovery(db, targetRevision) {
|
|
8961
|
-
return readRecoveryRows(db, `${RECOVERY_SELECT} WHERE target_revision=? AND state IN ('scheduled','running')
|
|
8962
|
-
ORDER BY recovery_sequence DESC LIMIT 1`, targetRevision)[0] ?? null;
|
|
9359
|
+
recovery_sequence DESC LIMIT 1`)[0] ?? null;
|
|
8963
9360
|
}
|
|
8964
9361
|
function requireRecoveryId(recoveryId) {
|
|
8965
9362
|
if (typeof recoveryId !== "string" || !isLowercaseUuid(recoveryId)) {
|
|
8966
|
-
|
|
9363
|
+
invalid5("recovery_id is invalid");
|
|
8967
9364
|
}
|
|
8968
9365
|
}
|
|
8969
9366
|
function requireNow(now) {
|
|
8970
9367
|
if (!Number.isSafeInteger(now) || now < 0 || now > Number.MAX_SAFE_INTEGER)
|
|
8971
|
-
|
|
9368
|
+
invalid5("recovery timestamp is invalid");
|
|
8972
9369
|
}
|
|
8973
9370
|
function initialRetryAt(trigger, now) {
|
|
8974
9371
|
if (trigger === "manual")
|
|
8975
9372
|
return null;
|
|
8976
9373
|
if (now > Number.MAX_SAFE_INTEGER - RECOVERY_INITIAL_DELAY_MS)
|
|
8977
|
-
|
|
9374
|
+
invalid5("automatic recovery retry timestamp would overflow");
|
|
8978
9375
|
return now + RECOVERY_INITIAL_DELAY_MS;
|
|
8979
9376
|
}
|
|
8980
9377
|
function requireAttempt(attemptCount) {
|
|
8981
9378
|
if (!Number.isSafeInteger(attemptCount) || attemptCount < 0 || attemptCount > RECOVERY_MAX_ATTEMPTS) {
|
|
8982
|
-
|
|
9379
|
+
invalid5("recovery attempt count is invalid");
|
|
8983
9380
|
}
|
|
8984
9381
|
}
|
|
8985
9382
|
function requireDetail(detail) {
|
|
8986
9383
|
if (detail !== null && (detail.length > 512 || detail.trim().length === 0))
|
|
8987
|
-
|
|
9384
|
+
invalid5("recovery reason detail is invalid");
|
|
8988
9385
|
}
|
|
8989
9386
|
function requireReasonCompatible(db, recovery, reason) {
|
|
8990
9387
|
if (reason !== "deterministic_worker_rejection" && reason !== "deterministic_protocol_failure" && reason !== "deterministic_control_failure" && reason !== "fatal_source_failure")
|
|
@@ -8997,22 +9394,16 @@ function requireReasonCompatible(db, recovery, reason) {
|
|
|
8997
9394
|
function requireRevisionDrift(db, recovery) {
|
|
8998
9395
|
const currentRevision = sqliteGet(db, "SELECT active_revision FROM configuration_state WHERE id=1")?.active_revision;
|
|
8999
9396
|
if (currentRevision === undefined || currentRevision <= recovery.target_revision)
|
|
9000
|
-
|
|
9397
|
+
invalid5("revision has not been superseded");
|
|
9001
9398
|
}
|
|
9002
|
-
function
|
|
9399
|
+
function requireTimestamp3(now, recovery) {
|
|
9003
9400
|
requireNow(now);
|
|
9004
9401
|
if (now < recovery.updated_at)
|
|
9005
|
-
|
|
9402
|
+
invalid5("recovery timestamp regressed");
|
|
9006
9403
|
}
|
|
9007
9404
|
function sameIdentity(recovery, trigger, sourceMutationId, targetRevision) {
|
|
9008
9405
|
return recovery.trigger === trigger && recovery.source_mutation_id === sourceMutationId && recovery.target_revision === targetRevision;
|
|
9009
9406
|
}
|
|
9010
|
-
function requireCurrentTarget(db, recovery) {
|
|
9011
|
-
const currentRevision = sqliteGet(db, "SELECT active_revision FROM configuration_state WHERE id=1")?.active_revision;
|
|
9012
|
-
if (currentRevision !== recovery.target_revision) {
|
|
9013
|
-
throw new ConfigRepositoryError("stale_revision", "recovery target revision is no longer active");
|
|
9014
|
-
}
|
|
9015
|
-
}
|
|
9016
9407
|
function requireSource(db, sourceMutationId) {
|
|
9017
9408
|
const source = sqliteGet(db, "SELECT state,error_code,committed_revision FROM configuration_operations WHERE mutation_id=?", sourceMutationId);
|
|
9018
9409
|
if (source === null || source.state !== "degraded" || source.error_code !== "replacement_convergence_failed" && source.error_code !== "control_readiness_failed") {
|
|
@@ -9022,10 +9413,9 @@ function requireSource(db, sourceMutationId) {
|
|
|
9022
9413
|
}
|
|
9023
9414
|
function requireNoActivePublication(db) {
|
|
9024
9415
|
const active = sqliteGet(db, `SELECT mutation_id FROM configuration_operations
|
|
9025
|
-
WHERE
|
|
9026
|
-
AND state IN ('committed','publishing','draining') LIMIT 1`);
|
|
9416
|
+
WHERE state IN ('committed','publishing','draining') LIMIT 1`);
|
|
9027
9417
|
if (active !== null)
|
|
9028
|
-
|
|
9418
|
+
invalid5("an active publication already exists");
|
|
9029
9419
|
}
|
|
9030
9420
|
function insertRecovery(db, recoveryId, sourceMutationId, targetRevision, trigger, now, initial = { state: "scheduled", final_reason_code: null, final_reason_detail: null }) {
|
|
9031
9421
|
requireRecoveryId(recoveryId);
|
|
@@ -9037,20 +9427,21 @@ function insertRecovery(db, recoveryId, sourceMutationId, targetRevision, trigge
|
|
|
9037
9427
|
}
|
|
9038
9428
|
return existing;
|
|
9039
9429
|
}
|
|
9040
|
-
const active =
|
|
9041
|
-
|
|
9430
|
+
const active = readRecoveryRows(db, `${RECOVERY_SELECT} WHERE target_revision=? AND state IN ('scheduled','running')
|
|
9431
|
+
ORDER BY recovery_sequence DESC LIMIT 1`, targetRevision)[0];
|
|
9432
|
+
if (active !== undefined) {
|
|
9042
9433
|
throw new ConfigRepositoryError("recovery_in_progress", "target revision already has an active recovery", undefined, active);
|
|
9043
9434
|
}
|
|
9044
9435
|
const latest = readLatestRecovery(db, targetRevision);
|
|
9045
9436
|
if (latest !== null && now < latest.updated_at)
|
|
9046
|
-
|
|
9437
|
+
invalid5("recovery timestamp regressed");
|
|
9047
9438
|
const latestCreatedAt = sqliteGet(db, "SELECT created_at FROM configuration_recoveries ORDER BY recovery_sequence DESC LIMIT 1")?.created_at;
|
|
9048
9439
|
if (latestCreatedAt !== null && latestCreatedAt !== undefined && now < latestCreatedAt) {
|
|
9049
|
-
|
|
9440
|
+
invalid5("recovery creation timestamp regressed");
|
|
9050
9441
|
}
|
|
9051
9442
|
const nextRetryAt = initial.state === "scheduled" ? initialRetryAt(trigger, now) : null;
|
|
9052
9443
|
if (initial.state === "stopped" && (initial.final_reason_code === null || initial.final_reason_code === "target_serving" || initial.final_reason_code === "already_serving" || initial.final_reason_code === "retry_exhausted" || initial.final_reason_code === "revision_superseded" || initial.final_reason_code === "safety_outcome_unknown")) {
|
|
9053
|
-
|
|
9444
|
+
invalid5("initial stopped recovery reason is invalid");
|
|
9054
9445
|
}
|
|
9055
9446
|
if (initial.final_reason_detail !== null)
|
|
9056
9447
|
requireDetail(initial.final_reason_detail);
|
|
@@ -9097,13 +9488,21 @@ function createManualRecovery(db, recoveryId, sourceMutationId, expectedRevision
|
|
|
9097
9488
|
throw new ConfigRepositoryError("source_not_retryable", "recovery source operation is not retryable");
|
|
9098
9489
|
}
|
|
9099
9490
|
requireNoActivePublication(db);
|
|
9491
|
+
const barrier = readPublicationRecoveryBarrier(db);
|
|
9492
|
+
if (barrier !== null) {
|
|
9493
|
+
throw new ConfigRepositoryError("recovery_in_progress", "configuration application is blocked by an unresolved recovery", undefined, barrier);
|
|
9494
|
+
}
|
|
9100
9495
|
return insertRecovery(db, recoveryId, sourceMutationId, expectedRevision, "manual", now);
|
|
9101
9496
|
}
|
|
9102
9497
|
function claimRecoveryAttempt(db, recoveryId, previousAttemptCount, now) {
|
|
9103
9498
|
const recovery = readRecovery(db, recoveryId);
|
|
9104
9499
|
if (recovery === null)
|
|
9105
|
-
|
|
9106
|
-
|
|
9500
|
+
invalid5("recovery was not found");
|
|
9501
|
+
requireNoActivePublication(db);
|
|
9502
|
+
const barrier = readPublicationRecoveryBarrier(db, recoveryId);
|
|
9503
|
+
if (barrier !== null) {
|
|
9504
|
+
throw new ConfigRepositoryError("recovery_in_progress", "configuration application is blocked by an unresolved recovery", undefined, barrier);
|
|
9505
|
+
}
|
|
9107
9506
|
requireAttempt(previousAttemptCount);
|
|
9108
9507
|
requireNow(now);
|
|
9109
9508
|
if (recovery.state === "running" && recovery.attempt_count === previousAttemptCount + 1)
|
|
@@ -9111,7 +9510,7 @@ function claimRecoveryAttempt(db, recoveryId, previousAttemptCount, now) {
|
|
|
9111
9510
|
if (recovery.state !== "scheduled" || recovery.attempt_count !== previousAttemptCount) {
|
|
9112
9511
|
throw new ConfigRepositoryError("cas_conflict", "recovery claim CAS failed");
|
|
9113
9512
|
}
|
|
9114
|
-
|
|
9513
|
+
requireTimestamp3(now, recovery);
|
|
9115
9514
|
if (previousAttemptCount >= recovery.max_attempts) {
|
|
9116
9515
|
throw new ConfigRepositoryError("attempts_exhausted", "recovery attempt limit reached");
|
|
9117
9516
|
}
|
|
@@ -9131,20 +9530,19 @@ function claimRecoveryAttempt(db, recoveryId, previousAttemptCount, now) {
|
|
|
9131
9530
|
function scheduleRecoveryRetry(db, recoveryId, attemptCount, nextRetryAt, now) {
|
|
9132
9531
|
const recovery = readRecovery(db, recoveryId);
|
|
9133
9532
|
if (recovery === null)
|
|
9134
|
-
|
|
9135
|
-
requireCurrentTarget(db, recovery);
|
|
9533
|
+
invalid5("recovery was not found");
|
|
9136
9534
|
requireAttempt(attemptCount);
|
|
9137
9535
|
requireNow(nextRetryAt);
|
|
9138
9536
|
if (recovery.state === "scheduled" && recovery.attempt_count === attemptCount && recovery.next_retry_at === nextRetryAt)
|
|
9139
9537
|
return recovery;
|
|
9140
9538
|
if (recovery.state !== "running" || recovery.attempt_count !== attemptCount)
|
|
9141
9539
|
throw new ConfigRepositoryError("cas_conflict", "recovery retry CAS failed");
|
|
9142
|
-
|
|
9540
|
+
requireTimestamp3(now, recovery);
|
|
9143
9541
|
if (attemptCount >= recovery.max_attempts) {
|
|
9144
9542
|
throw new ConfigRepositoryError("attempts_exhausted", "recovery attempt limit reached");
|
|
9145
9543
|
}
|
|
9146
9544
|
if (nextRetryAt <= now)
|
|
9147
|
-
|
|
9545
|
+
invalid5("next retry time must be in the future");
|
|
9148
9546
|
const result = db.run(`UPDATE configuration_recoveries SET state='scheduled',next_retry_at=?,updated_at=?
|
|
9149
9547
|
WHERE recovery_id=? AND state='running' AND attempt_count=?`, [nextRetryAt, now, recoveryId, attemptCount]);
|
|
9150
9548
|
if (result.changes !== 1)
|
|
@@ -9157,20 +9555,18 @@ function scheduleRecoveryRetry(db, recoveryId, attemptCount, nextRetryAt, now) {
|
|
|
9157
9555
|
function terminalTransition(db, recoveryId, attemptCount, state, finalReasonCode, finalReasonDetail, now) {
|
|
9158
9556
|
const recovery = readRecovery(db, recoveryId);
|
|
9159
9557
|
if (recovery === null)
|
|
9160
|
-
|
|
9558
|
+
invalid5("recovery was not found");
|
|
9161
9559
|
requireAttempt(attemptCount);
|
|
9162
|
-
validateTerminalMatrix(state, attemptCount, finalReasonCode,
|
|
9560
|
+
validateTerminalMatrix(state, attemptCount, finalReasonCode, invalid5);
|
|
9163
9561
|
requireDetail(finalReasonDetail);
|
|
9164
9562
|
if (recovery.state === state && recovery.attempt_count === attemptCount && recovery.final_reason_code === finalReasonCode && recovery.final_reason_detail === finalReasonDetail)
|
|
9165
9563
|
return recovery;
|
|
9166
9564
|
if (state === "succeeded" && recovery.state !== "running" && recovery.state !== "scheduled" || state === "stopped" && recovery.state !== "running" && recovery.state !== "scheduled" || recovery.attempt_count !== attemptCount)
|
|
9167
9565
|
throw new ConfigRepositoryError("cas_conflict", "recovery terminal transition CAS failed");
|
|
9168
|
-
if (state === "succeeded")
|
|
9169
|
-
requireCurrentTarget(db, recovery);
|
|
9170
9566
|
if (state === "stopped" && finalReasonCode === "revision_superseded")
|
|
9171
9567
|
requireRevisionDrift(db, recovery);
|
|
9172
9568
|
requireReasonCompatible(db, recovery, finalReasonCode);
|
|
9173
|
-
|
|
9569
|
+
requireTimestamp3(now, recovery);
|
|
9174
9570
|
const result = db.run(`UPDATE configuration_recoveries SET state=?,next_retry_at=NULL,
|
|
9175
9571
|
final_reason_code=?,final_reason_detail=?,updated_at=?
|
|
9176
9572
|
WHERE recovery_id=? AND state IN ('scheduled','running') AND attempt_count=?`, [state, finalReasonCode, finalReasonDetail, now, recoveryId, attemptCount]);
|
|
@@ -9190,8 +9586,7 @@ function stopRecovery(db, recoveryId, attemptCount, finalReasonCode, finalReason
|
|
|
9190
9586
|
function requeueRecovery(db, recoveryId, attemptCount, now) {
|
|
9191
9587
|
const recovery = readRecovery(db, recoveryId);
|
|
9192
9588
|
if (recovery === null)
|
|
9193
|
-
|
|
9194
|
-
requireCurrentTarget(db, recovery);
|
|
9589
|
+
invalid5("recovery was not found");
|
|
9195
9590
|
requireAttempt(attemptCount);
|
|
9196
9591
|
requireNow(now);
|
|
9197
9592
|
if (attemptCount >= recovery.max_attempts) {
|
|
@@ -9201,7 +9596,7 @@ function requeueRecovery(db, recoveryId, attemptCount, now) {
|
|
|
9201
9596
|
return recovery;
|
|
9202
9597
|
if (recovery.state !== "running" || recovery.attempt_count !== attemptCount)
|
|
9203
9598
|
throw new ConfigRepositoryError("cas_conflict", "recovery requeue CAS failed");
|
|
9204
|
-
|
|
9599
|
+
requireTimestamp3(now, recovery);
|
|
9205
9600
|
const result = db.run(`UPDATE configuration_recoveries SET state='scheduled',next_retry_at=NULL,updated_at=?
|
|
9206
9601
|
WHERE recovery_id=? AND state='running' AND attempt_count=?`, [now, recoveryId, attemptCount]);
|
|
9207
9602
|
if (result.changes !== 1)
|
|
@@ -9211,57 +9606,502 @@ function requeueRecovery(db, recoveryId, attemptCount, now) {
|
|
|
9211
9606
|
throw new ConfigRepositoryError("repository_failure", "recovery requeue failed");
|
|
9212
9607
|
return queued;
|
|
9213
9608
|
}
|
|
9214
|
-
function verifyRecoveryIntegrity(db,
|
|
9609
|
+
function verifyRecoveryIntegrity(db, _allowActiveRecoveryDrift = false) {
|
|
9215
9610
|
const rows = readRecoveryRows(db, `${RECOVERY_SELECT} ORDER BY recovery_sequence`);
|
|
9216
9611
|
const sequences = sqliteAll(db, "SELECT recovery_sequence,created_at FROM configuration_recoveries ORDER BY recovery_sequence");
|
|
9217
9612
|
if (sequences.length !== rows.length || sequences.some((row, index) => row.recovery_sequence !== index + 1) || sequences.some((row, index) => index > 0 && row.created_at < sequences[index - 1].created_at)) {
|
|
9218
|
-
|
|
9613
|
+
corrupt3("configuration recovery sequences are not contiguous");
|
|
9219
9614
|
}
|
|
9220
9615
|
const sqliteSequence = sqliteGet(db, "SELECT seq FROM sqlite_sequence WHERE name='configuration_recoveries'");
|
|
9221
9616
|
const maxSequence = rows.length === 0 ? 0 : rows.length;
|
|
9222
9617
|
if (sqliteSequence === null && maxSequence !== 0 || sqliteSequence !== null && sqliteSequence.seq !== maxSequence) {
|
|
9223
|
-
|
|
9618
|
+
corrupt3("configuration recovery sqlite sequence is incoherent");
|
|
9619
|
+
}
|
|
9620
|
+
const activeByTarget = new Set;
|
|
9621
|
+
const currentRevision = sqliteGet(db, "SELECT active_revision FROM configuration_state WHERE id=1")?.active_revision;
|
|
9622
|
+
if (currentRevision === undefined)
|
|
9623
|
+
corrupt3("configuration state is missing for recovery audit");
|
|
9624
|
+
for (const recovery of rows) {
|
|
9625
|
+
const source = sqliteGet(db, "SELECT state,error_code,committed_revision FROM configuration_operations WHERE mutation_id=?", recovery.source_mutation_id);
|
|
9626
|
+
if (source === null || source.state !== "degraded" || source.committed_revision !== recovery.target_revision || source.error_code !== "replacement_convergence_failed" && source.error_code !== "control_readiness_failed") {
|
|
9627
|
+
corrupt3("configuration recovery source metadata is incoherent");
|
|
9628
|
+
}
|
|
9629
|
+
if (recovery.final_reason_code === "deterministic_control_failure" && source.error_code !== "control_readiness_failed") {
|
|
9630
|
+
corrupt3("configuration recovery reason is incompatible with its source");
|
|
9631
|
+
}
|
|
9632
|
+
if ((recovery.final_reason_code === "deterministic_worker_rejection" || recovery.final_reason_code === "deterministic_protocol_failure") && source.error_code !== "replacement_convergence_failed") {
|
|
9633
|
+
corrupt3("configuration recovery reason is incompatible with its source");
|
|
9634
|
+
}
|
|
9635
|
+
if (recovery.final_reason_code === "fatal_source_failure" && source.error_code !== "replacement_convergence_failed" && source.error_code !== "control_readiness_failed") {
|
|
9636
|
+
corrupt3("fatal recovery reason is incompatible with its source");
|
|
9637
|
+
}
|
|
9638
|
+
const target = sqliteGet(db, "SELECT revision FROM configuration_revisions WHERE revision=?", recovery.target_revision);
|
|
9639
|
+
if (target === null)
|
|
9640
|
+
corrupt3("configuration recovery target revision is missing");
|
|
9641
|
+
if ((recovery.state === "scheduled" || recovery.state === "running") && activeByTarget.has(recovery.target_revision)) {
|
|
9642
|
+
corrupt3("multiple active recoveries target one revision");
|
|
9643
|
+
}
|
|
9644
|
+
if (recovery.final_reason_code === "revision_superseded" && recovery.target_revision >= currentRevision) {
|
|
9645
|
+
corrupt3("superseded recovery target is not older than the active revision");
|
|
9646
|
+
}
|
|
9647
|
+
if (recovery.target_revision > currentRevision) {
|
|
9648
|
+
corrupt3("recovery target revision is newer than the active revision");
|
|
9649
|
+
}
|
|
9650
|
+
if (recovery.state === "scheduled" || recovery.state === "running")
|
|
9651
|
+
activeByTarget.add(recovery.target_revision);
|
|
9652
|
+
}
|
|
9653
|
+
}
|
|
9654
|
+
|
|
9655
|
+
// src/config-storage/operation-relations.ts
|
|
9656
|
+
function validateOperationIdentity(db, operation, workers, snapshot) {
|
|
9657
|
+
validateOperationRelations(operation, workers);
|
|
9658
|
+
const revision = sqliteGet(db, "SELECT content_hash,kind,created_at FROM configuration_revisions WHERE revision=?", snapshot.revision);
|
|
9659
|
+
if (operation.committed_revision !== snapshot.revision || operation.expected_revision !== snapshot.revision - 1 || revision === null || revision.content_hash !== snapshot.content_hash || revision.kind !== operation.kind || revision.created_at !== operation.created_at || operation.request_hash !== hashConfigurationRequest({
|
|
9660
|
+
...readManagementRequestIdentity(db, operation.mutation_id),
|
|
9661
|
+
kind: operation.kind,
|
|
9662
|
+
expected_revision: operation.expected_revision,
|
|
9663
|
+
aggregate: snapshot.aggregate,
|
|
9664
|
+
target_worker_slots: workers.map((worker) => worker.worker_slot).sort((left, right) => left - right)
|
|
9665
|
+
})) {
|
|
9666
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation identity is incoherent");
|
|
9667
|
+
}
|
|
9668
|
+
}
|
|
9669
|
+
function validateOperationRelations(operation, workers) {
|
|
9670
|
+
if (workers.some((worker) => worker.mutation_id !== operation.mutation_id || worker.target_revision !== operation.committed_revision || worker.updated_at < operation.created_at || worker.updated_at > operation.updated_at)) {
|
|
9671
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation worker metadata is incoherent");
|
|
9672
|
+
}
|
|
9673
|
+
if (workers.length !== operation.target_worker_count) {
|
|
9674
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation target cardinality is incoherent");
|
|
9675
|
+
}
|
|
9676
|
+
if (workers.some(({ drain_recovery_generation }) => drain_recovery_generation !== operation.drain_recovery_generation)) {
|
|
9677
|
+
throw new ConfigRepositoryError("schema_corrupt", "operation recovery generation is incoherent");
|
|
9678
|
+
}
|
|
9679
|
+
if ((operation.state === "pending" || operation.state === "committed") && workers.some(({ state: workerState, attempt_no }) => workerState !== "pending" || attempt_no !== 0)) {
|
|
9680
|
+
throw new ConfigRepositoryError("schema_corrupt", "unstarted operation has terminal worker state");
|
|
9681
|
+
}
|
|
9682
|
+
if (operation.state === "draining" && workers.some(({ state: workerState, attempt_no }) => workerState !== "converged" || attempt_no === 0)) {
|
|
9683
|
+
const invalidRecovery = workers.some(({ state: workerState, attempt_no, last_begin_reason }) => attempt_no === 0 || workerState !== "converged" && last_begin_reason !== "master_recovery" && last_begin_reason !== "retry");
|
|
9684
|
+
if (invalidRecovery) {
|
|
9685
|
+
throw new ConfigRepositoryError("schema_corrupt", "draining operation targets are incoherent");
|
|
9686
|
+
}
|
|
9687
|
+
}
|
|
9688
|
+
if (operation.state === "draining" && operation.drain_recovery_generation > 0 && workers.some(({ last_begin_reason }) => last_begin_reason !== "master_recovery" && last_begin_reason !== "retry")) {
|
|
9689
|
+
throw new ConfigRepositoryError("schema_corrupt", "draining recovery targets are not fully fenced");
|
|
9690
|
+
}
|
|
9691
|
+
if (operation.state === "draining" && operation.drain_recovery_generation === 0 && workers.some(({ state: workerState }) => workerState !== "converged")) {
|
|
9692
|
+
throw new ConfigRepositoryError("schema_corrupt", "unfenced draining operation has active recovery targets");
|
|
9693
|
+
}
|
|
9694
|
+
if (operation.state === "converged" && workers.some(({ state: workerState }) => workerState !== "converged")) {
|
|
9695
|
+
throw new ConfigRepositoryError("schema_corrupt", "converged operation targets are incoherent");
|
|
9696
|
+
}
|
|
9697
|
+
if (operation.state === "degraded") {
|
|
9698
|
+
if (operation.error_code === "replacement_convergence_failed" && (workers.some(({ state: workerState }) => workerState === "pending") || !workers.some(({ state: workerState }) => workerState === "failed"))) {
|
|
9699
|
+
throw new ConfigRepositoryError("schema_corrupt", "replacement failure targets are incoherent");
|
|
9700
|
+
}
|
|
9701
|
+
if (operation.error_code === "old_worker_drain_failed" && workers.some(({ state: workerState, attempt_no }) => workerState !== "converged" || attempt_no === 0)) {
|
|
9702
|
+
throw new ConfigRepositoryError("schema_corrupt", "drain failure targets are incoherent");
|
|
9703
|
+
}
|
|
9704
|
+
if (operation.drain_recovery_generation > 0 && operation.error_code !== "old_worker_drain_failed" && operation.error_code !== "control_readiness_failed") {
|
|
9705
|
+
throw new ConfigRepositoryError("schema_corrupt", "drain recovery terminal result is incoherent");
|
|
9706
|
+
}
|
|
9707
|
+
if (operation.drain_recovery_generation > 0 && workers.some(({ last_begin_reason }) => last_begin_reason !== "master_recovery" && last_begin_reason !== "retry")) {
|
|
9708
|
+
throw new ConfigRepositoryError("schema_corrupt", "drain recovery terminal targets are not fully fenced");
|
|
9709
|
+
}
|
|
9710
|
+
}
|
|
9711
|
+
}
|
|
9712
|
+
|
|
9713
|
+
// src/config-storage/active-publication.ts
|
|
9714
|
+
var OWNER_STATES = `('committed','publishing','draining')`;
|
|
9715
|
+
var SUPERSEDED_DETAIL = "revision was superseded before publication was claimed";
|
|
9716
|
+
var CANCELLED_DETAIL = "publication candidate was cancelled before admission preparation";
|
|
9717
|
+
function readPublicationOwner(db) {
|
|
9718
|
+
const rows = sqliteAll(db, `${OPERATION_SELECT} WHERE state IN ${OWNER_STATES}`);
|
|
9719
|
+
if (rows.length > 1)
|
|
9720
|
+
throw new ConfigRepositoryError("schema_corrupt", "multiple publication owners exist");
|
|
9721
|
+
const row = rows[0];
|
|
9722
|
+
if (row === undefined)
|
|
9723
|
+
return null;
|
|
9724
|
+
const operation = operationFromRow(row);
|
|
9725
|
+
if (operation.state === "pending" || operation.state === "converged" || operation.state === "degraded" || operation.state === "superseded") {
|
|
9726
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication owner state is invalid");
|
|
9727
|
+
}
|
|
9728
|
+
return { operation, targets: readOperationWorkers(db, operation.mutation_id) };
|
|
9729
|
+
}
|
|
9730
|
+
function resolveSnapshot(db, operation, pluginCatalogHash) {
|
|
9731
|
+
const revision = sqliteGet(db, "SELECT content_hash FROM configuration_revisions WHERE revision=?", operation.committed_revision);
|
|
9732
|
+
if (revision === null)
|
|
9733
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication revision is missing");
|
|
9734
|
+
const snapshot = getServingSnapshot(db, {
|
|
9735
|
+
revision: operation.committed_revision,
|
|
9736
|
+
content_hash: revision.content_hash,
|
|
9737
|
+
plugin_catalog_hash: pluginCatalogHash
|
|
9738
|
+
});
|
|
9739
|
+
if (snapshot === null)
|
|
9740
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication snapshot is missing");
|
|
9741
|
+
validateOperationIdentity(db, operation, readOperationWorkers(db, operation.mutation_id), snapshot);
|
|
9742
|
+
return snapshot;
|
|
9743
|
+
}
|
|
9744
|
+
function publicationFrom(db, owner, pluginCatalogHash) {
|
|
9745
|
+
const { operation, targets } = owner;
|
|
9746
|
+
const snapshot = resolveSnapshot(db, operation, pluginCatalogHash);
|
|
9747
|
+
const uniqueSlots = new Set(targets.map(({ worker_slot }) => worker_slot));
|
|
9748
|
+
if (targets.length !== operation.target_worker_count || uniqueSlots.size !== targets.length) {
|
|
9749
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication target cardinality is incoherent");
|
|
9750
|
+
}
|
|
9751
|
+
if (targets.some(({ target_revision }) => target_revision !== operation.committed_revision)) {
|
|
9752
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication targets do not belong to the frozen revision");
|
|
9753
|
+
}
|
|
9754
|
+
return { operation, snapshot, targets, plugin_catalog_hash: pluginCatalogHash };
|
|
9755
|
+
}
|
|
9756
|
+
function readActivePublication(db) {
|
|
9757
|
+
const owner = readPublicationOwner(db);
|
|
9758
|
+
if (owner === null)
|
|
9759
|
+
return null;
|
|
9760
|
+
if (owner.operation.plugin_catalog_hash === null) {
|
|
9761
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication snapshot catalog identity is missing");
|
|
9762
|
+
}
|
|
9763
|
+
return publicationFrom(db, owner, owner.operation.plugin_catalog_hash);
|
|
9764
|
+
}
|
|
9765
|
+
function requireLatestAggregate(db, snapshot, revision) {
|
|
9766
|
+
if (snapshot.revision !== revision || snapshot.revision !== readActiveRevision(db)) {
|
|
9767
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication target disagrees with the latest snapshot");
|
|
9768
|
+
}
|
|
9769
|
+
return snapshot.aggregate;
|
|
9770
|
+
}
|
|
9771
|
+
function claimPublicationTarget(db, snapshot, pluginCatalogHash, updatedAt) {
|
|
9772
|
+
if (!validateDigest(pluginCatalogHash)) {
|
|
9773
|
+
throw new ConfigRepositoryError("invalid_command", "publication catalog identity is invalid");
|
|
9774
|
+
}
|
|
9775
|
+
if (!Number.isSafeInteger(updatedAt) || updatedAt < 0) {
|
|
9776
|
+
throw new ConfigRepositoryError("invalid_command", "publication claim timestamp is invalid");
|
|
9777
|
+
}
|
|
9778
|
+
const owner = readPublicationOwner(db);
|
|
9779
|
+
if (owner !== null) {
|
|
9780
|
+
if (owner.operation.plugin_catalog_hash === null) {
|
|
9781
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication owner has no frozen catalog identity");
|
|
9782
|
+
}
|
|
9783
|
+
if (owner.operation.plugin_catalog_hash !== pluginCatalogHash) {
|
|
9784
|
+
throw new ConfigRepositoryError("invalid_operation", "claimed publication catalog identity is immutable");
|
|
9785
|
+
}
|
|
9786
|
+
return publicationFrom(db, owner, pluginCatalogHash);
|
|
9787
|
+
}
|
|
9788
|
+
const recovery = readPublicationRecoveryBarrier(db);
|
|
9789
|
+
if (recovery !== null) {
|
|
9790
|
+
throw new ConfigRepositoryError("recovery_in_progress", "configuration application is blocked by an unresolved recovery", undefined, recovery);
|
|
9791
|
+
}
|
|
9792
|
+
const retirement = sqliteGet(db, "SELECT mutation_id FROM configuration_retirements WHERE state<>'released' LIMIT 1");
|
|
9793
|
+
if (retirement !== null) {
|
|
9794
|
+
throw new ConfigRepositoryError("invalid_operation", "configuration application is blocked by unresolved worker retirement");
|
|
9795
|
+
}
|
|
9796
|
+
if (readUnsettledWorkerLaunches(db).length > 0) {
|
|
9797
|
+
throw new ConfigRepositoryError("invalid_operation", "configuration application is blocked by an unsettled worker launch");
|
|
9798
|
+
}
|
|
9799
|
+
const candidateRow = sqliteGet(db, `${OPERATION_SELECT} WHERE state='pending' ORDER BY committed_revision DESC LIMIT 1`);
|
|
9800
|
+
if (candidateRow === null)
|
|
9801
|
+
return null;
|
|
9802
|
+
const candidate = operationFromRow(candidateRow);
|
|
9803
|
+
if (candidate.state !== "pending")
|
|
9804
|
+
throw new ConfigRepositoryError("schema_corrupt", "pending target state is invalid");
|
|
9805
|
+
const activeRevision = readActiveRevision(db);
|
|
9806
|
+
if (candidate.committed_revision !== activeRevision) {
|
|
9807
|
+
throw new ConfigRepositoryError("schema_corrupt", "pending target is not the latest revision");
|
|
9808
|
+
}
|
|
9809
|
+
const supersededAt = Math.max(updatedAt, candidate.created_at);
|
|
9810
|
+
db.run(`UPDATE configuration_operations
|
|
9811
|
+
SET state='superseded',result_status=409,error_code='revision_superseded',error_detail=?,updated_at=?
|
|
9812
|
+
WHERE state='pending' AND committed_revision<>?`, [SUPERSEDED_DETAIL, supersededAt, candidate.committed_revision]);
|
|
9813
|
+
const aggregate = requireLatestAggregate(db, snapshot, candidate.committed_revision);
|
|
9814
|
+
const revision = sqliteGet(db, "SELECT content_hash FROM configuration_revisions WHERE revision=?", candidate.committed_revision);
|
|
9815
|
+
if (revision === null || hashConfigurationContent(aggregate) !== revision.content_hash) {
|
|
9816
|
+
throw new ConfigRepositoryError("schema_corrupt", "claimed target aggregate does not match its revision");
|
|
9817
|
+
}
|
|
9818
|
+
writeServingSnapshot(db, {
|
|
9819
|
+
revision: candidate.committed_revision,
|
|
9820
|
+
content_hash: revision.content_hash,
|
|
9821
|
+
aggregate
|
|
9822
|
+
}, pluginCatalogHash);
|
|
9823
|
+
const claimed = db.run(`UPDATE configuration_operations
|
|
9824
|
+
SET state='committed',plugin_catalog_hash=?,updated_at=?
|
|
9825
|
+
WHERE mutation_id=? AND state='pending'`, [pluginCatalogHash, supersededAt, candidate.mutation_id]);
|
|
9826
|
+
if (claimed.changes !== 1)
|
|
9827
|
+
throw new ConfigRepositoryError("repository_failure", "publication claim lost its target");
|
|
9828
|
+
const ownerAfter = readPublicationOwner(db);
|
|
9829
|
+
if (ownerAfter === null)
|
|
9830
|
+
throw new ConfigRepositoryError("repository_failure", "publication claim did not persist");
|
|
9831
|
+
return publicationFrom(db, ownerAfter, pluginCatalogHash);
|
|
9832
|
+
}
|
|
9833
|
+
function requireOwner(db, mutationId, committedRevision) {
|
|
9834
|
+
const owner = readPublicationOwner(db);
|
|
9835
|
+
if (owner === null || owner.operation.mutation_id !== mutationId || owner.operation.committed_revision !== committedRevision) {
|
|
9836
|
+
throw new ConfigRepositoryError("invalid_operation", "publication command does not match the current owner");
|
|
9837
|
+
}
|
|
9838
|
+
return owner.operation;
|
|
9839
|
+
}
|
|
9840
|
+
function requireTimestamp4(updatedAt, operation) {
|
|
9841
|
+
if (!Number.isSafeInteger(updatedAt) || updatedAt < operation.updated_at) {
|
|
9842
|
+
throw new ConfigRepositoryError("invalid_operation", "operation timestamp regressed or is unsafe");
|
|
9843
|
+
}
|
|
9844
|
+
}
|
|
9845
|
+
function requestPublicationCancellation(db, mutationId, committedRevision, updatedAt) {
|
|
9846
|
+
const operation = requireOwner(db, mutationId, committedRevision);
|
|
9847
|
+
if (operation.prepare_started || operation.state === "draining") {
|
|
9848
|
+
throw new ConfigRepositoryError("cancellation_not_permitted", "publication candidate has entered admission preparation");
|
|
9849
|
+
}
|
|
9850
|
+
if (operation.cancel_requested)
|
|
9851
|
+
return operation;
|
|
9852
|
+
requireTimestamp4(updatedAt, operation);
|
|
9853
|
+
db.run(`UPDATE configuration_operations SET cancel_requested=1,updated_at=?
|
|
9854
|
+
WHERE mutation_id=? AND state IN ('committed','publishing') AND prepare_started=0`, [updatedAt, mutationId]);
|
|
9855
|
+
const updated = sqliteGet(db, `${OPERATION_SELECT} WHERE mutation_id=?`, mutationId);
|
|
9856
|
+
if (updated === null)
|
|
9857
|
+
throw new ConfigRepositoryError("repository_failure", "cancellation request was not persisted");
|
|
9858
|
+
return operationFromRow(updated);
|
|
9859
|
+
}
|
|
9860
|
+
function enterPublicationPrepare(db, mutationId, committedRevision, updatedAt) {
|
|
9861
|
+
const operation = requireOwner(db, mutationId, committedRevision);
|
|
9862
|
+
if (operation.state === "draining")
|
|
9863
|
+
throw new ConfigRepositoryError("invalid_operation", "operation is not a candidate");
|
|
9864
|
+
if (operation.prepare_started)
|
|
9865
|
+
return { kind: "granted", operation };
|
|
9866
|
+
const latestRevision = readActiveRevision(db);
|
|
9867
|
+
if (latestRevision < operation.committed_revision) {
|
|
9868
|
+
throw new ConfigRepositoryError("schema_corrupt", "publication target is newer than the latest revision");
|
|
9869
|
+
}
|
|
9870
|
+
if (latestRevision > operation.committed_revision) {
|
|
9871
|
+
if (!operation.cancel_requested) {
|
|
9872
|
+
db.run(`UPDATE configuration_operations SET cancel_requested=1,updated_at=?
|
|
9873
|
+
WHERE mutation_id=? AND state IN ('committed','publishing') AND prepare_started=0 AND cancel_requested=0`, [Math.max(updatedAt, operation.updated_at), mutationId]);
|
|
9874
|
+
}
|
|
9875
|
+
return { kind: "cancelled" };
|
|
9876
|
+
}
|
|
9877
|
+
if (operation.cancel_requested)
|
|
9878
|
+
return { kind: "cancelled" };
|
|
9879
|
+
requireTimestamp4(updatedAt, operation);
|
|
9880
|
+
const granted = db.run(`UPDATE configuration_operations SET prepare_started=1,updated_at=?
|
|
9881
|
+
WHERE mutation_id=? AND state IN ('committed','publishing') AND prepare_started=0 AND cancel_requested=0`, [updatedAt, mutationId]).changes;
|
|
9882
|
+
const current = sqliteGet(db, `${OPERATION_SELECT} WHERE mutation_id=?`, mutationId);
|
|
9883
|
+
if (current === null)
|
|
9884
|
+
throw new ConfigRepositoryError("repository_failure", "preparation decision was not persisted");
|
|
9885
|
+
const result = operationFromRow(current);
|
|
9886
|
+
if (granted === 1)
|
|
9887
|
+
return { kind: "granted", operation: result };
|
|
9888
|
+
if (result.state === "committed" || result.state === "publishing") {
|
|
9889
|
+
if (result.cancel_requested)
|
|
9890
|
+
return { kind: "cancelled" };
|
|
9891
|
+
}
|
|
9892
|
+
throw new ConfigRepositoryError("invalid_operation", "preparation decision lost the owner");
|
|
9893
|
+
}
|
|
9894
|
+
function recordPublicationCandidateExit(db, mutationId, committedRevision, workerSlot, attemptNo, evidence, updatedAt) {
|
|
9895
|
+
if (evidence === null || typeof evidence !== "object" || evidence.kind !== "not_started" && (evidence.kind !== "exited" || evidence.cleanup !== "released")) {
|
|
9896
|
+
throw new ConfigRepositoryError("invalid_command", "candidate exit evidence is invalid");
|
|
9897
|
+
}
|
|
9898
|
+
const operation = requireOwner(db, mutationId, committedRevision);
|
|
9899
|
+
if (operation.state === "draining") {
|
|
9900
|
+
throw new ConfigRepositoryError("invalid_operation", "operation is not a candidate");
|
|
9901
|
+
}
|
|
9902
|
+
requireTimestamp4(updatedAt, operation);
|
|
9903
|
+
const worker = readOperationWorkers(db, mutationId).find((candidate) => candidate.worker_slot === workerSlot);
|
|
9904
|
+
if (worker === undefined || !Number.isSafeInteger(attemptNo) || attemptNo <= 0 || worker.attempt_no !== attemptNo) {
|
|
9905
|
+
throw new ConfigRepositoryError("invalid_operation", "candidate attempt identity is stale or not started");
|
|
9906
|
+
}
|
|
9907
|
+
const exitKind = evidence.kind;
|
|
9908
|
+
const cleanup = evidence.kind === "not_started" ? "not_started" : "released";
|
|
9909
|
+
const launchFacts = readWorkerLaunchAllocationFacts(db, { mutation_id: mutationId, worker_slot: workerSlot, attempt_no: attemptNo });
|
|
9910
|
+
if (launchFacts !== null && (exitKind === "not_started" && launchFacts.exited_at !== null || exitKind === "exited" && launchFacts.not_started_at !== null)) {
|
|
9911
|
+
throw new ConfigRepositoryError("cas_conflict", "candidate exit evidence conflicts with worker launch proof");
|
|
9912
|
+
}
|
|
9913
|
+
const existing = sqliteGet(db, `SELECT exit_kind,cleanup FROM configuration_publication_candidate_evidence
|
|
9914
|
+
WHERE mutation_id=? AND worker_slot=? AND attempt_no=?`, mutationId, workerSlot, attemptNo);
|
|
9915
|
+
if (existing !== null) {
|
|
9916
|
+
if (existing.exit_kind !== exitKind || existing.cleanup !== cleanup) {
|
|
9917
|
+
throw new ConfigRepositoryError("cas_conflict", "candidate exit evidence is already frozen");
|
|
9918
|
+
}
|
|
9919
|
+
return;
|
|
9920
|
+
}
|
|
9921
|
+
db.run(`INSERT INTO configuration_publication_candidate_evidence
|
|
9922
|
+
(mutation_id,worker_slot,attempt_no,exit_kind,cleanup,updated_at) VALUES (?,?,?,?,?,?)`, [mutationId, workerSlot, attemptNo, exitKind, cleanup, updatedAt]);
|
|
9923
|
+
}
|
|
9924
|
+
function readOutstandingPublicationCandidates(db) {
|
|
9925
|
+
const owner = readPublicationOwner(db);
|
|
9926
|
+
if (owner === null)
|
|
9927
|
+
return [];
|
|
9928
|
+
return owner.targets.filter(({ attempt_no }) => attempt_no > 0).map(({ worker_slot, attempt_no, state, updated_at }) => ({
|
|
9929
|
+
mutation_id: owner.operation.mutation_id,
|
|
9930
|
+
committed_revision: owner.operation.committed_revision,
|
|
9931
|
+
plugin_catalog_hash: owner.operation.plugin_catalog_hash,
|
|
9932
|
+
worker_slot,
|
|
9933
|
+
attempt_no,
|
|
9934
|
+
state,
|
|
9935
|
+
updated_at
|
|
9936
|
+
}));
|
|
9937
|
+
}
|
|
9938
|
+
function confirmPublicationCandidateExited(db, mutationId, committedRevision, updatedAt) {
|
|
9939
|
+
const operation = requireOwner(db, mutationId, committedRevision);
|
|
9940
|
+
if (operation.state === "draining" || operation.prepare_started) {
|
|
9941
|
+
throw new ConfigRepositoryError("cancellation_not_permitted", "publication candidate has entered admission preparation");
|
|
9942
|
+
}
|
|
9943
|
+
if (!operation.cancel_requested) {
|
|
9944
|
+
throw new ConfigRepositoryError("invalid_operation", "candidate cancellation was not requested");
|
|
9945
|
+
}
|
|
9946
|
+
const started = readOperationWorkers(db, mutationId).filter(({ attempt_no }) => attempt_no > 0);
|
|
9947
|
+
for (const worker of started) {
|
|
9948
|
+
const evidence = sqliteGet(db, `SELECT attempt_no FROM configuration_publication_candidate_evidence
|
|
9949
|
+
WHERE mutation_id=? AND worker_slot=? AND attempt_no=?`, mutationId, worker.worker_slot, worker.attempt_no);
|
|
9950
|
+
const launch = readWorkerLaunchAllocationFacts(db, {
|
|
9951
|
+
mutation_id: mutationId,
|
|
9952
|
+
worker_slot: worker.worker_slot,
|
|
9953
|
+
attempt_no: worker.attempt_no
|
|
9954
|
+
});
|
|
9955
|
+
if (evidence === null && launch?.settled !== true) {
|
|
9956
|
+
throw new ConfigRepositoryError("invalid_operation", "candidate exit evidence is incomplete");
|
|
9957
|
+
}
|
|
9958
|
+
}
|
|
9959
|
+
requireTimestamp4(updatedAt, operation);
|
|
9960
|
+
const changed = db.run(`UPDATE configuration_operations
|
|
9961
|
+
SET state='superseded',result_status=409,error_code='revision_superseded',error_detail=?,updated_at=?
|
|
9962
|
+
WHERE mutation_id=? AND state IN ('committed','publishing') AND prepare_started=0 AND cancel_requested=1`, [CANCELLED_DETAIL, updatedAt, mutationId]).changes;
|
|
9963
|
+
if (changed !== 1)
|
|
9964
|
+
throw new ConfigRepositoryError("cas_conflict", "candidate supersession lost its owner");
|
|
9965
|
+
const terminal = sqliteGet(db, `${OPERATION_SELECT} WHERE mutation_id=?`, mutationId);
|
|
9966
|
+
if (terminal === null)
|
|
9967
|
+
throw new ConfigRepositoryError("repository_failure", "candidate supersession was not persisted");
|
|
9968
|
+
return operationFromRow(terminal);
|
|
9969
|
+
}
|
|
9970
|
+
|
|
9971
|
+
// src/config-storage/materialize.ts
|
|
9972
|
+
function writeBindings(db, bindings, owner) {
|
|
9973
|
+
for (const binding of bindings) {
|
|
9974
|
+
db.run(`INSERT INTO plugin_bindings
|
|
9975
|
+
(id,scope_kind,scope_owner,service_id,route_id,upstream_id,position,plugin_name,options_json,enabled)
|
|
9976
|
+
VALUES (?,?,?,?,?,?,?,?,?,?)`, [
|
|
9977
|
+
binding.id,
|
|
9978
|
+
owner.kind,
|
|
9979
|
+
owner.id,
|
|
9980
|
+
owner.kind === "service" ? owner.id : null,
|
|
9981
|
+
owner.kind === "route" ? owner.id : null,
|
|
9982
|
+
owner.kind === "upstream" ? owner.id : null,
|
|
9983
|
+
binding.position,
|
|
9984
|
+
binding.name,
|
|
9985
|
+
binding.options === undefined ? null : canonicalJson(binding.options),
|
|
9986
|
+
binding.enabled ? 1 : 0
|
|
9987
|
+
]);
|
|
9988
|
+
}
|
|
9989
|
+
}
|
|
9990
|
+
function upstreamPolicy(upstream) {
|
|
9991
|
+
const { id, position, target, weight, priority, is_disabled, plugins, ...policy } = upstream;
|
|
9992
|
+
return policy;
|
|
9993
|
+
}
|
|
9994
|
+
function writeUpstreams(db, upstreams, owner) {
|
|
9995
|
+
for (const upstream of upstreams) {
|
|
9996
|
+
db.run(`INSERT INTO upstreams
|
|
9997
|
+
(id,owner_kind,service_id,route_id,position,target,weight,priority,is_disabled,policy_json)
|
|
9998
|
+
VALUES (?,?,?,?,?,?,?,?,?,?)`, [
|
|
9999
|
+
upstream.id,
|
|
10000
|
+
owner.kind,
|
|
10001
|
+
owner.kind === "service" ? owner.id : null,
|
|
10002
|
+
owner.kind === "route" ? owner.id : null,
|
|
10003
|
+
upstream.position,
|
|
10004
|
+
upstream.target,
|
|
10005
|
+
upstream.weight,
|
|
10006
|
+
upstream.priority,
|
|
10007
|
+
upstream.is_disabled ? 1 : 0,
|
|
10008
|
+
canonicalJson(upstreamPolicy(upstream))
|
|
10009
|
+
]);
|
|
10010
|
+
writeBindings(db, upstream.plugins, { kind: "upstream", id: upstream.id });
|
|
10011
|
+
}
|
|
10012
|
+
}
|
|
10013
|
+
function servicePolicy(service) {
|
|
10014
|
+
const { id, position, name, endpoints, service_references, plugins, ...policy } = service;
|
|
10015
|
+
return policy;
|
|
10016
|
+
}
|
|
10017
|
+
function routePolicy(route) {
|
|
10018
|
+
const { id, position, path, plugins, ...remainder } = route;
|
|
10019
|
+
const { endpoints, service_references, ...policy } = remainder;
|
|
10020
|
+
return policy;
|
|
10021
|
+
}
|
|
10022
|
+
function writeServices(db, services) {
|
|
10023
|
+
for (const service of services) {
|
|
10024
|
+
db.run("INSERT INTO services (id,position,name,policy_json) VALUES (?,?,?,?)", [
|
|
10025
|
+
service.id,
|
|
10026
|
+
service.position,
|
|
10027
|
+
service.name,
|
|
10028
|
+
canonicalJson(servicePolicy(service))
|
|
10029
|
+
]);
|
|
10030
|
+
writeUpstreams(db, service.endpoints, { kind: "service", id: service.id });
|
|
10031
|
+
writeBindings(db, service.plugins, { kind: "service", id: service.id });
|
|
10032
|
+
}
|
|
10033
|
+
}
|
|
10034
|
+
function writeRoutes(db, routes) {
|
|
10035
|
+
for (const route of routes) {
|
|
10036
|
+
db.run("INSERT INTO routes (id,position,path,policy_json) VALUES (?,?,?,?)", [
|
|
10037
|
+
route.id,
|
|
10038
|
+
route.position,
|
|
10039
|
+
route.path,
|
|
10040
|
+
canonicalJson(routePolicy(route))
|
|
10041
|
+
]);
|
|
10042
|
+
if (route.endpoints !== undefined)
|
|
10043
|
+
writeUpstreams(db, route.endpoints, { kind: "route", id: route.id });
|
|
10044
|
+
writeBindings(db, route.plugins, { kind: "route", id: route.id });
|
|
9224
10045
|
}
|
|
9225
|
-
|
|
9226
|
-
|
|
9227
|
-
if (
|
|
9228
|
-
|
|
9229
|
-
|
|
9230
|
-
|
|
9231
|
-
|
|
9232
|
-
|
|
9233
|
-
|
|
9234
|
-
|
|
9235
|
-
|
|
9236
|
-
|
|
9237
|
-
|
|
9238
|
-
|
|
9239
|
-
|
|
9240
|
-
|
|
9241
|
-
|
|
9242
|
-
}
|
|
9243
|
-
|
|
9244
|
-
|
|
9245
|
-
|
|
9246
|
-
|
|
9247
|
-
|
|
9248
|
-
|
|
9249
|
-
|
|
9250
|
-
|
|
9251
|
-
|
|
9252
|
-
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
10046
|
+
}
|
|
10047
|
+
function replaceActiveMaterialization(db, aggregate) {
|
|
10048
|
+
if (db.query("SELECT 1 FROM sqlite_schema WHERE name='service_references'").get())
|
|
10049
|
+
db.run("DELETE FROM service_references");
|
|
10050
|
+
db.run("DELETE FROM plugin_bindings");
|
|
10051
|
+
db.run("DELETE FROM plugin_activations");
|
|
10052
|
+
db.run("DELETE FROM upstreams");
|
|
10053
|
+
db.run("DELETE FROM routes");
|
|
10054
|
+
db.run("DELETE FROM services");
|
|
10055
|
+
db.run("DELETE FROM settings");
|
|
10056
|
+
const logical = aggregate.logical_configuration;
|
|
10057
|
+
const settingsColumns = new Set(db.query("PRAGMA table_info(settings)").all().map(({ name }) => name));
|
|
10058
|
+
const publicationColumn = settingsColumns.has("publication_json") ? ",publication_json" : "";
|
|
10059
|
+
const publicationValue = settingsColumns.has("publication_json") ? ",?" : "";
|
|
10060
|
+
const hasWebSocketLimit = settingsColumns.has("websocket_max_connections_json");
|
|
10061
|
+
const hasWebSocketMessageSize = settingsColumns.has("websocket_max_message_bytes");
|
|
10062
|
+
db.run(`INSERT INTO settings
|
|
10063
|
+
(id,log_level,body_parser_limit,auth_json,logging_json${publicationColumn}${hasWebSocketLimit ? ",websocket_max_connections_json" : ""}${hasWebSocketMessageSize ? ",websocket_max_message_bytes" : ""}) VALUES (1,?,?,?,?${publicationValue}${hasWebSocketLimit ? ",?" : ""}${hasWebSocketMessageSize ? ",?" : ""})`, [
|
|
10064
|
+
logical.log_level ?? null,
|
|
10065
|
+
logical.body_parser_limit ?? null,
|
|
10066
|
+
logical.auth === undefined ? null : canonicalJson(logical.auth),
|
|
10067
|
+
logical.logging === undefined ? null : canonicalJson(logical.logging),
|
|
10068
|
+
...settingsColumns.has("publication_json") ? [logical.publication === undefined ? null : canonicalJson(logical.publication)] : [],
|
|
10069
|
+
...hasWebSocketLimit ? [logical.websocket_max_connections === undefined ? null : canonicalJson(logical.websocket_max_connections)] : [],
|
|
10070
|
+
...hasWebSocketMessageSize ? [logical.websocket_max_message_bytes ?? null] : []
|
|
10071
|
+
]);
|
|
10072
|
+
writeServices(db, logical.services);
|
|
10073
|
+
writeRoutes(db, logical.routes);
|
|
10074
|
+
for (const service of logical.services)
|
|
10075
|
+
writeReferences(db, service.service_references ?? [], "service", service.id);
|
|
10076
|
+
for (const route of logical.routes)
|
|
10077
|
+
writeReferences(db, route.service_references ?? [], "route", route.id);
|
|
10078
|
+
writeBindings(db, logical.plugins, { kind: "global", id: "" });
|
|
10079
|
+
for (const activation of aggregate.plugin_activations) {
|
|
10080
|
+
db.run("INSERT INTO plugin_activations (plugin_name) VALUES (?)", [activation.plugin_name]);
|
|
9257
10081
|
}
|
|
9258
10082
|
}
|
|
10083
|
+
function writeReferences(db, references, ownerKind, ownerId) {
|
|
10084
|
+
for (const ref of references)
|
|
10085
|
+
db.run(`INSERT INTO service_references
|
|
10086
|
+
(id,owner_kind,owner_service_id,route_id,position,service_id,weight,priority,is_disabled) VALUES(?,?,?,?,?,?,?,?,?)`, [
|
|
10087
|
+
ref.id,
|
|
10088
|
+
ownerKind,
|
|
10089
|
+
ownerKind === "service" ? ownerId : null,
|
|
10090
|
+
ownerKind === "route" ? ownerId : null,
|
|
10091
|
+
ref.position,
|
|
10092
|
+
ref.service_id,
|
|
10093
|
+
ref.weight,
|
|
10094
|
+
ref.priority,
|
|
10095
|
+
ref.is_disabled ? 1 : 0
|
|
10096
|
+
]);
|
|
10097
|
+
}
|
|
9259
10098
|
|
|
9260
10099
|
// src/config-storage/commit-transaction.ts
|
|
9261
10100
|
function commitTransaction(db, prepared, options, snapshot, offlineManagement = false) {
|
|
9262
10101
|
const existing = sqliteGet(db, `SELECT mutation_id,request_hash,expected_revision,
|
|
9263
10102
|
committed_revision,kind,target_worker_count,state,result_status,error_code,error_detail,
|
|
9264
|
-
drain_recovery_generation,last_drain_recovery_previous_generation,
|
|
10103
|
+
drain_recovery_generation,last_drain_recovery_previous_generation,plugin_catalog_hash,cancel_requested,
|
|
10104
|
+
prepare_started,created_at,updated_at
|
|
9265
10105
|
FROM configuration_operations WHERE mutation_id=?`, prepared.mutationId);
|
|
9266
10106
|
if (existing !== null) {
|
|
9267
10107
|
const operation = operationFromRow(existing);
|
|
@@ -9270,38 +10110,11 @@ function commitTransaction(db, prepared, options, snapshot, offlineManagement =
|
|
|
9270
10110
|
}
|
|
9271
10111
|
return { kind: "duplicate", operation };
|
|
9272
10112
|
}
|
|
9273
|
-
const
|
|
9274
|
-
if (
|
|
9275
|
-
return { kind: "stale_revision", expected_revision: prepared.expectedRevision, active_revision:
|
|
9276
|
-
}
|
|
9277
|
-
const activeRow = sqliteGet(db, `SELECT mutation_id,request_hash,expected_revision,
|
|
9278
|
-
committed_revision,kind,target_worker_count,state,result_status,error_code,error_detail,
|
|
9279
|
-
drain_recovery_generation,last_drain_recovery_previous_generation,created_at,updated_at
|
|
9280
|
-
FROM configuration_operations WHERE committed_revision=?`, state.active_revision);
|
|
9281
|
-
if (activeRow !== null) {
|
|
9282
|
-
const active = operationFromRow(activeRow);
|
|
9283
|
-
validateActiveOperationIdentity(db, active, readOperationWorkers(db, active.mutation_id), snapshot);
|
|
9284
|
-
if (active.state === "committed" || active.state === "publishing" || active.state === "draining") {
|
|
9285
|
-
return {
|
|
9286
|
-
kind: "operation_in_progress",
|
|
9287
|
-
mutation_id: active.mutation_id,
|
|
9288
|
-
committed_revision: active.committed_revision,
|
|
9289
|
-
state: active.state
|
|
9290
|
-
};
|
|
9291
|
-
}
|
|
9292
|
-
} else if (state.active_revision !== 1) {
|
|
9293
|
-
throw new ConfigRepositoryError("schema_corrupt", "active revision operation is missing");
|
|
9294
|
-
}
|
|
9295
|
-
const activeRecovery = readActiveRecovery(db, state.active_revision);
|
|
9296
|
-
if (activeRecovery !== null && (activeRecovery.state === "scheduled" || activeRecovery.state === "running")) {
|
|
9297
|
-
return {
|
|
9298
|
-
kind: "recovery_in_progress",
|
|
9299
|
-
recovery_id: activeRecovery.recovery_id,
|
|
9300
|
-
target_revision: activeRecovery.target_revision,
|
|
9301
|
-
state: activeRecovery.state
|
|
9302
|
-
};
|
|
10113
|
+
const activeRevision = readActiveRevision(db);
|
|
10114
|
+
if (activeRevision !== prepared.expectedRevision) {
|
|
10115
|
+
return { kind: "stale_revision", expected_revision: prepared.expectedRevision, active_revision: activeRevision };
|
|
9303
10116
|
}
|
|
9304
|
-
if (
|
|
10117
|
+
if (activeRevision === Number.MAX_SAFE_INTEGER) {
|
|
9305
10118
|
throw new ConfigRepositoryError("repository_failure", "configuration revision limit reached");
|
|
9306
10119
|
}
|
|
9307
10120
|
const protection = readManagementProtection(db);
|
|
@@ -9311,14 +10124,29 @@ function commitTransaction(db, prepared, options, snapshot, offlineManagement =
|
|
|
9311
10124
|
if (prepared.managementProvider !== null && !prepared.aggregate.plugin_activations.some((a) => a.plugin_name === prepared.managementProvider)) {
|
|
9312
10125
|
throw new ConfigRepositoryError("invalid_configuration", "selected management provider activation is missing");
|
|
9313
10126
|
}
|
|
9314
|
-
const
|
|
10127
|
+
const latestRow = sqliteGet(db, `SELECT mutation_id,request_hash,expected_revision,
|
|
10128
|
+
committed_revision,kind,target_worker_count,state,result_status,error_code,error_detail,
|
|
10129
|
+
drain_recovery_generation,last_drain_recovery_previous_generation,plugin_catalog_hash,cancel_requested,
|
|
10130
|
+
prepare_started,created_at,updated_at
|
|
10131
|
+
FROM configuration_operations WHERE committed_revision=?`, activeRevision);
|
|
10132
|
+
if (latestRow !== null) {
|
|
10133
|
+
if (snapshot.revision !== activeRevision) {
|
|
10134
|
+
throw new ConfigRepositoryError("schema_corrupt", "repository snapshot disagrees with the latest revision");
|
|
10135
|
+
}
|
|
10136
|
+
const latest = operationFromRow(latestRow);
|
|
10137
|
+
validateOperationIdentity(db, latest, readOperationWorkers(db, latest.mutation_id), snapshot);
|
|
10138
|
+
}
|
|
10139
|
+
if (!offlineManagement)
|
|
10140
|
+
readActivePublication(db);
|
|
10141
|
+
const committedRevision = activeRevision + 1;
|
|
9315
10142
|
replaceActiveMaterialization(db, prepared.aggregate);
|
|
9316
10143
|
options.faultInjection?.("after_materialization");
|
|
9317
10144
|
db.run(`INSERT INTO configuration_revisions (revision,content_hash,kind,created_at) VALUES (?,?,?,?)`, [committedRevision, prepared.contentHash, prepared.kind, prepared.createdAt]);
|
|
9318
10145
|
db.run(`INSERT INTO configuration_operations
|
|
9319
10146
|
(mutation_id,request_hash,expected_revision,committed_revision,kind,state,result_status,error_code,error_detail,
|
|
9320
|
-
drain_recovery_generation,last_drain_recovery_previous_generation,
|
|
9321
|
-
|
|
10147
|
+
drain_recovery_generation,last_drain_recovery_previous_generation,plugin_catalog_hash,cancel_requested,
|
|
10148
|
+
prepare_started,target_worker_count,created_at,updated_at)
|
|
10149
|
+
VALUES (?,?,?,?,?,'pending',NULL,NULL,NULL,0,NULL,NULL,0,0,?,?,?)`, [
|
|
9322
10150
|
prepared.mutationId,
|
|
9323
10151
|
prepared.requestHash,
|
|
9324
10152
|
prepared.expectedRevision,
|
|
@@ -9354,7 +10182,10 @@ function commitTransaction(db, prepared, options, snapshot, offlineManagement =
|
|
|
9354
10182
|
target_worker_count: prepared.targetSlots.length,
|
|
9355
10183
|
drain_recovery_generation: 0,
|
|
9356
10184
|
last_drain_recovery_previous_generation: null,
|
|
9357
|
-
|
|
10185
|
+
plugin_catalog_hash: null,
|
|
10186
|
+
cancel_requested: false,
|
|
10187
|
+
prepare_started: false,
|
|
10188
|
+
state: "pending",
|
|
9358
10189
|
result_status: null,
|
|
9359
10190
|
error_code: null,
|
|
9360
10191
|
error_detail: null,
|
|
@@ -9604,11 +10435,17 @@ function auditConfigurationTables(db) {
|
|
|
9604
10435
|
}
|
|
9605
10436
|
workersByMutation.set(worker.mutation_id, [...workersByMutation.get(worker.mutation_id) ?? [], worker]);
|
|
9606
10437
|
}
|
|
10438
|
+
let owner;
|
|
9607
10439
|
for (const operation of operations) {
|
|
9608
10440
|
const workers = workersByMutation.get(operation.mutation_id) ?? [];
|
|
9609
10441
|
validateOperationRelations(operation, workers);
|
|
9610
|
-
if (operation.
|
|
9611
|
-
|
|
10442
|
+
if (operation.state === "committed" || operation.state === "publishing" || operation.state === "draining") {
|
|
10443
|
+
if (owner !== undefined)
|
|
10444
|
+
throw new ConfigRepositoryError("schema_corrupt", "multiple publication owners exist");
|
|
10445
|
+
owner = operation;
|
|
10446
|
+
}
|
|
10447
|
+
if (operation.state === "superseded" && operation.committed_revision === state.active_revision) {
|
|
10448
|
+
throw new ConfigRepositoryError("schema_corrupt", "the latest revision cannot be superseded");
|
|
9612
10449
|
}
|
|
9613
10450
|
}
|
|
9614
10451
|
const activeRevisionRow = revisions.at(-1);
|
|
@@ -9700,129 +10537,6 @@ function prepareCommitCommand(input, compileOptions) {
|
|
|
9700
10537
|
};
|
|
9701
10538
|
}
|
|
9702
10539
|
|
|
9703
|
-
// src/config-storage/consistent-read.ts
|
|
9704
|
-
function withConsistentRead(db, fn) {
|
|
9705
|
-
if (db.inTransaction)
|
|
9706
|
-
return fn();
|
|
9707
|
-
return db.transaction(fn).deferred();
|
|
9708
|
-
}
|
|
9709
|
-
|
|
9710
|
-
// src/config-storage/serving-snapshot.ts
|
|
9711
|
-
var MAX_AGGREGATE_BYTES = 1048576;
|
|
9712
|
-
function invalid4(message) {
|
|
9713
|
-
throw new ConfigRepositoryError("invalid_configuration", message);
|
|
9714
|
-
}
|
|
9715
|
-
function corrupt3(message) {
|
|
9716
|
-
throw new ConfigRepositoryError("serving_snapshot_corrupt", message);
|
|
9717
|
-
}
|
|
9718
|
-
function canonicalAggregate(aggregate) {
|
|
9719
|
-
const result = parseNormalizeCompileAggregate(aggregate, undefined);
|
|
9720
|
-
if (!result.ok)
|
|
9721
|
-
invalid4("configuration aggregate is invalid");
|
|
9722
|
-
const aggregateJson = canonicalJson(result.value);
|
|
9723
|
-
const bytes = new TextEncoder().encode(aggregateJson).byteLength;
|
|
9724
|
-
if (bytes < 2 || bytes > MAX_AGGREGATE_BYTES) {
|
|
9725
|
-
invalid4("configuration aggregate is too large");
|
|
9726
|
-
}
|
|
9727
|
-
return { aggregateJson, contentHash: hashConfigurationContent(result.value) };
|
|
9728
|
-
}
|
|
9729
|
-
function appendServingSnapshot(db, snapshot, pluginCatalogHash) {
|
|
9730
|
-
if (!Number.isSafeInteger(snapshot?.revision) || snapshot.revision <= 0 || typeof snapshot.content_hash !== "string" || !validateDigest(snapshot.content_hash) || !validateDigest(pluginCatalogHash)) {
|
|
9731
|
-
invalid4("serving snapshot identity is invalid");
|
|
9732
|
-
}
|
|
9733
|
-
const normalized = canonicalAggregate(snapshot.aggregate);
|
|
9734
|
-
if (normalized.contentHash !== snapshot.content_hash) {
|
|
9735
|
-
invalid4("configuration aggregate content hash does not match");
|
|
9736
|
-
}
|
|
9737
|
-
const transaction = db.transaction(() => {
|
|
9738
|
-
const revision = sqliteGet(db, "SELECT revision,content_hash FROM configuration_revisions WHERE revision=?", snapshot.revision);
|
|
9739
|
-
if (revision === null || revision.content_hash !== snapshot.content_hash) {
|
|
9740
|
-
invalid4("serving snapshot revision does not match configuration history");
|
|
9741
|
-
}
|
|
9742
|
-
const existing = sqliteGet(db, `SELECT revision,content_hash,plugin_catalog_hash,aggregate_json
|
|
9743
|
-
FROM configuration_serving_snapshots
|
|
9744
|
-
WHERE revision=? AND content_hash=? AND plugin_catalog_hash=?`, snapshot.revision, snapshot.content_hash, pluginCatalogHash);
|
|
9745
|
-
if (existing !== null) {
|
|
9746
|
-
if (existing.aggregate_json !== normalized.aggregateJson) {
|
|
9747
|
-
corrupt3("configuration serving snapshot is immutable and inconsistent");
|
|
9748
|
-
}
|
|
9749
|
-
return;
|
|
9750
|
-
}
|
|
9751
|
-
db.run(`INSERT INTO configuration_serving_snapshots
|
|
9752
|
-
(revision,content_hash,plugin_catalog_hash,aggregate_json) VALUES (?,?,?,?)`, [snapshot.revision, snapshot.content_hash, pluginCatalogHash, normalized.aggregateJson]);
|
|
9753
|
-
});
|
|
9754
|
-
transaction.immediate();
|
|
9755
|
-
}
|
|
9756
|
-
function getServingSnapshot(db, key) {
|
|
9757
|
-
if (!Number.isSafeInteger(key?.revision) || key.revision <= 0 || typeof key.content_hash !== "string" || !validateDigest(key.content_hash) || typeof key.plugin_catalog_hash !== "string" || !validateDigest(key.plugin_catalog_hash)) {
|
|
9758
|
-
invalid4("serving snapshot lookup identity is invalid");
|
|
9759
|
-
}
|
|
9760
|
-
return withConsistentRead(db, () => {
|
|
9761
|
-
const row = sqliteGet(db, `SELECT revision,content_hash,plugin_catalog_hash,aggregate_json
|
|
9762
|
-
FROM configuration_serving_snapshots
|
|
9763
|
-
WHERE revision=? AND content_hash=? AND plugin_catalog_hash=?`, key.revision, key.content_hash, key.plugin_catalog_hash);
|
|
9764
|
-
if (row === null)
|
|
9765
|
-
return null;
|
|
9766
|
-
if (row.revision !== key.revision || row.content_hash !== key.content_hash || row.plugin_catalog_hash !== key.plugin_catalog_hash || !Number.isSafeInteger(row.revision) || row.revision <= 0 || !validateDigest(row.content_hash) || !validateDigest(row.plugin_catalog_hash)) {
|
|
9767
|
-
corrupt3("configuration serving snapshot identity is invalid");
|
|
9768
|
-
}
|
|
9769
|
-
const bytes = new TextEncoder().encode(row.aggregate_json).byteLength;
|
|
9770
|
-
if (bytes < 2 || bytes > MAX_AGGREGATE_BYTES)
|
|
9771
|
-
corrupt3("configuration serving snapshot size is invalid");
|
|
9772
|
-
let parsed;
|
|
9773
|
-
try {
|
|
9774
|
-
parsed = JSON.parse(row.aggregate_json);
|
|
9775
|
-
} catch {
|
|
9776
|
-
corrupt3("configuration serving snapshot JSON is invalid");
|
|
9777
|
-
}
|
|
9778
|
-
let canonical;
|
|
9779
|
-
try {
|
|
9780
|
-
canonical = canonicalJson(parsed);
|
|
9781
|
-
} catch {
|
|
9782
|
-
corrupt3("configuration serving snapshot JSON is invalid");
|
|
9783
|
-
}
|
|
9784
|
-
if (canonical !== row.aggregate_json)
|
|
9785
|
-
corrupt3("configuration serving snapshot JSON is not canonical");
|
|
9786
|
-
const normalized = parseNormalizeCompileAggregate(parsed, undefined);
|
|
9787
|
-
if (!normalized.ok) {
|
|
9788
|
-
if (normalized.errors.some((error) => error.code === "unknown_field" && /^logical_configuration\.routes\[\d+\]\.(service_id|service)$/.test(error.path))) {
|
|
9789
|
-
throw new ConfigRepositoryError("invalid_configuration", "historical serving snapshot does not use the current configuration schema and cannot be loaded");
|
|
9790
|
-
}
|
|
9791
|
-
corrupt3("configuration serving snapshot aggregate is invalid");
|
|
9792
|
-
}
|
|
9793
|
-
if (canonicalJson(normalized.value) !== row.aggregate_json) {
|
|
9794
|
-
corrupt3("configuration serving snapshot aggregate normalization drifted");
|
|
9795
|
-
}
|
|
9796
|
-
if (hashConfigurationContent(normalized.value) !== key.content_hash) {
|
|
9797
|
-
corrupt3("configuration serving snapshot content hash is invalid");
|
|
9798
|
-
}
|
|
9799
|
-
const revision = sqliteGet(db, "SELECT revision,content_hash FROM configuration_revisions WHERE revision=?", key.revision);
|
|
9800
|
-
if (revision === null || revision.revision !== key.revision || revision.content_hash !== key.content_hash) {
|
|
9801
|
-
corrupt3("configuration serving snapshot revision is invalid");
|
|
9802
|
-
}
|
|
9803
|
-
return { revision: row.revision, content_hash: row.content_hash, aggregate: normalized.value };
|
|
9804
|
-
});
|
|
9805
|
-
}
|
|
9806
|
-
function auditServingSnapshotHistory(db) {
|
|
9807
|
-
const rows = db.query(`SELECT s.revision,s.content_hash,s.plugin_catalog_hash,s.aggregate_json,
|
|
9808
|
-
r.content_hash AS revision_hash FROM configuration_serving_snapshots s
|
|
9809
|
-
LEFT JOIN configuration_revisions r ON r.revision=s.revision`).all();
|
|
9810
|
-
for (const row of rows) {
|
|
9811
|
-
if (row.revision_hash !== row.content_hash || !validateDigest(row.content_hash) || !validateDigest(row.plugin_catalog_hash)) {
|
|
9812
|
-
corrupt3("historical serving snapshot identity is invalid");
|
|
9813
|
-
}
|
|
9814
|
-
try {
|
|
9815
|
-
const parsed = JSON.parse(row.aggregate_json);
|
|
9816
|
-
if (new TextEncoder().encode(row.aggregate_json).byteLength > MAX_AGGREGATE_BYTES || canonicalJson(parsed) !== row.aggregate_json || hashConfigurationContent(parsed) !== row.content_hash)
|
|
9817
|
-
corrupt3("historical serving snapshot content is invalid");
|
|
9818
|
-
} catch (error) {
|
|
9819
|
-
if (error instanceof ConfigRepositoryError)
|
|
9820
|
-
throw error;
|
|
9821
|
-
corrupt3("historical serving snapshot JSON is invalid");
|
|
9822
|
-
}
|
|
9823
|
-
}
|
|
9824
|
-
}
|
|
9825
|
-
|
|
9826
10540
|
// src/config-storage/schema-fingerprint.ts
|
|
9827
10541
|
import { Database } from "bun:sqlite";
|
|
9828
10542
|
|
|
@@ -10317,8 +11031,184 @@ var PUBLICATION_RETIREMENT_MIGRATION = {
|
|
|
10317
11031
|
}
|
|
10318
11032
|
};
|
|
10319
11033
|
|
|
11034
|
+
// src/config-storage/migrations/publication-targets.ts
|
|
11035
|
+
var PUBLICATION_TARGET_MIGRATION = {
|
|
11036
|
+
version: 8,
|
|
11037
|
+
name: "publication_targets_and_cancellation",
|
|
11038
|
+
up(db) {
|
|
11039
|
+
const unfinished = sqliteGet(db, `SELECT mutation_id,state FROM configuration_operations
|
|
11040
|
+
WHERE state IN ('committed','publishing','draining') LIMIT 1`);
|
|
11041
|
+
if (unfinished !== null) {
|
|
11042
|
+
throw new ConfigRepositoryError("migration_failed", `configuration upgrade cannot resume publication ${unfinished.mutation_id} (${unfinished.state}); finish it with the previous executable before upgrading`);
|
|
11043
|
+
}
|
|
11044
|
+
db.run(`CREATE TABLE configuration_operations_next (
|
|
11045
|
+
mutation_id TEXT PRIMARY KEY CHECK(length(mutation_id) BETWEEN 1 AND 128),
|
|
11046
|
+
request_hash TEXT NOT NULL CHECK(length(request_hash)=71 AND substr(request_hash,1,7)='sha256:' AND substr(request_hash,8) NOT GLOB '*[^0-9a-f]*'),
|
|
11047
|
+
expected_revision INTEGER NOT NULL CHECK(expected_revision > 0 AND expected_revision <= 9007199254740991),
|
|
11048
|
+
committed_revision INTEGER NOT NULL CHECK(committed_revision > 0 AND committed_revision <= 9007199254740991)
|
|
11049
|
+
REFERENCES configuration_revisions(revision),
|
|
11050
|
+
kind TEXT NOT NULL CHECK(kind IN ('config','admin_state')),
|
|
11051
|
+
target_worker_count INTEGER NOT NULL CHECK(target_worker_count >= 0 AND target_worker_count <= 9007199254740991),
|
|
11052
|
+
state TEXT NOT NULL CHECK(state IN ('pending','committed','publishing','draining','converged','degraded','superseded')),
|
|
11053
|
+
result_status INTEGER,
|
|
11054
|
+
error_code TEXT,
|
|
11055
|
+
error_detail TEXT,
|
|
11056
|
+
drain_recovery_generation INTEGER NOT NULL DEFAULT 0
|
|
11057
|
+
CHECK(drain_recovery_generation >= 0 AND drain_recovery_generation <= 9007199254740991),
|
|
11058
|
+
last_drain_recovery_previous_generation INTEGER
|
|
11059
|
+
CHECK(last_drain_recovery_previous_generation IS NULL OR
|
|
11060
|
+
(last_drain_recovery_previous_generation >= 0 AND
|
|
11061
|
+
last_drain_recovery_previous_generation < 9007199254740991)),
|
|
11062
|
+
management_provider TEXT,
|
|
11063
|
+
offline_management INTEGER NOT NULL DEFAULT 0 CHECK(offline_management IN (0,1)),
|
|
11064
|
+
plugin_catalog_hash TEXT CHECK(plugin_catalog_hash IS NULL OR
|
|
11065
|
+
(length(plugin_catalog_hash)=71 AND substr(plugin_catalog_hash,1,7)='sha256:' AND
|
|
11066
|
+
substr(plugin_catalog_hash,8) NOT GLOB '*[^0-9a-f]*')),
|
|
11067
|
+
cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),
|
|
11068
|
+
prepare_started INTEGER NOT NULL DEFAULT 0 CHECK(prepare_started IN (0,1)),
|
|
11069
|
+
created_at INTEGER NOT NULL CHECK(created_at >= 0 AND created_at <= 9007199254740991),
|
|
11070
|
+
updated_at INTEGER NOT NULL CHECK(updated_at >= created_at AND updated_at <= 9007199254740991),
|
|
11071
|
+
UNIQUE(mutation_id,committed_revision),
|
|
11072
|
+
CHECK((drain_recovery_generation=0 AND last_drain_recovery_previous_generation IS NULL) OR
|
|
11073
|
+
(drain_recovery_generation > 0 AND
|
|
11074
|
+
last_drain_recovery_previous_generation=drain_recovery_generation-1)),
|
|
11075
|
+
CHECK((state='pending' AND drain_recovery_generation=0 AND result_status IS NULL AND
|
|
11076
|
+
error_code IS NULL AND error_detail IS NULL AND cancel_requested=0 AND prepare_started=0) OR
|
|
11077
|
+
(state IN ('committed','publishing') AND drain_recovery_generation=0 AND
|
|
11078
|
+
result_status IS NULL AND error_code IS NULL AND error_detail IS NULL) OR
|
|
11079
|
+
(state='draining' AND result_status IS NULL AND error_code IS NULL AND error_detail IS NULL) OR
|
|
11080
|
+
(state='converged' AND drain_recovery_generation=0 AND
|
|
11081
|
+
result_status=200 AND error_code IS NULL AND error_detail IS NULL) OR
|
|
11082
|
+
(state='degraded' AND result_status=202 AND
|
|
11083
|
+
error_code IN ('replacement_convergence_failed','old_worker_drain_failed','control_readiness_failed') AND
|
|
11084
|
+
(error_code <> 'replacement_convergence_failed' OR drain_recovery_generation=0) AND
|
|
11085
|
+
error_detail IS NOT NULL AND length(error_detail) <= 512 AND length(trim(error_detail)) > 0) OR
|
|
11086
|
+
(state='superseded' AND drain_recovery_generation=0 AND result_status=409 AND
|
|
11087
|
+
error_code='revision_superseded' AND prepare_started=0 AND
|
|
11088
|
+
error_detail IS NOT NULL AND length(error_detail) <= 512 AND length(trim(error_detail)) > 0))
|
|
11089
|
+
) STRICT`);
|
|
11090
|
+
db.run(`INSERT INTO configuration_operations_next
|
|
11091
|
+
(mutation_id,request_hash,expected_revision,committed_revision,kind,target_worker_count,state,
|
|
11092
|
+
result_status,error_code,error_detail,drain_recovery_generation,
|
|
11093
|
+
last_drain_recovery_previous_generation,management_provider,offline_management,created_at,updated_at)
|
|
11094
|
+
SELECT mutation_id,request_hash,expected_revision,committed_revision,kind,target_worker_count,state,
|
|
11095
|
+
result_status,error_code,error_detail,drain_recovery_generation,
|
|
11096
|
+
last_drain_recovery_previous_generation,management_provider,offline_management,created_at,updated_at
|
|
11097
|
+
FROM configuration_operations`);
|
|
11098
|
+
db.run("DROP TABLE configuration_operations");
|
|
11099
|
+
db.run("ALTER TABLE configuration_operations_next RENAME TO configuration_operations");
|
|
11100
|
+
db.run(`CREATE TRIGGER configuration_operations_terminal_immutable_delete
|
|
11101
|
+
BEFORE DELETE ON configuration_operations
|
|
11102
|
+
WHEN OLD.state IN ('converged','degraded','superseded')
|
|
11103
|
+
BEGIN SELECT RAISE(ABORT,'terminal configuration operations are immutable'); END`);
|
|
11104
|
+
db.run(`CREATE TRIGGER configuration_operations_terminal_immutable_update
|
|
11105
|
+
BEFORE UPDATE ON configuration_operations
|
|
11106
|
+
WHEN OLD.state IN ('converged','degraded','superseded')
|
|
11107
|
+
BEGIN SELECT RAISE(ABORT,'terminal configuration operations are immutable'); END`);
|
|
11108
|
+
db.run(`CREATE UNIQUE INDEX configuration_operations_single_owner
|
|
11109
|
+
ON configuration_operations((state IN ('committed','publishing','draining')))
|
|
11110
|
+
WHERE state IN ('committed','publishing','draining')`);
|
|
11111
|
+
db.run(`CREATE TABLE configuration_publication_candidate_evidence (
|
|
11112
|
+
mutation_id TEXT NOT NULL,
|
|
11113
|
+
worker_slot INTEGER NOT NULL CHECK(worker_slot >= 0 AND worker_slot <= 9007199254740991),
|
|
11114
|
+
attempt_no INTEGER NOT NULL CHECK(attempt_no > 0 AND attempt_no <= 9007199254740991),
|
|
11115
|
+
exit_kind TEXT NOT NULL CHECK(exit_kind IN ('not_started','exited')),
|
|
11116
|
+
cleanup TEXT NOT NULL CHECK((exit_kind='not_started' AND cleanup='not_started') OR
|
|
11117
|
+
(exit_kind='exited' AND cleanup='released')),
|
|
11118
|
+
updated_at INTEGER NOT NULL CHECK(updated_at >= 0 AND updated_at <= 9007199254740991),
|
|
11119
|
+
PRIMARY KEY(mutation_id,worker_slot,attempt_no),
|
|
11120
|
+
FOREIGN KEY(mutation_id,worker_slot)
|
|
11121
|
+
REFERENCES configuration_operation_workers(mutation_id,worker_slot)
|
|
11122
|
+
) STRICT, WITHOUT ROWID`);
|
|
11123
|
+
db.run("CREATE TRIGGER publication_candidate_evidence_no_delete BEFORE DELETE ON configuration_publication_candidate_evidence BEGIN SELECT RAISE(ABORT,'publication candidate evidence is immutable'); END");
|
|
11124
|
+
db.run("CREATE TRIGGER publication_candidate_evidence_no_update BEFORE UPDATE ON configuration_publication_candidate_evidence BEGIN SELECT RAISE(ABORT,'publication candidate evidence is immutable'); END");
|
|
11125
|
+
db.run("CREATE TRIGGER publication_candidate_evidence_no_replace BEFORE INSERT ON configuration_publication_candidate_evidence WHEN EXISTS(SELECT 1 FROM configuration_publication_candidate_evidence WHERE mutation_id=NEW.mutation_id AND worker_slot=NEW.worker_slot AND attempt_no=NEW.attempt_no) BEGIN SELECT RAISE(ABORT,'publication candidate evidence is immutable'); END");
|
|
11126
|
+
db.run(`CREATE TABLE configuration_worker_launch_intents (
|
|
11127
|
+
worker_instance_id TEXT PRIMARY KEY CHECK(length(worker_instance_id)=36 AND
|
|
11128
|
+
substr(worker_instance_id,9,1)='-' AND substr(worker_instance_id,14,1)='-' AND
|
|
11129
|
+
substr(worker_instance_id,19,1)='-' AND substr(worker_instance_id,24,1)='-' AND
|
|
11130
|
+
replace(worker_instance_id,'-','') NOT GLOB '*[^0-9a-f]*'),
|
|
11131
|
+
master_generation TEXT NOT NULL CHECK(length(master_generation)=36),
|
|
11132
|
+
worker_slot INTEGER NOT NULL CHECK(worker_slot >= 0 AND worker_slot <= 9007199254740991),
|
|
11133
|
+
allocation_mutation_id TEXT CHECK(allocation_mutation_id IS NULL OR
|
|
11134
|
+
length(allocation_mutation_id) BETWEEN 1 AND 128),
|
|
11135
|
+
allocation_worker_slot INTEGER CHECK(allocation_worker_slot IS NULL OR
|
|
11136
|
+
(allocation_worker_slot >= 0 AND allocation_worker_slot <= 9007199254740991)),
|
|
11137
|
+
allocation_attempt_no INTEGER CHECK(allocation_attempt_no IS NULL OR
|
|
11138
|
+
(allocation_attempt_no > 0 AND allocation_attempt_no <= 9007199254740991)),
|
|
11139
|
+
guard_json TEXT NOT NULL CHECK(length(guard_json) > 0),
|
|
11140
|
+
registered_at INTEGER NOT NULL CHECK(registered_at >= 0 AND registered_at <= 9007199254740991),
|
|
11141
|
+
CHECK((allocation_mutation_id IS NULL AND allocation_worker_slot IS NULL AND allocation_attempt_no IS NULL) OR
|
|
11142
|
+
(allocation_mutation_id IS NOT NULL AND allocation_worker_slot IS NOT NULL AND
|
|
11143
|
+
allocation_attempt_no IS NOT NULL AND allocation_worker_slot=worker_slot)),
|
|
11144
|
+
FOREIGN KEY(allocation_mutation_id,allocation_worker_slot)
|
|
11145
|
+
REFERENCES configuration_operation_workers(mutation_id,worker_slot)
|
|
11146
|
+
) STRICT`);
|
|
11147
|
+
db.run("CREATE TRIGGER configuration_worker_launch_intents_no_delete BEFORE DELETE ON configuration_worker_launch_intents BEGIN SELECT RAISE(ABORT,'worker launch intent is immutable'); END");
|
|
11148
|
+
db.run("CREATE TRIGGER configuration_worker_launch_intents_no_update BEFORE UPDATE ON configuration_worker_launch_intents BEGIN SELECT RAISE(ABORT,'worker launch intent is immutable'); END");
|
|
11149
|
+
db.run(`CREATE TABLE configuration_worker_launch_facts (
|
|
11150
|
+
fact_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11151
|
+
kind TEXT NOT NULL CHECK(kind IN ('reserved','not_started','admitted','exited','cleanup')),
|
|
11152
|
+
mutation_id TEXT,
|
|
11153
|
+
worker_slot INTEGER,
|
|
11154
|
+
attempt_no INTEGER,
|
|
11155
|
+
worker_instance_id TEXT,
|
|
11156
|
+
recorded_at INTEGER NOT NULL CHECK(recorded_at >= 0 AND recorded_at <= 9007199254740991),
|
|
11157
|
+
CHECK((mutation_id IS NULL AND worker_slot IS NULL AND attempt_no IS NULL) OR
|
|
11158
|
+
(mutation_id IS NOT NULL AND worker_slot IS NOT NULL AND attempt_no IS NOT NULL AND
|
|
11159
|
+
worker_slot >= 0 AND worker_slot <= 9007199254740991 AND
|
|
11160
|
+
attempt_no > 0 AND attempt_no <= 9007199254740991)),
|
|
11161
|
+
CHECK((kind='reserved' AND worker_instance_id IS NULL AND mutation_id IS NOT NULL) OR
|
|
11162
|
+
(kind='not_started' AND (worker_instance_id IS NOT NULL OR mutation_id IS NOT NULL)) OR
|
|
11163
|
+
(kind IN ('admitted','exited','cleanup') AND worker_instance_id IS NOT NULL)),
|
|
11164
|
+
FOREIGN KEY(mutation_id,worker_slot) REFERENCES configuration_operation_workers(mutation_id,worker_slot),
|
|
11165
|
+
FOREIGN KEY(worker_instance_id) REFERENCES configuration_worker_launch_intents(worker_instance_id)
|
|
11166
|
+
) STRICT`);
|
|
11167
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_reserved ON configuration_worker_launch_facts(mutation_id,worker_slot,attempt_no) WHERE kind='reserved'");
|
|
11168
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_not_started_allocation ON configuration_worker_launch_facts(mutation_id,worker_slot,attempt_no) WHERE kind='not_started' AND mutation_id IS NOT NULL");
|
|
11169
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_not_started_instance ON configuration_worker_launch_facts(worker_instance_id) WHERE kind='not_started' AND worker_instance_id IS NOT NULL");
|
|
11170
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_admitted ON configuration_worker_launch_facts(worker_instance_id) WHERE kind='admitted'");
|
|
11171
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_exited ON configuration_worker_launch_facts(worker_instance_id) WHERE kind='exited'");
|
|
11172
|
+
db.run("CREATE UNIQUE INDEX configuration_worker_launch_facts_cleanup ON configuration_worker_launch_facts(worker_instance_id) WHERE kind='cleanup'");
|
|
11173
|
+
db.run("CREATE TRIGGER configuration_worker_launch_facts_no_delete BEFORE DELETE ON configuration_worker_launch_facts BEGIN SELECT RAISE(ABORT,'worker launch facts are immutable'); END");
|
|
11174
|
+
db.run("CREATE TRIGGER configuration_worker_launch_facts_no_update BEFORE UPDATE ON configuration_worker_launch_facts BEGIN SELECT RAISE(ABORT,'worker launch facts are immutable'); END");
|
|
11175
|
+
}
|
|
11176
|
+
};
|
|
11177
|
+
|
|
11178
|
+
// src/config-storage/migrations/request-logs-default.ts
|
|
11179
|
+
var REQUEST_LOGS_DEFAULT_MIGRATION = {
|
|
11180
|
+
version: 9,
|
|
11181
|
+
name: "request_logs_default",
|
|
11182
|
+
up(db) {
|
|
11183
|
+
db.run(`CREATE TABLE configuration_request_logs_default (
|
|
11184
|
+
id INTEGER PRIMARY KEY CHECK(id=1),
|
|
11185
|
+
settled_revision INTEGER NOT NULL REFERENCES configuration_revisions(revision)
|
|
11186
|
+
) STRICT, WITHOUT ROWID`);
|
|
11187
|
+
}
|
|
11188
|
+
};
|
|
11189
|
+
|
|
11190
|
+
// src/config-storage/migrations/worker-launch-capacity.ts
|
|
11191
|
+
var WORKER_LAUNCH_CAPACITY_MIGRATION = {
|
|
11192
|
+
version: 10,
|
|
11193
|
+
name: "worker_launch_capacity",
|
|
11194
|
+
up(db) {
|
|
11195
|
+
db.run(`CREATE TABLE configuration_worker_launch_capacity_reclaims (
|
|
11196
|
+
worker_instance_id TEXT PRIMARY KEY REFERENCES configuration_worker_launch_intents(worker_instance_id),
|
|
11197
|
+
recorded_at INTEGER NOT NULL CHECK(recorded_at >= 0 AND recorded_at <= 9007199254740991)
|
|
11198
|
+
) STRICT, WITHOUT ROWID`);
|
|
11199
|
+
db.run(`CREATE TRIGGER configuration_worker_launch_capacity_reclaims_guard BEFORE INSERT ON configuration_worker_launch_capacity_reclaims
|
|
11200
|
+
WHEN EXISTS (SELECT 1 FROM configuration_worker_launch_capacity_reclaims WHERE worker_instance_id=NEW.worker_instance_id)
|
|
11201
|
+
OR NOT EXISTS (SELECT 1 FROM configuration_worker_launch_facts WHERE worker_instance_id=NEW.worker_instance_id AND kind='admitted' AND recorded_at<=NEW.recorded_at)
|
|
11202
|
+
OR NOT EXISTS (SELECT 1 FROM configuration_worker_launch_facts WHERE worker_instance_id=NEW.worker_instance_id AND kind='exited' AND recorded_at<=NEW.recorded_at)
|
|
11203
|
+
OR EXISTS (SELECT 1 FROM configuration_worker_launch_facts WHERE worker_instance_id=NEW.worker_instance_id AND kind IN ('not_started','cleanup'))
|
|
11204
|
+
BEGIN SELECT RAISE(ABORT,'worker launch capacity reclaim requires a new admitted exit without successful cleanup'); END`);
|
|
11205
|
+
db.run("CREATE TRIGGER configuration_worker_launch_capacity_reclaims_no_delete BEFORE DELETE ON configuration_worker_launch_capacity_reclaims BEGIN SELECT RAISE(ABORT,'worker launch capacity reclaim is immutable'); END");
|
|
11206
|
+
db.run("CREATE TRIGGER configuration_worker_launch_capacity_reclaims_no_update BEFORE UPDATE ON configuration_worker_launch_capacity_reclaims BEGIN SELECT RAISE(ABORT,'worker launch capacity reclaim is immutable'); END");
|
|
11207
|
+
}
|
|
11208
|
+
};
|
|
11209
|
+
|
|
10320
11210
|
// src/config-storage/migrations/plan.ts
|
|
10321
|
-
var CONFIG_MIGRATIONS = [CONFIG_BASELINE, PUBLICATION_RETIREMENT_MIGRATION, UI_MENUS_MIGRATION, MANAGEMENT_PROTECTION_MIGRATION, SERVICE_REFERENCES_MIGRATION, WEBSOCKET_CONNECTIONS_MIGRATION, WEBSOCKET_MESSAGE_SIZE_MIGRATION];
|
|
11211
|
+
var CONFIG_MIGRATIONS = [CONFIG_BASELINE, PUBLICATION_RETIREMENT_MIGRATION, UI_MENUS_MIGRATION, MANAGEMENT_PROTECTION_MIGRATION, SERVICE_REFERENCES_MIGRATION, WEBSOCKET_CONNECTIONS_MIGRATION, WEBSOCKET_MESSAGE_SIZE_MIGRATION, PUBLICATION_TARGET_MIGRATION, REQUEST_LOGS_DEFAULT_MIGRATION, WORKER_LAUNCH_CAPACITY_MIGRATION];
|
|
10322
11212
|
var CONFIG_SCHEMA_VERSION = CONFIG_MIGRATIONS.at(-1).version;
|
|
10323
11213
|
|
|
10324
11214
|
// src/config-storage/schema-fingerprint.ts
|
|
@@ -10480,15 +11370,87 @@ function convertServiceReferenceRevision(db, options) {
|
|
|
10480
11370
|
const result = commitTransaction(db, command, options, snapshot);
|
|
10481
11371
|
if (result.kind !== "committed")
|
|
10482
11372
|
throw new ConfigRepositoryError("migration_failed", `service reference revision commit failed (${result.kind})`);
|
|
10483
|
-
|
|
10484
|
-
markDraining(db, operationId, now);
|
|
10485
|
-
finalizePublication(db, operationId, { outcome: "converged", old_workers_exited: true }, now);
|
|
11373
|
+
finalizeOfflineOperation(db, operationId, now);
|
|
10486
11374
|
readRepositorySnapshot(db);
|
|
10487
11375
|
}
|
|
10488
11376
|
|
|
11377
|
+
// src/config-storage/request-logs-default.ts
|
|
11378
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
11379
|
+
var PLUGIN = "request-logs";
|
|
11380
|
+
function settleRequestLogsDefault(db, options, revision) {
|
|
11381
|
+
if (!options.compileOptions?.availablePlugins?.has(PLUGIN))
|
|
11382
|
+
return;
|
|
11383
|
+
db.run(`INSERT INTO configuration_request_logs_default (id,settled_revision) VALUES(1,?)
|
|
11384
|
+
ON CONFLICT(id) DO NOTHING`, [revision]);
|
|
11385
|
+
}
|
|
11386
|
+
function applyRequestLogsDefault(db, options, targetWorkerSlots) {
|
|
11387
|
+
if (!options.compileOptions?.availablePlugins?.has(PLUGIN))
|
|
11388
|
+
return false;
|
|
11389
|
+
const state = sqliteGet(db, `SELECT updated_at FROM configuration_state WHERE id=1
|
|
11390
|
+
AND NOT EXISTS (SELECT 1 FROM configuration_request_logs_default WHERE id=1)`);
|
|
11391
|
+
if (state === null)
|
|
11392
|
+
return false;
|
|
11393
|
+
verifyRepositoryIntegrity(db);
|
|
11394
|
+
const snapshot = readRepositorySnapshot(db);
|
|
11395
|
+
let settledRevision = snapshot.revision;
|
|
11396
|
+
if (!snapshot.aggregate.plugin_activations.some((activation) => activation.plugin_name === PLUGIN)) {
|
|
11397
|
+
const unfinished = sqliteGet(db, `SELECT 1 AS unfinished FROM configuration_operations
|
|
11398
|
+
WHERE state IN ('committed','publishing','draining') OR (state='pending' AND committed_revision=(
|
|
11399
|
+
SELECT active_revision FROM configuration_state WHERE id=1))
|
|
11400
|
+
UNION ALL SELECT 1 FROM configuration_retirements WHERE state<>'released'
|
|
11401
|
+
UNION ALL SELECT 1 FROM configuration_recoveries WHERE state='stopped' AND recovery_sequence=(
|
|
11402
|
+
SELECT max(recovery_sequence) FROM configuration_recoveries WHERE target_revision=(
|
|
11403
|
+
SELECT active_revision FROM configuration_state WHERE id=1))
|
|
11404
|
+
LIMIT 1`);
|
|
11405
|
+
if (unfinished !== null || readPublicationRecoveryBarrier(db) !== null || readUnsettledWorkerLaunches(db).length > 0)
|
|
11406
|
+
return false;
|
|
11407
|
+
const aggregate = {
|
|
11408
|
+
...snapshot.aggregate,
|
|
11409
|
+
plugin_activations: [...snapshot.aggregate.plugin_activations, { plugin_name: PLUGIN }]
|
|
11410
|
+
};
|
|
11411
|
+
const operationId = randomUUID3();
|
|
11412
|
+
const now = Math.max(Date.now(), state.updated_at);
|
|
11413
|
+
const prepared = prepareCommitCommand({
|
|
11414
|
+
mutation_id: operationId,
|
|
11415
|
+
expected_revision: snapshot.revision,
|
|
11416
|
+
aggregate,
|
|
11417
|
+
kind: "config",
|
|
11418
|
+
created_at: now,
|
|
11419
|
+
target_worker_slots: targetWorkerSlots ?? []
|
|
11420
|
+
});
|
|
11421
|
+
const provider = readManagementProtection(db).selectedProvider;
|
|
11422
|
+
const command = {
|
|
11423
|
+
...prepared,
|
|
11424
|
+
managementProvider: provider,
|
|
11425
|
+
requestHash: hashConfigurationRequest({
|
|
11426
|
+
kind: prepared.kind,
|
|
11427
|
+
expected_revision: prepared.expectedRevision,
|
|
11428
|
+
aggregate: prepared.aggregate,
|
|
11429
|
+
target_worker_slots: prepared.targetSlots,
|
|
11430
|
+
management_provider: provider
|
|
11431
|
+
})
|
|
11432
|
+
};
|
|
11433
|
+
const result = commitTransaction(db, command, options, snapshot);
|
|
11434
|
+
if (result.kind !== "committed") {
|
|
11435
|
+
throw new ConfigRepositoryError("migration_failed", `request logs activation revision commit failed (${result.kind})`);
|
|
11436
|
+
}
|
|
11437
|
+
if (targetWorkerSlots === undefined)
|
|
11438
|
+
finalizeOfflineOperation(db, operationId, now);
|
|
11439
|
+
settledRevision = readRepositorySnapshot(db).revision;
|
|
11440
|
+
}
|
|
11441
|
+
settleRequestLogsDefault(db, options, settledRevision);
|
|
11442
|
+
return settledRevision !== snapshot.revision;
|
|
11443
|
+
}
|
|
11444
|
+
|
|
10489
11445
|
// src/config-storage/migrations/index.ts
|
|
10490
11446
|
function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}) {
|
|
11447
|
+
if (db.inTransaction)
|
|
11448
|
+
throw new ConfigRepositoryError("migration_failed", "configuration migration must not nest in a transaction");
|
|
11449
|
+
db.run("PRAGMA foreign_keys = OFF");
|
|
10491
11450
|
try {
|
|
11451
|
+
if (db.query("PRAGMA foreign_keys").get()?.foreign_keys !== 0) {
|
|
11452
|
+
throw new ConfigRepositoryError("migration_failed", "configuration migration could not disable foreign keys");
|
|
11453
|
+
}
|
|
10492
11454
|
db.transaction(() => {
|
|
10493
11455
|
if (!plan.length || plan[0] !== CONFIG_MIGRATIONS[0] || plan.some((m, i) => i > 0 && m.version !== plan[i - 1].version + 1) || new Set(plan.map((m) => m.name)).size !== plan.length)
|
|
10494
11456
|
throw new ConfigRepositoryError("migration_failed", "invalid configuration migration plan");
|
|
@@ -10508,6 +11470,11 @@ function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}
|
|
|
10508
11470
|
if (plan === CONFIG_MIGRATIONS && applied.length > 0 && applied.at(-1).version < 5) {
|
|
10509
11471
|
convertServiceReferenceRevision(db, options);
|
|
10510
11472
|
}
|
|
11473
|
+
if (plan === CONFIG_MIGRATIONS)
|
|
11474
|
+
applyRequestLogsDefault(db, options);
|
|
11475
|
+
if (plan.length > applied.length && db.query("PRAGMA foreign_key_check").all().length > 0) {
|
|
11476
|
+
throw new ConfigRepositoryError("schema_corrupt", "configuration migration left invalid references");
|
|
11477
|
+
}
|
|
10511
11478
|
}).immediate();
|
|
10512
11479
|
} catch (error) {
|
|
10513
11480
|
if (error instanceof ConfigRepositoryError)
|
|
@@ -10515,11 +11482,13 @@ function migrateConfigurationDatabase(db, plan = CONFIG_MIGRATIONS, options = {}
|
|
|
10515
11482
|
if (isSqliteBusyError(error))
|
|
10516
11483
|
throw repositoryFailure("configuration migration was blocked by SQLite", error);
|
|
10517
11484
|
throw new ConfigRepositoryError("migration_failed", "configuration migration failed", error);
|
|
11485
|
+
} finally {
|
|
11486
|
+
db.run("PRAGMA foreign_keys = ON");
|
|
10518
11487
|
}
|
|
10519
11488
|
}
|
|
10520
11489
|
|
|
10521
11490
|
// src/config-storage/config-repository.ts
|
|
10522
|
-
import { randomUUID as
|
|
11491
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
10523
11492
|
|
|
10524
11493
|
// src/config-storage/sqlite-version.ts
|
|
10525
11494
|
class SqliteVersionError extends Error {
|
|
@@ -10806,7 +11775,7 @@ class ConfigRepository {
|
|
|
10806
11775
|
return;
|
|
10807
11776
|
const protection = readManagementProtection(this.db);
|
|
10808
11777
|
const provider = protection.selectedProvider !== null && available.has(protection.selectedProvider) ? protection.selectedProvider : null;
|
|
10809
|
-
const now = Date.now(), operationId =
|
|
11778
|
+
const now = Date.now(), operationId = randomUUID4();
|
|
10810
11779
|
const prepared = prepareCommitCommand({
|
|
10811
11780
|
mutation_id: operationId,
|
|
10812
11781
|
expected_revision: snapshot.revision,
|
|
@@ -10830,9 +11799,7 @@ class ConfigRepository {
|
|
|
10830
11799
|
const result = commitTransaction(this.db, command, this.options, snapshot, true);
|
|
10831
11800
|
if (result.kind !== "committed")
|
|
10832
11801
|
throw new ConfigRepositoryError("invalid_operation", `plugin catalog reconciliation cannot proceed (${result.kind})`);
|
|
10833
|
-
|
|
10834
|
-
markDraining(this.db, operationId, now);
|
|
10835
|
-
finalizePublication(this.db, operationId, { outcome: "converged", old_workers_exited: true }, now);
|
|
11802
|
+
finalizeOfflineOperation(this.db, operationId, now);
|
|
10836
11803
|
}));
|
|
10837
11804
|
this.snapshot = freezeSnapshot(readRepositorySnapshot(this.db));
|
|
10838
11805
|
}
|
|
@@ -10883,11 +11850,9 @@ class ConfigRepository {
|
|
|
10883
11850
|
};
|
|
10884
11851
|
const result = commitTransaction(this.db, offlinePrepared, this.options, snapshot, true);
|
|
10885
11852
|
if (result.kind !== "committed") {
|
|
10886
|
-
throw new ConfigRepositoryError(
|
|
11853
|
+
throw new ConfigRepositoryError("invalid_operation", `offline management change cannot proceed (${result.kind})`);
|
|
10887
11854
|
}
|
|
10888
|
-
|
|
10889
|
-
markDraining(this.db, operationId, now);
|
|
10890
|
-
finalizePublication(this.db, operationId, { outcome: "converged", old_workers_exited: true }, now);
|
|
11855
|
+
finalizeOfflineOperation(this.db, operationId, now);
|
|
10891
11856
|
}));
|
|
10892
11857
|
return this.getControlProjection();
|
|
10893
11858
|
}
|
|
@@ -10913,15 +11878,39 @@ class ConfigRepository {
|
|
|
10913
11878
|
return runRepositoryAction(() => consumeControllerClaimCapability(capability, () => this.mutationTransaction(() => this.supervision.claim(controllerId, updatedAt))));
|
|
10914
11879
|
}
|
|
10915
11880
|
getActivePublication() {
|
|
10916
|
-
return runRepositoryAction(() => withConsistentRead(this.db, () => readActivePublication(this.db
|
|
11881
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readActivePublication(this.db)));
|
|
11882
|
+
}
|
|
11883
|
+
claimPublicationTarget(pluginCatalogHash, updatedAt) {
|
|
11884
|
+
return runRepositoryAction(() => this.publicationTransaction(null, () => claimPublicationTarget(this.db, this.snapshot, pluginCatalogHash, updatedAt)));
|
|
11885
|
+
}
|
|
11886
|
+
requestPublicationCancellation(mutationId, committedRevision, updatedAt) {
|
|
11887
|
+
return runRepositoryAction(() => this.publicationTransaction(mutationId, () => requestPublicationCancellation(this.db, mutationId, committedRevision, updatedAt)));
|
|
11888
|
+
}
|
|
11889
|
+
enterPublicationPrepare(mutationId, committedRevision, updatedAt) {
|
|
11890
|
+
return runRepositoryAction(() => this.publicationTransaction(mutationId, () => enterPublicationPrepare(this.db, mutationId, committedRevision, updatedAt)));
|
|
11891
|
+
}
|
|
11892
|
+
recordPublicationCandidateExit(mutationId, committedRevision, workerSlot, attemptNo, evidence, updatedAt) {
|
|
11893
|
+
return runRepositoryAction(() => this.mutationTransaction(() => recordPublicationCandidateExit(this.db, mutationId, committedRevision, workerSlot, attemptNo, evidence, updatedAt)));
|
|
11894
|
+
}
|
|
11895
|
+
confirmPublicationCandidateExited(mutationId, committedRevision, updatedAt) {
|
|
11896
|
+
return runRepositoryAction(() => this.mutationTransaction(() => confirmPublicationCandidateExited(this.db, mutationId, committedRevision, updatedAt)));
|
|
11897
|
+
}
|
|
11898
|
+
getOutstandingPublicationCandidates() {
|
|
11899
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readOutstandingPublicationCandidates(this.db)));
|
|
10917
11900
|
}
|
|
10918
11901
|
commit(command) {
|
|
10919
11902
|
return this.commitPrepared(prepareCommitCommand(command, this.options.compileOptions));
|
|
10920
11903
|
}
|
|
11904
|
+
applyPendingRequestLogsDefault(targetWorkerSlots) {
|
|
11905
|
+
const applied = this.mutationTransaction(() => applyRequestLogsDefault(this.db, this.options, targetWorkerSlots));
|
|
11906
|
+
return applied ? this.getControlProjection() : null;
|
|
11907
|
+
}
|
|
10921
11908
|
commitPrepared(prepared) {
|
|
10922
11909
|
try {
|
|
10923
11910
|
const decision = this.mutationTransaction(() => {
|
|
10924
11911
|
const result = commitTransaction(this.db, prepared, this.options, this.snapshot);
|
|
11912
|
+
if (result.kind === "committed")
|
|
11913
|
+
settleRequestLogsDefault(this.db, this.options, result.operation.committed_revision);
|
|
10925
11914
|
readManagementProtection(this.db);
|
|
10926
11915
|
return result;
|
|
10927
11916
|
});
|
|
@@ -10961,10 +11950,10 @@ class ConfigRepository {
|
|
|
10961
11950
|
}));
|
|
10962
11951
|
}
|
|
10963
11952
|
getCurrentRecovery() {
|
|
10964
|
-
return runRepositoryAction(() => withConsistentRead(this.db, () =>
|
|
10965
|
-
|
|
10966
|
-
|
|
10967
|
-
|
|
11953
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readCurrentRecovery(this.db)));
|
|
11954
|
+
}
|
|
11955
|
+
getPublicationRecoveryBarrier(excludeRecoveryId = null) {
|
|
11956
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readPublicationRecoveryBarrier(this.db, excludeRecoveryId)));
|
|
10968
11957
|
}
|
|
10969
11958
|
getLatestRecovery(targetRevision) {
|
|
10970
11959
|
return runRepositoryAction(() => withConsistentRead(this.db, () => {
|
|
@@ -11046,6 +12035,33 @@ class ConfigRepository {
|
|
|
11046
12035
|
return operation;
|
|
11047
12036
|
}));
|
|
11048
12037
|
}
|
|
12038
|
+
registerWorkerLaunch(identity, guard, allocation, updatedAt) {
|
|
12039
|
+
return runRepositoryAction(() => this.mutationTransaction(() => registerWorkerLaunch(this.db, identity, guard, allocation, updatedAt)));
|
|
12040
|
+
}
|
|
12041
|
+
fenceWorkerLaunchNotStarted(mutationId, workerSlot, attemptNo, updatedAt) {
|
|
12042
|
+
return runRepositoryAction(() => this.mutationTransaction(() => fenceWorkerLaunchNotStarted(this.db, mutationId, workerSlot, attemptNo, updatedAt)));
|
|
12043
|
+
}
|
|
12044
|
+
recordWorkerLaunchAdmitted(workerInstanceId, updatedAt) {
|
|
12045
|
+
return runRepositoryAction(() => this.mutationTransaction(() => recordWorkerLaunchAdmitted(this.db, workerInstanceId, updatedAt)));
|
|
12046
|
+
}
|
|
12047
|
+
recordWorkerLaunchExit(workerInstanceId, evidence, updatedAt) {
|
|
12048
|
+
return runRepositoryAction(() => this.mutationTransaction(() => recordWorkerLaunchExit(this.db, workerInstanceId, evidence, updatedAt)));
|
|
12049
|
+
}
|
|
12050
|
+
recordWorkerLaunchCapacityReclaimed(workerInstanceId, guard, updatedAt) {
|
|
12051
|
+
return runRepositoryAction(() => this.mutationTransaction(() => recordWorkerLaunchCapacityReclaimed(this.db, workerInstanceId, guard, updatedAt)));
|
|
12052
|
+
}
|
|
12053
|
+
getWorkerLaunch(workerInstanceId) {
|
|
12054
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readWorkerLaunch(this.db, workerInstanceId)));
|
|
12055
|
+
}
|
|
12056
|
+
getWorkerLaunchAllocationFacts(allocation) {
|
|
12057
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readWorkerLaunchAllocationFacts(this.db, allocation)));
|
|
12058
|
+
}
|
|
12059
|
+
getUnsettledWorkerLaunches() {
|
|
12060
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readUnsettledWorkerLaunches(this.db)));
|
|
12061
|
+
}
|
|
12062
|
+
getWorkerLaunchInventory() {
|
|
12063
|
+
return runRepositoryAction(() => withConsistentRead(this.db, () => readWorkerLaunchInventory(this.db)));
|
|
12064
|
+
}
|
|
11049
12065
|
recordWorkerResult(mutationId, workerSlot, result, updatedAt) {
|
|
11050
12066
|
return runRepositoryAction(() => this.publicationTransaction(mutationId, () => {
|
|
11051
12067
|
const worker = recordWorkerResult(this.db, mutationId, workerSlot, result, updatedAt);
|
|
@@ -11053,22 +12069,27 @@ class ConfigRepository {
|
|
|
11053
12069
|
}));
|
|
11054
12070
|
}
|
|
11055
12071
|
finalizePublication(mutationId, outcome, updatedAt) {
|
|
11056
|
-
return runRepositoryAction(() => this.
|
|
12072
|
+
return runRepositoryAction(() => this.mutationTransaction(() => {
|
|
11057
12073
|
const before = getOperation(this.db, mutationId);
|
|
11058
12074
|
if (before === null)
|
|
11059
12075
|
throw new ConfigRepositoryError("invalid_operation", "configuration operation was not found");
|
|
12076
|
+
if (before.state !== "converged" && before.state !== "degraded" && before.state !== "superseded") {
|
|
12077
|
+
this.requirePublicationOwner(mutationId);
|
|
12078
|
+
if (outcome.outcome === "degraded")
|
|
12079
|
+
assertPublicationLaunchDebtSettled(this.db, mutationId);
|
|
12080
|
+
}
|
|
11060
12081
|
const operation = finalizePublication(this.db, mutationId, outcome, updatedAt);
|
|
11061
|
-
if (before.state !== "converged" && before.state !== "degraded" && outcome.outcome === "degraded" && (outcome.error_code === "replacement_convergence_failed" || outcome.error_code === "control_readiness_failed")) {
|
|
12082
|
+
if (before.state !== "converged" && before.state !== "degraded" && before.state !== "superseded" && outcome.outcome === "degraded" && (outcome.error_code === "replacement_convergence_failed" || outcome.error_code === "control_readiness_failed")) {
|
|
11062
12083
|
switch (outcome.recovery_disposition) {
|
|
11063
12084
|
case "retryable":
|
|
11064
|
-
createAutomaticRecovery(this.db,
|
|
12085
|
+
createAutomaticRecovery(this.db, randomUUID4(), mutationId, operation.committed_revision, updatedAt);
|
|
11065
12086
|
this.options.faultInjection?.("after_automatic_recovery");
|
|
11066
12087
|
break;
|
|
11067
12088
|
case "deterministic_worker_rejection":
|
|
11068
12089
|
case "deterministic_protocol_failure":
|
|
11069
12090
|
case "deterministic_control_failure":
|
|
11070
12091
|
case "fatal":
|
|
11071
|
-
createStoppedRecovery(this.db,
|
|
12092
|
+
createStoppedRecovery(this.db, randomUUID4(), mutationId, operation.committed_revision, outcome.recovery_disposition === "fatal" ? "fatal_source_failure" : outcome.recovery_disposition, outcome.error_detail, updatedAt);
|
|
11072
12093
|
break;
|
|
11073
12094
|
default: {
|
|
11074
12095
|
const unhandled = outcome.recovery_disposition;
|
|
@@ -11154,10 +12175,19 @@ class ConfigRepository {
|
|
|
11154
12175
|
}
|
|
11155
12176
|
publicationTransaction(mutationId, action) {
|
|
11156
12177
|
return this.mutationTransaction(() => {
|
|
11157
|
-
|
|
11158
|
-
|
|
12178
|
+
if (mutationId !== null)
|
|
12179
|
+
this.requirePublicationOwner(mutationId);
|
|
11159
12180
|
const result = action();
|
|
11160
|
-
|
|
12181
|
+
if (mutationId !== null) {
|
|
12182
|
+
const operation = getOperation(this.db, mutationId);
|
|
12183
|
+
if (operation === null)
|
|
12184
|
+
throw new ConfigRepositoryError("repository_failure", "publication operation disappeared");
|
|
12185
|
+
if (operation.state === "committed" || operation.state === "publishing" || operation.state === "draining") {
|
|
12186
|
+
readActivePublication(this.db);
|
|
12187
|
+
}
|
|
12188
|
+
} else if (readPublicationOwner(this.db) !== null) {
|
|
12189
|
+
readActivePublication(this.db);
|
|
12190
|
+
}
|
|
11161
12191
|
return result;
|
|
11162
12192
|
});
|
|
11163
12193
|
}
|
|
@@ -11169,12 +12199,12 @@ class ConfigRepository {
|
|
|
11169
12199
|
return action();
|
|
11170
12200
|
}).immediate();
|
|
11171
12201
|
}
|
|
11172
|
-
|
|
11173
|
-
const
|
|
11174
|
-
if (
|
|
11175
|
-
throw new ConfigRepositoryError("invalid_operation", "only the
|
|
12202
|
+
requirePublicationOwner(mutationId) {
|
|
12203
|
+
const owner = readPublicationOwner(this.db);
|
|
12204
|
+
if (owner === null || owner.operation.mutation_id !== mutationId) {
|
|
12205
|
+
throw new ConfigRepositoryError("invalid_operation", "only the current publication owner may publish");
|
|
11176
12206
|
}
|
|
11177
|
-
|
|
12207
|
+
readActivePublication(this.db);
|
|
11178
12208
|
}
|
|
11179
12209
|
}
|
|
11180
12210
|
|
|
@@ -11188,15 +12218,32 @@ var STORAGE_METHODS = [
|
|
|
11188
12218
|
"getControlProjection",
|
|
11189
12219
|
"setManagementProviderOffline",
|
|
11190
12220
|
"commitPrepared",
|
|
12221
|
+
"applyPendingRequestLogsDefault",
|
|
11191
12222
|
"appendServingSnapshot",
|
|
11192
12223
|
"getServingSnapshot",
|
|
11193
12224
|
"claimController",
|
|
11194
12225
|
"getActivePublication",
|
|
12226
|
+
"claimPublicationTarget",
|
|
12227
|
+
"requestPublicationCancellation",
|
|
12228
|
+
"enterPublicationPrepare",
|
|
12229
|
+
"recordPublicationCandidateExit",
|
|
12230
|
+
"confirmPublicationCandidateExited",
|
|
12231
|
+
"getOutstandingPublicationCandidates",
|
|
12232
|
+
"registerWorkerLaunch",
|
|
12233
|
+
"fenceWorkerLaunchNotStarted",
|
|
12234
|
+
"recordWorkerLaunchAdmitted",
|
|
12235
|
+
"recordWorkerLaunchExit",
|
|
12236
|
+
"recordWorkerLaunchCapacityReclaimed",
|
|
12237
|
+
"getWorkerLaunch",
|
|
12238
|
+
"getWorkerLaunchAllocationFacts",
|
|
12239
|
+
"getUnsettledWorkerLaunches",
|
|
12240
|
+
"getWorkerLaunchInventory",
|
|
11195
12241
|
"getOperation",
|
|
11196
12242
|
"getOperationState",
|
|
11197
12243
|
"getCurrentOperationState",
|
|
11198
12244
|
"getRecovery",
|
|
11199
12245
|
"getCurrentRecovery",
|
|
12246
|
+
"getPublicationRecoveryBarrier",
|
|
11200
12247
|
"getLatestRecovery",
|
|
11201
12248
|
"createManualRecovery",
|
|
11202
12249
|
"claimRecoveryAttempt",
|
|
@@ -11234,11 +12281,17 @@ var READ_METHODS = new Set([
|
|
|
11234
12281
|
"getPublicationServingSet",
|
|
11235
12282
|
"getServingSnapshot",
|
|
11236
12283
|
"getActivePublication",
|
|
12284
|
+
"getOutstandingPublicationCandidates",
|
|
12285
|
+
"getWorkerLaunch",
|
|
12286
|
+
"getWorkerLaunchAllocationFacts",
|
|
12287
|
+
"getUnsettledWorkerLaunches",
|
|
12288
|
+
"getWorkerLaunchInventory",
|
|
11237
12289
|
"getOperation",
|
|
11238
12290
|
"getOperationState",
|
|
11239
12291
|
"getCurrentOperationState",
|
|
11240
12292
|
"getRecovery",
|
|
11241
12293
|
"getCurrentRecovery",
|
|
12294
|
+
"getPublicationRecoveryBarrier",
|
|
11242
12295
|
"getLatestRecovery",
|
|
11243
12296
|
"verify",
|
|
11244
12297
|
"getRetirementDescriptorCleanupState",
|