This repository was archived by the owner on Oct 24, 2026. It is now read-only.
Repository navigation
fix: serve demo videos with byte ranges so Safari can play them #759
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9865a5d
fix: serve demo videos with byte ranges so Safari can play them
AbhishekDoshi26 14af74e
fix: tighten video range handling per RFC 9110
AbhishekDoshi26 3911309
fix: stream video range slices and keep 416 out of caches
AbhishekDoshi26 2ad0e7c
fix: simplify the streamed video slice and tidy range responses
AbhishekDoshi26 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| /// <reference types="@cloudflare/workers-types" /> | ||
|
|
||
| // Byte-range support for the demo videos. Cloudflare Pages answers a Range | ||
| // request for a static asset with the whole file and a 200, and Safari (and | ||
| // anything else built on AVFoundation) won't play an MP4 from a server that | ||
| // doesn't return 206 partial content. This serves the asset and slices it. | ||
|
|
||
| interface Env { | ||
| ASSETS: Fetcher; | ||
| } | ||
|
|
||
| // `bytes=start-end`, `bytes=start-` or `bytes=-suffixLength`. Multi-range | ||
| // requests aren't used by media players, so they get the whole file. | ||
| function parseRange( | ||
| header: string, | ||
| size: number, | ||
| ): { start: number; end: number } | 'unsatisfiable' | null { | ||
| const match = /^bytes\s*=\s*(\d*)-(\d*)$/i.exec(header.trim()); | ||
| if (!match) return null; | ||
| const [, first, last] = match; | ||
| if (first === '' && last === '') return null; | ||
| let start: number; | ||
| let end: number; | ||
| if (first === '') { | ||
| const suffix = Number(last); | ||
| if (suffix === 0) return 'unsatisfiable'; | ||
| start = Math.max(0, size - suffix); | ||
| end = size - 1; | ||
| } else { | ||
| start = Number(first); | ||
| // A last-pos before first-pos makes the range invalid, so it's ignored | ||
| // rather than unsatisfiable (RFC 9110 section 14.1.1). | ||
| if (last !== '' && Number(last) < start) return null; | ||
| end = last === '' ? size - 1 : Math.min(Number(last), size - 1); | ||
| } | ||
| if (start >= size) return 'unsatisfiable'; | ||
| return { start, end }; | ||
| } | ||
|
|
||
| // Passes through only bytes start..end (inclusive) of a stream. | ||
| function sliceStream( | ||
| start: number, | ||
| end: number, | ||
| ): TransformStream<Uint8Array, Uint8Array> { | ||
| let offset = 0; | ||
| return new TransformStream({ | ||
| transform(chunk, controller) { | ||
| const from = Math.max(start - offset, 0); | ||
| const to = Math.min(end + 1 - offset, chunk.byteLength); | ||
| if (from < to) controller.enqueue(chunk.subarray(from, to)); | ||
| offset += chunk.byteLength; | ||
| if (offset > end) controller.terminate(); | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| export const onRequest: PagesFunction<Env> = async (context) => { | ||
| const { request } = context; | ||
| if ( | ||
| (request.method !== 'GET' && request.method !== 'HEAD') || | ||
| !/\.mp4$/i.test(new URL(request.url).pathname) | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| ) { | ||
| return context.next(); | ||
| } | ||
|
|
||
| // Slices are cut from the raw bytes, so ask for an unencoded asset. | ||
| const assetHeaders = new Headers(request.headers); | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| assetHeaders.delete('Range'); | ||
| assetHeaders.delete('Accept-Encoding'); | ||
| const asset = await context.env.ASSETS.fetch( | ||
| new Request(request.url, { method: request.method, headers: assetHeaders }), | ||
| ); | ||
| if (asset.status !== 200) return asset; | ||
| const headers = new Headers(asset.headers); | ||
| headers.set('Accept-Ranges', 'bytes'); | ||
|
|
||
| // Range only applies to GET (RFC 9110 section 14.2). A stale If-Range | ||
| // means the client's partial copy is out of date, so it gets the whole new | ||
| // file. Pages assets have a strong ETag and no Last-Modified, so only an | ||
| // exact match on a strong entity tag counts (RFC 9110 section 13.1.5). | ||
| const range = request.headers.get('Range'); | ||
| const ifRange = request.headers.get('If-Range')?.trim(); | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| const ifRangeMatches = | ||
| ifRange === undefined || | ||
| (!ifRange.startsWith('W/') && ifRange === asset.headers.get('ETag')); | ||
| if ( | ||
| request.method !== 'GET' || | ||
| range === null || | ||
| !ifRangeMatches || | ||
| !asset.body | ||
| ) { | ||
| return new Response(asset.body, { status: 200, headers }); | ||
| } | ||
|
|
||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| // Stream the slice when the asset's size is known up front; otherwise read | ||
| // it once to learn the size. Pages caps a file at 25 MiB, which bounds the | ||
| // buffer. | ||
| const declaredSize = Number(asset.headers.get('Content-Length')); | ||
| const buffered = declaredSize > 0 ? null : await asset.arrayBuffer(); | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| const size = buffered ? buffered.byteLength : declaredSize; | ||
| const whole = buffered ?? asset.body; | ||
|
|
||
| const parsed = parseRange(range, size); | ||
| if (parsed === null) return new Response(whole, { status: 200, headers }); | ||
| if (parsed === 'unsatisfiable') { | ||
| if (!buffered) await asset.body.cancel(); | ||
| return new Response(null, { | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| status: 416, | ||
| headers: { | ||
| 'Accept-Ranges': 'bytes', | ||
| 'Content-Range': `bytes */${size}`, | ||
| 'Cache-Control': 'no-store', | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| const { start, end } = parsed; | ||
| const length = end - start + 1; | ||
| headers.set('Content-Range', `bytes ${start}-${end}/${size}`); | ||
| headers.set('Content-Length', String(length)); | ||
| const body = buffered | ||
| ? new Uint8Array(buffered, start, length) | ||
| : asset.body | ||
| .pipeThrough(sliceStream(start, end)) | ||
| .pipeThrough(new FixedLengthStream(length)); | ||
| return new Response(body, { status: 206, headers }); | ||
| }; | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| { | ||
| "version": 1, | ||
| "include": ["/*"], | ||
| "exclude": ["/videos/*"] | ||
| "exclude": ["/videos/*.jpg"] | ||
|
AbhishekDoshi26 marked this conversation as resolved.
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.