Repository navigation
feat(uploads): report PDFs and covers go straight to R2 #1699
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
Merged
+1,103
−141
Merged
Changes from all 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
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
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,120 @@ | ||
| // The files people upload, and the ones made from them, kept in Cloudflare R2 (#1695): the bucket the `UPLOADS_*` | ||
| // settings name, one per deployment. The browser sends a file straight there through an address signed here, so no | ||
| // upload goes through our proxy, which takes at most 100 MB a request on dev. Signed with `aws4fetch`, as the paper | ||
| // PDF store is (convex/lib/paperPdfs.ts). | ||
| import { AwsClient } from "aws4fetch"; | ||
|
|
||
| /** The most one request carries to R2: 5 GiB less 5 MiB (developers.cloudflare.com/r2/platform/limits). A larger file goes up in parts. */ | ||
| export const R2_SINGLE_PUT_MAX = 5 * 1024 * 1024 * 1024 - 5 * 1024 * 1024; | ||
| /** How long an address to send a file or a part of it lasts: a slow connection may take hours over a large file. */ | ||
| const SEND_SECONDS = 24 * 60 * 60; | ||
| /** How long an address to read a file lasts: long enough for a PDF viewer to ask for its pages, short enough that a copied link stops working. */ | ||
| const READ_SECONDS = 15 * 60; | ||
|
|
||
| function bucket() { | ||
| const { UPLOADS_ENDPOINT: endpoint, UPLOADS_BUCKET: name, UPLOADS_ACCESS_KEY_ID: accessKeyId, UPLOADS_SECRET_ACCESS_KEY: secretAccessKey } = process.env; | ||
| if (!endpoint || !name || !accessKeyId || !secretAccessKey) throw new Error("UPLOADS_ENDPOINT, UPLOADS_BUCKET, UPLOADS_ACCESS_KEY_ID and UPLOADS_SECRET_ACCESS_KEY must be set for uploads."); | ||
| return { name, client: new AwsClient({ accessKeyId, secretAccessKey, service: "s3", region: "auto" }), url: (key: string) => `${endpoint.replace(/\/$/, "")}/${name}/${key.split("/").map(encodeURIComponent).join("/")}` }; | ||
| } | ||
|
|
||
| const signed = async (url: string, method: "GET" | "PUT" | "HEAD", seconds: number) => { | ||
| const { client } = bucket(); | ||
| const query = url.includes("?") ? "&" : "?"; | ||
| return (await client.sign(`${url}${query}X-Amz-Expires=${seconds}`, { method, aws: { signQuery: true } })).url; | ||
| }; | ||
|
|
||
| /** Why R2 refused, for the logs. */ | ||
| async function refusal(what: string, response: Response) { | ||
| return new Error(`R2 refused ${what}: ${response.status} ${(await response.text().catch(() => "")).slice(0, 300)}`); | ||
| } | ||
|
|
||
| /** The address a browser sends a whole file to, with one PUT. */ | ||
| export const sendAddress = (key: string) => signed(bucket().url(key), "PUT", SEND_SECONDS); | ||
|
|
||
| /** Starts a file sent in parts, and gives the upload's id. */ | ||
| export async function startParts(key: string, contentType: string) { | ||
| const { client, url } = bucket(); | ||
| const response = await client.fetch(`${url(key)}?uploads`, { method: "POST", headers: { "Content-Type": contentType } }); | ||
| if (!response.ok) throw await refusal("a new upload in parts", response); | ||
| const id = /<UploadId>([^<]+)<\/UploadId>/.exec(await response.text())?.[1]; | ||
| if (!id) throw new Error("R2 started an upload in parts without saying its id."); | ||
| return id; | ||
| } | ||
|
|
||
| /** The addresses a browser sends each part to, numbered from 1. */ | ||
| export async function partAddresses(key: string, uploadId: string, parts: number) { | ||
| const { url } = bucket(); | ||
| return await Promise.all(Array.from({ length: parts }, (_, at) => signed(`${url(key)}?partNumber=${at + 1}&uploadId=${encodeURIComponent(uploadId)}`, "PUT", SEND_SECONDS))); | ||
| } | ||
|
|
||
| /** Joins a file's parts, each named by the ETag R2 answered it with. */ | ||
| export async function finishParts(key: string, uploadId: string, etags: string[]) { | ||
| const { client, url } = bucket(); | ||
| const body = `<CompleteMultipartUpload>${etags.map((etag, at) => `<Part><PartNumber>${at + 1}</PartNumber><ETag>${etag.replace(/[<>&]/g, "")}</ETag></Part>`).join("")}</CompleteMultipartUpload>`; | ||
| const response = await client.fetch(`${url(key)}?uploadId=${encodeURIComponent(uploadId)}`, { method: "POST", body }); | ||
| // R2, like S3, can answer 200 with an error in its body. | ||
| const text = response.ok ? await response.text() : ""; | ||
| if (!response.ok || text.includes("<Error>")) throw response.ok ? new Error(`R2 refused to join the parts: ${text.slice(0, 300)}`) : await refusal("to join the parts", response); | ||
| } | ||
|
|
||
| /** Gives up an upload in parts, so its parts aren't kept. */ | ||
| export async function dropParts(key: string, uploadId: string) { | ||
| const { client, url } = bucket(); | ||
| const response = await client.fetch(`${url(key)}?uploadId=${encodeURIComponent(uploadId)}`, { method: "DELETE" }); | ||
| if (!response.ok && response.status !== 404) throw await refusal("to drop an upload's parts", response); | ||
| } | ||
|
|
||
| /** A file's size and type as R2 holds it; null when it holds none under `key`. */ | ||
| export async function headOf(key: string): Promise<{ bytes: number; contentType: string } | null> { | ||
| const { client, url } = bucket(); | ||
| const response = await client.fetch(url(key), { method: "HEAD" }); | ||
| if (response.status === 404) return null; | ||
| if (!response.ok) throw await refusal("to describe a file", response); | ||
| return { bytes: Number(response.headers.get("content-length") ?? 0), contentType: response.headers.get("content-type") ?? "application/octet-stream" }; | ||
| } | ||
|
|
||
| /** A file as R2 answers it, its body a stream: read it once. Null when R2 holds nothing under `key`; throws when R2 can't be read. */ | ||
| export async function read(key: string) { | ||
| const { client, url } = bucket(); | ||
| const response = await client.fetch(url(key)); | ||
| if (response.status === 404) return null; | ||
| if (!response.ok || !response.body) throw await refusal("to read a file", response); | ||
| return response; | ||
| } | ||
|
|
||
| /** Keeps `body` under `key`. Its length is said, as R2 refuses a write without one (411). */ | ||
| export async function write(key: string, body: Blob | Uint8Array | string, contentType: string) { | ||
| const { client, url } = bucket(); | ||
| const bytes = body instanceof Blob ? new Uint8Array(await body.arrayBuffer()) : typeof body === "string" ? new TextEncoder().encode(body) : body; | ||
| const response = await client.fetch(url(key), { method: "PUT", body: bytes.buffer.byteLength === bytes.byteLength ? (bytes.buffer as ArrayBuffer) : bytes.slice().buffer, headers: { "Content-Type": contentType, "Content-Length": String(bytes.length) } }); | ||
| if (!response.ok) throw await refusal("to keep a file", response); | ||
| return bytes.length; | ||
| } | ||
|
|
||
| /** | ||
| * Copies a file to `to`, within the bucket, as R2 holds it now. A file sent with one signed PUT is copied to a key no | ||
| * address was ever signed for, so the address it came by, which works until it expires, can't change it once it was | ||
| * checked. Up to 5 GiB, which every file sent with one PUT is (`UPLOAD_PART_BYTES`). | ||
| */ | ||
| export async function copy(from: string, to: string) { | ||
| const { client, url, name } = bucket(); | ||
| const response = await client.fetch(url(to), { method: "PUT", headers: { "x-amz-copy-source": `/${name}/${from.split("/").map(encodeURIComponent).join("/")}` } }); | ||
| const text = response.ok ? await response.text() : ""; | ||
| if (!response.ok || text.includes("<Error>")) throw response.ok ? new Error(`R2 refused to copy a file: ${text.slice(0, 300)}`) : await refusal("to copy a file", response); | ||
| } | ||
|
|
||
| /** Deletes a file; one already gone counts as deleted. */ | ||
| export async function remove(key: string) { | ||
| const { client, url } = bucket(); | ||
| const response = await client.fetch(url(key), { method: "DELETE" }); | ||
| if (!response.ok && response.status !== 404) throw await refusal("to delete a file", response); | ||
| } | ||
|
|
||
| /** | ||
| * An address that reads the file for a few minutes, named `filename`, shown in the browser or saved, and said to be | ||
| * `contentType` whatever it was sent as: a file uploaded as a report's PDF is never served as a page. | ||
| */ | ||
| export async function readAddress(key: string, { filename, inline, contentType }: { filename: string; inline: boolean; contentType: string }) { | ||
| const disposition = `${inline ? "inline" : "attachment"}; filename="${filename.replace(/["\\\r\n]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(filename)}`; | ||
| return await signed(`${bucket().url(key)}?response-content-disposition=${encodeURIComponent(disposition)}&response-content-type=${encodeURIComponent(contentType)}`, "GET", READ_SECONDS); | ||
| } | ||
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,38 @@ | ||
| // Reading a file wherever it is kept: in R2 (./r2.ts), or in Convex storage, where every file was before R2 (#1695). | ||
| // A row of `storedFiles` names an R2 file; any other id is Convex storage's. | ||
| import { internal } from "../_generated/api"; | ||
| import type { Id } from "../_generated/dataModel"; | ||
| import type { ActionCtx, QueryCtx } from "../_generated/server"; | ||
| import { read } from "./r2"; | ||
| import type { FileRef } from "./validators"; | ||
|
|
||
| /** The Convex storage id a file has, when it is still there; null for one in R2. */ | ||
| export const inConvex = (ctx: QueryCtx, file: FileRef) => (ctx.db.normalizeId("storedFiles", file) ? null : (file as Id<"_storage">)); | ||
|
|
||
| /** | ||
| * A file's whole bytes as a Blob, for an action; null when it is gone. R2 failing to answer throws, with what it | ||
| * said, so the caller tries again rather than carry on without the file. | ||
| */ | ||
| export async function fileBlob(ctx: Pick<ActionCtx, "runQuery" | "storage">, file: FileRef): Promise<Blob | null> { | ||
| const kept = await ctx.runQuery(internal.files.uploads.keyOf, { id: file }); | ||
| if (!kept) return await ctx.storage.get(file as Id<"_storage">); | ||
| const response = await read(kept.key); | ||
| if (!response) console.error(JSON.stringify({ event: "upload-missing-in-r2", file, key: kept.key })); | ||
| return response ? new Blob([await response.arrayBuffer()], { type: kept.contentType }) : null; | ||
| } | ||
|
|
||
| /** A file's text, for an action; empty when it is gone. */ | ||
| export async function fileText(ctx: Pick<ActionCtx, "runQuery" | "storage">, file: FileRef) { | ||
| return (await (await fileBlob(ctx, file))?.text()) ?? ""; | ||
| } | ||
|
|
||
| /** | ||
| * The address a file is read at by whoever is given it: Convex storage's own for a file there, which lasts; for one | ||
| * in R2, the Convex site route `path` that checks who may have it and sends them to a signed address that lasts | ||
| * minutes (convex/reports/files.ts). Null when the file is gone. | ||
| */ | ||
| export async function fileAddress(ctx: QueryCtx, file: FileRef, path: string) { | ||
| const stored = inConvex(ctx, file); | ||
| if (stored) return await ctx.storage.getUrl(stored); | ||
| return `${process.env.CONVEX_SITE_URL!.replace(/\/$/, "")}${path}`; | ||
| } |
Oops, something went wrong.
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.