Skip to content

AI-native design editor. Open-source Figma alternative.

feat(cloud): name images in live rooms instead of carrying their bytes (#1350)

Danila Poyarkov608de7820bac
diff --git a/packages/cloud/src/client/api.ts b/packages/cloud/src/client/api.ts
index 33b9e7899..49d0a5b75 100644
--- a/packages/cloud/src/client/api.ts
+++ b/packages/cloud/src/client/api.ts
@@ -7,7 +7,6 @@ import {
createInvitationContinuationSchema,
documentAccessSchema,
documentDownloadSchema,
- imageUploadOfferSchema,
objectUploadSchema,
documentGrantSchema,
documentInvitationSchema,
@@ -27,9 +26,7 @@ import {
type CollaborationTicket,
type CreateInvitationContinuationInput,
type InvitationContinuation,
- type CommitImageUploadsInput,
type CommitUploadRequest,
- type RequestImageUploadsInput,
type CreateDocumentInput,
type CreateDocumentInvitationInput,
type CreateDocumentShareInput,
@@ -40,7 +37,6 @@ import {
type DocumentInvitation,
type DocumentShare,
type DocumentSummary,
- type ImageUploadOffer,
type DocumentVersion,
type DocumentVersionDownload,
type DocumentVersions,
@@ -60,6 +56,7 @@ import { pickBy } from 'es-toolkit/object'
import { hc } from 'hono/client'
import * as v from 'valibot'
+import { createImageRequests } from './images'
import { CloudAPIError, parseResponse, responseBody, type CloudClientDiagnostic } from './response'
import { createWorkspaceRequests } from './workspaces'
@@ -97,7 +94,6 @@ const uploadResponseSchema = v.object({
id: v.pipe(v.string(), v.uuid()),
upload: objectUploadSchema
})
-const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) })
export type CloudRequestOptions = {
fetch?: CloudFetch
@@ -164,6 +160,7 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
return response.user
},
...createWorkspaceRequests(client, options.onDiagnostic),
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
/** Documents shared with the person directly, outside their workspaces. */
async listSharedDocuments(): Promise<SharedDocument[]> {
const response = await parseResponse(
@@ -428,32 +425,6 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
options.onDiagnostic
)
},
- /** 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({
diff --git a/packages/cloud/src/client/images.ts b/packages/cloud/src/client/images.ts
new file mode 100644
index 000000000..8e9a68fba
--- /dev/null
+++ b/packages/cloud/src/client/images.ts
@@ -0,0 +1,81 @@
+import {
+ documentImageLinkSchema,
+ imageUploadOfferSchema,
+ type CommitImageUploadsInput,
+ type DocumentImageLink,
+ type ImageUploadOffer,
+ type RequestImageUploadsInput,
+ type ResolveDocumentShareInput
+} from '#cloud/contract'
+import type { CloudAPI, PublicCloudAPI } from '#cloud/server/api'
+import type { hc } from 'hono/client'
+import * as v from 'valibot'
+
+import { parseResponse, responseBody, type CloudClientDiagnostic } from './response'
+
+const imageLinksResponseSchema = v.object({ images: v.array(documentImageLinkSchema) })
+const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) })
+
+/** The images a save uploads apart from the document, and the links a live room loads them by. */
+export function createImageRequests(
+ client: ReturnType<typeof hc<CloudAPI>>,
+ publicClient: ReturnType<typeof hc<PublicCloudAPI>>,
+ onDiagnostic?: CloudClientDiagnostic
+) {
+ return {
+ /** 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,
+ onDiagnostic
+ )
+ return response.uploads
+ },
+ /** 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, onDiagnostic)
+ },
+ /** Links for images a document's live room names. */
+ async getImageLinks(documentId: string, checksums: string[]): Promise<DocumentImageLink[]> {
+ const response = await parseResponse(
+ client.documents[':documentId'].images.links.$post({
+ param: { documentId },
+ json: { checksums }
+ }),
+ imageLinksResponseSchema,
+ onDiagnostic
+ )
+ return response.images
+ },
+ /** Links for images a shared document's live room names, as the share's guest. */
+ async getSharedImageLinks(
+ shareId: string,
+ input: ResolveDocumentShareInput,
+ checksums: string[]
+ ): Promise<DocumentImageLink[]> {
+ const response = await parseResponse(
+ publicClient.shares[':shareId'].images.$post({
+ param: { shareId },
+ json: { ...input, checksums }
+ }),
+ imageLinksResponseSchema,
+ onDiagnostic
+ )
+ return response.images
+ }
+ }
+}
diff --git a/packages/cloud/src/contract/documents.ts b/packages/cloud/src/contract/documents.ts
index 4a02fe8dd..26c6edfe3 100644
--- a/packages/cloud/src/contract/documents.ts
+++ b/packages/cloud/src/contract/documents.ts
@@ -4,6 +4,11 @@ export const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/))
+/** Whether a value is a SHA-256 checksum as the server names stored objects, base64 encoded. */
+export function isCloudChecksum(value: string): boolean {
+ return v.is(checksumSchema, value)
+}
+
/** The most images one revision, or one request for image uploads, may name. */
export const CLOUD_MAX_DOCUMENT_IMAGES = 10_000
@@ -30,6 +35,20 @@ export const documentImageDownloadSchema = v.object({
})
export type DocumentImageDownload = v.InferOutput<typeof documentImageDownloadSchema>
+/** Where to download an image a document uses, found by its checksum. */
+export const documentImageLinkSchema = v.object({
+ checksum: checksumSchema,
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ download: objectDownloadSchema
+})
+export type DocumentImageLink = v.InferOutput<typeof documentImageLinkSchema>
+
+/** The images a live room names, by checksum, that a peer needs links for. */
+export const requestImageLinksSchema = v.object({
+ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
+})
+export type RequestImageLinksInput = v.InferOutput<typeof requestImageLinksSchema>
+
export const documentPermissionSchema = v.picklist(['view', 'edit'])
export type DocumentPermission = v.InferOutput<typeof documentPermissionSchema>
@@ -221,6 +240,10 @@ export function parseCommitImageUploads(input: unknown): CommitImageUploadsInput
return v.parse(commitImageUploadsSchema, input)
}
+export function parseRequestImageLinks(input: unknown): RequestImageLinksInput {
+ return v.parse(requestImageLinksSchema, 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.ts
index d071d2fbf..42d332afa 100644
--- a/packages/cloud/src/contract/index.ts
+++ b/packages/cloud/src/contract/index.ts
@@ -71,6 +71,7 @@ export {
documentAccessSourceSchema,
documentDownloadSchema,
documentImageDownloadSchema,
+ documentImageLinkSchema,
documentPermissionSchema,
imageUploadOfferSchema,
objectUploadSchema,
@@ -78,11 +79,14 @@ export {
sharedDocumentSchema,
type SharedDocument,
workspaceUsageSchema,
+ isCloudChecksum,
parseCommitImageUploads,
parseCommitUpload,
parseCreateDocument,
parseCreateUpload,
+ parseRequestImageLinks,
parseRequestImageUploads,
+ requestImageLinksSchema,
requestImageUploadsSchema,
type CloudActorContract,
type CloudSession,
@@ -95,8 +99,10 @@ export {
type DocumentAccessSource,
type DocumentDownload,
type DocumentImageDownload,
+ type DocumentImageLink,
type DocumentPermission,
type DocumentSummary,
+ type RequestImageLinksInput,
type ImageUploadOffer,
type ObjectUploadTarget,
type RequestImageUploadsInput,
@@ -121,9 +127,11 @@ export {
parseCreateDocumentShare,
parseLookupCloudUser,
parsePutDocumentGrant,
+ parseRequestSharedImageLinks,
parseResolveDocumentShare,
parseUpdateDocumentShare,
putDocumentGrantSchema,
+ requestSharedImageLinksSchema,
resolveDocumentShareSchema,
resolvedDocumentShareSchema,
updateDocumentShareSchema,
@@ -140,6 +148,7 @@ export {
type InvitationPreview,
type LookupCloudUserInput,
type PutDocumentGrantInput,
+ type RequestSharedImageLinksInput,
type ResolveDocumentShareInput,
type ResolvedDocumentShare,
type UpdateDocumentShareInput
diff --git a/packages/cloud/src/contract/sharing.ts b/packages/cloud/src/contract/sharing.ts
index 0905c847c..ed2394f26 100644
--- a/packages/cloud/src/contract/sharing.ts
+++ b/packages/cloud/src/contract/sharing.ts
@@ -1,7 +1,7 @@
import * as v from 'valibot'
import { collaborationPrincipalSchema } from './collaboration'
-import { documentPermissionSchema } from './documents'
+import { documentPermissionSchema, requestImageLinksSchema } from './documents'
import { workspaceRoleSchema } from './workspaces'
export const documentShareSchema = v.object({
@@ -40,6 +40,17 @@ export const resolveDocumentShareSchema = v.object({
})
export type ResolveDocumentShareInput = v.InferOutput<typeof resolveDocumentShareSchema>
+/** A guest's request for the links of images a shared document's live room names. */
+export const requestSharedImageLinksSchema = v.object({
+ ...resolveDocumentShareSchema.entries,
+ ...requestImageLinksSchema.entries
+})
+export type RequestSharedImageLinksInput = v.InferOutput<typeof requestSharedImageLinksSchema>
+
+export function parseRequestSharedImageLinks(input: unknown): RequestSharedImageLinksInput {
+ return v.parse(requestSharedImageLinksSchema, input)
+}
+
export const resolvedDocumentShareSchema = v.object({
documentId: v.pipe(v.string(), v.uuid()),
permission: documentPermissionSchema,
diff --git a/packages/cloud/src/server/documents/images.ts b/packages/cloud/src/server/documents/images.ts
index c6a90eb4c..a18c431d8 100644
--- a/packages/cloud/src/server/documents/images.ts
+++ b/packages/cloud/src/server/documents/images.ts
@@ -1,6 +1,7 @@
import type {
CommitUploadInput,
DocumentImageDownload,
+ DocumentImageLink,
ImageUploadOffer,
RequestImageUploadsInput
} from '#cloud/contract'
@@ -27,6 +28,36 @@ export function createDocumentImages(
objects: ObjectStore,
quota: StorageQuotaService
) {
+ /**
+ * Gives up uploads a request reserved when it could not offer them all, so a retry is not
+ * refused for space they hold. A multipart upload the store began is aborted first; one that
+ * cannot be stays pending for cleanup, which aborts it once it expires.
+ */
+ async function abandonUploads(
+ uploads: readonly { uploadId: string; objectKey: string }[],
+ offers: readonly ImageUploadOffer[]
+ ): Promise<void> {
+ const begun = new Map(offers.map((offer) => [offer.uploadId, offer.upload]))
+ for (const { uploadId, objectKey } of uploads) {
+ try {
+ const upload = begun.get(uploadId)
+ if (upload?.kind === 'multipart') {
+ await objects.abortUpload({ key: objectKey, uploadId: upload.uploadId })
+ }
+ await quota.release(uploadId)
+ await database
+ .updateTable('upload')
+ .set({ status: 'abandoned' })
+ .where('id', '=', uploadId)
+ .where('status', '=', 'pending')
+ .execute()
+ } catch (error) {
+ // Cleanup releases it once it expires.
+ console.warn('Giving up an image upload failed', error)
+ }
+ }
+ }
+
return {
/**
* Uploads for the images of `input` the workspace lacks, each with its own object key and
@@ -99,22 +130,27 @@ export function createDocumentImages(
}
})
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()
+ try {
+ 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
+ })
+ offers.push({ checksum: image.checksum, uploadId: image.uploadId, upload })
+ 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 })
+ } catch (error) {
+ await abandonUploads(missing, offers)
+ throw error
}
return offers
},
@@ -310,3 +346,62 @@ export async function releaseUnusedImages(
return { released: unused.length, bytes }
})
}
+
+/**
+ * Where to download the images of `checksums` the document's workspace holds, for someone who may
+ * view the document. A live room names images by checksum before any save does, and an editor
+ * whose image the workspace already holds through another document uploads nothing for this one,
+ * so the workspace, not the document, is what an image belongs to. Asking needs the image's
+ * SHA-256, which only someone with its bytes has.
+ */
+export async function documentImageLinks(
+ executor: Executor,
+ objects: ObjectStore,
+ input: { documentId: string; checksums: string[]; expiresAt: Date }
+): Promise<DocumentImageLink[]> {
+ const rows = await executor
+ .selectFrom('workspaceImage')
+ .innerJoin('document', 'document.workspaceId', 'workspaceImage.workspaceId')
+ .innerJoin('storageObject', 'storageObject.id', 'workspaceImage.storageObjectId')
+ .select(['workspaceImage.checksum', 'storageObject.objectKey', 'storageObject.byteSize'])
+ .where('document.id', '=', input.documentId)
+ .where('workspaceImage.checksum', 'in', uniq(input.checksums))
+ .execute()
+ return Promise.all(
+ rows.map(async (row) => ({
+ checksum: row.checksum,
+ byteSize: Number(row.byteSize),
+ download: await objects.createDownload({ key: row.objectKey, expiresAt: input.expiresAt })
+ }))
+ )
+}
+
+/** The images the workspace's current revisions use, each counted once however many use it. */
+export async function currentImageUsage(
+ executor: Executor,
+ workspaceId: string
+): Promise<{ objectCount: number; bytesUsed: number }> {
+ const usage = await executor
+ .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 { objectCount: Number(usage.objectCount), bytesUsed: Number(usage.bytesUsed) }
+}
diff --git a/packages/cloud/src/server/documents/routes.ts b/packages/cloud/src/server/documents/routes.ts
index d93f1d1ad..4b00592e3 100644
--- a/packages/cloud/src/server/documents/routes.ts
+++ b/packages/cloud/src/server/documents/routes.ts
@@ -3,6 +3,7 @@ import {
parseCommitUpload,
parseCreateDocument,
parseCreateUpload,
+ parseRequestImageLinks,
parseRequestImageUploads
} from '#cloud/contract'
import type { CloudActor } from '#cloud/server/auth'
@@ -198,6 +199,17 @@ export function createDocumentRoutes(
return context.body(null, 204)
})
)
+ .post('/documents/:documentId/images/links', validatedJSON(parseRequestImageLinks), (context) =>
+ documentResponse(context, async () =>
+ context.json(
+ await service.imageLinks(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json').checksums
+ )
+ )
+ )
+ )
.post('/documents/:documentId/images', validatedJSON(parseRequestImageUploads), (context) =>
documentResponse(context, async () =>
context.json(
diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.ts
index 73b383151..7969c02be 100644
--- a/packages/cloud/src/server/documents/service.ts
+++ b/packages/cloud/src/server/documents/service.ts
@@ -22,7 +22,12 @@ import {
DocumentNotFoundError,
UploadInvalidError
} from '#cloud/server/documents/errors'
-import { createDocumentImages, revisionImageDownloads } from '#cloud/server/documents/images'
+import {
+ createDocumentImages,
+ currentImageUsage,
+ documentImageLinks,
+ revisionImageDownloads
+} from '#cloud/server/documents/images'
import { writableDocument } from '#cloud/server/documents/limits'
import {
findDocument,
@@ -37,7 +42,7 @@ import { announceVersions, recordCheckpoint } from '#cloud/server/documents/vers
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 { limitAsync, uniq, uniqBy } from 'es-toolkit'
import type { Kysely, Transaction } from 'kysely'
const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
@@ -170,6 +175,14 @@ export function createDocumentService(
return checkpointed
}
+ /** Links for images a live room names, by checksum. */
+ async function imageLinksOf(documentId: string, checksums: string[]) {
+ const expiresAt = new Date(Date.now() + DOWNLOAD_LIFETIME_MS)
+ return {
+ images: await documentImageLinks(database, objects, { documentId, checksums, expiresAt })
+ }
+ }
+
async function createDownload(documentId: string): Promise<DocumentDownload> {
const row = await getDocumentSummaryRow(database, documentId)
if (!row?.currentRevisionId) throw new DocumentNotFoundError()
@@ -358,32 +371,10 @@ 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()
+ const shared = await currentImageUsage(database, workspaceId)
return {
- bytesUsed: Number(result.bytesUsed) + Number(shared.bytesUsed),
- objectCount: Number(result.objectCount) + Number(shared.objectCount),
+ bytesUsed: Number(result.bytesUsed) + shared.bytesUsed,
+ objectCount: Number(result.objectCount) + shared.objectCount,
documentCount: Number(result.documentCount)
}
},
@@ -398,6 +389,18 @@ export function createDocumentService(
return createDownload(documentId)
},
+ /** Links for images a live room names, for someone who may view the document. */
+ async imageLinks(userId: string, documentId: string, checksums: string[]) {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ return imageLinksOf(documentId, checksums)
+ },
+
+ /** Links for images a live room names, for a guest a share already let in. */
+ imageLinksShared(documentId: string, checksums: string[]) {
+ return imageLinksOf(documentId, checksums)
+ },
+
async download(userId: string, documentId: string): Promise<DocumentDownload> {
const access = await resolveDocumentAccess(database, userId, documentId)
if (!access) throw new DocumentNotFoundError()
@@ -566,18 +569,16 @@ export function createDocumentService(
}
// 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)
+ const land = limitAsync(
+ (upload: UploadRow, multipart: CommitUploadInput['multipart']) =>
+ finalizeUpload(upload, multipart, (stored) => landImage(upload, stored)),
+ 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()
- }
+ if (upload.status !== 'committed') await land(upload, commit.multipart)
})
)
}
diff --git a/packages/cloud/src/server/sharing/document-routes.ts b/packages/cloud/src/server/sharing/document-routes.ts
index 440e60330..a31ab7678 100644
--- a/packages/cloud/src/server/sharing/document-routes.ts
+++ b/packages/cloud/src/server/sharing/document-routes.ts
@@ -1,4 +1,4 @@
-import { parseResolveDocumentShare } from '#cloud/contract'
+import { parseRequestSharedImageLinks, parseResolveDocumentShare } from '#cloud/contract'
import type { DocumentService } from '#cloud/server/documents'
import type { DocumentSharingService } from '#cloud/server/sharing'
import { sharingRoute } from '#cloud/server/sharing/http'
@@ -9,10 +9,8 @@ export function createPublicDocumentRoutes(
sharing: DocumentSharingService,
documents: DocumentService
) {
- return new Hono().post(
- '/shares/:shareId/document',
- validatedJSON(parseResolveDocumentShare),
- (context) =>
+ return new Hono()
+ .post('/shares/:shareId/document', validatedJSON(parseResolveDocumentShare), (context) =>
sharingRoute(context, async () => {
const resolution = await sharing.resolveShare(
context.req.param('shareId'),
@@ -23,5 +21,12 @@ export function createPublicDocumentRoutes(
document: await documents.downloadShared(resolution.documentId)
})
})
- )
+ )
+ .post('/shares/:shareId/images', validatedJSON(parseRequestSharedImageLinks), (context) =>
+ sharingRoute(context, async () => {
+ const { checksums, ...share } = context.req.valid('json')
+ const resolution = await sharing.resolveShare(context.req.param('shareId'), share)
+ return context.json(await documents.imageLinksShared(resolution.documentId, checksums))
+ })
+ )
}
diff --git a/packages/cloud/tests/integration/server/documents/images.test.ts b/packages/cloud/tests/integration/server/documents/images.test.ts
index 118cdd72d..9cbd10100 100644
--- a/packages/cloud/tests/integration/server/documents/images.test.ts
+++ b/packages/cloud/tests/integration/server/documents/images.test.ts
@@ -4,10 +4,14 @@ import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
import { responseJSON } from '#cloud-tests/helpers/response'
import {
+ CLOUD_FEATURE_KEYS,
createBetterAuthAdapter,
createCloudApp,
+ createDefaultCloudPolicy,
createRevisionCompactionService,
+ EntitlementOpenFeatureProvider,
parseCloudServerConfig,
+ StaticEntitlementSource,
type CloudActor
} from '#cloud/server'
import * as v from 'valibot'
@@ -62,6 +66,15 @@ async function testApp() {
database: runtime.database,
auth: createBetterAuthAdapter(config, runtime.database),
objects: objects.store,
+ // Guests reach a document through its share links.
+ policy: createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ new StaticEntitlementSource({
+ [CLOUD_FEATURE_KEYS.capabilityLinks]: true,
+ [CLOUD_FEATURE_KEYS.anonymousView]: true
+ })
+ )
+ ),
resolveSession: async () => alice
})
const request = (path: string, init: { method?: string; json?: unknown } = {}) =>
@@ -178,7 +191,39 @@ async function testApp() {
}
}
- return { runtime, objects, request, documentId, uploadImages, save, download, usage, age }
+ /** Links for images the document's live room names, as its people ask for them. */
+ async function links(checksums: string[], document = documentId) {
+ return responseJSON(
+ await request(`/documents/${document}/images/links`, { method: 'POST', json: { checksums } }),
+ v.object({ images: v.array(v.object({ checksum: v.string(), byteSize: v.number() })) })
+ )
+ }
+
+ /** Another document in the same workspace. */
+ async function createDocument(name: string) {
+ const created = await responseJSON(
+ await request(`/workspaces/${workspace.workspace.id}/documents`, {
+ method: 'POST',
+ json: { name }
+ }),
+ documentSchema
+ )
+ return created.document.id
+ }
+
+ return {
+ runtime,
+ objects,
+ request,
+ documentId,
+ uploadImages,
+ save,
+ download,
+ usage,
+ age,
+ links,
+ createDocument
+ }
}
const photo: Image = { name: '0a1b', checksum: checksumOf('P'), byteSize: 1000 }
@@ -208,6 +253,41 @@ describe('Cloud document images', () => {
}
})
+ test('gives back what an image request reserved when the store cannot take every upload', async () => {
+ const context = await testApp()
+ const createUpload = context.objects.store.createUpload.bind(context.objects.store)
+ let calls = 0
+ context.objects.store.createUpload = async (input) => {
+ calls++
+ if (calls === 2) throw new Error('object store unavailable')
+ return createUpload(input)
+ }
+ try {
+ const response = await context.request(`/documents/${context.documentId}/images`, {
+ method: 'POST',
+ json: { images: [photo, logo].map(({ checksum, byteSize }) => ({ checksum, byteSize })) }
+ })
+ expect(response.status).toBe(500)
+ const uploads = await context.runtime.database
+ .selectFrom('upload')
+ .select('status')
+ .where('kind', '=', 'image')
+ .execute()
+ expect(uploads.map((upload) => upload.status)).toEqual(['abandoned', 'abandoned'])
+ const held = await context.runtime.database
+ .selectFrom('uploadStorageReservation')
+ .select('id')
+ .where('releasedAt', 'is', null)
+ .execute()
+ expect(held).toHaveLength(0)
+
+ // The retry gets both again.
+ expect(await context.uploadImages([photo, logo])).toHaveLength(2)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
test('refuses a save that names an image the workspace does not hold', async () => {
const context = await testApp()
try {
@@ -291,4 +371,41 @@ describe('Cloud document images', () => {
await context.runtime.close()
}
})
+
+ test("links the images the workspace holds, for a document's people and its guests", async () => {
+ const context = await testApp()
+ try {
+ // Uploaded for the document's live room, not saved yet; the workspace lacks the logo.
+ await context.uploadImages([photo])
+ expect((await context.links([photo.checksum, logo.checksum])).images).toEqual([
+ expect.objectContaining({ checksum: photo.checksum, byteSize: photo.byteSize })
+ ])
+
+ // Another document's room names an image the workspace holds through the first one.
+ const other = await context.createDocument('Flyer')
+ expect((await context.links([photo.checksum], other)).images).toHaveLength(1)
+
+ const created = await context.request(`/documents/${context.documentId}/shares`, {
+ method: 'POST',
+ json: { permission: 'view' }
+ })
+ const share = await responseJSON(
+ created,
+ v.object({ share: v.object({ id: v.string() }), secret: v.string() })
+ )
+ const guest = await context.request(`/shares/${share.share.id}/images`, {
+ method: 'POST',
+ json: { secret: share.secret, checksums: [photo.checksum] }
+ })
+ expect(guest.status).toBe(200)
+ expect(await guest.json()).toMatchObject({ images: [{ checksum: photo.checksum }] })
+ const wrongSecret = await context.request(`/shares/${share.share.id}/images`, {
+ method: 'POST',
+ json: { secret: 'f'.repeat(48), checksums: [photo.checksum] }
+ })
+ expect(wrongSecret.status).toBeGreaterThanOrEqual(400)
+ } finally {
+ await context.runtime.close()
+ }
+ })
})
diff --git a/packages/cloud/tests/server/api/router.test.ts b/packages/cloud/tests/server/api/router.test.ts
index dadfe7410..8931e8763 100644
--- a/packages/cloud/tests/server/api/router.test.ts
+++ b/packages/cloud/tests/server/api/router.test.ts
@@ -52,6 +52,12 @@ function services() {
commitImageUploads: async () => {
throw new Error('not used')
},
+ imageLinks: async () => {
+ throw new Error('not used')
+ },
+ imageLinksShared: 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.md
index 6ac710dc8..d132a3327 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -158,6 +158,15 @@ a ticket, a full room, or a frame past those limits, leaves the room: the docume
is not editing live and offers to rejoin, a viewer stays read-only, and an editor saves on its own,
since a tab that was not the room's saver had its edits counted as saved by the room.
+A Cloud room names its images instead of carrying them: an editor stores an image it adds in the
+document's workspace and puts only its SHA-256 in the room's `imageRefs` map, and every peer loads
+the images it lacks through links the server signs for anyone who may view the document, or for a
+guest through its share link. A guest or a viewer cannot store images, so the ones it adds travel as
+bytes until an editor in the room stores them and swaps them for references; a store that fails
+leaves the bytes in the room. The room's state, which the relay saves, therefore holds no image
+bytes once an editor has stored them. A peer that cannot load an image asks again later, waiting
+longer each time up to a minute, while the room still names it.
+
The relay enforces what the ticket allows: a viewer's document updates and sync replies never leave
it, and presence updates are rewritten so others see the ticket's name and a `cloud` field with the
verified identity and permission. A peer cannot claim presence clients another peer owns. Voice is
diff --git a/src/app/cloud/rooms/images.ts b/src/app/cloud/rooms/images.ts
new file mode 100644
index 000000000..48da731e5
--- /dev/null
+++ b/src/app/cloud/rooms/images.ts
@@ -0,0 +1,85 @@
+import { groupBy, limitAsync } from 'es-toolkit'
+
+import type { CloudAPIClient } from '@open-pencil/cloud/client'
+import {
+ isCloudChecksum,
+ type DocumentImageLink,
+ type ResolveDocumentShareInput
+} from '@open-pencil/cloud/contract'
+
+import type { RoomImageStore } from '@/app/collab/images'
+import { cloudChecksum, downloadCloudImage } from '@/app/integrations/storage/cloud/download'
+import { uploadCloudImages } from '@/app/integrations/storage/cloud/images'
+import { storageFetch } from '@/app/integrations/storage/s3/fetch'
+
+const IMAGE_LOAD_CONCURRENCY = 6
+
+/**
+ * The bytes of each reference, downloaded once per checksum however many names share it. A
+ * reference that is no checksum, or an image whose download fails, is left out, so the others
+ * still load.
+ */
+async function loadLinked(
+ refs: readonly { name: string; ref: string }[],
+ links: (checksums: string[]) => Promise<DocumentImageLink[]>
+): Promise<ReadonlyMap<string, Uint8Array>> {
+ const byChecksum = groupBy(
+ refs.filter((ref) => isCloudChecksum(ref.ref)),
+ (ref) => ref.ref
+ )
+ const checksums = Object.keys(byChecksum)
+ const loaded = new Map<string, Uint8Array>()
+ if (checksums.length === 0) return loaded
+ const download = limitAsync(
+ (link: DocumentImageLink) => downloadCloudImage(link, storageFetch),
+ IMAGE_LOAD_CONCURRENCY
+ )
+ await Promise.allSettled(
+ (await links(checksums)).map(async (link) => {
+ const bytes = await download(link)
+ for (const ref of byChecksum[link.checksum] ?? []) loaded.set(ref.name, bytes)
+ })
+ )
+ return loaded
+}
+
+/**
+ * A Cloud room's images, kept in the document's workspace under their SHA-256: an editor stores
+ * what it adds, and everyone with access loads what the room names.
+ */
+export function cloudRoomImages(
+ client: Pick<CloudAPIClient, 'requestImageUploads' | 'commitImageUploads' | 'getImageLinks'>,
+ documentId: string,
+ canStore: boolean
+): RoomImageStore {
+ return {
+ canStore,
+ async store(images) {
+ const named = await Promise.all(
+ images.map(async (image) => ({ ...image, checksum: await cloudChecksum(image.bytes) }))
+ )
+ await uploadCloudImages({
+ cloud: client,
+ documentId,
+ images: named,
+ objectFetch: storageFetch
+ })
+ return new Map(named.map((image) => [image.name, image.checksum]))
+ },
+ load: (refs) => loadLinked(refs, (checksums) => client.getImageLinks(documentId, checksums))
+ }
+}
+
+/** A guest's view of a shared Cloud room's images: it loads what the room names and stores none. */
+export function sharedCloudRoomImages(
+ client: Pick<CloudAPIClient, 'getSharedImageLinks'>,
+ shareId: string,
+ share: ResolveDocumentShareInput
+): RoomImageStore {
+ return {
+ canStore: false,
+ store: async () => new Map(),
+ load: (refs) =>
+ loadLinked(refs, (checksums) => client.getSharedImageLinks(shareId, share, checksums))
+ }
+}
diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.ts
index 8d5a3f6b5..b06b806e1 100644
--- a/src/app/cloud/rooms/live.ts
+++ b/src/app/cloud/rooms/live.ts
@@ -3,6 +3,7 @@ import { effectScope, onScopeDispose, shallowRef, watch } from 'vue'
import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'
+import type { RoomImageStore } from '@/app/collab/images'
import { leaveRoom, openDocumentRoom, roomForStore } from '@/app/collab/rooms'
import type { RoomIdentity, RoomSession } from '@/app/collab/session'
import type { JoinCollabRoom } from '@/app/collab/transport'
@@ -24,6 +25,7 @@ import { cloudConnection, cloudConnections, type CloudSessionState } from '../se
import { cloudShareTarget } from '../sharing/document'
import { versionsChanged } from '../versions/history'
import { accountRoomIdentity } from './identity'
+import { cloudRoomImages } from './images'
import { onceOnServer, shareRoomUploads, uploadStoredDocument } from './upload'
/** Each Cloud tab's permission in its room, for the status beside the name. */
@@ -180,11 +182,19 @@ export function openCloudDocumentRoom(
uploadNow?: () => Promise<boolean>
/** Who the tab is in the room; the device's own identity unless an account names it. */
identity?: RoomIdentity
+ /** Where the room keeps its images: the document's workspace, so the room names them. */
+ images?: RoomImageStore
}
) {
const canEdit = options.permission === 'edit'
const canSave = canEdit && !options.guest
- const session = openDocumentRoom(store, options.roomId, options.transport, options.identity)
+ const session = openDocumentRoom(
+ store,
+ options.roomId,
+ options.transport,
+ options.identity,
+ options.images
+ )
// Everything the room follows lives in one scope, so stopping it leaves nothing behind.
const scope = effectScope(true)
const uploads = scope.run(() => {
@@ -386,6 +396,7 @@ export async function startCloudRoom(store: EditorStore): Promise<void> {
onRefused: () => leaveRefusedRoom(store, { permission: first.permission, canSave: true })
}),
permission: first.permission,
+ images: cloudRoomImages(target.client, binding.documentId, first.permission === 'edit'),
roomIsCurrent: async () => (await nextTicket()).roomId === first.roomId,
onRestored: restart
})
diff --git a/src/app/cloud/sharing/link.ts b/src/app/cloud/sharing/link.ts
index fc838c0f5..1754b1b93 100644
--- a/src/app/cloud/sharing/link.ts
+++ b/src/app/cloud/sharing/link.ts
@@ -10,6 +10,7 @@ import { storageFetch } from '@/app/integrations/storage/s3/fetch'
import { getTabForStore, openFileInNewTab } from '@/app/tabs'
import { IS_BROWSER } from '@/constants'
+import { sharedCloudRoomImages } from '../rooms/images'
import {
cloudRelayTransport,
leaveRefusedRoom,
@@ -61,7 +62,8 @@ export async function openCloudShareLink(link: CloudShareLink): Promise<void> {
{ onRefused: () => leaveRefusedRoom(store, { permission: first.permission, canSave: false }) }
),
permission: first.permission,
- guest: true
+ guest: true,
+ images: sharedCloudRoomImages(client, link.shareId, input)
})
stopWithTab(store, room)
}
diff --git a/src/app/collab/images.ts b/src/app/collab/images.ts
new file mode 100644
index 000000000..0ef3a470f
--- /dev/null
+++ b/src/app/collab/images.ts
@@ -0,0 +1,194 @@
+import { compact, partition } from 'es-toolkit'
+import type * as Y from 'yjs'
+
+import type { EditorStore } from '@/app/editor/active-store'
+
+/**
+ * Where a room keeps its images instead of in its document, as a Cloud room keeps them in its
+ * workspace. The document then names each image by reference, so the room's state and what a
+ * newcomer receives stay small however many images it holds.
+ */
+export interface RoomImageStore {
+ /** Whether this peer may store images; a guest or a viewer leaves the ones it adds in the room. */
+ readonly canStore: boolean
+ /** Stores images and returns the reference to each, by name. */
+ store(
+ images: readonly { name: string; bytes: Uint8Array }[]
+ ): Promise<ReadonlyMap<string, string>>
+ /** The bytes behind references, by name; ones the store cannot give are left out. */
+ load(refs: readonly { name: string; ref: string }[]): Promise<ReadonlyMap<string, Uint8Array>>
+}
+
+/** How long a peer waits before asking again for an image it could not load, by attempt. */
+export function imageRetryDelayMs(attempt: number): number {
+ return Math.min(1000 * 2 ** attempt, 60_000)
+}
+
+/** The room's image references by name, beside the `images` map of bytes. */
+export type YImageRefs = Y.Map<string>
+
+export type RoomImages = {
+ /** Takes an image this peer added to store and name; false leaves it for the room's bytes. */
+ share(name: string, bytes: Uint8Array): boolean
+ /** Whether the room names this image by reference, so removing its bytes keeps the image. */
+ hasRef(name: string): boolean
+ dispose(): void
+}
+
+/**
+ * Keeps a room's images in `images`: a peer that may store them stores what it adds and names it
+ * by reference, and stores the bytes others put in the room, such as a guest's, swapping them for
+ * references; every peer loads the images references name that it lacks.
+ */
+export function bindRoomImages({
+ ydoc,
+ yimages,
+ yrefs,
+ store,
+ images,
+ report,
+ retryDelayMs = imageRetryDelayMs
+}: {
+ ydoc: Y.Doc
+ yimages: Y.Map<Uint8Array>
+ yrefs: YImageRefs
+ store: EditorStore
+ images: RoomImageStore
+ report: (message: string, error: unknown) => void
+ retryDelayMs?: (attempt: number) => number
+}): RoomImages {
+ const toStore = new Map<string, Uint8Array>()
+ const toLoad = new Set<string>()
+ /** Images on their way to or from the store, so none is asked for twice at once. */
+ const busy = new Set<string>()
+ /** Failed loads so far by name, and the timers that will ask for those images again. */
+ const attempts = new Map<string, number>()
+ const retries = new Set<ReturnType<typeof setTimeout>>()
+ let scheduled = false
+ let disposed = false
+
+ function soon() {
+ if (scheduled || disposed) return
+ scheduled = true
+ queueMicrotask(() => {
+ scheduled = false
+ void flush()
+ })
+ }
+
+ async function storeQueued() {
+ const batch = [...toStore].map(([name, bytes]) => ({ name, bytes }))
+ toStore.clear()
+ if (batch.length === 0) return
+ for (const image of batch) busy.add(image.name)
+ try {
+ const refs = await images.store(batch)
+ if (disposed) return
+ ydoc.transact(() => {
+ for (const [name, ref] of refs) {
+ yrefs.set(name, ref)
+ if (yimages.has(name)) yimages.delete(name)
+ }
+ })
+ } catch (error) {
+ // The bytes stay in the room, as a peer that cannot store images leaves them.
+ for (const image of batch) {
+ if (!yimages.has(image.name) && !yrefs.has(image.name)) {
+ yimages.set(image.name, image.bytes)
+ }
+ }
+ report('Storing room images failed', error)
+ } finally {
+ for (const image of batch) busy.delete(image.name)
+ }
+ }
+
+ async function loadQueued() {
+ const batch = compact(
+ [...toLoad].map((name) => {
+ const ref = yrefs.get(name)
+ return ref ? { name, ref } : undefined
+ })
+ )
+ toLoad.clear()
+ if (batch.length === 0) return
+ for (const image of batch) busy.add(image.name)
+ let loaded: ReadonlyMap<string, Uint8Array> = new Map()
+ try {
+ loaded = await images.load(batch)
+ if (disposed) return
+ for (const [name, bytes] of loaded) store.graph.images.set(name, bytes)
+ if (loaded.size > 0) store.requestRender()
+ } catch (error) {
+ report('Loading room images failed', error)
+ } finally {
+ for (const image of batch) busy.delete(image.name)
+ }
+ const [arrived, missed] = partition(batch, (image) => loaded.has(image.name))
+ for (const image of arrived) attempts.delete(image.name)
+ for (const image of missed) retryLoad(image.name, image.ref)
+ }
+
+ /** Asks again later for an image a load left out, as long as the room still names it so. */
+ function retryLoad(name: string, ref: string) {
+ if (disposed) return
+ const attempt = attempts.get(name) ?? 0
+ attempts.set(name, attempt + 1)
+ const timer = setTimeout(() => {
+ retries.delete(timer)
+ if (!disposed && yrefs.get(name) === ref) wantLoad(name)
+ }, retryDelayMs(attempt))
+ retries.add(timer)
+ }
+
+ async function flush() {
+ await Promise.all([storeQueued(), loadQueued()])
+ }
+
+ function wantLoad(name: string) {
+ if (busy.has(name) || store.graph.images.has(name)) return
+ toLoad.add(name)
+ soon()
+ }
+
+ function wantStore(name: string, bytes: Uint8Array) {
+ if (!images.canStore || busy.has(name) || yrefs.has(name)) return
+ toStore.set(name, bytes)
+ soon()
+ }
+
+ function onRefs(event: Y.YMapEvent<string>) {
+ for (const [name, change] of event.changes.keys) {
+ attempts.delete(name)
+ if (change.action !== 'delete') wantLoad(name)
+ }
+ }
+
+ function onImages(event: Y.YMapEvent<Uint8Array>) {
+ for (const [name, change] of event.changes.keys) {
+ const bytes = change.action === 'delete' ? undefined : yimages.get(name)
+ if (bytes) wantStore(name, bytes)
+ }
+ }
+
+ yrefs.observe(onRefs)
+ yimages.observe(onImages)
+ for (const name of yrefs.keys()) wantLoad(name)
+ for (const [name, bytes] of yimages) wantStore(name, bytes)
+
+ return {
+ share(name, bytes) {
+ if (!images.canStore) return false
+ wantStore(name, bytes)
+ return true
+ },
+ hasRef: (name) => yrefs.has(name),
+ dispose() {
+ disposed = true
+ for (const timer of retries) clearTimeout(timer)
+ retries.clear()
+ yrefs.unobserve(onRefs)
+ yimages.unobserve(onImages)
+ }
+ }
+}
diff --git a/src/app/collab/rooms.ts b/src/app/collab/rooms.ts
index 2e5ccceaf..5ca8d0eb9 100644
--- a/src/app/collab/rooms.ts
+++ b/src/app/collab/rooms.ts
@@ -1,6 +1,7 @@
import { computed, shallowRef, watch } from 'vue'
import { generateRoomId } from '@/app/collab/awareness'
+import type { RoomImageStore } from '@/app/collab/images'
import { isRoomId } from '@/app/collab/room/id'
import { openRoomSession, type RoomIdentity, type RoomSession } from '@/app/collab/session'
import type { JoinCollabRoom } from '@/app/collab/transport'
@@ -64,7 +65,8 @@ export function openDocumentRoom(
store: EditorStore,
roomId: string,
transport: JoinCollabRoom,
- identity?: RoomIdentity
+ identity?: RoomIdentity,
+ images?: RoomImageStore
): RoomSession {
const existing = roomForStore(store)
if (existing?.roomId === roomId) return existing
@@ -77,7 +79,8 @@ export function openDocumentRoom(
joinRoom: transport,
holdsDocument: true,
leavable: false,
- identity
+ identity,
+ images
})
addSession(session)
return session
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index 015ee809a..89c5b5f2b 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -9,6 +9,7 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { shareAgentPreviews } from '@/app/collab/agent-preview'
import { buildRemotePeers } from '@/app/collab/awareness'
import { useCollabIdentity } from '@/app/collab/identity'
+import { bindRoomImages, type RoomImageStore } from '@/app/collab/images'
import { publishLocalAgents } from '@/app/collab/local-awareness'
import { connectCollabRoom } from '@/app/collab/room/connection'
import { trackRoomSaves, type RoomSaves } from '@/app/collab/room/saves'
@@ -104,6 +105,8 @@ export interface RoomSessionOptions {
holdsDocument?: boolean
/** False for a room the tab's document lives in, which the person never leaves by hand. */
leavable?: boolean
+ /** Where the room keeps its images instead of in its document, as a Cloud room does. */
+ images?: RoomImageStore
}
function openIndexedDBCopy(roomId: string, ydoc: Y.Doc): RoomSavedCopy {
@@ -122,12 +125,23 @@ export function openRoomSession({
unreachableMs = ROOM_UNREACHABLE_MS,
tickMs = ROOM_STATUS_TICK_MS,
holdsDocument = false,
- leavable = true
+ leavable = true,
+ images
}: RoomSessionOptions): RoomSession {
const ydoc = new Y.Doc()
const awareness = new awarenessProtocol.Awareness(ydoc)
const ynodes: YNodes = ydoc.getMap('nodes')
const yimages = ydoc.getMap<Uint8Array>('images')
+ const roomImages = images
+ ? bindRoomImages({
+ ydoc,
+ yimages,
+ yrefs: ydoc.getMap<string>('imageRefs'),
+ store,
+ images,
+ report: (message, error) => console.error(`[Collab] ${message}:`, error)
+ })
+ : null
const meta = ydoc.getMap<unknown>('meta')
const yvariables: YRecords = ydoc.getMap('variables')
const ycollections: YRecords = ydoc.getMap('collections')
@@ -167,6 +181,7 @@ export function openRoomSession({
getYdoc: () => (disposed ? null : ydoc),
getYnodes: () => (disposed ? null : ynodes),
getYimages: () => (disposed ? null : yimages),
+ shareImage: roomImages ? (name, bytes) => roomImages.share(name, bytes) : undefined,
setSuppressYjsEvents: (value) => {
suppressYjsEvents = value
}
@@ -214,6 +229,7 @@ export function openRoomSession({
store,
ynodes,
yimages,
+ hasImageRef: roomImages ? (name) => roomImages.hasRef(name) : undefined,
getSuppressYjsEvents: () => suppressYjsEvents,
setSuppressGraphSync: (value) => {
suppressGraphSync = value
@@ -304,6 +320,7 @@ export function openRoomSession({
// Unbinding writes an edit still waiting to be sent, so it runs while the room is open.
unbindGraphEvents()
variableSync.dispose()
+ roomImages?.dispose()
disposed = true
connectionTimer.pause()
stopNameWatch()
diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.ts
index 0d2a83923..835de5478 100644
--- a/src/app/collab/yjs-sync.ts
+++ b/src/app/collab/yjs-sync.ts
@@ -45,6 +45,8 @@ type YjsObserverOptions = {
store: EditorStore
ynodes: YNodes
yimages: YImages
+ /** Whether the room names an image by reference, which keeps it when its bytes leave. */
+ hasImageRef?: (name: string) => boolean
getSuppressYjsEvents: () => boolean
setSuppressGraphSync: (value: boolean) => void
applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void
@@ -55,6 +57,8 @@ type YjsGraphSyncOptions = {
getYdoc: () => Y.Doc | null
getYnodes: () => YNodes | null
getYimages: () => YImages | null
+ /** Takes an image a layer uses to share some other way; false writes its bytes into the room. */
+ shareImage?: (name: string, bytes: Uint8Array) => boolean
setSuppressYjsEvents: (value: boolean) => void
}
@@ -131,6 +135,7 @@ export function registerYjsObservers({
store,
ynodes,
yimages,
+ hasImageRef,
getSuppressYjsEvents,
setSuppressGraphSync,
applyYjsToGraph
@@ -156,7 +161,7 @@ export function registerYjsObservers({
if (change.action === 'add' || change.action === 'update') {
const data = yimages.get(key)
if (data) store.graph.images.set(key, new Uint8Array(data))
- } else {
+ } else if (!hasImageRef?.(key)) {
store.graph.images.delete(key)
}
}
@@ -179,6 +184,7 @@ export function createYjsGraphSync({
getYdoc,
getYnodes,
getYimages,
+ shareImage,
setSuppressYjsEvents
}: YjsGraphSyncOptions) {
let pendingPageSwitch: { store: EditorStore; pageId: string } | undefined
@@ -206,10 +212,9 @@ export function createYjsGraphSync({
const localYimages = getYimages()
if (!localYimages) return
for (const fill of node.fills) {
- if (fill.imageHash && !localYimages.has(fill.imageHash)) {
- const data = graph.images.get(fill.imageHash)
- if (data) localYimages.set(fill.imageHash, data)
- }
+ if (!fill.imageHash || localYimages.has(fill.imageHash)) continue
+ const data = graph.images.get(fill.imageHash)
+ if (data && !shareImage?.(fill.imageHash, data)) localYimages.set(fill.imageHash, data)
}
}
diff --git a/src/app/integrations/storage/cloud/download.ts b/src/app/integrations/storage/cloud/download.ts
index 78ff9b751..3b5b65afa 100644
--- a/src/app/integrations/storage/cloud/download.ts
+++ b/src/app/integrations/storage/cloud/download.ts
@@ -1,7 +1,7 @@
-import { Semaphore, sumBy } from 'es-toolkit'
+import { limitAsync, sumBy } from 'es-toolkit'
import { fromUint8Array } from 'js-base64'
-import type { DocumentDownload } from '@open-pencil/cloud/contract'
+import type { DocumentDownload, DocumentImageLink } from '@open-pencil/cloud/contract'
import type { StorageTransferProgress } from '../types'
import { assembleCloudDocument } from './images'
@@ -37,6 +37,15 @@ async function fetchVerified(
return bytes
}
+/** An image a live room names, from where the server linked it, checked against its record. */
+export function downloadCloudImage(
+ link: DocumentImageLink,
+ objectFetch: ObjectFetch,
+ signal?: AbortSignal
+): Promise<Uint8Array> {
+ return fetchVerified(link.download, link, objectFetch, signal)
+}
+
/** A revision as the editor opens it: its stored file with every image put back under its name. */
export async function downloadCloudDocument(
download: DocumentDownload,
@@ -50,18 +59,16 @@ export async function downloadCloudDocument(
options.onProgress?.({ transferredBytes, totalBytes })
return bytes
}
- const semaphore = new Semaphore(IMAGE_DOWNLOAD_CONCURRENCY)
+ const fetchImage = limitAsync(
+ async (image: DocumentDownload['images'][number]) => ({
+ name: image.name,
+ bytes: received(await fetchVerified(image.download, image, objectFetch, options.signal))
+ }),
+ 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()
- }
- })
+ ...download.images.map(fetchImage)
])
return assembleCloudDocument(lean, images)
}
diff --git a/src/app/integrations/storage/cloud/images.ts b/src/app/integrations/storage/cloud/images.ts
index 4f0095728..b0ee7360e 100644
--- a/src/app/integrations/storage/cloud/images.ts
+++ b/src/app/integrations/storage/cloud/images.ts
@@ -1,8 +1,8 @@
-import { Semaphore } from 'es-toolkit'
+import { limitAsync } 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 { CLOUD_IMAGE_NAME_PATTERN, type ObjectUploadTarget } from '@open-pencil/cloud/contract'
import { putCloudObject, type CloudObjectTransfer } from './upload'
@@ -68,22 +68,17 @@ export async function uploadCloudImages(input: {
images: [...byChecksum].map(([checksum, bytes]) => ({ checksum, byteSize: bytes.byteLength }))
})
if (offers.length === 0) return
- const semaphore = new Semaphore(IMAGE_UPLOAD_CONCURRENCY)
+ const put = limitAsync(
+ (target: ObjectUploadTarget, bytes: Uint8Array) =>
+ putCloudObject(target, { bytes, objectFetch: input.objectFetch, signal: input.signal }),
+ 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()
- }
+ const multipart = await put(offer.upload, bytes)
+ return { uploadId: offer.uploadId, checksum: offer.checksum, multipart }
})
)
// One commit for every image, however many a save adds.
diff --git a/src/app/integrations/storage/cloud/upload.ts b/src/app/integrations/storage/cloud/upload.ts
index 607175d9a..f8310e917 100644
--- a/src/app/integrations/storage/cloud/upload.ts
+++ b/src/app/integrations/storage/cloud/upload.ts
@@ -1,4 +1,4 @@
-import { retry, Semaphore } from 'es-toolkit'
+import { limitAsync, retry } from 'es-toolkit'
import type { CloudAPIClient } from '@open-pencil/cloud/client'
import type { ObjectUploadTarget } from '@open-pencil/cloud/contract'
@@ -93,29 +93,24 @@ 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 })
- const semaphore = new Semaphore(Math.min(MULTIPART_CONCURRENCY, multipart.parts.length))
let transferred = 0
+ const putOne = limitAsync(async (part: MultipartUpload['parts'][number]) => {
+ try {
+ controller.signal.throwIfAborted()
+ const start = (part.partNumber - 1) * multipart.partSize
+ const bytes = upload.bytes.subarray(start, start + multipart.partSize)
+ const etag = await putPart(upload, part, bytes, controller.signal)
+ transferred += bytes.byteLength
+ report(upload, transferred)
+ return { partNumber: part.partNumber, etag }
+ } catch (error) {
+ // One failed part fails the upload; the others stop instead of finishing for nothing.
+ controller.abort(error)
+ throw error
+ }
+ }, MULTIPART_CONCURRENCY)
try {
- return await Promise.all(
- multipart.parts.map(async (part) => {
- await semaphore.acquire()
- try {
- controller.signal.throwIfAborted()
- const start = (part.partNumber - 1) * multipart.partSize
- const bytes = upload.bytes.subarray(start, start + multipart.partSize)
- const etag = await putPart(upload, part, bytes, controller.signal)
- transferred += bytes.byteLength
- report(upload, transferred)
- return { partNumber: part.partNumber, etag }
- } catch (error) {
- // One failed part fails the upload; the others stop instead of finishing for nothing.
- controller.abort(error)
- throw error
- } finally {
- semaphore.release()
- }
- })
- )
+ return await Promise.all(multipart.parts.map(putOne))
} finally {
upload.signal?.removeEventListener('abort', stop)
}
diff --git a/tests/app/cloud/rooms/images.test.ts b/tests/app/cloud/rooms/images.test.ts
new file mode 100644
index 000000000..98f007f60
--- /dev/null
+++ b/tests/app/cloud/rooms/images.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, spyOn, test } from 'bun:test'
+
+import type { DocumentImageLink } from '@open-pencil/cloud/contract'
+
+import { cloudRoomImages } from '@/app/cloud/rooms/images'
+import { cloudChecksum } from '@/app/integrations/storage/cloud/download'
+
+import { fetchStub } from '#tests/helpers/fetch'
+
+const DOCUMENT = 'document-1'
+const photo = new Uint8Array([137, 80, 78, 71, 1, 2, 3])
+const logo = new Uint8Array([71, 73, 70, 56, 4, 5])
+
+let objectStore: ReturnType<typeof spyOn<typeof globalThis, 'fetch'>> | undefined
+
+afterEach(() => {
+ objectStore?.mockRestore()
+})
+
+/** Links to images at `https://objects.test/<checksum>`, the ones in `stored` answering. */
+async function cloud(stored: Map<string, Uint8Array>) {
+ const asked: string[][] = []
+ objectStore = spyOn(globalThis, 'fetch').mockImplementation(
+ fetchStub(async (input) => {
+ const url = new URL(input instanceof Request ? input.url : String(input))
+ const bytes = stored.get(decodeURIComponent(url.pathname.slice(1)))
+ return bytes ? new Response(Uint8Array.from(bytes)) : new Response(null, { status: 503 })
+ })
+ )
+ const images = cloudRoomImages(
+ {
+ requestImageUploads: async () => [],
+ commitImageUploads: async () => undefined,
+ async getImageLinks(_documentId, checksums): Promise<DocumentImageLink[]> {
+ asked.push(checksums)
+ return checksums.map((checksum) => ({
+ checksum,
+ byteSize: stored.get(checksum)?.byteLength ?? 1,
+ download: {
+ method: 'GET',
+ url: `https://objects.test/${encodeURIComponent(checksum)}`,
+ headers: {},
+ expiresAt: new Date(Date.now() + 60_000).toISOString()
+ }
+ }))
+ }
+ },
+ DOCUMENT,
+ true
+ )
+ return { images, asked }
+}
+
+describe('Cloud room images', () => {
+ test('loads the images it can and leaves out a failed download and a malformed reference', async () => {
+ const photoChecksum = await cloudChecksum(photo)
+ const logoChecksum = await cloudChecksum(logo)
+ const { images, asked } = await cloud(new Map([[logoChecksum, logo]]))
+ const loaded = await images.load([
+ { name: 'photo', ref: photoChecksum },
+ { name: 'logo', ref: logoChecksum },
+ { name: 'copy', ref: logoChecksum },
+ { name: 'broken', ref: 'not a checksum' }
+ ])
+ expect(asked).toEqual([[photoChecksum, logoChecksum]])
+ expect([...loaded.keys()].sort()).toEqual(['copy', 'logo'])
+ expect(loaded.get('logo')).toEqual(logo)
+ })
+
+ test('asks the server nothing when no reference is a checksum', async () => {
+ const { images, asked } = await cloud(new Map())
+ expect((await images.load([{ name: 'broken', ref: 'nope' }])).size).toBe(0)
+ expect(asked).toEqual([])
+ })
+})
diff --git a/tests/app/collab/images.test.ts b/tests/app/collab/images.test.ts
new file mode 100644
index 000000000..53edc419b
--- /dev/null
+++ b/tests/app/collab/images.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as Y from 'yjs'
+
+import { bindRoomImages, type RoomImageStore } from '@/app/collab/images'
+import type { EditorStore } from '@/app/editor/active-store'
+
+import { asDouble } from '#tests/helpers/doubles'
+
+/** A store that keeps images by a reference of its own, counting what it was asked. */
+function memoryImageStore(canStore = true, failStoring = false) {
+ const kept = new Map<string, Uint8Array>()
+ const calls = { stored: 0, loaded: 0 }
+ const store: RoomImageStore = {
+ canStore,
+ async store(images) {
+ calls.stored++
+ if (failStoring) throw new Error('Storage is down')
+ return new Map(
+ images.map((image) => {
+ const ref = `ref:${image.name}`
+ kept.set(ref, image.bytes)
+ return [image.name, ref]
+ })
+ )
+ },
+ async load(refs) {
+ calls.loaded++
+ return new Map(
+ refs.flatMap(({ name, ref }) => {
+ const bytes = kept.get(ref)
+ return bytes ? [[name, bytes] as const] : []
+ })
+ )
+ }
+ }
+ return { store, kept, calls }
+}
+
+/** A peer of a room: its document and the images its editor holds. */
+function peer(images: RoomImageStore, retryDelayMs?: (attempt: number) => number) {
+ const ydoc = new Y.Doc()
+ const graphImages = new Map<string, Uint8Array>()
+ let renders = 0
+ const reports: string[] = []
+ const editor = asDouble<EditorStore>({
+ graph: { images: graphImages },
+ requestRender: () => {
+ renders++
+ }
+ })
+ const bound = bindRoomImages({
+ ydoc,
+ yimages: ydoc.getMap<Uint8Array>('images'),
+ yrefs: ydoc.getMap<string>('imageRefs'),
+ store: editor,
+ images,
+ report: (message) => {
+ reports.push(message)
+ },
+ retryDelayMs
+ })
+ return { ydoc, graphImages, bound, reports, renders: () => renders }
+}
+
+/** Lets queued stores and loads finish. */
+async function settle() {
+ for (let index = 0; index < 10; index++) await Promise.resolve()
+}
+
+/** Lets a retry's timer fire and the load it starts finish. */
+async function afterRetry() {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 1)
+ })
+ await settle()
+}
+
+/** Sends everything `from` has that `to` lacks, as the relay would. */
+function sync(from: Y.Doc, to: Y.Doc) {
+ Y.applyUpdate(to, Y.encodeStateAsUpdate(from, Y.encodeStateVector(to)))
+}
+
+const photo = new Uint8Array([137, 80, 78, 71, 1, 2, 3])
+
+describe('room images', () => {
+ test('a peer that may store an image names it by reference instead of sending its bytes', async () => {
+ const images = memoryImageStore()
+ const editor = peer(images.store)
+ expect(editor.bound.share('a1', photo)).toBe(true)
+ await settle()
+ expect(editor.ydoc.getMap<string>('imageRefs').get('a1')).toBe('ref:a1')
+ expect(editor.ydoc.getMap('images').has('a1')).toBe(false)
+
+ // Another peer loads it from the reference.
+ const loader = peer(images.store)
+ sync(editor.ydoc, loader.ydoc)
+ await settle()
+ expect(loader.graphImages.get('a1')).toEqual(photo)
+ expect(loader.renders()).toBeGreaterThan(0)
+ })
+
+ test('bytes a guest puts in the room are stored and swapped for a reference', async () => {
+ const images = memoryImageStore()
+ const guest = peer(memoryImageStore(false).store)
+ expect(guest.bound.share('g1', photo)).toBe(false)
+ guest.ydoc.getMap<Uint8Array>('images').set('g1', photo)
+
+ const editor = peer(images.store)
+ sync(guest.ydoc, editor.ydoc)
+ await settle()
+ expect(editor.ydoc.getMap<string>('imageRefs').get('g1')).toBe('ref:g1')
+ expect(editor.ydoc.getMap('images').has('g1')).toBe(false)
+ expect(images.calls.stored).toBe(1)
+ })
+
+ test('an image the store refused stays in the room as bytes', async () => {
+ const editor = peer(memoryImageStore(true, true).store)
+ editor.bound.share('a1', photo)
+ await settle()
+ expect(editor.ydoc.getMap<Uint8Array>('images').get('a1')).toEqual(photo)
+ expect(editor.ydoc.getMap('imageRefs').has('a1')).toBe(false)
+ expect(editor.reports).toHaveLength(1)
+ })
+
+ test('an image that fails to load, or is left out, is asked for again until it loads', async () => {
+ const images = memoryImageStore()
+ const editor = peer(images.store)
+ editor.bound.share('a1', photo)
+ await settle()
+ const load = images.store.load.bind(images.store)
+ let failures = 2
+ const flaky: RoomImageStore = {
+ ...images.store,
+ async load(refs) {
+ failures--
+ if (failures === 1) throw new Error('Network is down')
+ if (failures === 0) return new Map()
+ return load(refs)
+ }
+ }
+ const loader = peer(flaky, () => 0)
+ sync(editor.ydoc, loader.ydoc)
+ await settle()
+ expect(loader.graphImages.has('a1')).toBe(false)
+ expect(loader.reports).toEqual(['Loading room images failed'])
+ await afterRetry()
+ expect(loader.graphImages.has('a1')).toBe(false)
+ await afterRetry()
+ expect(loader.graphImages.get('a1')).toEqual(photo)
+ })
+
+ test('a peer that leaves the room stops asking for images it could not load', async () => {
+ let loads = 0
+ const missing: RoomImageStore = {
+ canStore: false,
+ store: async () => new Map(),
+ load: async () => {
+ loads++
+ return new Map()
+ }
+ }
+ const loader = peer(missing, () => 0)
+ loader.ydoc.getMap<string>('imageRefs').set('a1', 'ref:a1')
+ await settle()
+ expect(loads).toBe(1)
+ loader.bound.dispose()
+ await afterRetry()
+ expect(loads).toBe(1)
+ })
+})