AI-native design editor. Open-source Figma alternative.
feat(cloud): store images once per workspace and keep revisions without them (#1345)
Danila Poyarkov530b057cb3c3
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex f1b10a238..5dcfafce5 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -12,6 +12,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- Database rows use `crypto.randomUUID()`; secrets that leave the server use `randomHex` from `@open-pencil/scene-graph/random`, are stored as SHA-256 digests (a single-use OAuth continuation keeps a JWE copy), and travel in URL fragments (`src/server/sharing/capabilities/service.ts`).- Every HTTP body goes through `validatedJSON` with a contract schema, and every response the client reads is parsed with Valibot (`src/server/validation.ts`, `src/client/api.ts`).+- A revision's images live in `revision_image`; code that makes a revision from another copies them with `copyRevisionImages`, and a storage object a `workspace_image` holds is never unreferenced (`src/server/documents/images.ts`, `tests/integration/server/documents/images.test.ts`).- Add schema changes as a new numbered migration in `src/server/db/migrations/` registered in `src/server/db/migrate.ts`; never edit a migration that has shipped. Better Auth's tables have their own versioned migration (`016_auth_schema.ts`).- Raw SQL lives only in migrations and the reviewed helpers in `src/server/db/expressions.ts`; everything else uses typed Kysely queries (`open-pencil/no-cloud-raw-sql`).- Cloud code keeps secrets out of query strings and logs, and the server never builds an HTML response from values (`open-pencil/no-cloud-secret-in-query`, `open-pencil/no-cloud-secret-logging`, `open-pencil/no-cloud-dynamic-html`).diff --git a/packages/cloud/src/client/api.ts b/packages/cloud/src/client/api.tsindex 61616dfc3..33b9e7899 100644--- a/packages/cloud/src/client/api.ts+++ b/packages/cloud/src/client/api.ts@@ -7,6 +7,8 @@ import {createInvitationContinuationSchema,documentAccessSchema,documentDownloadSchema,+ imageUploadOfferSchema,+ objectUploadSchema,documentGrantSchema,documentInvitationSchema,documentShareSchema,@@ -25,7 +27,9 @@ import {type CollaborationTicket,type CreateInvitationContinuationInput,type InvitationContinuation,- type CommitUploadInput,+ type CommitImageUploadsInput,+ type CommitUploadRequest,+ type RequestImageUploadsInput,type CreateDocumentInput,type CreateDocumentInvitationInput,type CreateDocumentShareInput,@@ -36,6 +40,7 @@ import {type DocumentInvitation,type DocumentShare,type DocumentSummary,+ type ImageUploadOffer,type DocumentVersion,type DocumentVersionDownload,type DocumentVersions,@@ -90,30 +95,9 @@ const sharedDocumentResponseSchema = v.object({const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) })const uploadResponseSchema = v.object({id: v.pipe(v.string(), v.uuid()),- upload: v.variant('kind', [- v.object({- kind: v.literal('single'),- url: v.pipe(v.string(), v.url()),- method: v.literal('PUT'),- headers: v.record(v.string(), v.string()),- expiresAt: v.string()- }),- v.object({- kind: v.literal('multipart'),- uploadId: v.string(),- partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),- parts: v.array(- v.object({- partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),- url: v.pipe(v.string(), v.url()),- method: v.literal('PUT'),- headers: v.record(v.string(), v.string())- })- ),- expiresAt: v.string()- })- ])+ upload: objectUploadSchema})+const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) })export type CloudRequestOptions = {fetch?: CloudFetch@@ -444,11 +428,37 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptiooptions.onDiagnostic)},- async commitUpload(uploadId: string, input: CommitUploadInput): Promise<DocumentSummary> {+ /** Commits the image uploads a save asked for, once their bytes are in place. */+ async commitImageUploads(+ documentId: string,+ uploads: CommitImageUploadsInput['uploads']+ ): Promise<void> {+ const response = await client.documents[':documentId'].images.commit.$post({+ param: { documentId },+ json: { uploads }+ })+ await responseBody(response, options.onDiagnostic)+ },+ /** Uploads for the images a save will name that the document's workspace lacks. */+ async requestImageUploads(+ documentId: string,+ input: RequestImageUploadsInput+ ): Promise<ImageUploadOffer[]> {+ const response = await parseResponse(+ client.documents[':documentId'].images.$post({+ param: { documentId },+ json: input+ }),+ imageUploadsResponseSchema,+ options.onDiagnostic+ )+ return response.uploads+ },+ async commitUpload(uploadId: string, input: CommitUploadRequest): Promise<DocumentSummary> {const response = await parseResponse(client.uploads[':uploadId'].commit.$post({param: { uploadId },- json: input+ json: { ...input, images: input.images ?? [] }}),documentResponseSchema,options.onDiagnosticdiff --git a/packages/cloud/src/contract/documents.ts b/packages/cloud/src/contract/documents.tsindex 719619831..4a02fe8dd 100644--- a/packages/cloud/src/contract/documents.ts+++ b/packages/cloud/src/contract/documents.ts@@ -4,6 +4,32 @@ export const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1024 * 1024 * 1024const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/))+/** The most images one revision, or one request for image uploads, may name. */+export const CLOUD_MAX_DOCUMENT_IMAGES = 10_000++/**+ * An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it+ * by, or an older plain name. A client leaves images under other names inside the file.+ */+export const CLOUD_IMAGE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/+const imageNameSchema = v.pipe(v.string(), v.regex(CLOUD_IMAGE_NAME_PATTERN))++const objectDownloadSchema = v.object({+ url: v.pipe(v.string(), v.url()),+ method: v.literal('GET'),+ headers: v.record(v.string(), v.string()),+ expiresAt: v.string()+})++/** An image a stored revision uses, where to download it, and what to check it against. */+export const documentImageDownloadSchema = v.object({+ name: imageNameSchema,+ checksum: checksumSchema,+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),+ download: objectDownloadSchema+})+export type DocumentImageDownload = v.InferOutput<typeof documentImageDownloadSchema>+export const documentPermissionSchema = v.picklist(['view', 'edit'])export type DocumentPermission = v.InferOutput<typeof documentPermissionSchema>@@ -44,12 +70,9 @@ export const documentDownloadSchema = v.object({byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),checksum: checksumSchema,contentType: v.string(),- download: v.object({- url: v.pipe(v.string(), v.url()),- method: v.literal('GET'),- headers: v.record(v.string(), v.string()),- expiresAt: v.string()- })+ download: objectDownloadSchema,+ /** The images the stored file leaves out, which a client puts back under their names. */+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))})export type DocumentDownload = v.InferOutput<typeof documentDownloadSchema>@@ -89,6 +112,57 @@ export const createUploadSchema = v.object({})export type CreateUploadInput = v.InferOutput<typeof createUploadSchema>+const imageSizeSchema = v.pipe(+ v.number(),+ v.integer(),+ v.minValue(1),+ v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)+)++/** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */+export const objectUploadSchema = v.variant('kind', [+ v.object({+ kind: v.literal('single'),+ url: v.pipe(v.string(), v.url()),+ method: v.literal('PUT'),+ headers: v.record(v.string(), v.string()),+ expiresAt: v.string()+ }),+ v.object({+ kind: v.literal('multipart'),+ uploadId: v.string(),+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),+ parts: v.array(+ v.object({+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),+ url: v.pipe(v.string(), v.url()),+ method: v.literal('PUT'),+ headers: v.record(v.string(), v.string())+ })+ ),+ expiresAt: v.string()+ })+])+export type ObjectUploadTarget = v.InferOutput<typeof objectUploadSchema>++/** An upload the server offers for an image the workspace lacks. */+export const imageUploadOfferSchema = v.object({+ checksum: checksumSchema,+ uploadId: v.pipe(v.string(), v.uuid()),+ upload: objectUploadSchema+})+export type ImageUploadOffer = v.InferOutput<typeof imageUploadOfferSchema>++/** The images a save will refer to; the server answers with uploads for those it lacks. */+export const requestImageUploadsSchema = v.object({+ images: v.pipe(+ v.array(v.object({ checksum: checksumSchema, byteSize: imageSizeSchema })),+ v.minLength(1),+ v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)+ )+})+export type RequestImageUploadsInput = v.InferOutput<typeof requestImageUploadsSchema>+export const completedUploadPartSchema = v.object({partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(10_000)),etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))@@ -101,10 +175,36 @@ export const commitUploadSchema = v.object({uploadId: v.pipe(v.string(), v.minLength(1)),parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(10_000))})+ ),+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */+ images: v.optional(+ v.pipe(+ v.array(v.object({ name: imageNameSchema, checksum: checksumSchema })),+ v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)+ ),+ [])})export type CommitUploadInput = v.InferOutput<typeof commitUploadSchema>+/** The image uploads a save asked for, committed together once their bytes are in place. */+export const commitImageUploadsSchema = v.object({+ uploads: v.pipe(+ v.array(+ v.object({+ uploadId: v.pipe(v.string(), v.uuid()),+ checksum: checksumSchema,+ multipart: commitUploadSchema.entries.multipart+ })+ ),+ v.minLength(1),+ v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)+ )+})+export type CommitImageUploadsInput = v.InferOutput<typeof commitImageUploadsSchema>+/** A commit as a client sends it, which may leave out the images a whole file holds itself. */+export type CommitUploadRequest = v.InferInput<typeof commitUploadSchema>+export function parseCreateDocument(input: unknown): CreateDocumentInput {return v.parse(createDocumentSchema, input)}@@ -113,6 +213,14 @@ export function parseCreateUpload(input: unknown): CreateUploadInput {return v.parse(createUploadSchema, input)}+export function parseRequestImageUploads(input: unknown): RequestImageUploadsInput {+ return v.parse(requestImageUploadsSchema, input)+}++export function parseCommitImageUploads(input: unknown): CommitImageUploadsInput {+ return v.parse(commitImageUploadsSchema, input)+}+export function parseCommitUpload(input: unknown): CommitUploadInput {return v.parse(commitUploadSchema, input)}diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.tsindex 3435df0e0..d071d2fbf 100644--- a/packages/cloud/src/contract/index.ts+++ b/packages/cloud/src/contract/index.ts@@ -58,33 +58,48 @@ export {type CloudListing} from './discovery'export {+ CLOUD_IMAGE_NAME_PATTERN,+ CLOUD_MAX_DOCUMENT_IMAGES,CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,cloudActorSchema,cloudSessionSchema,+ commitImageUploadsSchema,commitUploadSchema,createDocumentSchema,createUploadSchema,documentAccessSchema,documentAccessSourceSchema,documentDownloadSchema,+ documentImageDownloadSchema,documentPermissionSchema,+ imageUploadOfferSchema,+ objectUploadSchema,documentSummarySchema,sharedDocumentSchema,type SharedDocument,workspaceUsageSchema,+ parseCommitImageUploads,parseCommitUpload,parseCreateDocument,parseCreateUpload,+ parseRequestImageUploads,+ requestImageUploadsSchema,type CloudActorContract,type CloudSession,+ type CommitImageUploadsInput,type CommitUploadInput,+ type CommitUploadRequest,type CreateDocumentInput,type CreateUploadInput,type DocumentAccess,type DocumentAccessSource,type DocumentDownload,+ type DocumentImageDownload,type DocumentPermission,type DocumentSummary,+ type ImageUploadOffer,+ type ObjectUploadTarget,+ type RequestImageUploadsInput,type WorkspaceUsage} from './documents'export {diff --git a/packages/cloud/src/server/ai/service.ts b/packages/cloud/src/server/ai/service.tsindex 56224d0ed..703810956 100644--- a/packages/cloud/src/server/ai/service.ts+++ b/packages/cloud/src/server/ai/service.ts@@ -1,8 +1,8 @@import { CLOUD_AI_TOKEN_AUDIENCE, type AIToken } from '#cloud/contract'import type { CloudActor } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'+import { DocumentNotFoundError } from '#cloud/server/documents/errors'import { workspaceRole } from '#cloud/server/documents/repository'-import { DocumentNotFoundError } from '#cloud/server/documents/service'import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'import type { CloudPolicy } from '#cloud/server/policy/policy'import { SignJWT } from 'jose'diff --git a/packages/cloud/src/server/cleanup/objects.ts b/packages/cloud/src/server/cleanup/objects.tsindex c87edbb3f..de1867196 100644--- a/packages/cloud/src/server/cleanup/objects.ts+++ b/packages/cloud/src/server/cleanup/objects.ts@@ -1,14 +1,27 @@import type { CloudDatabase } from '#cloud/server/db'import type { ExpressionBuilder } from 'kysely'-/** No revision refers to the stored file any more, so it can leave the object store. */+/**+ * No revision refers to the stored file any more, and no workspace keeps it as an image, so it+ * can leave the object store.+ */export function unreferencedObject(expression: ExpressionBuilder<CloudDatabase, 'storageObject'>) {- return expression.not(- expression.exists(- expression- .selectFrom('documentRevision')- .select('documentRevision.id')- .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')+ return expression.and([+ expression.not(+ expression.exists(+ expression+ .selectFrom('documentRevision')+ .select('documentRevision.id')+ .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')+ )+ ),+ expression.not(+ expression.exists(+ expression+ .selectFrom('workspaceImage')+ .select('workspaceImage.checksum')+ .whereRef('workspaceImage.storageObjectId', '=', 'storageObject.id')+ ))- )+ ])}diff --git a/packages/cloud/src/server/cleanup/revisions.ts b/packages/cloud/src/server/cleanup/revisions.tsindex b7f8c3700..c25537c79 100644--- a/packages/cloud/src/server/cleanup/revisions.ts+++ b/packages/cloud/src/server/cleanup/revisions.ts@@ -1,4 +1,5 @@import type { CloudDatabase } from '#cloud/server/db'+import { IMAGE_RELEASE_GRACE_MS, releaseUnusedImages } from '#cloud/server/documents/images'import { historyStart, LIMITED_HISTORY_DAYS } from '#cloud/server/documents/versions/history'import type { ObjectStore } from '#cloud/server/objects'import type { CloudPolicyContext } from '#cloud/server/policy/keys'@@ -20,6 +21,8 @@ export type RevisionCompactionOptions = {export type RevisionCompactionResult = {versionsPruned: number+ /** Images no revision used any more, released after their grace period. */+ imagesReleased: numberrevisionsDeleted: numberobjectsDeleted: numberbytesReclaimed: number@@ -184,6 +187,7 @@ export function createRevisionCompactionService(const before = new Date(now.getTime() - input.graceMs)const result: RevisionCompactionResult = {versionsPruned: await pruneVersions(now, input.batchSize),+ imagesReleased: 0,revisionsDeleted: 0,objectsDeleted: 0,bytesReclaimed: 0,@@ -208,6 +212,19 @@ export function createRevisionCompactionService(result.failed++}}+ // Compaction just freed the images of the saves it deleted; the release lets their grace pass.+ // A release that raced a save referring to an image fails whole and is tried next time.+ try {+ const images = await releaseUnusedImages(+ database,+ new Date(now.getTime() - IMAGE_RELEASE_GRACE_MS),+ input.batchSize+ )+ result.imagesReleased = images.released+ result.bytesReclaimed += images.bytes+ } catch {+ result.failed+++ }await sweepObjects(input.batchSize, result)return result}diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.tsindex 97695f59c..d00de09d5 100644--- a/packages/cloud/src/server/db/migrate.ts+++ b/packages/cloud/src/server/db/migrate.ts@@ -23,6 +23,7 @@ import * as betterAuthAccountIssuer from './migrations/019_better_auth_account_iimport * as workspaceInvitations from './migrations/020_workspace_invitations'import * as documentVersions from './migrations/021_document_versions'import * as entitlementExternalVersion from './migrations/022_entitlement_external_version'+import * as documentImages from './migrations/023_document_images'import type { CloudDatabase } from './schema'const migrations: Record<string, Migration> = {@@ -47,7 +48,8 @@ const migrations: Record<string, Migration> = {'019_better_auth_account_issuer': betterAuthAccountIssuer,'020_workspace_invitations': workspaceInvitations,'021_document_versions': documentVersions,- '022_entitlement_external_version': entitlementExternalVersion+ '022_entitlement_external_version': entitlementExternalVersion,+ '023_document_images': documentImages}class CloudMigrationProvider implements MigrationProvider {diff --git a/packages/cloud/src/server/db/migrations/023_document_images.ts b/packages/cloud/src/server/db/migrations/023_document_images.tsnew file mode 100644index 000000000..f5016050a--- /dev/null+++ b/packages/cloud/src/server/db/migrations/023_document_images.ts@@ -0,0 +1,61 @@+import type { Kysely } from 'kysely'++import { addCheckConstraint, addCurrentTimestampColumns } from './helpers'++/**+ * Images live once per workspace, keyed by the SHA-256 the object store verifies, each a stored+ * object of its own, and a stored revision holds the document without them: each revision lists+ * the images it uses under the names its file gives them. An image upload is an upload of its own+ * kind, so reservations, commits, and expired-upload cleanup cover it.+ */+export async function up(database: Kysely<unknown>): Promise<void> {+ await database.schema+ .alterTable('upload')+ .addColumn('kind', 'text', (column) => column.notNull().defaultTo('revision'))+ .execute()+ await addCheckConstraint(database, 'upload', 'upload_kind_check', 'kind', ['revision', 'image'])++ await database.schema+ .createTable('workspace_image')+ .addColumn('workspace_id', 'uuid', (column) =>+ column.references('workspace.id').onDelete('cascade').notNull()+ )+ .addColumn('checksum', 'text', (column) => column.notNull())+ .addColumn('storage_object_id', 'uuid', (column) =>+ column.references('storage_object.id').notNull().unique()+ )+ .addPrimaryKeyConstraint('workspace_image_pkey', ['workspace_id', 'checksum'])+ .execute()+ await addCurrentTimestampColumns(database, 'workspace_image', ['touched_at'])++ await database.schema+ .createTable('revision_image')+ .addColumn('revision_id', 'uuid', (column) =>+ column.references('document_revision.id').onDelete('cascade').notNull()+ )+ .addColumn('name', 'text', (column) => column.notNull())+ .addColumn('workspace_id', 'uuid', (column) => column.notNull())+ .addColumn('checksum', 'text', (column) => column.notNull())+ .addPrimaryKeyConstraint('revision_image_pkey', ['revision_id', 'name'])+ // No cascade: an image is released only once no revision uses it, and a release that raced a+ // save fails rather than taking the revision's images with it.+ .addForeignKeyConstraint(+ 'revision_image_image_fkey',+ ['workspace_id', 'checksum'],+ 'workspace_image',+ ['workspace_id', 'checksum']+ )+ .execute()+ await database.schema+ .createIndex('revision_image_image_index')+ .on('revision_image')+ .columns(['workspace_id', 'checksum'])+ .execute()+}++export async function down(database: Kysely<unknown>): Promise<void> {+ await database.schema.dropTable('revision_image').execute()+ await database.schema.dropTable('workspace_image').execute()+ await database.schema.alterTable('upload').dropConstraint('upload_kind_check').execute()+ await database.schema.alterTable('upload').dropColumn('kind').execute()+}diff --git a/packages/cloud/src/server/db/schema.ts b/packages/cloud/src/server/db/schema.tsindex d1adb4e9a..bb2226ccb 100644--- a/packages/cloud/src/server/db/schema.ts+++ b/packages/cloud/src/server/db/schema.ts@@ -108,6 +108,24 @@ export interface DocumentRevisionTable {createdAt: TimestampColumn}+/** An image a workspace's documents use, stored once; see migration 023. */+export interface WorkspaceImageTable {+ workspaceId: string+ /** The SHA-256 of the bytes, which the object store verified. */+ checksum: string+ storageObjectId: string+ /** When a save last asked for it; an image no revision uses is released a while after. */+ touchedAt: TimestampColumn+}++/** An image a stored revision uses, under the name its file gives it. */+export interface RevisionImageTable {+ revisionId: string+ name: string+ workspaceId: string+ checksum: string+}+/** A revision kept in the document's history; see migration 021. */export interface DocumentVersionTable {id: string@@ -121,9 +139,13 @@ export interface DocumentVersionTable {createdAt: TimestampColumn}+export type UploadKind = 'revision' | 'image'+export interface UploadTable {id: string+ /** An image upload names the document it was asked for, which decides who may make it. */documentId: string+ kind: Generated<UploadKind>baseRevisionId: string | nullobjectKey: stringchecksum: string@@ -307,6 +329,8 @@ export interface CloudDatabase {document: DocumentTablestorageObject: StorageObjectTabledocumentRevision: DocumentRevisionTable+ revisionImage: RevisionImageTable+ workspaceImage: WorkspaceImageTabledocumentVersion: DocumentVersionTabledocumentShare: DocumentShareTabledocumentGrant: DocumentGrantTablediff --git a/packages/cloud/src/server/documents/errors.ts b/packages/cloud/src/server/documents/errors.tsnew file mode 100644index 000000000..9f443dd27--- /dev/null+++ b/packages/cloud/src/server/documents/errors.ts@@ -0,0 +1,16 @@+/** The document does not exist, or the person may not know it does. */+export class DocumentNotFoundError extends Error {+ override readonly name = 'DocumentNotFoundError'+}+/** The person may see the document but not do this to it. */+export class DocumentForbiddenError extends Error {+ override readonly name = 'DocumentForbiddenError'+}+/** A save named a base revision the document has moved on from. */+export class DocumentConflictError extends Error {+ override readonly name = 'DocumentConflictError'+}+/** An upload is not the file it declared, or no longer one that can land. */+export class UploadInvalidError extends Error {+ override readonly name = 'UploadInvalidError'+}diff --git a/packages/cloud/src/server/documents/images.ts b/packages/cloud/src/server/documents/images.tsnew file mode 100644index 000000000..c6a90eb4c--- /dev/null+++ b/packages/cloud/src/server/documents/images.ts@@ -0,0 +1,312 @@+import type {+ CommitUploadInput,+ DocumentImageDownload,+ ImageUploadOffer,+ RequestImageUploadsInput+} from '#cloud/contract'+import type { CloudDatabase } from '#cloud/server/db'+import type { ObjectStore } from '#cloud/server/objects'+import type { StorageQuotaService } from '#cloud/server/quota'+import { uniq, uniqBy } from 'es-toolkit'+import type { Kysely, Transaction } from 'kysely'++/** Images are stored as the bytes their file holds, whatever format those are. */+export const IMAGE_CONTENT_TYPE = 'application/octet-stream'++type Executor = Kysely<CloudDatabase> | Transaction<CloudDatabase>++/** An image no revision has used for this long may be released; a save uploads first. */+export const IMAGE_RELEASE_GRACE_MS = 24 * 60 * 60_000++/**+ * The images a workspace's documents use, each stored once under the SHA-256 the object store+ * verified, and which of them each stored revision uses under the names its file gives them.+ */+export function createDocumentImages(+ database: Kysely<CloudDatabase>,+ objects: ObjectStore,+ quota: StorageQuotaService+) {+ return {+ /**+ * Uploads for the images of `input` the workspace lacks, each with its own object key and+ * reservation, so an abandoned one is cleaned up like any other upload. Images it holds+ * already need nothing.+ */+ async requestUploads(input: {+ userId: string+ documentId: string+ workspaceId: string+ images: RequestImageUploadsInput['images']+ expiresAt: Date+ maximumBytes: number | null+ }): Promise<ImageUploadOffer[]> {+ const requested = uniqBy(input.images, (image) => image.checksum)+ // Held images are renewed, so none is released before the save that asked commits.+ const held = new Set(+ (+ await database+ .updateTable('workspaceImage')+ .set({ touchedAt: new Date() })+ .where('workspaceId', '=', input.workspaceId)+ .where(+ 'checksum',+ 'in',+ requested.map((image) => image.checksum)+ )+ .returning('checksum')+ .execute()+ ).map((row) => row.checksum)+ )+ const missing = requested+ .filter((image) => !held.has(image.checksum))+ .map((image) => {+ const uploadId = crypto.randomUUID()+ return {+ ...image,+ uploadId,+ objectKey: `documents/${input.workspaceId}/images/${uploadId}`+ }+ })+ if (missing.length === 0) return []+ await database.transaction().execute(async (transaction) => {+ for (const image of missing) {+ await transaction+ .insertInto('upload')+ .values({+ id: image.uploadId,+ kind: 'image',+ documentId: input.documentId,+ baseRevisionId: null,+ objectKey: image.objectKey,+ checksum: image.checksum,+ byteSize: image.byteSize,+ contentType: IMAGE_CONTENT_TYPE,+ multipartUploadId: null,+ status: 'pending',+ finalizationStartedAt: null,+ createdBy: input.userId,+ expiresAt: input.expiresAt+ })+ .execute()+ await quota.reserveInTransaction(transaction, {+ workspaceId: input.workspaceId,+ uploadId: image.uploadId,+ bytes: image.byteSize,+ expiresAt: input.expiresAt,+ maximumBytes: input.maximumBytes+ })+ }+ })+ const offers: ImageUploadOffer[] = []+ for (const image of missing) {+ const upload = await objects.createUpload({+ key: image.objectKey,+ byteSize: image.byteSize,+ checksum: image.checksum,+ contentType: IMAGE_CONTENT_TYPE,+ expiresAt: input.expiresAt+ })+ if (upload.kind === 'multipart') {+ await database+ .updateTable('upload')+ .set({ multipartUploadId: upload.uploadId })+ .where('id', '=', image.uploadId)+ .execute()+ }+ offers.push({ checksum: image.checksum, uploadId: image.uploadId, upload })+ }+ return offers+ },++ /**+ * Stores a verified image upload as the workspace's copy of that image. When another upload of+ * the same bytes got there first, this one's file is left unreferenced for cleanup to delete+ * and its reservation is released rather than counted twice.+ */+ async landInTransaction(+ transaction: Transaction<CloudDatabase>,+ input: {+ uploadId: string+ workspaceId: string+ objectKey: string+ stored: { checksum: string; byteSize: number; contentType: string }+ }+ ): Promise<void> {+ const storageObjectId = crypto.randomUUID()+ await transaction+ .insertInto('storageObject')+ .values({+ id: storageObjectId,+ objectKey: input.objectKey,+ checksum: input.stored.checksum,+ byteSize: input.stored.byteSize,+ contentType: input.stored.contentType+ })+ .execute()+ const landed = await transaction+ .insertInto('workspaceImage')+ .values({+ workspaceId: input.workspaceId,+ checksum: input.stored.checksum,+ storageObjectId+ })+ .onConflict((conflict) => conflict.columns(['workspaceId', 'checksum']).doNothing())+ .returning('checksum')+ .executeTakeFirst()+ await transaction+ .updateTable('upload')+ .set({ status: 'committed', finalizationStartedAt: null })+ .where('id', '=', input.uploadId)+ .execute()+ if (landed) await quota.commitInTransaction(transaction, input.uploadId)+ else await quota.releaseInTransaction(transaction, input.uploadId)+ },++ /**+ * Records the images a new revision uses. Each must be the workspace's already; holding them+ * until the revision refers to them keeps a release of an unused image from racing the save.+ * Whether every image was there.+ */+ async attachInTransaction(+ transaction: Transaction<CloudDatabase>,+ input: { workspaceId: string; revisionId: string; images: CommitUploadInput['images'] }+ ): Promise<boolean> {+ const images = uniqBy(input.images, (image) => image.name)+ if (images.length === 0) return true+ const checksums = uniq(images.map((image) => image.checksum))+ const held = await transaction+ .selectFrom('workspaceImage')+ .select('checksum')+ .where('workspaceId', '=', input.workspaceId)+ .where('checksum', 'in', checksums)+ .forShare()+ .execute()+ if (held.length !== checksums.length) return false+ await transaction+ .insertInto('revisionImage')+ .values(+ images.map((image) => ({+ revisionId: input.revisionId,+ name: image.name,+ workspaceId: input.workspaceId,+ checksum: image.checksum+ }))+ )+ .execute()+ return true+ }+ }+}++export type DocumentImages = ReturnType<typeof createDocumentImages>++/** Gives a revision made from another, by a restore or a duplicate, the same images. */+export async function copyRevisionImages(+ transaction: Transaction<CloudDatabase>,+ fromRevisionId: string,+ toRevisionId: string+): Promise<void> {+ await transaction+ .insertInto('revisionImage')+ .columns(['revisionId', 'name', 'workspaceId', 'checksum'])+ .expression((expression) =>+ expression+ .selectFrom('revisionImage')+ .select((select) => [+ select.val(toRevisionId).as('revisionId'),+ 'name',+ 'workspaceId',+ 'checksum'+ ])+ .where('revisionId', '=', fromRevisionId)+ )+ .execute()+}++/** Where to download each image a revision uses, under its name in the file. */+export async function revisionImageDownloads(+ executor: Executor,+ objects: ObjectStore,+ revisionId: string,+ expiresAt: Date+): Promise<DocumentImageDownload[]> {+ const rows = await executor+ .selectFrom('revisionImage')+ .innerJoin('workspaceImage', (join) =>+ join+ .onRef('workspaceImage.workspaceId', '=', 'revisionImage.workspaceId')+ .onRef('workspaceImage.checksum', '=', 'revisionImage.checksum')+ )+ .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')+ .select([+ 'revisionImage.name',+ 'revisionImage.checksum',+ 'storageObject.objectKey',+ 'storageObject.byteSize'+ ])+ .where('revisionImage.revisionId', '=', revisionId)+ .orderBy('revisionImage.name')+ .execute()+ return Promise.all(+ rows.map(async (row) => ({+ name: row.name,+ checksum: row.checksum,+ byteSize: Number(row.byteSize),+ download: await objects.createDownload({ key: row.objectKey, expiresAt })+ }))+ )+}++/**+ * Releases up to `batchSize` images no revision uses that no save has asked for since `before`:+ * their bytes go back to the workspace's usage, and their files, no longer anyone's, are left for+ * the object sweep. A save holds the images it refers to, so it either lands first and keeps them+ * or finds them gone and uploads them again. How many were released and their bytes.+ */+export async function releaseUnusedImages(+ database: Kysely<CloudDatabase>,+ before: Date,+ batchSize: number+): Promise<{ released: number; bytes: number }> {+ return database.transaction().execute(async (transaction) => {+ const unused = await transaction+ .selectFrom('workspaceImage')+ .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')+ .select(['workspaceImage.workspaceId', 'workspaceImage.checksum', 'storageObject.byteSize'])+ .where('workspaceImage.touchedAt', '<', before)+ .where((expression) =>+ expression.not(+ expression.exists(+ expression+ .selectFrom('revisionImage')+ .select('revisionImage.name')+ .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')+ .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')+ )+ )+ )+ .limit(batchSize)+ .forUpdate('workspaceImage')+ .skipLocked()+ .execute()+ let bytes = 0+ for (const image of unused) {+ await transaction+ .deleteFrom('workspaceImage')+ .where('workspaceId', '=', image.workspaceId)+ .where('checksum', '=', image.checksum)+ .execute()+ await transaction+ .updateTable('workspaceStorageUsage')+ .set({+ committedBytes: (expression) => expression('committedBytes', '-', Number(image.byteSize)),+ updatedAt: new Date()+ })+ .where('workspaceId', '=', image.workspaceId)+ .execute()+ bytes += Number(image.byteSize)+ }+ return { released: unused.length, bytes }+ })+}diff --git a/packages/cloud/src/server/documents/index.ts b/packages/cloud/src/server/documents/index.tsindex 4f297e765..160278096 100644--- a/packages/cloud/src/server/documents/index.ts+++ b/packages/cloud/src/server/documents/index.ts@@ -6,10 +6,9 @@ export {} from './access'export { createDocumentRoutes, type DocumentRouteEnvironment } from './routes'export {- createDocumentService,DocumentConflictError,DocumentForbiddenError,DocumentNotFoundError,- UploadInvalidError,- type DocumentService-} from './service'+ UploadInvalidError+} from './errors'+export { createDocumentService, type DocumentService } from './service'diff --git a/packages/cloud/src/server/documents/limits.ts b/packages/cloud/src/server/documents/limits.tsnew file mode 100644index 000000000..f69fe1cb4--- /dev/null+++ b/packages/cloud/src/server/documents/limits.ts@@ -0,0 +1,57 @@+import type { CloudDatabase } from '#cloud/server/db'+import { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'+import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'+import type { DocumentServiceOptions } from '#cloud/server/documents/service'+import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'+import type { Kysely } from 'kysely'++/**+ * The document `userId` may write to, and how large one file and the workspace's storage may+ * be for this save: technical limits, tightened by policy.+ */+export async function writableDocument(+ database: Kysely<CloudDatabase>,+ options: Pick<DocumentServiceOptions, 'policy' | 'technicalMaximumUploadBytes'>,+ userId: string,+ documentId: string+) {+ const access = await resolveDocumentAccess(database, userId, documentId)+ if (!access) throw new DocumentNotFoundError()+ if (!canEditDocument(access)) throw new DocumentForbiddenError()+ // Access was resolved just above, so the document is read without resolving it again.+ const row = await getDocumentSummaryRow(database, documentId)+ if (!row) throw new DocumentNotFoundError()+ const document = documentSummary(row)+ const policyContext = {+ targetingKey: document.workspaceId,+ actorId: userId,+ workspaceId: document.workspaceId,+ documentId,+ deploymentMode: 'self-hosted' as const+ }+ const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER+ const maximumFileBytes = Math.min(+ technicalMaximum,+ options.policy+ ? await options.policy.number(+ CLOUD_FEATURE_KEYS.maximumFileBytes,+ technicalMaximum,+ policyContext+ )+ : technicalMaximum+ )+ const maximumStorageBytes = options.policy+ ? await options.policy.number(+ CLOUD_FEATURE_KEYS.maximumStorageBytes,+ Number.MAX_SAFE_INTEGER,+ policyContext+ )+ : Number.MAX_SAFE_INTEGER+ return {+ document,+ maximumFileBytes,+ maximumStorageBytes:+ maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes+ }+}diff --git a/packages/cloud/src/server/documents/routes.ts b/packages/cloud/src/server/documents/routes.tsindex 4dd449577..d93f1d1ad 100644--- a/packages/cloud/src/server/documents/routes.ts+++ b/packages/cloud/src/server/documents/routes.ts@@ -1,13 +1,19 @@-import { parseCommitUpload, parseCreateDocument, parseCreateUpload } from '#cloud/contract'+import {+ parseCommitImageUploads,+ parseCommitUpload,+ parseCreateDocument,+ parseCreateUpload,+ parseRequestImageUploads+} from '#cloud/contract'import type { CloudActor } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'-import type { DocumentService } from '#cloud/server/documents/service'import {DocumentConflictError,DocumentForbiddenError,DocumentNotFoundError,UploadInvalidError-} from '#cloud/server/documents/service'+} from '#cloud/server/documents/errors'+import type { DocumentService } from '#cloud/server/documents/service'import { StorageQuotaExceededError } from '#cloud/server/quota'import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'import { validatedJSON } from '#cloud/server/validation'@@ -40,6 +46,20 @@ export function documentDomainError(context: Context, error: unknown): Responsereturn null}+/** Answers with what `respond` gives, or with the response a document domain error stands for. */+async function documentResponse<T extends Response>(+ context: Context,+ respond: () => Promise<T>+): Promise<T | Response> {+ try {+ return await respond()+ } catch (error) {+ const response = documentDomainError(context, error)+ if (response) return response+ throw error+ }+}+export function createDocumentRoutes(service: DocumentService,rateLimit?: { database: Kysely<CloudDatabase>; secret: string }@@ -56,6 +76,16 @@ export function createDocumentRoutes((context) => context.req.param('workspaceId') ?? 'unknown'))+ router.use(+ '/documents/:documentId/images',+ createActorRateLimiter(+ rateLimit.database,+ rateLimit.secret,+ CLOUD_RATE_LIMITS.uploadCreation,+ (context) => context.req.method !== 'POST',+ (context) => context.req.param('documentId') ?? 'unknown'+ )+ )router.use('/documents/:documentId/uploads',createActorRateLimiter(@@ -143,20 +173,43 @@ export function createDocumentRoutes(throw error}})- .post('/documents/:documentId/uploads', validatedJSON(parseCreateUpload), async (context) => {- try {- const result = await service.createUpload(- context.get('actor').userId,- context.req.param('documentId'),- context.req.valid('json')+ .post('/documents/:documentId/uploads', validatedJSON(parseCreateUpload), (context) =>+ documentResponse(context, async () =>+ context.json(+ await service.createUpload(+ context.get('actor').userId,+ context.req.param('documentId'),+ context.req.valid('json')+ ),+ 201)- return context.json(result, 201)- } catch (error) {- const response = documentDomainError(context, error)- if (response) return response- throw error- }- })+ )+ )+ .post(+ '/documents/:documentId/images/commit',+ validatedJSON(parseCommitImageUploads),+ (context) =>+ documentResponse(context, async () => {+ await service.commitImageUploads(+ context.get('actor').userId,+ context.req.param('documentId'),+ context.req.valid('json').uploads+ )+ return context.body(null, 204)+ })+ )+ .post('/documents/:documentId/images', validatedJSON(parseRequestImageUploads), (context) =>+ documentResponse(context, async () =>+ context.json(+ await service.requestImageUploads(+ context.get('actor').userId,+ context.req.param('documentId'),+ context.req.valid('json')+ ),+ 201+ )+ )+ ).post('/uploads/:uploadId/commit', validatedJSON(parseCommitUpload), async (context) => {try {const document = await service.commitUpload(diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.tsindex 5cc9adf0c..73b383151 100644--- a/packages/cloud/src/server/documents/service.ts+++ b/packages/cloud/src/server/documents/service.ts@@ -1,9 +1,12 @@import type {+ CommitImageUploadsInput,CommitUploadInput,CreateDocumentInput,CreateUploadInput,DocumentDownload,DocumentSummary,+ ImageUploadOffer,+ RequestImageUploadsInput,SharedDocument} from '#cloud/contract'import { createUploadCleanupService } from '#cloud/server/cleanup'@@ -13,6 +16,14 @@ import {canEditDocument,resolveDocumentAccess} from '#cloud/server/documents/access'+import {+ DocumentConflictError,+ DocumentForbiddenError,+ DocumentNotFoundError,+ UploadInvalidError+} from '#cloud/server/documents/errors'+import { createDocumentImages, revisionImageDownloads } from '#cloud/server/documents/images'+import { writableDocument } from '#cloud/server/documents/limits'import {findDocument,insertDocument,@@ -23,29 +34,18 @@ import {import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'import type { CreateDocumentUploadResult } from '#cloud/server/documents/types'import { announceVersions, recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'-import type { ObjectStore } from '#cloud/server/objects'-import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'+import type { ObjectStore, StoredObject } from '#cloud/server/objects'import type { CloudPolicy } from '#cloud/server/policy/policy'import { createStorageQuotaService } from '#cloud/server/quota'+import { Semaphore, uniq, uniqBy } from 'es-toolkit'import type { Kysely, Transaction } from 'kysely'const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000const UPLOAD_LIFETIME_MS = 15 * 60 * 1000+/** How many of a save's images are checked and landed at once. */+const IMAGE_COMMIT_CONCURRENCY = 8const WRITABLE_ROLES = new Set(['admin', 'editor'])-export class DocumentNotFoundError extends Error {- override readonly name = 'DocumentNotFoundError'-}-export class DocumentForbiddenError extends Error {- override readonly name = 'DocumentForbiddenError'-}-export class DocumentConflictError extends Error {- override readonly name = 'DocumentConflictError'-}-export class UploadInvalidError extends Error {- override readonly name = 'UploadInvalidError'-}-export type DocumentServiceOptions = {policy?: CloudPolicytechnicalMaximumUploadBytes?: number@@ -72,6 +72,7 @@ export function createDocumentService() {const cleanup = createUploadCleanupService(database, objects)const quota = createStorageQuotaService(database)+ const images = createDocumentImages(database, objects, quota)/*** Makes a committed upload the document's current revision, unless it already was, and records@@ -85,14 +86,21 @@ export function createDocumentService(upload,stored,revisionId,- storageObjectId+ storageObjectId,+ images: revisionImages}: {userId: stringuploadId: string- upload: { documentId: string; baseRevisionId: string | null; objectKey: string }+ upload: {+ documentId: string+ workspaceId: string+ baseRevisionId: string | null+ objectKey: string+ }stored: { checksum: string; byteSize: number; contentType: string }revisionId: stringstorageObjectId: string+ images: CommitUploadInput['images']}): Promise<boolean> {const lockedUpload = await transaction@@ -132,6 +140,12 @@ export function createDocumentService(createdBy: userId}).execute()+ const attached = await images.attachInTransaction(transaction, {+ workspaceId: upload.workspaceId,+ revisionId,+ images: revisionImages+ })+ if (!attached) throw new UploadInvalidError()await transaction.updateTable('document').set({@@ -174,17 +188,138 @@ export function createDocumentService(.where('documentRevision.documentId', '=', documentId).executeTakeFirst()if (!revision) throw new DocumentNotFoundError()+ const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)return {document,revisionId: revision.revisionId,byteSize: Number(revision.byteSize),checksum: revision.checksum,contentType: revision.contentType,- download: await objects.createDownload({- key: revision.objectKey,- expiresAt: new Date(Date.now() + DOWNLOAD_LIFETIME_MS)+ download: await objects.createDownload({ key: revision.objectKey, expiresAt }),+ images: await revisionImageDownloads(database, objects, revision.revisionId, expiresAt)+ }+ }++ /** What committing an upload reads of it and its document. */+ function selectUploads() {+ return database+ .selectFrom('upload')+ .innerJoin('document', 'document.id', 'upload.documentId')+ .select([+ 'upload.id',+ 'upload.documentId',+ 'upload.kind',+ 'document.workspaceId',+ 'upload.baseRevisionId',+ 'upload.objectKey',+ 'upload.checksum',+ 'upload.byteSize',+ 'upload.contentType',+ 'upload.multipartUploadId',+ 'upload.status',+ 'upload.expiresAt'+ ])+ }+ type UploadRow = Awaited<ReturnType<ReturnType<typeof selectUploads>['executeTakeFirstOrThrow']>>++ /**+ * Claims a pending upload, completes it when it came in parts, checks the store holds the file+ * it declared, and lands it with `land`. An upload that fails goes back to pending, so its+ * commit can be tried again.+ */+ async function finalizeUpload<T>(+ upload: UploadRow,+ multipart: CommitUploadInput['multipart'],+ land: (stored: StoredObject) => Promise<T>+ ): Promise<T> {+ if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {+ throw new UploadInvalidError()+ }+ const claimed = await database+ .updateTable('upload')+ .set({ status: 'finalizing', finalizationStartedAt: new Date() })+ .where('id', '=', upload.id)+ .where('status', '=', 'pending')+ .returning('id')+ .executeTakeFirst()+ if (!claimed) throw new UploadInvalidError()+ try {+ if (multipart) {+ if (+ !objects.capabilities.multipartUpload ||+ multipart.uploadId !== upload.multipartUploadId+ ) {+ throw new UploadInvalidError()+ }+ await objects.completeUpload({+ key: upload.objectKey,+ uploadId: multipart.uploadId,+ parts: multipart.parts+ })+ }+ const stored = await objects.head(upload.objectKey)+ if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()+ return await land(stored)+ } catch (error) {+ await database+ .updateTable('upload')+ .set({ status: 'pending', finalizationStartedAt: null })+ .where('id', '=', upload.id)+ .where('status', '=', 'finalizing')+ .execute()+ throw error+ }+ }++ function landImage(upload: UploadRow, stored: StoredObject): Promise<void> {+ return database.transaction().execute((transaction) =>+ images.landInTransaction(transaction, {+ uploadId: upload.id,+ workspaceId: upload.workspaceId,+ objectKey: upload.objectKey,+ stored})+ )+ }++ async function commitUpload(+ userId: string,+ uploadId: string,+ input: CommitUploadInput+ ): Promise<DocumentSummary> {+ const upload = await selectUploads()+ .where('upload.id', '=', uploadId)+ .where('upload.createdBy', '=', userId)+ .executeTakeFirst()+ if (!upload) throw new DocumentNotFoundError()+ const access = await resolveDocumentAccess(database, userId, upload.documentId)+ if (!access) throw new DocumentNotFoundError()+ if (!canEditDocument(access)) throw new DocumentForbiddenError()+ if (input.checksum !== upload.checksum) throw new UploadInvalidError()+ if (upload.status !== 'committed') {+ const checkpointed =+ upload.kind === 'image'+ ? await finalizeUpload(upload, input.multipart, (stored) =>+ landImage(upload, stored).then(() => false)+ )+ : await finalizeUpload(upload, input.multipart, (stored) =>+ database.transaction().execute((transaction) =>+ landRevision(transaction, {+ userId,+ uploadId,+ upload,+ stored,+ revisionId: crypto.randomUUID(),+ storageObjectId: crypto.randomUUID(),+ images: input.images+ })+ )+ )+ if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)}+ const document = await findDocument(database, userId, upload.documentId)+ if (!document) throw new DocumentNotFoundError()+ return document}return {@@ -223,9 +358,32 @@ export function createDocumentService(.where('document.workspaceId', '=', workspaceId).where('document.deletedAt', 'is', null).executeTakeFirstOrThrow()+ // Images current revisions use, each counted once however many documents share it.+ const shared = await database+ .selectFrom('workspaceImage')+ .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')+ .select((expression) => [+ expression.fn.count('storageObject.id').as('objectCount'),+ expression.fn+ .coalesce(expression.fn.sum('storageObject.byteSize'), expression.val(0))+ .as('bytesUsed')+ ])+ .where('workspaceImage.workspaceId', '=', workspaceId)+ .where((expression) =>+ expression.exists(+ expression+ .selectFrom('revisionImage')+ .innerJoin('document', 'document.currentRevisionId', 'revisionImage.revisionId')+ .select('revisionImage.name')+ .whereRef('revisionImage.workspaceId', '=', 'workspaceImage.workspaceId')+ .whereRef('revisionImage.checksum', '=', 'workspaceImage.checksum')+ .where('document.deletedAt', 'is', null)+ )+ )+ .executeTakeFirstOrThrow()return {- bytesUsed: Number(result.bytesUsed),- objectCount: Number(result.objectCount),+ bytesUsed: Number(result.bytesUsed) + Number(shared.bytesUsed),+ objectCount: Number(result.objectCount) + Number(shared.objectCount),documentCount: Number(result.documentCount)}},@@ -285,37 +443,14 @@ export function createDocumentService(documentId: string,input: CreateUploadInput): Promise<CreateDocumentUploadResult> {- const access = await resolveDocumentAccess(database, userId, documentId)- if (!access) throw new DocumentNotFoundError()- if (!canEditDocument(access)) throw new DocumentForbiddenError()- const document = await findDocument(database, userId, documentId)- if (!document) throw new DocumentNotFoundError()+ const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(+ database,+ options,+ userId,+ documentId+ )if (document.currentRevisionId !== input.baseRevisionId) throw new DocumentConflictError()- const policyContext = {- targetingKey: document.workspaceId,- actorId: userId,- workspaceId: document.workspaceId,- documentId,- deploymentMode: 'self-hosted' as const- }- const technicalMaximum = options.technicalMaximumUploadBytes ?? Number.MAX_SAFE_INTEGER- const entitlementMaximum = options.policy- ? await options.policy.number(- CLOUD_FEATURE_KEYS.maximumFileBytes,- technicalMaximum,- policyContext- )- : technicalMaximum- if (input.byteSize > Math.min(technicalMaximum, entitlementMaximum)) {- throw new UploadInvalidError()- }- const maximumStorageBytes = options.policy- ? await options.policy.number(- 'cloud.storage.maximum-bytes',- Number.MAX_SAFE_INTEGER,- policyContext- )- : Number.MAX_SAFE_INTEGER+ if (input.byteSize > maximumFileBytes) throw new UploadInvalidError()const uploadId = crypto.randomUUID()const objectKey = `documents/${document.workspaceId}/${documentId}/uploads/${uploadId}.fig`const expiresAt = new Date(Date.now() + UPLOAD_LIFETIME_MS)@@ -342,7 +477,7 @@ export function createDocumentService(uploadId,bytes: input.byteSize,expiresAt,- maximumBytes: maximumStorageBytes === Number.MAX_SAFE_INTEGER ? null : maximumStorageBytes+ maximumBytes: maximumStorageBytes})})let objectUpload@@ -373,92 +508,78 @@ export function createDocumentService(return { id: uploadId, upload: objectUpload }},- async commitUpload(+ /** Uploads for the images a save of the document will name that its workspace lacks. */+ async requestImageUploads(userId: string,- uploadId: string,- input: CommitUploadInput- ): Promise<DocumentSummary> {- const upload = await database- .selectFrom('upload')- .innerJoin('document', 'document.id', 'upload.documentId')- .select([- 'upload.documentId',- 'upload.baseRevisionId',- 'upload.objectKey',- 'upload.checksum',- 'upload.byteSize',- 'upload.contentType',- 'upload.multipartUploadId',- 'upload.status',- 'upload.expiresAt'- ])- .where('upload.id', '=', uploadId)- .where('upload.createdBy', '=', userId)- .executeTakeFirst()- if (!upload) throw new DocumentNotFoundError()- const access = await resolveDocumentAccess(database, userId, upload.documentId)+ documentId: string,+ input: RequestImageUploadsInput+ ): Promise<{ uploads: ImageUploadOffer[] }> {+ const { document, maximumFileBytes, maximumStorageBytes } = await writableDocument(+ database,+ options,+ userId,+ documentId+ )+ if (input.images.some((image) => image.byteSize > maximumFileBytes)) {+ throw new UploadInvalidError()+ }+ return {+ uploads: await images.requestUploads({+ userId,+ documentId,+ workspaceId: document.workspaceId,+ images: input.images,+ expiresAt: new Date(Date.now() + UPLOAD_LIFETIME_MS),+ maximumBytes: maximumStorageBytes+ })+ }+ },+ commitUpload,++ /**+ * Commits the image uploads a save asked for in one request, however many there are: each+ * must be an image upload this person made for the document.+ */+ async commitImageUploads(+ userId: string,+ documentId: string,+ uploads: CommitImageUploadsInput['uploads']+ ): Promise<void> {+ const access = await resolveDocumentAccess(database, userId, documentId)if (!access) throw new DocumentNotFoundError()if (!canEditDocument(access)) throw new DocumentForbiddenError()- if (input.checksum !== upload.checksum) throw new UploadInvalidError()- if (upload.status === 'committed') {- const document = await findDocument(database, userId, upload.documentId)- if (!document) throw new DocumentNotFoundError()- return document- }- if (upload.status !== 'pending' || new Date(upload.expiresAt).getTime() <= Date.now()) {+ const ids = uniq(uploads.map((upload) => upload.uploadId))+ const rows = new Map(+ (+ await selectUploads()+ .where('upload.id', 'in', ids)+ .where('upload.documentId', '=', documentId)+ .where('upload.createdBy', '=', userId)+ .execute()+ ).map((row) => [row.id, row])+ )+ if (rows.size !== ids.length || [...rows.values()].some((row) => row.kind !== 'image')) {throw new UploadInvalidError()}- const claimed = await database- .updateTable('upload')- .set({ status: 'finalizing', finalizationStartedAt: new Date() })- .where('id', '=', uploadId)- .where('status', '=', 'pending')- .returning('id')- .executeTakeFirst()- if (!claimed) throw new UploadInvalidError()- let checkpointed = false- try {- if (input.multipart) {- if (- !objects.capabilities.multipartUpload ||- input.multipart.uploadId !== upload.multipartUploadId- ) {- throw new UploadInvalidError()- }- await objects.completeUpload({- key: upload.objectKey,- uploadId: input.multipart.uploadId,- parts: input.multipart.parts- })- }- const stored = await objects.head(upload.objectKey)- if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()-- const revisionId = crypto.randomUUID()- const storageObjectId = crypto.randomUUID()- checkpointed = await database.transaction().execute((transaction) =>- landRevision(transaction, {- userId,- uploadId,- upload,- stored,- revisionId,- storageObjectId- })- )- } catch (error) {- await database- .updateTable('upload')- .set({ status: 'pending', finalizationStartedAt: null })- .where('id', '=', uploadId)- .where('status', '=', 'finalizing')- .execute()- throw error+ for (const commit of uploads) {+ if (rows.get(commit.uploadId)?.checksum !== commit.checksum) throw new UploadInvalidError()}- if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)- const document = await findDocument(database, userId, upload.documentId)- if (!document) throw new DocumentNotFoundError()- return document+ // Each image is its own object, so a few are checked and landed at once, each once however+ // often the request names it.+ const semaphore = new Semaphore(IMAGE_COMMIT_CONCURRENCY)+ await Promise.all(+ uniqBy(uploads, (commit) => commit.uploadId).map(async (commit) => {+ const upload = rows.get(commit.uploadId)+ if (!upload) throw new UploadInvalidError()+ if (upload.status === 'committed') return+ await semaphore.acquire()+ try {+ await finalizeUpload(upload, commit.multipart, (stored) => landImage(upload, stored))+ } finally {+ semaphore.release()+ }+ })+ )}}}diff --git a/packages/cloud/src/server/documents/versions/service.ts b/packages/cloud/src/server/documents/versions/service.tsindex 630116993..824d2ff4f 100644--- a/packages/cloud/src/server/documents/versions/service.ts+++ b/packages/cloud/src/server/documents/versions/service.ts@@ -9,8 +9,9 @@ import type {} from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'import { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'+import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'+import { copyRevisionImages, revisionImageDownloads } from '#cloud/server/documents/images'import { findDocument, insertDocument, workspaceRole } from '#cloud/server/documents/repository'-import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/service'import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'import type { ObjectStore } from '#cloud/server/objects'import type { CloudPolicyContext } from '#cloud/server/policy/keys'@@ -236,6 +237,7 @@ export function createDocumentVersionService(const { document, start } = await openHistory(userId, documentId, false)const version = await findVersion(documentId, versionId, start)const stored = await storedRevision(database, version.revisionId)+ const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)return {document: {document: documentSummary(document),@@ -243,10 +245,8 @@ export function createDocumentVersionService(byteSize: Number(stored.byteSize),checksum: stored.checksum,contentType: stored.contentType,- download: await objects.createDownload({- key: stored.objectKey,- expiresAt: new Date(Date.now() + DOWNLOAD_LIFETIME_MS)- })+ download: await objects.createDownload({ key: stored.objectKey, expiresAt }),+ images: await revisionImageDownloads(database, objects, version.revisionId, expiresAt)},version: versionOf(version, document.currentRevisionId)}@@ -299,6 +299,7 @@ export function createDocumentVersionService(createdBy: userId}).execute()+ await copyRevisionImages(transaction, version.revisionId, revisionId)await transaction.updateTable('document').set({@@ -372,6 +373,7 @@ export function createDocumentVersionService(createdBy: userId}).execute()+ await copyRevisionImages(transaction, version.revisionId, revisionId)await transaction.updateTable('document').set({ currentRevisionId: revisionId, version: 1 })diff --git a/packages/cloud/src/server/policy/service.ts b/packages/cloud/src/server/policy/service.tsindex adc8908cc..723f5b853 100644--- a/packages/cloud/src/server/policy/service.ts+++ b/packages/cloud/src/server/policy/service.ts@@ -1,7 +1,7 @@import type { WorkspaceEntitlements } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'+import { DocumentNotFoundError } from '#cloud/server/documents/errors'import { workspaceRole } from '#cloud/server/documents/repository'-import { DocumentNotFoundError } from '#cloud/server/documents/service'import { createStorageQuotaService } from '#cloud/server/quota'import type { Kysely } from 'kysely'diff --git a/packages/cloud/src/server/quota/reconcile.ts b/packages/cloud/src/server/quota/reconcile.tsindex 6d995ed46..df275df51 100644--- a/packages/cloud/src/server/quota/reconcile.ts+++ b/packages/cloud/src/server/quota/reconcile.ts@@ -28,6 +28,14 @@ export function createStorageReconciliationService(database: Kysely<CloudDatabas.select(['storageObject.id', 'storageObject.byteSize']).distinct().where('document.workspaceId', '=', workspace.id)+ // Images are the workspace's once, whichever revisions use them.+ .union((union) =>+ union+ .selectFrom('storageObject')+ .innerJoin('workspaceImage', 'workspaceImage.storageObjectId', 'storageObject.id')+ .select(['storageObject.id', 'storageObject.byteSize'])+ .where('workspaceImage.workspaceId', '=', workspace.id)+ ).execute()])const recordedBytes = Number(recorded?.committedBytes ?? 0)diff --git a/packages/cloud/src/server/quota/storage.ts b/packages/cloud/src/server/quota/storage.tsindex 8fb858d70..ef1889422 100644--- a/packages/cloud/src/server/quota/storage.ts+++ b/packages/cloud/src/server/quota/storage.ts@@ -108,6 +108,16 @@ export function createStorageQuotaService(database: Kysely<CloudDatabase>) {.execute()}+ async function release(executor: StorageDatabase, uploadId: string): Promise<void> {+ await executor+ .updateTable('uploadStorageReservation')+ .set({ releasedAt: new Date() })+ .where('uploadId', '=', uploadId)+ .where('committedAt', 'is', null)+ .where('releasedAt', 'is', null)+ .execute()+ }+return {snapshot: (workspaceId: string) => snapshot(database, workspaceId),@@ -143,13 +153,11 @@ export function createStorageQuotaService(database: Kysely<CloudDatabase>) {},async release(uploadId: string): Promise<void> {- await database- .updateTable('uploadStorageReservation')- .set({ releasedAt: new Date() })- .where('uploadId', '=', uploadId)- .where('committedAt', 'is', null)- .where('releasedAt', 'is', null)- .execute()+ await release(database, uploadId)+ },++ releaseInTransaction(transaction: Transaction<CloudDatabase>, uploadId: string): Promise<void> {+ return release(transaction, uploadId)}}}diff --git a/packages/cloud/src/server/sharing/access.ts b/packages/cloud/src/server/sharing/access.tsindex eeae715dd..33bbbce31 100644--- a/packages/cloud/src/server/sharing/access.ts+++ b/packages/cloud/src/server/sharing/access.ts@@ -1,6 +1,6 @@import type { CloudDatabase } from '#cloud/server/db'import { resolveDocumentAccess } from '#cloud/server/documents/access'-import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/service'+import { DocumentForbiddenError, DocumentNotFoundError } from '#cloud/server/documents/errors'import type { Kysely } from 'kysely'export async function requireSharingAccess(diff --git a/packages/cloud/src/server/sharing/capabilities/service.ts b/packages/cloud/src/server/sharing/capabilities/service.tsindex 9c7efbf4d..24243ece2 100644--- a/packages/cloud/src/server/sharing/capabilities/service.ts+++ b/packages/cloud/src/server/sharing/capabilities/service.ts@@ -7,7 +7,7 @@ import type {} from '#cloud/contract'import type { CloudActor } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'-import { DocumentNotFoundError } from '#cloud/server/documents/service'+import { DocumentNotFoundError } from '#cloud/server/documents/errors'import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'import type { CloudPolicy } from '#cloud/server/policy/policy'import type { Kysely, UpdateObject } from 'kysely'diff --git a/packages/cloud/src/server/sharing/grants/service.ts b/packages/cloud/src/server/sharing/grants/service.tsindex 75e5c2f3d..f216f8f16 100644--- a/packages/cloud/src/server/sharing/grants/service.ts+++ b/packages/cloud/src/server/sharing/grants/service.ts@@ -1,6 +1,6 @@import type { DocumentGrant, PutDocumentGrantInput } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'-import { DocumentNotFoundError } from '#cloud/server/documents/service'+import { DocumentNotFoundError } from '#cloud/server/documents/errors'import type { Kysely } from 'kysely'import { advanceCollaborationEpoch, requireSharingAccess } from '../access'diff --git a/packages/cloud/src/server/sharing/invitations/service.ts b/packages/cloud/src/server/sharing/invitations/service.tsindex f5e0aec04..dc743f052 100644--- a/packages/cloud/src/server/sharing/invitations/service.ts+++ b/packages/cloud/src/server/sharing/invitations/service.ts@@ -10,7 +10,7 @@ import type {import { cloudInvitationURL } from '#cloud/contract'import type { CloudActor } from '#cloud/server/auth'import type { CloudDatabase } from '#cloud/server/db'-import { DocumentNotFoundError } from '#cloud/server/documents/service'+import { DocumentNotFoundError } from '#cloud/server/documents/errors'import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'import type { Kysely } from 'kysely'diff --git a/packages/cloud/src/server/sharing/policy.ts b/packages/cloud/src/server/sharing/policy.tsindex 4a7656eda..eb2c48ffd 100644--- a/packages/cloud/src/server/sharing/policy.ts+++ b/packages/cloud/src/server/sharing/policy.ts@@ -1,6 +1,6 @@import type { DocumentPermission } from '#cloud/contract'import type { CloudDatabase } from '#cloud/server/db'-import { DocumentForbiddenError } from '#cloud/server/documents/service'+import { DocumentForbiddenError } from '#cloud/server/documents/errors'import { CLOUD_FEATURE_KEYS, type CloudPolicy, type CloudPolicyContext } from '#cloud/server/policy'import type { Kysely } from 'kysely'diff --git a/packages/cloud/tests/integration/server/documents/images.test.ts b/packages/cloud/tests/integration/server/documents/images.test.tsnew file mode 100644index 000000000..118cdd72d--- /dev/null+++ b/packages/cloud/tests/integration/server/documents/images.test.ts@@ -0,0 +1,294 @@+import { describe, expect, test } from 'bun:test'++import { createCloudTestDatabase } from '#cloud-tests/helpers/database'+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'+import { responseJSON } from '#cloud-tests/helpers/response'+import {+ createBetterAuthAdapter,+ createCloudApp,+ createRevisionCompactionService,+ parseCloudServerConfig,+ type CloudActor+} from '#cloud/server'+import * as v from 'valibot'++const config = parseCloudServerConfig({+ deployment: 'self-hosted',+ publicURL: 'http://localhost:8787',+ databaseURL: 'postgresql://test:test@localhost/test',+ authSecret: 'integration-test-secret-at-least-32-characters',+ s3Endpoint: 'http://localhost:9000',+ s3Region: 'us-east-1',+ s3Bucket: 'openpencil',+ s3AccessKeyId: 'openpencil',+ s3SecretAccessKey: 'openpencil-secret'+})++const alice: CloudActor = { userId: 'alice', email: '[email protected]', name: 'Alice' }+const DAY_MS = 24 * 60 * 60_000+const FILE_BYTES = 128+const OCTETS = 'application/octet-stream'++/** A checksum the memory store takes as verified, one per letter. */+const checksumOf = (letter: string) => `${letter.repeat(43)}=`++type Image = { name: string; checksum: string; byteSize: number }++const documentSchema = v.object({+ document: v.object({ id: v.string(), currentRevisionId: v.nullable(v.string()) })+})+const offersSchema = v.object({+ uploads: v.array(v.object({ checksum: v.string(), uploadId: v.string() }))+})+const downloadSchema = v.object({+ document: v.object({+ revisionId: v.string(),+ images: v.array(+ v.object({+ name: v.string(),+ checksum: v.string(),+ byteSize: v.number(),+ download: v.object({ url: v.string() })+ })+ )+ })+})++async function testApp() {+ const runtime = await createCloudTestDatabase()+ const objects = createMemoryObjectStore()+ const app = createCloudApp({+ config,+ database: runtime.database,+ auth: createBetterAuthAdapter(config, runtime.database),+ objects: objects.store,+ resolveSession: async () => alice+ })+ const request = (path: string, init: { method?: string; json?: unknown } = {}) =>+ app.request(`/api${path}`, {+ method: init.method ?? 'GET',+ headers: { 'Content-Type': 'application/json' },+ body: init.json === undefined ? undefined : JSON.stringify(init.json)+ })+ const workspace = await responseJSON(+ await request('/workspaces', { method: 'POST', json: { name: 'Studio' } }),+ v.object({ workspace: v.object({ id: v.string() }) })+ )+ const created = await responseJSON(+ await request(`/workspaces/${workspace.workspace.id}/documents`, {+ method: 'POST',+ json: { name: 'Poster' }+ }),+ documentSchema+ )+ const documentId = created.document.id+ let current: string | null = null+ let saves = 0++ /** Puts what an upload declared where the object store keeps it, as a client's PUT would. */+ async function store(uploadId: string) {+ const row = await runtime.database+ .selectFrom('upload')+ .select(['objectKey', 'byteSize', 'checksum'])+ .where('id', '=', uploadId)+ .executeTakeFirstOrThrow()+ objects.put(row.objectKey, {+ byteSize: Number(row.byteSize),+ checksum: row.checksum,+ checksumVerification: 'native',+ contentType: OCTETS+ })+ }++ /** Uploads the images the workspace lacks, as the editor does before a save. */+ async function uploadImages(images: Image[]) {+ const offers = await responseJSON(+ await request(`/documents/${documentId}/images`, {+ method: 'POST',+ json: { images: images.map(({ checksum, byteSize }) => ({ checksum, byteSize })) }+ }),+ offersSchema+ )+ if (offers.uploads.length === 0) return offers.uploads+ for (const offer of offers.uploads) await store(offer.uploadId)+ // Naming an upload twice lands it once.+ const commits = offers.uploads.map(({ uploadId, checksum }) => ({ uploadId, checksum }))+ const committed = await request(`/documents/${documentId}/images/commit`, {+ method: 'POST',+ json: { uploads: [...commits, ...commits] }+ })+ expect(committed.status).toBe(204)+ return offers.uploads+ }++ /** Saves the document without its images, naming them instead. */+ async function save(images: Image[] = []) {+ saves+++ const checksum = checksumOf(String.fromCharCode(64 + saves))+ const upload = await responseJSON(+ await request(`/documents/${documentId}/uploads`, {+ method: 'POST',+ json: { baseRevisionId: current, byteSize: FILE_BYTES, checksum, contentType: OCTETS }+ }),+ v.object({ id: v.string() })+ )+ await store(upload.id)+ const response = await request(`/uploads/${upload.id}/commit`, {+ method: 'POST',+ json: { checksum, images: images.map(({ name, checksum }) => ({ name, checksum })) }+ })+ if (response.status !== 200) return response+ current = (await responseJSON(response, documentSchema)).document.currentRevisionId+ return response+ }++ async function download() {+ return (await responseJSON(await request(`/documents/${documentId}`), downloadSchema)).document+ }++ async function usage() {+ return responseJSON(+ await request(`/workspaces/${workspace.workspace.id}/usage`),+ v.object({ usage: v.object({ bytesUsed: v.number(), objectCount: v.number() }) })+ )+ }++ /** Moves saves and image requests back in time, as if they were made that long ago. */+ async function age(milliseconds: number) {+ for (const table of ['documentVersion', 'documentRevision'] as const) {+ const rows = await runtime.database.selectFrom(table).select(['id', 'createdAt']).execute()+ for (const row of rows) {+ await runtime.database+ .updateTable(table)+ .set({ createdAt: new Date(row.createdAt.getTime() - milliseconds) })+ .where('id', '=', row.id)+ .execute()+ }+ }+ const images = await runtime.database+ .selectFrom('workspaceImage')+ .select(['checksum', 'touchedAt'])+ .execute()+ for (const image of images) {+ await runtime.database+ .updateTable('workspaceImage')+ .set({ touchedAt: new Date(image.touchedAt.getTime() - milliseconds) })+ .where('checksum', '=', image.checksum)+ .execute()+ }+ }++ return { runtime, objects, request, documentId, uploadImages, save, download, usage, age }+}++const photo: Image = { name: '0a1b', checksum: checksumOf('P'), byteSize: 1000 }+const logo: Image = { name: '2c3d', checksum: checksumOf('L'), byteSize: 300 }++describe('Cloud document images', () => {+ test('stores each image once and gives a save its images back under their names', async () => {+ const context = await testApp()+ try {+ expect(await context.uploadImages([photo, logo])).toHaveLength(2)+ expect((await context.save([photo, logo])).status).toBe(200)+ const download = await context.download()+ expect(+ download.images.map(({ name, checksum, byteSize }) => ({ name, checksum, byteSize }))+ ).toEqual([photo, logo])++ // The workspace has both, so the next save uploads neither, even under another name.+ const renamed = { ...photo, name: 'renamed' }+ expect(await context.uploadImages([renamed, logo])).toHaveLength(0)+ expect((await context.save([renamed, logo])).status).toBe(200)+ expect((await context.usage()).usage).toEqual({+ bytesUsed: FILE_BYTES + photo.byteSize + logo.byteSize,+ objectCount: 3+ })+ } finally {+ await context.runtime.close()+ }+ })++ test('refuses a save that names an image the workspace does not hold', async () => {+ const context = await testApp()+ try {+ const response = await context.save([photo])+ expect(response.status).toBe(422)+ // Nor does committing images take a document's own upload.+ const upload = await responseJSON(+ await context.request(`/documents/${context.documentId}/uploads`, {+ method: 'POST',+ json: {+ baseRevisionId: null,+ byteSize: FILE_BYTES,+ checksum: checksumOf('Z'),+ contentType: OCTETS+ }+ }),+ v.object({ id: v.string() })+ )+ const asImage = await context.request(`/documents/${context.documentId}/images/commit`, {+ method: 'POST',+ json: { uploads: [{ uploadId: upload.id, checksum: checksumOf('Z') }] }+ })+ expect(asImage.status).toBe(422)+ expect(+ await context.runtime.database.selectFrom('documentRevision').select('id').execute()+ ).toHaveLength(0)+ } finally {+ await context.runtime.close()+ }+ })++ test('a restored version keeps its images', async () => {+ const context = await testApp()+ try {+ await context.uploadImages([photo])+ await context.save([photo])+ await context.save()+ const history = await responseJSON(+ await context.request(`/documents/${context.documentId}/versions`),+ v.object({ versions: v.array(v.object({ id: v.string(), current: v.boolean() })) })+ )+ const first = history.versions.find((version) => !version.current)+ if (!first) throw new Error('Expected the first save in the history')+ const restored = await context.request(+ `/documents/${context.documentId}/versions/${first.id}/restore`,+ { method: 'POST' }+ )+ expect(restored.status).toBe(200)+ expect((await context.download()).images.map((image) => image.name)).toEqual([photo.name])+ } finally {+ await context.runtime.close()+ }+ })++ test('releases an image once no kept save uses it, and deletes its file', async () => {+ const context = await testApp()+ try {+ await context.save()+ await context.uploadImages([photo])+ await context.save([photo])+ await context.save()+ await context.age(2 * DAY_MS)+ const imageKey = await context.runtime.database+ .selectFrom('workspaceImage')+ .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')+ .select('storageObject.objectKey')+ .executeTakeFirstOrThrow()++ const result = await createRevisionCompactionService(+ context.runtime.database,+ context.objects.store+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })+ expect(result).toMatchObject({ revisionsDeleted: 1, imagesReleased: 1, failed: 0 })+ expect(context.objects.deletedKeys).toContain(imageKey.objectKey)+ const usage = await context.runtime.database+ .selectFrom('workspaceStorageUsage')+ .select('committedBytes')+ .executeTakeFirstOrThrow()+ expect(Number(usage.committedBytes)).toBe(2 * FILE_BYTES)+ } finally {+ await context.runtime.close()+ }+ })+})diff --git a/packages/cloud/tests/server/api/router.test.ts b/packages/cloud/tests/server/api/router.test.tsindex 56b6964d2..dadfe7410 100644--- a/packages/cloud/tests/server/api/router.test.ts+++ b/packages/cloud/tests/server/api/router.test.ts@@ -46,6 +46,12 @@ function services() {createUpload: async () => {throw new Error('not used')},+ requestImageUploads: async () => {+ throw new Error('not used')+ },+ commitImageUploads: async () => {+ throw new Error('not used')+ },commitUpload: async () => {throw new Error('not used')}diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex 969ee17f0..b8b6c6f83 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -46,6 +46,17 @@ revision has its own object key.replace it.- Deleting a document is immediate for users; the cleanup worker removes revisions and objects oncethe retention period passes.+- Images are stored once per workspace, keyed by the SHA-256 the object store verifies, and a stored+ revision leaves them out of its file: it lists the images it uses under the names the file gives+ them, and a download returns a link for each. Before a save the client asks which of its images+ the workspace lacks and uploads only those, each as an upload of its own kind with its own+ reservation, committed together in one request; asking renews the images the workspace holds.+ An image under a name Cloud does not accept stays inside the file. A save that names an image+ the workspace does not hold is refused. Keying by the verified checksum, with names kept per+ revision, means bytes uploaded under the wrong name can only reach the revision that named them.+- Restoring or duplicating a version gives the new revision the same images. Compaction releases an+ image no kept revision uses once a day has passed since a save last asked for it: its bytes return+ to the workspace's usage and the object sweep deletes its file.### Version historydiff --git a/src/app/cloud/sharing/link.ts b/src/app/cloud/sharing/link.tsindex d21d26e3e..8066a2c05 100644--- a/src/app/cloud/sharing/link.ts+++ b/src/app/cloud/sharing/link.ts@@ -5,7 +5,7 @@ import { createCloudAPIClient } from '@open-pencil/cloud/client'import { randomHex } from '@open-pencil/scene-graph/random'import { useCollabIdentity } from '@/app/collab/identity'-import { downloadCloudRevision } from '@/app/integrations/storage/cloud/download'+import { downloadCloudDocument } from '@/app/integrations/storage/cloud/download'import { storageFetch } from '@/app/integrations/storage/s3/fetch'import { getTabForStore, openFileInNewTab } from '@/app/tabs'import { IS_BROWSER } from '@/constants'@@ -37,7 +37,7 @@ export async function openCloudShareLink(link: CloudShareLink): Promise<void> {guestId: guestId.value}const { document } = await client.getSharedDocument(link.shareId, input)- const bytes = await downloadCloudRevision(document, (input, init) => storageFetch(input, init))+ const bytes = await downloadCloudDocument(document, (input, init) => storageFetch(input, init))const name = document.document.nameconst store = await openFileInNewTab(new File([Uint8Array.from(bytes)], `${name}.fig`, { type: 'application/octet-stream' })diff --git a/src/app/cloud/versions/history.ts b/src/app/cloud/versions/history.tsindex 7cfc629d1..95390d3df 100644--- a/src/app/cloud/versions/history.ts+++ b/src/app/cloud/versions/history.ts@@ -3,7 +3,7 @@ import { shallowReactive, shallowRef } from 'vue'import type { DocumentVersion } from '@open-pencil/cloud/contract'import { createEditorStore, type EditorStore } from '@/app/editor/session'-import { downloadCloudRevision } from '@/app/integrations/storage/cloud/download'+import { downloadCloudDocument } from '@/app/integrations/storage/cloud/download'import { storageFetch } from '@/app/integrations/storage/s3/fetch'import { readFigBytes } from '@/app/tabs'@@ -149,7 +149,7 @@ export async function previewVersion(store: EditorStore, version: DocumentVersiotarget.documentId,version.id)- const bytes = await downloadCloudRevision(download, storageFetch, { signal: load.signal })+ const bytes = await downloadCloudDocument(download, storageFetch, { signal: load.signal })const name = document.state.documentNamepreview = createEditorStore(await readFigBytes(bytes, name, load.signal))preview.state.documentName = namediff --git a/src/app/integrations/storage/cloud/adapter.ts b/src/app/integrations/storage/cloud/adapter.tsindex bb07fc327..dd85f9768 100644--- a/src/app/integrations/storage/cloud/adapter.ts+++ b/src/app/integrations/storage/cloud/adapter.ts@@ -12,13 +12,19 @@ import {import { StorageRevisionConflictError, StorageUnavailableError } from '../errors'import { storageFetch } from '../s3/fetch'import type { StorageAdapter, StorageProviderRuntime } from '../types'-import { cloudChecksum, downloadCloudRevision, readCloudRevisionRange } from './download'+import { cloudChecksum, downloadCloudDocument, readCloudRevisionRange } from './download'+import { splitCloudDocument, uploadCloudImages } from './images'import { uploadCloudObject } from './upload'function revisionConflict(error: unknown): boolean {return error instanceof CloudAPIError && error.code === 'revision_conflict'}+/** The server refused the save as declared, as when an image it named was released meanwhile. */+function invalidUpload(error: unknown): boolean {+ return error instanceof CloudAPIError && error.code === 'invalid_upload'+}+export type CloudStorageDependencies = {/** The signed-in API client for a server, or a `StorageUnavailableError`. */client(serverId: string): Promise<CloudAPIClient>@@ -91,7 +97,7 @@ export function createCloudStorageAdapter(async getDocument(id, onProgress, signal) {const download = await (await client()).getDocument(id)- const bytes = await downloadCloudRevision(+ const bytes = await downloadCloudDocument(download,(input, init) => dependencies.objectFetch(input, init),{ signal, onProgress }@@ -106,22 +112,38 @@ export function createCloudStorageAdapter(if (!baseRevision && !(await listed(id))) {await cloud.createDocument(workspaceId(), { id, name: metadata.name })}- const checksum = await cloudChecksum(bytes)- try {+ // The workspace keeps images once; the stored file names them and uploads only those it lacks.+ const { lean, images } = splitCloudDocument(bytes)+ const named = await Promise.all(+ images.map(async (image) => ({ ...image, checksum: await cloudChecksum(image.bytes) }))+ )+ const checksum = await cloudChecksum(lean)+ const objectFetch = (input: string, init: RequestInit) =>+ dependencies.objectFetch(input, init)+ const save = async () => {+ await uploadCloudImages({ cloud, documentId: id, images: named, objectFetch })const upload = await uploadCloudObject({cloud,documentId: id,- bytes,+ bytes: lean,checksum,baseRevision,- objectFetch: (input, init) => dependencies.objectFetch(input, init),+ objectFetch,onProgress})const committed = await cloud.commitUpload(upload.uploadId, {checksum,- multipart: upload.multipart+ multipart: upload.multipart,+ images: named.map((image) => ({ name: image.name, checksum: image.checksum }))})return { revision: committed.currentRevisionId }+ }+ try {+ // An image released between asking and committing is uploaded again by a second try.+ return await save().catch((error: unknown) => {+ if (invalidUpload(error)) return save()+ throw error+ })} catch (error) {if (revisionConflict(error)) {throw new StorageRevisionConflictError((await listed(id))?.currentRevisionId ?? null)diff --git a/src/app/integrations/storage/cloud/download.ts b/src/app/integrations/storage/cloud/download.tsindex 5caeb9147..78ff9b751 100644--- a/src/app/integrations/storage/cloud/download.ts+++ b/src/app/integrations/storage/cloud/download.ts@@ -1,37 +1,71 @@+import { Semaphore, sumBy } from 'es-toolkit'import { fromUint8Array } from 'js-base64'import type { DocumentDownload } from '@open-pencil/cloud/contract'import type { StorageTransferProgress } from '../types'+import { assembleCloudDocument } from './images'export async function cloudChecksum(bytes: Uint8Array): Promise<string> {const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))return fromUint8Array(new Uint8Array(digest))}-/** A revision's bytes from the object store, checked against what the server recorded. */-export async function downloadCloudRevision(- download: DocumentDownload,- objectFetch: (input: string, init: RequestInit) => Promise<Response>,- options: { signal?: AbortSignal; onProgress?: (progress: StorageTransferProgress) => void } = {}+type ObjectFetch = (input: string, init: RequestInit) => Promise<Response>+const IMAGE_DOWNLOAD_CONCURRENCY = 6++/** An object's bytes from the store, checked against the size and checksum the server recorded. */+async function fetchVerified(+ target: DocumentDownload['download'],+ expected: { byteSize: number; checksum: string },+ objectFetch: ObjectFetch,+ signal?: AbortSignal): Promise<Uint8Array> {- const response = await objectFetch(download.download.url, {- method: download.download.method,- headers: download.download.headers,- signal: options.signal+ const response = await objectFetch(target.url, {+ method: target.method,+ headers: target.headers,+ signal})if (!response.ok) throw new Error(`Cloud document download failed with HTTP ${response.status}`)const bytes = new Uint8Array(await response.arrayBuffer())if (- bytes.byteLength !== download.byteSize ||- (await cloudChecksum(bytes)) !== download.checksum+ bytes.byteLength !== expected.byteSize ||+ (await cloudChecksum(bytes)) !== expected.checksum) {throw new Error('The downloaded Cloud document does not match what the server stored')}- options.onProgress?.({ transferredBytes: bytes.byteLength, totalBytes: download.byteSize })return bytes}+/** A revision as the editor opens it: its stored file with every image put back under its name. */+export async function downloadCloudDocument(+ download: DocumentDownload,+ objectFetch: ObjectFetch,+ options: { signal?: AbortSignal; onProgress?: (progress: StorageTransferProgress) => void } = {}+): Promise<Uint8Array> {+ const totalBytes = download.byteSize + sumBy(download.images, (image) => image.byteSize)+ let transferredBytes = 0+ const received = (bytes: Uint8Array) => {+ transferredBytes += bytes.byteLength+ options.onProgress?.({ transferredBytes, totalBytes })+ return bytes+ }+ const semaphore = new Semaphore(IMAGE_DOWNLOAD_CONCURRENCY)+ const [lean, ...images] = await Promise.all([+ fetchVerified(download.download, download, objectFetch, options.signal).then(received),+ ...download.images.map(async (image) => {+ await semaphore.acquire()+ try {+ const bytes = await fetchVerified(image.download, image, objectFetch, options.signal)+ return { name: image.name, bytes: received(bytes) }+ } finally {+ semaphore.release()+ }+ })+ ])+ return assembleCloudDocument(lean, images)+}+/*** Reads exactly `length` bytes of a response, stopping a body that runs past them rather than* receiving the rest.diff --git a/src/app/integrations/storage/cloud/images.ts b/src/app/integrations/storage/cloud/images.tsnew file mode 100644index 000000000..4f0095728--- /dev/null+++ b/src/app/integrations/storage/cloud/images.ts@@ -0,0 +1,91 @@+import { Semaphore } from 'es-toolkit'+import { unzipSync, zipSync, type Zippable } from 'fflate'++import type { CloudAPIClient } from '@open-pencil/cloud/client'+import { CLOUD_IMAGE_NAME_PATTERN } from '@open-pencil/cloud/contract'++import { putCloudObject, type CloudObjectTransfer } from './upload'++/** Where a `.fig` archive keeps its images, each under the name its paints refer to. */+const IMAGE_ENTRY_PREFIX = 'images/'+const ZIP_SIGNATURE = [0x50, 0x4b, 0x03, 0x04]+const IMAGE_UPLOAD_CONCURRENCY = 4++/** An image a `.fig` archive holds, as Cloud stores it apart from the file. */+export type CloudDocumentImage = { name: string; bytes: Uint8Array }++function isZip(bytes: Uint8Array): boolean {+ return ZIP_SIGNATURE.every((byte, index) => bytes[index] === byte)+}++/**+ * The archive without its images, and the images. A file that is not a zip archive, or holds no+ * images, comes back whole; an image under a name Cloud does not store apart stays inside.+ */+export function splitCloudDocument(bytes: Uint8Array): {+ lean: Uint8Array+ images: CloudDocumentImage[]+} {+ if (!isZip(bytes)) return { lean: bytes, images: [] }+ const entries = unzipSync(bytes)+ const images: CloudDocumentImage[] = []+ const rest: Zippable = {}+ for (const [path, data] of Object.entries(entries)) {+ const name = path.startsWith(IMAGE_ENTRY_PREFIX) ? path.slice(IMAGE_ENTRY_PREFIX.length) : null+ // An empty image, or one under a name Cloud does not take, stays inside the file.+ if (name && CLOUD_IMAGE_NAME_PATTERN.test(name) && data.byteLength > 0) {+ images.push({ name, bytes: data })+ } else rest[path] = [data, { level: 0 }]+ }+ return images.length === 0 ? { lean: bytes, images } : { lean: zipSync(rest), images }+}++/** The archive with its images put back under their names; the lean archive when there are none. */+export function assembleCloudDocument(lean: Uint8Array, images: CloudDocumentImage[]): Uint8Array {+ if (images.length === 0) return lean+ const entries: Zippable = {}+ for (const [path, data] of Object.entries(unzipSync(lean))) entries[path] = [data, { level: 0 }]+ for (const image of images) {+ entries[`${IMAGE_ENTRY_PREFIX}${image.name}`] = [image.bytes, { level: 0 }]+ }+ return zipSync(entries)+}++/**+ * Uploads the images the document's workspace lacks: the server answers with uploads for those+ * only, and they are committed together once their bytes are in place.+ */+export async function uploadCloudImages(input: {+ cloud: Pick<CloudAPIClient, 'requestImageUploads' | 'commitImageUploads'>+ documentId: string+ images: { checksum: string; bytes: Uint8Array }[]+ objectFetch: CloudObjectTransfer['objectFetch']+ signal?: AbortSignal+}): Promise<void> {+ if (input.images.length === 0) return+ const byChecksum = new Map(input.images.map((image) => [image.checksum, image.bytes]))+ const offers = await input.cloud.requestImageUploads(input.documentId, {+ images: [...byChecksum].map(([checksum, bytes]) => ({ checksum, byteSize: bytes.byteLength }))+ })+ if (offers.length === 0) return+ const semaphore = new Semaphore(IMAGE_UPLOAD_CONCURRENCY)+ const uploaded = await Promise.all(+ offers.map(async (offer) => {+ const bytes = byChecksum.get(offer.checksum)+ if (!bytes) throw new Error('The server offered an upload for an image this save lacks')+ await semaphore.acquire()+ try {+ const multipart = await putCloudObject(offer.upload, {+ bytes,+ objectFetch: input.objectFetch,+ signal: input.signal+ })+ return { uploadId: offer.uploadId, checksum: offer.checksum, multipart }+ } finally {+ semaphore.release()+ }+ })+ )+ // One commit for every image, however many a save adds.+ await input.cloud.commitImageUploads(input.documentId, uploaded)+}diff --git a/src/app/integrations/storage/cloud/upload.ts b/src/app/integrations/storage/cloud/upload.tsindex 27c1fb4f0..607175d9a 100644--- a/src/app/integrations/storage/cloud/upload.ts+++ b/src/app/integrations/storage/cloud/upload.ts@@ -1,6 +1,7 @@import { retry, Semaphore } from 'es-toolkit'-import type { CloudAPIClient, CloudUpload } from '@open-pencil/cloud/client'+import type { CloudAPIClient } from '@open-pencil/cloud/client'+import type { ObjectUploadTarget } from '@open-pencil/cloud/contract'import type { StorageTransferProgress } from '../types'@@ -9,22 +10,32 @@ const PART_RETRIES = 2const RETRY_DELAY_MS = 200type ObjectFetch = (input: string, init: RequestInit) => Promise<Response>-type MultipartUpload = Extract<CloudUpload['upload'], { kind: 'multipart' }>+type MultipartUpload = Extract<ObjectUploadTarget, { kind: 'multipart' }>-export type CloudObjectUpload = {- cloud: Pick<CloudAPIClient, 'createUpload'>- documentId: string+/** Bytes on their way to the object store, and how to report and stop the transfer. */+export type CloudObjectTransfer = {bytes: Uint8Array- checksum: string- baseRevision: string | nullobjectFetch: ObjectFetchonProgress?: (progress: StorageTransferProgress) => voidsignal?: AbortSignal}+export type CloudObjectUpload = CloudObjectTransfer & {+ cloud: Pick<CloudAPIClient, 'createUpload'>+ documentId: string+ checksum: string+ baseRevision: string | null+}++/** The parts a multipart upload's commit names. */+export type CloudMultipartCommit = {+ uploadId: string+ parts: { partNumber: number; etag: string }[]+}+export type CloudObjectUploadResult = {uploadId: string- multipart?: { uploadId: string; parts: { partNumber: number; etag: string }[] }+ multipart?: CloudMultipartCommit}/** An object-store request the presigned URL refused or the store failed. */@@ -46,12 +57,12 @@ function body(bytes: Uint8Array): Uint8Array<ArrayBuffer> {: Uint8Array.from(bytes)}-function report(upload: CloudObjectUpload, transferredBytes: number): void {+function report(upload: CloudObjectTransfer, transferredBytes: number): void {upload.onProgress?.({ transferredBytes, totalBytes: upload.bytes.byteLength })}async function putPart(- upload: CloudObjectUpload,+ upload: CloudObjectTransfer,part: MultipartUpload['parts'][number],bytes: Uint8Array,signal: AbortSignal@@ -78,7 +89,7 @@ async function putPart()}-async function putParts(upload: CloudObjectUpload, multipart: MultipartUpload) {+async function putParts(upload: CloudObjectTransfer, multipart: MultipartUpload) {const controller = new AbortController()const stop = () => controller.abort(upload.signal?.reason)upload.signal?.addEventListener('abort', stop, { once: true })@@ -110,27 +121,39 @@ async function putParts(upload: CloudObjectUpload, multipart: MultipartUpload) {}}-async function transfer(upload: CloudObjectUpload): Promise<CloudObjectUploadResult> {- const pending = await upload.cloud.createUpload(upload.documentId, {- baseRevisionId: upload.baseRevision,- byteSize: upload.bytes.byteLength,- checksum: upload.checksum,- contentType: 'application/octet-stream'- })+/**+ * Puts bytes where the server said, in parallel parts for a multipart upload. What a commit names+ * of a multipart upload, or nothing for a single one.+ */+export async function putCloudObject(+ target: ObjectUploadTarget,+ upload: CloudObjectTransfer+): Promise<CloudMultipartCommit | undefined> {report(upload, 0)- if (pending.upload.kind === 'single') {- const response = await upload.objectFetch(pending.upload.url, {- method: pending.upload.method,- headers: pending.upload.headers,+ if (target.kind === 'single') {+ const response = await upload.objectFetch(target.url, {+ method: target.method,+ headers: target.headers,body: body(upload.bytes),signal: upload.signal})if (!response.ok) throw new ObjectUploadError(response.status)report(upload, upload.bytes.byteLength)- return { uploadId: pending.id }+ return undefined}- const parts = await putParts(upload, pending.upload)- return { uploadId: pending.id, multipart: { uploadId: pending.upload.uploadId, parts } }+ const parts = await putParts(upload, target)+ return { uploadId: target.uploadId, parts }+}++async function transfer(upload: CloudObjectUpload): Promise<CloudObjectUploadResult> {+ const pending = await upload.cloud.createUpload(upload.documentId, {+ baseRevisionId: upload.baseRevision,+ byteSize: upload.bytes.byteLength,+ checksum: upload.checksum,+ contentType: 'application/octet-stream'+ })+ const multipart = await putCloudObject(pending.upload, upload)+ return multipart ? { uploadId: pending.id, multipart } : { uploadId: pending.id }}/**diff --git a/tests/app/integrations/storage/cloud/adapter.test.ts b/tests/app/integrations/storage/cloud/adapter.test.tsindex e54a52629..1379786aa 100644--- a/tests/app/integrations/storage/cloud/adapter.test.ts+++ b/tests/app/integrations/storage/cloud/adapter.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'import { readFileSync } from 'node:fs'+import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate'import { fromUint8Array } from 'js-base64'import { createCloudAPIClient } from '@open-pencil/cloud/client'@@ -18,7 +19,14 @@ async function sha256(bytes: Uint8Array): Promise<string> {/** Just enough of a Cloud server and its object store to save and open documents. */function cloudServer() {- type Doc = { name: string; revision: string | null; version: number; checksum?: string }+ type Image = { name: string; checksum: string }+ type Doc = {+ name: string+ revision: string | null+ version: number+ checksum?: string+ images?: Image[]+ }const documents = new Map<string, Doc>()const objects = new Map<string, Uint8Array>()let fullReads = 0@@ -28,7 +36,10 @@ function cloudServer() {* than asked and no `Content-Range` to tell, or with another range than asked.*/let ranges: 'honored' | 'ignored' | 'oversized' | 'short' | 'other' = 'honored'- const uploads = new Map<string, { documentId: string; base: string | null }>()+ const uploads = new Map<string, { documentId: string; base: string | null; image?: string }>()+ /** The workspace's images by checksum, as the object key their upload put them under. */+ const images = new Map<string, string>()+ const imageUploads: string[] = []const summary = (id: string, doc: Doc) => ({id,workspaceId: WORKSPACE,@@ -82,6 +93,47 @@ function cloudServer() {return json({ id, upload: { ...upload, expiresAt: '2030-01-01T00:00:00.000Z' } }, 201)}],+ [+ 'POST',+ /^\/documents\/([^/]+)\/images$/,+ ([, documentId = ''], body) => {+ const requested = Array.isArray(body.images) ? body.images : []+ const offers = requested.flatMap((image: { checksum: string }) => {+ if (images.has(image.checksum)) return []+ const uploadId = crypto.randomUUID()+ uploads.set(uploadId, { documentId, base: null, image: image.checksum })+ imageUploads.push(image.checksum)+ return [+ {+ checksum: image.checksum,+ uploadId,+ upload: {+ kind: 'single',+ url: `https://objects.test/${uploadId}`,+ method: 'PUT',+ headers: {},+ expiresAt: '2030-01-01T00:00:00.000Z'+ }+ }+ ]+ })+ return json({ uploads: offers }, 201)+ }+ ],+ [+ 'POST',+ /^\/documents\/([^/]+)\/images\/commit$/,+ (_match, body) => {+ const committed = (Array.isArray(body.uploads) ? body.uploads : []) as {+ uploadId: string+ }[]+ for (const { uploadId } of committed) {+ const image = uploads.get(uploadId)?.image+ if (image) images.set(image, uploadId)+ }+ return new Response(null, { status: 204 })+ }+ ],['POST',/^\/uploads\/([^/]+)\/commit$/,@@ -89,10 +141,19 @@ function cloudServer() {const upload = uploads.get(uploadId)const doc = upload ? documents.get(upload.documentId) : undefinedif (!upload || !doc) return json({ error: { code: 'not_found' } }, 404)+ const named = (Array.isArray(body.images) ? body.images : []) as Image[]+ if (named.some((image) => !images.has(image.checksum))) {+ return json({ error: { code: 'invalid_upload' } }, 422)+ }if (doc.revision !== upload.base) return json({ error: { code: 'revision_conflict' } }, 409)const revision = crypto.randomUUID()objects.set(revision, objects.get(uploadId) ?? new Uint8Array())- Object.assign(doc, { revision, version: doc.version + 1, checksum: String(body.checksum) })+ Object.assign(doc, {+ revision,+ version: doc.version + 1,+ checksum: String(body.checksum),+ images: named+ })return json({ document: summary(upload.documentId, doc) })}],@@ -111,7 +172,20 @@ function cloudServer() {byteSize: bytes.byteLength,checksum: doc.checksum ?? (await sha256(bytes)),contentType: 'application/octet-stream',- download: { ...download, expiresAt: '2030-01-01T00:00:00.000Z' }+ download: { ...download, expiresAt: '2030-01-01T00:00:00.000Z' },+ images: (doc.images ?? []).map((image) => {+ const key = images.get(image.checksum) ?? ''+ return {+ ...image,+ byteSize: objects.get(key)?.byteLength ?? 0,+ download: {+ url: `https://objects.test/${key}`,+ method: 'GET',+ headers: {},+ expiresAt: '2030-01-01T00:00:00.000Z'+ }+ }+ })}})}@@ -190,6 +264,8 @@ function cloudServer() {objectFetch,saveElsewhere,objects,+ /** The checksums of every image an upload was offered for. */+ imageUploads,fullReads: () => fullReads,cancelledReads: () => cancelledReads,answerRanges(answer: typeof ranges) {@@ -226,6 +302,45 @@ describe('Cloud storage adapter', () => {expect(opened.revision).toBe(saved.revision)})+ test('stores a file without its images, uploads only images it lacks, and opens it whole', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const photo = crypto.getRandomValues(new Uint8Array(4096))+ const logo = crypto.getRandomValues(new Uint8Array(512))+ const archive = (pages: string) =>+ zipSync({+ 'canvas.fig': strToU8(pages),+ 'meta.json': strToU8('{}'),+ 'images/a1b2': photo,+ 'images/c3d4': logo,+ // Cloud stores apart only names it accepts; this one stays inside the file.+ 'images/old name.png': logo,+ // Nor does an empty image, which the server refuses to store.+ 'images/e5f6': new Uint8Array()+ })+ const first = crypto.randomUUID()+ const saved = await storage.putDocument(first, archive('first'), { name: 'A', updatedAt: '' })+ const stored = saved.revision ? server.objects.get(saved.revision) : undefined+ if (!stored) throw new Error('Expected the stored file')+ expect(Object.keys(unzipSync(stored)).sort()).toEqual([+ 'canvas.fig',+ 'images/e5f6',+ 'images/old name.png',+ 'meta.json'+ ])+ expect(server.imageUploads).toHaveLength(2)++ // Another document with the same images uploads neither.+ await storage.putDocument(crypto.randomUUID(), archive('second'), { name: 'B', updatedAt: '' })+ expect(server.imageUploads).toHaveLength(2)++ const opened = unzipSync((await storage.getDocument(first)).bytes)+ expect(strFromU8(opened['canvas.fig'] ?? new Uint8Array())).toBe('first')+ expect(opened['images/a1b2']).toEqual(photo)+ expect(opened['images/c3d4']).toEqual(logo)+ expect(opened['images/old name.png']).toEqual(logo)+ })+test('saves on top of the revision it was edited from', async () => {const server = cloudServer()const storage = adapter(server)