@sentropic/artifacts 0.2.12 → 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 +93 -0
- package/README.md +45 -10
- package/dist/adapters/local-blob.d.ts +3 -0
- package/dist/adapters/local-blob.js +93 -0
- package/dist/adapters/postgres-management.js +3 -2
- package/dist/adapters/postgres-reader-consent.d.ts +11 -0
- package/dist/adapters/postgres-reader-consent.js +109 -0
- package/dist/adapters/postgres-uploads.d.ts +14 -0
- package/dist/adapters/postgres-uploads.js +174 -0
- package/dist/adapters/postgres.js +4 -3
- package/dist/adapters/s3-uploads.d.ts +33 -0
- package/dist/adapters/s3-uploads.js +105 -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/content/headers.js +12 -0
- package/dist/http.d.ts +32 -2
- package/dist/http.js +615 -13
- package/dist/mcp-core.d.ts +3 -3
- package/dist/mcp-core.js +90 -4
- package/dist/profile/contracts.d.ts +1 -1
- package/dist/profile/contracts.js +7 -0
- package/dist/profile/index.js +43 -2
- package/dist/profile/radar.js +7 -0
- package/dist/profile/schemas.js +119 -0
- package/dist/profile/validation.d.ts +11 -0
- package/dist/profile/validation.js +98 -6
- package/dist/server/access.d.ts +2 -0
- package/dist/server/command-identity.d.ts +1 -1
- package/dist/server/command-identity.js +6 -3
- package/dist/server/consent.d.ts +65 -0
- package/dist/server/consent.js +42 -0
- package/dist/server/gc.d.ts +42 -0
- package/dist/server/gc.js +98 -0
- package/dist/server/management.d.ts +3 -1
- package/dist/server/management.js +48 -7
- package/dist/server/metrics.d.ts +21 -0
- package/dist/server/metrics.js +6 -0
- package/dist/server/mime.d.ts +26 -2
- package/dist/server/mime.js +124 -2
- package/dist/server/ports.d.ts +29 -0
- package/dist/server/ports.js +11 -0
- package/dist/server/publication-limits.d.ts +20 -0
- package/dist/server/publication-limits.js +27 -1
- package/dist/server/publication.d.ts +14 -0
- package/dist/server/publication.js +10 -2
- package/dist/server/reader-store.d.ts +58 -0
- package/dist/server/reader-store.js +109 -0
- package/dist/server/source-read.d.ts +12 -9
- package/dist/server/source-read.js +17 -5
- package/dist/server/templates.js +50 -2
- package/dist/server/upload-page.d.ts +157 -0
- package/dist/server/upload-page.js +438 -0
- package/dist/server/uploads.d.ts +229 -19
- package/dist/server/uploads.js +387 -80
- package/migrations/0007_uploads.sql +43 -0
- package/migrations/0008_reader_consent.sql +48 -0
- package/migrations/0009_upload_pages.sql +25 -0
- package/package.json +34 -1
- package/sql/reader-consent.sql +47 -0
- package/sql/sqlite/0001_artifacts.sql +156 -0
- package/sql/sqlite/0002_activation.sql +73 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CommitExecutor } from '../server/commit/types.js';
|
|
2
|
+
import type { PostgresArtifactStore } from './postgres.js';
|
|
3
|
+
import type { SqliteDatabase } from './sqlite-sql.js';
|
|
4
|
+
export type { SqliteDatabase, SqliteStatement } from './sqlite-sql.js';
|
|
5
|
+
export { normalizeSql, runQuery } from './sqlite-sql.js';
|
|
6
|
+
/** Serialized writer over the single connection (async mutex, not reentrant). */
|
|
7
|
+
export interface SqliteWriter {
|
|
8
|
+
/** Run work holding the writer; concurrent callers queue behind it. */
|
|
9
|
+
run<T>(work: () => T): Promise<T>;
|
|
10
|
+
/** run + BEGIN IMMEDIATE … COMMIT (ROLLBACK on throw): one atomic unit. */
|
|
11
|
+
tx<T>(work: () => T): Promise<T>;
|
|
12
|
+
/** Acquire the writer across awaits; the returned function releases it. */
|
|
13
|
+
acquire(): Promise<() => void>;
|
|
14
|
+
}
|
|
15
|
+
/** Open (creating if needed) a durable local database file and apply the DDL. */
|
|
16
|
+
export declare function openSqliteDatabase(path: string): SqliteDatabase;
|
|
17
|
+
/** Create the serialized writer over one database connection. */
|
|
18
|
+
export declare function createSqliteWriter(db: SqliteDatabase): SqliteWriter;
|
|
19
|
+
export type SqliteArtifactStore = PostgresArtifactStore;
|
|
20
|
+
import { createSqliteArtifactStore } from './sqlite-store.js';
|
|
21
|
+
import { createSqliteCommitExecutor } from './sqlite-commit.js';
|
|
22
|
+
export { createSqliteArtifactStore, createSqliteCommitExecutor };
|
|
23
|
+
export { createSqliteManagementUnit } from './sqlite-management.js';
|
|
24
|
+
export { createSqliteActivationStore, type SqliteActivationStore } from './sqlite-activation.js';
|
|
25
|
+
export { createLocalBlobStore } from './local-blob.js';
|
|
26
|
+
/** One-call wiring: open a file, create the writer, build store + executor. */
|
|
27
|
+
export declare function openSqliteArtifacts(path: string): {
|
|
28
|
+
db: SqliteDatabase;
|
|
29
|
+
writer: SqliteWriter;
|
|
30
|
+
store: SqliteArtifactStore;
|
|
31
|
+
executor: CommitExecutor;
|
|
32
|
+
close(): void;
|
|
33
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* U1 — local SQLite adapter set, entry point (`@sentropic/artifacts/sqlite`).
|
|
3
|
+
*
|
|
4
|
+
* Durable local equivalent of the Postgres adapters, over the repo-standard
|
|
5
|
+
* `node:sqlite` driver (same driver as cluster-mesh identity; no new native
|
|
6
|
+
* dependency). One connection per database file plus one serialized writer:
|
|
7
|
+
* every mutation runs through `SqliteWriter`, and multi-statement units run
|
|
8
|
+
* inside a single `BEGIN IMMEDIATE` transaction. SQLite then serializes
|
|
9
|
+
* writers — stronger isolation than the Postgres READ COMMITTED units, with
|
|
10
|
+
* the same observable port behaviour; there is no second behaviour. The
|
|
11
|
+
* 0004 terminal guards are enforced in adapter code because all writes are
|
|
12
|
+
* serialized (check-then-write is atomic). The root and portable entries
|
|
13
|
+
* never import this module: only the `./sqlite` subpath pulls in node:sqlite.
|
|
14
|
+
*
|
|
15
|
+
* Schema mapping: SQLite has no schemas, so Postgres `artifacts.<t>` /
|
|
16
|
+
* `artifact_host.<t>` map to plain `<t>` in the single file (DDL owned by
|
|
17
|
+
* this adapter: sql/sqlite/0001_artifacts.sql, sql/sqlite/0002_activation.sql).
|
|
18
|
+
*/
|
|
19
|
+
import { readFileSync } from 'node:fs';
|
|
20
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
21
|
+
export { normalizeSql, runQuery } from './sqlite-sql.js';
|
|
22
|
+
const DDL_ARTIFACTS = readFileSync(new URL('../../sql/sqlite/0001_artifacts.sql', import.meta.url), 'utf8');
|
|
23
|
+
const DDL_ACTIVATION = readFileSync(new URL('../../sql/sqlite/0002_activation.sql', import.meta.url), 'utf8');
|
|
24
|
+
/** Open (creating if needed) a durable local database file and apply the DDL. */
|
|
25
|
+
export function openSqliteDatabase(path) {
|
|
26
|
+
const db = new DatabaseSync(path);
|
|
27
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
28
|
+
db.exec('PRAGMA synchronous = FULL');
|
|
29
|
+
db.exec('PRAGMA foreign_keys = ON');
|
|
30
|
+
db.exec(DDL_ARTIFACTS);
|
|
31
|
+
db.exec(DDL_ACTIVATION);
|
|
32
|
+
return db;
|
|
33
|
+
}
|
|
34
|
+
/** Create the serialized writer over one database connection. */
|
|
35
|
+
export function createSqliteWriter(db) {
|
|
36
|
+
let tail = Promise.resolve();
|
|
37
|
+
const acquire = () => {
|
|
38
|
+
let release;
|
|
39
|
+
const gate = new Promise((resolve) => { release = resolve; });
|
|
40
|
+
const previous = tail;
|
|
41
|
+
tail = previous.then(() => gate);
|
|
42
|
+
return previous.then(() => release);
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
acquire,
|
|
46
|
+
async run(work) {
|
|
47
|
+
const release = await acquire();
|
|
48
|
+
try {
|
|
49
|
+
return work();
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
release();
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
async tx(work) {
|
|
56
|
+
const release = await acquire();
|
|
57
|
+
try {
|
|
58
|
+
db.exec('BEGIN IMMEDIATE');
|
|
59
|
+
try {
|
|
60
|
+
const result = work();
|
|
61
|
+
db.exec('COMMIT');
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
try {
|
|
66
|
+
db.exec('ROLLBACK');
|
|
67
|
+
}
|
|
68
|
+
catch { /* transaction already gone */ }
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
release();
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
import { createSqliteArtifactStore } from './sqlite-store.js';
|
|
79
|
+
import { createSqliteCommitExecutor } from './sqlite-commit.js';
|
|
80
|
+
export { createSqliteArtifactStore, createSqliteCommitExecutor };
|
|
81
|
+
export { createSqliteManagementUnit } from './sqlite-management.js';
|
|
82
|
+
export { createSqliteActivationStore } from './sqlite-activation.js';
|
|
83
|
+
export { createLocalBlobStore } from './local-blob.js';
|
|
84
|
+
/** One-call wiring: open a file, create the writer, build store + executor. */
|
|
85
|
+
export function openSqliteArtifacts(path) {
|
|
86
|
+
const db = openSqliteDatabase(path);
|
|
87
|
+
const writer = createSqliteWriter(db);
|
|
88
|
+
return {
|
|
89
|
+
db,
|
|
90
|
+
writer,
|
|
91
|
+
store: createSqliteArtifactStore(db, writer),
|
|
92
|
+
executor: createSqliteCommitExecutor(db, writer),
|
|
93
|
+
close() { db.close(); },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AclStore } from '../server/access.js';
|
|
2
|
+
import type { ArtifactsMetrics } from '../server/metrics.js';
|
|
2
3
|
import type { LifecycleService } from '../server/lifecycle.js';
|
|
3
4
|
import { type SharingPolicyPort } from '../server/ports.js';
|
|
4
5
|
import type { PublicationBlobStore, PublicationService } from '../server/publication.js';
|
|
@@ -11,6 +12,8 @@ export interface ContentRequest {
|
|
|
11
12
|
actorId?: string;
|
|
12
13
|
cookie?: string;
|
|
13
14
|
ticket?: string;
|
|
15
|
+
/** Raw HTTP Range header, mapped by the host; absent ⇒ whole file. */
|
|
16
|
+
range?: string;
|
|
14
17
|
}
|
|
15
18
|
export interface ContentResponse {
|
|
16
19
|
status: number;
|
|
@@ -26,6 +29,8 @@ export interface ContentHandlerDeps {
|
|
|
26
29
|
grants: GrantSigner;
|
|
27
30
|
tickets: TicketService;
|
|
28
31
|
baseDomain: string;
|
|
32
|
+
/** LOT 2 §D.3: `content_range_requests {result}`; absent ⇒ no-op. */
|
|
33
|
+
metrics?: ArtifactsMetrics;
|
|
29
34
|
isApprovedAccount?: (principalId: string) => boolean | Promise<boolean>;
|
|
30
35
|
/** G1 lock 2 (runtime): sharing policy per scope, fail-closed when absent. */
|
|
31
36
|
sharingPolicy?: SharingPolicyPort;
|