@sentropic/artifacts 0.2.13 → 0.2.14
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 +26 -0
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/s3.js +23 -0
- package/dist/adapters/sqlite-activation.d.ts +20 -0
- package/dist/adapters/sqlite-activation.js +205 -0
- package/dist/adapters/sqlite-commit.d.ts +15 -0
- package/dist/adapters/sqlite-commit.js +89 -0
- package/dist/adapters/sqlite-management.d.ts +10 -0
- package/dist/adapters/sqlite-management.js +60 -0
- package/dist/adapters/sqlite-sql.d.ts +32 -0
- package/dist/adapters/sqlite-sql.js +36 -0
- package/dist/adapters/sqlite-store.d.ts +12 -0
- package/dist/adapters/sqlite-store.js +410 -0
- package/dist/adapters/sqlite.d.ts +33 -0
- package/dist/adapters/sqlite.js +95 -0
- package/dist/content/handler.d.ts +5 -0
- package/dist/content/handler.js +80 -9
- package/dist/http.d.ts +16 -0
- package/dist/http.js +371 -82
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +43 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +4 -0
- package/dist/profile/index.js +12 -2
- package/dist/profile/schemas.js +60 -0
- package/dist/profile/validation.js +31 -4
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +4 -3
- package/dist/server/gc.d.ts +28 -3
- package/dist/server/gc.js +81 -5
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/publication-limits.d.ts +8 -0
- package/dist/server/publication-limits.js +8 -0
- package/dist/server/publication.d.ts +5 -0
- package/dist/server/publication.js +6 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +75 -1
- package/dist/server/uploads.js +187 -27
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +13 -1
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { runQuery } from './sqlite-sql.js';
|
|
2
|
+
function toReceipt(row) {
|
|
3
|
+
return {
|
|
4
|
+
scopeId: row.storage_scope_id,
|
|
5
|
+
internalKey: row.internal_key,
|
|
6
|
+
commandHash: row.command_hash,
|
|
7
|
+
codecVersion: row.command_codec,
|
|
8
|
+
receipt: JSON.parse(row.receipt),
|
|
9
|
+
createdAt: row.created_at,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
/** Create the SQLite finalization executor over one database + writer. */
|
|
13
|
+
export function createSqliteCommitExecutor(db, writer) {
|
|
14
|
+
return {
|
|
15
|
+
async ensureCoordinationRow(scopeId, internalKey) {
|
|
16
|
+
await writer.run(() => {
|
|
17
|
+
runQuery(db, 'INSERT INTO operation_keys (storage_scope_id, internal_key) VALUES ($1, $2) ON CONFLICT (storage_scope_id, internal_key) DO NOTHING', [scopeId, internalKey]);
|
|
18
|
+
});
|
|
19
|
+
},
|
|
20
|
+
async beginFinalization() {
|
|
21
|
+
const releaseWriter = await writer.acquire();
|
|
22
|
+
db.exec('BEGIN IMMEDIATE');
|
|
23
|
+
let finished = false;
|
|
24
|
+
let released = false;
|
|
25
|
+
const finish = () => {
|
|
26
|
+
if (!finished) {
|
|
27
|
+
finished = true;
|
|
28
|
+
try {
|
|
29
|
+
db.exec('ROLLBACK');
|
|
30
|
+
}
|
|
31
|
+
catch { /* transaction already closed */ }
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
query(text, params) {
|
|
36
|
+
// pg deferred-constraint directive has no SQLite equivalent; every
|
|
37
|
+
// SQLite constraint is already immediate, which is what it asks for.
|
|
38
|
+
if (/^\s*SET\s+CONSTRAINTS\b/i.test(text))
|
|
39
|
+
return Promise.resolve({ rows: [], rowCount: 0 });
|
|
40
|
+
return Promise.resolve(runQuery(db, text, params));
|
|
41
|
+
},
|
|
42
|
+
// BEGIN IMMEDIATE is already open; SQLite serializes writers, which
|
|
43
|
+
// subsumes the pg READ COMMITTED + FOR UPDATE key lock.
|
|
44
|
+
beginReadCommitted() { return Promise.resolve(); },
|
|
45
|
+
lockOperationKey(scopeId, internalKey) {
|
|
46
|
+
runQuery(db, 'SELECT 1 FROM operation_keys WHERE storage_scope_id = $1 AND internal_key = $2', [scopeId, internalKey]);
|
|
47
|
+
return Promise.resolve();
|
|
48
|
+
},
|
|
49
|
+
async readReceipt(scopeId, internalKey) {
|
|
50
|
+
const { rows } = runQuery(db, `SELECT storage_scope_id, internal_key, command_codec, command_hash, receipt, created_at
|
|
51
|
+
FROM operation_receipts WHERE storage_scope_id = $1 AND internal_key = $2`, [scopeId, internalKey]);
|
|
52
|
+
return rows[0] === undefined ? undefined : toReceipt(rows[0]);
|
|
53
|
+
},
|
|
54
|
+
async insertReceipt(receipt) {
|
|
55
|
+
try {
|
|
56
|
+
runQuery(db, `INSERT INTO operation_receipts (storage_scope_id, internal_key, command_codec, command_hash, receipt)
|
|
57
|
+
VALUES ($1, $2, $3, $4, $5)`, [receipt.scopeId, receipt.internalKey, receipt.codecVersion, receipt.commandHash, JSON.stringify(receipt.receipt)]);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// Adapt the driver error to the pg code the coordinator's
|
|
61
|
+
// isUniqueViolation() port contract expects.
|
|
62
|
+
if (error instanceof Error && /UNIQUE constraint failed/i.test(error.message)) {
|
|
63
|
+
throw Object.assign(new Error(error.message, { cause: error }), { code: '23505' });
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
async commit() {
|
|
69
|
+
db.exec('COMMIT');
|
|
70
|
+
finished = true;
|
|
71
|
+
},
|
|
72
|
+
async rollback() {
|
|
73
|
+
finish();
|
|
74
|
+
},
|
|
75
|
+
release(error) {
|
|
76
|
+
if (released)
|
|
77
|
+
throw new Error('finalization client already released');
|
|
78
|
+
released = true;
|
|
79
|
+
finish();
|
|
80
|
+
releaseWriter();
|
|
81
|
+
if (error !== undefined) {
|
|
82
|
+
// Single connection: nothing to destroy; an uncertain COMMIT left
|
|
83
|
+
// the file consistent (WAL), and the caller sees the error.
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U1 — SQLite management unit, same ManagementUnit port as
|
|
3
|
+
* `createPostgresManagementUnit`. Runs on the caller's finalization client
|
|
4
|
+
* (inside the serialized writer transaction), so the pg FOR UPDATE row locks
|
|
5
|
+
* are unnecessary: the parent lock is the writer mutex itself.
|
|
6
|
+
*/
|
|
7
|
+
import type { FinalizeTxClient } from '../server/commit/types.js';
|
|
8
|
+
import type { ManagementUnit } from '../server/management.js';
|
|
9
|
+
/** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
|
|
10
|
+
export declare function createSqliteManagementUnit(client: FinalizeTxClient): ManagementUnit;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { applyModeTransition, PLATFORM_PRINCIPAL, PUBLIC_PRINCIPAL } from '../server/access.js';
|
|
2
|
+
/** Parent lock serializes ACL inserts, lifecycle changes and publication FKs. */
|
|
3
|
+
export function createSqliteManagementUnit(client) {
|
|
4
|
+
const listGrants = async (id) => {
|
|
5
|
+
const { rows } = await client.query('SELECT principal_id, permission, created_at FROM artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
|
|
6
|
+
return rows.map((row) => ({ principalId: row.principal_id, grant: row.permission,
|
|
7
|
+
createdAt: row.created_at }));
|
|
8
|
+
};
|
|
9
|
+
return {
|
|
10
|
+
async lock(id) {
|
|
11
|
+
await client.query('SELECT id FROM artifacts WHERE id = $1', [id]);
|
|
12
|
+
await client.query('SELECT principal_id FROM artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [id]);
|
|
13
|
+
await client.query('SELECT release_id FROM artifact_current WHERE artifact_id = $1', [id]);
|
|
14
|
+
},
|
|
15
|
+
async read(id) {
|
|
16
|
+
const { rows } = await client.query(`SELECT a.owner_id, a.storage_scope_id, a.lifecycle_state, a.is_public, a.access_mode, a.terminal_deleted_at, c.release_id
|
|
17
|
+
FROM artifacts a LEFT JOIN artifact_current c ON c.artifact_id = a.id WHERE a.id = $1`, [id]);
|
|
18
|
+
const row = rows[0];
|
|
19
|
+
if (!row)
|
|
20
|
+
return undefined;
|
|
21
|
+
// G1: access_mode is authoritative; is_public is its legacy projection.
|
|
22
|
+
const accessMode = (row.access_mode ?? (row.is_public === 1 ? 'platform' : 'restricted'));
|
|
23
|
+
const acl = { ownerId: row.owner_id, storageScopeId: row.storage_scope_id,
|
|
24
|
+
isPublic: accessMode !== 'restricted', accessMode, withdrawn: row.lifecycle_state === 'withdrawn', grants: [] };
|
|
25
|
+
return { acl, state: row.lifecycle_state, terminal: row.terminal_deleted_at !== null,
|
|
26
|
+
currentReleaseId: row.release_id };
|
|
27
|
+
},
|
|
28
|
+
async setAccess(id, principalId, action, updatedAt) {
|
|
29
|
+
const modeRow = await client.query('SELECT access_mode, is_public FROM artifacts WHERE id = $1', [id]);
|
|
30
|
+
const current = (modeRow.rows[0] === undefined ? 'restricted'
|
|
31
|
+
: (modeRow.rows[0].access_mode ?? (modeRow.rows[0].is_public === 1 ? 'platform' : 'restricted')));
|
|
32
|
+
if (principalId === PLATFORM_PRINCIPAL || principalId === PUBLIC_PRINCIPAL) {
|
|
33
|
+
// Wide-audience sentinels move the mode through the normative transitions;
|
|
34
|
+
// is_public follows as projection (never forced to false).
|
|
35
|
+
const transition = applyModeTransition(current, action, principalId);
|
|
36
|
+
if (transition.changed) {
|
|
37
|
+
await client.query(`UPDATE artifacts SET access_mode = $2, is_public = ($2 <> 'restricted'), updated_at = $3 WHERE id = $1`, [id, transition.mode, updatedAt]);
|
|
38
|
+
}
|
|
39
|
+
return { grants: await listGrants(id), updatedAt, accessMode: transition.mode, changed: transition.changed };
|
|
40
|
+
}
|
|
41
|
+
const changed = action === 'grant' ? await client.query(`INSERT INTO artifact_access (artifact_id, principal_id, permission) VALUES ($1, $2, 'read')
|
|
42
|
+
ON CONFLICT (artifact_id, principal_id) DO NOTHING`, [id, principalId])
|
|
43
|
+
: await client.query('DELETE FROM artifact_access WHERE artifact_id = $1 AND principal_id = $2', [id, principalId]);
|
|
44
|
+
if (changed.rowCount > 0) {
|
|
45
|
+
await client.query('UPDATE artifacts SET updated_at = $2 WHERE id = $1', [id, updatedAt]);
|
|
46
|
+
}
|
|
47
|
+
const stamp = await client.query('SELECT updated_at FROM artifacts WHERE id = $1', [id]);
|
|
48
|
+
return { grants: await listGrants(id), updatedAt: stamp.rows[0]?.updated_at ?? null,
|
|
49
|
+
accessMode: current, changed: changed.rowCount > 0 };
|
|
50
|
+
},
|
|
51
|
+
async recordEvent(event) {
|
|
52
|
+
await client.query(`INSERT INTO artifact_access_events (artifact_id, actor_id, action, audience, principal_id, policy_revision)
|
|
53
|
+
VALUES ($1, $2, $3, $4, $5, $6)`, [event.artifactId, event.actorId, event.action, event.audience, event.principalId, event.policyRevision]);
|
|
54
|
+
},
|
|
55
|
+
async delete(id, deletedAt) {
|
|
56
|
+
await client.query(`UPDATE artifacts SET lifecycle_state = 'deleted', terminal_deleted_at = $2,
|
|
57
|
+
updated_at = $2, is_public = 0 WHERE id = $1`, [id, deletedAt]);
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U1 — shared SQLite SQL helpers for the local adapter set (no driver import:
|
|
3
|
+
* only the structural database interface, so test doubles can wrap it).
|
|
4
|
+
*/
|
|
5
|
+
export interface SqliteStatement {
|
|
6
|
+
run(...params: unknown[]): {
|
|
7
|
+
changes: number | bigint;
|
|
8
|
+
};
|
|
9
|
+
all(...params: unknown[]): unknown[];
|
|
10
|
+
get(...params: unknown[]): unknown;
|
|
11
|
+
}
|
|
12
|
+
export interface SqliteDatabase {
|
|
13
|
+
exec(sql: string): void;
|
|
14
|
+
prepare(sql: string): SqliteStatement;
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Normalize portable caller SQL for SQLite: `$N` placeholders become `?`
|
|
19
|
+
* (params re-ordered by first appearance), pg casts `::type` and row-lock
|
|
20
|
+
* clauses (`FOR UPDATE/SHARE … SKIP LOCKED/NOWAIT`) are stripped — the
|
|
21
|
+
* serialized writer already provides the locking. Booleans bind as 0/1,
|
|
22
|
+
* undefined as NULL.
|
|
23
|
+
*/
|
|
24
|
+
export declare function normalizeSql(text: string, params?: readonly unknown[]): {
|
|
25
|
+
sql: string;
|
|
26
|
+
args: unknown[];
|
|
27
|
+
};
|
|
28
|
+
/** Execute one statement: rows for SELECT/RETURNING, rowCount = changes otherwise. */
|
|
29
|
+
export declare function runQuery<T>(db: SqliteDatabase, text: string, params?: readonly unknown[]): {
|
|
30
|
+
rows: T[];
|
|
31
|
+
rowCount: number;
|
|
32
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalize portable caller SQL for SQLite: `$N` placeholders become `?`
|
|
3
|
+
* (params re-ordered by first appearance), pg casts `::type` and row-lock
|
|
4
|
+
* clauses (`FOR UPDATE/SHARE … SKIP LOCKED/NOWAIT`) are stripped — the
|
|
5
|
+
* serialized writer already provides the locking. Booleans bind as 0/1,
|
|
6
|
+
* undefined as NULL.
|
|
7
|
+
*/
|
|
8
|
+
export function normalizeSql(text, params = []) {
|
|
9
|
+
const args = [];
|
|
10
|
+
let sql = text.replace(/\$(\d+)/g, (_match, index) => {
|
|
11
|
+
args.push(params[Number(index) - 1]);
|
|
12
|
+
return '?';
|
|
13
|
+
});
|
|
14
|
+
sql = sql
|
|
15
|
+
.replace(/::[A-Za-z_][A-Za-z0-9_]*(\[\])?/g, '')
|
|
16
|
+
.replace(/\s+FOR\s+(?:UPDATE|SHARE|KEY\s+SHARE|NO KEY UPDATE)(?:\s+OF\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*)*)?(?:\s+(?:SKIP\s+LOCKED|NOWAIT))?/gi, '');
|
|
17
|
+
const bound = args.map((value) => {
|
|
18
|
+
if (value === undefined)
|
|
19
|
+
return null;
|
|
20
|
+
if (typeof value === 'boolean')
|
|
21
|
+
return value ? 1 : 0;
|
|
22
|
+
return value;
|
|
23
|
+
});
|
|
24
|
+
return { sql, args: bound };
|
|
25
|
+
}
|
|
26
|
+
/** Execute one statement: rows for SELECT/RETURNING, rowCount = changes otherwise. */
|
|
27
|
+
export function runQuery(db, text, params = []) {
|
|
28
|
+
const { sql, args } = normalizeSql(text, params);
|
|
29
|
+
const statement = db.prepare(sql);
|
|
30
|
+
if (/\bRETURNING\b/i.test(sql) || /^\s*SELECT\b/i.test(sql)) {
|
|
31
|
+
const rows = statement.all(...args);
|
|
32
|
+
return { rows, rowCount: rows.length };
|
|
33
|
+
}
|
|
34
|
+
const info = statement.run(...args);
|
|
35
|
+
return { rows: [], rowCount: Number(info.changes) };
|
|
36
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RefcountStore } from '../server/gc.js';
|
|
2
|
+
import type { LifecycleStore } from '../server/lifecycle.js';
|
|
3
|
+
import type { SourceStore } from '../server/sources.js';
|
|
4
|
+
import type { PreparationIntentStore } from '../server/object-intents.js';
|
|
5
|
+
import type { IdempotencyStore } from '../server/idempotency.js';
|
|
6
|
+
import type { PublicationStateStore } from '../server/publication.js';
|
|
7
|
+
import type { PostgresArtifactStore } from './postgres.js';
|
|
8
|
+
import { type SqliteDatabase } from './sqlite-sql.js';
|
|
9
|
+
import type { SqliteWriter } from './sqlite.js';
|
|
10
|
+
/** Create the SQLite-backed store implementing the same ports as the pg store. */
|
|
11
|
+
export declare function createSqliteArtifactStore(db: SqliteDatabase, writer: SqliteWriter): PostgresArtifactStore;
|
|
12
|
+
export type { PreparationIntentStore, PublicationStateStore, IdempotencyStore, RefcountStore, SourceStore, LifecycleStore };
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U1 — SQLite artifact store: the same port interfaces as
|
|
3
|
+
* `createPostgresArtifactStore` (bindings, intents, preparation-cleanup reads,
|
|
4
|
+
* idempotency, ACL, sources, lifecycle, publication state + CAS, refcounts),
|
|
5
|
+
* over one serialized writer. Multi-statement units (ensureArtifact race
|
|
6
|
+
* path, putRelease, terminal-guarded updates) run in one BEGIN IMMEDIATE
|
|
7
|
+
* transaction; single statements are atomic on the single connection. The
|
|
8
|
+
* 0004 terminal guards are enforced here (check-then-write is atomic under
|
|
9
|
+
* the writer) with the same 'terminal artifact' error text as the pg triggers.
|
|
10
|
+
*/
|
|
11
|
+
import { randomUUID } from 'node:crypto';
|
|
12
|
+
import { ArtifactOperationError } from '../server/failures.js';
|
|
13
|
+
import { runQuery } from './sqlite-sql.js';
|
|
14
|
+
function toIntent(row) {
|
|
15
|
+
return {
|
|
16
|
+
intentId: row.id,
|
|
17
|
+
kind: row.kind,
|
|
18
|
+
state: row.state,
|
|
19
|
+
payload: JSON.parse(row.payload),
|
|
20
|
+
error: row.error ?? undefined,
|
|
21
|
+
createdAt: row.created_at,
|
|
22
|
+
updatedAt: row.updated_at,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function toRelease(row) {
|
|
26
|
+
return {
|
|
27
|
+
authorPrincipalId: row.author_principal_id,
|
|
28
|
+
parentReleaseId: row.parent_release_id,
|
|
29
|
+
revertedFromReleaseId: row.reverted_from_release_id,
|
|
30
|
+
releaseId: row.id,
|
|
31
|
+
artifactId: row.artifact_id,
|
|
32
|
+
manifestDigest: row.manifest_digest,
|
|
33
|
+
manifest: row.manifest,
|
|
34
|
+
state: row.state,
|
|
35
|
+
createdAt: row.created_at,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const nowIso = () => new Date().toISOString();
|
|
39
|
+
/** Terminal guard (pg 0004 reject_terminal_restore): returns the row or throws. */
|
|
40
|
+
function artifactRow(db, artifactId) {
|
|
41
|
+
const { rows } = runQuery(db, 'SELECT lifecycle_state, renewed_at, terminal_deleted_at FROM artifacts WHERE id = $1', [artifactId]);
|
|
42
|
+
const row = rows[0];
|
|
43
|
+
if (row === undefined)
|
|
44
|
+
throw new Error(`unknown artifact: ${artifactId}`);
|
|
45
|
+
return row;
|
|
46
|
+
}
|
|
47
|
+
function assertRestorable(row, newState, newRenewedAt) {
|
|
48
|
+
if (row.terminal_deleted_at !== null && (newState !== 'deleted' && newState !== 'purged' || newRenewedAt !== row.renewed_at)) {
|
|
49
|
+
throw new Error('terminal artifact');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Create the SQLite-backed store implementing the same ports as the pg store. */
|
|
53
|
+
export function createSqliteArtifactStore(db, writer) {
|
|
54
|
+
const store = {
|
|
55
|
+
async ensureArtifact(input) {
|
|
56
|
+
return writer.tx(() => {
|
|
57
|
+
const where = 'WHERE storage_scope_id = $1 AND owner_id = $2 AND binding_name = $3';
|
|
58
|
+
const args = [input.storageScopeId, input.ownerId, input.bindingName];
|
|
59
|
+
const found = runQuery(db, `SELECT id, terminal_deleted_at IS NOT NULL AS terminal FROM artifacts ${where}`, args);
|
|
60
|
+
if (found.rows[0] !== undefined) {
|
|
61
|
+
if (found.rows[0].terminal)
|
|
62
|
+
throw new ArtifactOperationError('gone');
|
|
63
|
+
return { artifactId: found.rows[0].id, created: false };
|
|
64
|
+
}
|
|
65
|
+
const inserted = runQuery(db, `INSERT INTO artifacts (id, storage_scope_id, owner_id, binding_name, profile)
|
|
66
|
+
VALUES ($4, $1, $2, $3, $5)
|
|
67
|
+
ON CONFLICT (storage_scope_id, owner_id, binding_name) DO NOTHING RETURNING id`, [...args, randomUUID(), JSON.stringify(input.profile)]);
|
|
68
|
+
if (inserted.rows[0] !== undefined)
|
|
69
|
+
return { artifactId: inserted.rows[0].id, created: true };
|
|
70
|
+
const raced = runQuery(db, `SELECT id, terminal_deleted_at IS NOT NULL AS terminal FROM artifacts ${where}`, args);
|
|
71
|
+
const row = raced.rows[0];
|
|
72
|
+
if (row === undefined)
|
|
73
|
+
throw new Error(`artifact binding lost for ${input.bindingName}`);
|
|
74
|
+
if (row.terminal)
|
|
75
|
+
throw new ArtifactOperationError('gone');
|
|
76
|
+
return { artifactId: row.id, created: false };
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
async record(kind, payload) {
|
|
80
|
+
return writer.run(() => {
|
|
81
|
+
const { rows } = runQuery(db, `INSERT INTO object_intents (id, kind, payload) VALUES ($1, $2, $3)
|
|
82
|
+
RETURNING id, kind, state, payload, error, created_at, updated_at`, [randomUUID(), kind, JSON.stringify(payload)]);
|
|
83
|
+
const row = rows[0];
|
|
84
|
+
if (row === undefined)
|
|
85
|
+
throw new Error('intent insert failed');
|
|
86
|
+
return toIntent(row);
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
async complete(intentId) {
|
|
90
|
+
await writer.run(() => {
|
|
91
|
+
const { rowCount } = runQuery(db, `UPDATE object_intents SET state = 'done', updated_at = $2 WHERE id = $1`, [intentId, nowIso()]);
|
|
92
|
+
if (rowCount === 0)
|
|
93
|
+
throw new Error(`unknown intent: ${intentId}`);
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
async markFailed(intentId, error) {
|
|
97
|
+
await writer.run(() => {
|
|
98
|
+
const { rowCount } = runQuery(db, `UPDATE object_intents SET state = 'failed', error = $2, updated_at = $3 WHERE id = $1`, [intentId, error, nowIso()]);
|
|
99
|
+
if (rowCount === 0)
|
|
100
|
+
throw new Error(`unknown intent: ${intentId}`);
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
async get(intentId) {
|
|
104
|
+
const { rows } = runQuery(db, 'SELECT id, kind, state, payload, error, created_at, updated_at FROM object_intents WHERE id = $1', [intentId]);
|
|
105
|
+
return rows[0] === undefined ? undefined : toIntent(rows[0]);
|
|
106
|
+
},
|
|
107
|
+
async listPending() {
|
|
108
|
+
const { rows } = runQuery(db, `SELECT id, kind, state, payload, error, created_at, updated_at FROM object_intents
|
|
109
|
+
WHERE state = 'pending' ORDER BY created_at`);
|
|
110
|
+
return rows.map(toIntent);
|
|
111
|
+
},
|
|
112
|
+
async listPreparationIntents(query = {}) {
|
|
113
|
+
const { rows } = runQuery(db, `SELECT id, kind, state, payload, error, created_at, updated_at FROM object_intents
|
|
114
|
+
WHERE kind = 'commit-release' AND state <> 'done'
|
|
115
|
+
AND json_type(payload, '$.cleanupDeadlineMs') IS NOT NULL
|
|
116
|
+
AND ($1 IS NULL OR json_extract(payload, '$.artifactId') = $1)
|
|
117
|
+
AND ($2 IS NULL OR (
|
|
118
|
+
COALESCE(error, '') NOT LIKE 'invalid preparation metadata%'
|
|
119
|
+
AND CASE WHEN json_type(payload, '$.cleanupDeadlineMs') IN ('integer', 'real')
|
|
120
|
+
THEN json_extract(payload, '$.cleanupDeadlineMs') ELSE 0 END <= $2
|
|
121
|
+
AND (json_extract(payload, '$.cleanupState') IS NOT 'failed-cleaned'
|
|
122
|
+
OR json_extract(payload, '$.cleanupDeadlineMs') >= $2 - 60000)))
|
|
123
|
+
ORDER BY COALESCE(json_extract(payload, '$.cleanupState') = 'failed-cleaned', 0),
|
|
124
|
+
CASE WHEN json_type(payload, '$.cleanupDeadlineMs') IN ('integer', 'real')
|
|
125
|
+
THEN json_extract(payload, '$.cleanupDeadlineMs') ELSE 0 END, id
|
|
126
|
+
LIMIT $3`, [query.artifactId ?? null, query.throughMs ?? null, query.limit ?? -1]);
|
|
127
|
+
return rows.map(toIntent);
|
|
128
|
+
},
|
|
129
|
+
async claimPreparationCleanup(intentId, throughMs) {
|
|
130
|
+
return writer.run(() => {
|
|
131
|
+
// Serialized with finalization's intent completion on the same row.
|
|
132
|
+
const { rows } = runQuery(db, `UPDATE object_intents SET state = 'failed',
|
|
133
|
+
error = COALESCE(error, 'preparation expired; explicit retry required'), updated_at = $3
|
|
134
|
+
WHERE id = $1 AND kind = 'commit-release' AND state <> 'done'
|
|
135
|
+
AND json_type(payload, '$.cleanupDeadlineMs') IN ('integer', 'real')
|
|
136
|
+
AND json_extract(payload, '$.cleanupDeadlineMs') <= $2
|
|
137
|
+
RETURNING id, kind, state, payload, error, created_at, updated_at`, [intentId, throughMs, nowIso()]);
|
|
138
|
+
return rows[0] === undefined ? undefined : toIntent(rows[0]);
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
async settlePreparationCleanup(intentId) {
|
|
142
|
+
await writer.run(() => {
|
|
143
|
+
const { rowCount } = runQuery(db, `UPDATE object_intents SET payload = json_set(payload, '$.cleanupState', 'failed-cleaned'), updated_at = $2
|
|
144
|
+
WHERE id = $1 AND state = 'failed'`, [intentId, nowIso()]);
|
|
145
|
+
if (rowCount === 0)
|
|
146
|
+
throw new Error('cleanup needs a failed preparation');
|
|
147
|
+
});
|
|
148
|
+
},
|
|
149
|
+
async putRelease(release) {
|
|
150
|
+
await writer.tx(() => {
|
|
151
|
+
const parsed = JSON.parse(release.manifest);
|
|
152
|
+
// 0004 terminal_release_guard: the artifact must exist and not be terminal.
|
|
153
|
+
const artifact = runQuery(db, 'SELECT terminal_deleted_at IS NOT NULL AS terminal FROM artifacts WHERE id = $1', [release.artifactId]);
|
|
154
|
+
if (artifact.rows[0] === undefined || artifact.rows[0].terminal)
|
|
155
|
+
throw new Error('terminal artifact');
|
|
156
|
+
runQuery(db, `INSERT INTO releases (id, artifact_id, manifest_digest, manifest, state, created_at)
|
|
157
|
+
VALUES ($1, $2, $3, $4, 'ready', $5)`, [release.releaseId, release.artifactId, release.manifestDigest, release.manifest, release.createdAt]);
|
|
158
|
+
const scope = runQuery(db, 'SELECT storage_scope_id FROM artifacts WHERE id = $1', [release.artifactId]);
|
|
159
|
+
const scopeId = scope.rows[0]?.storage_scope_id;
|
|
160
|
+
if (scopeId === undefined)
|
|
161
|
+
throw new Error(`unknown artifact: ${release.artifactId}`);
|
|
162
|
+
for (const file of parsed.files ?? []) {
|
|
163
|
+
if (typeof file.digest !== 'string' || typeof file.size !== 'number')
|
|
164
|
+
continue;
|
|
165
|
+
runQuery(db, 'INSERT INTO blobs (storage_scope_id, digest, size) VALUES ($1, $2, $3) ON CONFLICT (storage_scope_id, digest) DO NOTHING', [scopeId, file.digest, file.size]);
|
|
166
|
+
}
|
|
167
|
+
// 0004 publication_updated_at side effect.
|
|
168
|
+
runQuery(db, 'UPDATE artifacts SET updated_at = $2 WHERE id = $1', [release.artifactId, release.createdAt]);
|
|
169
|
+
});
|
|
170
|
+
},
|
|
171
|
+
async getRelease(releaseId) {
|
|
172
|
+
const { rows } = runQuery(db, 'SELECT * FROM releases WHERE id = $1', [releaseId]);
|
|
173
|
+
return rows[0] === undefined ? undefined : toRelease(rows[0]);
|
|
174
|
+
},
|
|
175
|
+
async listReleases(artifactId) {
|
|
176
|
+
const { rows } = runQuery(db, 'SELECT * FROM releases WHERE artifact_id = $1 ORDER BY created_at, id', [artifactId]);
|
|
177
|
+
return rows.map(toRelease);
|
|
178
|
+
},
|
|
179
|
+
async getCurrentReleaseId(artifactId) {
|
|
180
|
+
const { rows } = runQuery(db, 'SELECT release_id FROM artifact_current WHERE artifact_id = $1', [artifactId]);
|
|
181
|
+
return rows[0]?.release_id;
|
|
182
|
+
},
|
|
183
|
+
async compareAndSwapCurrent(artifactId, expected, next) {
|
|
184
|
+
return writer.run(() => {
|
|
185
|
+
// 0004 terminal_pointer_guard.
|
|
186
|
+
const artifact = runQuery(db, 'SELECT terminal_deleted_at IS NOT NULL AS terminal FROM artifacts WHERE id = $1', [artifactId]);
|
|
187
|
+
if (artifact.rows[0] !== undefined && artifact.rows[0].terminal)
|
|
188
|
+
throw new Error('terminal artifact');
|
|
189
|
+
if (expected === null) {
|
|
190
|
+
const inserted = runQuery(db, 'INSERT INTO artifact_current (artifact_id, release_id) VALUES ($1, $2) ON CONFLICT (artifact_id) DO NOTHING', [artifactId, next]);
|
|
191
|
+
return inserted.rowCount !== 0;
|
|
192
|
+
}
|
|
193
|
+
const updated = runQuery(db, 'UPDATE artifact_current SET release_id = $3 WHERE artifact_id = $1 AND release_id = $2', [artifactId, expected, next]);
|
|
194
|
+
return updated.rowCount !== 0;
|
|
195
|
+
});
|
|
196
|
+
},
|
|
197
|
+
async execute(key, paramsHash, work) {
|
|
198
|
+
const select = 'SELECT params_hash, result FROM idempotency_keys WHERE key = $1';
|
|
199
|
+
const found = runQuery(db, select, [`idempotency:${key}`]);
|
|
200
|
+
const stored = found.rows[0];
|
|
201
|
+
if (stored !== undefined) {
|
|
202
|
+
if (stored.params_hash !== paramsHash) {
|
|
203
|
+
throw new Error(`idempotency conflict: key ${key} already used with different parameters`);
|
|
204
|
+
}
|
|
205
|
+
return { result: JSON.parse(stored.result), replayed: true };
|
|
206
|
+
}
|
|
207
|
+
const result = await work();
|
|
208
|
+
return writer.run(() => {
|
|
209
|
+
const inserted = runQuery(db, 'INSERT INTO idempotency_keys (key, params_hash, result) VALUES ($1, $2, $3) ON CONFLICT (key) DO NOTHING RETURNING key', [`idempotency:${key}`, paramsHash, JSON.stringify(result)]);
|
|
210
|
+
if (inserted.rowCount !== 0)
|
|
211
|
+
return { result, replayed: false };
|
|
212
|
+
const raced = runQuery(db, select, [`idempotency:${key}`]);
|
|
213
|
+
const winner = raced.rows[0];
|
|
214
|
+
if (winner === undefined)
|
|
215
|
+
throw new Error(`idempotency record lost for ${key}`);
|
|
216
|
+
if (winner.params_hash !== paramsHash) {
|
|
217
|
+
throw new Error(`idempotency conflict: key ${key} already used with different parameters`);
|
|
218
|
+
}
|
|
219
|
+
return { result: JSON.parse(winner.result), replayed: true };
|
|
220
|
+
});
|
|
221
|
+
},
|
|
222
|
+
async listRegisteredBlobs(storageScopeId) {
|
|
223
|
+
const { rows } = runQuery(db, 'SELECT digest FROM blobs WHERE storage_scope_id = $1 ORDER BY digest', [storageScopeId]);
|
|
224
|
+
return rows.map((row) => row.digest);
|
|
225
|
+
},
|
|
226
|
+
async getArtifactAcl(artifactId) {
|
|
227
|
+
const { rows } = runQuery(db, `SELECT owner_id, storage_scope_id, is_public, access_mode, lifecycle_state, binding_name, created_at, updated_at, metadata
|
|
228
|
+
FROM artifacts WHERE id = $1`, [artifactId]);
|
|
229
|
+
const row = rows[0];
|
|
230
|
+
if (row === undefined)
|
|
231
|
+
return undefined;
|
|
232
|
+
const grants = runQuery(db, 'SELECT principal_id, permission, created_at FROM artifact_access WHERE artifact_id = $1 ORDER BY principal_id', [artifactId]);
|
|
233
|
+
const metadata = row.metadata === null ? {} : JSON.parse(row.metadata);
|
|
234
|
+
// G1: access_mode is authoritative; is_public is its legacy projection.
|
|
235
|
+
const accessMode = (row.access_mode ?? (row.is_public === 1 ? 'platform' : 'restricted'));
|
|
236
|
+
return {
|
|
237
|
+
bindingName: row.binding_name, createdAt: row.created_at, updatedAt: row.updated_at,
|
|
238
|
+
...metadata,
|
|
239
|
+
ownerId: row.owner_id,
|
|
240
|
+
storageScopeId: row.storage_scope_id,
|
|
241
|
+
isPublic: accessMode !== 'restricted',
|
|
242
|
+
accessMode,
|
|
243
|
+
withdrawn: row.lifecycle_state === 'withdrawn',
|
|
244
|
+
grants: grants.rows.map((grant) => ({ principalId: grant.principal_id, grant: grant.permission,
|
|
245
|
+
createdAt: grant.created_at })),
|
|
246
|
+
...(Object.keys(metadata).length === 0 ? {} : { metadata }),
|
|
247
|
+
};
|
|
248
|
+
},
|
|
249
|
+
async putArtifactAcl(artifactId, acl) {
|
|
250
|
+
// G1: write access_mode; is_public stays as its projection (never forced false).
|
|
251
|
+
const accessMode = acl.accessMode ?? (acl.isPublic ? 'platform' : 'restricted');
|
|
252
|
+
await writer.tx(() => {
|
|
253
|
+
runQuery(db, `UPDATE artifacts SET access_mode = $2, is_public = ($2 <> 'restricted'), metadata = $4,
|
|
254
|
+
lifecycle_state = CASE WHEN $3 <> 0 THEN 'withdrawn'
|
|
255
|
+
WHEN lifecycle_state = 'withdrawn' THEN 'active'
|
|
256
|
+
ELSE lifecycle_state END
|
|
257
|
+
WHERE id = $1`, [artifactId, accessMode, acl.withdrawn ? 1 : 0, JSON.stringify(acl.metadata ?? {})]);
|
|
258
|
+
runQuery(db, 'DELETE FROM artifact_access WHERE artifact_id = $1', [artifactId]);
|
|
259
|
+
for (const grant of acl.grants) {
|
|
260
|
+
// Q1 schema invariant: a source grant exists only in restricted mode. A
|
|
261
|
+
// legacy platform/public artifact may still carry one; rewriting its ACL
|
|
262
|
+
// must not trip the source guard on re-insert, so the stale source grant
|
|
263
|
+
// is demoted to read — the grant row is kept, never dropped.
|
|
264
|
+
const permission = grant.grant === 'source' && accessMode !== 'restricted' ? 'read' : grant.grant;
|
|
265
|
+
runQuery(db, 'INSERT INTO artifact_access (artifact_id, principal_id, permission, created_at) VALUES ($1, $2, $3, COALESCE($4, strftime(\'%Y-%m-%dT%H:%M:%fZ\', \'now\')))', [artifactId, grant.principalId, permission, grant.createdAt ?? null]);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
},
|
|
269
|
+
async listArtifactIds() {
|
|
270
|
+
const { rows } = runQuery(db, 'SELECT id FROM artifacts ORDER BY created_at ASC, id ASC');
|
|
271
|
+
return rows.map((row) => row.id);
|
|
272
|
+
},
|
|
273
|
+
async getSource(artifactId) {
|
|
274
|
+
const { rows } = runQuery(db, 'SELECT kind, commit_tx, steps FROM artifact_sources WHERE artifact_id = $1', [artifactId]);
|
|
275
|
+
const row = rows[0];
|
|
276
|
+
if (row === undefined)
|
|
277
|
+
return undefined;
|
|
278
|
+
if (row.kind === 'inline-original')
|
|
279
|
+
return { kind: 'inline-original' };
|
|
280
|
+
if (row.kind === 'base-commit')
|
|
281
|
+
return { kind: 'base-commit', commit: row.commit_tx ?? '' };
|
|
282
|
+
if (row.kind === 'recipe') {
|
|
283
|
+
const steps = row.steps === null ? [] : JSON.parse(row.steps);
|
|
284
|
+
return { kind: 'recipe', steps: Array.isArray(steps) ? steps.map((step) => String(step)) : [] };
|
|
285
|
+
}
|
|
286
|
+
throw new Error(`unknown source kind: ${row.kind}`);
|
|
287
|
+
},
|
|
288
|
+
async putSource(artifactId, source) {
|
|
289
|
+
await writer.run(() => {
|
|
290
|
+
const commit = source.kind === 'base-commit' ? source.commit : null;
|
|
291
|
+
const steps = source.kind === 'recipe' ? JSON.stringify(source.steps) : null;
|
|
292
|
+
runQuery(db, `INSERT INTO artifact_sources (artifact_id, kind, commit_tx, steps) VALUES ($1, $2, $3, $4)
|
|
293
|
+
ON CONFLICT (artifact_id) DO UPDATE SET kind = excluded.kind, commit_tx = excluded.commit_tx, steps = excluded.steps`, [artifactId, source.kind, commit, steps]);
|
|
294
|
+
});
|
|
295
|
+
},
|
|
296
|
+
async register(artifactId, ownerId) {
|
|
297
|
+
const { rows } = runQuery(db, 'SELECT owner_id FROM artifacts WHERE id = $1', [artifactId]);
|
|
298
|
+
const row = rows[0];
|
|
299
|
+
if (row === undefined)
|
|
300
|
+
throw new Error(`unknown artifact: ${artifactId}`);
|
|
301
|
+
if (row.owner_id !== ownerId)
|
|
302
|
+
throw new Error(`owner mismatch for ${artifactId}`);
|
|
303
|
+
},
|
|
304
|
+
async getOwner(artifactId) {
|
|
305
|
+
const { rows } = runQuery(db, 'SELECT owner_id FROM artifacts WHERE id = $1', [artifactId]);
|
|
306
|
+
return rows[0]?.owner_id;
|
|
307
|
+
},
|
|
308
|
+
async getArtifactState(artifactId) {
|
|
309
|
+
const { rows } = runQuery(db, 'SELECT lifecycle_state FROM artifacts WHERE id = $1', [artifactId]);
|
|
310
|
+
return rows[0]?.lifecycle_state ?? 'active';
|
|
311
|
+
},
|
|
312
|
+
async isTerminal(artifactId) {
|
|
313
|
+
const { rows } = runQuery(db, 'SELECT terminal_deleted_at IS NOT NULL AS terminal FROM artifacts WHERE id = $1', [artifactId]);
|
|
314
|
+
return rows[0]?.terminal === 1;
|
|
315
|
+
},
|
|
316
|
+
async markTerminal(artifactId) {
|
|
317
|
+
await writer.run(() => {
|
|
318
|
+
// pg markTerminal ignores unknown artifacts (no rowCount check).
|
|
319
|
+
const { rows } = runQuery(db, 'SELECT lifecycle_state, renewed_at, terminal_deleted_at FROM artifacts WHERE id = $1', [artifactId]);
|
|
320
|
+
const row = rows[0];
|
|
321
|
+
if (row === undefined)
|
|
322
|
+
return;
|
|
323
|
+
assertRestorable(row, 'deleted', row.renewed_at);
|
|
324
|
+
runQuery(db, `UPDATE artifacts SET terminal_deleted_at = COALESCE(terminal_deleted_at, $2), lifecycle_state = 'deleted' WHERE id = $1`, [artifactId, nowIso()]);
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
async setArtifactState(artifactId, state) {
|
|
328
|
+
await writer.run(() => {
|
|
329
|
+
const row = artifactRow(db, artifactId);
|
|
330
|
+
assertRestorable(row, state, row.renewed_at);
|
|
331
|
+
const { rowCount } = runQuery(db, 'UPDATE artifacts SET lifecycle_state = $2 WHERE id = $1', [artifactId, state]);
|
|
332
|
+
if (rowCount === 0)
|
|
333
|
+
throw new Error(`unknown artifact: ${artifactId}`);
|
|
334
|
+
});
|
|
335
|
+
},
|
|
336
|
+
async getRenewedAt(artifactId) {
|
|
337
|
+
const { rows } = runQuery(db, 'SELECT renewed_at FROM artifacts WHERE id = $1', [artifactId]);
|
|
338
|
+
return rows[0]?.renewed_at ?? undefined;
|
|
339
|
+
},
|
|
340
|
+
async setRenewedAt(artifactId, renewedAt) {
|
|
341
|
+
await writer.run(() => {
|
|
342
|
+
const row = artifactRow(db, artifactId);
|
|
343
|
+
assertRestorable(row, row.lifecycle_state, renewedAt);
|
|
344
|
+
const { rowCount } = runQuery(db, 'UPDATE artifacts SET renewed_at = $2 WHERE id = $1', [artifactId, renewedAt]);
|
|
345
|
+
if (rowCount === 0)
|
|
346
|
+
throw new Error(`unknown artifact: ${artifactId}`);
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
async addRelease(artifactId, releaseId) {
|
|
350
|
+
await writer.run(() => {
|
|
351
|
+
const artifact = runQuery(db, 'SELECT id FROM artifacts WHERE id = $1', [artifactId]);
|
|
352
|
+
if (artifact.rows.length === 0)
|
|
353
|
+
throw new Error(`unknown artifact: ${artifactId}`);
|
|
354
|
+
const release = runQuery(db, 'SELECT id FROM releases WHERE id = $1', [releaseId]);
|
|
355
|
+
if (release.rows.length === 0)
|
|
356
|
+
throw new Error(`unknown release: ${releaseId}`);
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
async listArtifactReleases(artifactId) {
|
|
360
|
+
const { rows } = runQuery(db, 'SELECT id FROM releases WHERE artifact_id = $1 ORDER BY created_at, id', [artifactId]);
|
|
361
|
+
return rows.map((row) => row.id);
|
|
362
|
+
},
|
|
363
|
+
async getReleaseState(releaseId) {
|
|
364
|
+
const { rows } = runQuery(db, 'SELECT state FROM releases WHERE id = $1', [releaseId]);
|
|
365
|
+
return rows[0]?.state ?? 'ready';
|
|
366
|
+
},
|
|
367
|
+
async setReleaseState(releaseId, state) {
|
|
368
|
+
await writer.run(() => {
|
|
369
|
+
const { rowCount } = runQuery(db, 'UPDATE releases SET state = $2 WHERE id = $1', [releaseId, state]);
|
|
370
|
+
if (rowCount === 0)
|
|
371
|
+
throw new Error(`unknown release: ${releaseId}`);
|
|
372
|
+
});
|
|
373
|
+
},
|
|
374
|
+
async addRef(digest, holder) {
|
|
375
|
+
await writer.run(() => {
|
|
376
|
+
runQuery(db, 'INSERT INTO blob_ref_holders (digest, holder) VALUES ($1, $2) ON CONFLICT (digest, holder) DO NOTHING', [digest, holder]);
|
|
377
|
+
});
|
|
378
|
+
},
|
|
379
|
+
async releaseRef(digest, holder) {
|
|
380
|
+
await writer.run(() => {
|
|
381
|
+
const { rowCount } = runQuery(db, 'DELETE FROM blob_ref_holders WHERE digest = $1 AND holder = $2', [digest, holder]);
|
|
382
|
+
if (rowCount === 0)
|
|
383
|
+
throw new Error(`refcount not held: ${digest} by ${holder}`);
|
|
384
|
+
});
|
|
385
|
+
},
|
|
386
|
+
async pin(digest, reason) {
|
|
387
|
+
await writer.run(() => {
|
|
388
|
+
const inserted = runQuery(db, 'INSERT INTO blob_pins (digest, reason) VALUES ($1, $2) ON CONFLICT (digest, reason) DO NOTHING RETURNING digest', [digest, reason]);
|
|
389
|
+
if (inserted.rowCount === 0)
|
|
390
|
+
throw new Error(`duplicate pin: ${digest} (${reason})`);
|
|
391
|
+
});
|
|
392
|
+
},
|
|
393
|
+
async unpin(digest, reason) {
|
|
394
|
+
await writer.run(() => {
|
|
395
|
+
const { rowCount } = runQuery(db, 'DELETE FROM blob_pins WHERE digest = $1 AND reason = $2', [digest, reason]);
|
|
396
|
+
if (rowCount === 0)
|
|
397
|
+
throw new Error(`not pinned: ${digest} (${reason})`);
|
|
398
|
+
});
|
|
399
|
+
},
|
|
400
|
+
async count(digest) {
|
|
401
|
+
const { rows } = runQuery(db, 'SELECT COUNT(*) AS total FROM blob_ref_holders WHERE digest = $1', [digest]);
|
|
402
|
+
return Number(rows[0]?.total ?? 0);
|
|
403
|
+
},
|
|
404
|
+
async isPinned(digest) {
|
|
405
|
+
const { rows } = runQuery(db, 'SELECT EXISTS (SELECT 1 FROM blob_pins WHERE digest = $1) AS found', [digest]);
|
|
406
|
+
return rows[0]?.found === 1;
|
|
407
|
+
},
|
|
408
|
+
};
|
|
409
|
+
return store;
|
|
410
|
+
}
|