Skip to content
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: support http range header #10

Merged
merged 42 commits into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
aa705a7
chore: limit body parameters to the types used
SgtPooki Mar 4, 2024
089ae24
chore: add response-header helper and tests
SgtPooki Mar 4, 2024
5af9252
feat: add range header parsing support
SgtPooki Mar 4, 2024
3b2e379
feat: verified-fetch supports range-requests
SgtPooki Mar 4, 2024
d805a51
test: fix dns test asserting test failure since we are catching it now
SgtPooki Mar 4, 2024
4d8e57d
fix: return 500 error when streaming unixfs content throws
SgtPooki Mar 4, 2024
aa25f0c
fix: cleanup code and unexecuting tests hiding errors
SgtPooki Mar 5, 2024
60b56c9
chore: some cleanup and code coverage
SgtPooki Mar 5, 2024
6da36fd
tmp: most things working
SgtPooki Mar 5, 2024
cac2b79
fix: stream slicing and test correctness
SgtPooki Mar 5, 2024
72618bc
chore: fixed some ByteRangeContext tests
SgtPooki Mar 6, 2024
698ee8f
test: add back header helpers
SgtPooki Mar 7, 2024
e413fa5
fix: unixfs tests are passing
SgtPooki Mar 7, 2024
96c7f00
fix: range-requests on raw content
SgtPooki Mar 7, 2024
deb2f2b
feat: tests are passing
SgtPooki Mar 7, 2024
f357a3d
chore: log string casing
SgtPooki Mar 7, 2024
83e80d8
chore: use 502 response instead of 500
SgtPooki Mar 7, 2024
121747b
chore: use libp2p/interface for types in src
SgtPooki Mar 7, 2024
05a6dfb
chore: failing to create range resp logs error
SgtPooki Mar 7, 2024
9dcd798
chore: Apply suggestions from code review
SgtPooki Mar 7, 2024
f296f0b
chore: fix broken tests from github PR patches (my own)
SgtPooki Mar 7, 2024
912ee47
chore: re-enable stream tests for ByteRangeContext
SgtPooki Mar 7, 2024
b0b6a4a
chore: clean up getBody a bit
SgtPooki Mar 8, 2024
f399bed
chore: ByteRangeContext getBody cleanup
SgtPooki Mar 8, 2024
607e5be
Merge branch 'main' into 9-heliaverified-fetch-http-range-request-sup…
SgtPooki Mar 8, 2024
eb0224b
chore: apply suggestions from code review
SgtPooki Mar 15, 2024
d1e6a82
fix: getSlicedBody uses correct types
SgtPooki Mar 15, 2024
07ab941
chore: remove extra stat call
SgtPooki Mar 15, 2024
ac621a2
chore: fix jsdoc with '*/'
SgtPooki Mar 15, 2024
46dc133
chore: fileSize is public property, but should not be used
SgtPooki Mar 15, 2024
36f6c96
test: fix blob comparisons that broke or were never worjing properly
SgtPooki Mar 15, 2024
acdd632
Merge branch 'main' into 9-heliaverified-fetch-http-range-request-sup…
SgtPooki Mar 15, 2024
b48c672
Merge branch 'main' into 9-heliaverified-fetch-http-range-request-sup…
SgtPooki Mar 15, 2024
5fc7ceb
chore: Update byte-range-context.ts
SgtPooki Mar 15, 2024
19c2713
chore: jsdoc cleanup
SgtPooki Mar 15, 2024
a1686a3
Revert "chore: fileSize is public property, but should not be used"
SgtPooki Mar 15, 2024
e7e3fd0
chore: jsdoc comments explaining .fileSize use
SgtPooki Mar 15, 2024
c184e2a
chore: isRangeRequest is public
SgtPooki Mar 15, 2024
d633456
chore: getters/setters update
SgtPooki Mar 15, 2024
314adca
chore: remove unnecessary _contentRangeHeaderValue
SgtPooki Mar 15, 2024
8837738
chore: ByteRangeContext uses setFileSize and getFileSize
SgtPooki Mar 15, 2024
3963006
chore: remove .stat changes that are no longer needed
SgtPooki Mar 15, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/verified-fetch/src/types.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export type RequestFormatShorthand = 'raw' | 'car' | 'tar' | 'ipns-record' | 'dag-json' | 'dag-cbor' | 'json' | 'cbor'

export type SupportedBodyTypes = string | ArrayBuffer | Blob | ReadableStream<Uint8Array> | null
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Picking nits but Types is redundant in a type, Supported is a business-logic kind of decision not a type, so just Body?

Suggested change
export type SupportedBodyTypes = string | ArrayBuffer | Blob | ReadableStream<Uint8Array> | null
export type Body = string | ArrayBuffer | Blob | ReadableStream<Uint8Array> | null

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rather do something like ResponseBody, but i'm good with any.

Body could easily be a type that comes from builtin/global types that could cause confusion. SupportedBody would be better I guess.. but it's explicitly informing devs reading the code that it's not just typical Response.body types.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ResponseBody would be fine. It's a minor point tbh.

86 changes: 86 additions & 0 deletions packages/verified-fetch/src/utils/request-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { type CatOptions } from '@helia/unixfs'
import { CodeError } from '@libp2p/interface'
import { type ExporterOptions } from 'ipfs-unixfs-exporter'

export function getHeader (headers: HeadersInit | undefined, header: string): string | undefined {
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
if (headers == null) {
return undefined
}
if (headers instanceof Headers) {
return headers.get(header) ?? undefined
}
if (Array.isArray(headers)) {
const entry = headers.find(([key]) => key.toLowerCase() === header.toLowerCase())
return entry?.[1]
}
const key = Object.keys(headers).find(k => k.toLowerCase() === header.toLowerCase())
if (key == null) {
return undefined
}

return headers[key]
}

/**
* Type abstraction that will break the build if the supported range options change.
*/
export interface HeliaRangeOptions extends Pick<ExporterOptions | CatOptions, 'offset' | 'length'> {
suffixLength?: number
}

/**
* Converts a range request header into helia/unixfs supported range options
* Note that the gateway specification says we "MAY" support multiple ranges (https://specs.ipfs.tech/http-gateways/path-gateway/#range-request-header) but we don't
*
* Also note that @helia/unixfs and ipfs-unixfs-exporter expect length and offset to be numbers, the range header is a string, and the size of the resource is likely a bigint.
*
* SUPPORTED:
* Range: bytes=<range-start>-<range-end>
* Range: bytes=<range-start>-
* Range: bytes=-<suffix-length> // must pass size so we can calculate the offset
*
* NOT SUPPORTED:
* Range: bytes=<range-start>-<range-end>, <range-start>-<range-end>
* Range: bytes=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range-end>
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range#directives
*/
export function getRequestRange (headers: Headers | HeadersInit | undefined, size?: bigint): HeliaRangeOptions | undefined {
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
const range = getHeader(headers, 'Range')
if (range == null) {
return undefined
}

/**
* Range: bytes=<start>-<end> | bytes=<start2>- | bytes=-<end2>
*/
const match = range.match(/^bytes=((?<start>\d+)-(?<end>\d+)|(?<start2>\d+)-|-(?<end2>\d+))$/)
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
if (match?.groups == null) {
throw new CodeError('ERR_INVALID_RANGE_REQUEST', 'Invalid range request')
}
const { start, end, start2, end2 } = match.groups

let offset: number | undefined
let length: number | undefined
let suffixLength: number | undefined
if (end2 != null) {
if (size == null) {
suffixLength = Number(end2)
} else {
const stop = BigInt(end2)
offset = Number(size - stop)
length = Number(stop)
}
} else if (start2 != null) {
offset = parseInt(start2)
} else {
offset = parseInt(start)
length = parseInt(end) - offset + 1
}

return {
offset,
length,
suffixLength
}
}
53 changes: 53 additions & 0 deletions packages/verified-fetch/src/utils/response-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { CodeError } from '@libp2p/interface'
import type { SupportedBodyTypes } from '../types.js'

/**
* Gets the body size of a given body if it's possible to calculate it synchronously.
*/
function syncBodySize (body: SupportedBodyTypes): number | null {
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
if (typeof body === 'string') {
return body.length
}
if (body instanceof ArrayBuffer || body instanceof Uint8Array) {
return body.byteLength
}
if (body instanceof Blob) {
return body.size
}

if (body instanceof ReadableStream) {
return null
}

return null
}

/**
* This function returns the value of the `Content-Range` header for a given range.
* If you know the total size of the body, you should pass it in the `options` object.
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
*
* offset and length are 0-based, and the range is inclusive.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
*/
export function getContentRangeHeader ({ body, ...opts }: { offset?: number, length?: number, total?: number, body: SupportedBodyTypes }): string {
const totalSizeNum = opts.total ?? syncBodySize(body)
const rangeStart = opts.offset ?? 0
let rangeEnd = opts.length

if (rangeEnd == null) {
if (totalSizeNum == null) {
throw new CodeError('Cannot calculate content range without total size or length', 'ERR_INVALID_CONTENT_RANGE')
}

Check warning on line 41 in packages/verified-fetch/src/utils/response-headers.ts

View check run for this annotation

Codecov / codecov/patch

packages/verified-fetch/src/utils/response-headers.ts#L40-L41

Added lines #L40 - L41 were not covered by tests
rangeEnd = totalSizeNum - rangeStart + 1
}
let end: number
if (rangeStart != null && rangeEnd != null) {
end = rangeStart + rangeEnd - 1
} else {
end = totalSizeNum ?? 0
}

Check warning on line 49 in packages/verified-fetch/src/utils/response-headers.ts

View check run for this annotation

Codecov / codecov/patch

packages/verified-fetch/src/utils/response-headers.ts#L48-L49

Added lines #L48 - L49 were not covered by tests
const total = totalSizeNum ?? '*' // if we don't know the total size, we should use *

return `bytes ${rangeStart}-${end}/${total}`
}
84 changes: 80 additions & 4 deletions packages/verified-fetch/src/utils/responses.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { getContentRangeHeader } from './response-headers.js'
import type { SupportedBodyTypes } from '../types.js'

function setField (response: Response, name: string, value: string | boolean): void {
Object.defineProperty(response, name, {
enumerable: true,
Expand All @@ -23,7 +26,7 @@
redirected?: boolean
}

export function okResponse (url: string, body?: BodyInit | null, init?: ResponseOptions): Response {
export function okResponse (url: string, body?: SupportedBodyTypes, init?: ResponseOptions): Response {
const response = new Response(body, {
...(init ?? {}),
status: 200,
Expand All @@ -40,7 +43,20 @@
return response
}

export function notSupportedResponse (url: string, body?: BodyInit | null, init?: ResponseInit): Response {
export function internalServerErrorResponse (url: string, body?: SupportedBodyTypes, init?: ResponseInit): Response {
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
const response = new Response(body, {
...(init ?? {}),
status: 500,
statusText: 'Internal Server Error'
})

setType(response, 'basic')
setUrl(response, url)

return response
}

export function notSupportedResponse (url: string, body?: SupportedBodyTypes, init?: ResponseInit): Response {
const response = new Response(body, {
...(init ?? {}),
status: 501,
Expand All @@ -54,7 +70,7 @@
return response
}

export function notAcceptableResponse (url: string, body?: BodyInit | null, init?: ResponseInit): Response {
export function notAcceptableResponse (url: string, body?: SupportedBodyTypes, init?: ResponseInit): Response {
const response = new Response(body, {
...(init ?? {}),
status: 406,
Expand All @@ -67,7 +83,7 @@
return response
}

export function badRequestResponse (url: string, body?: BodyInit | null, init?: ResponseInit): Response {
export function badRequestResponse (url: string, body?: SupportedBodyTypes, init?: ResponseInit): Response {
const response = new Response(body, {
...(init ?? {}),
status: 400,
Expand Down Expand Up @@ -96,3 +112,63 @@

return response
}

type RangeOptions = { offset: number, length: number, totalSize?: number } | { offset: number, length?: number, totalSize: number }

/**
* Some caveats about range responses here:
* * We only support single range requests (multi-range is optional), see https://specs.ipfs.tech/http-gateways/path-gateway/#range-request-header
* * Range responses are only supported for unixfs and raw data, see https://specs.ipfs.tech/http-gateways/path-gateway/#range-request-header.
*
* If the user requests something other than unixfs or raw data, we should not call this method and ignore the range header (200 OK). See https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests#partial_request_responses
*
* TODO: Supporting multiple range requests will require additional changes to the `handleDagPb` and `handleRaw` functions in `src/verified-fetch.js`
*/
export function okRangeResponse (url: string, body: SupportedBodyTypes, range: RangeOptions, init?: ResponseOptions): Response {
// if we know the full size of the body, we should use it in the content-range header. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range
let contentRangeHeader: string | undefined

try {
contentRangeHeader = getContentRangeHeader({ body, total: range.totalSize, offset: range.offset, length: range.length })
} catch (e) {
return badRangeResponse(url, body, init)
SgtPooki marked this conversation as resolved.
Show resolved Hide resolved
}

Check warning on line 135 in packages/verified-fetch/src/utils/responses.ts

View check run for this annotation

Codecov / codecov/patch

packages/verified-fetch/src/utils/responses.ts#L134-L135

Added lines #L134 - L135 were not covered by tests

const response = new Response(body, {
...(init ?? {}),
status: 206,
statusText: 'Partial Content',
headers: {
...(init?.headers ?? {}),
'content-range': contentRangeHeader
}
})

if (init?.redirected === true) {
setRedirected(response)
}

Check warning on line 149 in packages/verified-fetch/src/utils/responses.ts

View check run for this annotation

Codecov / codecov/patch

packages/verified-fetch/src/utils/responses.ts#L148-L149

Added lines #L148 - L149 were not covered by tests

setType(response, 'basic')
setUrl(response, url)

return response
}

/**
* We likely need to catch errors handled by upstream helia libraries if range-request throws an error. Some examples:
* * The range is out of bounds
* * The range is invalid
* * The range is not supported for the given type
*/
export function badRangeResponse (url: string, body?: SupportedBodyTypes, init?: ResponseInit): Response {
const response = new Response(body, {
...(init ?? {}),
status: 416,
statusText: 'Requested Range Not Satisfiable'
})

setType(response, 'basic')
setUrl(response, url)

return response
}
Loading
Loading