Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 41 additions & 20 deletions convex/reports/registrar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -230,7 +230,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.
Expand Down Expand Up @@ -259,33 +259,36 @@ 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;
const poster = job.cover ? await ctx.storage.get(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]] : [])));
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) {
Expand All @@ -295,7 +298,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) }));
Expand Down
91 changes: 91 additions & 0 deletions convex/reports/registration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -233,6 +236,94 @@ describe("registering a live report", () => {
expect(await world.t.mutation(internal.reports.registration.begin, { reportId, rev: before })).toBeNull();
});

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<Record<string, unknown>> = [];
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, {
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);
Expand Down
Loading
Loading