@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
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.28
|
|
4
|
+
|
|
5
|
+
- Add DB blob placement: migration `0014_db_blob_placement.sql` (`placement`, `blob_bytes`,
|
|
6
|
+
`upload_staging_bytes`), `db-blob` and `composite-blob` adapters with advisory digest-lock
|
|
7
|
+
coordination, and placement-aware publication writes with keyset-paged blob enumeration.
|
|
8
|
+
- Harden the blob bridge: create-only verified S3/local puts, bounded pages with sealed
|
|
9
|
+
keyset cursors, and store-level `listKeysPaged` delegation.
|
|
10
|
+
- Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
|
|
11
|
+
|
|
12
|
+
## 0.2.27
|
|
13
|
+
|
|
14
|
+
- Wire the builder terminal failure through the live package: a `reconcile` answer with
|
|
15
|
+
`ready: false` and `failure: { code, reason }` moves the runtime to DORMANT with
|
|
16
|
+
`code:reason` as `stateDetail`, reports `onWorkerEvent` (`failed` with the code and reason),
|
|
17
|
+
and is never re-driven; a later owner `start` or edit revives normally. The live-host
|
|
18
|
+
`LiveBridgeAck` parser preserves a well-formed `failure` and ignores malformed shapes.
|
|
19
|
+
A total `stop` (builder holds no or no longer this session) converges instead of replaying
|
|
20
|
+
a refusal.
|
|
21
|
+
- Fence concurrent live settles: one settle per identity at a time (no parallel
|
|
22
|
+
`reconcile`/`stop` for the same session), a stop requires its session plus a
|
|
23
|
+
`QUIESCING`/`SAVING`/`DECOMMISSIONING` phase and lease match before any worker call, and a
|
|
24
|
+
settle that did not move the runtime reports `skipped` instead of `settled`. A `void`
|
|
25
|
+
reconcile answer reports `pending` with an event instead of going silent.
|
|
26
|
+
- Bound the re-drive: `pending` limits clamp to `[0, 64]` identically on memory and Postgres,
|
|
27
|
+
ordering is deterministic (`lastAccessAt`, `artifact_id`, `binding_generation`), and
|
|
28
|
+
`redriveLiveWorkers` runs at most 4 items in flight (tunable via
|
|
29
|
+
`redriveConcurrency`) with a 35 s per-item budget (tunable via `redriveItemTimeoutMs`,
|
|
30
|
+
`timeout` failure on expiry) and skips an overlapping pass for the same scope.
|
|
31
|
+
- Add partial index migration `0014_live_drafts_pending.sql` so the scoped pending scan reads
|
|
32
|
+
pending rows only; DORMANT rows stay out of the index.
|
|
33
|
+
- `codeOf` also reads `error.code`/`error.name` instead of `unknown` for standard errors.
|
|
34
|
+
- Stays in `0.2.x` (cluster-mesh peer `>=0.2.0 <0.3.0`).
|
|
35
|
+
|
|
3
36
|
## 0.2.25
|
|
4
37
|
|
|
5
38
|
- `@sentropic/artifacts/live-host` ships a generic pending-build reconcile: `reconcilePendingBuilds`
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CMF-S2 — composite `db+s3` blob adapter.
|
|
3
|
+
*
|
|
4
|
+
* Routes new `putBlob` keys by mode and size (`db`: DB, `s3`: object,
|
|
5
|
+
* `db+s3`: DB at or below the inline threshold, object above), preserves
|
|
6
|
+
* registered placement on rewrites, and resolves reads
|
|
7
|
+
* through the registered `artifacts.blobs.placement` (probing DB then object
|
|
8
|
+
* for prepared-but-unfinalized blobs), and coordinates `deleteBlob` across
|
|
9
|
+
* both sides under the caller's digest lock so neither an orphan DB row nor
|
|
10
|
+
* an orphan object survives GC. Enumeration is the ordered union; bounded
|
|
11
|
+
* pages merge both sides by keyset resume under one sealed continuation
|
|
12
|
+
* (`listKeysPaged`, CR-4) so no side is ever bulk-loaded.
|
|
13
|
+
*/
|
|
14
|
+
import type { PublicationBlobStore } from '../server/publication.js';
|
|
15
|
+
import type { FinalizeTxClient } from '../server/commit/types.js';
|
|
16
|
+
export type CompositeBlobMode = 'db' | 's3' | 'db+s3';
|
|
17
|
+
export type RegisteredBlobPlacement = 'db' | 'object';
|
|
18
|
+
export interface CompositeBlobPlacements {
|
|
19
|
+
/** Registered placement of a finalized blob; undefined before finalization. */
|
|
20
|
+
getPlacement(key: string): Promise<RegisteredBlobPlacement | undefined>;
|
|
21
|
+
}
|
|
22
|
+
export interface CompositeBlobOptions {
|
|
23
|
+
readonly db: PublicationBlobStore;
|
|
24
|
+
readonly s3: PublicationBlobStore;
|
|
25
|
+
readonly mode: CompositeBlobMode;
|
|
26
|
+
/** `db+s3` only: blobs at or below this byte size land in the DB. */
|
|
27
|
+
readonly inlineMaxBytes: number;
|
|
28
|
+
readonly placements: CompositeBlobPlacements;
|
|
29
|
+
/** Runs work under the digest lock shared with GC; direct when absent. */
|
|
30
|
+
readonly withDigestLock?: (digest: string, work: () => Promise<void>, transaction?: FinalizeTxClient) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/** Pure routing decision, shared with the publication promotion path. */
|
|
33
|
+
export declare function placementForPut(mode: CompositeBlobMode, sizeBytes: number, inlineMaxBytes: number): RegisteredBlobPlacement;
|
|
34
|
+
/** Create the composite blob store (no env reads, no connections). */
|
|
35
|
+
export declare function createCompositeBlobStore(options: CompositeBlobOptions): PublicationBlobStore;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
function digestOfKey(key) {
|
|
2
|
+
const hex = key.split('/').pop() ?? '';
|
|
3
|
+
if (!/^[0-9a-f]{64}$/.test(hex))
|
|
4
|
+
throw new Error(`invalid blob key: ${key}`);
|
|
5
|
+
return `sha256:${hex}`;
|
|
6
|
+
}
|
|
7
|
+
/** Pure routing decision, shared with the publication promotion path. */
|
|
8
|
+
export function placementForPut(mode, sizeBytes, inlineMaxBytes) {
|
|
9
|
+
if (mode === 'db')
|
|
10
|
+
return 'db';
|
|
11
|
+
if (mode === 's3')
|
|
12
|
+
return 'object';
|
|
13
|
+
if (!Number.isSafeInteger(inlineMaxBytes) || inlineMaxBytes < 1)
|
|
14
|
+
throw new Error('invalid inline max bytes');
|
|
15
|
+
return sizeBytes <= inlineMaxBytes ? 'db' : 'object';
|
|
16
|
+
}
|
|
17
|
+
/** Create the composite blob store (no env reads, no connections). */
|
|
18
|
+
export function createCompositeBlobStore(options) {
|
|
19
|
+
const { db, s3, mode, inlineMaxBytes, placements } = options;
|
|
20
|
+
if (mode !== 'db' && mode !== 's3' && mode !== 'db+s3')
|
|
21
|
+
throw new Error(`invalid blob placement mode: ${mode}`);
|
|
22
|
+
const lock = options.withDigestLock ?? (async (_digest, work) => { await work(); });
|
|
23
|
+
return {
|
|
24
|
+
async putBlob(key, bytes) {
|
|
25
|
+
// Registration survives collection; retries must restore its readable side.
|
|
26
|
+
const placement = await placements.getPlacement(key) ?? placementForPut(mode, bytes.byteLength, inlineMaxBytes);
|
|
27
|
+
const target = placement === 'db' ? db : s3;
|
|
28
|
+
await target.putBlob(key, bytes);
|
|
29
|
+
},
|
|
30
|
+
async getBlob(key) {
|
|
31
|
+
const placement = await placements.getPlacement(key);
|
|
32
|
+
if (placement === 'db')
|
|
33
|
+
return db.getBlob(key);
|
|
34
|
+
if (placement === 'object')
|
|
35
|
+
return s3.getBlob(key);
|
|
36
|
+
return (await db.getBlob(key)) ?? s3.getBlob(key);
|
|
37
|
+
},
|
|
38
|
+
async getBlobRange(key, start, endInclusive) {
|
|
39
|
+
const placement = await placements.getPlacement(key);
|
|
40
|
+
if (placement === 'db')
|
|
41
|
+
return db.getBlobRange?.(key, start, endInclusive);
|
|
42
|
+
if (placement === 'object')
|
|
43
|
+
return s3.getBlobRange?.(key, start, endInclusive);
|
|
44
|
+
return (await db.getBlobRange?.(key, start, endInclusive)) ??
|
|
45
|
+
s3.getBlobRange?.(key, start, endInclusive);
|
|
46
|
+
},
|
|
47
|
+
async listKeys(prefix) {
|
|
48
|
+
const [fromDb, fromS3] = await Promise.all([db.listKeys(prefix), s3.listKeys(prefix)]);
|
|
49
|
+
return [...new Set([...fromDb, ...fromS3])].sort();
|
|
50
|
+
},
|
|
51
|
+
async listKeysPaged(prefix, page) {
|
|
52
|
+
// Ordered union over one shared keyset resume: both sides fetch their
|
|
53
|
+
// first `maxItems` keys after the same resume key, which always covers
|
|
54
|
+
// the union's first `maxItems` keys (a union member ranks no higher in
|
|
55
|
+
// its own side than in the union). Bounded per side, no bulk load; the
|
|
56
|
+
// bridge applies the byte budget and seals the single resume key.
|
|
57
|
+
if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
|
|
58
|
+
throw new Error('invalid blob page maxItems');
|
|
59
|
+
const sides = [db, s3];
|
|
60
|
+
const fetched = await Promise.all(sides.map(async (side) => {
|
|
61
|
+
const input = page.startAfter === undefined
|
|
62
|
+
? { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes }
|
|
63
|
+
: { maxItems: page.maxItems, maxEncodedBytes: page.maxEncodedBytes, startAfter: page.startAfter };
|
|
64
|
+
if (side.listKeysPaged !== undefined)
|
|
65
|
+
return side.listKeysPaged(prefix, input);
|
|
66
|
+
const all = (await side.listKeys(prefix)).filter((key) => key.startsWith(prefix)).sort();
|
|
67
|
+
const start = page.startAfter === undefined ? 0 : (() => {
|
|
68
|
+
const index = all.findIndex((key) => key > page.startAfter);
|
|
69
|
+
return index === -1 ? all.length : index;
|
|
70
|
+
})();
|
|
71
|
+
const keys = all.slice(start, start + page.maxItems);
|
|
72
|
+
return { keys, hasMore: start + page.maxItems < all.length };
|
|
73
|
+
}));
|
|
74
|
+
const seen = new Set();
|
|
75
|
+
for (const result of fetched) {
|
|
76
|
+
for (const key of result.keys)
|
|
77
|
+
seen.add(key);
|
|
78
|
+
}
|
|
79
|
+
const union = [...seen].sort();
|
|
80
|
+
const keys = union.slice(0, page.maxItems);
|
|
81
|
+
const hasMore = fetched.some((result) => result.hasMore) || union.length > page.maxItems;
|
|
82
|
+
return { keys, hasMore };
|
|
83
|
+
},
|
|
84
|
+
async deleteBlob(key, transaction) {
|
|
85
|
+
await lock(digestOfKey(key), async () => {
|
|
86
|
+
// Deferred per side: a synchronously-throwing store (unknown key)
|
|
87
|
+
// must settle as a rejection inside allSettled, never escape during
|
|
88
|
+
// argument evaluation and leave the other side floating unawaited.
|
|
89
|
+
const attempt = async (side) => {
|
|
90
|
+
await side.deleteBlob(key);
|
|
91
|
+
};
|
|
92
|
+
const outcomes = await Promise.allSettled([attempt(db), attempt(s3)]);
|
|
93
|
+
for (const outcome of outcomes) {
|
|
94
|
+
if (outcome.status === 'rejected' &&
|
|
95
|
+
!(outcome.reason instanceof Error && outcome.reason.message === `unknown blob: ${key}`) &&
|
|
96
|
+
outcome.reason?.name !== 'NoSuchKey' && outcome.reason?.name !== 'NotFound') {
|
|
97
|
+
throw outcome.reason;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (outcomes.every((outcome) => outcome.status === 'rejected')) {
|
|
101
|
+
throw outcomes[0].reason;
|
|
102
|
+
}
|
|
103
|
+
}, transaction);
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CMF-S2 — Postgres DB blob placement (`artifacts.blob_bytes`).
|
|
3
|
+
*
|
|
4
|
+
* DB-mode `ArtifactBlobPort`: digest-addressed blobs in the `blob_bytes`
|
|
5
|
+
* table (no FK to `artifacts.blobs`, so preparation-phase puts succeed before
|
|
6
|
+
* `registerBlob`). Create-only (`ON CONFLICT DO NOTHING`) + read-back
|
|
7
|
+
* verification: identical retries are idempotent, different bytes fail closed
|
|
8
|
+
* without overwriting. The runtime role holds SELECT + INSERT only; DELETE
|
|
9
|
+
* belongs to the lifecycle maintenance role (CR-5).
|
|
10
|
+
*/
|
|
11
|
+
import type { Pool } from 'pg';
|
|
12
|
+
import type { PublicationBlobStore } from '../server/publication.js';
|
|
13
|
+
/** Create a DB-backed blob store over an injected pg pool (no env reads). */
|
|
14
|
+
export declare function createPostgresDbBlobStore(pool: Pool): PublicationBlobStore;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { assertBlobPrefix } from '../server/blob-prefix.js';
|
|
2
|
+
import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
|
|
3
|
+
/** Per-call fetch cap: one page never materializes more than this. */
|
|
4
|
+
const PAGE_FETCH_CAP = 1000;
|
|
5
|
+
const BLOB_KEY_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\/([0-9a-f]{64})$/;
|
|
6
|
+
const SCOPE_PREFIX_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\//;
|
|
7
|
+
function splitKey(key) {
|
|
8
|
+
const match = BLOB_KEY_PATTERN.exec(key);
|
|
9
|
+
if (!match)
|
|
10
|
+
throw new Error(`invalid blob key: ${key}`);
|
|
11
|
+
return { scope: match[1], digest: `sha256:${match[2]}` };
|
|
12
|
+
}
|
|
13
|
+
/** Create a DB-backed blob store over an injected pg pool (no env reads). */
|
|
14
|
+
export function createPostgresDbBlobStore(pool) {
|
|
15
|
+
return {
|
|
16
|
+
async putBlob(key, bytes) {
|
|
17
|
+
const snapshot = cloneBlobBytes(bytes);
|
|
18
|
+
verifyBytesForKey(key, snapshot);
|
|
19
|
+
const { scope, digest } = splitKey(key);
|
|
20
|
+
await pool.query(`INSERT INTO artifacts.blob_bytes (storage_scope_id, digest, bytes) VALUES ($1, $2, $3)
|
|
21
|
+
ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scope, digest, Buffer.from(snapshot)]);
|
|
22
|
+
const stored = await this.getBlob(key);
|
|
23
|
+
if (stored === undefined)
|
|
24
|
+
throw new Error(`blob missing after write: ${key}`);
|
|
25
|
+
},
|
|
26
|
+
async getBlob(key) {
|
|
27
|
+
const { scope, digest } = splitKey(key);
|
|
28
|
+
const { rows } = await pool.query('SELECT bytes FROM artifacts.blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
|
|
29
|
+
if (rows[0] === undefined)
|
|
30
|
+
return undefined;
|
|
31
|
+
return verifyStoredBytesForKey(key, new Uint8Array(rows[0].bytes));
|
|
32
|
+
},
|
|
33
|
+
async getBlobRange(key, start, endInclusive) {
|
|
34
|
+
const stored = await this.getBlob(key);
|
|
35
|
+
if (stored === undefined || !Number.isSafeInteger(start) || !Number.isSafeInteger(endInclusive) ||
|
|
36
|
+
start < 0 || endInclusive < start)
|
|
37
|
+
return undefined;
|
|
38
|
+
return stored.slice(start, Math.min(endInclusive + 1, stored.length));
|
|
39
|
+
},
|
|
40
|
+
async listKeys(prefix) {
|
|
41
|
+
assertBlobPrefix(prefix);
|
|
42
|
+
const match = SCOPE_PREFIX_PATTERN.exec(prefix);
|
|
43
|
+
if (!match)
|
|
44
|
+
throw new Error(`blob listing requires a scope prefix: ${prefix}`);
|
|
45
|
+
const { rows } = await pool.query('SELECT digest FROM artifacts.blob_bytes WHERE storage_scope_id = $1 ORDER BY digest', [match[1]]);
|
|
46
|
+
return rows
|
|
47
|
+
.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
|
|
48
|
+
.filter((key) => key.startsWith(prefix))
|
|
49
|
+
.sort();
|
|
50
|
+
},
|
|
51
|
+
async deleteBlob(key) {
|
|
52
|
+
const { scope, digest } = splitKey(key);
|
|
53
|
+
const result = await pool.query('DELETE FROM artifacts.blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
|
|
54
|
+
if (result.rowCount === 0)
|
|
55
|
+
throw new Error(`unknown blob: ${key}`);
|
|
56
|
+
},
|
|
57
|
+
async listKeysPaged(prefix, page) {
|
|
58
|
+
assertBlobPrefix(prefix);
|
|
59
|
+
const match = SCOPE_PREFIX_PATTERN.exec(prefix);
|
|
60
|
+
if (!match)
|
|
61
|
+
throw new Error(`blob listing requires a scope prefix: ${prefix}`);
|
|
62
|
+
if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
|
|
63
|
+
throw new Error('invalid blob page maxItems');
|
|
64
|
+
const after = page.startAfter === undefined ? undefined : (() => {
|
|
65
|
+
if (!page.startAfter.startsWith(prefix))
|
|
66
|
+
throw new Error(`invalid blob page resume key: ${page.startAfter}`);
|
|
67
|
+
return splitKey(page.startAfter).digest;
|
|
68
|
+
})();
|
|
69
|
+
const limit = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
|
|
70
|
+
const { rows } = await pool.query(`SELECT digest FROM artifacts.blob_bytes WHERE storage_scope_id = $1
|
|
71
|
+
AND substr(digest, 1, length($2::text)) = $2
|
|
72
|
+
AND ($3::text IS NULL OR digest > $3) ORDER BY digest LIMIT $4`, [match[1], `sha256:${prefix.slice(match[0].length)}`, after ?? null, limit]);
|
|
73
|
+
const keys = rows.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
|
|
74
|
+
.filter((key) => key.startsWith(prefix))
|
|
75
|
+
.sort();
|
|
76
|
+
return { keys: keys.slice(0, page.maxItems), hasMore: rows.length === limit };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -7,11 +7,10 @@
|
|
|
7
7
|
* read-back, atomic temp-file+rename writes, and strict deletes (unknown keys
|
|
8
8
|
* fail so callers notice, per the port contract).
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
11
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
12
11
|
import { dirname, join } from 'node:path';
|
|
13
|
-
import { blobDigestOfKey } from '../server/publication.js';
|
|
14
12
|
import { assertBlobPrefix } from '../server/blob-prefix.js';
|
|
13
|
+
import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
|
|
15
14
|
const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
|
|
16
15
|
/** Reject anything but digest-addressed blob keys, before any I/O. */
|
|
17
16
|
function assertBlobKey(key) {
|
|
@@ -19,8 +18,8 @@ function assertBlobKey(key) {
|
|
|
19
18
|
throw new Error(`invalid blob key (must be artifacts/<scope>/blobs/sha256/<hex>): ${key}`);
|
|
20
19
|
}
|
|
21
20
|
}
|
|
22
|
-
function
|
|
23
|
-
return
|
|
21
|
+
function readVerified(key, target) {
|
|
22
|
+
return verifyStoredBytesForKey(key, new Uint8Array(readFileSync(target)));
|
|
24
23
|
}
|
|
25
24
|
/** Create a filesystem-backed blob store rooted at `root` (created on demand). */
|
|
26
25
|
export function createLocalBlobStore(root) {
|
|
@@ -40,30 +39,44 @@ export function createLocalBlobStore(root) {
|
|
|
40
39
|
};
|
|
41
40
|
return {
|
|
42
41
|
async putBlob(key, bytes) {
|
|
43
|
-
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
if (actual !== expected) {
|
|
47
|
-
throw new Error(`digest mismatch for blob key ${key}: content sha256:${actual}`);
|
|
48
|
-
}
|
|
42
|
+
// CR-1: clone before verification, then verify before any I/O.
|
|
43
|
+
const snapshot = cloneBlobBytes(bytes);
|
|
44
|
+
verifyBytesForKey(key, snapshot);
|
|
49
45
|
const target = pathOf(key);
|
|
46
|
+
if (existsSync(target)) {
|
|
47
|
+
// Create-only: digest-verified read proves the stored bytes name the
|
|
48
|
+
// key, hence equal the snapshot barring SHA-256 collision.
|
|
49
|
+
readVerified(key, target);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
50
52
|
mkdirSync(dirname(target), { recursive: true });
|
|
51
53
|
const temp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
52
|
-
writeFileSync(temp,
|
|
53
|
-
|
|
54
|
+
writeFileSync(temp, snapshot, { flag: 'wx' });
|
|
55
|
+
try {
|
|
56
|
+
// Atomic create-only: link fails with EEXIST instead of overwriting.
|
|
57
|
+
linkSync(temp, target);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error.code === 'EEXIST') {
|
|
61
|
+
readVerified(key, target);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
try {
|
|
68
|
+
unlinkSync(temp);
|
|
69
|
+
}
|
|
70
|
+
catch { /* already linked or never created */ }
|
|
71
|
+
}
|
|
54
72
|
},
|
|
55
73
|
async getBlob(key) {
|
|
56
74
|
assertBlobKey(key);
|
|
57
75
|
const target = pathOf(key);
|
|
58
76
|
if (!existsSync(target))
|
|
59
77
|
return undefined;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const actual = sha256Hex(bytes);
|
|
63
|
-
if (actual !== expected) {
|
|
64
|
-
throw new Error(`digest mismatch on read for blob key ${key}: stored sha256:${actual}`);
|
|
65
|
-
}
|
|
66
|
-
return bytes;
|
|
78
|
+
// CR-2: digest verified before serving bytes as verified.
|
|
79
|
+
return readVerified(key, target);
|
|
67
80
|
},
|
|
68
81
|
async listKeys(prefix) {
|
|
69
82
|
assertBlobPrefix(prefix);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ArtifactOperationError } from '../server/failures.js';
|
|
2
|
-
import { liveIdentityKey } from '../server/live-store.js';
|
|
2
|
+
import { liveIdentityKey, normalizeRedriveLimit } from '../server/live-store.js';
|
|
3
3
|
const INVITATION_COLUMNS = `storage_scope_id,artifact_id,binding_generation,live_session_id,invitation_id,principal_id,
|
|
4
4
|
created_by,status,epoch,expires_at,accepted_at,revoked_at,created_at,row_version`;
|
|
5
5
|
const iso = (value) => value === null ? null : new Date(value).toISOString();
|
|
@@ -48,6 +48,16 @@ export function createPostgresLiveStore(pool) {
|
|
|
48
48
|
WHERE storage_scope_id=$1 AND artifact_id=$2 AND record #>> '{runtime,liveSessionId}'=$3`, [scope, artifactId, sessionId]);
|
|
49
49
|
return result.rows[0] ? { storageScopeId: scope, artifactId, bindingGeneration: Number(result.rows[0].binding_generation) } : undefined;
|
|
50
50
|
},
|
|
51
|
+
async pending(scope, limit) {
|
|
52
|
+
// Partial index 0014_live_drafts_pending.sql covers the scope filter and the access-time order;
|
|
53
|
+
// DORMANT rows stay out of the index so every host tick scans pending rows only.
|
|
54
|
+
const result = await pool.query(`SELECT artifact_id, binding_generation FROM artifacts.live_drafts
|
|
55
|
+
WHERE storage_scope_id=$1 AND (record #>> '{runtime,phase}' IN ('REVIVING','QUIESCING','SAVING','DECOMMISSIONING')
|
|
56
|
+
OR (record #>> '{runtime,phase}' = 'LIVE' AND record #>> '{runtime,appliedRevision}' IS DISTINCT FROM record ->> 'revision'))
|
|
57
|
+
ORDER BY record #>> '{runtime,lastAccessAt}', artifact_id, binding_generation LIMIT $2`, [scope, normalizeRedriveLimit(limit)]);
|
|
58
|
+
return result.rows.map(row => ({ storageScopeId: scope, artifactId: String(row.artifact_id),
|
|
59
|
+
bindingGeneration: Number(row.binding_generation) }));
|
|
60
|
+
},
|
|
51
61
|
async transaction(identity, action) {
|
|
52
62
|
const client = await pool.connect();
|
|
53
63
|
const values = [identity.storageScopeId, identity.artifactId, identity.bindingGeneration];
|
|
@@ -99,10 +109,11 @@ export function createPostgresLiveStore(pool) {
|
|
|
99
109
|
(storage_scope_id,actor_id,artifact_id,invocation_id,created_at) VALUES ($1,$2,$3,$4,$5)`, [identity.storageScopeId, actor, identity.artifactId, invocation, now]);
|
|
100
110
|
},
|
|
101
111
|
async advanceBinding(input) {
|
|
112
|
+
// The state is kept: a commit on a build_failed binding leaves it build_failed until the next publish.
|
|
102
113
|
const result = await client.query(`UPDATE artifacts.git_bindings SET head_commit_sha=$4,
|
|
103
|
-
|
|
114
|
+
version=version+1, updated_at=$5
|
|
104
115
|
WHERE storage_scope_id=$1 AND artifact_id=$2 AND generation=$3 AND head_commit_sha=$6
|
|
105
|
-
AND state
|
|
116
|
+
AND state IN ('attached','build_failed') RETURNING artifact_id`, [...values, input.commitSha, input.now, input.expectedHeadSha]);
|
|
106
117
|
if (!result.rows.length)
|
|
107
118
|
throw new ArtifactOperationError('git_live_conflict', { publicDetails: { reason: 'stale_fence' } });
|
|
108
119
|
await client.query(`INSERT INTO artifacts.git_binding_events
|
|
@@ -133,8 +133,8 @@ export function createPostgresArtifactStore(pool) {
|
|
|
133
133
|
for (const file of parsed.files ?? []) {
|
|
134
134
|
if (typeof file.digest !== 'string' || typeof file.size !== 'number')
|
|
135
135
|
continue;
|
|
136
|
-
await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size)
|
|
137
|
-
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [scopeId, file.digest, file.size]);
|
|
136
|
+
await client.query(`INSERT INTO artifacts.blobs (storage_scope_id, digest, size, placement)
|
|
137
|
+
VALUES ($1, $2, $3, 'object') ON CONFLICT DO NOTHING`, [scopeId, file.digest, file.size]);
|
|
138
138
|
}
|
|
139
139
|
await client.query('COMMIT');
|
|
140
140
|
}
|
package/dist/adapters/s3.js
CHANGED
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { DeleteObjectCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, } from '@aws-sdk/client-s3';
|
|
13
13
|
import { assertBlobPrefix } from '../server/blob-prefix.js';
|
|
14
|
+
import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
|
|
15
|
+
/** Per-call fetch cap: one page never materializes more than this (S3 MaxKeys bound). */
|
|
16
|
+
const PAGE_FETCH_CAP = 1000;
|
|
14
17
|
const BLOB_KEY_PATTERN = /^artifacts\/[A-Za-z0-9_-]+\/blobs\/sha256\/[0-9a-f]{64}$/;
|
|
15
18
|
/** Reject anything but digest-addressed blob keys, before any I/O. */
|
|
16
19
|
function assertBlobKey(key) {
|
|
@@ -20,10 +23,32 @@ function assertBlobKey(key) {
|
|
|
20
23
|
}
|
|
21
24
|
/** Create an S3-backed blob store over an injected client (no env reads). */
|
|
22
25
|
export function createS3BlobStore(options) {
|
|
23
|
-
|
|
26
|
+
const store = {
|
|
24
27
|
async putBlob(key, bytes) {
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
// CR-1: clone before verification, then verify before any I/O.
|
|
29
|
+
const snapshot = cloneBlobBytes(bytes);
|
|
30
|
+
verifyBytesForKey(key, snapshot);
|
|
31
|
+
try {
|
|
32
|
+
await options.client.send(new PutObjectCommand({ Bucket: options.bucket, Key: key, Body: snapshot, IfNoneMatch: '*' }));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
// Create-only: the key already exists. Settle by read-back — identical
|
|
36
|
+
// bytes are idempotent (verified digest match), different bytes fail
|
|
37
|
+
// closed without overwrite.
|
|
38
|
+
if (typeof error === 'object' && error !== null && 'name' in error &&
|
|
39
|
+
error.name === 'PreconditionFailed') {
|
|
40
|
+
const stored = await store.getBlob(key);
|
|
41
|
+
if (stored !== undefined) {
|
|
42
|
+
verifyStoredBytesForKey(key, stored);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
const stored = await store.getBlob(key);
|
|
49
|
+
if (stored === undefined)
|
|
50
|
+
throw new Error(`blob missing after write: ${key}`);
|
|
51
|
+
verifyStoredBytesForKey(key, stored);
|
|
27
52
|
},
|
|
28
53
|
async getBlob(key) {
|
|
29
54
|
assertBlobKey(key);
|
|
@@ -32,7 +57,8 @@ export function createS3BlobStore(options) {
|
|
|
32
57
|
if (out.Body === undefined)
|
|
33
58
|
return undefined;
|
|
34
59
|
const collected = await out.Body.transformToByteArray();
|
|
35
|
-
|
|
60
|
+
// CR-2: digest and length verified before serving bytes as verified.
|
|
61
|
+
return verifyStoredBytesForKey(key, new Uint8Array(collected));
|
|
36
62
|
}
|
|
37
63
|
catch (error) {
|
|
38
64
|
if (typeof error === 'object' && error !== null && 'name' in error) {
|
|
@@ -84,5 +110,29 @@ export function createS3BlobStore(options) {
|
|
|
84
110
|
assertBlobKey(key);
|
|
85
111
|
await options.client.send(new DeleteObjectCommand({ Bucket: options.bucket, Key: key }));
|
|
86
112
|
},
|
|
113
|
+
async listKeysPaged(prefix, page) {
|
|
114
|
+
assertBlobPrefix(prefix);
|
|
115
|
+
if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
|
|
116
|
+
throw new Error('invalid blob page maxItems');
|
|
117
|
+
if (page.startAfter !== undefined) {
|
|
118
|
+
if (!page.startAfter.startsWith(prefix)) {
|
|
119
|
+
throw new Error(`invalid blob page resume key: ${page.startAfter}`);
|
|
120
|
+
}
|
|
121
|
+
assertBlobKey(page.startAfter);
|
|
122
|
+
}
|
|
123
|
+
// Keyset resume: one bounded ListObjectsV2 from the resume key (no
|
|
124
|
+
// full-prefix load). The caller replays byte-trimmed tails by key.
|
|
125
|
+
const maxKeys = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
|
|
126
|
+
const out = await options.client.send(new ListObjectsV2Command({ Bucket: options.bucket, Prefix: prefix,
|
|
127
|
+
StartAfter: page.startAfter, MaxKeys: maxKeys }));
|
|
128
|
+
const keys = (out.Contents ?? []).flatMap((entry) => entry.Key === undefined ? [] : [entry.Key])
|
|
129
|
+
.filter((key) => key.startsWith(prefix))
|
|
130
|
+
.sort();
|
|
131
|
+
return {
|
|
132
|
+
keys: keys.slice(0, page.maxItems),
|
|
133
|
+
hasMore: out.IsTruncated === true || keys.length > page.maxItems,
|
|
134
|
+
};
|
|
135
|
+
},
|
|
87
136
|
};
|
|
137
|
+
return store;
|
|
88
138
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CMF-S2 — SQLite DB blob placement (`blob_bytes`).
|
|
3
|
+
*
|
|
4
|
+
* SQLite equivalent of `db-blob.ts`: digest-addressed blobs in the
|
|
5
|
+
* `blob_bytes` table (no FK to `blobs`, so preparation-phase puts succeed
|
|
6
|
+
* before registration). Create-only (`ON CONFLICT DO NOTHING`) + read-back
|
|
7
|
+
* verification: identical retries are idempotent, different bytes fail closed
|
|
8
|
+
* without overwriting.
|
|
9
|
+
*/
|
|
10
|
+
import type { PublicationBlobStore } from '../server/publication.js';
|
|
11
|
+
import { type SqliteDatabase } from './sqlite-sql.js';
|
|
12
|
+
/** Create a SQLite-backed blob store over an open database (no env reads). */
|
|
13
|
+
export declare function createSqliteDbBlobStore(db: SqliteDatabase): PublicationBlobStore;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { assertBlobPrefix } from '../server/blob-prefix.js';
|
|
2
|
+
import { cloneBlobBytes, verifyBytesForKey, verifyStoredBytesForKey } from '../server/blob-bridge.js';
|
|
3
|
+
import { runQuery } from './sqlite-sql.js';
|
|
4
|
+
/** Per-call fetch cap: one page never materializes more than this. */
|
|
5
|
+
const PAGE_FETCH_CAP = 1000;
|
|
6
|
+
const BLOB_KEY_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\/([0-9a-f]{64})$/;
|
|
7
|
+
const SCOPE_PREFIX_PATTERN = /^artifacts\/([A-Za-z0-9_-]+)\/blobs\/sha256\//;
|
|
8
|
+
function splitKey(key) {
|
|
9
|
+
const match = BLOB_KEY_PATTERN.exec(key);
|
|
10
|
+
if (!match)
|
|
11
|
+
throw new Error(`invalid blob key: ${key}`);
|
|
12
|
+
return { scope: match[1], digest: `sha256:${match[2]}` };
|
|
13
|
+
}
|
|
14
|
+
/** Create a SQLite-backed blob store over an open database (no env reads). */
|
|
15
|
+
export function createSqliteDbBlobStore(db) {
|
|
16
|
+
return {
|
|
17
|
+
async putBlob(key, bytes) {
|
|
18
|
+
const snapshot = cloneBlobBytes(bytes);
|
|
19
|
+
verifyBytesForKey(key, snapshot);
|
|
20
|
+
const { scope, digest } = splitKey(key);
|
|
21
|
+
runQuery(db, `INSERT INTO blob_bytes (storage_scope_id, digest, bytes) VALUES ($1, $2, $3)
|
|
22
|
+
ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scope, digest, Buffer.from(snapshot)]);
|
|
23
|
+
const stored = await this.getBlob(key);
|
|
24
|
+
if (stored === undefined)
|
|
25
|
+
throw new Error(`blob missing after write: ${key}`);
|
|
26
|
+
},
|
|
27
|
+
async getBlob(key) {
|
|
28
|
+
const { scope, digest } = splitKey(key);
|
|
29
|
+
const { rows } = runQuery(db, 'SELECT bytes FROM blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
|
|
30
|
+
if (rows[0] === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
return verifyStoredBytesForKey(key, new Uint8Array(rows[0].bytes));
|
|
33
|
+
},
|
|
34
|
+
async getBlobRange(key, start, endInclusive) {
|
|
35
|
+
const stored = await this.getBlob(key);
|
|
36
|
+
if (stored === undefined || !Number.isSafeInteger(start) || !Number.isSafeInteger(endInclusive) ||
|
|
37
|
+
start < 0 || endInclusive < start)
|
|
38
|
+
return undefined;
|
|
39
|
+
return stored.slice(start, Math.min(endInclusive + 1, stored.length));
|
|
40
|
+
},
|
|
41
|
+
async listKeys(prefix) {
|
|
42
|
+
assertBlobPrefix(prefix);
|
|
43
|
+
const match = SCOPE_PREFIX_PATTERN.exec(prefix);
|
|
44
|
+
if (!match)
|
|
45
|
+
throw new Error(`blob listing requires a scope prefix: ${prefix}`);
|
|
46
|
+
const { rows } = runQuery(db, 'SELECT digest FROM blob_bytes WHERE storage_scope_id = $1 ORDER BY digest', [match[1]]);
|
|
47
|
+
return rows
|
|
48
|
+
.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
|
|
49
|
+
.filter((key) => key.startsWith(prefix))
|
|
50
|
+
.sort();
|
|
51
|
+
},
|
|
52
|
+
async deleteBlob(key) {
|
|
53
|
+
const { scope, digest } = splitKey(key);
|
|
54
|
+
const result = runQuery(db, 'DELETE FROM blob_bytes WHERE storage_scope_id = $1 AND digest = $2', [scope, digest]);
|
|
55
|
+
if (result.rowCount === 0)
|
|
56
|
+
throw new Error(`unknown blob: ${key}`);
|
|
57
|
+
},
|
|
58
|
+
async listKeysPaged(prefix, page) {
|
|
59
|
+
assertBlobPrefix(prefix);
|
|
60
|
+
const match = SCOPE_PREFIX_PATTERN.exec(prefix);
|
|
61
|
+
if (!match)
|
|
62
|
+
throw new Error(`blob listing requires a scope prefix: ${prefix}`);
|
|
63
|
+
if (!Number.isSafeInteger(page.maxItems) || page.maxItems < 1)
|
|
64
|
+
throw new Error('invalid blob page maxItems');
|
|
65
|
+
const after = page.startAfter === undefined ? undefined : (() => {
|
|
66
|
+
if (!page.startAfter.startsWith(prefix))
|
|
67
|
+
throw new Error(`invalid blob page resume key: ${page.startAfter}`);
|
|
68
|
+
return splitKey(page.startAfter).digest;
|
|
69
|
+
})();
|
|
70
|
+
const limit = Math.min(page.maxItems + 1, PAGE_FETCH_CAP);
|
|
71
|
+
const { rows } = runQuery(db, `SELECT digest FROM blob_bytes WHERE storage_scope_id = $1
|
|
72
|
+
AND substr(digest, 1, length($2)) = $2
|
|
73
|
+
AND ($3 IS NULL OR digest > $3) ORDER BY digest LIMIT $4`, [match[1], `sha256:${prefix.slice(match[0].length)}`, after ?? null, limit]);
|
|
74
|
+
const keys = rows.map((row) => `artifacts/${match[1]}/blobs/sha256/${row.digest.slice('sha256:'.length)}`)
|
|
75
|
+
.filter((key) => key.startsWith(prefix))
|
|
76
|
+
.sort();
|
|
77
|
+
return { keys: keys.slice(0, page.maxItems), hasMore: rows.length === limit };
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -162,7 +162,8 @@ export function createSqliteArtifactStore(db, writer) {
|
|
|
162
162
|
for (const file of parsed.files ?? []) {
|
|
163
163
|
if (typeof file.digest !== 'string' || typeof file.size !== 'number')
|
|
164
164
|
continue;
|
|
165
|
-
runQuery(db,
|
|
165
|
+
runQuery(db, `INSERT INTO blobs (storage_scope_id, digest, size, placement) VALUES ($1, $2, $3, 'object')
|
|
166
|
+
ON CONFLICT (storage_scope_id, digest) DO NOTHING`, [scopeId, file.digest, file.size]);
|
|
166
167
|
}
|
|
167
168
|
// 0004 publication_updated_at side effect.
|
|
168
169
|
runQuery(db, 'UPDATE artifacts SET updated_at = $2 WHERE id = $1', [release.artifactId, release.createdAt]);
|
|
@@ -14,6 +14,12 @@ export interface SqliteWriter {
|
|
|
14
14
|
}
|
|
15
15
|
/** Open (creating if needed) a durable local database file and apply the DDL. */
|
|
16
16
|
export declare function openSqliteDatabase(path: string): SqliteDatabase;
|
|
17
|
+
/**
|
|
18
|
+
* CMF-S2 — idempotent DB blob placement upgrade for local files.
|
|
19
|
+
* `CREATE TABLE IF NOT EXISTS` re-runs cleanly on every open; the `blobs`
|
|
20
|
+
* placement column is added only when missing so existing files reopen.
|
|
21
|
+
*/
|
|
22
|
+
export declare function applySqliteBlobPlacementUpgrade(db: SqliteDatabase): void;
|
|
17
23
|
/** Create the serialized writer over one database connection. */
|
|
18
24
|
export declare function createSqliteWriter(db: SqliteDatabase): SqliteWriter;
|
|
19
25
|
export type SqliteArtifactStore = PostgresArtifactStore;
|
|
@@ -23,6 +29,7 @@ export { createSqliteArtifactStore, createSqliteCommitExecutor };
|
|
|
23
29
|
export { createSqliteManagementUnit } from './sqlite-management.js';
|
|
24
30
|
export { createSqliteActivationStore, type SqliteActivationStore } from './sqlite-activation.js';
|
|
25
31
|
export { createLocalBlobStore } from './local-blob.js';
|
|
32
|
+
export { createSqliteDbBlobStore } from './sqlite-blob.js';
|
|
26
33
|
/** One-call wiring: open a file, create the writer, build store + executor. */
|
|
27
34
|
export declare function openSqliteArtifacts(path: string): {
|
|
28
35
|
db: SqliteDatabase;
|