Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 7 additions & 7 deletions components/reports/publish-flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import { stepBack, withoutKeys } from "@/lib/url-state/step-back";
import { useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href";
import { inWorkspace, useWorkspace, useWorkspaceScope } from "@/lib/workspaces/url";
import { MAX_PDF_BYTES, MAX_PDF_MB } from "@/lib/files/limits";
import { useUpload } from "@/lib/files/upload";
import { cn, finePointer } from "@/lib/utils";


Expand Down Expand Up @@ -1980,11 +1981,9 @@ function UploadStep({ report, workspaceId, onAttached, onBack, onNext }: { repor
void setBy(picked);
if (picked === "added" && report.pdf?.lacksByline && report.pdf.bylineBy !== "added") void addByline(here).catch(failed(t("bylineBy.addFailed")));
};
const put = async (file: Blob, type: string) => {
const response = await fetch(await startUpload(here), { method: "POST", headers: { "Content-Type": type }, body: file });
if (!response.ok) throw new Error(t("uploadLost"));
return ((await response.json()) as { storageId: Id<"_storage"> }).storageId;
};
const upload = useUpload();
// Straight to R2 (lib/files/upload.ts), once the report has said it takes a PDF now.
const put = (file: Blob, purpose: "report-pdf" | "report-cover", name: string) => upload(file, purpose, { name });
// A PDF is being read from the moment it's the report's until its pages are known. A reading that has gone on too
// long is given up on here, so the PDF can be sent again. One already read, as when the author comes back to
// replace it, is neither.
Expand All @@ -2003,9 +2002,10 @@ function UploadStep({ report, workspaceId, onAttached, onBack, onNext }: { repor
let arrived = false;
try {
// The PDF goes up while its first page is drawn here: a cover that can't be drawn leaves the title page.
await startUpload(here);
const [file, cover] = await Promise.all([
put(picked, "application/pdf"),
drawCover(picked).then(async (drawn) => (drawn ? { id: await put(drawn.picture, "image/jpeg"), shape: drawn.shape } : undefined)).catch(() => undefined),
put(new Blob([picked], { type: "application/pdf" }), "report-pdf", picked.name),
drawCover(picked).then(async (drawn) => (drawn ? { id: await put(new Blob([drawn.picture], { type: "image/jpeg" }), "report-cover", `${report.key}-page-1.jpg`), shape: drawn.shape } : undefined)).catch(() => undefined),
]);
arrived = true;
const refused = await attachPdf({ ...here, file, name: picked.name, bylineBy: by, ...(cover && { cover: cover.id, coverShape: cover.shape }) });
Expand Down
12 changes: 12 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,10 @@ import type * as featureFlags_admin from "../featureFlags/admin.js";
import type * as featureFlags_guard from "../featureFlags/guard.js";
import type * as featureFlags_internal from "../featureFlags/internal.js";
import type * as featureFlags_queries from "../featureFlags/queries.js";
import type * as files_r2 from "../files/r2.js";
import type * as files_read from "../files/read.js";
import type * as files_uploads from "../files/uploads.js";
import type * as files_validators from "../files/validators.js";
import type * as http from "../http.js";
import type * as lib_analytics from "../lib/analytics.js";
import type * as lib_analyticsEvents from "../lib/analyticsEvents.js";
Expand Down Expand Up @@ -366,6 +370,8 @@ import type * as migrations_placeRatings from "../migrations/placeRatings.js";
import type * as migrations_publicationBalance from "../migrations/publicationBalance.js";
import type * as migrations_recordApprovedQueries from "../migrations/recordApprovedQueries.js";
import type * as migrations_reportAuthorNames from "../migrations/reportAuthorNames.js";
import type * as migrations_reportFilesToR2 from "../migrations/reportFilesToR2.js";
import type * as migrations_reportFilesToR2Rows from "../migrations/reportFilesToR2Rows.js";
import type * as migrations_reportIntake from "../migrations/reportIntake.js";
import type * as migrations_reportIssn from "../migrations/reportIssn.js";
import type * as migrations_revokeDeletedOrganizationMemberships from "../migrations/revokeDeletedOrganizationMemberships.js";
Expand Down Expand Up @@ -844,6 +850,10 @@ declare const fullApi: ApiFromModules<{
"featureFlags/guard": typeof featureFlags_guard;
"featureFlags/internal": typeof featureFlags_internal;
"featureFlags/queries": typeof featureFlags_queries;
"files/r2": typeof files_r2;
"files/read": typeof files_read;
"files/uploads": typeof files_uploads;
"files/validators": typeof files_validators;
http: typeof http;
"lib/analytics": typeof lib_analytics;
"lib/analyticsEvents": typeof lib_analyticsEvents;
Expand Down Expand Up @@ -929,6 +939,8 @@ declare const fullApi: ApiFromModules<{
"migrations/publicationBalance": typeof migrations_publicationBalance;
"migrations/recordApprovedQueries": typeof migrations_recordApprovedQueries;
"migrations/reportAuthorNames": typeof migrations_reportAuthorNames;
"migrations/reportFilesToR2": typeof migrations_reportFilesToR2;
"migrations/reportFilesToR2Rows": typeof migrations_reportFilesToR2Rows;
"migrations/reportIntake": typeof migrations_reportIntake;
"migrations/reportIssn": typeof migrations_reportIssn;
"migrations/revokeDeletedOrganizationMemberships": typeof migrations_revokeDeletedOrganizationMemberships;
Expand Down
8 changes: 8 additions & 0 deletions convex/crons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ crons.interval(
{},
);

// Uploads never finished, and uploaded files nothing took, are deleted from R2 (files/uploads.ts).
crons.interval(
"sweep stray uploads",
{ hours: 1 },
internal.files.uploads.sweep,
{},
);

// Custom domains that stop pointing at us should stop showing as working.
crons.interval(
"recheck evidence library custom domains",
Expand Down
120 changes: 120 additions & 0 deletions convex/files/r2.ts
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);
Comment thread
sickerine marked this conversation as resolved.
Resolved

/** 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);
}
38 changes: 38 additions & 0 deletions convex/files/read.ts
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}`;
}
Loading
Loading