Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

database.ts

315 lines11.0 KB

1// @effect-diagnostics cryptoRandomUUID:off globalConsole:off - vendored upstream protocol, not an Effect service.
2import { HttpError, unavailable } from './errors.ts';
3import { GRACE_SECONDS, LEASE_SECONDS } from './limits.ts';
4import { measured, type Observations } from './observations.ts';
5​
6export interface Scope {
7 scope_id: string;
8 endpoint: string;
9 repository_id: string;
10 repository_owner_id: string;
11 branch: string;
12 policy_version: number;
13 writes_enabled: number;
14 // 1 when `pull_request` runs whose PR targets `branch` may also publish.
15 pull_requests: number;
17export interface Generation {
18 generation_id: string;
19 scope_id: string;
20 value_object: string;
21 blob_object: string;
22 blob_id: string | null;
23 value_size: number;
24 blob_size: number;
26export interface Selection extends Generation {
27 kind: 'exact' | 'fallback';
28 key: number[];
30export type Entries =
31 | { kind: 'exact'; entries: Generation[] }
32 | { kind: 'fallback'; key: Uint8Array }
33 | null;
34​
35// Preserve empty and non-UTF-8 keys as BLOBs, without text or hash conversions.
36export function binary(bytes: Uint8Array): ArrayBuffer {
37 return bytes.slice().buffer;
39​
40export async function getScope(db: D1Database, id: string, stats?: Observations): Promise<Scope> {
41 let scope: Scope | null;
42 try {
43 const { results } = await measured(
44 db
45 .prepare(`SELECT s.*, (s.writes_enabled AND d.writes_enabled) AS writes_enabled
46 FROM scopes s, deployment d WHERE s.scope_id = ? AND s.enabled = 1 AND d.enabled = 1`)
47 .bind(id)
48 .all<Scope>(),
49 stats,
50 );
51 scope = results[0] ?? null;
52 } catch {
53 unavailable();
54 }
55 if (!scope) throw new HttpError(404, 'unknown_scope');
56 return scope;
58​
59export async function selectEntries(
60 db: D1Database,
61 scope: string,
62 key: Uint8Array,
63 secondary: Uint8Array,
64 stats?: Observations,
65): Promise<Entries> {
66 // One statement reads the key's newest live entries and the association in one SQLite snapshot.
67 // The association is used only when the key has no live entry.
68 let results: Selection[];
69 try {
70 ({ results } = await measured(
71 db
72 .prepare(`
73 SELECT * FROM (
74 SELECT g.*, e.key, 'exact' AS kind, 0 AS priority, e.seq
75 FROM entries e JOIN generations g ON g.generation_id = e.generation_id
76 JOIN scopes s ON s.scope_id = e.scope_id CROSS JOIN deployment d
77 WHERE e.scope_id = ?1 AND e.key = ?2 AND g.state = 'ready' AND g.expires_at > unixepoch()
78 AND s.enabled = 1 AND d.enabled = 1
79 ORDER BY e.seq DESC
80 LIMIT (SELECT entries_per_key FROM scopes WHERE scope_id = ?1))
81 UNION ALL
82 SELECT * FROM (
83 SELECT g.*, e.key, 'fallback' AS kind, 1 AS priority, e.seq
84 FROM associations a JOIN entries e ON e.scope_id = a.scope_id AND e.key = a.target_key
85 JOIN generations g ON g.generation_id = e.generation_id
86 JOIN scopes s ON s.scope_id = e.scope_id CROSS JOIN deployment d
87 WHERE a.scope_id = ?1 AND a.secondary_key = ?3 AND g.state = 'ready' AND g.expires_at > unixepoch()
88 AND s.enabled = 1 AND d.enabled = 1
89 LIMIT 1)
90 ORDER BY priority, seq DESC`)
91 .bind(scope, binary(key), binary(secondary))
92 .all<Selection>(),
93 stats,
94 ));
95 } catch {
96 unavailable();
97 }
98 const exact = results.filter((row) => row.kind === 'exact');
99 if (exact.length) return { kind: 'exact', entries: exact };
100 const fallback = results[0];
101 return fallback ? { kind: 'fallback', key: new Uint8Array(fallback.key) } : null;
103​
104export async function selectBlob(
105 db: D1Database,
106 scope: string,
107 blob: string,
108 stats?: Observations,
109): Promise<Generation | null> {
110 try {
111 const { results } = await measured(
112 db
113 .prepare(`SELECT g.* FROM generations g JOIN scopes s ON s.scope_id = g.scope_id CROSS JOIN deployment d
114 WHERE g.scope_id = ? AND g.blob_id = ? AND s.enabled = 1 AND d.enabled = 1
115 AND ((g.state = 'ready' AND g.expires_at > unixepoch()) OR (g.state = 'retired' AND g.gc_after > unixepoch()))`)
116 .bind(scope, blob)
117 .all<Generation>(),
118 stats,
119 );
120 return results[0] ?? null;
121 } catch {
122 unavailable();
123 }
125​
126export async function reserve(
127 db: D1Database,
128 scope: Scope,
129 tokenExp: number,
130 bytes: number,
131 stats?: Observations,
132): Promise<Generation> {
133 const id = crypto.randomUUID();
134 const prefix = `${scope.scope_id}/${id}`;
135 try {
136 await measured(
137 db
138 .prepare(`INSERT INTO generations
139 (generation_id, scope_id, state, policy_version, token_exp, lease_until, gc_after, value_object, blob_object, charged_bytes)
140 VALUES (?, ?, 'uploading', ?, ?, unixepoch() + ?, unixepoch() + ?, ?, ?, ?)`)
141 .bind(
142 id,
143 scope.scope_id,
144 scope.policy_version,
145 tokenExp,
146 LEASE_SECONDS,
147 LEASE_SECONDS + GRACE_SECONDS,
148 `${prefix}/value`,
149 `${prefix}/blob`,
150 bytes,
151 )
152 .run(),
153 stats,
154 );
155 } catch {
156 unavailable();
157 }
158 return {
159 generation_id: id,
160 scope_id: scope.scope_id,
161 value_object: `${prefix}/value`,
162 blob_object: `${prefix}/blob`,
163 blob_id: null,
164 value_size: 0,
165 blob_size: 0,
166 };
168​
169export async function recordMultipart(
170 db: D1Database,
171 generation: Generation,
172 uploadId: string,
173 stats?: Observations,
174): Promise<void> {
175 const result = await measured(
176 db
177 .prepare(
178 `UPDATE generations SET upload_id = ? WHERE generation_id = ? AND state = 'uploading' AND lease_until > unixepoch()`,
179 )
180 .bind(uploadId, generation.generation_id)
181 .run(),
182 stats,
183 );
184 if (result.meta.changes !== 1) unavailable();
186​
187export async function publish(
188 db: D1Database,
189 generation: Generation,
190 key: Uint8Array,
191 secondary: Uint8Array,
192 stats?: Observations,
193): Promise<void> {
194 const actual = generation.value_size + generation.blob_size;
195 let results: D1Result[];
196 try {
197 results = await measured(
198 db.batch([
199 db
200 .prepare(`UPDATE generations SET state = 'ready', key = ?, secondary_key = ?, blob_id = ?,
201 value_size = ?, blob_size = ?, charged_bytes = ?, upload_id = NULL,
202 expires_at = unixepoch() + (SELECT retention_seconds FROM scopes WHERE scope_id = generations.scope_id),
203 gc_after = unixepoch() + (SELECT retention_seconds FROM scopes WHERE scope_id = generations.scope_id)
204 WHERE generation_id = ? AND state = 'uploading' AND lease_until > unixepoch() AND token_exp > unixepoch()
205 AND charged_bytes >= ? AND EXISTS (
206 SELECT 1 FROM scopes s, deployment d WHERE s.scope_id = generations.scope_id
207 AND s.policy_version = generations.policy_version AND s.enabled = 1 AND s.writes_enabled = 1
208 AND d.enabled = 1 AND d.writes_enabled = 1 AND s.charged_bytes <= s.byte_limit AND d.charged_bytes <= d.byte_limit
209 ) RETURNING generation_id`)
210 .bind(
211 binary(key),
212 binary(secondary),
213 generation.blob_id,
214 generation.value_size,
215 generation.blob_size,
216 actual,
217 generation.generation_id,
218 actual,
219 ),
220 ]),
221 stats,
222 );
223 } catch {
224 unavailable();
225 }
226 if (results[0]?.results.length !== 1) throw new HttpError(503, 'publication_guard');
228​
229export async function abandon(db: D1Database, id: string): Promise<void> {
230 // Keep charges during the grace period for R2 operations that finish late.
231 await db
232 .prepare(`UPDATE generations SET lease_until = min(lease_until, unixepoch()), gc_after = min(gc_after, unixepoch() + ?)
233 WHERE generation_id = ? AND state = 'uploading'`)
234 .bind(GRACE_SECONDS, id)
235 .run();
237​
238// R2 binding errors read "<operation>: <message> (<code>)". Code 10024 (NoSuchUpload) means the
239// multipart upload no longer exists.
240function uploadGone(error: unknown): boolean {
241 return error instanceof Error && error.message.endsWith('(10024)');
243​
244export async function cleanup(env: Env): Promise<void> {
245 const limit = Number(env.GC_BATCH_SIZE);
246 if (!Number.isInteger(limit) || limit < 1 || limit > 256)
247 throw new Error('Invalid GC batch size');
248 const claim = crypto.randomUUID();
249 const claimed =
250 await env.INDEX.prepare(`UPDATE generations SET state = 'deleting', gc_claim = ?, gc_after = unixepoch() + 600
251 WHERE generation_id IN (SELECT generation_id FROM generations WHERE gc_after <= unixepoch() ORDER BY gc_after LIMIT ?)
252 RETURNING generation_id, value_object, blob_object, upload_id`)
253 .bind(claim, limit)
254 .all<{
255 generation_id: string;
256 value_object: string;
257 blob_object: string;
258 upload_id: string | null;
259 }>();
260 let deleted = 0;
261 for (const generation of claimed.results) {
262 try {
263 // A recorded upload may already be complete, aborted, or gone: R2 doesn't check that a
264 // resumed upload still exists. Only an error that confirms this lets deletion go on. Any
265 // other failure keeps the generation, its charge, and its upload ID for the next retry.
266 if (generation.upload_id)
267 await env.ARTIFACTS.resumeMultipartUpload(generation.blob_object, generation.upload_id)
268 .abort()
269 .catch((error: unknown) => {
270 if (!uploadGone(error)) throw error;
271 });
272 await env.ARTIFACTS.delete([generation.value_object, generation.blob_object]);
273 // FK deletion only removes entries still selecting this generation.
274 await env.INDEX.prepare(
275 `DELETE FROM generations WHERE generation_id = ? AND state = 'deleting' AND gc_claim = ?`,
276 )
277 .bind(generation.generation_id, claim)
278 .run();
279 deleted++;
280 } catch {
281 console.warn(
282 JSON.stringify({
283 operation: 'cleanup',
284 error: 'deletion_failed',
285 generation: generation.generation_id,
286 }),
287 );
288 }
289 }
290 await cleanAssociations(env.INDEX, limit);
291 console.log(JSON.stringify({ operation: 'cleanup', claimed: claimed.results.length, deleted }));
293​
294async function cleanAssociations(db: D1Database, limit: number): Promise<void> {
295 // Cursor bounds scanning as well as deletion, even when all associations are live.
296 const batch = await db
297 .prepare(`SELECT scope_id, secondary_key FROM associations
298 WHERE (scope_id, secondary_key) > (SELECT scope_id, secondary_key FROM maintenance WHERE id = 1)
299 ORDER BY scope_id, secondary_key LIMIT ?`)
300 .bind(limit)
301 .all<{ scope_id: string; secondary_key: number[] }>();
302 const last = batch.results.at(-1);
303 await db.batch([
304 db
305 .prepare(`DELETE FROM associations WHERE (scope_id, secondary_key) IN (
306 SELECT scope_id, secondary_key FROM associations
307 WHERE (scope_id, secondary_key) > (SELECT scope_id, secondary_key FROM maintenance WHERE id = 1)
308 ORDER BY scope_id, secondary_key LIMIT ?)
309 AND NOT EXISTS (SELECT 1 FROM entries e WHERE e.scope_id = associations.scope_id AND e.key = associations.target_key)`)
310 .bind(limit),
311 db
312 .prepare('UPDATE maintenance SET scope_id = ?, secondary_key = ? WHERE id = 1')
313 .bind(last?.scope_id ?? '', binary(new Uint8Array(last?.secondary_key ?? []))),
314 ]);