|
| 1 | +export const EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE = "exact_review_artifact_receipts"; |
| 2 | +const EXACT_REVIEW_ARTIFACT_CACHE_META_TABLE = "exact_review_artifact_cache_meta"; |
| 3 | +export const EXACT_REVIEW_ARTIFACT_CACHE_PREFIX = "artifacts/exact-review/v1/"; |
| 4 | +export const EXACT_REVIEW_ARTIFACT_RECEIPT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; |
| 5 | + |
| 6 | +const DIGEST_PATTERN = /^[0-9a-f]{64}$/; |
| 7 | +const ITEM_KEY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#\d+$/; |
| 8 | +const ARTIFACT_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,200}$/; |
| 9 | +const CLEANUP_LIMIT = 128; |
| 10 | + |
| 11 | +type SqlRow = Record<string, unknown>; |
| 12 | +type ArtifactReceiptStorage = { |
| 13 | + sql: { exec: (query: string, ...bindings: unknown[]) => Iterable<SqlRow> }; |
| 14 | + transactionSync: <T>(callback: () => T) => T; |
| 15 | +}; |
| 16 | + |
| 17 | +type ArtifactR2Object = { |
| 18 | + key: string; |
| 19 | + size: number; |
| 20 | + uploaded?: Date; |
| 21 | + customMetadata?: Record<string, string>; |
| 22 | +}; |
| 23 | + |
| 24 | +type ArtifactR2Bucket = { |
| 25 | + head: (key: string) => Promise<ArtifactR2Object | null>; |
| 26 | + list: (options: { |
| 27 | + prefix: string; |
| 28 | + cursor?: string; |
| 29 | + limit: number; |
| 30 | + include: string[]; |
| 31 | + }) => Promise<{ objects: ArtifactR2Object[]; truncated: boolean; cursor?: string }>; |
| 32 | + delete: (key: string) => Promise<void>; |
| 33 | +}; |
| 34 | + |
| 35 | +export type ExactReviewArtifactReceiptTuple = { |
| 36 | + producerRunId: string; |
| 37 | + producerRunAttempt: number; |
| 38 | + artifactName: string; |
| 39 | + canonicalItemKey: string; |
| 40 | + leaseRevision: number; |
| 41 | + protocolVersion: number; |
| 42 | +}; |
| 43 | + |
| 44 | +export type ExactReviewArtifactReceipt = ExactReviewArtifactReceiptTuple & { |
| 45 | + digest: string; |
| 46 | + bytes: number; |
| 47 | + objectKey: string; |
| 48 | + createdAt: number; |
| 49 | + expiresAt: number; |
| 50 | +}; |
| 51 | + |
| 52 | +export type ExactReviewArtifactReceiptStoreResult = |
| 53 | + | { ok: true; receipt: ExactReviewArtifactReceipt; deduped: boolean } |
| 54 | + | { ok: false; error: string; status: number }; |
| 55 | + |
| 56 | +export function exactReviewArtifactReceiptTuple( |
| 57 | + value: unknown, |
| 58 | +): ExactReviewArtifactReceiptTuple | null { |
| 59 | + const body = objectValue(value); |
| 60 | + const producerRunId = String(body.producer_run_id || "").trim(); |
| 61 | + const producerRunAttempt = Number(body.producer_run_attempt); |
| 62 | + const artifactName = String(body.artifact_name || "").trim(); |
| 63 | + const canonicalItemKey = String(body.canonical_item_key || "").trim(); |
| 64 | + const leaseRevision = Number(body.lease_revision); |
| 65 | + const protocolVersion = Number(body.protocol_version); |
| 66 | + if ( |
| 67 | + !/^\d+$/.test(producerRunId) || |
| 68 | + !Number.isSafeInteger(producerRunAttempt) || |
| 69 | + producerRunAttempt < 1 || |
| 70 | + !ARTIFACT_NAME_PATTERN.test(artifactName) || |
| 71 | + !ITEM_KEY_PATTERN.test(canonicalItemKey) || |
| 72 | + !Number.isSafeInteger(leaseRevision) || |
| 73 | + leaseRevision < 1 || |
| 74 | + !Number.isSafeInteger(protocolVersion) || |
| 75 | + protocolVersion < 1 |
| 76 | + ) { |
| 77 | + return null; |
| 78 | + } |
| 79 | + return { |
| 80 | + producerRunId, |
| 81 | + producerRunAttempt, |
| 82 | + artifactName, |
| 83 | + canonicalItemKey, |
| 84 | + leaseRevision, |
| 85 | + protocolVersion, |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +export function exactReviewArtifactObjectKey(digest: string): string | null { |
| 90 | + return DIGEST_PATTERN.test(digest) ? `${EXACT_REVIEW_ARTIFACT_CACHE_PREFIX}${digest}` : null; |
| 91 | +} |
| 92 | + |
| 93 | +export class ExactReviewArtifactReceiptStore { |
| 94 | + private readonly storage: ArtifactReceiptStorage; |
| 95 | + private readonly bucket: ArtifactR2Bucket | null; |
| 96 | + |
| 97 | + constructor(storage: ArtifactReceiptStorage, bucketBinding: unknown) { |
| 98 | + this.storage = storage; |
| 99 | + this.bucket = artifactBucket(bucketBinding); |
| 100 | + } |
| 101 | + |
| 102 | + ensureSchemaSync() { |
| 103 | + this.storage.sql.exec( |
| 104 | + `CREATE TABLE IF NOT EXISTS ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} ( |
| 105 | + producer_run_id TEXT NOT NULL, |
| 106 | + producer_run_attempt INTEGER NOT NULL CHECK (producer_run_attempt >= 1), |
| 107 | + artifact_name TEXT NOT NULL, |
| 108 | + canonical_item_key TEXT NOT NULL, |
| 109 | + lease_revision INTEGER NOT NULL CHECK (lease_revision >= 1), |
| 110 | + protocol_version INTEGER NOT NULL CHECK (protocol_version >= 1), |
| 111 | + digest TEXT NOT NULL, |
| 112 | + bytes INTEGER NOT NULL CHECK (bytes >= 1), |
| 113 | + object_key TEXT NOT NULL, |
| 114 | + created_at INTEGER NOT NULL, |
| 115 | + expires_at INTEGER NOT NULL, |
| 116 | + PRIMARY KEY ( |
| 117 | + producer_run_id, producer_run_attempt, artifact_name, |
| 118 | + canonical_item_key, lease_revision, protocol_version |
| 119 | + ) |
| 120 | + ) STRICT`, |
| 121 | + ); |
| 122 | + this.storage.sql.exec( |
| 123 | + `CREATE INDEX IF NOT EXISTS exact_review_artifact_receipts_expiry |
| 124 | + ON ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} (expires_at, digest)`, |
| 125 | + ); |
| 126 | + this.storage.sql.exec( |
| 127 | + `CREATE INDEX IF NOT EXISTS exact_review_artifact_receipts_digest_expiry |
| 128 | + ON ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} (digest, expires_at)`, |
| 129 | + ); |
| 130 | + this.storage.sql.exec( |
| 131 | + `CREATE TABLE IF NOT EXISTS ${EXACT_REVIEW_ARTIFACT_CACHE_META_TABLE} ( |
| 132 | + singleton_id INTEGER PRIMARY KEY CHECK (singleton_id = 1), |
| 133 | + prune_cursor TEXT |
| 134 | + ) STRICT`, |
| 135 | + ); |
| 136 | + this.storage.sql.exec( |
| 137 | + `INSERT OR IGNORE INTO ${EXACT_REVIEW_ARTIFACT_CACHE_META_TABLE} |
| 138 | + (singleton_id, prune_cursor) VALUES (1, NULL)`, |
| 139 | + ); |
| 140 | + } |
| 141 | + |
| 142 | + lookup(value: unknown, now: number): ExactReviewArtifactReceipt | null { |
| 143 | + const tuple = exactReviewArtifactReceiptTuple(value); |
| 144 | + if (!tuple) return null; |
| 145 | + this.deleteExpiredReceiptsSync(now); |
| 146 | + const row = firstRow( |
| 147 | + this.storage.sql.exec( |
| 148 | + `SELECT digest, bytes, object_key, created_at, expires_at |
| 149 | + FROM ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 150 | + WHERE producer_run_id = ? AND producer_run_attempt = ? AND artifact_name = ? |
| 151 | + AND canonical_item_key = ? AND lease_revision = ? AND protocol_version = ? |
| 152 | + AND expires_at > ?`, |
| 153 | + tuple.producerRunId, |
| 154 | + tuple.producerRunAttempt, |
| 155 | + tuple.artifactName, |
| 156 | + tuple.canonicalItemKey, |
| 157 | + tuple.leaseRevision, |
| 158 | + tuple.protocolVersion, |
| 159 | + now, |
| 160 | + ), |
| 161 | + ); |
| 162 | + return row ? receiptFromRow(tuple, row) : null; |
| 163 | + } |
| 164 | + |
| 165 | + async store(value: unknown, now: number): Promise<ExactReviewArtifactReceiptStoreResult> { |
| 166 | + const tuple = exactReviewArtifactReceiptTuple(value); |
| 167 | + const body = objectValue(value); |
| 168 | + const digest = String(body.digest || "").trim(); |
| 169 | + const bytes = Number(body.bytes); |
| 170 | + const objectKey = exactReviewArtifactObjectKey(digest); |
| 171 | + if (!tuple || !objectKey || !Number.isSafeInteger(bytes) || bytes < 1) { |
| 172 | + return { ok: false, error: "invalid_artifact_receipt", status: 400 }; |
| 173 | + } |
| 174 | + if (!this.bucket) { |
| 175 | + return { ok: false, error: "artifact_cache_unavailable", status: 503 }; |
| 176 | + } |
| 177 | + const object = await this.bucket.head(objectKey); |
| 178 | + if (!object || object.size !== bytes || object.customMetadata?.sha256 !== digest) { |
| 179 | + return { ok: false, error: "artifact_cache_object_mismatch", status: 409 }; |
| 180 | + } |
| 181 | + const expiresAt = now + EXACT_REVIEW_ARTIFACT_RECEIPT_RETENTION_MS; |
| 182 | + const stored = this.storage.transactionSync(() => { |
| 183 | + this.deleteExpiredReceiptsSync(now); |
| 184 | + const existing = this.lookupExactSync(tuple); |
| 185 | + if (existing && (existing.digest !== digest || existing.bytes !== bytes)) { |
| 186 | + return { conflict: true as const }; |
| 187 | + } |
| 188 | + this.storage.sql.exec( |
| 189 | + `INSERT INTO ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 190 | + (producer_run_id, producer_run_attempt, artifact_name, canonical_item_key, |
| 191 | + lease_revision, protocol_version, digest, bytes, object_key, created_at, expires_at) |
| 192 | + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 193 | + ON CONFLICT ( |
| 194 | + producer_run_id, producer_run_attempt, artifact_name, |
| 195 | + canonical_item_key, lease_revision, protocol_version |
| 196 | + ) DO UPDATE SET expires_at = excluded.expires_at`, |
| 197 | + tuple.producerRunId, |
| 198 | + tuple.producerRunAttempt, |
| 199 | + tuple.artifactName, |
| 200 | + tuple.canonicalItemKey, |
| 201 | + tuple.leaseRevision, |
| 202 | + tuple.protocolVersion, |
| 203 | + digest, |
| 204 | + bytes, |
| 205 | + objectKey, |
| 206 | + now, |
| 207 | + expiresAt, |
| 208 | + ); |
| 209 | + return { conflict: false as const, deduped: Boolean(existing) }; |
| 210 | + }); |
| 211 | + if (stored.conflict) { |
| 212 | + return { ok: false, error: "artifact_receipt_immutable_conflict", status: 409 }; |
| 213 | + } |
| 214 | + const receipt = this.lookupExactSync(tuple); |
| 215 | + if (!receipt) { |
| 216 | + return { ok: false, error: "artifact_receipt_store_failed", status: 503 }; |
| 217 | + } |
| 218 | + return { |
| 219 | + ok: true, |
| 220 | + deduped: stored.deduped, |
| 221 | + receipt, |
| 222 | + }; |
| 223 | + } |
| 224 | + |
| 225 | + async prune(now: number): Promise<{ receiptsDeleted: number; objectsDeleted: number }> { |
| 226 | + const receiptsDeleted = this.deleteExpiredReceiptsSync(now); |
| 227 | + if (!this.bucket) return { receiptsDeleted, objectsDeleted: 0 }; |
| 228 | + const cursorRow = firstRow( |
| 229 | + this.storage.sql.exec( |
| 230 | + `SELECT prune_cursor FROM ${EXACT_REVIEW_ARTIFACT_CACHE_META_TABLE} |
| 231 | + WHERE singleton_id = 1`, |
| 232 | + ), |
| 233 | + ); |
| 234 | + const cursor = typeof cursorRow?.prune_cursor === "string" ? cursorRow.prune_cursor : null; |
| 235 | + const page = await this.bucket.list({ |
| 236 | + prefix: EXACT_REVIEW_ARTIFACT_CACHE_PREFIX, |
| 237 | + ...(cursor ? { cursor } : {}), |
| 238 | + limit: CLEANUP_LIMIT, |
| 239 | + include: ["customMetadata"], |
| 240 | + }); |
| 241 | + let objectsDeleted = 0; |
| 242 | + const cutoff = now - EXACT_REVIEW_ARTIFACT_RECEIPT_RETENTION_MS; |
| 243 | + for (const object of page.objects) { |
| 244 | + const uploadedAt = object.uploaded?.getTime(); |
| 245 | + if (!Number.isFinite(uploadedAt) || Number(uploadedAt) > cutoff) continue; |
| 246 | + const digest = object.key.slice(EXACT_REVIEW_ARTIFACT_CACHE_PREFIX.length); |
| 247 | + if (!DIGEST_PATTERN.test(digest) || this.hasLiveDigestSync(digest, now)) continue; |
| 248 | + await this.bucket.delete(object.key); |
| 249 | + objectsDeleted += 1; |
| 250 | + } |
| 251 | + this.storage.sql.exec( |
| 252 | + `UPDATE ${EXACT_REVIEW_ARTIFACT_CACHE_META_TABLE} |
| 253 | + SET prune_cursor = ? WHERE singleton_id = 1`, |
| 254 | + page.truncated && page.cursor ? page.cursor : null, |
| 255 | + ); |
| 256 | + return { receiptsDeleted, objectsDeleted }; |
| 257 | + } |
| 258 | + |
| 259 | + private lookupExactSync( |
| 260 | + tuple: ExactReviewArtifactReceiptTuple, |
| 261 | + ): ExactReviewArtifactReceipt | null { |
| 262 | + const row = firstRow( |
| 263 | + this.storage.sql.exec( |
| 264 | + `SELECT digest, bytes, object_key, created_at, expires_at |
| 265 | + FROM ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 266 | + WHERE producer_run_id = ? AND producer_run_attempt = ? AND artifact_name = ? |
| 267 | + AND canonical_item_key = ? AND lease_revision = ? AND protocol_version = ?`, |
| 268 | + tuple.producerRunId, |
| 269 | + tuple.producerRunAttempt, |
| 270 | + tuple.artifactName, |
| 271 | + tuple.canonicalItemKey, |
| 272 | + tuple.leaseRevision, |
| 273 | + tuple.protocolVersion, |
| 274 | + ), |
| 275 | + ); |
| 276 | + return row ? receiptFromRow(tuple, row) : null; |
| 277 | + } |
| 278 | + |
| 279 | + private deleteExpiredReceiptsSync(now: number): number { |
| 280 | + const rows = Array.from( |
| 281 | + this.storage.sql.exec( |
| 282 | + `SELECT producer_run_id, producer_run_attempt, artifact_name, canonical_item_key, |
| 283 | + lease_revision, protocol_version |
| 284 | + FROM ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 285 | + WHERE expires_at <= ? |
| 286 | + ORDER BY expires_at |
| 287 | + LIMIT ${CLEANUP_LIMIT}`, |
| 288 | + now, |
| 289 | + ), |
| 290 | + ); |
| 291 | + for (const row of rows) { |
| 292 | + this.storage.sql.exec( |
| 293 | + `DELETE FROM ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 294 | + WHERE producer_run_id = ? AND producer_run_attempt = ? AND artifact_name = ? |
| 295 | + AND canonical_item_key = ? AND lease_revision = ? AND protocol_version = ?`, |
| 296 | + row.producer_run_id, |
| 297 | + row.producer_run_attempt, |
| 298 | + row.artifact_name, |
| 299 | + row.canonical_item_key, |
| 300 | + row.lease_revision, |
| 301 | + row.protocol_version, |
| 302 | + ); |
| 303 | + } |
| 304 | + return rows.length; |
| 305 | + } |
| 306 | + |
| 307 | + private hasLiveDigestSync(digest: string, now: number): boolean { |
| 308 | + return Boolean( |
| 309 | + firstRow( |
| 310 | + this.storage.sql.exec( |
| 311 | + `SELECT 1 AS found FROM ${EXACT_REVIEW_ARTIFACT_RECEIPT_TABLE} |
| 312 | + WHERE digest = ? AND expires_at > ? LIMIT 1`, |
| 313 | + digest, |
| 314 | + now, |
| 315 | + ), |
| 316 | + ), |
| 317 | + ); |
| 318 | + } |
| 319 | +} |
| 320 | + |
| 321 | +function receiptFromRow( |
| 322 | + tuple: ExactReviewArtifactReceiptTuple, |
| 323 | + row: SqlRow, |
| 324 | +): ExactReviewArtifactReceipt { |
| 325 | + return { |
| 326 | + ...tuple, |
| 327 | + digest: String(row.digest), |
| 328 | + bytes: Number(row.bytes), |
| 329 | + objectKey: String(row.object_key), |
| 330 | + createdAt: Number(row.created_at), |
| 331 | + expiresAt: Number(row.expires_at), |
| 332 | + }; |
| 333 | +} |
| 334 | + |
| 335 | +function artifactBucket(value: unknown): ArtifactR2Bucket | null { |
| 336 | + if (!value || typeof value !== "object") return null; |
| 337 | + const candidate = value as Partial<ArtifactR2Bucket>; |
| 338 | + return typeof candidate.head === "function" && |
| 339 | + typeof candidate.list === "function" && |
| 340 | + typeof candidate.delete === "function" |
| 341 | + ? (candidate as ArtifactR2Bucket) |
| 342 | + : null; |
| 343 | +} |
| 344 | + |
| 345 | +function firstRow(rows: Iterable<SqlRow>): SqlRow | undefined { |
| 346 | + return Array.from(rows)[0]; |
| 347 | +} |
| 348 | + |
| 349 | +function objectValue(value: unknown): Record<string, unknown> { |
| 350 | + return value && typeof value === "object" && !Array.isArray(value) |
| 351 | + ? (value as Record<string, unknown>) |
| 352 | + : {}; |
| 353 | +} |
0 commit comments