Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

blob-range.ts

101 lines4.3 KB

1import type { BlobRange } from './types'
2​
3/**
4 * Resolve a requested {@link BlobRange} against an object's real size, the way
5 * every byte-storing blob store has to before it slices.
6 *
7 * Clamps `length` to the end of the object and treats an absent `length` as
8 * "to the end", so the result is always the slice actually served — which is
9 * what `BlobObject.range` reports and what a `206` response's `Content-Range`
10 * is built from.
11 *
12 * Throws on an `offset` outside the object: that is a caller error, not a
13 * store error. A serve route knows the size (it is on the artifact record) and
14 * answers `416` from it, so a store only ever sees a satisfiable range unless
15 * something upstream is wrong — and silently returning an empty body there
16 * would serve a `206` that claims bytes it does not carry.
17 *
18 * @example
19 * ```ts
20 * const { offset, length } = resolveBlobRange(bytes.byteLength, range)
21 * const slice = bytes.subarray(offset, offset + length)
22 * ```
23 */
24export function resolveBlobRange(
25 size: number,
26 range: BlobRange,
27): { offset: number; length: number } {
28 const { offset } = range
29 if (!Number.isInteger(offset) || offset < 0 || offset >= size) {
30 throw new RangeError(
31 `Blob range offset ${offset} is outside the object (size ${size}).`,
32 )
33 }
34 const remaining = size - offset
35 if (range.length === undefined) return { offset, length: remaining }
36 if (!Number.isInteger(range.length) || range.length < 0) {
37 throw new RangeError(`Blob range length ${range.length} is not valid.`)
38 }
39 return { offset, length: Math.min(range.length, remaining) }
41​
42/**
43 * Resolve an HTTP `Range` header against a known object size, for a route that
44 * serves artifact bytes.
45 *
46 * Returns the {@link BlobRange} to pass to `retrieveBlob` / `BlobStore.get`,
47 * `'unsatisfiable'` when the request names bytes the object does not have — answer
48 * `416`, whose `content-range` is the literal `bytes` `*` then a slash then the
49 * size — or `undefined` when there is no range to honour and the whole object
50 * should be served: an absent header, an invalid byte-range-spec (`bytes=100-50`,
51 * which RFC 9110 says to ignore rather than reject), and the forms this does not
52 * implement (multiple ranges, units other than `bytes`), which a server is
53 * always free to answer in full.
54 *
55 * @example
56 * ```ts
57 * const range = parseRangeHeader(request.headers.get('range'), record.size)
58 * if (range === 'unsatisfiable') return new Response(null, { status: 416 })
59 * const blob = await retrieveBlob(
60 * persistence,
61 * record,
62 * range ? { range } : undefined,
63 * )
64 * ```
65 */
66export function parseRangeHeader(
67 header: string | null | undefined,
68 size: number,
69): BlobRange | 'unsatisfiable' | undefined {
70 const match = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? '')
71 if (!match) return undefined
72 const [, rawStart, rawEnd] = match
73 // `bytes=-` names nothing at all.
74 if (rawStart === '' && rawEnd === '') return undefined
75​
76 // `bytes=-500` is the LAST 500 bytes, not "from 0 to 500" — the one form
77 // that is easy to read backwards, and reading it backwards serves the wrong
78 // bytes with a 206 that claims they are the right ones.
79 if (rawStart === '') {
80 const suffix = Number(rawEnd)
81 // A zero-length suffix names no bytes, and NO range is satisfiable against
82 // a zero-byte object — without the size check, `bytes=-1` on an empty
83 // artifact resolves to `{ offset: 0 }` and throws out of the store instead
84 // of answering 416.
85 if (suffix === 0 || size === 0) return 'unsatisfiable'
86 return { offset: Math.max(0, size - suffix) }
87 }
88​
89 const start = Number(rawStart)
90 const end = rawEnd === '' ? undefined : Number(rawEnd)
91 // `bytes=100-50` is an INVALID byte-range-spec, not an unsatisfiable one
92 // (RFC 9110 §14.1.1). An invalid spec is ignored and the whole
93 // representation is served — answering 416 would fail a request that is
94 // supposed to succeed. Checked before satisfiability so the size cannot turn
95 // an ignorable spec into a 416.
96 if (end !== undefined && end < start) return undefined
97 if (start >= size) return 'unsatisfiable'
98 if (end === undefined) return { offset: start }
99 // `end` is inclusive, and past the end of the object it simply clamps.
100 return { offset: start, length: Math.min(end, size - 1) - start + 1 }