Open History to see the last commit
1import type {
2 AIPersistence,
3 ArtifactRecord,
4 BlobGetOptions,
5 BlobObject,
6} from './types'
7
8/**
9 * The DEFAULT blob-store key a generation artifact's bytes are stored under,
10 * used when `withGenerationPersistence` is given no `storageKey` mapper.
11 *
12 * Reads go through {@link resolveArtifactBlobKey} instead: a record written with
13 * a custom `storageKey` carries its real key in `blobKey`, and recomputing the
14 * default would look in the wrong place.
15 *
16 * @internal
17 */
18export function artifactBlobKey(
19 ref: Pick<ArtifactRecord, 'runId' | 'artifactId'>,
20): string {
21 return `artifacts/${ref.runId}/${ref.artifactId}`
22}
23
24/**
25 * The blob-store key to read an artifact's bytes from: the key recorded when it
26 * was written, falling back to the default convention for records written
27 * before `blobKey` existed.
28 *
29 * The fallback is what makes `blobKey` a non-breaking addition — and why the
30 * default convention can never be changed retroactively without one.
31 */
32export function resolveArtifactBlobKey(record: ArtifactRecord): string {
33 return record.blobKey ?? artifactBlobKey(record)
34}
35
36/**
37 * Look up a persisted generation artifact's metadata by id. Returns `null` when
38 * the persistence has no `artifacts` store or no record matches — so a serve
39 * handler can map that straight to a 404.
40 */
41export async function retrieveArtifact(
42 persistence: AIPersistence,
43 artifactId: string,
44): Promise<ArtifactRecord | null> {
45 const record = await persistence.stores.artifacts?.get(artifactId)
46 return record ?? null
47}
48
49/**
50 * Look up a persisted generation artifact's stored bytes. Pass an `artifactId`
51 * (resolved to its record first) or an already-loaded {@link ArtifactRecord}
52 * (no second metadata lookup). Returns `null` when the artifact, its record, or
53 * its blob is missing, or the stores are not configured.
54 *
55 * Pass `options.range` to read one slice — how a serve route answers a `Range`
56 * request with `206` + `Content-Range` instead of the whole file, which is what
57 * `<video>` seeking is built on. Resolve the range against `record.size` and
58 * reply `416` yourself when it does not fit; the store is handed satisfiable
59 * ranges only. The returned object's `range` reports the slice actually served.
60 */
61export async function retrieveBlob(
62 persistence: AIPersistence,
63 artifact: string | ArtifactRecord,
64 options?: BlobGetOptions,
65): Promise<BlobObject | null> {
66 const record =
67 typeof artifact === 'string'
68 ? await retrieveArtifact(persistence, artifact)
69 : artifact
70 if (!record) return null
71
72 const blob = await persistence.stores.blobs?.get(
73 resolveArtifactBlobKey(record),
74 options,
75 )
76 return blob ?? null
77}