Open History to see the last commit
1import type {
2 AIPersistence,
3 ArtifactRecord,
4 BlobGetOptions,
5 BlobObject,
6} from './types'
7
8/**
9 * Look up a persisted generation artifact's metadata by id. Returns `null` when
10 * the persistence has no `artifacts` store or no record matches — so a serve
11 * handler can map that straight to a 404.
12 */
13export async function retrieveArtifact(
14 persistence: AIPersistence,
15 artifactId: string,
16): Promise<ArtifactRecord | null> {
17 const record = await persistence.stores.artifacts?.get(artifactId)
18 return record ?? null
19}
20
21/**
22 * Look up a persisted generation artifact's stored bytes. Pass an `artifactId`
23 * (resolved to its record first) or an already-loaded {@link ArtifactRecord}
24 * (no second metadata lookup). Returns `null` when the artifact, its record, or
25 * its blob is missing, or the stores are not configured.
26 *
27 * Pass `options.range` to read one slice — how a serve route answers a `Range`
28 * request with `206` + `Content-Range` instead of the whole file, which is what
29 * `<video>` seeking is built on. Resolve the range against `record.size` and
30 * reply `416` yourself when it does not fit; the store is handed satisfiable
31 * ranges only. The returned object's `range` reports the slice actually served.
32 */
33export async function retrieveBlob(
34 persistence: AIPersistence,
35 artifact: string | ArtifactRecord,
36 options?: BlobGetOptions,
37): Promise<BlobObject | null> {
38 const record =
39 typeof artifact === 'string'
40 ? await retrieveArtifact(persistence, artifact)
41 : artifact
42 if (!record) return null
43 // A 0.x record has no `blobKey`. Fail loudly instead of a misleading 404.
44 if (!record.blobKey) {
45 throw new Error(
46 `Artifact ${record.artifactId} has no blobKey. Records written by 0.x need blob_key backfilled before their bytes can be read.`,
47 )
48 }
49
50 const blob = await persistence.stores.blobs?.get(record.blobKey, options)
51 return blob ?? null
52}