@sentropic/artifacts 0.2.26 → 0.2.28
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/CHANGELOG.md +33 -0
- package/dist/adapters/composite-blob.d.ts +35 -0
- package/dist/adapters/composite-blob.js +106 -0
- package/dist/adapters/db-blob.d.ts +14 -0
- package/dist/adapters/db-blob.js +79 -0
- package/dist/adapters/local-blob.js +33 -20
- package/dist/adapters/postgres-live.js +14 -3
- package/dist/adapters/postgres.js +2 -2
- package/dist/adapters/s3.js +54 -4
- package/dist/adapters/sqlite-blob.d.ts +13 -0
- package/dist/adapters/sqlite-blob.js +80 -0
- package/dist/adapters/sqlite-store.js +2 -1
- package/dist/adapters/sqlite.d.ts +7 -0
- package/dist/adapters/sqlite.js +27 -0
- package/dist/live-host/worker-client.d.ts +7 -1
- package/dist/live-host/worker-client.js +8 -1
- package/dist/mcp-core.d.ts +1 -1
- package/dist/mcp-core.js +1 -1
- package/dist/server/blob-bridge.d.ts +69 -0
- package/dist/server/blob-bridge.js +229 -0
- package/dist/server/gc.d.ts +4 -2
- package/dist/server/gc.js +35 -13
- package/dist/server/live-commit.js +3 -3
- package/dist/server/live-contracts.d.ts +40 -1
- package/dist/server/live-contracts.js +3 -0
- package/dist/server/live-invitation-state.d.ts +1 -1
- package/dist/server/live-mutations.js +3 -1
- package/dist/server/live-service.js +6 -5
- package/dist/server/live-store.d.ts +10 -0
- package/dist/server/live-store.js +28 -0
- package/dist/server/live-worker.d.ts +18 -4
- package/dist/server/live-worker.js +235 -40
- package/dist/server/preparation-cleanup.d.ts +2 -0
- package/dist/server/preparation-cleanup.js +1 -1
- package/dist/server/publication.d.ts +34 -2
- package/dist/server/publication.js +17 -4
- package/migrations/0014_db_blob_placement.sql +32 -0
- package/migrations/0014_live_drafts_pending.sql +7 -0
- package/package.json +13 -1
|
@@ -57,7 +57,9 @@ export async function mutateLive(input) {
|
|
|
57
57
|
action = 'project';
|
|
58
58
|
}
|
|
59
59
|
else {
|
|
60
|
-
|
|
60
|
+
// A start on a session that is still reviving joins it and dispatches the worker again (same session, same
|
|
61
|
+
// fences); only a session that is already LIVE refuses.
|
|
62
|
+
if (phase !== 'DORMANT' && phase !== 'REVIVING')
|
|
61
63
|
liveBusy('active_session');
|
|
62
64
|
action = 'project';
|
|
63
65
|
}
|
|
@@ -9,15 +9,16 @@ import { validateLiveMutation } from './live-tree.js';
|
|
|
9
9
|
import { readLivePage } from './live-read.js';
|
|
10
10
|
import { liveBusy, mutateLive } from './live-mutations.js';
|
|
11
11
|
import { executeLiveCommit } from './live-commit.js';
|
|
12
|
-
import { settleLiveWorker } from './live-worker.js';
|
|
13
|
-
import { liveResponse } from './live-contracts.js';
|
|
12
|
+
import { redriveLiveWorkers, settleLiveWorker } from './live-worker.js';
|
|
13
|
+
import { liveResponse, liveWritable } from './live-contracts.js';
|
|
14
14
|
import { executeLiveInvitation, LIVE_INVITATION_OPERATIONS } from './live-invitations.js';
|
|
15
15
|
import { liveInvitationViews } from './live-invitation-state.js';
|
|
16
16
|
export { LIVE_INVITATIONS_OPEN_MAX } from './live-invitations.js';
|
|
17
17
|
export { LIVE_INVITATION_TOOL_CLASSES } from '../git-tool-definitions.js';
|
|
18
18
|
export function createLiveService(deps) {
|
|
19
19
|
const now = deps.now ?? Date.now;
|
|
20
|
-
return { ...liveInvitationViews(deps),
|
|
20
|
+
return { ...liveInvitationViews(deps), redrive: (storageScopeId, limit) => redriveLiveWorkers(deps, storageScopeId, limit),
|
|
21
|
+
async execute(operation, raw, invocation) {
|
|
21
22
|
const args = structuredClone(raw);
|
|
22
23
|
if (LIVE_INVITATION_OPERATIONS.includes(operation)) {
|
|
23
24
|
if (!matchesSchema(args, GIT_TOOL_DEFINITIONS[`artifacts_${operation}`].inputSchema)) {
|
|
@@ -57,7 +58,7 @@ export function createLiveService(deps) {
|
|
|
57
58
|
throw new ArtifactOperationError('git_diverged');
|
|
58
59
|
if (binding.state === 'detached')
|
|
59
60
|
throw new ArtifactOperationError('git_not_attached');
|
|
60
|
-
if (binding.state
|
|
61
|
+
if (!liveWritable(binding.state))
|
|
61
62
|
liveBusy(binding.pendingJobId ? 'pending_publication' : 'invalid_phase');
|
|
62
63
|
if (binding.channel !== 'personal' || binding.personalPrincipalId !== invocation.actorId || binding.executor !== 'sandbox')
|
|
63
64
|
liveBusy('invalid_phase');
|
|
@@ -134,7 +135,7 @@ export function createLiveService(deps) {
|
|
|
134
135
|
!(operation === 'live_read' && current.invited && current.canReadCode) ||
|
|
135
136
|
(!stop && !current.canReadCode))
|
|
136
137
|
throw new ArtifactOperationError('access_denied');
|
|
137
|
-
if (writer && !stop && (!current.canWrite || !current.humanLinked || current.binding.state
|
|
138
|
+
if (writer && !stop && (!current.canWrite || !current.humanLinked || !liveWritable(current.binding.state)))
|
|
138
139
|
throw new ArtifactOperationError('access_denied');
|
|
139
140
|
if ((operation === 'live_write' || operation === 'live_control' && !stop) && !current.qualified)
|
|
140
141
|
throw new ArtifactOperationError('builder_unavailable');
|
|
@@ -5,6 +5,11 @@ export interface LiveIdentity {
|
|
|
5
5
|
}
|
|
6
6
|
/** A-LIVE Amendment 1: idle strictly after 900 s since the last qualifying access; there is no absolute lifetime. */
|
|
7
7
|
export declare const LIVE_IDLE_THRESHOLD_MS = 900000;
|
|
8
|
+
/** Upper bound of one redriveLiveWorkers pass: the 60 s host timer stays safe with the default pool. */
|
|
9
|
+
export declare const MAX_REDRIVE_LIMIT = 64;
|
|
10
|
+
/** Clamps a caller limit to [0, MAX_REDRIVE_LIMIT]: undefined stays the default, 0/negative/NaN select nothing,
|
|
11
|
+
* oversized values stop at the cap. Memory and Postgres share it so both adapters agree on every input. */
|
|
12
|
+
export declare const normalizeRedriveLimit: (limit?: unknown) => number;
|
|
8
13
|
export interface LiveOverlayEntry {
|
|
9
14
|
path: string;
|
|
10
15
|
text: string | null;
|
|
@@ -133,7 +138,12 @@ export interface LiveTransaction {
|
|
|
133
138
|
export interface LiveStore {
|
|
134
139
|
transaction<T>(identity: LiveIdentity, action: (tx: LiveTransaction) => Promise<T>): Promise<T>;
|
|
135
140
|
sessionIdentity(scope: string, artifactId: string, liveSessionId: string): Promise<LiveIdentity | undefined>;
|
|
141
|
+
/** Drafts of the scope whose runtime still waits for the worker (see liveWorkerPending), oldest access first.
|
|
142
|
+
* Absent when the adapter cannot list them: the host then has no durable re-drive. */
|
|
143
|
+
pending?(scope: string, limit?: number): Promise<LiveIdentity[]>;
|
|
136
144
|
}
|
|
145
|
+
/** A runtime waits for the worker while it revives, while a stop is not DORMANT yet, or while LIVE trails its draft. */
|
|
146
|
+
export declare function liveWorkerPending(record: Pick<LiveDraftRecord, 'revision' | 'runtime'> | undefined): 'project' | 'stop' | null;
|
|
137
147
|
export declare const liveIdentityKey: (identity: LiveIdentity) => string;
|
|
138
148
|
/** Atomic fake; the persisted representation contains encrypted objects and metadata only. */
|
|
139
149
|
export declare function createMemoryLiveStore(): LiveStore;
|
|
@@ -2,6 +2,27 @@ import { createKeyMutex } from './ports.js';
|
|
|
2
2
|
import { ArtifactOperationError } from './failures.js';
|
|
3
3
|
/** A-LIVE Amendment 1: idle strictly after 900 s since the last qualifying access; there is no absolute lifetime. */
|
|
4
4
|
export const LIVE_IDLE_THRESHOLD_MS = 900_000;
|
|
5
|
+
/** Upper bound of one redriveLiveWorkers pass: the 60 s host timer stays safe with the default pool. */
|
|
6
|
+
export const MAX_REDRIVE_LIMIT = 64;
|
|
7
|
+
/** Clamps a caller limit to [0, MAX_REDRIVE_LIMIT]: undefined stays the default, 0/negative/NaN select nothing,
|
|
8
|
+
* oversized values stop at the cap. Memory and Postgres share it so both adapters agree on every input. */
|
|
9
|
+
export const normalizeRedriveLimit = (limit) => {
|
|
10
|
+
if (limit === undefined)
|
|
11
|
+
return MAX_REDRIVE_LIMIT;
|
|
12
|
+
const n = Math.trunc(Number(limit));
|
|
13
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
14
|
+
return 0;
|
|
15
|
+
return Math.min(n, MAX_REDRIVE_LIMIT);
|
|
16
|
+
};
|
|
17
|
+
/** A runtime waits for the worker while it revives, while a stop is not DORMANT yet, or while LIVE trails its draft. */
|
|
18
|
+
export function liveWorkerPending(record) {
|
|
19
|
+
const runtime = record?.runtime;
|
|
20
|
+
if (!record || !runtime)
|
|
21
|
+
return null;
|
|
22
|
+
if (runtime.phase === 'QUIESCING' || runtime.phase === 'SAVING' || runtime.phase === 'DECOMMISSIONING')
|
|
23
|
+
return 'stop';
|
|
24
|
+
return runtime.phase === 'REVIVING' || (runtime.phase === 'LIVE' && runtime.appliedRevision !== record.revision) ? 'project' : null;
|
|
25
|
+
}
|
|
5
26
|
export const liveIdentityKey = (identity) => JSON.stringify([
|
|
6
27
|
identity.storageScopeId, identity.artifactId, identity.bindingGeneration
|
|
7
28
|
]);
|
|
@@ -49,6 +70,13 @@ export function createMemoryLiveStore() {
|
|
|
49
70
|
row.runtime?.liveSessionId === sessionId);
|
|
50
71
|
return record ? { storageScopeId: scope, artifactId, bindingGeneration: record.bindingGeneration } : undefined;
|
|
51
72
|
},
|
|
73
|
+
async pending(scope, limit) {
|
|
74
|
+
return [...records.values()].filter(row => row.storageScopeId === scope && liveWorkerPending(row))
|
|
75
|
+
.sort((a, b) => a.runtime.lastAccessAt.localeCompare(b.runtime.lastAccessAt) ||
|
|
76
|
+
a.artifactId.localeCompare(b.artifactId) || a.bindingGeneration - b.bindingGeneration)
|
|
77
|
+
.slice(0, normalizeRedriveLimit(limit))
|
|
78
|
+
.map(row => ({ storageScopeId: scope, artifactId: row.artifactId, bindingGeneration: row.bindingGeneration }));
|
|
79
|
+
},
|
|
52
80
|
transaction: (identity, action) => mutex.runSerialized('live-store', async () => {
|
|
53
81
|
const id = liveIdentityKey(identity);
|
|
54
82
|
const pendingObjects = new Map();
|
|
@@ -1,10 +1,24 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import type { LiveServiceDeps } from './live-contracts.js';
|
|
3
|
-
/**
|
|
1
|
+
import { type LiveIdentity } from './live-store.js';
|
|
2
|
+
import type { LiveRedriveItem, LiveServiceDeps, LiveWorkerOutcome } from './live-contracts.js';
|
|
3
|
+
/**
|
|
4
|
+
* Side effects follow durable intents. Failure leaves the accepted source recoverable and pending: the outcome is
|
|
5
|
+
* returned and reported to `deps.onWorkerEvent` (`failed` with the typed code, `pending` for a worker that is not
|
|
6
|
+
* ready yet), and `redriveLiveWorkers` settles the same intent again. Never throws.
|
|
7
|
+
*/
|
|
4
8
|
export declare function settleLiveWorker(input: {
|
|
5
9
|
deps: LiveServiceDeps;
|
|
6
10
|
identity: LiveIdentity;
|
|
7
11
|
action: 'project' | 'stop';
|
|
8
12
|
result: Record<string, any>;
|
|
9
13
|
now: number;
|
|
10
|
-
}): Promise<
|
|
14
|
+
}): Promise<LiveWorkerOutcome>;
|
|
15
|
+
/**
|
|
16
|
+
* Durable re-drive (host timer, at boot and at most every 60 s): settles again every runtime of the scope that still
|
|
17
|
+
* waits for the worker. A revive whose builder answered `ready: false`, a settle lost with its process and a stop the
|
|
18
|
+
* worker refused are all picked up here; the worker call is the same fenced, idempotent reconcile or stop.
|
|
19
|
+
* Bounded: at most `redriveConcurrency` (default 4) worker calls in flight, each abandoned after
|
|
20
|
+
* `redriveItemTimeoutMs` (default 35 s) with a `timeout` failure; an overlapping pass for the same scope yields
|
|
21
|
+
* no items. A terminal builder failure (`failure: { code, reason }`) moves the runtime to DORMANT with
|
|
22
|
+
* `code:reason` as stateDetail and is never re-driven. Never throws.
|
|
23
|
+
*/
|
|
24
|
+
export declare function redriveLiveWorkers(deps: LiveServiceDeps, storageScopeId: string, limit?: number): Promise<LiveRedriveItem[]>;
|
|
@@ -1,55 +1,250 @@
|
|
|
1
1
|
import { expireLiveDraft, persistLiveOverlay, readLiveOverlay } from './live-drafts.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { liveIdentityKey, liveWorkerPending, normalizeRedriveLimit } from './live-store.js';
|
|
3
|
+
const REDRIVE_CONCURRENCY_DEFAULT = 4;
|
|
4
|
+
const REDRIVE_CONCURRENCY_MAX = 8;
|
|
5
|
+
const REDRIVE_ITEM_TIMEOUT_MS_DEFAULT = 35_000;
|
|
6
|
+
const STOP_PHASES = ['QUIESCING', 'SAVING', 'DECOMMISSIONING'];
|
|
7
|
+
const LIVE_SETTLE_PHASES = ['REVIVING', 'LIVE'];
|
|
8
|
+
const codeOf = (error) => {
|
|
9
|
+
const record = error;
|
|
10
|
+
if (record) {
|
|
11
|
+
if (typeof record.kind === 'string' && record.kind)
|
|
12
|
+
return record.kind;
|
|
13
|
+
if (typeof record.code === 'string' && record.code)
|
|
14
|
+
return record.code;
|
|
15
|
+
if (typeof record.code === 'number')
|
|
16
|
+
return String(record.code);
|
|
17
|
+
if (typeof record.name === 'string' && record.name && record.name !== 'Error')
|
|
18
|
+
return record.name;
|
|
19
|
+
}
|
|
20
|
+
return 'unknown';
|
|
21
|
+
};
|
|
22
|
+
/** A host observer never changes the outcome of a settle. */
|
|
23
|
+
function report(deps, identity, action, outcome, code, reason) {
|
|
24
|
+
try {
|
|
25
|
+
deps.onWorkerEvent?.({ identity, action, outcome, ...(code ? { code } : {}), ...(reason ? { reason } : {}) });
|
|
26
|
+
}
|
|
27
|
+
catch { /* observer only */ }
|
|
28
|
+
}
|
|
29
|
+
const validFailure = (failure) => {
|
|
30
|
+
if (!failure || typeof failure !== 'object')
|
|
31
|
+
return null;
|
|
32
|
+
const { code, reason } = failure;
|
|
33
|
+
if (typeof code !== 'string' || !code)
|
|
34
|
+
return null;
|
|
35
|
+
return { code, reason: typeof reason === 'string' && reason ? reason : code };
|
|
36
|
+
};
|
|
37
|
+
/** One settle per identity at a time: a concurrent caller waits for the in-flight attempt instead of
|
|
38
|
+
* doubling the worker call, then runs its own fenced attempt. No parallel reconcile/stop per session. */
|
|
39
|
+
const settleLocks = new Map();
|
|
40
|
+
async function withSettleLock(key, run) {
|
|
41
|
+
while (settleLocks.has(key)) {
|
|
42
|
+
try {
|
|
43
|
+
await settleLocks.get(key);
|
|
44
|
+
}
|
|
45
|
+
catch { /* locks never reject */ }
|
|
46
|
+
}
|
|
47
|
+
let release;
|
|
48
|
+
const current = new Promise(resolve => { release = resolve; });
|
|
49
|
+
settleLocks.set(key, current);
|
|
50
|
+
try {
|
|
51
|
+
return await run();
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
if (settleLocks.get(key) === current)
|
|
55
|
+
settleLocks.delete(key);
|
|
56
|
+
release();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** One redrive pass per scope at a time: an overlapping timer tick yields no items instead of doubling the pool. */
|
|
60
|
+
const redriveInflight = new Set();
|
|
61
|
+
async function settleOnce(input) {
|
|
62
|
+
const { deps, identity, action, result } = input;
|
|
5
63
|
if (!deps.worker)
|
|
6
|
-
return;
|
|
64
|
+
return 'skipped';
|
|
7
65
|
try {
|
|
8
66
|
if (action === 'stop') {
|
|
9
67
|
const runtime = await deps.store.transaction(identity, async (tx) => tx.record?.runtime);
|
|
68
|
+
const expectedLease = typeof result.leaseEpoch === 'number'
|
|
69
|
+
? result.leaseEpoch : undefined;
|
|
10
70
|
if (!runtime || runtime.liveSessionId !== result.liveSessionId)
|
|
11
|
-
return;
|
|
71
|
+
return 'skipped';
|
|
72
|
+
if (!STOP_PHASES.includes(runtime.phase))
|
|
73
|
+
return 'skipped';
|
|
74
|
+
if (expectedLease !== undefined && runtime.leaseEpoch !== expectedLease)
|
|
75
|
+
return 'skipped';
|
|
12
76
|
await deps.worker.stop({ ...identity, liveSessionId: runtime.liveSessionId, leaseEpoch: runtime.leaseEpoch });
|
|
13
|
-
await deps.store.transaction(identity, async (tx) => {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
77
|
+
const moved = await deps.store.transaction(identity, async (tx) => {
|
|
78
|
+
const current = tx.record?.runtime;
|
|
79
|
+
if (!current || current.liveSessionId !== runtime.liveSessionId || current.leaseEpoch !== runtime.leaseEpoch ||
|
|
80
|
+
!STOP_PHASES.includes(current.phase))
|
|
81
|
+
return false;
|
|
82
|
+
current.phase = 'DORMANT';
|
|
83
|
+
current.appliedRevision = null;
|
|
84
|
+
result.state = 'DORMANT';
|
|
85
|
+
result.runtimeState = 'DORMANT';
|
|
86
|
+
result.appliedRevision = null;
|
|
87
|
+
return true;
|
|
88
|
+
});
|
|
89
|
+
return moved ? 'settled' : 'skipped';
|
|
90
|
+
}
|
|
91
|
+
const stillProject = await deps.store.transaction(identity, async (tx) => liveWorkerPending(tx.record) === 'project');
|
|
92
|
+
if (!stillProject)
|
|
93
|
+
return 'skipped';
|
|
94
|
+
const ack = await deps.worker.reconcile(identity);
|
|
95
|
+
if (!ack) {
|
|
96
|
+
report(deps, identity, action, 'pending');
|
|
97
|
+
return 'pending';
|
|
98
|
+
}
|
|
99
|
+
if (!ack.ready) {
|
|
100
|
+
const failure = validFailure(ack.failure);
|
|
101
|
+
if (failure) {
|
|
102
|
+
const moved = await deps.store.transaction(identity, async (tx) => {
|
|
103
|
+
const record = tx.record;
|
|
104
|
+
const runtime = record?.runtime;
|
|
105
|
+
if (!record || !runtime || ack.liveSessionId !== runtime.liveSessionId || ack.leaseEpoch !== runtime.leaseEpoch ||
|
|
106
|
+
ack.routeEpoch !== runtime.routeEpoch || ack.revision !== record.revision ||
|
|
107
|
+
!(runtime.phase === 'REVIVING' || (runtime.phase === 'LIVE' && runtime.appliedRevision !== record.revision)))
|
|
108
|
+
return false;
|
|
109
|
+
runtime.phase = 'DORMANT';
|
|
110
|
+
runtime.appliedRevision = null;
|
|
111
|
+
runtime.stateDetail = `${failure.code}:${failure.reason}`;
|
|
18
112
|
result.state = 'DORMANT';
|
|
19
113
|
result.runtimeState = 'DORMANT';
|
|
20
114
|
result.appliedRevision = null;
|
|
21
|
-
|
|
22
|
-
|
|
115
|
+
result.stateDetail = runtime.stateDetail;
|
|
116
|
+
return true;
|
|
117
|
+
}).catch(() => false);
|
|
118
|
+
if (!moved)
|
|
119
|
+
return 'skipped';
|
|
120
|
+
report(deps, identity, action, 'failed', failure.code, failure.reason);
|
|
121
|
+
return 'failed';
|
|
122
|
+
}
|
|
123
|
+
report(deps, identity, action, 'pending');
|
|
124
|
+
return 'pending';
|
|
23
125
|
}
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
|
|
126
|
+
const moved = await deps.store.transaction(identity, async (tx) => {
|
|
127
|
+
const record = tx.record;
|
|
128
|
+
const runtime = record?.runtime;
|
|
129
|
+
if (!record || !runtime || ack.liveSessionId !== runtime.liveSessionId || ack.leaseEpoch !== runtime.leaseEpoch ||
|
|
130
|
+
ack.routeEpoch !== runtime.routeEpoch || ack.revision !== record.revision || !LIVE_SETTLE_PHASES.includes(runtime.phase))
|
|
131
|
+
return false;
|
|
132
|
+
const at = (deps.now ?? Date.now)();
|
|
133
|
+
if (expireLiveDraft(tx, at))
|
|
134
|
+
return false;
|
|
135
|
+
if (runtime.renewOnReady && record.changedPaths) {
|
|
136
|
+
const overlay = await readLiveOverlay(tx, deps.keys);
|
|
137
|
+
const renewed = await persistLiveOverlay(tx, deps.keys, { identity, expectedRevision: record.revision,
|
|
138
|
+
baseHeadSha: record.baseHeadSha, baseTreeSha: record.baseTreeSha, liveTreeSha: record.liveTreeSha, overlay }, at, true, true);
|
|
139
|
+
// Source revision remains fenced to the worker ACK; reauthentication is handled by the vault.
|
|
140
|
+
result.draftExpiresAt = renewed.expiresAt;
|
|
141
|
+
}
|
|
142
|
+
runtime.renewOnReady = false;
|
|
143
|
+
runtime.appliedRevision = ack.revision;
|
|
144
|
+
runtime.phase = 'LIVE';
|
|
145
|
+
result.appliedRevision = ack.revision;
|
|
146
|
+
result.workerPending = false;
|
|
147
|
+
result.runtimeState = 'LIVE';
|
|
148
|
+
result.state = 'LIVE';
|
|
149
|
+
return true;
|
|
150
|
+
});
|
|
151
|
+
return moved ? 'settled' : 'skipped';
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
// The durable intent remains available to redriveLiveWorkers; the failure is reported, never silent.
|
|
155
|
+
report(deps, identity, action, 'failed', codeOf(error));
|
|
156
|
+
return 'failed';
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Side effects follow durable intents. Failure leaves the accepted source recoverable and pending: the outcome is
|
|
161
|
+
* returned and reported to `deps.onWorkerEvent` (`failed` with the typed code, `pending` for a worker that is not
|
|
162
|
+
* ready yet), and `redriveLiveWorkers` settles the same intent again. Never throws.
|
|
163
|
+
*/
|
|
164
|
+
export async function settleLiveWorker(input) {
|
|
165
|
+
if (!input.deps.worker)
|
|
166
|
+
return 'skipped';
|
|
167
|
+
return withSettleLock(liveIdentityKey(input.identity), () => settleOnce(input));
|
|
168
|
+
}
|
|
169
|
+
const normalizeConcurrency = (value) => {
|
|
170
|
+
const n = Math.trunc(Number(value));
|
|
171
|
+
if (!Number.isFinite(n))
|
|
172
|
+
return REDRIVE_CONCURRENCY_DEFAULT;
|
|
173
|
+
return Math.min(REDRIVE_CONCURRENCY_MAX, Math.max(1, n));
|
|
174
|
+
};
|
|
175
|
+
const normalizeItemTimeout = (value) => {
|
|
176
|
+
const n = Math.trunc(Number(value));
|
|
177
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
178
|
+
return REDRIVE_ITEM_TIMEOUT_MS_DEFAULT;
|
|
179
|
+
return Math.min(120_000, n);
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Durable re-drive (host timer, at boot and at most every 60 s): settles again every runtime of the scope that still
|
|
183
|
+
* waits for the worker. A revive whose builder answered `ready: false`, a settle lost with its process and a stop the
|
|
184
|
+
* worker refused are all picked up here; the worker call is the same fenced, idempotent reconcile or stop.
|
|
185
|
+
* Bounded: at most `redriveConcurrency` (default 4) worker calls in flight, each abandoned after
|
|
186
|
+
* `redriveItemTimeoutMs` (default 35 s) with a `timeout` failure; an overlapping pass for the same scope yields
|
|
187
|
+
* no items. A terminal builder failure (`failure: { code, reason }`) moves the runtime to DORMANT with
|
|
188
|
+
* `code:reason` as stateDetail and is never re-driven. Never throws.
|
|
189
|
+
*/
|
|
190
|
+
export async function redriveLiveWorkers(deps, storageScopeId, limit) {
|
|
191
|
+
if (!deps.worker || !deps.store.pending)
|
|
192
|
+
return [];
|
|
193
|
+
if (redriveInflight.has(storageScopeId))
|
|
194
|
+
return [];
|
|
195
|
+
redriveInflight.add(storageScopeId);
|
|
196
|
+
try {
|
|
197
|
+
const pending = await deps.store.pending(storageScopeId, normalizeRedriveLimit(limit));
|
|
198
|
+
if (!pending.length)
|
|
199
|
+
return [];
|
|
200
|
+
const concurrency = normalizeConcurrency(deps.redriveConcurrency);
|
|
201
|
+
const timeoutMs = normalizeItemTimeout(deps.redriveItemTimeoutMs);
|
|
202
|
+
const ordered = new Array(pending.length).fill(null);
|
|
203
|
+
let next = 0;
|
|
204
|
+
const runOne = async () => {
|
|
205
|
+
while (true) {
|
|
206
|
+
const index = next++;
|
|
207
|
+
if (index >= pending.length)
|
|
36
208
|
return;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
209
|
+
const identity = pending[index];
|
|
210
|
+
let waiting = null;
|
|
211
|
+
try {
|
|
212
|
+
waiting = await deps.store.transaction(identity, async (tx) => {
|
|
213
|
+
const action = liveWorkerPending(tx.record);
|
|
214
|
+
return action && tx.record.runtime
|
|
215
|
+
? { action, liveSessionId: tx.record.runtime.liveSessionId, leaseEpoch: tx.record.runtime.leaseEpoch } : null;
|
|
216
|
+
});
|
|
43
217
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
218
|
+
catch {
|
|
219
|
+
waiting = null;
|
|
220
|
+
}
|
|
221
|
+
if (!waiting)
|
|
222
|
+
continue;
|
|
223
|
+
let timer;
|
|
224
|
+
try {
|
|
225
|
+
const settle = settleLiveWorker({ deps, identity, action: waiting.action,
|
|
226
|
+
result: { liveSessionId: waiting.liveSessionId, leaseEpoch: waiting.leaseEpoch }, now: (deps.now ?? Date.now)() });
|
|
227
|
+
const late = new Promise(resolve => {
|
|
228
|
+
timer = setTimeout(() => {
|
|
229
|
+
report(deps, identity, waiting.action, 'failed', 'timeout');
|
|
230
|
+
resolve('failed');
|
|
231
|
+
}, timeoutMs);
|
|
232
|
+
});
|
|
233
|
+
ordered[index] = { ...identity, action: waiting.action, outcome: await Promise.race([settle, late]) };
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
ordered[index] = { ...identity, action: waiting.action, outcome: 'failed' };
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
if (timer)
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, pending.length) }, () => runOne()));
|
|
245
|
+
return ordered.filter((item) => item !== null);
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
redriveInflight.delete(storageScopeId);
|
|
53
249
|
}
|
|
54
|
-
catch { /* The durable intent remains available to the controller's fenced reconciliation. */ }
|
|
55
250
|
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type { PreparationIntentStore } from './object-intents.js';
|
|
2
2
|
import { type PublicationBlobStore } from './publication.js';
|
|
3
3
|
import type { DeletionClaimStore, RefcountStore } from './gc.js';
|
|
4
|
+
import type { FinalizeTxClient } from './commit/types.js';
|
|
4
5
|
export interface PreparationCleanupHost {
|
|
5
6
|
readonly intents: PreparationIntentStore;
|
|
6
7
|
readonly blobs: PublicationBlobStore;
|
|
7
8
|
readonly refs: RefcountStore;
|
|
8
9
|
/** PostgreSQL callers retain the transaction-scoped exclusion through DELETE. */
|
|
9
10
|
readonly claims: DeletionClaimStore;
|
|
11
|
+
readonly transaction?: FinalizeTxClient;
|
|
10
12
|
readonly cleanupBatchSize?: number;
|
|
11
13
|
}
|
|
12
14
|
export interface PreparationAttempt {
|
|
@@ -88,7 +88,7 @@ export async function scheduleBoundedPreparationCleanup(host, throughMs) {
|
|
|
88
88
|
await claims.claim(digest, `cleanup:${intent.intentId}`);
|
|
89
89
|
try {
|
|
90
90
|
if ((await host.blobs.listKeys(key)).includes(key))
|
|
91
|
-
await host.blobs.deleteBlob(key);
|
|
91
|
+
await host.blobs.deleteBlob(key, host.transaction);
|
|
92
92
|
}
|
|
93
93
|
finally {
|
|
94
94
|
await claims.releaseClaim(digest);
|
|
@@ -28,6 +28,24 @@ export interface PublicationStateStore {
|
|
|
28
28
|
getCurrentReleaseId(artifactId: string): Promise<string | undefined>;
|
|
29
29
|
compareAndSwapCurrent(artifactId: string, expected: string | null, next: string): Promise<boolean>;
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* CMF-S1 (CR-4) — bounded keyset page over a digest-addressed blob prefix.
|
|
33
|
+
* `startAfter` resumes after a full key (exclusive); absent starts at the
|
|
34
|
+
* prefix. Stores return at most `maxItems` keys (fewer under `maxEncodedBytes`
|
|
35
|
+
* only when the caller trims; see `cutBlobKeysByBudget`); `hasMore` is true
|
|
36
|
+
* when unreturned keys remain. Resume is by key, never by offset, so a
|
|
37
|
+
* trimmed page replays exactly (bounded re-read, no skip, no duplication).
|
|
38
|
+
* Enumerating the whole prefix still uses `listKeys` (GC/crash recovery).
|
|
39
|
+
*/
|
|
40
|
+
export interface BlobKeyPage {
|
|
41
|
+
readonly maxItems: number;
|
|
42
|
+
readonly maxEncodedBytes: number;
|
|
43
|
+
readonly startAfter?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface BlobKeyPageResult {
|
|
46
|
+
readonly keys: string[];
|
|
47
|
+
readonly hasMore: boolean;
|
|
48
|
+
}
|
|
31
49
|
export interface PublicationBlobStore {
|
|
32
50
|
putBlob(key: string, bytes: Uint8Array): Promise<void>;
|
|
33
51
|
getBlob(key: string): Promise<Uint8Array | undefined>;
|
|
@@ -38,8 +56,14 @@ export interface PublicationBlobStore {
|
|
|
38
56
|
getBlobRange?(key: string, start: number, endInclusive: number): Promise<Uint8Array | undefined>;
|
|
39
57
|
/** List keys under a prefix (orphan enumeration for crash recovery/GC). */
|
|
40
58
|
listKeys(prefix: string): Promise<string[]>;
|
|
59
|
+
/**
|
|
60
|
+
* CMF-S1 (CR-4): bounded keyset page. Optional: the bridge
|
|
61
|
+
* (`listBlobKeysPaged`) falls back to `listKeys` + in-memory slicing when
|
|
62
|
+
* absent. Every in-repo store implements it.
|
|
63
|
+
*/
|
|
64
|
+
listKeysPaged?(prefix: string, page: BlobKeyPage): Promise<BlobKeyPageResult>;
|
|
41
65
|
/** Delete a key (strict: unknown keys fail so callers notice). */
|
|
42
|
-
deleteBlob(key: string): Promise<void>;
|
|
66
|
+
deleteBlob(key: string, transaction?: import('./commit/types.js').FinalizeTxClient): Promise<void>;
|
|
43
67
|
}
|
|
44
68
|
/** Derive the `sha256:<hex>` digest from a digest-addressed blob key. */
|
|
45
69
|
export declare function blobDigestOfKey(key: string): string;
|
|
@@ -167,7 +191,7 @@ export interface PublicationUnitWriter {
|
|
|
167
191
|
}>;
|
|
168
192
|
putSource(artifactId: string, source: SourceRef): Promise<void>;
|
|
169
193
|
putRelease(release: ReleaseRecord): Promise<void>;
|
|
170
|
-
registerBlob(storageScopeId: string, digest: string, size: number): Promise<void>;
|
|
194
|
+
registerBlob(storageScopeId: string, digest: string, size: number, placement?: 'db' | 'object'): Promise<void>;
|
|
171
195
|
promoteCurrentLatestWins(artifactId: string, releaseId: string): Promise<void>;
|
|
172
196
|
addReleaseRef(digest: string, holder: string): Promise<void>;
|
|
173
197
|
completeIntent(intentId: string): Promise<void>;
|
|
@@ -204,6 +228,14 @@ export interface GuardedPublicationDeps {
|
|
|
204
228
|
readonly blobConcurrency?: number;
|
|
205
229
|
/** Per-publish blob-staging budget in ms; one shared deadline for every concurrent blob operation. */
|
|
206
230
|
readonly blobDeadlineMs?: number;
|
|
231
|
+
/**
|
|
232
|
+
* CMF-S2 — DB placement promotion. Decides, per staged blob size, whether
|
|
233
|
+
* the finalized `artifacts.blobs` row reads 'db' (bytes in `blob_bytes`)
|
|
234
|
+
* instead of the default 'object'. Absent = 'object' (current behavior).
|
|
235
|
+
* Promotion only; a publication never demotes a row (mode changes go
|
|
236
|
+
* through placement migration).
|
|
237
|
+
*/
|
|
238
|
+
readonly placementForSize?: (sizeBytes: number) => 'db' | 'object';
|
|
207
239
|
}
|
|
208
240
|
export interface GuardedPublicationService {
|
|
209
241
|
replayFinalized(input: Omit<GuardedPublishInput, 'files' | 'source' | 'profile'>): Promise<FinalizeResult | undefined>;
|
|
@@ -77,6 +77,18 @@ export function createMemoryBlobStore() {
|
|
|
77
77
|
assertBlobPrefix(prefix);
|
|
78
78
|
return [...blobs.keys()].filter((key) => key.startsWith(prefix)).sort();
|
|
79
79
|
},
|
|
80
|
+
async listKeysPaged(prefix, page) {
|
|
81
|
+
assertBlobPrefix(prefix);
|
|
82
|
+
const ordered = [...blobs.keys()].filter((key) => key.startsWith(prefix)).sort();
|
|
83
|
+
const start = page.startAfter === undefined ? 0 : (() => {
|
|
84
|
+
if (!page.startAfter.startsWith(prefix))
|
|
85
|
+
throw new Error(`invalid blob page resume key: ${page.startAfter}`);
|
|
86
|
+
const index = ordered.findIndex((key) => key > page.startAfter);
|
|
87
|
+
return index === -1 ? ordered.length : index;
|
|
88
|
+
})();
|
|
89
|
+
const keys = ordered.slice(start, start + page.maxItems);
|
|
90
|
+
return { keys, hasMore: start + page.maxItems < ordered.length };
|
|
91
|
+
},
|
|
80
92
|
deleteBlob(key) {
|
|
81
93
|
if (!blobs.has(key))
|
|
82
94
|
throw new Error(`unknown blob: ${key}`);
|
|
@@ -307,9 +319,9 @@ export function createPostgresPublicationUnitWriter(client) {
|
|
|
307
319
|
VALUES ($1, $2, $3, $4, 'ready', $5, $6, $7, $8)`, [release.releaseId, release.artifactId, release.manifestDigest, release.manifest, release.createdAt,
|
|
308
320
|
release.authorPrincipalId ?? null, release.parentReleaseId ?? null, release.revertedFromReleaseId ?? null]);
|
|
309
321
|
},
|
|
310
|
-
async registerBlob(storageScopeId, digest, size) {
|
|
311
|
-
await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size)
|
|
312
|
-
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [storageScopeId, digest, size]);
|
|
322
|
+
async registerBlob(storageScopeId, digest, size, placement = 'object') {
|
|
323
|
+
await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size, placement)
|
|
324
|
+
VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`, [storageScopeId, digest, size, placement]);
|
|
313
325
|
},
|
|
314
326
|
async promoteCurrentLatestWins(artifactId, releaseId) {
|
|
315
327
|
// CR-3 latest-wins: last committer wins the pointer, no loser conflict.
|
|
@@ -481,7 +493,8 @@ export function createGuardedPublicationService(deps) {
|
|
|
481
493
|
createdAt: new Date(nowMs).toISOString(),
|
|
482
494
|
});
|
|
483
495
|
for (const staged of prepared.entries) {
|
|
484
|
-
|
|
496
|
+
const placement = deps.placementForSize?.(staged.entry.size) ?? 'object';
|
|
497
|
+
await unit.registerBlob(input.storageScopeId, staged.entry.digest, staged.entry.size, placement);
|
|
485
498
|
await unit.addReleaseRef(staged.entry.digest, releaseId);
|
|
486
499
|
addedRefs.push(staged.entry.digest);
|
|
487
500
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
-- CMF-S2 — DB blob placement (additive, IF NOT EXISTS only).
|
|
2
|
+
--
|
|
3
|
+
-- `artifacts.blobs.placement` records where the bytes of a registered blob
|
|
4
|
+
-- live: 'object' (S3 placement, pre-0014 rows read as such) or 'db'
|
|
5
|
+
-- (`artifacts.blob_bytes`). `artifacts.blob_bytes` carries NO foreign key to
|
|
6
|
+
-- `artifacts.blobs`: preparation-phase `putBlob` runs before `registerBlob`
|
|
7
|
+
-- commits inside finalization, so prepared bytes must land without a parent
|
|
8
|
+
-- row; unreferenced prepared bytes stay protected by `artifacts.object_intents`
|
|
9
|
+
-- and collected by the lifecycle GC. `artifacts.upload_staging_bytes` is the
|
|
10
|
+
-- DB-mode staging buffer (`artifacts/<scope>/staging/<uploadId>`), swept by
|
|
11
|
+
-- TTL like the object-prefix staging sweeper.
|
|
12
|
+
ALTER TABLE artifacts.blobs
|
|
13
|
+
ADD COLUMN IF NOT EXISTS placement TEXT NOT NULL DEFAULT 'object'
|
|
14
|
+
CHECK (placement IN ('object', 'db'));
|
|
15
|
+
|
|
16
|
+
CREATE TABLE IF NOT EXISTS artifacts.blob_bytes (
|
|
17
|
+
storage_scope_id TEXT NOT NULL,
|
|
18
|
+
digest TEXT NOT NULL CHECK (digest ~ '^sha256:[0-9a-f]{64}$'),
|
|
19
|
+
bytes BYTEA NOT NULL,
|
|
20
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
21
|
+
PRIMARY KEY (storage_scope_id, digest)
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
CREATE TABLE IF NOT EXISTS artifacts.upload_staging_bytes (
|
|
25
|
+
storage_scope_id TEXT NOT NULL,
|
|
26
|
+
upload_id UUID NOT NULL,
|
|
27
|
+
bytes BYTEA NOT NULL,
|
|
28
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
29
|
+
PRIMARY KEY (storage_scope_id, upload_id)
|
|
30
|
+
);
|
|
31
|
+
CREATE INDEX IF NOT EXISTS upload_staging_bytes_by_updated
|
|
32
|
+
ON artifacts.upload_staging_bytes (updated_at);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
-- Live re-drive pending scan (package redriveLiveWorkers, host timer at boot and every <= 60 s).
|
|
2
|
+
-- The pending() query filters one storage scope on JSONB phase and orders by last access time; DORMANT
|
|
3
|
+
-- rows (the idle majority) stay out of this partial index so every tick scans pending rows only.
|
|
4
|
+
CREATE INDEX IF NOT EXISTS live_drafts_pending_idx ON artifacts.live_drafts
|
|
5
|
+
(storage_scope_id, (record #>> '{runtime,lastAccessAt}'), artifact_id, binding_generation)
|
|
6
|
+
WHERE (record #>> '{runtime,phase}' IN ('REVIVING','QUIESCING','SAVING','DECOMMISSIONING')
|
|
7
|
+
OR (record #>> '{runtime,phase}' = 'LIVE'));
|