-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: serve CAR blocks #68
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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 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,82 @@ | ||
/* eslint-env browser */ | ||
/* global FixedLengthStream */ | ||
import { HttpError } from '@web3-storage/gateway-lib/util' | ||
import { CAR_CODE } from '../constants.js' | ||
import * as Http from '../lib/http.js' | ||
|
||
/** @typedef {import('@web3-storage/gateway-lib').IpfsUrlContext} CarBlockHandlerContext */ | ||
|
||
/** | ||
* Handler that serves CAR files directly from R2. | ||
* | ||
* @type {import('@web3-storage/gateway-lib').Handler<CarBlockHandlerContext, import('../bindings').Environment>} | ||
*/ | ||
export async function handleCarBlock (request, env, ctx) { | ||
const { searchParams, dataCid } = ctx | ||
if (!dataCid) throw new Error('missing data CID') | ||
if (!searchParams) throw new Error('missing URL search params') | ||
|
||
if (request.method !== 'HEAD' && request.method !== 'GET') { | ||
throw new HttpError('method not allowed', { status: 405 }) | ||
} | ||
if (dataCid.code !== CAR_CODE) { | ||
throw new HttpError('not a CAR CID', { status: 400 }) | ||
} | ||
|
||
const etag = `"${dataCid}"` | ||
if (request.headers.get('If-None-Match') === etag) { | ||
return new Response(null, { status: 304 }) | ||
} | ||
|
||
if (request.method === 'HEAD') { | ||
const obj = await env.CARPARK.head(`${dataCid}/${dataCid}.car`) | ||
if (!obj) throw new HttpError('CAR not found', { status: 404 }) | ||
return new Response(undefined, { | ||
headers: { | ||
'Accept-Ranges': 'bytes', | ||
'Content-Length': obj.size.toString(), | ||
Etag: etag | ||
} | ||
}) | ||
} | ||
|
||
/** @type {import('../lib/http').Range|undefined} */ | ||
let range | ||
if (request.headers.has('range')) { | ||
try { | ||
range = Http.parseRange(request.headers.get('range') ?? '') | ||
} catch (err) { | ||
throw new HttpError('invalid range', { status: 400, cause: err }) | ||
} | ||
} | ||
|
||
const obj = await env.CARPARK.get(`${dataCid}/${dataCid}.car`, { range }) | ||
if (!obj) throw new HttpError('CAR not found', { status: 404 }) | ||
|
||
const status = range ? 206 : 200 | ||
const headers = new Headers({ | ||
'Content-Type': 'application/vnd.ipld.car; version=1;', | ||
'X-Content-Type-Options': 'nosniff', | ||
'Cache-Control': 'public, max-age=29030400, immutable', | ||
'Content-Disposition': `attachment; filename="${dataCid}.car"`, | ||
Etag: etag | ||
}) | ||
|
||
let contentLength = obj.size | ||
if (range) { | ||
let first, last | ||
if ('suffix' in range) { | ||
first = obj.size - range.suffix | ||
last = obj.size - 1 | ||
} else { | ||
first = range.offset || 0 | ||
last = range.length != null ? first + range.length - 1 : obj.size - 1 | ||
} | ||
headers.set('Content-Range', `bytes ${first}-${last}/${obj.size}`) | ||
contentLength = last - first | ||
} | ||
headers.set('Content-Length', contentLength.toString()) | ||
|
||
// @ts-expect-error ReadableStream types incompatible | ||
return new Response(obj.body.pipeThrough(new FixedLengthStream(contentLength)), { status, headers }) | ||
} |
This file contains 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 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 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,20 @@ | ||
import { CarReader } from '@ipld/car' | ||
import { CAR_CODE } from '../constants.js' | ||
|
||
export const code = CAR_CODE | ||
|
||
/** | ||
* @param {Uint8Array} bytes | ||
* @returns {Promise<Array<{ cid: import('multiformats').UnknownLink, bytes: Uint8Array }>>} | ||
*/ | ||
export async function decode (bytes) { | ||
const reader = await CarReader.fromBytes(bytes) | ||
const blocks = [] | ||
for await (const b of reader.blocks()) { | ||
blocks.push({ | ||
cid: /** @type {import('multiformats').UnknownLink} */ (b.cid), | ||
bytes: b.bytes | ||
}) | ||
} | ||
return blocks | ||
} |
This file contains 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 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,19 @@ | ||
// @ts-expect-error no types | ||
import httpRangeParse from 'http-range-parse' | ||
|
||
/** @typedef {{ offset: number, length?: number } | { offset?: number, length: number } | { suffix: number }} Range */ | ||
|
||
/** | ||
* Convert a HTTP Range header to a range object. | ||
* @param {string} value | ||
* @returns {Range} | ||
*/ | ||
export function parseRange (value) { | ||
const result = httpRangeParse(value) | ||
if (result.ranges) throw new Error('Multipart ranges not supported') | ||
const { unit, first, last, suffix } = result | ||
if (unit !== 'bytes') throw new Error(`Unsupported range unit: ${unit}`) | ||
return suffix != null | ||
? { suffix } | ||
: { offset: first, length: last != null ? last - first + 1 : undefined } | ||
} |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could be cool to try this with roundabout. I think it should work and let us redirect to presigned url.
Probably good to keep as is and track issue to attempt cost optimisation :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, yes but we probably don't want to give out those URLs to anyone via the gateway. Someone will try to use/abuse and they also expire...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So the usage would be the same as here? it would be a redirect that response will be read right away right? So, expiration would not be a problem, and if we perform request to
roundabout
within the worker and redirect to presigned URL then user will not even know how URL was created.Use/abuse would be the same as via freeway no. So, rate limits is really the solution we seem to have to avoid abuse