Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Keep thumbnails from outliving a draft or drawing for cards that left
Claudecc9fe68b468f
diff --git a/src/components/shared/document-thumbnail.tsx b/src/components/shared/document-thumbnail.tsxindex 729d6c8..e45f4e8 100644--- a/src/components/shared/document-thumbnail.tsx+++ b/src/components/shared/document-thumbnail.tsx@@ -35,12 +35,16 @@ export function DocumentThumbnail({const [drawnUrl, setDrawnUrl] = useState<string | null>(null);const imageRef = useRef<HTMLImageElement | null>(null);const isMountedRef = useRef(true);+ const releaseBackfillRef = useRef<(() => void) | null>(null);useEffect(() => {isMountedRef.current = true;return () => {isMountedRef.current = false;+ // A card that is gone must not keep its place in the drawing queue.+ releaseBackfillRef.current?.();+ releaseBackfillRef.current = null;};}, []);@@ -71,11 +75,20 @@ export function DocumentThumbnail({}, []);function handleStoredThumbnailMissing() {- if (!envelopeId || state !== "loading" || drawnUrl) {+ if (+ !envelopeId ||+ state !== "loading" ||+ drawnUrl ||+ releaseBackfillRef.current+ ) {return;}- backfillEnvelopeThumbnail(envelopeId)+ const backfill = backfillEnvelopeThumbnail(envelopeId);++ releaseBackfillRef.current = backfill.release;++ backfill.result.then((thumbnail) => {if (!isMountedRef.current) {return;diff --git a/src/lib/envelope-thumbnail.dbtest.ts b/src/lib/envelope-thumbnail.dbtest.tsnew file mode 100644index 0000000..d8c192f--- /dev/null+++ b/src/lib/envelope-thumbnail.dbtest.ts@@ -0,0 +1,193 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, before, test } from "node:test";++import type pg from "pg";++import { openTestDatabase } from "./db/test-database.ts";+import {+ deleteDraftEnvelope,+ EnvelopeDocumentAccessError,+ getEnvelopeThumbnailForUser,+ saveEnvelopeThumbnailForUser,+} from "./envelopes.ts";+import { buildEnvelopeThumbnailKey } from "./services/storage-keys.ts";+import {+ createStorageService,+ type StorageService,+} from "./services/storage.ts";++// The first-page picture and the envelope it belongs to, against a real+// Postgres: a picture must never outlive its envelope, even when the two+// are written and deleted at the same moment. Run with `npm run test:db`.++// Just the headers of a 480 x 621 JPEG, which is all the size check reads.+const THUMBNAIL = Uint8Array.from([+ 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x02, 0x6d, 0x01, 0xe0, 0x03, 0x01,+ 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xd9,+]);++let database: pg.Pool;+let storageDir: string;+let storageService: StorageService;+const userIds: string[] = [];++async function insertDraft(): Promise<{ envelopeId: string; userId: string }> {+ const userId = randomUUID();+ const envelopeId = randomUUID();++ await database.query(+ `insert into public."user" (id, name, email) values ($1, $2, $3)`,+ [userId, "Thumbnail Tester", `thumbnail+${userId}@example.com`],+ );+ await database.query(+ `+ insert into public.envelopes (+ id, user_id, title, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash+ ) values ($1, $2, $3, $4, $5, $6, $7, $8)+ `,+ [+ envelopeId,+ userId,+ "Thumbnail test",+ `users/${userId}/envelopes/${envelopeId}/original.pdf`,+ "sample.pdf",+ 1024,+ 1,+ "0".repeat(64),+ ],+ );+ userIds.push(userId);++ return { envelopeId, userId };+}++async function thumbnailExists(input: {+ envelopeId: string;+ userId: string;+}): Promise<boolean> {+ const head = await storageService.headObject(+ buildEnvelopeThumbnailKey(input),+ );++ return head.exists;+}++function assertNotFound(error: unknown): true {+ assert.ok(error instanceof EnvelopeDocumentAccessError);+ assert.equal(error.statusCode, 404);++ return true;+}++before(async () => {+ database = await openTestDatabase();+ storageDir = await mkdtemp(path.join(tmpdir(), "signudoc-thumbnail-"));+ storageService = createStorageService({+ env: { STORAGE_DRIVER: "local", STORAGE_LOCAL_DIR: storageDir },+ });+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ userIds,+ ]);+ await database.end();+ await rm(storageDir, { force: true, recursive: true });+});++test("a picture is kept for an envelope that exists", async () => {+ const draft = await insertDraft();++ await saveEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ THUMBNAIL,+ { database, storageService },+ );++ assert.equal(await thumbnailExists(draft), true);+});++test("nobody else can store a picture for the envelope", async () => {+ const draft = await insertDraft();+ const stranger = await insertDraft();++ await assert.rejects(+ saveEnvelopeThumbnailForUser(stranger.userId, draft.envelopeId, THUMBNAIL, {+ database,+ storageService,+ }),+ assertNotFound,+ );++ assert.equal(await thumbnailExists(draft), false);+ assert.equal(+ await thumbnailExists({+ envelopeId: draft.envelopeId,+ userId: stranger.userId,+ }),+ false,+ );+});++test("a picture written while its draft is being deleted does not stay behind", async () => {+ const draft = await insertDraft();+ // The upload passes its first check, and the draft is deleted, files and+ // all, before the picture reaches storage.+ const storageWithSlowWrite: StorageService = {+ ...storageService,+ deleteObject: (key) => storageService.deleteObject(key),+ getObject: (key) => storageService.getObject(key),+ getObjectStream: (key) => storageService.getObjectStream(key),+ headObject: (key) => storageService.headObject(key),+ async putObject(input) {+ await database.query("delete from public.envelopes where id = $1", [+ draft.envelopeId,+ ]);+ await storageService.deleteObject(input.key);++ return storageService.putObject(input);+ },+ };++ await assert.rejects(+ saveEnvelopeThumbnailForUser(draft.userId, draft.envelopeId, THUMBNAIL, {+ database,+ storageService: storageWithSlowWrite,+ }),+ assertNotFound,+ );++ assert.equal(await thumbnailExists(draft), false);+});++test("deleting a draft removes its picture", async () => {+ const draft = await insertDraft();++ await saveEnvelopeThumbnailForUser(+ draft.userId,+ draft.envelopeId,+ THUMBNAIL,+ { database, storageService },+ );+ assert.equal(await thumbnailExists(draft), true);++ await deleteDraftEnvelope(draft.userId, draft.envelopeId, {+ database,+ storageService,+ });++ assert.equal(await thumbnailExists(draft), false);+ await assert.rejects(+ getEnvelopeThumbnailForUser(draft.userId, draft.envelopeId, {+ database,+ storageService,+ }),+ assertNotFound,+ );+});diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 8ff723b..7dfd2af 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -62,6 +62,7 @@ import {createStorageService,StorageObjectNotFoundError,type StorageObjectStream,+ type StorageService,} from "./services/storage.ts";import {assertThumbnailImage,@@ -1284,8 +1285,10 @@ export async function saveEnvelopeThumbnailForUser(body: Uint8Array,{database = getDb(),+ storageService = createStorageService(),}: {database?: DbExecutor;+ storageService?: StorageService;} = {},): Promise<void> {assertThumbnailImage(body);@@ -1296,11 +1299,31 @@ export async function saveEnvelopeThumbnailForUser(throw new EnvelopeDocumentAccessError("Envelope not found.", 404);}- await createStorageService().putObject({+ const key = buildEnvelopeThumbnailKey({ envelopeId: envelope.id, userId });++ await storageService.putObject({body,contentType: THUMBNAIL_CONTENT_TYPE,- key: buildEnvelopeThumbnailKey({ envelopeId: envelope.id, userId }),+ key,});++ // The envelope may have been deleted while the picture was being written:+ // by its owner, by the cleanup job or with the whole account. Each of+ // those removes the row first and the files after, so a row that is still+ // here now will have this picture removed with it. A row that is gone has+ // already had its files removed, and nothing would ever come back for this+ // one.+ const envelopeAfterWrite = await getEnvelopeByIdForUser(+ userId,+ envelopeId,+ database,+ );++ if (!envelopeAfterWrite) {+ await storageService.deleteObject(key);++ throw new EnvelopeDocumentAccessError("Envelope not found.", 404);+ }}/** Streams the stored first-page picture, or says there is none (404). */@@ -1309,8 +1332,10 @@ export async function getEnvelopeThumbnailForUser(envelopeId: string,{database = getDb(),+ storageService = createStorageService(),}: {database?: DbExecutor;+ storageService?: StorageService;} = {},): Promise<StorageObjectStream> {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);@@ -1320,7 +1345,7 @@ export async function getEnvelopeThumbnailForUser(}try {- return await createStorageService().getObjectStream(+ return await storageService.getObjectStream(buildEnvelopeThumbnailKey({ envelopeId: envelope.id, userId }),);} catch (error) {@@ -2203,8 +2228,10 @@ export async function deleteDraftEnvelope(envelopeId: string,{database = getDb(),+ storageService = createStorageService(),}: {database?: DbExecutor;+ storageService?: StorageService;} = {},): Promise<EnvelopeRecord> {const envelope = await getEnvelopeByIdForUser(userId, envelopeId, database);@@ -2220,7 +2247,6 @@ export async function deleteDraftEnvelope();}- const storageService = createStorageService();const deleteResult = await database.query(`DELETE FROM envelopesdiff --git a/src/lib/pdf-thumbnail.ts b/src/lib/pdf-thumbnail.tsindex 9fe3de8..0a7458b 100644--- a/src/lib/pdf-thumbnail.ts+++ b/src/lib/pdf-thumbnail.ts@@ -1,4 +1,8 @@import { loadPdfJsModule, PDF_JS_STANDARD_FONT_DATA_URL } from "./pdfjs-client";+import {+ createSharedSerialQueue,+ type SharedQueueRequest,+} from "./shared-serial-queue.ts";// Draws the first page of a PDF as a small JPEG, in the browser. The server// never renders PDFs, so this is where a document's dashboard thumbnail@@ -94,25 +98,26 @@ export async function uploadEnvelopeThumbnail(}// A dashboard full of envelopes without thumbnails would otherwise download-// and draw every PDF at once.-let backfillQueue: Promise<unknown> = Promise.resolve();+// and draw every PDF at once. The queue draws one at a time, draws each+// envelope once however many cards ask for it, and skips an envelope whose+// cards have all gone (a changed filter, another page) before its turn.+const backfillQueue = createSharedSerialQueue(async (envelopeId: string) => {+ const thumbnail = await renderPdfThumbnail({+ url: `/api/envelopes/${encodeURIComponent(envelopeId)}/document`,+ });++ void uploadEnvelopeThumbnail(envelopeId, thumbnail);++ return thumbnail;+});/*** Makes the thumbnail for an envelope that has none, from its stored PDF,- * and saves it for next time. One document at a time.+ * and saves it for next time. Call `release` when the result is no longer+ * wanted, such as when the card that asked for it is removed.*/-export function backfillEnvelopeThumbnail(envelopeId: string): Promise<Blob> {- const result = backfillQueue.then(async () => {- const thumbnail = await renderPdfThumbnail({- url: `/api/envelopes/${encodeURIComponent(envelopeId)}/document`,- });-- void uploadEnvelopeThumbnail(envelopeId, thumbnail);-- return thumbnail;- });-- backfillQueue = result.catch(() => undefined);-- return result;+export function backfillEnvelopeThumbnail(+ envelopeId: string,+): SharedQueueRequest<Blob> {+ return backfillQueue.request(envelopeId);}diff --git a/src/lib/shared-serial-queue.test.ts b/src/lib/shared-serial-queue.test.tsnew file mode 100644index 0000000..7391a6d--- /dev/null+++ b/src/lib/shared-serial-queue.test.ts@@ -0,0 +1,169 @@+import assert from "node:assert/strict";+import { test } from "node:test";++import {+ createSharedSerialQueue,+ NobodyWaitingError,+} from "./shared-serial-queue.ts";++type Deferred = {+ promise: Promise<string>;+ reject: (error: Error) => void;+ resolve: (value: string) => void;+};++function defer(): Deferred {+ let resolve: (value: string) => void = () => undefined;+ let reject: (error: Error) => void = () => undefined;+ const promise = new Promise<string>((onResolve, onReject) => {+ resolve = onResolve;+ reject = onReject;+ });++ return { promise, reject, resolve };+}++// A queue whose jobs finish only when the test says so.+function createControlledQueue() {+ const started: string[] = [];+ const deferred = new Map<string, Deferred>();+ const queue = createSharedSerialQueue((key) => {+ const job = defer();++ started.push(key);+ deferred.set(key, job);++ return job.promise;+ });++ return {+ finish(key: string) {+ deferred.get(key)?.resolve(`${key} done`);+ },+ fail(key: string) {+ deferred.get(key)?.reject(new Error(`${key} failed`));+ },+ queue,+ started,+ };+}++function settle() {+ return new Promise((resolve) => setImmediate(resolve));+}++test("runs one job at a time, in the order they were asked for", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");+ const second = queue.request("b");++ await settle();+ assert.deepEqual(started, ["a"]);++ finish("a");+ assert.equal(await first.result, "a done");+ await settle();+ assert.deepEqual(started, ["a", "b"]);++ finish("b");+ assert.equal(await second.result, "b done");+});++test("gives everyone who asks for the same key the same job", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");+ const second = queue.request("a");++ await settle();+ finish("a");++ assert.equal(await first.result, "a done");+ assert.equal(await second.result, "a done");+ assert.deepEqual(started, ["a"]);+});++test("drops a waiting job once nobody wants it, and moves on", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");+ const unwanted = queue.request("b");+ const third = queue.request("c");++ unwanted.release();+ // Releasing twice must not count against anyone else.+ unwanted.release();++ await settle();+ finish("a");+ await first.result;++ await assert.rejects(unwanted.result, NobodyWaitingError);+ await settle();+ assert.deepEqual(started, ["a", "c"]);++ finish("c");+ assert.equal(await third.result, "c done");+});++test("keeps a waiting job while at least one caller still wants it", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");+ const gone = queue.request("b");+ const stillHere = queue.request("b");++ gone.release();++ await settle();+ finish("a");+ await first.result;+ await settle();+ assert.deepEqual(started, ["a", "b"]);++ finish("b");+ assert.equal(await stillHere.result, "b done");+});++test("finishes a job that has started even if its caller leaves", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");++ await settle();+ first.release();+ finish("a");++ assert.equal(await first.result, "a done");+ assert.deepEqual(started, ["a"]);+});++test("a job that fails does not hold up the ones behind it", async () => {+ const { fail, finish, queue } = createControlledQueue();+ const first = queue.request("a");+ const second = queue.request("b");++ await settle();+ fail("a");+ await assert.rejects(first.result, /a failed/);++ await settle();+ finish("b");+ assert.equal(await second.result, "b done");+});++test("asking again after a job has finished starts a new one", async () => {+ const { finish, queue, started } = createControlledQueue();+ const first = queue.request("a");++ await settle();+ finish("a");+ await first.result;++ const again = queue.request("a");++ // The earlier caller letting go late must not drop the new job.+ first.release();++ await settle();+ assert.deepEqual(started, ["a", "a"]);++ finish("a");+ assert.equal(await again.result, "a done");+});diff --git a/src/lib/shared-serial-queue.ts b/src/lib/shared-serial-queue.tsnew file mode 100644index 0000000..abed364--- /dev/null+++ b/src/lib/shared-serial-queue.ts@@ -0,0 +1,79 @@+// A queue for slow work that several parts of a page may ask for at once,+// such as drawing a thumbnail from a PDF. It does three things:+//+// - runs one job at a time, in the order they were first asked for;+// - gives everyone who asks for the same key the same job;+// - drops a job that has not started once nobody is waiting for it.+//+// A job that has started always finishes: its result may still be useful to+// whoever asks next.++export type SharedQueueRequest<T> = {+ /**+ * Says the caller no longer needs the result. Safe to call more than once,+ * and after the job has finished.+ */+ release: () => void;+ result: Promise<T>;+};++/** What a job that was dropped before it started rejects with. */+export class NobodyWaitingError extends Error {+ constructor(key: string) {+ super(`Nobody is waiting for "${key}" any more.`);+ this.name = "NobodyWaitingError";+ }+}++type QueuedJob<T> = {+ result: Promise<T>;+ waiting: { count: number };+};++export function createSharedSerialQueue<T>(run: (key: string) => Promise<T>) {+ const jobs = new Map<string, QueuedJob<T>>();+ let tail: Promise<unknown> = Promise.resolve();++ function enqueue(key: string): QueuedJob<T> {+ const waiting = { count: 0 };+ const result = tail+ .then(() => {+ if (waiting.count === 0) {+ throw new NobodyWaitingError(key);+ }++ return run(key);+ })+ .finally(() => {+ jobs.delete(key);+ });+ const job = { result, waiting };++ // The next job starts when this one settles, whichever way it goes.+ tail = result.catch(() => undefined);+ jobs.set(key, job);++ return job;+ }++ return {+ request(key: string): SharedQueueRequest<T> {+ const job = jobs.get(key) ?? enqueue(key);+ let released = false;++ job.waiting.count += 1;++ return {+ release() {+ if (released) {+ return;+ }++ released = true;+ job.waiting.count -= 1;+ },+ result: job.result,+ };+ },+ };+}