Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Let the file store refuse a second thumbnail, so two at once cannot swap

Claude497679a33031
diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.ts
index 3e80510..6a74f3d 100644
--- a/src/lib/envelopes.ts
+++ b/src/lib/envelopes.ts
@@ -1580,17 +1580,12 @@ export async function saveEnvelopeThumbnailForUser(
userId,
});
- // Two uploads that arrive together can both get past this check. Both are
- // drawn from the same page, so whichever is written last is as good.
- const stored = await storageService.headObject(key);
-
- if (!stored.exists) {
- await storageService.putObject({
- body,
- contentType: THUMBNAIL_CONTENT_TYPE,
- key,
- });
- }
+ await storageService.putObject({
+ body,
+ contentType: THUMBNAIL_CONTENT_TYPE,
+ keepExisting: true,
+ 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
diff --git a/src/lib/services/storage/blob.test.ts b/src/lib/services/storage/blob.test.ts
index e5f9f08..b643107 100644
--- a/src/lib/services/storage/blob.test.ts
+++ b/src/lib/services/storage/blob.test.ts
@@ -1,4 +1,7 @@
import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
import { test } from "node:test";
import { BlobNotFoundError } from "@vercel/blob";
@@ -6,6 +9,7 @@ import { BlobNotFoundError } from "@vercel/blob";
import { ServiceConfigurationError } from "../service-config.ts";
import { type BlobClient, createBlobStorageService } from "./blob.ts";
import { resolveStorageDriver, supportsDirectUploads } from "./driver.ts";
+import { createLocalStorageService } from "./local.ts";
import { StorageObjectNotFoundError } from "./types.ts";
type StoredBlob = { body: Uint8Array; contentType: string };
@@ -64,9 +68,16 @@ function createFakeBlobClient() {
async put(
pathname: string,
body: Buffer,
- options: { contentType: string },
+ options: { allowOverwrite?: boolean; contentType: string },
) {
calls.push({ args: [pathname, body, options], method: "put" });
+
+ // As Blob does: an object that is there is not written over unless
+ // the caller allows it, and the error has no class of its own.
+ if (!options.allowOverwrite && blobs.has(pathname)) {
+ throw new Error("Vercel Blob: This blob already exists.");
+ }
+
blobs.set(pathname, {
body: new Uint8Array(body),
contentType: options.contentType,
@@ -109,6 +120,122 @@ test("objects are written privately, without a random suffix, and replace what w
});
});
+test("an object that is to be kept is not written over", async () => {
+ const { blobs, calls, client } = createFakeBlobClient();
+ const storage = createBlobStorageService({ client, env: connectedEnv });
+
+ await storage.putObject({
+ body: new Uint8Array([1, 2, 3]),
+ contentType: "image/jpeg",
+ keepExisting: true,
+ key: KEY,
+ });
+
+ // The first write is told not to replace anything either: it is Blob that
+ // decides, so of two writers at once only one can be kept.
+ assert.deepEqual(calls[0]?.args[2], {
+ access: "private",
+ addRandomSuffix: false,
+ allowOverwrite: false,
+ contentType: "image/jpeg",
+ });
+
+ const reference = await storage.putObject({
+ body: new Uint8Array([4, 5, 6]),
+ contentType: "image/jpeg",
+ keepExisting: true,
+ key: KEY,
+ });
+
+ assert.equal(reference.key, KEY);
+ assert.deepEqual([...(blobs.get(KEY)?.body ?? [])], [1, 2, 3]);
+
+ // Without it, a write still replaces what is there.
+ await storage.putObject({
+ body: new Uint8Array([7, 8, 9]),
+ contentType: "image/jpeg",
+ key: KEY,
+ });
+
+ assert.deepEqual([...(blobs.get(KEY)?.body ?? [])], [7, 8, 9]);
+});
+
+test("a write that fails with nothing stored is still a failure", async () => {
+ const { client } = createFakeBlobClient();
+ const failing = {
+ ...client,
+ put: async () => {
+ throw new Error("Vercel Blob: The store is suspended.");
+ },
+ } as unknown as BlobClient;
+ const storage = createBlobStorageService({
+ client: failing,
+ env: connectedEnv,
+ });
+
+ await assert.rejects(
+ storage.putObject({
+ body: new Uint8Array([1, 2, 3]),
+ contentType: "image/jpeg",
+ keepExisting: true,
+ key: KEY,
+ }),
+ /suspended/,
+ );
+});
+
+test("the local store keeps the first object too, and keeps it whole", async () => {
+ const rootDir = await mkdtemp(path.join(tmpdir(), "signudoc-storage-"));
+
+ try {
+ const storage = createLocalStorageService({ rootDir });
+ const bodies = Array.from({ length: 12 }, (_, index) =>
+ new Uint8Array(4096).fill(index + 1),
+ );
+
+ // Twelve writers at once, each with its own bytes.
+ await Promise.all(
+ bodies.map((body) =>
+ storage.putObject({
+ body,
+ contentType: "image/jpeg",
+ keepExisting: true,
+ key: KEY,
+ }),
+ ),
+ );
+
+ const kept = (await storage.getObject(KEY)).body;
+
+ // One of them was kept, all of it.
+ assert.equal(kept.byteLength, 4096);
+ assert.ok(kept.every((byte) => byte === kept[0]));
+
+ await storage.putObject({
+ body: new Uint8Array(4096).fill(99),
+ contentType: "image/jpeg",
+ keepExisting: true,
+ key: KEY,
+ });
+
+ assert.deepEqual(
+ [...(await storage.getObject(KEY)).body],
+ [...kept],
+ "a later writer does not replace it",
+ );
+ assert.equal((await storage.getObject(KEY)).contentType, "image/jpeg");
+
+ // No temporary files are left beside it.
+ const leftovers = (
+ await readdir(path.dirname(path.join(rootDir, KEY)))
+ ).filter((name) => name.endsWith(".tmp"));
+
+ assert.deepEqual(leftovers, []);
+ } finally {
+ await rm(rootDir, { force: true, recursive: true });
+ }
+});
+
test("objects are read back whole or as a stream, bypassing the cache", async () => {
const { calls, client } = createFakeBlobClient();
const storage = createBlobStorageService({ client, env: connectedEnv });
diff --git a/src/lib/services/storage/blob.ts b/src/lib/services/storage/blob.ts
index f1436da..054f3f3 100644
--- a/src/lib/services/storage/blob.ts
+++ b/src/lib/services/storage/blob.ts
@@ -5,6 +5,7 @@ import { ServiceConfigurationError } from "../service-config.ts";
import { hasBlobCredentials } from "./driver.ts";
import {
normalizeStorageKey,
+ type StorageObjectHead,
StorageObjectNotFoundError,
type StorageService,
} from "./types.ts";
@@ -56,6 +57,33 @@ export function createBlobStorageService({
return { normalizedKey, result };
}
+ async function headObject(key: string): Promise<StorageObjectHead> {
+ const normalizedKey = normalizeStorageKey(key);
+
+ try {
+ const metadata = await client.head(normalizedKey);
+
+ return {
+ bucketName: BLOB_BUCKET_NAME,
+ contentLength: metadata.size,
+ contentType: metadata.contentType,
+ etag: metadata.etag,
+ exists: true,
+ key: normalizedKey,
+ };
+ } catch (error) {
+ if (error instanceof BlobNotFoundError) {
+ return {
+ bucketName: BLOB_BUCKET_NAME,
+ exists: false,
+ key: normalizedKey,
+ };
+ }
+
+ throw error;
+ }
+ }
+
return {
async deleteObject(key) {
await client.del(normalizeStorageKey(key));
@@ -86,51 +114,37 @@ export function createBlobStorageService({
stream: result.stream,
};
},
- async headObject(key) {
- const normalizedKey = normalizeStorageKey(key);
+ headObject,
+ async putObject(input) {
+ const normalizedKey = normalizeStorageKey(input.key);
try {
- const metadata = await client.head(normalizedKey);
-
- return {
- bucketName: BLOB_BUCKET_NAME,
- contentLength: metadata.size,
- contentType: metadata.contentType,
- etag: metadata.etag,
- exists: true,
- key: normalizedKey,
- };
+ await client.put(
+ normalizedKey,
+ Buffer.from(
+ input.body.buffer,
+ input.body.byteOffset,
+ input.body.byteLength,
+ ),
+ {
+ access: BLOB_ACCESS,
+ // Keys are complete and deterministic: the same key must always
+ // name the same object. Writing it again replaces it, unless the
+ // caller asked for what is there to be kept, and then Blob
+ // itself refuses the write.
+ addRandomSuffix: false,
+ allowOverwrite: !input.keepExisting,
+ contentType: input.contentType,
+ },
+ );
} catch (error) {
- if (error instanceof BlobNotFoundError) {
- return {
- bucketName: BLOB_BUCKET_NAME,
- exists: false,
- key: normalizedKey,
- };
+ // The SDK has no error of its own for "something is already stored
+ // here", so ask. An object that is there is what was asked for; a
+ // write that failed for any other reason is still a failure.
+ if (!input.keepExisting || !(await headObject(normalizedKey)).exists) {
+ throw error;
}
-
- throw error;
}
- },
- async putObject(input) {
- const normalizedKey = normalizeStorageKey(input.key);
-
- await client.put(
- normalizedKey,
- Buffer.from(
- input.body.buffer,
- input.body.byteOffset,
- input.body.byteLength,
- ),
- {
- access: BLOB_ACCESS,
- // Keys are complete and deterministic: the same key must always
- // name the same object, and writing it again replaces it.
- addRandomSuffix: false,
- allowOverwrite: true,
- contentType: input.contentType,
- },
- );
return {
bucketName: BLOB_BUCKET_NAME,
diff --git a/src/lib/services/storage/local.ts b/src/lib/services/storage/local.ts
index 587a324..1ef8182 100644
--- a/src/lib/services/storage/local.ts
+++ b/src/lib/services/storage/local.ts
@@ -1,6 +1,14 @@
import { randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
-import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
+import {
+ link,
+ mkdir,
+ readFile,
+ rename,
+ rm,
+ stat,
+ writeFile,
+} from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream";
@@ -54,6 +62,24 @@ async function writeFileAtomically(
}
}
+// Writes the file only if there is none. A hard link cannot replace a file
+// that is there, and the file it makes is whole from its first moment, so of
+// two writers that arrive together exactly one is kept.
+async function writeFileIfAbsent(filePath: string, data: Uint8Array | string) {
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
+
+ try {
+ await writeFile(temporaryPath, data);
+ await link(temporaryPath, filePath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
+ throw error;
+ }
+ } finally {
+ await rm(temporaryPath, { force: true });
+ }
+}
+
export function createLocalStorageService({
env = process.env,
rootDir,
@@ -186,16 +212,20 @@ export function createLocalStorageService({
async putObject(input) {
const { normalizedKey, objectPath } = resolveObjectPath(input.key);
+ const write = input.keepExisting
+ ? writeFileIfAbsent
+ : writeFileAtomically;
+
await mkdir(path.dirname(objectPath), { recursive: true });
// Metadata first: once the object itself is visible, its content type
// is already there to be read.
- await writeFileAtomically(
+ await write(
`${objectPath}${METADATA_SUFFIX}`,
JSON.stringify({
contentType: input.contentType,
} satisfies LocalObjectMetadata),
);
- await writeFileAtomically(objectPath, input.body);
+ await write(objectPath, input.body);
return {
bucketName: LOCAL_BUCKET_NAME,
diff --git a/src/lib/services/storage/types.ts b/src/lib/services/storage/types.ts
index 2945794..0b8be9a 100644
--- a/src/lib/services/storage/types.ts
+++ b/src/lib/services/storage/types.ts
@@ -41,6 +41,13 @@ export interface StorageService {
body: Uint8Array;
contentType: string;
key: string;
+ /**
+ * Leave an object that is already stored under this key as it is. The
+ * store itself refuses the second write, so of two writers that arrive
+ * together exactly one is kept. Without this, a write replaces what is
+ * there.
+ */
+ keepExisting?: boolean;
}): Promise<StorageObjectRef>;
}