// Single objects: HEAD, GET (one Range), PUT and DELETE. import type { S3Client } from './s3' import { BodyReader, contentLength } from './body' import { fromS3Response, ShimError } from './errors' import { fromS3Headers, isConditional, toS3Headers, unquote } from './headers' import { completeUpload, createUpload } from './multipart' /** Up to this many bytes are one S3 PUT; more become a multipart upload of parts this size. */ export const PART = 8 * 1024 * 1024 export async function readObject(s3: S3Client, bucket: string, key: string, request: Request): Promise { const method = request.method === 'HEAD' ? 'HEAD' : 'GET' const headers: Record = {} const range = request.headers.get('range') if (range !== null) headers.range = range const response = await s3.send({ method, bucket, key, headers }) if (!response.ok) throw await fromS3Response(response) return new Response(method === 'HEAD' ? null : response.body, { status: response.status, headers: fromS3Headers(response.headers), // The stored bytes, as they are: don't encode them again by their Content-Encoding. encodeBody: 'manual', }) } export async function deleteObject(s3: S3Client, bucket: string, key: string): Promise { const response = await s3.send({ method: 'DELETE', bucket, key }) // Deleting a missing key succeeds, as in R2 (S3 answers 204; some servers 404). if (!response.ok && response.status !== 404) throw await fromS3Response(response) await response.body?.cancel() return new Response('') } /** * A put of `Content-Length` bytes. Up to `PART` is one PUT, fenced by the request's `If-Match` / * `If-None-Match: *`; more streams as a multipart upload, `PART` bytes held at a time. r2.js sends * a precondition only for puts up to `PART` (it checks larger ones itself when they start). */ export async function putObject(s3: S3Client, bucket: string, key: string, request: Request): Promise { const size = contentLength(request) const body = new BodyReader(request.body) if (size <= PART) { const bytes = await body.read(size) const response = await s3.send({ method: 'PUT', bucket, key, headers: toS3Headers(request.headers), body: bytes, retry: isConditional(request.headers) ? 'conditional' : 'idempotent', }) if (!response.ok) throw await fromS3Response(response) return new Response('', { headers: fromS3Headers(response.headers) }) } if (isConditional(request.headers)) throw new ShimError(501, 'NotImplemented', 'A precondition on a put over 8 MiB is not fenced; check it before the put.') // The ETag of this upload's completion, not of a later HEAD that could see another write. const etag = await multipartPut(s3, bucket, key, request.headers, body, size) return new Response('', { headers: { 'etag': `"${etag}"`, 'x-version': etag } }) } async function multipartPut(s3: S3Client, bucket: string, key: string, headers: Headers, body: BodyReader, size: number): Promise { const uploadId = await createUpload(s3, bucket, key, toS3Headers(headers, { conditions: false })) const upload = `uploadId=${encodeURIComponent(uploadId)}` try { const parts: { part: number, etag: string }[] = [] for (let offset = 0; offset < size; offset += PART) { const part = parts.length + 1 const bytes = await body.read(Math.min(PART, size - offset)) const response = await s3.ok({ method: 'PUT', bucket, key, query: `partNumber=${part}&${upload}`, body: bytes }) parts.push({ part, etag: unquote(response.headers.get('etag')) }) } return await completeUpload(s3, bucket, key, uploadId, parts) } catch (error) { // Don't leave the parts behind (a failed checksum in r2.js ends up here too). await s3.send({ method: 'DELETE', bucket, key, query: upload }).then(r => r.body?.cancel()).catch(() => {}) throw error } }