diff --git a/convex/reports/registrar.ts b/convex/reports/registrar.ts index 884da79cc..5050d5d78 100644 --- a/convex/reports/registrar.ts +++ b/convex/reports/registrar.ts @@ -6,7 +6,7 @@ // (./registration.ts). Every attempt is logged with what the registrar said, since it is the only record of a refusal. import type { ZenodoHost } from "./validators"; import { v } from "convex/values"; -import { CrossrefApiClient, ProviderHttpError, ZenodoApiClient, buildDocidDeposit, mapCrossrefRecord, type CrossrefDiagnosticResult } from "@opendeved/doi-sync-core"; +import { CrossrefApiClient, DOCID_MAX_FILE_BYTES, ProviderHttpError, ZenodoApiClient, buildDocidDeposit, buildDocidFile, mapCrossrefRecord, type CrossrefDiagnosticResult } from "@opendeved/doi-sync-core"; import { internal } from "../_generated/api"; import { zenodoAccessToken } from "../zenodo/connectionActions"; import { internalAction } from "../_generated/server"; @@ -231,7 +231,7 @@ export const register = internalAction({ throw new Error(job.docid.sandbox ? "This report's DOCiD was minted on DOCiD's demo, and DOCiD is now set to an account on DOCiD itself." : "This report's DOCiD was minted on DOCiD itself, and DOCiD is now set to its sandbox."); const client = docidClient(sandbox); const { token, userId } = await client.signIn({ email: docid.email, password: secrets.docidPassword }); - const note = (kept: { docidHandle?: string; docidSandbox?: boolean; docidPublicationId?: number; docidRetired?: boolean; docidDepositTried?: boolean }) => ctx.runMutation(internal.reports.registration.noted, { reportId, rev, ...kept }); + const note = (kept: { docidHandle?: string; docidSandbox?: boolean; docidPublicationId?: number; docidRetired?: boolean; docidDepositTried?: boolean; docidFileHandle?: string }) => ctx.runMutation(internal.reports.registration.noted, { reportId, rev, ...kept }); const held = { ...(job.docid ?? { state: "queued" as const }) }; // A deposit sent before whose answer never came is found in the account's records first: it may need // retiring, and it is never sent twice. @@ -260,6 +260,14 @@ export const register = internalAction({ handle = await client.mint({ token, title: record.title, description: record.abstract ?? record.title, idempotencyKey: mintKey(job.key) }); await note({ docidHandle: handle, docidSandbox: sandbox }); } + // The record Crossref and Zenodo are sent, of the kind its author chose, as Zenodo files it, with its date + // as the author gave it: DOCiD takes a year or a month alone, where Zenodo needs a whole date. + const { doi: _, ...sent } = zenodoRecord(record, job.metadata); + const docidRecord = { ...sent, publicationDate: record.publicationDate, ...(doi && { doi }) }; + // Read now, so a type DOCiD added since the settings were saved is used. + const lists = () => readDocidLists(token, sandbox); + // Its file only when anyone may get it: DOCiD shows what it holds to everyone. + 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; @@ -267,26 +275,21 @@ export const register = internalAction({ // 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]] : []))); - const { doi: _, ...sent } = zenodoRecord(record, job.metadata); const deposited = await client.deposit({ token, - // The record Crossref and Zenodo are sent, of the kind its author chose, as Zenodo files it, with its date - // as the author gave it: DOCiD takes a year or a month alone, where Zenodo needs a whole date. - deposit: buildDocidDeposit( - { ...sent, publicationDate: record.publicationDate, ...(doi && { doi }) }, - { - docid: handle, - // Read now, so a type DOCiD added since the settings were saved is used. - lists: await readDocidLists(token, sandbox), - organizationTypes, - // Its file only when anyone may get it: DOCiD shows what it holds to everyone. - ...(openFile && { file: { filename: `${job.key}.pdf`, contentType: "application/pdf", bytes: new Uint8Array(await openFile.arrayBuffer()) } }), - ...(poster && { poster: { filename: `${job.key}-cover.png`, contentType: poster.type || "image/png", bytes: new Uint8Array(await poster.arrayBuffer()) } }), - }, - ), + deposit: buildDocidDeposit(docidRecord, { + docid: handle, + lists: await lists(), + organizationTypes, + ...(openFile && { file: await pdfFile(openFile) }), + ...(poster && { poster: { filename: `${job.key}-cover.png`, contentType: poster.type || "image/png", bytes: new Uint8Array(await poster.arrayBuffer()) } }), + }), }); - await note({ docidPublicationId: deposited.publicationId }); - console.info(JSON.stringify({ event: "report-docid-deposit", reportId, key: job.key, handle, record: deposited.publicationId })); + // A file the deposit carried is under the record's own Handle. + await note({ docidPublicationId: deposited.publicationId, ...(openFile && { docidFileHandle: handle }) }); + held.publicationId = deposited.publicationId; + if (openFile) held.fileHandle = handle; + console.info(JSON.stringify({ event: "report-docid-deposit", reportId, key: job.key, handle, record: deposited.publicationId, file: openFile !== null })); } else { // A reinstated report's record comes back, and a corrected one takes its new title, abstract and DOI. if (held.retired) { @@ -296,7 +299,25 @@ export const register = internalAction({ await client.update({ token, publicationId: held.publicationId, title: record.title, description: record.abstract ?? record.title, ...(doi && { doi }) }); console.info(JSON.stringify({ event: "report-docid-update", reportId, key: job.key, handle, record: held.publicationId })); } - if (!(await settle(provider, { outcome: "done" }))) return null; + // A deposit carries the PDF only if anyone could get it then. Once its embargo ends or its file is opened, + // the PDF is added to the record, under a Handle of its own, and kept so it is never sent twice. DOCiD takes + // 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); + 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. + const added = await client.addFile({ token, publicationId: held.publicationId, file: buildDocidFile(docidRecord, { lists: await lists(), file: await pdfFile(pdf) }) }); + if (added.outcome === "too-large") { + fileNote = `DOCiD's record has no PDF: DOCiD takes files up to ${DOCID_MAX_FILE_BYTES / 1024 / 1024} MB, and this one is ${(pdf.size / 1024 / 1024).toFixed(1)} MB.`; + console.error(JSON.stringify({ event: "report-docid-file-too-large", reportId, key: job.key, handle, record: held.publicationId, bytes: pdf.size })); + } else { + await note({ docidFileHandle: added.handle }); + console.info(JSON.stringify({ event: "report-docid-file-added", reportId, key: job.key, handle, record: held.publicationId, outcome: added.outcome, file: added.fileId, fileHandle: added.handle })); + } + } + if (!(await settle(provider, { outcome: "done", ...(fileNote && { error: fileNote }) }))) return null; } } catch (error) { console.error(JSON.stringify({ event: "report-registration-failed", reportId, key: job.key, provider, error: words(error) })); diff --git a/convex/reports/registration.test.ts b/convex/reports/registration.test.ts index 2901e99ed..2406a13a6 100644 --- a/convex/reports/registration.test.ts +++ b/convex/reports/registration.test.ts @@ -3,6 +3,9 @@ import { buildCrossrefPublicationXml, buildZenodoRecordPayload, mapCrossrefRecor import { api, internal } from "../_generated/api"; import { registrationRecord, zenodoRecord } from "../../lib/reports/registration-record"; 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"; beforeEach(() => { @@ -253,6 +256,95 @@ describe("registering a live report", () => { expect(await world.t.mutation(internal.reports.registration.begin, { reportId: next.reportId, rev: await revOf(world, next.reportId) })).toMatchObject({ series: { issn: "2049-3630" } }); }); + it("adds the PDF to the DOCiD record it already holds once the embargo ends, never twice, and says so when DOCiD can't take it", async () => { + const KEY = "11".repeat(32); + vi.stubEnv("ENCRYPTION_KEY", KEY); + // DOCiD as its API answers (Africa-PID-Alliance/DOCiD publications.py, publication_edit.py), holding record 4321. + const sent: string[] = []; + const held: Array> = []; + vi.stubGlobal("fetch", async (url: string, init: RequestInit = {}) => { + 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" } }); + if (path === "/auth/login") return answer({ user_id: 203, token: "jwt", refresh_token: "refresh" }); + if (path === "/publications/get-list-publication-types") return answer([{ id: 18, publication_type_name: "Report" }, { id: 5, publication_type_name: "Monograph" }]); + if (path.startsWith("/publications/get-list-")) return answer([]); + if (path === "/publications/get-publication-for-edit/4321") return answer({ id: 4321, publications_files: held }); + if (path === "/publications/4321/files") { + held.push({ id: 77, file_name: `3fa85f6457b2_${(init.body as FormData).get("file") instanceof File ? ((init.body as FormData).get("file") as File).name : ""}`, handle_identifier: "20.500.14351/c0ffee" }); + return answer({ message: "File added", id: 77, handle: "20.500.14351/c0ffee" }, 201); + } + if (path === "/publications/update-publication/4321") return answer({ message: "Publication updated" }); + return answer({ results: [] }); + }); + try { + const world = await setup(); + const { key, reportId } = await live(world); + await settled(world); + await world.t.run(async (ctx) => { + const settings = (await ctx.db.query("reportSettings").first())!; + await ctx.db.patch("reportSettings", settings._id, { + publication: { ...settings.publication, docid: { mode: "custom", email: "docid@test.local", options: { resourceTypes: [], publicationTypes: [], funderTypes: [] } } }, + encryptedCredentials: encrypt(JSON.stringify({ docidPassword: "secret" }), KEY), + }); + const report = (await ctx.db.get("reports", reportId))!; + // Deposited while embargoed, so DOCiD's record has no file yet. + await ctx.db.patch("reports", reportId, { + accountsId: undefined, + registration: { ...report.registration, crossref: false, zenodo: false, docid: true }, + deposit: "none", + archive: "none", + registrations: { docid: { state: "registered", handle: "20.500.14351/9f2c1e", sandbox: false, publicationId: 4321 } }, + ...keptAccess({ mode: "embargo", until: "2026-12-01" }), + }); + }); + vi.setSystemTime(new Date("2026-12-01T00:30:00Z")); + expect(await world.t.mutation(internal.reports.fileAccess.openEmbargoes, {})).toBe(1); + await settled(world); + expect(sent.filter((call) => call === "POST /publications/4321/files")).toHaveLength(1); + let report = await row(world.t, key); + expect(report.registrations?.docid).toMatchObject({ state: "registered", fileHandle: "20.500.14351/c0ffee" }); + expect(report).not.toHaveProperty("registrationError"); + + // Registered again, as a correction does: DOCiD is known to hold it, so nothing is asked or sent. + sent.length = 0; + await world.t.run(async (ctx) => register(ctx, (await ctx.db.get("reports", reportId))!)); + await settled(world); + expect(sent).toContain("PUT /publications/update-publication/4321"); + expect(sent.filter((call) => call.includes("/files") || call.includes("get-publication-for-edit"))).toEqual([]); + + // A try whose answer was lost: DOCiD's record already has the file, which is found and kept, not sent again. + sent.length = 0; + await world.t.run(async (ctx) => { + const now = (await ctx.db.get("reports", reportId))!; + await ctx.db.patch("reports", reportId, { registrations: { docid: { ...now.registrations!.docid!, fileHandle: undefined } } }); + await register(ctx, (await ctx.db.get("reports", reportId))!); + }); + await settled(world); + expect(sent).toContain("GET /publications/get-publication-for-edit/4321"); + expect(sent).not.toContain("POST /publications/4321/files"); + expect((await row(world.t, key)).registrations?.docid).toMatchObject({ state: "registered", fileHandle: "20.500.14351/c0ffee" }); + + // A PDF over DOCiD's 25 MB: the registration is done without it, and says why. + sent.length = 0; + held.length = 0; + await world.t.run(async (ctx) => { + const now = (await ctx.db.get("reports", reportId))!; + const big = await ctx.storage.store(new Blob([new Uint8Array(26 * 1024 * 1024)], { type: "application/pdf" })); + await ctx.db.patch("reports", reportId, { pdf: { ...now.pdf!, file: big }, registrations: { docid: { ...now.registrations!.docid!, fileHandle: undefined } } }); + await register(ctx, (await ctx.db.get("reports", reportId))!); + }); + await settled(world); + expect(sent).not.toContain("POST /publications/4321/files"); + report = await row(world.t, key); + expect(report.registrations?.docid).toMatchObject({ state: "registered" }); + expect(report.registrations?.docid).not.toHaveProperty("fileHandle"); + expect(report.registrationError).toContain("25 MB"); + } finally { + vi.unstubAllGlobals(); + } + }); + it("goes to its registrars again when it is withdrawn and when it is reinstated", async () => { const world = await setup(); const { key, reportId } = await live(world); diff --git a/convex/reports/registration.ts b/convex/reports/registration.ts index dc9b5a9fa..8f10eac43 100644 --- a/convex/reports/registration.ts +++ b/convex/reports/registration.ts @@ -131,18 +131,18 @@ export const end = internalMutation({ * Crossref took the deposit (it is then looked for, not sent again), or Zenodo made a draft (it is carried on from). */ export const noted = internalMutation({ - args: { reportId: v.id("reports"), rev: v.number(), depositSent: v.optional(v.boolean()), zenodoDraftId: v.optional(v.string()), docidHandle: v.optional(v.string()), docidSandbox: v.optional(v.boolean()), docidPublicationId: v.optional(v.number()), docidRetired: v.optional(v.boolean()), docidDepositTried: v.optional(v.boolean()) }, + args: { reportId: v.id("reports"), rev: v.number(), depositSent: v.optional(v.boolean()), zenodoDraftId: v.optional(v.string()), docidHandle: v.optional(v.string()), docidSandbox: v.optional(v.boolean()), docidPublicationId: v.optional(v.number()), docidRetired: v.optional(v.boolean()), docidDepositTried: v.optional(v.boolean()), docidFileHandle: v.optional(v.string()) }, returns: v.null(), - handler: async (ctx, { reportId, rev, depositSent, zenodoDraftId, docidHandle, docidSandbox, docidPublicationId, docidRetired, docidDepositTried }) => { + handler: async (ctx, { reportId, rev, depositSent, zenodoDraftId, docidHandle, docidSandbox, docidPublicationId, docidRetired, docidDepositTried, docidFileHandle }) => { const report = await ctx.db.get("reports", reportId); if (!report) return null; // A draft is the report's whichever asking made it; a deposit is of the record as that asking had it. await ctx.db.patch("reports", reportId, { ...(zenodoDraftId && { zenodoDraftId }), ...(depositSent && report.registrationRev === rev && { depositSent: true }) }); // A DOCiD and its record are the report's whichever asking made them: kept at once, never made twice. A Handle // is part of what the report's page and the search index show, so it counts as a change. - if (docidHandle !== undefined || docidPublicationId !== undefined || docidRetired !== undefined || docidDepositTried !== undefined) { + if (docidHandle !== undefined || docidPublicationId !== undefined || docidRetired !== undefined || docidDepositTried !== undefined || docidFileHandle !== undefined) { const docid = report.registrations?.docid ?? { state: "queued" as const }; - const kept = { registrations: { ...report.registrations, docid: { ...docid, ...(docidHandle && { handle: docidHandle, sandbox: docidSandbox }), ...(docidPublicationId !== undefined && { publicationId: docidPublicationId }), ...(docidRetired !== undefined && { retired: docidRetired }), ...(docidDepositTried !== undefined && { depositTried: docidDepositTried }) } } }; + const kept = { registrations: { ...report.registrations, docid: { ...docid, ...(docidHandle && { handle: docidHandle, sandbox: docidSandbox }), ...(docidPublicationId !== undefined && { publicationId: docidPublicationId }), ...(docidRetired !== undefined && { retired: docidRetired }), ...(docidDepositTried !== undefined && { depositTried: docidDepositTried }), ...(docidFileHandle && { fileHandle: docidFileHandle }) } } }; if (docidHandle && docidHandle !== docid.handle) await touch(ctx, report, kept); else await ctx.db.patch("reports", reportId, kept); } @@ -153,7 +153,8 @@ export const noted = internalMutation({ /** * Keeps what one registrar answered. `done` moves on to the next; `refused` stops there and tells the team's inbox; * `unreached` tries again in a few minutes, a few times, then counts as refused. Answers whether the action goes on - * to the next registrar: not after anything but `done`, and not for an asking that a newer one replaced. + * to the next registrar: not after anything but `done`, and not for an asking that a newer one replaced. A `done` may + * carry a note, kept as the registration's error: a part the registrar couldn't take, which doesn't stop the rest. */ export const settle = internalMutation({ args: { reportId: v.id("reports"), rev: v.number(), provider: providerValidator, outcome: v.union(v.literal("done"), v.literal("refused"), v.literal("unreached")), error: v.optional(v.string()), zenodoRecordId: v.optional(v.string()), zenodoHost: v.optional(zenodoHostValidator), zenodoDoi: v.optional(v.string()) }, @@ -172,7 +173,7 @@ export const settle = internalMutation({ if (report.registrationRev !== rev || stateOf(report, provider) !== "queued") return false; const mark = (state: "done" | "failed") => (provider === "docid" ? { registrations: { ...report.registrations, docid: { ...report.registrations?.docid, state: state === "done" ? ("registered" as const) : ("failed" as const) } } } : { [provider === "crossref" ? "deposit" : "archive"]: state === "failed" ? "failed" : provider === "crossref" ? "deposited" : "archived" }); if (outcome === "done") { - await ctx.db.patch("reports", reportId, { ...mark("done"), registrationError: undefined, registrationTries: undefined, ...(provider === "crossref" && { depositSent: undefined }) }); + await ctx.db.patch("reports", reportId, { ...mark("done"), registrationError: error?.slice(0, ERROR_MAX), registrationTries: undefined, ...(provider === "crossref" && { depositSent: undefined }) }); return true; } const tries = (report.registrationTries ?? 0) + 1; diff --git a/convex/reports/validators.ts b/convex/reports/validators.ts index 131266f4f..f09a2b7de 100644 --- a/convex/reports/validators.ts +++ b/convex/reports/validators.ts @@ -251,6 +251,8 @@ export const docidRegistrationValidator = v.object({ retired: v.optional(v.boolean()), /** A deposit was sent: until DOCiD's record of it is kept, the next try looks for it before sending another. */ depositTried: v.optional(v.boolean()), + /** DOCiD holds the report's PDF, under this Handle: the record's own when the deposit carried it, its own when added after. Never sent again. */ + fileHandle: v.optional(v.string()), }); /** Each service's registration beyond Crossref's and Zenodo's, which keep their own fields until they move here. */ export const registrationsValidator = v.object({ docid: v.optional(docidRegistrationValidator) }); diff --git a/package-lock.json b/package-lock.json index 5f9ed0611..32068c303 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37,7 +37,7 @@ "@formatjs/intl-localematcher": "^0.8.1", "@hugeicons/core-free-icons": "^4.3.0", "@hugeicons/react": "^1.1.10", - "@opendeved/doi-sync-core": "github:OpenDevEd/doi-sync-core#7d74290dbabf6c36688f32ada3a5da0334a739ff", + "@opendeved/doi-sync-core": "github:OpenDevEd/doi-sync-core#157175801e854a28fd9e85eca5f6be4f18a4d00b", "@opendeved/paper-pdf": "github:OpenDevEd/paper-pdf#7f8313c47a28c786e71828ea9669d5f5e35611ad", "@openrouter/ai-sdk-provider": "^3.1.0", "@posthog/nextjs-config": "^1.12.1", @@ -4444,8 +4444,8 @@ }, "node_modules/@opendeved/doi-sync-core": { "version": "0.1.0", - "resolved": "git+ssh://git@github.com/OpenDevEd/doi-sync-core.git#7d74290dbabf6c36688f32ada3a5da0334a739ff", - "integrity": "sha512-vlZh/JwMTdq1v0hCxjPggeB5B4Ikj/3oBW4yQemkJ4kPqo8u9ZKACsTHSZP+dSXgq/B/mWhVQnVOEdiJdQ5Zmg==", + "resolved": "git+ssh://git@github.com/OpenDevEd/doi-sync-core.git#157175801e854a28fd9e85eca5f6be4f18a4d00b", + "integrity": "sha512-4S1nurVSNtWQVxT/giSj5sz6+WOHeIbaGrjBMSBbQQopJn01ibLf88F+gC33sMkvBRrccfYhFgkjcgTjjewI0A==", "license": "AGPL-3.0-only", "dependencies": { "bottleneck": "^2.19.5", diff --git a/package.json b/package.json index b79a30146..436aae465 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "@formatjs/intl-localematcher": "^0.8.1", "@hugeicons/core-free-icons": "^4.3.0", "@hugeicons/react": "^1.1.10", - "@opendeved/doi-sync-core": "github:OpenDevEd/doi-sync-core#7d74290dbabf6c36688f32ada3a5da0334a739ff", + "@opendeved/doi-sync-core": "github:OpenDevEd/doi-sync-core#157175801e854a28fd9e85eca5f6be4f18a4d00b", "@opendeved/paper-pdf": "github:OpenDevEd/paper-pdf#7f8313c47a28c786e71828ea9669d5f5e35611ad", "@openrouter/ai-sdk-provider": "^3.1.0", "@posthog/nextjs-config": "^1.12.1",