diff --git a/components/reports/publish-flow.tsx b/components/reports/publish-flow.tsx index e5a48f327..ec6780702 100644 --- a/components/reports/publish-flow.tsx +++ b/components/reports/publish-flow.tsx @@ -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"; @@ -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. @@ -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 }) }); diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 9757be908..93c149312 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -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"; @@ -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"; @@ -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; @@ -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; diff --git a/convex/crons.ts b/convex/crons.ts index f83b6d960..17c3ba16c 100644 --- a/convex/crons.ts +++ b/convex/crons.ts @@ -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", diff --git a/convex/files/r2.ts b/convex/files/r2.ts new file mode 100644 index 000000000..070060b33 --- /dev/null +++ b/convex/files/r2.ts @@ -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>/.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 = `${etags.map((etag, at) => `${at + 1}${etag.replace(/[<>&]/g, "")}`).join("")}`; + 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("")) 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("")) 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); +} diff --git a/convex/files/read.ts b/convex/files/read.ts new file mode 100644 index 000000000..5110fe82d --- /dev/null +++ b/convex/files/read.ts @@ -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, file: FileRef): Promise { + 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, 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}`; +} diff --git a/convex/files/uploads.test.ts b/convex/files/uploads.test.ts new file mode 100644 index 000000000..d1ddff93a --- /dev/null +++ b/convex/files/uploads.test.ts @@ -0,0 +1,112 @@ +// Uploads to R2 (#1695): a file is only its sender's to finish and hand on, it must arrive whole, and what nothing +// takes is swept away. R2 is answered by a fetch stub that holds what it is sent. +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { api, internal } from "../_generated/api"; +import type { Id } from "../_generated/dataModel"; +import { UPLOAD_PART_BYTES } from "../../lib/files/limits"; +import { R2_TEST, setup, stubUploads } from "../reports/reports.test-support"; +import { freshUpload } from "./uploads"; + +/** What the stub R2 holds, by key, and the parts of uploads under way. */ +let held: Map; + +beforeEach(() => { + held = new Map(); + stubUploads(); + vi.stubGlobal("fetch", async (input: string | Request, init: RequestInit = {}) => { + const request = typeof input === "string" ? new Request(input, init) : input; + const url = new URL(request.url); + if (!url.href.startsWith(R2_TEST)) return new Response("not here", { status: 404 }); + const key = decodeURIComponent(url.pathname.replace("/uploads/", "")); + if (request.method === "HEAD") return held.has(key) ? new Response(null, { headers: { "content-length": String(held.get(key)), "content-type": "application/pdf" } }) : new Response(null, { status: 404 }); + if (request.method === "POST" && url.searchParams.has("uploads")) return new Response("up-1"); + if (request.method === "POST" && url.searchParams.has("uploadId")) { + held.set(key, Number(url.searchParams.get("size") ?? 0) || held.get(`${key}#parts`) || 0); + return new Response(""); + } + if (request.method === "PUT" && request.headers.get("x-amz-copy-source")) { + const from = decodeURIComponent(request.headers.get("x-amz-copy-source")!.replace("/uploads/", "")); + held.set(key, held.get(from)!); + return new Response(""); + } + if (request.method === "DELETE") return held.delete(key), new Response(null, { status: 204 }); + return new Response("unexpected", { status: 400 }); + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +const keyOf = (world: Awaited>, fileId: Id<"storedFiles">) => world.t.run(async (ctx) => (await ctx.db.get("storedFiles", fileId))!.key); + +describe("uploads to R2", () => { + it("gives one address for a small file and parts for a large one, and refuses one too large or empty", async () => { + const world = await setup(); + const small = await world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "report.pdf", contentType: "application/pdf", bytes: 2048 }); + expect(small.url).toMatch(/^https:\/\/r2\.test\/uploads\/report-pdf\/.+\/report\.pdf\?.*X-Amz-Signature=/); + const large = await world.author.action(api.files.uploads.start, { purpose: "report-supplement", name: "data.zip", contentType: "application/zip", bytes: UPLOAD_PART_BYTES * 2 + 1 }); + expect(large.parts).toHaveLength(3); + expect(large.partBytes).toBe(UPLOAD_PART_BYTES); + await expect(world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "huge.pdf", contentType: "application/pdf", bytes: 101 * 1024 * 1024 })).rejects.toThrow(/too large/); + await expect(world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "empty.pdf", contentType: "application/pdf", bytes: 0 })).rejects.toThrow(/empty/); + }); + + it("is finished only by its sender, once R2 holds all of it, and is then theirs alone to hand on", async () => { + const world = await setup(); + const { fileId } = await world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "report.pdf", contentType: "application/pdf", bytes: 2048 }); + // Not arrived yet: R2 holds nothing. + await expect(world.author.action(api.files.uploads.finish, { fileId })).rejects.toThrow(/didn't arrive whole/); + held.set(await keyOf(world, fileId), 1000); + await expect(world.author.action(api.files.uploads.finish, { fileId })).rejects.toThrow(/didn't arrive whole/); + held.set(await keyOf(world, fileId), 2048); + await expect(world.stranger.action(api.files.uploads.finish, { fileId })).rejects.toThrow(/isn't one of yours/); + await world.author.action(api.files.uploads.finish, { fileId }); + // Kept under a key of its own, which no address was signed for; the copy it was sent as goes. + const sent = [...held.keys()].find((key) => !key.startsWith("kept/")); + expect(await keyOf(world, fileId)).toBe(`kept/${sent}`); + await world.t.finishAllScheduledFunctions(() => {}); + expect([...held.keys()]).toEqual([`kept/${sent}`]); + const [author, stranger] = await world.t.run(async (ctx) => { + const user = (clerkId: string) => ctx.db.query("users").withIndex("by_clerk_id", (q) => q.eq("clerkId", clerkId)).unique(); + return [(await user("author"))!._id, (await user("stranger"))!._id]; + }); + expect(await world.t.run((ctx) => freshUpload(ctx, fileId, author, "report-pdf"))).toMatchObject({ bytes: 2048, state: "kept" }); + expect(await world.t.run((ctx) => freshUpload(ctx, fileId, stranger, "report-pdf"))).toBeNull(); + expect(await world.t.run((ctx) => freshUpload(ctx, fileId, author, "report-cover"))).toBeNull(); + }); + + it("sweeps away uploads never finished and files nothing took, leaves held ones, and tries a failed delete again", async () => { + vi.useFakeTimers(); + try { + const world = await setup(); + const sending = await world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "a.pdf", contentType: "application/pdf", bytes: 10 }); + const unheld = await world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "b.pdf", contentType: "application/pdf", bytes: 10 }); + const kept = await world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "c.pdf", contentType: "application/pdf", bytes: 10 }); + for (const { fileId } of [unheld, kept]) { + held.set(await keyOf(world, fileId), 10); + await world.author.action(api.files.uploads.finish, { fileId }); + } + await world.t.run((ctx) => ctx.db.patch("storedFiles", kept.fileId, { heldBy: "report:r1" })); + vi.advanceTimersByTime(3 * 24 * 60 * 60 * 1000); + await world.t.finishAllScheduledFunctions(vi.runAllTimers); + expect(await world.t.mutation(internal.files.uploads.sweep, {})).toBe(2); + const state = () => world.t.run(async (ctx) => (await Promise.all([sending, unheld, kept].map(({ fileId }) => ctx.db.get("storedFiles", fileId)))).map((file) => file?.state ?? null)); + // Their rows stay until R2 has let the bytes go. + expect(await state()).toEqual(["dropping", "dropping", "kept"]); + // R2 refuses the deletes at first: the rows wait, and the sweep tries again an hour on. + const answer = globalThis.fetch; + vi.stubGlobal("fetch", async (input: string | Request, init?: RequestInit) => ((typeof input === "string" ? init?.method : input.method) === "DELETE" ? new Response("busy", { status: 503 }) : answer(input, init))); + await world.t.finishAllScheduledFunctions(vi.runAllTimers); + expect(await state()).toEqual(["dropping", "dropping", "kept"]); + vi.stubGlobal("fetch", answer); + vi.advanceTimersByTime(2 * 60 * 60 * 1000); + expect(await world.t.mutation(internal.files.uploads.sweep, {})).toBe(2); + await world.t.finishAllScheduledFunctions(vi.runAllTimers); + expect(await state()).toEqual([null, null, "kept"]); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/convex/files/uploads.ts b/convex/files/uploads.ts new file mode 100644 index 000000000..503e92b66 --- /dev/null +++ b/convex/files/uploads.ts @@ -0,0 +1,249 @@ +// Files sent to R2 (#1695): the browser asks for an address here, sends the file straight to R2, and says when it is +// done. What it uploaded is then a file only it may hand to something that takes files (a report, say), for a while +// (`freshUpload`). The server keeps the files it makes the same way (`keepFile`), and reads any of them back (`keyOf`). +import { v } from "convex/values"; +import { internal } from "../_generated/api"; +import type { Doc, Id } from "../_generated/dataModel"; +import type { ActionCtx, MutationCtx } from "../_generated/server"; +import { refuseApps, requireAuth } from "../lib/auth"; +import { createError } from "../lib/errors"; +import { action, internalAction, internalMutation, internalQuery } from "../lib/functions"; +import { UPLOAD_MAX_BYTES, UPLOAD_PART_BYTES } from "../../lib/files/limits"; +import { copy, dropParts, finishParts, headOf, partAddresses, remove, sendAddress, startParts, write } from "./r2"; +import { filePurposeValidator, uploadPurposeValidator, uploadTargetValidator } from "./validators"; + +type Purpose = Doc<"storedFiles">["purpose"]; + +/** The longest name a file keeps. */ +const NAME_MAX = 200; +/** How long after it arrived a file can still be handed to something. */ +const FRESH_MS = 60 * 60 * 1000; +/** A file still being sent this long after it was asked for is given up. */ +const SENDING_MS = 2 * 24 * 60 * 60 * 1000; +/** A kept file nothing took is deleted this long after it arrived. */ +const UNHELD_MS = 24 * 60 * 60 * 1000; +/** Files looked at a run of `sweep`. */ +const SWEPT = 100; + +/** Where a file is kept: by what it is, the month, and an id no one can guess, under the name it came with. */ +function keyFor(purpose: Purpose, name: string) { + const month = new Date().toISOString().slice(0, 7); + const safe = name.normalize("NFKD").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "").slice(-120) || "file"; + return `${purpose}/${month}/${crypto.randomUUID()}/${safe}`; +} + +const tidyName = (name: string) => name.trim().slice(-NAME_MAX) || "file"; + +export const begin = internalMutation({ + args: { purpose: uploadPurposeValidator, name: v.string(), contentType: v.string(), bytes: v.number(), key: v.string() }, + returns: v.id("storedFiles"), + handler: async (ctx, { purpose, name, contentType, bytes, key }) => { + await refuseApps(ctx); + const user = await requireAuth(ctx); + if (!Number.isInteger(bytes) || bytes <= 0) throw createError("VALIDATION_ERROR", "That file is empty."); + if (bytes > UPLOAD_MAX_BYTES[purpose]) throw createError("VALIDATION_ERROR", "That file is too large."); + return await ctx.db.insert("storedFiles", { key, name: tidyName(name), contentType: contentType.slice(0, 200) || "application/octet-stream", bytes, purpose, by: user._id, state: "sending" }); + }, +}); + +export const sentInParts = internalMutation({ + args: { fileId: v.id("storedFiles"), uploadId: v.string(), count: v.number() }, + returns: v.null(), + handler: async (ctx, { fileId, uploadId, count }) => { + await ctx.db.patch("storedFiles", fileId, { parts: { uploadId, count } }); + return null; + }, +}); + +/** + * Where the browser sends a file: one address, or one for each part of `partBytes` when it is larger. It says when + * it is done with `finish`. + */ +export const start = action({ + args: { purpose: uploadPurposeValidator, name: v.string(), contentType: v.string(), bytes: v.number() }, + returns: uploadTargetValidator, + handler: async (ctx, args): Promise<{ fileId: Id<"storedFiles">; url?: string; partBytes?: number; parts?: string[] }> => { + const key = keyFor(args.purpose, args.name); + const fileId: Id<"storedFiles"> = await ctx.runMutation(internal.files.uploads.begin, { ...args, key }); + if (args.bytes <= UPLOAD_PART_BYTES) return { fileId, url: await sendAddress(key) }; + const count = Math.ceil(args.bytes / UPLOAD_PART_BYTES); + const uploadId = await startParts(key, args.contentType || "application/octet-stream"); + await ctx.runMutation(internal.files.uploads.sentInParts, { fileId, uploadId, count }); + return { fileId, partBytes: UPLOAD_PART_BYTES, parts: await partAddresses(key, uploadId, count) }; + }, +}); + +/** A file the signed-in person is sending, as `start` began it; null for any other. */ +export const sending = internalQuery({ + args: { fileId: v.id("storedFiles") }, + returns: v.union(v.null(), v.object({ key: v.string(), bytes: v.number(), parts: v.optional(v.object({ uploadId: v.string(), count: v.number() })) })), + handler: async (ctx, { fileId }) => { + const user = await requireAuth(ctx); + const file = await ctx.db.get("storedFiles", fileId); + if (!file || file.by !== user._id || file.state !== "sending") return null; + return { key: file.key, bytes: file.bytes, ...(file.parts && { parts: file.parts }) }; + }, +}); + +export const arrived = internalMutation({ + args: { fileId: v.id("storedFiles"), contentType: v.string(), key: v.optional(v.string()) }, + returns: v.null(), + handler: async (ctx, { fileId, contentType, key }) => { + const file = await ctx.db.get("storedFiles", fileId); + if (!file || file.state !== "sending") return null; + await ctx.db.patch("storedFiles", fileId, { state: "kept", keptAt: Date.now(), contentType, parts: undefined, ...(key && { key }) }); + // The copy it was sent as, which the address it came by can still change, goes. + if (key && key !== file.key) await dropKey(ctx, file, file.key); + return null; + }, +}); + +/** Where a file sent with one PUT is kept once it is checked: a key no address was ever signed for. */ +const keptKey = (key: string) => `kept/${key}`; + +/** + * Says the browser has sent all of a file (each part's ETag, in order, for one sent in parts). Checks R2 holds all of + * it. A file sent with one PUT is copied to a key no address was signed for, since that address works until it + * expires: the file a report holds can't be changed after it was checked. A file sent in parts needs no copy: once + * they are joined, their addresses write to nothing. + */ +export const finish = action({ + args: { fileId: v.id("storedFiles"), etags: v.optional(v.array(v.string())) }, + returns: v.null(), + handler: async (ctx, { fileId, etags }): Promise => { + const file = await ctx.runQuery(internal.files.uploads.sending, { fileId }); + if (!file) throw createError("NOT_FOUND", "That upload isn't one of yours, or it has already finished."); + if (file.parts) { + if (!etags || etags.length !== file.parts.count) throw createError("VALIDATION_ERROR", "Some parts of the file didn't arrive. Upload it again."); + await finishParts(file.key, file.parts.uploadId, etags); + } + const key = file.parts ? file.key : keptKey(file.key); + if (!file.parts && (await headOf(file.key))?.bytes === file.bytes) await copy(file.key, key); + const held = await headOf(key); + if (!held || held.bytes !== file.bytes) { + console.error(JSON.stringify({ event: "upload-incomplete", fileId, expected: file.bytes, held: held?.bytes ?? null })); + throw createError("VALIDATION_ERROR", "The file didn't arrive whole. Upload it again."); + } + await ctx.runMutation(internal.files.uploads.arrived, { fileId, contentType: held.contentType, ...(key !== file.key && { key }) }); + return null; + }, +}); + +/** + * A file the person `userId` uploaded moments ago and nothing has taken yet, which they may now hand to something; + * null for any other. Its id is only known to the browser that sent it. + */ +export async function freshUpload(ctx: MutationCtx, fileId: Id<"storedFiles">, userId: Id<"users">, purpose: Purpose) { + const file = await ctx.db.get("storedFiles", fileId); + if (!file || file.by !== userId || file.state !== "kept" || file.heldBy !== undefined || file.purpose !== purpose) return null; + return Date.now() - (file.keptAt ?? 0) > FRESH_MS ? null : file; +} + +/** Marks a file as `holder`'s, so it is kept. */ +export const holdFile = (ctx: MutationCtx, fileId: Id<"storedFiles">, holder: string) => ctx.db.patch("storedFiles", fileId, { heldBy: holder }); + +/** + * Deletes a file. Its row stays, `dropping`, until R2 has let the bytes go (`erase`), so a delete that fails is tried + * again by the sweep and nothing is left in R2 that no row names. + */ +export async function dropFile(ctx: MutationCtx, fileId: Id<"storedFiles">) { + const file = await ctx.db.get("storedFiles", fileId); + if (!file || file.state === "dropping") return; + await ctx.db.patch("storedFiles", fileId, { state: "dropping", droppedAt: Date.now(), heldBy: undefined }); + await ctx.scheduler.runAfter(0, internal.files.uploads.erase, { fileId }); +} + +/** Deletes `key`, a copy `file` no longer is, the same way: a row of its own, `dropping`, until R2 lets it go. */ +async function dropKey(ctx: MutationCtx, file: Doc<"storedFiles">, key: string) { + const fileId = await ctx.db.insert("storedFiles", { key, name: file.name, contentType: file.contentType, bytes: file.bytes, purpose: file.purpose, state: "dropping", droppedAt: Date.now() }); + await ctx.scheduler.runAfter(0, internal.files.uploads.erase, { fileId }); +} + +export const dropping = internalQuery({ + args: { fileId: v.id("storedFiles") }, + returns: v.union(v.null(), v.object({ key: v.string(), uploadId: v.optional(v.string()) })), + handler: async (ctx, { fileId }) => { + const file = await ctx.db.get("storedFiles", fileId); + return file?.state === "dropping" ? { key: file.key, ...(file.parts && { uploadId: file.parts.uploadId }) } : null; + }, +}); + +export const erased = internalMutation({ + args: { fileId: v.id("storedFiles") }, + returns: v.null(), + handler: async (ctx, { fileId }) => { + const file = await ctx.db.get("storedFiles", fileId); + if (file?.state === "dropping") await ctx.db.delete("storedFiles", fileId); + return null; + }, +}); + +/** Lets a dropped file's bytes go in R2, then its row. A failure leaves the row for the sweep to try again. */ +export const erase = internalAction({ + args: { fileId: v.id("storedFiles") }, + returns: v.null(), + handler: async (ctx, { fileId }) => { + const file = await ctx.runQuery(internal.files.uploads.dropping, { fileId }); + if (!file) return null; + try { + if (file.uploadId) await dropParts(file.key, file.uploadId); + await remove(file.key); + } catch (error) { + console.error(JSON.stringify({ event: "upload-not-erased", fileId, key: file.key, error: String(error).slice(0, 300) })); + return null; + } + await ctx.runMutation(internal.files.uploads.erased, { fileId }); + return null; + }, +}); + +export const made = internalMutation({ + args: { key: v.string(), name: v.string(), contentType: v.string(), bytes: v.number(), purpose: filePurposeValidator }, + returns: v.id("storedFiles"), + handler: async (ctx, args) => await ctx.db.insert("storedFiles", { ...args, state: "sending" }), +}); + +/** + * Keeps a file the server made. Its row comes first, so a write that fails leaves one for the sweep. Nothing holds it + * until the function it was made for takes it (`holdFile`), so one whose maker failed before that is swept too. + */ +export async function keepFile(ctx: Pick, body: Blob | Uint8Array | string, { name, contentType, purpose }: { name: string; contentType: string; purpose: Purpose }) { + const key = keyFor(purpose, name); + const size = body instanceof Blob ? body.size : typeof body === "string" ? new TextEncoder().encode(body).length : body.length; + const fileId: Id<"storedFiles"> = await ctx.runMutation(internal.files.uploads.made, { key, name: tidyName(name), contentType, bytes: size, purpose }); + await write(key, body, contentType); + await ctx.runMutation(internal.files.uploads.arrived, { fileId, contentType }); + return fileId; +} + +/** Where a file is in R2, for an action that reads it; null when `id` names no kept file there (a file in Convex storage, say). */ +export const keyOf = internalQuery({ + args: { id: v.string() }, + returns: v.union(v.null(), v.object({ key: v.string(), name: v.string(), contentType: v.string(), bytes: v.number() })), + handler: async (ctx, { id }) => { + const fileId = ctx.db.normalizeId("storedFiles", id); + const file = fileId ? await ctx.db.get("storedFiles", fileId) : null; + return file?.state === "kept" ? { key: file.key, name: file.name, contentType: file.contentType, bytes: file.bytes } : null; + }, +}); + +/** How long a file waits to be deleted before its delete is tried again. */ +const ERASE_RETRY_MS = 60 * 60 * 1000; + +/** Deletes uploads never finished and kept files nothing took, and tries again deletes that failed, a run at a time. */ +export const sweep = internalMutation({ + args: {}, + returns: v.number(), + handler: async (ctx) => { + const now = Date.now(); + const stale = await ctx.db.query("storedFiles").withIndex("by_state", (q) => q.eq("state", "sending").lt("_creationTime", now - SENDING_MS)).take(SWEPT); + const unheld = await ctx.db.query("storedFiles").withIndex("by_heldBy_and_state_and_keptAt", (q) => q.eq("heldBy", undefined).eq("state", "kept").lt("keptAt", now - UNHELD_MS)).take(SWEPT); + for (const file of [...stale, ...unheld]) await dropFile(ctx, file._id); + const failed = await ctx.db.query("storedFiles").withIndex("by_state_and_droppedAt", (q) => q.eq("state", "dropping").lt("droppedAt", now - ERASE_RETRY_MS)).take(SWEPT); + for (const file of failed) { + await ctx.db.patch("storedFiles", file._id, { droppedAt: now }); + await ctx.scheduler.runAfter(0, internal.files.uploads.erase, { fileId: file._id }); + } + return stale.length + unheld.length + failed.length; + }, +}); diff --git a/convex/files/validators.ts b/convex/files/validators.ts new file mode 100644 index 000000000..9cc9570d6 --- /dev/null +++ b/convex/files/validators.ts @@ -0,0 +1,38 @@ +import { v, type Infer } from "convex/values"; +import { MAX_UPLOAD_PARTS } from "../../lib/files/limits"; +import { capped } from "../lib/listCaps"; + +/** What a file is uploaded as, which sets how large it may be (lib/files/limits.ts `UPLOAD_MAX_BYTES`). */ +export const uploadPurposeValidator = v.union(v.literal("report-pdf"), v.literal("report-cover"), v.literal("report-supplement")); +/** What a file is: one uploaded, or one the server made (the text read from a report's PDF). */ +export const filePurposeValidator = v.union(uploadPurposeValidator, v.literal("report-text")); + +/** + * A file kept in R2 (./r2.ts). `sending` while the browser sends it, `kept` once R2 holds all of it. `heldBy` names + * what it belongs to once something takes it (a report's PDF, say); a kept file nothing holds a day after it was sent + * is deleted (`sweep`), as is one never finished. A file sent with one PUT is kept under a key of its own once it is + * checked (`finish`). + */ +export const storedFileFields = { + key: v.string(), + name: v.string(), + contentType: v.string(), + bytes: v.number(), + purpose: filePurposeValidator, + /** Who sent it; none for a file the server made (a PDF with its byline page added, the text read from one). */ + by: v.optional(v.id("users")), + /** `dropping` once it is deleted, until R2 has let its bytes go. */ + state: v.union(v.literal("sending"), v.literal("kept"), v.literal("dropping")), + /** Sent in parts: the upload R2 joins them under. */ + parts: v.optional(v.object({ uploadId: v.string(), count: v.number() })), + keptAt: v.optional(v.number()), + droppedAt: v.optional(v.number()), + heldBy: v.optional(v.string()), +}; + +/** A file as reports keep it: in Convex storage, as every one was before R2, or in R2. */ +export const fileRefValidator = v.union(v.id("_storage"), v.id("storedFiles")); +export type FileRef = Infer; + +/** Where the browser sends a file: one address, or one for each part of `partBytes`. */ +export const uploadTargetValidator = v.object({ fileId: v.id("storedFiles"), url: v.optional(v.string()), partBytes: v.optional(v.number()), parts: capped(v.optional(v.array(v.string())), MAX_UPLOAD_PARTS) }); diff --git a/convex/http.ts b/convex/http.ts index 3490f726f..4a21b36a5 100644 --- a/convex/http.ts +++ b/convex/http.ts @@ -18,7 +18,7 @@ import { institutions as contactInstitutions, send as sendContact } from "./cont import { readCollectionItems } from "./evidenceLibraries/collectionSources"; import { COLLECTION_INVITATION_CALLS, serveCollectionInvitations } from "./evidenceLibraries/collectionInvitations"; import { download as downloadExport } from "./exports"; -import { kept as keptReportFile } from "./reports/files"; +import { kept as keptReportFile, open as openReportFile } from "./reports/files"; import { upload as uploadAssistantFile, uploadOptions as uploadAssistantFileOptions } from "./assistant/files"; import { requireAppUrl } from "./lib/env"; import { zoteroReturnUrl } from "./zotero/signInReturn"; @@ -32,6 +32,7 @@ import { const http = httpRouter(); http.route({path: "/export", method: "GET", handler: downloadExport}); http.route({path: "/reports/file", method: "GET", handler: keptReportFile}); +http.route({path: "/reports/open", method: "GET", handler: openReportFile}); // A signed-out visitor's AI overview, streamed to the Next app that vouches for them (convex/research/signedOutOverviews.ts). http.route({path: "/overviews/signed-out", method: "POST", handler: signedOutOverview}); // The contact form on openscholar.ai, through the Next app that vouches for its visitors (convex/contact.ts). diff --git a/convex/migrations/coverShapes.ts b/convex/migrations/coverShapes.ts index 6b4d643ac..ec74d2641 100644 --- a/convex/migrations/coverShapes.ts +++ b/convex/migrations/coverShapes.ts @@ -1,4 +1,6 @@ import { v } from "convex/values"; +import { fileBlob } from "../files/read"; +import { fileRefValidator, type FileRef } from "../files/validators"; import { internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; import { internalAction, internalMutation, internalQuery } from "../lib/functions"; @@ -20,9 +22,9 @@ export const run = internalAction({ let unread = 0; let cursor: string | null = null; for (;;) { - const page: { covers: Array<{ reportId: Id<"reports">; file: Id<"_storage"> }>; next: string | null } = await ctx.runQuery(internal.migrations.coverShapes.unshaped, { cursor }); + const page: { covers: Array<{ reportId: Id<"reports">; file: FileRef }>; next: string | null } = await ctx.runQuery(internal.migrations.coverShapes.unshaped, { cursor }); for (const { reportId, file } of page.covers) { - const blob = await ctx.storage.get(file); + const blob = await fileBlob(ctx, file); const size = blob ? jpegSize(new Uint8Array(await blob.arrayBuffer())) : null; const shape = size && size.height > 0 ? size.width / size.height : null; if (shape === null || !isCoverShape(shape)) { @@ -43,7 +45,7 @@ export const run = internalAction({ /** A page of reports, by their covers that have no shape yet. */ export const unshaped = internalQuery({ args: { cursor: v.union(v.string(), v.null()) }, - returns: v.object({ covers: v.array(v.object({ reportId: v.id("reports"), file: v.id("_storage") })), next: v.union(v.string(), v.null()) }), + returns: v.object({ covers: v.array(v.object({ reportId: v.id("reports"), file: fileRefValidator })), next: v.union(v.string(), v.null()) }), handler: async (ctx, { cursor }) => { const page = await ctx.db.query("reports").paginate({ cursor, numItems: 100 }); return { @@ -55,7 +57,7 @@ export const unshaped = internalQuery({ /** Keeps a cover's shape, when the report still has that cover and no shape for it. */ export const keep = internalMutation({ - args: { reportId: v.id("reports"), file: v.id("_storage"), shape: v.number() }, + args: { reportId: v.id("reports"), file: fileRefValidator, shape: v.number() }, returns: v.null(), handler: async (ctx, { reportId, file, shape }) => { const report = await ctx.db.get("reports", reportId); diff --git a/convex/migrations/reportFilesToR2.test.ts b/convex/migrations/reportFilesToR2.test.ts new file mode 100644 index 000000000..c3999dcf3 --- /dev/null +++ b/convex/migrations/reportFilesToR2.test.ts @@ -0,0 +1,40 @@ +// Report files kept in Convex storage before R2 (#1695) move to R2 and take their originals' place. +import { afterEach, describe, expect, it, vi } from "vitest"; +import { internal } from "../_generated/api"; +import { live, R2_TEST, row, setup, stubUploads } from "../reports/reports.test-support"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe("report files from Convex storage to R2", () => { + it("copies each file to R2 in its place, deletes the original, and changes nothing when run again", async () => { + stubUploads(); + const put: string[] = []; + vi.stubGlobal("fetch", async (input: string | Request, init: RequestInit = {}) => { + const request = typeof input === "string" ? new Request(input, init) : input; + if (request.url.startsWith(R2_TEST) && request.method === "PUT") put.push(new URL(request.url).pathname); + return new Response(null, { status: request.url.startsWith(R2_TEST) ? 200 : 404 }); + }); + const world = await setup(); + const { key, reportId } = await live(world); + const [pdf, cover] = await world.t.run(async (ctx) => { + const files = [await ctx.storage.store(new Blob(["%PDF-1.7 from before"], { type: "application/pdf" })), await ctx.storage.store(new Blob(["jpeg"], { type: "image/jpeg" }))]; + const report = (await ctx.db.get("reports", reportId))!; + await ctx.db.patch("reports", reportId, { pdf: { ...report.pdf!, file: files[0]!, text: undefined, original: undefined }, cover: { file: files[1]!, at: 1 } }); + await ctx.db.insert("reportFiles", { file: files[0]!, reportId }); + return files; + }); + expect(await world.t.action(internal.migrations.reportFilesToR2.run, { dryRun: true })).toEqual({ files: 2, bytes: 24, missing: 0 }); + expect(put).toEqual([]); + expect(await world.t.action(internal.migrations.reportFilesToR2.run, { dryRun: false })).toMatchObject({ files: 2 }); + expect(put).toHaveLength(2); + const after = await row(world.t, key); + const kept = await world.t.run(async (ctx) => [ctx.db.normalizeId("storedFiles", after.pdf!.file), ctx.db.normalizeId("storedFiles", after.cover!.file)]); + expect(kept.every(Boolean)).toBe(true); + expect(await world.t.run(async (ctx) => [await ctx.db.system.get(pdf!), await ctx.db.system.get(cover!)])).toEqual([null, null]); + expect(await world.t.run((ctx) => ctx.db.query("reportFiles").withIndex("by_file", (q) => q.eq("file", pdf!)).unique())).toBeNull(); + expect(await world.t.action(internal.migrations.reportFilesToR2.run, { dryRun: false })).toEqual({ files: 0, bytes: 0, missing: 0 }); + }); +}); diff --git a/convex/migrations/reportFilesToR2.ts b/convex/migrations/reportFilesToR2.ts new file mode 100644 index 000000000..6d1e923d4 --- /dev/null +++ b/convex/migrations/reportFilesToR2.ts @@ -0,0 +1,53 @@ +"use node"; + +import { v } from "convex/values"; +import { internal } from "../_generated/api"; +import type { Id } from "../_generated/dataModel"; +import { internalAction } from "../_generated/server"; +import { keepFile } from "../files/uploads"; +import type { Part } from "./reportFilesToR2Rows"; + +/** + * Copies every report's files still in Convex storage to R2 (#1695): its PDF, the one its author uploaded beside a + * PDF with the byline page added, the text read from it, and its first page's picture. Each copy takes the original's + * place on the report, then the original is deleted. In Node, which holds a 100 MB PDF where the default runtime + * can't. Run once per deployment after its Convex push, first with + * `dryRun` for the count: + * npx convex run migrations/reportFilesToR2:run '{"dryRun":true}' + * npx convex run migrations/reportFilesToR2:run '{"dryRun":false}' + * Safe to run again: a file already in R2 is left alone, and so is a copy whose report changed the file meanwhile + * (the copy is deleted instead). + */ +export const run = internalAction({ + args: { dryRun: v.boolean() }, + returns: v.object({ files: v.number(), bytes: v.number(), missing: v.number() }), + handler: async (ctx, { dryRun }): Promise<{ files: number; bytes: number; missing: number }> => { + let files = 0; + let bytes = 0; + let missing = 0; + let cursor: string | null = null; + for (;;) { + const read: { found: Array<{ reportId: Id<"reports">; key: string; part: Part; file: Id<"_storage"> }>; next: string | null } = await ctx.runQuery(internal.migrations.reportFilesToR2Rows.page, { cursor }); + for (const { reportId, key, part, file } of read.found) { + const blob = await ctx.storage.get(file); + if (!blob) { + missing++; + console.error(JSON.stringify({ event: "report-file-missing", reportId, key, part, file })); + continue; + } + files++; + bytes += blob.size; + if (dryRun) continue; + const name = part === "cover" ? `${key}-page-1.jpg` : part === "text" ? `${key}.txt` : `${key}${part === "original" ? "-original" : ""}.pdf`; + const contentType = blob.type || (part === "cover" ? "image/jpeg" : part === "text" ? "text/plain; charset=utf-8" : "application/pdf"); + const copy = await keepFile(ctx, blob, { name, contentType, purpose: part === "cover" ? "report-cover" : part === "text" ? "report-text" : "report-pdf" }); + await ctx.runMutation(internal.migrations.reportFilesToR2Rows.swap, { reportId, part, from: file, to: copy }); + } + if (read.next === null) break; + cursor = read.next; + } + console.log(JSON.stringify({ event: "report-files-to-r2", dryRun, files, bytes, missing })); + return { files, bytes, missing }; + }, +}); + diff --git a/convex/migrations/reportFilesToR2Rows.ts b/convex/migrations/reportFilesToR2Rows.ts new file mode 100644 index 000000000..b0b19da1d --- /dev/null +++ b/convex/migrations/reportFilesToR2Rows.ts @@ -0,0 +1,52 @@ +// The rows side of migrations/reportFilesToR2: which report files are still in Convex storage, and putting their copies in place. +import { v } from "convex/values"; +import type { Doc } from "../_generated/dataModel"; +import { internalMutation, internalQuery } from "../lib/functions"; +import { dropFile, holdFile } from "../files/uploads"; +import { inConvex } from "../files/read"; +import { reportHolder } from "../reports/validators"; + +/** A report's files, by where each sits on the report. */ +export const PARTS = ["pdf", "original", "text", "cover"] as const; +export type Part = (typeof PARTS)[number]; +export const partValidator = v.union(v.literal("pdf"), v.literal("original"), v.literal("text"), v.literal("cover")); + +const fileAt = (report: Doc<"reports">, part: Part) => (part === "cover" ? report.cover?.file : part === "pdf" ? report.pdf?.file : report.pdf?.[part]); + +/** One page of reports, with each of their files still in Convex storage. */ +export const page = internalQuery({ + args: { cursor: v.union(v.string(), v.null()) }, + returns: v.object({ found: v.array(v.object({ reportId: v.id("reports"), key: v.string(), part: partValidator, file: v.id("_storage") })), next: v.union(v.string(), v.null()) }), + handler: async (ctx, { cursor }) => { + const read = await ctx.db.query("reports").paginate({ cursor, numItems: 50 }); + const found = read.page.flatMap((report) => + PARTS.flatMap((part) => { + const file = fileAt(report, part); + const stored = file ? inConvex(ctx, file) : null; + return stored ? [{ reportId: report._id, key: report.key, part, file: stored }] : []; + }), + ); + return { found, next: read.isDone ? null : read.continueCursor }; + }, +}); + +/** Puts the copy in R2 in the original's place and deletes the original, unless the report's file changed meanwhile: then the copy goes. */ +export const swap = internalMutation({ + args: { reportId: v.id("reports"), part: partValidator, from: v.id("_storage"), to: v.id("storedFiles") }, + returns: v.null(), + handler: async (ctx, { reportId, part, from, to }) => { + const report = await ctx.db.get("reports", reportId); + if (!report || fileAt(report, part) !== from) { + await dropFile(ctx, to); + return null; + } + await holdFile(ctx, to, reportHolder(reportId)); + // Not a change anyone made: the report's own moment stays as it was. + if (part === "cover") await ctx.db.patch("reports", reportId, { cover: { ...report.cover!, file: to } }); + else await ctx.db.patch("reports", reportId, { pdf: { ...report.pdf!, [part === "pdf" ? "file" : part]: to } }); + const claim = await ctx.db.query("reportFiles").withIndex("by_file", (q) => q.eq("file", from)).unique(); + if (claim) await ctx.db.delete("reportFiles", claim._id); + if (await ctx.db.system.get(from)) await ctx.storage.delete(from); + return null; + }, +}); diff --git a/convex/reports/abstract.ts b/convex/reports/abstract.ts index 232f98254..e080cd88f 100644 --- a/convex/reports/abstract.ts +++ b/convex/reports/abstract.ts @@ -2,6 +2,7 @@ // An abstract written from a report's PDF when its author asks, on the details step: the reading copies only one the // PDF prints (./reader.ts), so a report whose PDF prints none can have one written, for its author to check and change. +import { fileText } from "../files/read"; import { generateText } from "ai"; import { v } from "convex/values"; import { internal } from "../_generated/api"; @@ -35,8 +36,7 @@ export const write = action({ const actor = workspaceId ? await ctx.runQuery(internal.workspaces.actor.signedInActor, { workspaceId }) : undefined; const source = await ctx.runQuery(internal.reports.readingState.abstractSource, { ...(actor && { actor }), key }); if (!source.modelId) throw createError("CONFLICT", "The model that reads reports isn't offered any more, so no abstract can be written now. Type one instead."); - const blob = await ctx.storage.get(source.text); - const text = blob ? (await blob.text()).slice(0, TEXT_LIMIT) : ""; + const text = (await fileText(ctx, source.text)).slice(0, TEXT_LIMIT); if (!text.trim()) throw createError("CONFLICT", "This report's PDF has no text to write an abstract from. Type one instead."); const named = /^[a-z]{2,3}$/i.test(language) ? new Intl.DisplayNames(["en"], { type: "language" }).of(language.toLowerCase()) : undefined; const { model, modelSlug } = await resolveOpenRouterModel(ctx, source.modelId); diff --git a/convex/reports/checkRuns.ts b/convex/reports/checkRuns.ts index bd383894f..8dc5fefd0 100644 --- a/convex/reports/checkRuns.ts +++ b/convex/reports/checkRuns.ts @@ -1,6 +1,7 @@ // What ./checks.ts, the action that runs a report's checks, reads before it starts and saves as it goes. Only the // latest run on the PDF it read counts: a run that a new PDF or a later run replaced saves nothing. import { v } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import { internalMutation } from "../lib/functions"; import { requireAuth } from "../lib/auth"; import { createError } from "../lib/errors"; @@ -34,14 +35,14 @@ export const start = internalMutation({ /** The address of the identifier its byline prints, which a check's `{doi}` stands for. */ printed: v.string(), byline: v.string(), - text: v.union(v.id("_storage"), v.null()), + text: v.union(fileRefValidator, v.null()), version: v.number(), checks: v.array(v.object({ ...checkValidator.fields, model: v.union(v.id("models"), v.null()) })), changes: v.boolean(), /** The licence the report was signed under: its details are checked, kept and printed with it, whatever was sent. */ licence: licenceValidator, /** The PDF whose last page Openscholar added, for a report on its way out: that page is written again with these details. */ - page: v.optional(v.object({ file: v.id("_storage"), at: v.number(), line: v.string(), series: v.string(), publisher: v.string(), /** The PDF as its author uploaded it, which the page is made from. */ original: v.optional(v.id("_storage")) })), + page: v.optional(v.object({ file: fileRefValidator, name: v.string(), at: v.number(), line: v.string(), series: v.string(), publisher: v.string(), /** The PDF as its author uploaded it, which the page is made from. */ original: v.optional(fileRefValidator) })), })), handler: async (ctx, { workspaceId, key, metadata, runId, from }) => { const actor = await actorFor(ctx, await requireAuth(ctx), workspaceId); @@ -99,7 +100,7 @@ export const start = internalMutation({ checks: await Promise.all(on.map(async (check) => ({ ...check, model: (await slugPick(ctx, check.modelId, check.effort, "screening"))?.modelId ?? null }))), changes, licence: licenceOf(report), - ...(!changes && report.pdf?.stamped && { page: { file: report.pdf.file, ...(report.pdf.original && { original: report.pdf.original }), at: report.pdf.at, line: report.byline, series: series.name, publisher: series.publisher } }), + ...(!changes && report.pdf?.stamped && { page: { file: report.pdf.file, name: report.pdf.name, ...(report.pdf.original && { original: report.pdf.original }), at: report.pdf.at, line: report.byline, series: series.name, publisher: series.publisher } }), }; }, }); diff --git a/convex/reports/checks.ts b/convex/reports/checks.ts index 6641b0df8..3c8cdfcc0 100644 --- a/convex/reports/checks.ts +++ b/convex/reports/checks.ts @@ -3,6 +3,9 @@ // Runs a report's checks side by side and saves each answer the moment it comes, then decides where the report // stands (./checkRuns.ts). The checks take from under a second (the byline) to about ten (Already published). A page // that leaves stops nothing: the checks still finish and their outcome is still saved. +import { keepFile } from "../files/uploads"; +import { fileText } from "../files/read"; +import type { FileRef } from "../files/validators"; import { generateText, Output } from "ai"; import { v } from "convex/values"; import { z } from "zod"; @@ -93,14 +96,14 @@ async function runCheck(check: Check, on: CheckModel & { name: string }, report: * added: it is written again with the ones its author is sending to the checks. Throws when it can't be, so a report * never goes on to be published with a page that says other details than its own. */ -async function restamp(ctx: ActionCtx, reportId: Id<"reports">, runId: string, page: { file: Id<"_storage">; original?: Id<"_storage">; at: number; line: string; series: string; publisher: string }, details: Metadata) { +async function restamp(ctx: ActionCtx, reportId: Id<"reports">, runId: string, page: { file: FileRef; original?: FileRef; name: string; at: number; line: string; series: string; publisher: string }, details: Metadata) { // Loaded here, by the runs that write a page: the checks of every other report never load the PDF library. const { stampedPdf } = await import("./stamping"); // Made from the PDF its author uploaded; a report stamped before that was kept has its last page replaced instead. const said = { line: page.line, series: page.series, publisher: page.publisher, details }; const { original, file: stamped } = page; const next = original ? await stampedPdf(() => storedBytes(ctx, original), said) : await stampedPdf(() => storedBytes(ctx, stamped), said, { replaceLast: true }); - const file = await ctx.storage.store(next.file); + const file = await keepFile(ctx, next.file, { name: page.name, contentType: "application/pdf", purpose: "report-pdf" }); await ctx.runMutation(internal.reports.readingState.restamped, { reportId, runId, at: page.at, file, bytes: next.bytes }); } @@ -116,7 +119,7 @@ export const run = action({ const started = await ctx.runMutation(internal.reports.checkRuns.start, { workspaceId, key, metadata, runId, from }); if ("unchanged" in started) throw createError("VALIDATION_ERROR", `These are the details your report already has, so there is nothing to change.${started.waiting ? " To give up the changes that are waiting, discard them." : ""}`); const { reportId } = started; - const text = started.text ? await (await ctx.storage.get(started.text))?.text() ?? "" : ""; + const text = started.text ? await fileText(ctx, started.text) : ""; // Before the checks, so a report is never ready with a page that says other details: what goes live is the PDF // with these on it. A page that can't be written ends the run here, and its author is told what to do. if (started.page) { @@ -146,7 +149,7 @@ export const run = action({ return await Promise.all( alike.map(async ({ text: file, ...report }) => ({ ...report, - abstract: report.abstract.trim() || (file ? reportSays({ abstract: "", text: (await (await ctx.storage.get(file))?.text()) ?? "" }) : ""), + abstract: report.abstract.trim() || (file ? reportSays({ abstract: "", text: await fileText(ctx, file) }) : ""), })), ); } catch (error) { diff --git a/convex/reports/files.ts b/convex/reports/files.ts index 439ad6361..373fa43e6 100644 --- a/convex/reports/files.ts +++ b/convex/reports/files.ts @@ -1,13 +1,18 @@ -// A withdrawn report's files (plans/publish-reports). A file in Convex storage keeps one address for as long as it -// exists, and a live report's PDF and cover were handed to everyone who read its page. When the report is withdrawn -// each is stored again under a new address and the old file is deleted, so the addresses already out stop working. +// A report's files as readers reach them (plans/publish-reports). A file in R2 (convex/files) is never handed out by +// its own address: these routes check who may have it each time and send them to a signed address that lasts minutes. +// A file still in Convex storage, from before R2, keeps one address for as long as it exists, and a live report's PDF +// and cover were handed to everyone who read its page: when the report is withdrawn each is stored again under a new +// address and the old file is deleted, so the addresses already out stop working. import { v } from "convex/values"; import { fileOut } from "../../lib/reports/report"; import { internal } from "../_generated/api"; -import { httpAction } from "../_generated/server"; +import { httpAction, type ActionCtx } from "../_generated/server"; +import type { FileRef } from "../files/validators"; import { readConvexErrorData } from "../lib/errors"; import type { Id } from "../_generated/dataModel"; import { internalAction, internalMutation, internalQuery } from "../lib/functions"; +import { inConvex } from "../files/read"; +import { readAddress } from "../files/r2"; const pairValidator = v.object({ from: v.id("_storage"), to: v.id("_storage") }); @@ -18,7 +23,10 @@ export const held = internalQuery({ handler: async (ctx, { reportId }) => { const report = await ctx.db.get("reports", reportId); if (!report || fileOut(report)) return null; - return { ...(report.pdf && { pdf: report.pdf.file }), ...(report.cover && { cover: report.cover.file }) }; + // Only a file in Convex storage has an address that outlasts the moment: one in R2 is never handed out. + const pdf = report.pdf && inConvex(ctx, report.pdf.file); + const cover = report.cover && inConvex(ctx, report.cover.file); + return { ...(pdf && { pdf }), ...(cover && { cover }) }; }, }); @@ -36,8 +44,8 @@ export const swap = internalMutation({ await ctx.storage.delete(pair.from); return true; }; - const newPdf = await take(pdf, report?.pdf?.file); - const newCover = await take(cover, report?.cover?.file); + const newPdf = await take(pdf, report?.pdf ? (inConvex(ctx, report.pdf.file) ?? undefined) : undefined); + const newCover = await take(cover, report?.cover ? (inConvex(ctx, report.cover.file) ?? undefined) : undefined); if (report && (newPdf || newCover)) { await ctx.db.patch("reports", reportId, { ...(newPdf && report.pdf && { pdf: { ...report.pdf, file: pdf!.to } }), @@ -78,7 +86,35 @@ export const kept = httpAction(async (ctx, request) => { if (readConvexErrorData(error)?.code === "UNAUTHENTICATED") return null; throw error; }); - const blob = file ? await ctx.storage.get(file) : null; - if (!blob) return new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store" } }); + return await answerWith(ctx, file, params.get("key") ?? "", part); +}); + +const NOT_FOUND = () => new Response("Not found", { status: 404, headers: { "Cache-Control": "no-store" } }); + +/** + * A report's file as these routes answer it: one in R2 by a redirect to a signed address that lasts minutes, which + * the app's route follows and passes on (lib/reports/pass-file.ts); one in Convex storage by its bytes. + */ +async function answerWith(ctx: Pick, file: FileRef | null, key: string, part: "pdf" | "cover") { + if (!file) return NOT_FOUND(); + const kept = await ctx.runQuery(internal.files.uploads.keyOf, { id: file }); + if (kept) { + const location = await readAddress(kept.key, { filename: part === "pdf" ? `${key}.pdf` : `${key}-page-1.jpg`, inline: true, contentType: part === "pdf" ? "application/pdf" : "image/jpeg" }); + return new Response(null, { status: 307, headers: { Location: location, "Cache-Control": "no-store" } }); + } + const blob = await ctx.storage.get(file as Id<"_storage">); + if (!blob) return NOT_FOUND(); return new Response(blob, { headers: { "Content-Type": blob.type || (part === "pdf" ? "application/pdf" : "image/jpeg"), "Content-Length": String(blob.size), "Cache-Control": "no-store" } }); +} + +/** + * `GET /reports/open?key=…&part=pdf|cover`: a report's file while it is out for everyone, kept in R2 + * (lib/reports/report.ts `openFilePath`). Its page hands out this address, never R2's own, so the file is gone from + * here the moment the report is withdrawn or its file is made private. + */ +export const open = httpAction(async (ctx, request) => { + const params = new URL(request.url).searchParams; + const part = params.get("part") === "cover" ? "cover" : "pdf"; + const key = params.get("key") ?? ""; + return await answerWith(ctx, await ctx.runQuery(internal.reports.paper.outFile, { key, part }), key, part); }); diff --git a/convex/reports/flow.test.ts b/convex/reports/flow.test.ts index 6ff1ba06e..eb7461695 100644 --- a/convex/reports/flow.test.ts +++ b/convex/reports/flow.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it, onTestFinished, vi } from "vitest"; +import type { Id } from "../_generated/dataModel"; import { DEFAULT_CHECKS } from "../../lib/reports/settings"; import { api, internal } from "../_generated/api"; import { stageOf, type Metadata } from "../../lib/reports/report"; import { startsLeft } from "./limits"; -import { activate, atDetails, checked, details, passed, read, refused, row, setup, sign } from "./reports.test-support"; +import { activate, atDetails, checked, details, passed, read, refused, row, setup, sign, uploaded, fileRow } from "./reports.test-support"; import { purgeWorkspace } from "../workspaces/purge"; import { ensureWorkspace } from "../workspaces/create"; @@ -200,7 +201,7 @@ describe("a PDF read while its author went back", () => { it("leaves the report at its DOI, with the details read, and the upload a step away", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { bytes: 17 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" }); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key, step: "doi" }); const { _id: reportId, pdf } = await row(world.t, key); @@ -238,10 +239,10 @@ describe("a report's PDF", () => { it("takes only a PDF within its size, deleting anything else and saying why", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const text = await world.t.run((ctx) => ctx.storage.store(new Blob(["notes"]))); + const text = await uploaded(world, { bytes: 5 }); expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file: text, name: "notes.txt" })).toBe("Choose a PDF."); - expect(await world.t.run((ctx) => ctx.db.system.get(text))).toBeNull(); - const empty = await world.t.run((ctx) => ctx.storage.store(new Blob([]))); + expect(await fileRow(world, text)).toBeNull(); + const empty = await uploaded(world, { bytes: 0 }); expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file: empty, name: "empty.pdf" })).toMatch(/empty/); expect(await read(world.author, world.own, key)).toMatchObject({ step: "doi" }); }); @@ -252,8 +253,8 @@ describe("a report's PDF", () => { const firstPdf = (await row(world.t, first.key)).pdf!.file; // The first report's PDF, named again for a report in another workspace with a name that would be refused. const other = await sign(world.author, world.lab); - expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.lab, key: other, file: firstPdf, name: "not-a-pdf.txt" })).toMatch(/didn't arrive/); - expect(await world.t.run((ctx) => ctx.db.system.get(firstPdf))).not.toBeNull(); + expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.lab, key: other, file: firstPdf as Id<"storedFiles">, name: "not-a-pdf.txt" })).toMatch(/didn't arrive/); + expect(await fileRow(world, firstPdf)).not.toBeNull(); expect((await read(world.author, world.own, first.key)).pdf?.url).toEqual(expect.any(String)); expect((await read(world.author, world.lab, other)).step).toBe("doi"); }); @@ -261,10 +262,10 @@ describe("a report's PDF", () => { it("is given up when its report was discarded while it was on its way", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7"]))); + const file = await uploaded(world, { bytes: 8 }); await world.author.mutation(api.reports.flow.discard, { workspaceId: world.own, key }); expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" })).toMatch(/discarded/); - expect(await world.t.run((ctx) => ctx.db.system.get(file))).toBeNull(); + expect(await fileRow(world, file)).toBeNull(); }); it("reads its details again from the PDF that replaced another, when its author asks, and only then", async () => { @@ -273,7 +274,7 @@ describe("a report's PDF", () => { // Read from its first PDF, the details aren't kept from anything: there is nothing to read again. await expect(world.author.mutation(api.reports.flow.readAgain, { workspaceId: world.own, key: first.key })).rejects.toMatchObject(refused("CONFLICT")); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key: first.key, step: "upload" }); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 the right file"]))); + const file = await uploaded(world, { bytes: 23 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key: first.key, file, name: "right.pdf" }); const at = (await row(world.t, first.key)).pdf!.at; await world.t.mutation(internal.reports.readingState.finish, { reportId: first.reportId, at, pages: 3 }); @@ -295,7 +296,7 @@ describe("a report's PDF", () => { const world = await setup(); const { key, reportId } = await atDetails(world); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key, step: "upload" }); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 no line"]))); + const file = await uploaded(world, { bytes: 16 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "no-line.pdf", bylineBy: "self" }); // Nothing to add while the PDF hasn't been found lacking. await expect(world.author.mutation(api.reports.flow.addByline, { workspaceId: world.own, key })).rejects.toMatchObject(refused("CONFLICT")); @@ -311,7 +312,7 @@ describe("a report's PDF", () => { await world.t.mutation(internal.reports.readingState.finish, { reportId, at: asked.at, pages: 5, withByline: { file: added, bytes: 36 } }); expect(await read(world.author, world.own, key)).toMatchObject({ step: "details", pdf: { pages: 5, bytes: 36, bylineBy: "added" }, metadata: { title: "Shade trees and maize yields" } }); expect((await row(world.t, key)).pdf!).toMatchObject({ file: added, stamped: true, original: file }); - expect(await world.t.run((ctx) => ctx.db.system.get(file))).not.toBeNull(); + expect(await fileRow(world, file)).not.toBeNull(); // A reading again is given the original, the report's own pages, to read. expect((await world.t.query(internal.reports.readingState.begin, { reportId, at: asked.at }))?.original).toBe(file); // The checks write the page again with the details they read, from the original: that file takes the last one's place. @@ -319,19 +320,19 @@ describe("a report's PDF", () => { await world.t.run((ctx) => ctx.db.patch("reports", reportId, { run: { id: "run-1", at: Date.now() } })); await world.t.mutation(internal.reports.readingState.restamped, { reportId, runId: "run-1", at: asked.at, file: again, bytes: 37 }); expect((await row(world.t, key)).pdf!).toMatchObject({ file: again, bytes: 37, stamped: true, original: file }); - expect(await world.t.run((ctx) => ctx.db.system.get(added))).toBeNull(); - expect(await world.t.run((ctx) => ctx.db.system.get(file))).not.toBeNull(); + expect(await fileRow(world, added)).toBeNull(); + expect(await fileRow(world, file)).not.toBeNull(); // One written by a run that is no longer the report's is given up. const late = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 late"]))); await world.t.mutation(internal.reports.readingState.restamped, { reportId, runId: "run-0", at: asked.at, file: late, bytes: 13 }); expect((await row(world.t, key)).pdf!.file).toBe(again); - expect(await world.t.run((ctx) => ctx.db.system.get(late))).toBeNull(); + expect(await fileRow(world, late)).toBeNull(); // A new upload takes the place of both: the PDF with the page and its original. - const replacing = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 another file"]))); + const replacing = await uploaded(world, { bytes: 21 }); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key, step: "upload" }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file: replacing, name: "another.pdf", bylineBy: "added" }); - expect(await world.t.run((ctx) => ctx.db.system.get(again))).toBeNull(); - expect(await world.t.run((ctx) => ctx.db.system.get(file))).toBeNull(); + expect(await fileRow(world, again)).toBeNull(); + expect(await fileRow(world, file)).toBeNull(); expect((await row(world.t, key)).pdf!.original).toBeUndefined(); // Its page couldn't be added, as it is protected against changes: its author is told why. await world.t.mutation(internal.reports.readingState.finish, { reportId, at: (await row(world.t, key)).pdf!.at, pages: 2, lacksByline: true, bylineTrouble: "protected" }); @@ -343,7 +344,7 @@ describe("a report's PDF", () => { // A first PDF, read, then replaced by one without the line: the reading is what finds it missing. const { key, reportId } = await atDetails(world); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key, step: "upload" }); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 no line"]))); + const file = await uploaded(world, { bytes: 16 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "no-line.pdf" }); await world.t.mutation(internal.reports.readingState.finish, { reportId, at: (await row(world.t, key)).pdf!.at, pages: 4, lacksByline: true }); expect(await read(world.author, world.own, key)).toMatchObject({ step: "upload", pdf: { pages: 4, lacksByline: true }, metadata: { title: "Shade trees and maize yields" } }); @@ -364,7 +365,7 @@ describe("a report's PDF", () => { const world = await setup(); const first = await atDetails(world); await world.author.mutation(api.reports.flow.goTo, { workspaceId: world.own, key: first.key, step: "upload" }); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a second report"]))); + const file = await uploaded(world, { bytes: 24 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key: first.key, file, name: "second.pdf" }); const second = (await row(world.t, first.key)).pdf!.at; await world.t.mutation(internal.reports.readingState.finish, { reportId: first.reportId, at: second, pages: 3, metadata: details("The second PDF's title") }); @@ -381,7 +382,7 @@ describe("a report's PDF", () => { const { _id: reportId, ownerId } = await row(world.t, key); const lab = { id: "I1", name: "University of Ghana", country: "GH" }; await world.t.run((ctx) => ctx.db.patch("users", ownerId, { profile: { affiliations: [lab], orcid: "0000-0002-1825-0097", emails: { updates: false, news: false, research: false } } })); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { bytes: 17 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" }); const author = (name: string, orcid = "") => ({ name, orcid, openalexId: null, affiliations: [], corresponding: false, roles: [] }); // The signer's iD wasn't printed: ORCID's search guessed one, which their own profile comes before. @@ -402,7 +403,7 @@ describe("a report's PDF", () => { // A change typed just before stepping back arrives after it, and is kept. await world.author.mutation(api.reports.flow.saveDetails, { workspaceId: world.own, key: first.key, changes: { keywords: ["agroforestry"] }, pdfAt: first.pdfAt }); expect((await read(world.author, world.own, first.key)).metadata?.keywords).toEqual(["agroforestry"]); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a second report"]))); + const file = await uploaded(world, { bytes: 24 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key: first.key, file, name: "second.pdf" }); const replaced = await read(world.author, world.own, first.key); expect(replaced.step).toBe("upload"); @@ -427,13 +428,13 @@ describe("a report's PDF", () => { const world = await setup(); const key = await sign(world.author, world.own); const attach = async (cover: Blob) => { - const [file, picture] = await world.t.run(async (ctx) => [await ctx.storage.store(new Blob(["%PDF-1.7"])), await ctx.storage.store(cover)] as const); + const [file, picture] = [await uploaded(world, { bytes: 8 }), await uploaded(world, { bytes: cover.size, purpose: "report-cover", contentType: cover.type || "application/octet-stream" })]; await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf", cover: picture }); return picture; }; const huge = await attach(new Blob([new Uint8Array(3 * 1024 * 1024)], { type: "image/jpeg" })); expect((await read(world.author, world.own, key)).coverUrl).toBeNull(); - expect(await world.t.run((ctx) => ctx.db.system.get(huge))).toBeNull(); + expect(await fileRow(world, huge)).toBeNull(); await attach(new Blob(["jpeg"], { type: "image/jpeg" })); expect((await read(world.author, world.own, key)).coverUrl).toEqual(expect.any(String)); }); @@ -607,7 +608,7 @@ describe("a deleted workspace's reports", () => { expect(await world.t.run((ctx) => purgeWorkspace(ctx, world.lab))).toBe(true); expect(await row(world.t, draft.key)).toBeNull(); - expect(await world.t.run((ctx) => ctx.db.system.get(draftFile))).toBeNull(); + expect(await fileRow(world, draftFile)).toBeNull(); expect(await world.t.run((ctx) => ctx.db.query("reportStarts").withIndex("by_workspaceId_and_at", (q) => q.eq("workspaceId", world.lab)).collect())).toEqual([]); expect(await row(world.t, published.key)).toMatchObject({ status: "live" }); }); diff --git a/convex/reports/flow.ts b/convex/reports/flow.ts index 6db36918c..3b5ebcbb2 100644 --- a/convex/reports/flow.ts +++ b/convex/reports/flow.ts @@ -1,6 +1,10 @@ // A report from its agreement to ready to activate (plans/publish-reports): what the Publish page reads and the // changes its author makes. A report is its workspace's. Every member of an organisation's workspace sees its // reports; the report's owner, who started it, and the workspace's admins change them. +import { reportHolder } from "./validators"; +import { fileAddress, inConvex } from "../files/read"; +import { dropFile, freshUpload, holdFile } from "../files/uploads"; +import type { FileRef } from "../files/validators"; import { chosenOf, citedOf, connectedOf, identifierName, pickProblem, routeOf, withAccounts, type Identifiers, type ServiceId } from "../../lib/reports/identifiers"; import { v, type Infer } from "convex/values"; import { fundsOf, readAccount } from "../billing/accounts"; @@ -18,7 +22,7 @@ import { PLACES } from "../../lib/constants"; import { SDGS, STUDY_DESIGNS } from "../../lib/openalex/vocabulary"; import { PENDING_DOCID, PENDING_DOI, bylineOf, canRegister, doisUnder, keyedDoi, numberedUnder } from "../../lib/reports/settings"; import { choosesLicence } from "../../lib/reports/agreement"; -import { withFoundDois, costOf, DETAILS_MAX_BYTES, DETAIL_CAPS, REPORT_TYPES, REPORT_LANGUAGES, DETAIL_TEXT, EARLIEST_YEAR, FILE_NAME_MAX, REPORTS_PER_PAGE, REVIEW_TEXT_MAX, SIGNER_NAME_MAX, STAGES, CODE_MAX, listedStage, waitsOnSomeone, DEFAULT_LICENCE, withNames, canDiscard, licenceOf, ownLicence, type Licence, fileAccessOf, fileHidden, fileOut, isCalendarDay, keptAccess, keptFileAddress, opensFurther, readersGetFile, utcDay, type FileAccess, isOrcid, keyOf, providersOf, stageOf, type Metadata, type Stage, doiIn, linkHref, dateParts, isAuthor } from "../../lib/reports/report"; +import { withFoundDois, costOf, DETAILS_MAX_BYTES, DETAIL_CAPS, REPORT_TYPES, REPORT_LANGUAGES, DETAIL_TEXT, EARLIEST_YEAR, FILE_NAME_MAX, REPORTS_PER_PAGE, REVIEW_TEXT_MAX, SIGNER_NAME_MAX, STAGES, CODE_MAX, listedStage, waitsOnSomeone, DEFAULT_LICENCE, withNames, canDiscard, licenceOf, ownLicence, type Licence, fileAccessOf, fileHidden, fileOut, isCalendarDay, keptAccess, keptFileAddress, openFilePath, opensFurther, readersGetFile, utcDay, type FileAccess, isOrcid, keyOf, providersOf, stageOf, type Metadata, type Stage, doiIn, linkHref, dateParts, isAuthor } from "../../lib/reports/report"; import { isCoverShape } from "../../lib/papers/cover"; import { countStart, startsLeft } from "./limits"; import { refuseClosed } from "./intake"; @@ -149,18 +153,28 @@ export function keptDetails(sent: Metadata, licence: Licence) { return metadata; } -const claimOf = (ctx: QueryCtx, file: Id<"_storage">) => ctx.db.query("reportFiles").withIndex("by_file", (q) => q.eq("file", file)).unique(); +const claimOf = (ctx: QueryCtx, file: FileRef) => ctx.db.query("reportFiles").withIndex("by_file", (q) => q.eq("file", file)).unique(); -/** Deletes files that are a report's, with the rows that say so. */ -export async function forget(ctx: MutationCtx, ...files: Array | undefined>) { +/** Deletes files that are a report's, with the rows that say so: one in R2 (convex/files), or in Convex storage from before. */ +export async function forget(ctx: MutationCtx, ...files: Array) { for (const file of files) { if (!file) continue; const claim = await claimOf(ctx, file); if (claim) await ctx.db.delete("reportFiles", claim._id); - if (await ctx.db.system.get(file)) await ctx.storage.delete(file); + const kept = ctx.db.normalizeId("storedFiles", file); + if (kept) await dropFile(ctx, kept); + const stored = inConvex(ctx, file); + if (stored && (await ctx.db.system.get(stored))) await ctx.storage.delete(stored); } } +/** Makes a file the report's, so it is kept: one in R2 is held by it; one in Convex storage, from before, is claimed. */ +export async function keepFor(ctx: MutationCtx, reportId: Id<"reports">, file: FileRef) { + const kept = ctx.db.normalizeId("storedFiles", file); + if (kept) await holdFile(ctx, kept, reportHolder(reportId)); + else await ctx.db.insert("reportFiles", { file, reportId }); +} + /** A removed report's reviewer decisions, and the emails about it, deleted a step. */ const REVIEWS_REMOVED = 100; @@ -194,19 +208,7 @@ export async function removeReport(ctx: MutationCtx, report: Doc<"reports">) { await ctx.db.delete("reports", report._id); } -/** How long after it was uploaded a file can still become a report's. */ -const UPLOAD_FRESH_MS = 15 * 60 * 1000; -/** - * A file the browser says it just uploaded for a report, if it can be: it exists, it is no report's yet, and it was - * uploaded moments ago. A storage ID is only ever known to the browser that uploaded it, so a fresh one that nothing - * claims is that upload. An older one, or one a report holds, is refused and left alone: it may be someone's file. - */ -async function uploaded(ctx: MutationCtx, file: Id<"_storage">) { - const stored = await ctx.db.system.get(file); - if (!stored || (await claimOf(ctx, file)) || Date.now() - stored._creationTime > UPLOAD_FRESH_MS) return null; - return stored; -} /** How many more reports the workspace may start at `now`, which the page gives so this query doesn't read the clock. */ export const startsAction = defineUserQuery({ @@ -585,16 +587,19 @@ export const addByline = workspaceMutation({ }, }); -/** Where the browser sends a report's PDF, and the picture of its first page, before attaching them. */ +/** + * Whether the report takes a PDF now, asked before the browser sends one (lib/files/upload.ts), so a refusal comes + * before the upload and not after it. + */ export const startUpload = workspaceMutation({ args: { key: v.string() }, - returns: v.string(), + returns: v.null(), handler: async (ctx, actor, { key }) => { await refuseApps(ctx); const report = await changing(ctx, actor, key); if (report.step === "done") throw createError("CONFLICT", MOVED_ON); if (report.doiUnder) throw createError("CONFLICT", DOI_WAITS); - return await ctx.storage.generateUploadUrl(); + return null; }, }); @@ -605,12 +610,12 @@ export const startUpload = workspaceMutation({ * anew, for the checks. A file that can't be this report's is deleted, and why is the answer: a throw would keep the file. */ export const attachPdf = workspaceMutation({ - args: { key: v.string(), file: v.id("_storage"), name: v.string(), cover: v.optional(v.id("_storage")), /** The cover's width over its height, as the browser drew it. */ coverShape: v.optional(v.number()), /** Who adds the byline, as the author chose at the upload. A page still open from before the choice sends none. */ bylineBy: v.optional(bylineByValidator) }, + args: { key: v.string(), file: v.id("storedFiles"), name: v.string(), cover: v.optional(v.id("storedFiles")), /** The cover's width over its height, as the browser drew it. */ coverShape: v.optional(v.number()), /** Who adds the byline, as the author chose at the upload. A page still open from before the choice sends none. */ bylineBy: v.optional(bylineByValidator) }, returns: v.union(v.null(), v.string()), handler: async (ctx, actor, { key, file, name, cover, coverShape, bylineBy }) => { await refuseApps(ctx); - const stored = await uploaded(ctx, file); - const picture = cover ? await uploaded(ctx, cover) : null; + const stored = await freshUpload(ctx, file, actor.userId, "report-pdf"); + const picture = cover ? await freshUpload(ctx, cover, actor.userId, "report-cover") : null; if (!stored) return "The upload didn't arrive. Upload the PDF again."; // From here both files are this upload's, so whatever isn't kept is deleted. const report = await byKey(ctx, key); @@ -620,8 +625,8 @@ export const attachPdf = workspaceMutation({ : report.step === "done" ? MOVED_ON : report.doiUnder ? DOI_WAITS : !/\.pdf$/i.test(name.trim()) ? "Choose a PDF." - : stored.size === 0 ? "That file is empty. Choose the PDF again." - : stored.size > MAX_PDF_BYTES ? `A report's PDF is at most ${MAX_PDF_MB} MB.` + : stored.bytes === 0 ? "That file is empty. Choose the PDF again." + : stored.bytes > MAX_PDF_BYTES ? `A report's PDF is at most ${MAX_PDF_MB} MB.` : null; if (refused || !report) { await forget(ctx, file, picture ? cover : undefined); @@ -632,12 +637,12 @@ export const attachPdf = workspaceMutation({ const at = Math.max(Date.now(), (report.pdf?.at ?? 0) + 1); // The picture of its first page, drawn by the browser that uploaded it. One that is too big or no picture is // dropped, and the report keeps its title page. - const pictured = !!picture && picture.size <= COVER_MAX_BYTES && (picture.contentType === undefined || picture.contentType.startsWith("image/")); + const pictured = !!picture && picture.bytes <= COVER_MAX_BYTES && picture.contentType.startsWith("image/"); if (picture && !pictured) await forget(ctx, cover); - await ctx.db.insert("reportFiles", { file, reportId: report._id }); - if (pictured) await ctx.db.insert("reportFiles", { file: cover!, reportId: report._id }); + await holdFile(ctx, file, reportHolder(report._id)); + if (pictured) await holdFile(ctx, cover!, reportHolder(report._id)); await ctx.db.patch("reportDetails", (await detailsOf(ctx, report._id))._id, { reviewRequest: undefined, running: undefined }); - await touch(ctx, report, { pdf: { file, name: name.trim().slice(-FILE_NAME_MAX), bytes: stored.size, at, by: actor.userId, ...(bylineBy && !report.bylineOff && { bylineBy }) }, cover: pictured ? { file: cover!, at, ...(coverShape !== undefined && isCoverShape(coverShape) && { shape: coverShape }) } : undefined, run: undefined, step: "upload", reopened: undefined, approved: undefined, asked: undefined }); + await touch(ctx, report, { pdf: { file, name: name.trim().slice(-FILE_NAME_MAX), bytes: stored.bytes, at, by: actor.userId, ...(bylineBy && !report.bylineOff && { bylineBy }) }, cover: pictured ? { file: cover!, at, ...(coverShape !== undefined && isCoverShape(coverShape) && { shape: coverShape }) } : undefined, run: undefined, step: "upload", reopened: undefined, approved: undefined, asked: undefined }); await ctx.scheduler.runAfter(0, internal.reports.reading.read, { reportId: report._id, at }); return null; }, @@ -764,7 +769,7 @@ async function row(ctx: QueryCtx, actor: Actor, report: Doc<"reports">, { humanR // A picture of the PDF's first page: for those who may have the PDF, as the PDF's address is. ...(await (async () => { const seen = report.cover && (mayChange(actor, report) || readersGetFile(report)); - return { coverUrl: seen ? (fileOut(report) ? await ctx.storage.getUrl(report.cover!.file) : keptFileAddress(report.key, "cover", report.cover!.at)) : null, ...(seen && report.cover!.shape && { coverShape: report.cover!.shape }) }; + return { coverUrl: seen ? (fileOut(report) ? await fileAddress(ctx, report.cover!.file, openFilePath(report.key, "cover")) : keptFileAddress(report.key, "cover", report.cover!.at)) : null, ...(seen && report.cover!.shape && { coverShape: report.cover!.shape }) }; })()), mine: mayChange(actor, report), }; @@ -957,7 +962,7 @@ export const getAction = defineUserQuery({ // moment Submit is pressed until the run names its own. checks: checkNames((await checksOf(ctx, report, report.status === "live", settings))?.checks ?? []), // A file its readers can't have is the address only of those who may change the report, not every member's. - ...(report.pdf && { pdf: { name: report.pdf.name, bytes: report.pdf.bytes, at: report.pdf.at, ...(report.pdf.pages !== undefined && { pages: report.pdf.pages }), ...(report.pdf.trouble && { trouble: report.pdf.trouble }), ...(report.pdf.lacksByline && { lacksByline: true }), ...(report.pdf.bylineTrouble && { bylineTrouble: report.pdf.bylineTrouble }), ...(report.pdf.bylineBy && { bylineBy: report.pdf.bylineBy }), ...(report.pdf.kept && { kept: true }), url: fileOut(report) ? await ctx.storage.getUrl(report.pdf.file) : readersGetFile(report) || mayChange(actor, report) ? keptFileAddress(report.key, "pdf", report.pdf.at) : null } }), + ...(report.pdf && { pdf: { name: report.pdf.name, bytes: report.pdf.bytes, at: report.pdf.at, ...(report.pdf.pages !== undefined && { pages: report.pdf.pages }), ...(report.pdf.trouble && { trouble: report.pdf.trouble }), ...(report.pdf.lacksByline && { lacksByline: true }), ...(report.pdf.bylineTrouble && { bylineTrouble: report.pdf.bylineTrouble }), ...(report.pdf.bylineBy && { bylineBy: report.pdf.bylineBy }), ...(report.pdf.kept && { kept: true }), url: fileOut(report) ? await fileAddress(ctx, report.pdf.file, openFilePath(report.key, "pdf")) : readersGetFile(report) || mayChange(actor, report) ? keptFileAddress(report.key, "pdf", report.pdf.at) : null } }), ...(details.metadata && { metadata: details.metadata }), ...(details.lookup && { lookup: details.lookup }), ...(details.results && { results: plain(details.results) }), diff --git a/convex/reports/mail.test.ts b/convex/reports/mail.test.ts index 754640471..cf92c7eb5 100644 --- a/convex/reports/mail.test.ts +++ b/convex/reports/mail.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api, internal } from "../_generated/api"; -import { activate, checked, details, live, passed, row, setReview, setup, sign, type World } from "./reports.test-support"; +import { activate, checked, details, live, passed, row, setReview, setup, sign, type World, uploaded } from "./reports.test-support"; // The emails are sent by scheduled actions: the tests run them, with no mail service set up, and read what each // report's record says was written. @@ -37,7 +37,7 @@ describe("the emails about a report", () => { // The author starts a report in the organisation and its admin uploads the PDF. const upload = async (title: string) => { const key = await sign(world.author, world.lab); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { by: world.orgAdmin, bytes: 17 }); expect(await world.orgAdmin.mutation(api.reports.flow.attachPdf, { workspaceId: world.lab, key, file, name: "report.pdf" })).toBeNull(); const { _id: reportId, pdf } = await row(world.t, key); return { key, finish: () => world.t.mutation(internal.reports.readingState.finish, { reportId, at: pdf!.at, pages: 12, metadata: details(title) }) }; diff --git a/convex/reports/ownReports.ts b/convex/reports/ownReports.ts index 291be9ace..a2df94835 100644 --- a/convex/reports/ownReports.ts +++ b/convex/reports/ownReports.ts @@ -1,6 +1,7 @@ // Openscholar Reports' own live reports, which the Already published check searches before anywhere else: one went // live here minutes before is in none of the other places yet (OpenAlex takes days to read a new DOI from Crossref). import { v } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import { internalQuery } from "../lib/functions"; import { detailsOf } from "./flow"; import { reportSettings, seriesReader } from "./settings"; @@ -14,7 +15,7 @@ const SEARCH_TERMS = 16; /** Live reports whose titles are closest to `title`, never the report being checked, with what each says of itself. */ export const alike = internalQuery({ args: { reportId: v.id("reports"), title: v.string() }, - returns: v.array(v.object({ title: v.string(), abstract: v.string(), url: v.string(), where: v.string(), year: v.string(), authors: v.string(), text: v.union(v.id("_storage"), v.null()) })), + returns: v.array(v.object({ title: v.string(), abstract: v.string(), url: v.string(), where: v.string(), year: v.string(), authors: v.string(), text: v.union(fileRefValidator, v.null()) })), handler: async (ctx, { reportId, title }) => { if (!title.trim()) return []; const seriesOf = seriesReader(ctx, (await reportSettings(ctx)).series); diff --git a/convex/reports/paper.test.ts b/convex/reports/paper.test.ts index dc8d51df6..0a961d80f 100644 --- a/convex/reports/paper.test.ts +++ b/convex/reports/paper.test.ts @@ -1,12 +1,15 @@ -import { describe, expect, it, vi } from "vitest"; +import type { Id } from "../_generated/dataModel"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { api, internal } from "../_generated/api"; -import { checked, live, passed, read, refused, row, setup, type World } from "./reports.test-support"; +import { checked, live, passed, read, refused, row, setup, type World, R2_TEST, stubUploads } from "./reports.test-support"; import { trimPaperData } from "../../lib/library/trim-paper-data"; import { reportPaper } from "../../lib/reports/report-paper"; const decide = async (world: World, key: string, decision: "withdraw" | "reinstate") => world.reviewer.mutation(api.reports.review.decide, { key, decision, seenPdfAt: (await row(world.t, key)).pdf!.at }); + +afterEach(() => vi.unstubAllEnvs()); describe("a report's page", () => { it("is anyone's to read once the report is live, and no one's before", async () => { const world = await setup(); @@ -100,12 +103,19 @@ describe("a report's page", () => { expect(back!.version > withdrawn!.version).toBe(true); }); - it("moves a withdrawn report's files, so the addresses its readers were given stop working", async () => { + it("moves a withdrawn report's files still in Convex storage, so the addresses its readers were given stop working", async () => { vi.useFakeTimers(); try { const world = await setup(); const { key, reportId } = await live(world); - const before = (await row(world.t, key)).pdf!.file; + // A PDF kept in Convex storage, as every one was before R2 (#1695), whose address lasts. + const before = await world.t.run(async (ctx) => { + const file = await ctx.storage.store(new Blob(["%PDF-1.7 from before R2"], { type: "application/pdf" })); + const report = (await ctx.db.get("reports", reportId))!; + await ctx.db.patch("reports", reportId, { pdf: { ...report.pdf!, file } }); + await ctx.db.insert("reportFiles", { file, reportId }); + return file; + }); await decide(world, key, "withdraw"); await world.t.finishAllScheduledFunctions(vi.runAllTimers); // Withdrawing schedules this. It is also run here by hand, so the test doesn't hang on when the scheduler got @@ -113,7 +123,7 @@ describe("a report's page", () => { await world.t.action(internal.reports.files.rotate, { reportId }); const after = await row(world.t, key); expect(after.pdf!.file).not.toBe(before); - expect(await world.t.run((ctx) => ctx.db.system.get(before))).toBeNull(); + expect(await world.t.run((ctx) => ctx.db.system.get(before as Id<"_storage">))).toBeNull(); // The file is the report's still: reinstated, its page gives the PDF again, and discarding rules still find it. expect(await world.t.run((ctx) => ctx.db.query("reportFiles").withIndex("by_file", (q) => q.eq("file", after.pdf!.file)).unique())).not.toBeNull(); await decide(world, key, "reinstate"); @@ -123,6 +133,15 @@ describe("a report's page", () => { } }); + it("hands out no address of a file in R2: the report's own route sends readers to it only while the report is out", async () => { + const world = await setup(); + const { key } = await live(world); + expect(await world.t.query(api.reports.paper.get, { key })).toMatchObject({ pdfUrl: expect.stringContaining(`/reports/open?key=${key}&part=pdf`) }); + expect(await world.t.query(internal.reports.paper.outFile, { key, part: "pdf" })).not.toBeNull(); + await decide(world, key, "withdraw"); + expect(await world.t.query(internal.reports.paper.outFile, { key, part: "pdf" })).toBeNull(); + }); + it("keeps its saved copies in step in every workspace: corrected, withdrawn and reinstated", async () => { vi.useFakeTimers(); try { @@ -244,10 +263,14 @@ describe("a report's page", () => { // Its workspace and the reviewers open it at an address that asks who they are, never the file store's own, // which would open for anyone the owner passed it to. expect(await read(world.author, world.own, key)).toMatchObject({ pdf: { url: expect.stringMatching(new RegExp(`^/api/reports/files/${key}\\?at=\\d+$`)) } }); + // A PDF in R2 is sent on to an address signed for minutes; a cover still in Convex storage is sent as it is. + stubUploads(); const kept = async (who: World["author"], part = "pdf") => (await who.fetch(`/reports/file?key=${key}&part=${part}`)).status; - expect(await kept(world.author)).toBe(200); + const pdfAt = (await (await world.author.fetch(`/reports/file?key=${key}&part=pdf`)).headers.get("location")) ?? ""; + expect(pdfAt.startsWith(`${R2_TEST}/uploads/`) && pdfAt.includes("X-Amz-Expires=900")).toBe(true); + expect(await kept(world.author)).toBe(307); expect(await kept(world.author, "cover")).toBe(200); - expect(await kept(world.reviewer)).toBe(200); + expect(await kept(world.reviewer)).toBe(307); expect(await kept(world.stranger)).toBe(404); // An app holding the reviewer's token gets nothing: it would open every report's. expect(await kept(world.t.withIdentity({ subject: "reviewer", client_id: "client_bee" }))).toBe(404); diff --git a/convex/reports/paper.ts b/convex/reports/paper.ts index 946959a58..fc8a24cae 100644 --- a/convex/reports/paper.ts +++ b/convex/reports/paper.ts @@ -1,7 +1,9 @@ // A published report as the rest of Openscholar reads it (plans/publish-reports): its paper page at /papers/R…, and // the DOI a community is given for a link to that page. Only a live report, or one withdrawn after going live, is // ever read here: a report that never went live has no page and nothing finds it. +import { fileAddress } from "../files/read"; import { v } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import type { Doc } from "../_generated/dataModel"; import { internalQuery, query, type QueryCtx } from "../_generated/server"; import { getCurrentUser, getIdentity } from "../lib/auth"; @@ -13,7 +15,7 @@ import { reportSettings, seriesFor, seriesReader, settingsChangedAt } from "./se import { namedOf } from "../../lib/reports/settings"; import { AUTHORS_LISTED, INSTITUTIONS_LISTED, paperRecordValidator } from "../research/searchValidators"; import { liveReportValidator, metadataValidator, withdrawnReportValidator } from "./validators"; -import { REPORTS_PER_READ, communityGetsFile, fileAccessOf, fileHidden, fullTitle, isAuthor, licenceName, licenceOf, licenceOpen, readersGetFile } from "../../lib/reports/report"; +import { REPORTS_PER_READ, communityGetsFile, fileAccessOf, fileHidden, fullTitle, isAuthor, licenceName, licenceOf, licenceOpen, openFilePath, fileOut, readersGetFile } from "../../lib/reports/report"; const byKey = (ctx: QueryCtx, key: string) => ctx.db.query("reports").withIndex("by_key", (q) => q.eq("key", key)).unique(); @@ -44,12 +46,12 @@ export const get = query({ metadata, series, // A file its readers can't have yet has no address here, so its page offers none and report.pdf answers not found. - pdfUrl: report.pdf && readersGetFile(report) ? await ctx.storage.getUrl(report.pdf.file) : null, + pdfUrl: report.pdf && readersGetFile(report) ? await fileAddress(ctx, report.pdf.file, openFilePath(key, "pdf")) : null, fileAccess: fileAccessOf(licenceOf(report), report.fileAccess), // Its copy on Zenodo, once archived, where it was archived. ...(report.zenodoRecordId && report.zenodoHost && { zenodoUrl: `https://${report.zenodoHost}/records/${report.zenodoRecordId}` }), // The cover is a picture of the PDF's first page: shown only to those who may have the PDF. - coverUrl: report.cover && readersGetFile(report) ? await ctx.storage.getUrl(report.cover.file) : null, ...(report.cover?.shape && readersGetFile(report) && { coverShape: report.cover.shape }), + coverUrl: report.cover && readersGetFile(report) ? await fileAddress(ctx, report.cover.file, openFilePath(key, "cover")) : null, ...(report.cover?.shape && readersGetFile(report) && { coverShape: report.cover.shape }), updatedAt: report.updatedAt, }; }, @@ -64,7 +66,7 @@ export const get = query({ */ export const keptFile = internalQuery({ args: { key: v.string(), part: v.union(v.literal("pdf"), v.literal("cover")) }, - returns: v.union(v.null(), v.id("_storage")), + returns: v.union(v.null(), fileRefValidator), handler: async (ctx, { key, part }) => { const user = appClientId(await getIdentity(ctx)) ? null : await getCurrentUser(ctx); const report = user ? await byKey(ctx, key) : null; @@ -76,6 +78,17 @@ export const keptFile = internalQuery({ }, }); +/** A report's PDF or first-page picture while it is out for everyone (live, and its readers get it); null otherwise. */ +export const outFile = internalQuery({ + args: { key: v.string(), part: v.union(v.literal("pdf"), v.literal("cover")) }, + returns: v.union(v.null(), fileRefValidator), + handler: async (ctx, { key, part }) => { + const report = await byKey(ctx, key); + if (!report || !fileOut(report)) return null; + return (part === "pdf" ? report.pdf?.file : report.cover?.file) ?? null; + }, +}); + /** * The key of the report a DOI names, for a link that knows a paper only by its DOI (app/papers/doi): a live report, or * one withdrawn after going live, which still has its page. Null for any other DOI. diff --git a/convex/reports/pdfBytes.ts b/convex/reports/pdfBytes.ts index b839727d8..3c09be7ab 100644 --- a/convex/reports/pdfBytes.ts +++ b/convex/reports/pdfBytes.ts @@ -1,13 +1,14 @@ // A report's PDF as the actions that work on it hold it (./reading.ts, ./checks.ts). -import type { Id } from "../_generated/dataModel"; import type { ActionCtx } from "../_generated/server"; +import { fileBlob } from "../files/read"; +import type { FileRef } from "../files/validators"; /** * A stored PDF's bytes, read on their own. The Blob they arrive in is let go as soon as they are out of it, so a PDF * near the upload limit is held once while it is worked on, not twice. Throws when the file is gone. */ -export async function storedBytes(ctx: Pick, file: Id<"_storage">) { - const blob = await ctx.storage.get(file); +export async function storedBytes(ctx: Pick, file: FileRef) { + const blob = await fileBlob(ctx, file); if (!blob) throw new Error("The report's PDF is gone."); return new Uint8Array(await blob.arrayBuffer()); } diff --git a/convex/reports/reading.ts b/convex/reports/reading.ts index 829e07e3c..7a37d9967 100644 --- a/convex/reports/reading.ts +++ b/convex/reports/reading.ts @@ -2,6 +2,7 @@ // Reads a report's PDF once it's uploaded (./flow.ts `attachPdf`): its pages and text, which the checks read, and // its details, which the model set on the admin page reads for the author to correct. +import { keepFile } from "../files/uploads"; import { v } from "convex/values"; import { internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; @@ -99,14 +100,14 @@ export const read = internalAction({ // unless the PDF carries the line already. A page that can't be added leaves the PDF as it was, without the line, which the upload then says. let text = job.stamped ? `${read}\n${job.line}` : read; let pages = opened.totalPages; - let withByline: { file: Id<"_storage">; bytes: number } | undefined; + let withByline: { file: Id<"storedFiles">; bytes: number } | undefined; let bylineTrouble: BylineTrouble | undefined; if (job.added && !carries(text, job.line)) { try { // Details a reading couldn't find are a file name and today's date: the page waits for the author's own. const known = job.held ?? metadata ?? undefined; const added = await (await stamping()).stampedPdf(bytes, { line: job.line, series: job.series, publisher: job.publisher, ...(known && { details: known }) }, { before: texts }); - withByline = { file: await ctx.storage.store(added.file), bytes: added.bytes }; + withByline = { file: await keepFile(ctx, added.file, { name: job.name, contentType: "application/pdf", purpose: "report-pdf" }), bytes: added.bytes }; text = `${text}\n${job.line}`; pages += 1; } catch (error) { @@ -116,7 +117,7 @@ export const read = internalAction({ console.error(JSON.stringify({ event: "report-byline-page-failed", reportId, name: job.name, bytes: size, trouble: bylineTrouble, error: String(error).slice(0, 300) })); } } - const textFile = await ctx.storage.store(new Blob([text], { type: "text/plain" })); + const textFile = await keepFile(ctx, text, { name: `${job.name}.txt`, contentType: "text/plain; charset=utf-8", purpose: "report-text" }); // The byline is text the PDF has or hasn't, so its author hears now, at the upload, not after the checks. A scan // has no text to look in, and says that instead. // An author who asked for the page and didn't get it is told so whether or not the byline check is on. diff --git a/convex/reports/readingState.ts b/convex/reports/readingState.ts index ea75e4eb8..ab38b9326 100644 --- a/convex/reports/readingState.ts +++ b/convex/reports/readingState.ts @@ -1,9 +1,10 @@ // What ./reading.ts, the action that reads an uploaded PDF, reads before it starts and saves when it's done. import { v } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import { internalMutation, internalQuery } from "../lib/functions"; import { slugPick } from "../ai/serverModel"; import { effortValidator } from "../aiModelConfig/validators"; -import { byKey, changing, detailsOf, forget, keptDetails, touch } from "./flow"; +import { byKey, changing, detailsOf, forget, keepFor, keptDetails, touch } from "./flow"; import { requireAdmin } from "../admins/access"; import { actorValidator } from "../workspaces/actor"; import { createError } from "../lib/errors"; @@ -21,7 +22,7 @@ import { licenceOf, type Metadata } from "../../lib/reports/report"; /** The PDF to read and the model that reads it; null when a newer PDF replaced it or the report is past its details. */ export const begin = internalQuery({ args: { reportId: v.id("reports"), at: v.number() }, - returns: v.union(v.null(), v.object({ file: v.id("_storage"), name: v.string(), doi: v.string(), signer: v.string(), /** The report's byline, and whether its author has Openscholar add it to the PDF on a last page. */ line: v.string(), added: v.boolean(), /** Its last page is one Openscholar added before. */ stamped: v.boolean(), /** The PDF as its author uploaded it, kept beside a stamped one. */ original: v.optional(v.id("_storage")), /** The series the report is published in, who publishes it, and the details it keeps, which that page prints. */ series: v.string(), publisher: v.string(), held: v.optional(metadataValidator), /** The line the byline check looks for in the PDF; null while that check is switched off. */ byline: v.union(v.string(), v.null()), modelId: v.union(v.id("models"), v.null()), effort: v.optional(effortValidator), /** The report has details already, from the PDF this one replaces: they are kept, and this one's aren't read. */ kept: v.boolean() })), + returns: v.union(v.null(), v.object({ file: fileRefValidator, name: v.string(), doi: v.string(), signer: v.string(), /** The report's byline, and whether its author has Openscholar add it to the PDF on a last page. */ line: v.string(), added: v.boolean(), /** Its last page is one Openscholar added before. */ stamped: v.boolean(), /** The PDF as its author uploaded it, kept beside a stamped one. */ original: v.optional(fileRefValidator), /** The series the report is published in, who publishes it, and the details it keeps, which that page prints. */ series: v.string(), publisher: v.string(), held: v.optional(metadataValidator), /** The line the byline check looks for in the PDF; null while that check is switched off. */ byline: v.union(v.string(), v.null()), modelId: v.union(v.id("models"), v.null()), effort: v.optional(effortValidator), /** The report has details already, from the PDF this one replaces: they are kept, and this one's aren't read. */ kept: v.boolean() })), handler: async (ctx, { reportId, at }) => { const report = await ctx.db.get("reports", reportId); if (!report?.pdf || report.pdf.at !== at || report.step === "done") return null; @@ -40,7 +41,7 @@ export const begin = internalQuery({ */ export const abstractSource = internalQuery({ args: { actor: v.optional(actorValidator), key: v.string() }, - returns: v.object({ text: v.id("_storage"), modelId: v.union(v.id("models"), v.null()), effort: v.optional(effortValidator) }), + returns: v.object({ text: fileRefValidator, modelId: v.union(v.id("models"), v.null()), effort: v.optional(effortValidator) }), handler: async (ctx, { actor, key }) => { const report = actor ? await changing(ctx, actor, key) : (await requireAdmin(ctx), await byKey(ctx, key)); if (!report?.pdf?.text) throw createError("CONFLICT", "This report's PDF has no text to write an abstract from. Type one instead."); @@ -79,13 +80,12 @@ function signerFilledIn(metadata: Metadata, signer: string, profile: Doc<"users" } export const finish = internalMutation({ - args: { reportId: v.id("reports"), at: v.number(), pages: v.optional(v.number()), text: v.optional(v.id("_storage")), metadata: v.optional(metadataValidator), trouble: v.optional(v.union(v.literal("textless"), v.literal("unread"))), /** Its text doesn't carry the byline: the report stays at the upload, which says so, with the way on to its details. */ lacksByline: v.optional(v.boolean()), /** The details couldn't be read from it, whatever else is wrong with it. */ unread: v.optional(v.boolean()), /** The PDF with the byline's page added, which readers get in place of the one uploaded. */ withByline: v.optional(v.object({ file: v.id("_storage"), bytes: v.number() })), /** Why the page asked for couldn't be added. */ bylineTrouble: v.optional(bylineTroubleValidator), /** The titles of the works its references without a DOI cite, which their lookup searches by. */ titles: v.optional(lookupTitlesValidator) }, + args: { reportId: v.id("reports"), at: v.number(), pages: v.optional(v.number()), text: v.optional(fileRefValidator), metadata: v.optional(metadataValidator), trouble: v.optional(v.union(v.literal("textless"), v.literal("unread"))), /** Its text doesn't carry the byline: the report stays at the upload, which says so, with the way on to its details. */ lacksByline: v.optional(v.boolean()), /** The details couldn't be read from it, whatever else is wrong with it. */ unread: v.optional(v.boolean()), /** The PDF with the byline's page added, which readers get in place of the one uploaded. */ withByline: v.optional(v.object({ file: fileRefValidator, bytes: v.number() })), /** Why the page asked for couldn't be added. */ bylineTrouble: v.optional(bylineTroubleValidator), /** The titles of the works its references without a DOI cite, which their lookup searches by. */ titles: v.optional(lookupTitlesValidator) }, returns: v.null(), handler: async (ctx, { reportId, at, pages, text, metadata, trouble, lacksByline, unread, withByline, bylineTrouble, titles }) => { const report = await ctx.db.get("reports", reportId); if (!report?.pdf || report.pdf.at !== at || report.step === "done") { - if (text) await ctx.storage.delete(text); - if (withByline) await ctx.storage.delete(withByline.file); + await forget(ctx, text, withByline?.file); return null; } // The PDF with the byline's page added is the one readers get; the one uploaded is kept as its original, which @@ -94,18 +94,19 @@ export const finish = internalMutation({ const pdf = withByline ? { ...report.pdf, ...withByline, stamped: true, original } : report.pdf; if (withByline) { if (report.pdf.file !== original) await forget(ctx, report.pdf.file); - await ctx.db.insert("reportFiles", { file: withByline.file, reportId }); + await keepFor(ctx, reportId, withByline.file); } const details = await detailsOf(ctx, reportId); // Details the report already has, from the PDF this one replaces, stay as their author left them. const held = details.metadata; // A PDF that couldn't be opened has no pages. if (pages === undefined || (!metadata && !held)) { + await forget(ctx, text); await touch(ctx, report, { pdf: { ...pdf, trouble: "unopened" } }); await notify(ctx, reportId, "pdf-unopened"); return null; } - if (text) await ctx.db.insert("reportFiles", { file: text, reportId }); + if (text) await keepFor(ctx, reportId, text); const profile = (await ctx.db.get("users", report.ownerId))?.profile; const kept = held ?? keptDetails(signerFilledIn(metadata!, report.signedBy.name, profile), licenceOf(report)); if (!held) { @@ -149,16 +150,16 @@ export const mailIfAway = internalMutation({ * given up. */ export const restamped = internalMutation({ - args: { reportId: v.id("reports"), /** The run of checks whose details the page says: an older run's page never replaces a newer one's. */ runId: v.string(), at: v.number(), file: v.id("_storage"), bytes: v.number() }, + args: { reportId: v.id("reports"), /** The run of checks whose details the page says: an older run's page never replaces a newer one's. */ runId: v.string(), at: v.number(), file: fileRefValidator, bytes: v.number() }, returns: v.null(), handler: async (ctx, { reportId, runId, at, file, bytes }) => { const report = await ctx.db.get("reports", reportId); if (!report?.pdf?.stamped || report.pdf.at !== at || report.run?.id !== runId) { - await ctx.storage.delete(file); + await forget(ctx, file); return null; } await forget(ctx, report.pdf.file); - await ctx.db.insert("reportFiles", { file, reportId }); + await keepFor(ctx, reportId, file); // Not a change its author made: the report's own moment stays as it was. await ctx.db.patch("reports", reportId, { pdf: { ...report.pdf, file, bytes } }); return null; diff --git a/convex/reports/referenceLookup.test.ts b/convex/reports/referenceLookup.test.ts index e53d7011c..5aeef864a 100644 --- a/convex/reports/referenceLookup.test.ts +++ b/convex/reports/referenceLookup.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api, internal } from "../_generated/api"; -import { details, row, setup, sign } from "./reports.test-support"; +import { details, row, setup, sign, uploaded } from "./reports.test-support"; import { register } from "./registering"; // The scheduled lookup itself asks doi.org, Crossref and Jev, so it never runs here: the tests give its findings to `save`. @@ -11,7 +11,7 @@ describe("the lookup of a report's references' DOIs", () => { it("writes what it finds onto the references still as read, keeps a found DOI from a form made before it, and the registration waits until it is over", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { bytes: 17 }); expect(await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" })).toBeNull(); const { _id: reportId, pdf } = await row(world.t, key); // The reading checked the printed DOI; the other three are looked up after it. @@ -54,7 +54,7 @@ describe("the lookup of a report's references' DOIs", () => { it("asks OpenAlex first, sends what it can't place to Crossref a chunk at a time, and ends when time runs out before the last", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { bytes: 17 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" }); const { _id: reportId, pdf } = await row(world.t, key); const citations = Array.from({ length: 22 }, (_, n) => ({ text: `Reference ${n}` })); @@ -114,7 +114,7 @@ describe("the lookup of a report's references' DOIs", () => { it("looks a reference printed twice up once, and ends when its DOI is found", async () => { const world = await setup(); const key = await sign(world.author, world.own); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { bytes: 17 }); await world.author.mutation(api.reports.flow.attachPdf, { workspaceId: world.own, key, file, name: "report.pdf" }); const { _id: reportId, pdf } = await row(world.t, key); const citations = [{ text: "Barro 1991" }, { text: "Barro 1991" }]; diff --git a/convex/reports/registrar.ts b/convex/reports/registrar.ts index 5050d5d78..df882356f 100644 --- a/convex/reports/registrar.ts +++ b/convex/reports/registrar.ts @@ -4,6 +4,7 @@ // community's records with (@opendeved/doi-sync-core), so both make the same deposits. A report goes to its // registrars in the order its route fixed when its DOI was reserved, and each answer is kept as it comes // (./registration.ts). Every attempt is logged with what the registrar said, since it is the only record of a refusal. +import { fileBlob } from "../files/read"; import type { ZenodoHost } from "./validators"; import { v } from "convex/values"; import { CrossrefApiClient, DOCID_MAX_FILE_BYTES, ProviderHttpError, ZenodoApiClient, buildDocidDeposit, buildDocidFile, mapCrossrefRecord, type CrossrefDiagnosticResult } from "@opendeved/doi-sync-core"; @@ -174,7 +175,7 @@ export const register = internalAction({ const { landingUrl, doi, ...metadata } = zenodoRecord(record, job.metadata); const shared = { token, doiPolicy, metadata: { ...metadata, ...(doiPolicy === "external-crossref" && { doi }) }, resourceUrl: landingUrl }; if (draftOnly) { - const blob = job.pdf && (await ctx.storage.get(job.pdf.file)); + const blob = job.pdf && (await fileBlob(ctx, job.pdf.file)); if (!blob) throw new Error("The report's PDF is missing, so there is nothing to archive."); // The draft already there takes the report as it now stands (its file and details), one gone is made again, // and a new draft's id is kept the moment Zenodo gives it, so a try that fails after never makes another. @@ -195,7 +196,7 @@ export const register = internalAction({ const identifiers = found ? await client.updateRecordMetadata({ ...shared, latestRecordId: found }) : await (async () => { - const blob = job.pdf && (await ctx.storage.get(job.pdf.file)); + const blob = job.pdf && (await fileBlob(ctx, job.pdf.file)); if (!blob) throw new Error("The report's PDF is missing, so there is nothing to archive."); return client.createRecord({ ...shared, @@ -270,8 +271,8 @@ export const register = internalAction({ const pdfFile = async (blob: Blob) => ({ filename: `${job.key}.pdf`, contentType: "application/pdf", bytes: new Uint8Array(await blob.arrayBuffer()) }); if (held.publicationId === undefined) { await note({ docidDepositTried: true }); - const openFile = !record.fileAccess && job.pdf ? await ctx.storage.get(job.pdf.file) : null; - const poster = job.cover ? await ctx.storage.get(job.cover) : null; + const openFile = !record.fileAccess && job.pdf ? await fileBlob(ctx, job.pdf.file) : null; + const poster = job.cover ? await fileBlob(ctx, job.cover) : null; // DOCiD keeps each organisation's type, as ROR gives it; one ROR can't say goes without. const rors = [...new Set(record.creators.flatMap((creator) => (creator.type === "personal" ? (creator.affiliations?.flatMap((affiliation) => affiliation.ror ?? []) ?? []) : [])))]; const organizationTypes = Object.fromEntries((await Promise.all(rors.map(async (ror) => [ror, (await rorFacts(ror).catch(() => null))?.type] as const))).flatMap(([ror, type]) => (type ? [[ror, type]] : []))); @@ -304,7 +305,7 @@ export const register = internalAction({ // no added file over 25 MB: the registration says so and is done without it. let fileNote: string | undefined; if (!record.fileAccess && job.pdf && !held.fileHandle) { - const pdf = await ctx.storage.get(job.pdf.file); + const pdf = await fileBlob(ctx, job.pdf.file); if (!pdf) throw new Error("The report's PDF is missing, so DOCiD can't have it."); console.info(JSON.stringify({ event: "report-docid-file-add", reportId, key: job.key, handle, record: held.publicationId, bytes: pdf.size })); // `held` when DOCiD already has it, from a try whose answer never came or from the deposit. diff --git a/convex/reports/registration.test.ts b/convex/reports/registration.test.ts index 2406a13a6..84d177c9a 100644 --- a/convex/reports/registration.test.ts +++ b/convex/reports/registration.test.ts @@ -6,7 +6,7 @@ import { REGISTRATION_TRIES } from "./registration"; import { register } from "./registering"; import { encrypt } from "../lib/crypto"; import { keptAccess } from "../../lib/reports/report"; -import { details, live, refused, row, setup, type World } from "./reports.test-support"; +import { details, live, refused, row, setup, type World, R2_TEST, stubUploads } from "./reports.test-support"; beforeEach(() => { vi.useFakeTimers(); @@ -262,7 +262,11 @@ describe("registering a live report", () => { // DOCiD as its API answers (Africa-PID-Alliance/DOCiD publications.py, publication_edit.py), holding record 4321. const sent: string[] = []; const held: Array> = []; + // The report's PDF, kept in R2 (convex/files/r2.ts). + stubUploads(); vi.stubGlobal("fetch", async (url: string, init: RequestInit = {}) => { + // aws4fetch hands fetch a signed Request, not an address. + if (String((url as unknown as Request).url ?? url).startsWith(R2_TEST)) return new Response(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }), { headers: { "Content-Type": "application/pdf" } }); const path = new URL(url).pathname.replace("/api/v1", ""); if (url.includes("docid")) sent.push(`${init.method ?? "GET"} ${path}`); const answer = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); diff --git a/convex/reports/registration.ts b/convex/reports/registration.ts index 8f10eac43..070d292c7 100644 --- a/convex/reports/registration.ts +++ b/convex/reports/registration.ts @@ -2,6 +2,7 @@ // (./registrar.ts) is given and how what it did is kept. A report is registered again whenever what its registrars // hold has to change (./registering.ts): its details were corrected, or it was withdrawn or reinstated. import { v } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import { internal } from "../_generated/api"; import type { Doc } from "../_generated/dataModel"; import { internalMutation, internalQuery, mutation, type MutationCtx, type QueryCtx } from "../lib/functions"; @@ -68,9 +69,9 @@ export const begin = internalMutation({ archiveOwnerId: v.optional(v.id("users")), /** Who may get its file, which Zenodo keeps private, or private until a day, when not anyone. */ fileAccess: v.optional(fileAccessValidator), - pdf: v.union(v.null(), v.object({ file: v.id("_storage"), name: v.string(), pages: v.optional(v.number()) })), + pdf: v.union(v.null(), v.object({ file: fileRefValidator, name: v.string(), pages: v.optional(v.number()) })), /** Its cover, which DOCiD shows as the record's poster. */ - cover: v.optional(v.id("_storage")), + cover: v.optional(fileRefValidator), /** Where its DOCiD stands: its Handle and DOCiD's record of it, once each exists. */ docid: v.optional(docidRegistrationValidator), publication: publicationSettingsValidator, diff --git a/convex/reports/reports.test-support.ts b/convex/reports/reports.test-support.ts index 2b7c77dbe..1a297ab11 100644 --- a/convex/reports/reports.test-support.ts +++ b/convex/reports/reports.test-support.ts @@ -3,9 +3,9 @@ import { register as registerPresence } from "@convex-dev/presence/test"; import { register as registerWorkpool } from "@convex-dev/workpool/test"; import { convexTest } from "convex-test"; -import { expect } from "vitest"; +import { expect, vi } from "vitest"; import { api, internal } from "../_generated/api"; -import type { Id } from "../_generated/dataModel"; +import type { Doc, Id } from "../_generated/dataModel"; import schema from "../schema"; import { REPORT_DEFAULTS } from "../../lib/reports/settings"; import { blankDetails, type Metadata } from "../../lib/reports/report"; @@ -74,7 +74,7 @@ export const row = (t: World["t"], key: string) => t.run(async (ctx) => (await c /** A report with a PDF attached and read, waiting at its details. */ export async function atDetails(world: World, who = world.author, workspaceId = world.own) { const key = await sign(who, workspaceId); - const file = await world.t.run((ctx) => ctx.storage.store(new Blob(["%PDF-1.7 a report"], { type: "application/pdf" }))); + const file = await uploaded(world, { by: who, bytes: 17 }); expect(await who.mutation(api.reports.flow.attachPdf, { workspaceId, key, file, name: "report.pdf" })).toBeNull(); const { _id: reportId, pdf } = await row(world.t, key); await world.t.mutation(internal.reports.readingState.finish, { reportId, at: pdf!.at, pages: 12, metadata: details() }); @@ -110,3 +110,32 @@ export async function live(world: World, who = world.author, workspaceId = world /** Whether review is on, set as an admin sets it. */ export const setReview = (world: World, humanReview: boolean) => world.reviewer.mutation(api.reports.settings.update, { humanReview }); + +/** + * A file the person `clerkId` has just uploaded to R2 (convex/files/uploads.ts), as `finish` leaves it: kept, and + * nothing holding it yet. Only its row: R2 isn't reached in these tests. + */ +export const uploaded = (world: Pick, { by, bytes = 1000, purpose = "report-pdf", contentType }: { /** Who sent it: the author when none is named. */ by?: World["author"]; bytes?: number; purpose?: Doc<"storedFiles">["purpose"]; contentType?: string } = {}) => + (by ?? world.t.withIdentity({ subject: "author" })).run(async (ctx) => { + const clerkId = (await ctx.auth.getUserIdentity())!.subject; + const user = (await ctx.db.query("users").withIndex("by_clerk_id", (q) => q.eq("clerkId", clerkId)).unique())!; + return await ctx.db.insert("storedFiles", { key: `test/${crypto.randomUUID()}`, name: "file", contentType: contentType ?? (purpose === "report-cover" ? "image/jpeg" : "application/pdf"), bytes, purpose, by: user._id, state: "kept", keptAt: Date.now() }); + }); + +/** A report's file as its store holds it: its R2 row, or a file in Convex storage from before; null once it is deleted (an R2 row waiting for R2 to let its bytes go counts). */ +export const fileRow = (world: Pick, file: Id<"storedFiles"> | Id<"_storage">) => + world.t.run(async (ctx) => { + const kept = ctx.db.normalizeId("storedFiles", file); + if (!kept) return await ctx.db.system.get(file as Id<"_storage">); + const row = await ctx.db.get("storedFiles", kept); + return row?.state === "dropping" ? null : row; + }); + +/** R2's address in these tests (convex/files/r2.ts): a fetch stub answers it, and signing needs only these settings. */ +export const R2_TEST = "https://r2.test"; +export function stubUploads() { + vi.stubEnv("UPLOADS_ENDPOINT", R2_TEST); + vi.stubEnv("UPLOADS_BUCKET", "uploads"); + vi.stubEnv("UPLOADS_ACCESS_KEY_ID", "test-key"); + vi.stubEnv("UPLOADS_SECRET_ACCESS_KEY", "test-secret"); +} diff --git a/convex/reports/review.ts b/convex/reports/review.ts index 4bf056ca2..a360e0311 100644 --- a/convex/reports/review.ts +++ b/convex/reports/review.ts @@ -1,6 +1,7 @@ // Reviewing Openscholar Reports (plans/publish-reports). Reviewers are Openscholar's admins. From Settings > Admin > // Publishing they read every report, approve, decline, withdraw and reinstate it whatever its checks said, approve // or decline changes to a live one, and edit a report's details themselves. +import { fileAddress } from "../files/read"; import { v, type Infer } from "convex/values"; import { internal } from "../_generated/api"; import type { Doc, Id } from "../_generated/dataModel"; @@ -10,7 +11,7 @@ import { refuseApps } from "../lib/auth"; import { createError } from "../lib/errors"; import { personName } from "../lib/people"; import { workspaceFrom } from "../workspaces/personal"; -import { REVIEW_TEXT_MAX, STAGES, beingWorkedOn, changesOf, costOf, nothingToPay, doiIn, fileAccessOf, fileOut, keptFileAddress, isReportKey, isAuthor, licenceOf, listedStage, stageOf, wantsReviewer, type Stage } from "../../lib/reports/report"; +import { REVIEW_TEXT_MAX, STAGES, beingWorkedOn, changesOf, costOf, nothingToPay, doiIn, fileAccessOf, fileOut, keptFileAddress, openFilePath, isReportKey, isAuthor, licenceOf, listedStage, stageOf, wantsReviewer, type Stage } from "../../lib/reports/report"; import { applyChanges } from "./corrections"; import { MAX_WORKSPACE_REPORTS, activatingOwner, changeFileAccess, checkedDetails, detailsOf, signedAgreement, touch } from "./flow"; import { becameReady, notify } from "./mail"; @@ -48,7 +49,7 @@ async function row(ctx: QueryCtx, report: Doc<"reports">, humanReview: boolean, ...((report.title ?? report.pdf?.name) && { title: report.title ?? report.pdf?.name }), withdrawn: report.withdrawnAt !== undefined, signer: report.signedBy.name, - coverUrl: report.cover ? (fileOut(report) ? await ctx.storage.getUrl(report.cover.file) : keptFileAddress(report.key, "cover", report.cover.at)) : null, ...(report.cover?.shape && { coverShape: report.cover.shape }), + coverUrl: report.cover ? (fileOut(report) ? await fileAddress(ctx, report.cover.file, openFilePath(report.key, "cover")) : keptFileAddress(report.key, "cover", report.cover.at)) : null, ...(report.cover?.shape && { coverShape: report.cover.shape }), ...(report.pdf && { pdfAt: report.pdf.at }), ...(first?.name && { first: { name: first.name, ...(first.affiliations[0]?.country && { country: first.affiliations[0].country }) } }), }; @@ -146,7 +147,7 @@ export const get = query({ agreementVersion: report.agreementVersion, ...(report.checksVersion !== undefined && { checksVersion: report.checksVersion }), ...(report.run && { run: { at: report.run.at, changes: report.run.changes === true } }), - ...(report.pdf && { pdf: { name: report.pdf.name, bytes: report.pdf.bytes, at: report.pdf.at, ...(report.pdf.pages !== undefined && { pages: report.pdf.pages }), ...(report.pdf.trouble && { trouble: report.pdf.trouble }), ...(report.pdf.lacksByline && { lacksByline: true }), ...(report.pdf.kept && { kept: true }), url: fileOut(report) ? await ctx.storage.getUrl(report.pdf.file) : keptFileAddress(report.key, "pdf", report.pdf.at) } }), + ...(report.pdf && { pdf: { name: report.pdf.name, bytes: report.pdf.bytes, at: report.pdf.at, ...(report.pdf.pages !== undefined && { pages: report.pdf.pages }), ...(report.pdf.trouble && { trouble: report.pdf.trouble }), ...(report.pdf.lacksByline && { lacksByline: true }), ...(report.pdf.kept && { kept: true }), url: fileOut(report) ? await fileAddress(ctx, report.pdf.file, openFilePath(report.key, "pdf")) : keptFileAddress(report.key, "pdf", report.pdf.at) } }), ...(details.metadata && { metadata: details.metadata }), ...(details.results && { results: details.results }), ...(details.reviewRequest && { reviewRequest: details.reviewRequest }), diff --git a/convex/reports/validators.ts b/convex/reports/validators.ts index f09a2b7de..e910e8df2 100644 --- a/convex/reports/validators.ts +++ b/convex/reports/validators.ts @@ -1,4 +1,5 @@ import { v, type Infer } from "convex/values"; +import { fileRefValidator } from "../files/validators"; import { effortValidator, modelSummaryValidator } from "../aiModelConfig/validators"; import { keptCustomValidator, publicationSettingsValidator } from "../evidenceLibraries/publicationValidators"; import { FUNDER_TYPES } from "@opendeved/doi-sync-core/docid"; @@ -264,7 +265,7 @@ export const bylineByValidator = v.union(v.literal("self"), v.literal("added")); /** Why the page Openscholar adds couldn't be added (lib/reports/byline-page.ts `BylineTrouble`): its author is told what to do about it. */ export const bylineTroubleValidator = v.union(v.literal("protected"), v.literal("damaged")); export const pdfValidator = v.object({ - file: v.id("_storage"), + file: fileRefValidator, name: v.string(), bytes: v.number(), /** When it was uploaded, which tells one upload's reading from the next one's. */ @@ -276,7 +277,7 @@ export const pdfValidator = v.object({ /** Known once it has been opened. */ pages: v.optional(v.number()), /** Its text, which the checks read, kept as a file beside it. */ - text: v.optional(v.id("_storage")), + text: v.optional(fileRefValidator), /** It couldn't be opened as a PDF, it holds no text (a scan), or its details couldn't be read from it: the author is told which. */ trouble: v.optional(pdfTroubleValidator), /** Its text doesn't carry the report's byline word for word, which the byline check looks for: said at the upload, before the checks. */ @@ -286,7 +287,7 @@ export const pdfValidator = v.object({ /** Its last page is the one Openscholar added, which says the report's details: written again when the checks read them. */ stamped: v.optional(v.boolean()), /** The PDF as its author uploaded it, kept beside the one with the page added: each page is made from it, never from a PDF made before. A report stamped before it was kept has none. */ - original: v.optional(v.id("_storage")), + original: v.optional(fileRefValidator), /** With `lacksByline` and the page asked for: why it couldn't be added. A PDF from before the reason was kept has none. */ bylineTrouble: v.optional(bylineTroubleValidator), /** Its details are the ones the report had before this PDF replaced another: the author may have them read from this one instead. */ @@ -374,7 +375,7 @@ export const reportFields = { run: v.optional(v.object({ id: v.string(), at: v.number(), /** It reads changes to a live report, which stays as it is meanwhile. */ changes: v.optional(v.boolean()), /** The checks it was given when it started, by name: what the page lists until it ends. A run started before these were kept has none. */ checks: optionalCheckNames })), pdf: v.optional(pdfValidator), /** A picture of the PDF's first page, and when it was made. */ - cover: v.optional(v.object({ file: v.id("_storage"), at: v.number(), /** Its width over its height, which its frame takes before it loads. A cover from before this has none (migrations/coverShapes). */ shape: v.optional(v.number()) })), + cover: v.optional(v.object({ file: fileRefValidator, at: v.number(), /** Its width over its height, which its frame takes before it loads. A cover from before this has none (migrations/coverShapes). */ shape: v.optional(v.number()) })), registration: registrationValidator, deposit: depositValidator, archive: archiveValidator, @@ -495,7 +496,7 @@ export const reviewDecisionValidator = v.union(v.literal("approve"), v.literal(" /** A reviewer's word on a report, or on changes to a live one: who gave it and when. One row each, oldest first by creation. */ export const reportReviewFields = { reportId: v.id("reports"), decision: reviewDecisionValidator, by: v.id("users"), at: v.number(), note: v.optional(v.string()) }; /** Which report a stored file is: its PDF, the picture of its first page, or its text. A file with a row here is never another report's. */ -export const reportFileFields = { file: v.id("_storage"), reportId: v.id("reports") }; +export const reportFileFields = { file: fileRefValidator, reportId: v.id("reports") }; /** What a run's details were made from: a PDF's reading, or a live report's details as they stood. */ export const runFromValidator = v.union(v.object({ pdfAt: v.number() }), v.object({ changesSince: v.number() })); @@ -547,3 +548,6 @@ export const withdrawnReportValidator = v.object({ state: v.literal("withdrawn") /** An email about a report, kept on its record: who it went to, what it said, and why it didn't go if it didn't. */ export const mailAudienceValidator = v.union(v.literal("team"), v.literal("author"), v.literal("admins")); export const reportEmailFields = { reportId: v.id("reports"), event: v.string(), audience: mailAudienceValidator, subject: v.string(), text: v.string(), at: v.number(), error: v.optional(v.string()) }; + +/** What a report holds its files in R2 under, so nothing else takes them and they are kept (convex/files/uploads.ts). */ +export const reportHolder = (reportId: string) => `report:${reportId}`; diff --git a/convex/schema.ts b/convex/schema.ts index a4a5e28b2..820c8b0b1 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -2,6 +2,7 @@ import { defineSchema, defineTable } from "convex/server"; import { exportFormatValidator, exportSourceValidator } from "./exportValidators"; import { libraryItemFields, removedItemValidator } from "./library/validators"; import { v } from "convex/values"; +import { storedFileFields } from "./files/validators"; import { sourceMetadataFields } from "./lib/paperMetadata"; import { paperIdentityFields } from "./lib/paperRef"; import { rateLimitTables } from "convex-helpers/server/rateLimit"; @@ -690,6 +691,8 @@ export default defineSchema({ reportReviews: defineTable(reportReviewFields).index("by_reportId", ["reportId"]), reportEmails: defineTable(reportEmailFields).index("by_reportId", ["reportId"]), reportFiles: defineTable(reportFileFields).index("by_file", ["file"]), + // Files kept in R2 (convex/files): uploads, and the files the server makes from them. + storedFiles: defineTable(storedFileFields).index("by_state", ["state"]).index("by_heldBy_and_state_and_keptAt", ["heldBy", "state", "keptAt"]).index("by_state_and_droppedAt", ["state", "droppedAt"]), // The number the next report's key is made from: one row. reportKeys: defineTable({ next: v.number() }), diff --git a/lib/files/limits.ts b/lib/files/limits.ts index bc80ed99f..7318686b7 100644 --- a/lib/files/limits.ts +++ b/lib/files/limits.ts @@ -1,2 +1,20 @@ export const MAX_PDF_MB = 100; export const MAX_PDF_BYTES = MAX_PDF_MB * 1024 * 1024; + +/** What Zenodo keeps in one record: 50 GB (help.zenodo.org/docs/deposit/manage-files), its supplements' limit together. */ +export const ZENODO_RECORD_BYTES = 50_000_000_000; + +/** The most a file uploaded as each of these may be. */ +export const UPLOAD_MAX_BYTES = { + "report-pdf": MAX_PDF_BYTES, + "report-cover": 10 * 1024 * 1024, + "report-supplement": ZENODO_RECORD_BYTES, +} as const; + +/** + * A file larger than this goes up in parts of this size, several at a time: one that fails is sent again on its own, + * and none comes near what one request to R2 takes. + */ +export const UPLOAD_PART_BYTES = 64 * 1024 * 1024; +/** The most parts one upload has: the largest file there is, in parts of `UPLOAD_PART_BYTES`. */ +export const MAX_UPLOAD_PARTS = Math.ceil(ZENODO_RECORD_BYTES / UPLOAD_PART_BYTES); diff --git a/lib/files/upload.ts b/lib/files/upload.ts new file mode 100644 index 000000000..8cbefce3a --- /dev/null +++ b/lib/files/upload.ts @@ -0,0 +1,82 @@ +"use client"; + +// Sends a file from the browser straight to R2 (convex/files/uploads.ts): one request, or parts of `partBytes` a few at +// a time for a large file. A part that fails is sent again on its own. Progress is told as bytes sent. +import { useAction } from "convex/react"; +import { useCallback } from "react"; +import { api } from "@/convex/_generated/api"; +import type { Id } from "@/convex/_generated/dataModel"; + +export type UploadPurpose = "report-pdf" | "report-cover" | "report-supplement"; + +/** Parts on their way at once. */ +const PARALLEL = 4; +/** Tries a part gets before the upload is given up. */ +const TRIES = 3; + +/** PUTs `body` to a signed address, telling how much of it has gone. Gives the ETag R2 answered with. */ +function put(url: string, body: Blob, contentType: string, onSent: (bytes: number) => void, signal?: AbortSignal) { + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest(); + request.open("PUT", url); + if (contentType) request.setRequestHeader("Content-Type", contentType); + request.upload.onprogress = (event) => onSent(event.loaded); + request.onload = () => (request.status >= 200 && request.status < 300 ? resolve(request.getResponseHeader("ETag") ?? "") : reject(new Error(`The upload was refused (${request.status}).`))); + request.onerror = () => reject(new Error("The upload was interrupted.")); + request.onabort = () => reject(new DOMException("The upload was stopped.", "AbortError")); + signal?.addEventListener("abort", () => request.abort(), { once: true }); + request.send(body); + }); +} + +async function tried(run: () => Promise, signal?: AbortSignal) { + for (let attempt = 1; ; attempt++) { + try { + return await run(); + } catch (error) { + if (signal?.aborted || attempt >= TRIES) throw error; + await new Promise((wait) => setTimeout(wait, 1000 * attempt)); + } + } +} + +/** The uploader: sends `file` as `purpose` and gives the id it is kept under, once R2 holds all of it. */ +export function useUpload() { + const start = useAction(api.files.uploads.start); + const finish = useAction(api.files.uploads.finish); + return useCallback( + async (file: File | Blob, purpose: UploadPurpose, { name, onProgress, signal }: { name?: string; onProgress?: (sent: number, total: number) => void; signal?: AbortSignal } = {}): Promise> => { + const contentType = file.type || "application/octet-stream"; + const filename = name ?? ("name" in file ? file.name : "file"); + const target = await start({ purpose, name: filename, contentType, bytes: file.size }); + if (target.url) { + await tried(() => put(target.url!, file, contentType, (sent) => onProgress?.(sent, file.size), signal), signal); + await finish({ fileId: target.fileId }); + return target.fileId; + } + const parts = target.parts ?? []; + const size = target.partBytes ?? file.size; + const sent = new Array(parts.length).fill(0); + const etags = new Array(parts.length); + let next = 0; + const worker = async () => { + while (next < parts.length) { + const at = next++; + const body = file.slice(at * size, Math.min(file.size, (at + 1) * size)); + etags[at] = await tried( + () => + put(parts[at]!, body, "", (bytes) => { + sent[at] = bytes; + onProgress?.(sent.reduce((sum, one) => sum + one, 0), file.size); + }, signal), + signal, + ); + } + }; + await Promise.all(Array.from({ length: Math.min(PARALLEL, parts.length) }, worker)); + await finish({ fileId: target.fileId, etags }); + return target.fileId; + }, + [start, finish], + ); +} diff --git a/lib/reports/report.ts b/lib/reports/report.ts index 62a28c3a6..d82a4e8bb 100644 --- a/lib/reports/report.ts +++ b/lib/reports/report.ts @@ -317,6 +317,8 @@ export const fileOut = (report: Parameters[0] & { status: * address that asks who they are each time (app/api/reports/files). The file store's own address works for anyone it is * passed to, for good, so a private or embargoed PDF copied from its owner's page would be anyone's. */ +/** Where a file out for everyone is read when it is kept in R2: a Convex site route that sends readers on to it (convex/reports/files.ts `open`). */ +export const openFilePath = (key: string, part: "pdf" | "cover") => `/reports/open?key=${encodeURIComponent(key)}&part=${part}`; export const keptFileAddress = (key: string, part: "pdf" | "cover", at: number) => `/api/reports/files/${key}?${part === "cover" ? "part=cover&" : ""}at=${at}`; /** What a deposit says of the file: nothing when anyone may have it, else restricted, until a day under an embargo. */ export function depositFileAccess(access: FileAccess): { restricted: true; until?: string } | undefined { diff --git a/scripts/convex-rules.json b/scripts/convex-rules.json index c600c9067..3e9ad3d31 100644 --- a/scripts/convex-rules.json +++ b/scripts/convex-rules.json @@ -167,7 +167,8 @@ "REVIEWS_REMOVED": "a removed report's reviewer decisions, deleted with it; one that can be removed never went live, so it has a decline or two", "OPENED_PER_RUN": "reports whose embargo ended opened in one hourly run; the rest are opened by the next", "DUE": "living screenings whose check is due, started in one run of the schedule; past it the run schedules itself for the rest", - "STEP": "papers one step of a change to a screening's reviewers looks at; it reschedules itself until every open paper has been" + "STEP": "papers one step of a change to a screening's reviewers looks at; it reschedules itself until every open paper has been", + "SWEPT": "uploads never finished and kept files nothing took, a run of the hourly sweep each; the next run takes the rest" } } } diff --git a/scripts/user-actions-exempt.json b/scripts/user-actions-exempt.json index 7ad647d98..e77d2328a 100644 --- a/scripts/user-actions-exempt.json +++ b/scripts/user-actions-exempt.json @@ -59,6 +59,8 @@ "extraction/queries:getJobShell": "The extraction page's frame while it loads. The assistant reads a job through extraction/queries:getJobDetails.", "extraction/queries:subscribeToJobProgress": "The extraction page's live progress. The assistant reads it through extraction/queries:getJobDetails.", "extraction/uploads:generateUploadUrl": "A storage URL for a file the person picks in their browser.", + "files/uploads:finish": "Says the browser has sent all of a file to R2. The assistant attaches no files of its own.", + "files/uploads:start": "Signed addresses for a file the person picks in their browser, sent straight to R2.", "extraction/uploads:recordUploadedFile": "Records a PDF the person's browser uploaded to an extraction.", "featureFlags/queries:list": "Feature flags the pages check before showing a feature.", "library/collections:deleteSoon": "The Library page's delete, held for its Undo. The assistant deletes with library/collections:deleteCollection, at once, and says it can't be undone.", diff --git a/tests/convex-timers.ts b/tests/convex-timers.ts index 7527cc3aa..77ddd6bf9 100644 --- a/tests/convex-timers.ts +++ b/tests/convex-timers.ts @@ -6,6 +6,9 @@ */ import { afterAll, afterEach } from "vitest"; +// Every Convex deployment says its HTTP actions' address; convex-test doesn't, and file addresses are built on it (convex/files/read.ts). +process.env.CONVEX_SITE_URL ??= "https://convex-site.test"; + type Timer = ReturnType; type Armed = { timers: Set; clear: typeof clearTimeout; set: typeof setTimeout }; type Backend = { finishInProgressScheduledFunctions: () => Promise };