Skip to content

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

feat(cloud): keep a version history and compact the saves between versions (#1249)

Danila Poyarkov7b718152edad
diff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.toml
index 4fa37e10b..f3489151c 100644
--- a/packages/cloud/deploy/openpencil-cloud.example.toml
+++ b/packages/cloud/deploy/openpencil-cloud.example.toml
@@ -97,6 +97,7 @@ source = "static"
[entitlements.documents]
maximum_file_bytes = 1_073_741_824
+# Keep every version; false keeps the last 30 days of version history.
revision_history = true
[entitlements.storage]
diff --git a/packages/cloud/src/client/api.ts b/packages/cloud/src/client/api.ts
index 144669f94..5a6b0f37e 100644
--- a/packages/cloud/src/client/api.ts
+++ b/packages/cloud/src/client/api.ts
@@ -11,6 +11,9 @@ import {
documentInvitationSchema,
documentShareSchema,
documentSummarySchema,
+ documentVersionResponseSchema,
+ documentVersionsSchema,
+ restoredDocumentSchema,
sharedDocumentSchema,
invitationContinuationSchema,
invitationPreviewSchema,
@@ -32,6 +35,11 @@ import {
type DocumentInvitation,
type DocumentShare,
type DocumentSummary,
+ type DocumentVersion,
+ type DocumentVersions,
+ type DuplicateDocumentVersionInput,
+ type SaveDocumentVersionInput,
+ type UpdateDocumentVersionInput,
type SharedDocument,
type InvitationPreview,
type LookupCloudUserInput,
@@ -41,6 +49,7 @@ import {
type AcceptedInvitation
} from '#cloud/contract'
import type { CloudAPI, PublicCloudAPI } from '#cloud/server/api'
+import { pickBy } from 'es-toolkit/object'
import { hc } from 'hono/client'
import * as v from 'valibot'
@@ -443,6 +452,80 @@ export function createCloudAPIClient(baseURL: string, options: CloudRequestOptio
options.onDiagnostic
)
return response.document
+ },
+ /** A page of the document's version history, newest first. */
+ async listDocumentVersions(
+ documentId: string,
+ page: { before?: string; limit?: number } = {}
+ ): Promise<DocumentVersions> {
+ return parseResponse(
+ client.documents[':documentId'].versions.$get({
+ param: { documentId },
+ query: pickBy(page, (value) => value !== undefined)
+ }),
+ documentVersionsSchema,
+ options.onDiagnostic
+ )
+ },
+ async saveDocumentVersion(
+ documentId: string,
+ input: SaveDocumentVersionInput
+ ): Promise<DocumentVersion> {
+ const response = await parseResponse(
+ client.documents[':documentId'].versions.$post({ param: { documentId }, json: input }),
+ documentVersionResponseSchema,
+ options.onDiagnostic
+ )
+ return response.version
+ },
+ async updateDocumentVersion(
+ documentId: string,
+ versionId: string,
+ input: UpdateDocumentVersionInput
+ ): Promise<DocumentVersion> {
+ const response = await parseResponse(
+ client.documents[':documentId'].versions[':versionId'].$patch({
+ param: { documentId, versionId },
+ json: input
+ }),
+ documentVersionResponseSchema,
+ options.onDiagnostic
+ )
+ return response.version
+ },
+ async getDocumentVersion(documentId: string, versionId: string): Promise<DocumentDownload> {
+ const response = await parseResponse(
+ client.documents[':documentId'].versions[':versionId'].$get({
+ param: { documentId, versionId }
+ }),
+ downloadResponseSchema,
+ options.onDiagnostic
+ )
+ return response.document
+ },
+ async restoreDocumentVersion(documentId: string, versionId: string) {
+ return parseResponse(
+ client.documents[':documentId'].versions[':versionId'].restore.$post({
+ param: { documentId, versionId }
+ }),
+ restoredDocumentSchema,
+ options.onDiagnostic
+ )
+ },
+ async duplicateDocumentVersion(
+ documentId: string,
+ versionId: string,
+ input: DuplicateDocumentVersionInput
+ ): Promise<DocumentSummary> {
+ const response = await parseResponse(
+ client.documents[':documentId'].versions[':versionId'].duplicate.$post({
+ param: { documentId, versionId },
+ json: input
+ }),
+ documentResponseSchema,
+ options.onDiagnostic
+ )
+ return response.document
}
}
}
diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.ts
index 74f22cc6c..bee9b63bf 100644
--- a/packages/cloud/src/contract/index.ts
+++ b/packages/cloud/src/contract/index.ts
@@ -125,3 +125,4 @@ export {
type WorkspaceSummary
} from './workspaces'
export { CLOUD_PORTAL_PAGE_ROOTS, isCloudPortalPage } from './portal'
+export * from './versions'
diff --git a/packages/cloud/src/contract/versions.ts b/packages/cloud/src/contract/versions.ts
new file mode 100644
index 000000000..d197dea6e
--- /dev/null
+++ b/packages/cloud/src/contract/versions.ts
@@ -0,0 +1,81 @@
+import * as v from 'valibot'
+
+import { documentSummarySchema } from './documents'
+
+/** How long a version's name may be; the history list shows the start of longer ones. */
+export const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100
+export const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1000
+
+/** A checkpoint the server kept on its own, or a version someone named. */
+export const documentVersionKindSchema = v.picklist(['checkpoint', 'named'])
+export type DocumentVersionKind = v.InferOutput<typeof documentVersionKindSchema>
+
+export const documentVersionSchema = v.object({
+ id: v.pipe(v.string(), v.uuid()),
+ revisionId: v.pipe(v.string(), v.uuid()),
+ kind: documentVersionKindSchema,
+ name: v.nullable(v.string()),
+ description: v.nullable(v.string()),
+ createdAt: v.string(),
+ /** Who made the version: the author of a checkpoint's save, or who named or restored it. */
+ createdBy: v.object({ id: v.string(), name: v.nullable(v.string()) }),
+ /** The version this one restored, while that version is still in the history. */
+ restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),
+ /** Whether the document holds this version now. */
+ current: v.boolean()
+})
+export type DocumentVersion = v.InferOutput<typeof documentVersionSchema>
+
+export const documentVersionsSchema = v.object({
+ versions: v.array(documentVersionSchema),
+ /** Pass as `before` for the next, older page; null on the last one. */
+ nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))
+})
+export type DocumentVersions = v.InferOutput<typeof documentVersionsSchema>
+
+const versionName = v.pipe(
+ v.string(),
+ v.trim(),
+ v.minLength(1),
+ v.maxLength(DOCUMENT_VERSION_NAME_MAX_LENGTH)
+)
+const versionDescription = v.pipe(
+ v.string(),
+ v.trim(),
+ v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH)
+)
+
+/** Names the document as it is now, like Save to version history. */
+export const saveDocumentVersionSchema = v.object({
+ name: versionName,
+ description: v.optional(versionDescription, '')
+})
+export type SaveDocumentVersionInput = v.InferOutput<typeof saveDocumentVersionSchema>
+
+/** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */
+export const updateDocumentVersionSchema = v.object({
+ name: v.nullable(versionName),
+ description: v.optional(versionDescription, '')
+})
+export type UpdateDocumentVersionInput = v.InferOutput<typeof updateDocumentVersionSchema>
+
+export const duplicateDocumentVersionSchema = v.object({
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))
+})
+export type DuplicateDocumentVersionInput = v.InferOutput<typeof duplicateDocumentVersionSchema>
+
+export const documentVersionResponseSchema = v.object({ version: documentVersionSchema })
+export const restoredDocumentSchema = v.object({
+ document: documentSummarySchema,
+ version: documentVersionSchema
+})
+
+export function parseSaveDocumentVersion(input: unknown): SaveDocumentVersionInput {
+ return v.parse(saveDocumentVersionSchema, input)
+}
+export function parseUpdateDocumentVersion(input: unknown): UpdateDocumentVersionInput {
+ return v.parse(updateDocumentVersionSchema, input)
+}
+export function parseDuplicateDocumentVersion(input: unknown): DuplicateDocumentVersionInput {
+ return v.parse(duplicateDocumentVersionSchema, input)
+}
diff --git a/packages/cloud/src/runtime/node/cleanup.ts b/packages/cloud/src/runtime/node/cleanup.ts
index b6019e268..82a01e851 100644
--- a/packages/cloud/src/runtime/node/cleanup.ts
+++ b/packages/cloud/src/runtime/node/cleanup.ts
@@ -1,5 +1,15 @@
import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
-import { createDocumentCleanupService, createUploadCleanupService } from '#cloud/server'
+import {
+ createDefaultCloudPolicy,
+ createDocumentCleanupService,
+ createRevisionCompactionService,
+ createUploadCleanupService,
+ DatabaseEntitlementSource,
+ EntitlementOpenFeatureProvider,
+ REVISION_COMPACTION_GRACE_MS,
+ StaticEntitlementSource,
+ staticEntitlementValues
+} from '#cloud/server'
import { loadNodeCloudServerConfig } from './config'
import { createNodeCloudDatabase } from './database'
@@ -17,7 +27,18 @@ try {
leaseDurationMs: config.cleanupLeaseDurationMs,
retentionMs: config.documentRetentionMs
})
- console.log(JSON.stringify({ uploads, documents }))
+ const policy = createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ config.staticEntitlements
+ ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
+ : new DatabaseEntitlementSource(database)
+ )
+ )
+ const revisions = await createRevisionCompactionService(database, objects, {
+ policy,
+ deploymentMode: config.deployment
+ }).compactRevisions({ batchSize: config.cleanupBatchSize, graceMs: REVISION_COMPACTION_GRACE_MS })
+ console.log(JSON.stringify({ uploads, documents, revisions }))
} finally {
await database.destroy()
}
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index 1129be1d1..3cba4be76 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -14,6 +14,7 @@ import {
staticEntitlementValues,
createDocumentCleanupService,
createRateLimitCleanupService,
+ createRevisionCompactionService,
createUploadCleanupService,
startCleanupWorker,
startTransactionalEmailWorker,
@@ -41,10 +42,21 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
transport: emailTransport
} = createNodeTransactionalEmailRuntime(config, database)
const { auth, enrollment } = createCloudAuthenticationRuntime(config, database, email)
+ const policy = createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ config.staticEntitlements
+ ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
+ : new DatabaseEntitlementSource(database)
+ )
+ )
const cleanup = config.cleanupEnabled
? startCleanupWorker(
{
documents: createDocumentCleanupService(database, objects),
+ revisions: createRevisionCompactionService(database, objects, {
+ policy,
+ deploymentMode: config.deployment
+ }),
uploads: createUploadCleanupService(database, objects),
rateLimits: createRateLimitCleanupService(database)
},
@@ -67,13 +79,6 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
enrollment,
relayURL: config.relayURL ?? defaultRelayURL(config.publicURL)
})
- const policy = createDefaultCloudPolicy(
- new EntitlementOpenFeatureProvider(
- config.staticEntitlements
- ? new StaticEntitlementSource(staticEntitlementValues(config.staticEntitlements))
- : new DatabaseEntitlementSource(database)
- )
- )
const relay = createCollaborationRelay({
authSecret: config.authSecret,
store: createCollaborationStateStore(database),
diff --git a/packages/cloud/src/server/api/router.ts b/packages/cloud/src/server/api/router.ts
index 41c4098ec..831b75ebf 100644
--- a/packages/cloud/src/server/api/router.ts
+++ b/packages/cloud/src/server/api/router.ts
@@ -8,6 +8,10 @@ import {
import type { CloudDatabase } from '#cloud/server/db'
import type { DocumentService } from '#cloud/server/documents'
import { createDocumentRoutes } from '#cloud/server/documents'
+import {
+ createDocumentVersionRoutes,
+ type DocumentVersionService
+} from '#cloud/server/documents/versions'
import type { EntitlementService } from '#cloud/server/policy'
import type { DocumentSharingService } from '#cloud/server/sharing'
import {
@@ -25,6 +29,7 @@ export type CloudAPIServices = {
rateLimitSecret?: string
collaboration: CollaborationTicketService
documents: DocumentService
+ versions: DocumentVersionService
sharing: DocumentSharingService
resolveSession?: CloudSessionResolver
entitlements?: EntitlementService
@@ -71,6 +76,7 @@ export function createCloudAPIRouter(services: CloudAPIServices) {
: undefined
)
)
+ .route('/', createDocumentVersionRoutes(services.versions))
.route(
'/',
createDocumentSharingRoutes(
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index a46e7dda7..eceb50e92 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -25,6 +25,7 @@ import { createCollaborationTicketService } from '#cloud/server/collaboration'
import { cloudDiscoveryFromConfig, type CloudServerConfig } from '#cloud/server/config'
import type { CloudDatabase } from '#cloud/server/db'
import { createDocumentService } from '#cloud/server/documents'
+import { createDocumentVersionService } from '#cloud/server/documents/versions'
import type { TransactionalEmailService } from '#cloud/server/email'
import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
import type { ObjectStore } from '#cloud/server/objects'
@@ -198,6 +199,10 @@ export function createCloudApp(services: CloudServices) {
policy,
technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes
})
+ const versions = createDocumentVersionService(services.database, services.objects, {
+ policy,
+ deploymentMode: services.config.deployment
+ })
const entitlements = createEntitlementService(
services.database,
policy,
@@ -276,6 +281,7 @@ export function createCloudApp(services: CloudServices) {
database: services.database,
rateLimitSecret: services.config.authSecret,
documents,
+ versions,
entitlements,
sharing,
workspaces,
@@ -285,6 +291,7 @@ export function createCloudApp(services: CloudServices) {
const publicCloudAPI = createPublicCloudAPIRouter({
collaboration,
documents,
+ versions,
entitlements,
sharing,
workspaces,
diff --git a/packages/cloud/src/server/cleanup/documents.ts b/packages/cloud/src/server/cleanup/documents.ts
index 66e595aed..b7fe1ea30 100644
--- a/packages/cloud/src/server/cleanup/documents.ts
+++ b/packages/cloud/src/server/cleanup/documents.ts
@@ -2,6 +2,8 @@ import type { CloudDatabase } from '#cloud/server/db'
import type { ObjectStore } from '#cloud/server/objects'
import type { Kysely } from 'kysely'
+import { unreferencedObject } from './objects'
+
export type DocumentCleanupOptions = {
batchSize: number
leaseDurationMs: number
@@ -193,16 +195,7 @@ async function removeDocumentMetadata(
const deleted = await transaction
.deleteFrom('storageObject')
.where('id', '=', object.id)
- .where((expression) =>
- expression.not(
- expression.exists(
- expression
- .selectFrom('documentRevision')
- .select('documentRevision.id')
- .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')
- )
- )
- )
+ .where(unreferencedObject)
.executeTakeFirst()
if (Number(deleted.numDeletedRows) > 0) {
objectsDeleted++
diff --git a/packages/cloud/src/server/cleanup/index.ts b/packages/cloud/src/server/cleanup/index.ts
index db140b086..17a1c884e 100644
--- a/packages/cloud/src/server/cleanup/index.ts
+++ b/packages/cloud/src/server/cleanup/index.ts
@@ -4,6 +4,13 @@ export {
type DocumentCleanupResult,
type DocumentCleanupService
} from './documents'
+export {
+ createRevisionCompactionService,
+ REVISION_COMPACTION_GRACE_MS,
+ type RevisionCompactionOptions,
+ type RevisionCompactionResult,
+ type RevisionCompactionService
+} from './revisions'
export {
createUploadCleanupService,
type UploadCleanupOptions,
diff --git a/packages/cloud/src/server/cleanup/objects.ts b/packages/cloud/src/server/cleanup/objects.ts
new file mode 100644
index 000000000..c87edbb3f
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/objects.ts
@@ -0,0 +1,14 @@
+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. */
+export function unreferencedObject(expression: ExpressionBuilder<CloudDatabase, 'storageObject'>) {
+ return expression.not(
+ expression.exists(
+ expression
+ .selectFrom('documentRevision')
+ .select('documentRevision.id')
+ .whereRef('documentRevision.storageObjectId', '=', 'storageObject.id')
+ )
+ )
+}
diff --git a/packages/cloud/src/server/cleanup/revisions.ts b/packages/cloud/src/server/cleanup/revisions.ts
new file mode 100644
index 000000000..b7f8c3700
--- /dev/null
+++ b/packages/cloud/src/server/cleanup/revisions.ts
@@ -0,0 +1,215 @@
+import type { CloudDatabase } from '#cloud/server/db'
+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'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import { groupBy, sumBy, uniq } from 'es-toolkit'
+import type { Kysely, Transaction } from 'kysely'
+
+import { unreferencedObject } from './objects'
+
+/** How long a save between versions is kept before compaction may delete it. */
+export const REVISION_COMPACTION_GRACE_MS = 24 * 60 * 60_000
+
+export type RevisionCompactionOptions = {
+ batchSize: number
+ /** How long a save stays before it can be compacted, so recent work is never lost to it. */
+ graceMs: number
+ now?: Date
+}
+
+export type RevisionCompactionResult = {
+ versionsPruned: number
+ revisionsDeleted: number
+ objectsDeleted: number
+ bytesReclaimed: number
+ failed: number
+}
+
+export type RevisionCompactionService = {
+ compactRevisions(options: RevisionCompactionOptions): Promise<RevisionCompactionResult>
+}
+
+/**
+ * Keeps a document's stored history to its versions. A save that is neither the document's
+ * current state nor kept by a version is deleted once it is older than the grace period, and its
+ * file with it when nothing else uses it; a workspace without full history first loses the
+ * versions older than its 30 days.
+ */
+export function createRevisionCompactionService(
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore,
+ options: { policy?: CloudPolicy; deploymentMode?: CloudPolicyContext['deploymentMode'] } = {}
+): RevisionCompactionService {
+ const deploymentMode = options.deploymentMode ?? 'self-hosted'
+ async function pruneVersions(now: Date, batchSize: number): Promise<number> {
+ if (!options.policy) return 0
+ const limitedBefore = new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)
+ const workspaces = await database
+ .selectFrom('documentVersion')
+ .innerJoin('document', 'document.id', 'documentVersion.documentId')
+ .select('document.workspaceId')
+ .distinct()
+ .where('documentVersion.createdAt', '<', limitedBefore)
+ .execute()
+ let pruned = 0
+ for (const { workspaceId } of workspaces) {
+ const start = await historyStart(options.policy, deploymentMode, workspaceId, now)
+ if (!start) continue
+ const deleted = await database
+ .deleteFrom('documentVersion')
+ .where('id', 'in', (query) =>
+ query
+ .selectFrom('documentVersion as version')
+ .innerJoin('document', 'document.id', 'version.documentId')
+ .select('version.id')
+ .where('document.workspaceId', '=', workspaceId)
+ .where('version.createdAt', '<', start)
+ // The document's current state stays listed however old it is.
+ .whereRef('version.revisionId', '!=', 'document.currentRevisionId')
+ .limit(batchSize)
+ )
+ .executeTakeFirst()
+ pruned += Number(deleted.numDeletedRows)
+ }
+ return pruned
+ }
+
+ /** Saves that may go: old, unversioned, not current, in a document that is not deleted. */
+ function compactable(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>, before: Date) {
+ return source
+ .selectFrom('documentRevision')
+ .innerJoin('document', 'document.id', 'documentRevision.documentId')
+ .where('documentRevision.createdAt', '<', before)
+ .where('document.deletedAt', 'is', null)
+ .where((expression) =>
+ expression.or([
+ expression('document.currentRevisionId', 'is', null),
+ expression('document.currentRevisionId', '!=', expression.ref('documentRevision.id'))
+ ])
+ )
+ .where((expression) =>
+ expression.not(
+ expression.exists(
+ expression
+ .selectFrom('documentVersion')
+ .select('documentVersion.id')
+ .whereRef('documentVersion.revisionId', '=', 'documentRevision.id')
+ )
+ )
+ )
+ }
+
+ /** A file no revision refers to: freed by compaction, waiting for the object store. */
+ function unreferencedObjects(source: Kysely<CloudDatabase> | Transaction<CloudDatabase>) {
+ return source.selectFrom('storageObject').where(unreferencedObject)
+ }
+
+ /**
+ * Deletes up to `limit` compactable saves of one document and returns the bytes of files nothing
+ * refers to any more to the workspace's usage. Their rows stay until the files are gone, so a
+ * delete that fails is tried again on the next pass.
+ */
+ async function compactDocument(
+ documentId: string,
+ workspaceId: string,
+ before: Date,
+ limit: number
+ ) {
+ return database.transaction().execute(async (transaction) => {
+ // Saves and restores lock the document too, so none can keep a revision deleted here.
+ await transaction
+ .selectFrom('document')
+ .select('id')
+ .where('id', '=', documentId)
+ .forUpdate()
+ .executeTakeFirst()
+ const revisions = await compactable(transaction, before)
+ .select(['documentRevision.id', 'documentRevision.storageObjectId'])
+ .where('documentRevision.documentId', '=', documentId)
+ .limit(limit)
+ .execute()
+ if (revisions.length === 0) return { revisions: 0, bytes: 0 }
+ await transaction
+ .deleteFrom('documentRevision')
+ .where(
+ 'id',
+ 'in',
+ revisions.map((revision) => revision.id)
+ )
+ .execute()
+ const freed = await unreferencedObjects(transaction)
+ .select('byteSize')
+ .where('id', 'in', uniq(revisions.map((revision) => revision.storageObjectId)))
+ .execute()
+ const bytes = sumBy(freed, (object) => Number(object.byteSize))
+ if (bytes > 0) {
+ await transaction
+ .updateTable('workspaceStorageUsage')
+ .set({
+ committedBytes: (expression) => expression('committedBytes', '-', bytes),
+ updatedAt: new Date()
+ })
+ .where('workspaceId', '=', workspaceId)
+ .execute()
+ }
+ return { revisions: revisions.length, bytes }
+ })
+ }
+
+ /** Deletes freed files from the object store, then their rows; a failure stays for next time. */
+ async function sweepObjects(batchSize: number, result: RevisionCompactionResult) {
+ const freed = await unreferencedObjects(database)
+ .select(['id', 'objectKey'])
+ .limit(batchSize)
+ .execute()
+ for (const object of freed) {
+ try {
+ await objects.delete(object.objectKey)
+ await database
+ .deleteFrom('storageObject')
+ .where('id', '=', object.id)
+ .where(unreferencedObject)
+ .execute()
+ result.objectsDeleted++
+ } catch {
+ result.failed++
+ }
+ }
+ }
+
+ return {
+ async compactRevisions(input) {
+ const now = input.now ?? new Date()
+ const before = new Date(now.getTime() - input.graceMs)
+ const result: RevisionCompactionResult = {
+ versionsPruned: await pruneVersions(now, input.batchSize),
+ revisionsDeleted: 0,
+ objectsDeleted: 0,
+ bytesReclaimed: 0,
+ failed: 0
+ }
+ const candidates = await compactable(database, before)
+ .select(['documentRevision.documentId', 'document.workspaceId'])
+ .limit(input.batchSize)
+ .execute()
+ let capacity = input.batchSize
+ for (const [documentId, rows] of Object.entries(
+ groupBy(candidates, (row) => row.documentId)
+ )) {
+ const workspaceId = rows[0]?.workspaceId
+ if (!workspaceId || capacity <= 0) continue
+ try {
+ const compacted = await compactDocument(documentId, workspaceId, before, capacity)
+ capacity -= compacted.revisions
+ result.revisionsDeleted += compacted.revisions
+ result.bytesReclaimed += compacted.bytes
+ } catch {
+ result.failed++
+ }
+ }
+ await sweepObjects(input.batchSize, result)
+ return result
+ }
+ }
+}
diff --git a/packages/cloud/src/server/cleanup/worker.ts b/packages/cloud/src/server/cleanup/worker.ts
index 19005d4cf..239662518 100644
--- a/packages/cloud/src/server/cleanup/worker.ts
+++ b/packages/cloud/src/server/cleanup/worker.ts
@@ -1,5 +1,10 @@
import { startPeriodicWorker } from '../worker/periodic'
import type { DocumentCleanupResult, DocumentCleanupService } from './documents'
+import {
+ REVISION_COMPACTION_GRACE_MS,
+ type RevisionCompactionResult,
+ type RevisionCompactionService
+} from './revisions'
import type { UploadCleanupResult, UploadCleanupService } from './uploads'
export type CleanupWorkerOptions = {
@@ -14,12 +19,14 @@ export type CleanupWorkerOptions = {
export type CleanupResult = {
uploads: UploadCleanupResult
documents: DocumentCleanupResult
+ revisions: RevisionCompactionResult | null
rateLimits: number
}
export type CleanupServices = {
documents: DocumentCleanupService
uploads: UploadCleanupService
+ revisions?: RevisionCompactionService
rateLimits?: { cleanupExpired(before: Date): Promise<number> }
}
@@ -46,10 +53,16 @@ export function startCleanupWorker(
leaseDurationMs: options.leaseDurationMs,
retentionMs: options.documentRetentionMs
})
+ const revisions = cleanup.revisions
+ ? await cleanup.revisions.compactRevisions({
+ batchSize: options.batchSize,
+ graceMs: REVISION_COMPACTION_GRACE_MS
+ })
+ : null
const rateLimits = cleanup.rateLimits
? await cleanup.rateLimits.cleanupExpired(new Date(Date.now() - 24 * 60 * 60_000))
: 0
- return { uploads, documents, rateLimits }
+ return { uploads, documents, revisions, rateLimits }
}
})
}
diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.ts
index ec6b8020a..4c9e68e5f 100644
--- a/packages/cloud/src/server/db/migrate.ts
+++ b/packages/cloud/src/server/db/migrate.ts
@@ -21,6 +21,7 @@ import * as authenticationEmailKinds from './migrations/017_authentication_email
import * as authenticationMFA from './migrations/018_authentication_mfa'
import * as betterAuthAccountIssuer from './migrations/019_better_auth_account_issuer'
import * as workspaceInvitations from './migrations/020_workspace_invitations'
+import * as documentVersions from './migrations/021_document_versions'
import type { CloudDatabase } from './schema'
const migrations: Record<string, Migration> = {
@@ -43,7 +44,8 @@ const migrations: Record<string, Migration> = {
'017_authentication_email_kinds': authenticationEmailKinds,
'018_authentication_mfa': authenticationMFA,
'019_better_auth_account_issuer': betterAuthAccountIssuer,
- '020_workspace_invitations': workspaceInvitations
+ '020_workspace_invitations': workspaceInvitations,
+ '021_document_versions': documentVersions
}
class CloudMigrationProvider implements MigrationProvider {
diff --git a/packages/cloud/src/server/db/migrations/021_document_versions.ts b/packages/cloud/src/server/db/migrations/021_document_versions.ts
new file mode 100644
index 000000000..5dfa85d01
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/021_document_versions.ts
@@ -0,0 +1,66 @@
+import { checkColumnIn } from '#cloud/server/db/expressions'
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+import { addCurrentTimestampColumns } from './helpers'
+
+/**
+ * A document's version history: the revisions kept as checkpoints or named versions. Saves in
+ * between are compacted away, so a version is what keeps a revision and its stored file.
+ */
+export async function up(database: Kysely<unknown>): Promise<void> {
+ await database.schema
+ .createTable('document_version')
+ .addColumn('id', 'uuid', (column) => column.primaryKey())
+ .addColumn('document_id', 'uuid', (column) =>
+ column.references('document.id').onDelete('cascade').notNull()
+ )
+ .addColumn('revision_id', 'uuid', (column) =>
+ column.references('document_revision.id').onDelete('cascade').notNull().unique()
+ )
+ .addColumn('kind', 'text', (column) => column.notNull())
+ .addColumn('name', 'text')
+ .addColumn('description', 'text')
+ .addColumn('created_by', 'text', (column) => column.notNull())
+ .addColumn('restored_from_version_id', 'uuid', (column) =>
+ column.references('document_version.id').onDelete('set null')
+ )
+ .addCheckConstraint(
+ 'document_version_kind_check',
+ checkColumnIn('kind', ['checkpoint', 'named'])
+ )
+ .execute()
+ await addCurrentTimestampColumns(database, 'document_version', ['created_at'])
+ await database.schema
+ .createIndex('document_version_document_index')
+ .on('document_version')
+ .columns(['document_id', 'created_at desc', 'id desc'])
+ .execute()
+ // History starts with what each document holds now.
+ await keepCurrentRevisions(database as Kysely<CloudDatabase>)
+}
+
+export async function down(database: Kysely<unknown>): Promise<void> {
+ await database.schema.dropTable('document_version').execute()
+}
+
+/** Keeps each document's current revision as the first checkpoint of its history. */
+export async function keepCurrentRevisions(database: Kysely<CloudDatabase>): Promise<void> {
+ await database
+ .insertInto('documentVersion')
+ .columns(['id', 'documentId', 'revisionId', 'kind', 'createdBy', 'createdAt'])
+ .expression((expression) =>
+ expression
+ .selectFrom('document')
+ .innerJoin('documentRevision', 'documentRevision.id', 'document.currentRevisionId')
+ .select((select) => [
+ select.fn<string>('gen_random_uuid').as('id'),
+ 'document.id as documentId',
+ 'documentRevision.id as revisionId',
+ select.val('checkpoint').as('kind'),
+ 'documentRevision.createdBy',
+ 'documentRevision.createdAt'
+ ])
+ )
+ .execute()
+}
diff --git a/packages/cloud/src/server/db/schema.ts b/packages/cloud/src/server/db/schema.ts
index cba542cb0..c31ce7e92 100644
--- a/packages/cloud/src/server/db/schema.ts
+++ b/packages/cloud/src/server/db/schema.ts
@@ -108,6 +108,19 @@ export interface DocumentRevisionTable {
createdAt: TimestampColumn
}
+/** A revision kept in the document's history; see migration 021. */
+export interface DocumentVersionTable {
+ id: string
+ documentId: string
+ revisionId: string
+ kind: 'checkpoint' | 'named'
+ name: string | null
+ description: string | null
+ createdBy: string
+ restoredFromVersionId: string | null
+ createdAt: TimestampColumn
+}
+
export interface UploadTable {
id: string
documentId: string
@@ -292,6 +305,7 @@ export interface CloudDatabase {
document: DocumentTable
storageObject: StorageObjectTable
documentRevision: DocumentRevisionTable
+ documentVersion: DocumentVersionTable
documentShare: DocumentShareTable
documentGrant: DocumentGrantTable
documentInvitation: DocumentInvitationTable
@@ -312,6 +326,7 @@ export type WorkspaceUpdate = Updateable<WorkspaceTable>
export type Document = Selectable<DocumentTable>
export type NewDocument = Insertable<DocumentTable>
export type DocumentRevision = Selectable<DocumentRevisionTable>
+export type DocumentVersion = Selectable<DocumentVersionTable>
export type NewDocumentRevision = Insertable<DocumentRevisionTable>
export type DocumentShare = Selectable<DocumentShareTable>
export type NewDocumentShare = Insertable<DocumentShareTable>
diff --git a/packages/cloud/src/server/documents/routes.ts b/packages/cloud/src/server/documents/routes.ts
index 80cbc068f..4dd449577 100644
--- a/packages/cloud/src/server/documents/routes.ts
+++ b/packages/cloud/src/server/documents/routes.ts
@@ -20,7 +20,8 @@ export type DocumentRouteEnvironment = {
}
}
-function domainError(context: Context, error: unknown): Response | null {
+/** The response a document domain error stands for, or null for any other error. */
+export function documentDomainError(context: Context, error: unknown): Response | null {
if (error instanceof DocumentNotFoundError) {
return context.json({ error: { code: 'not_found' as const } }, 404)
}
@@ -84,7 +85,7 @@ export function createDocumentRoutes(
usage: await service.usage(context.get('actor').userId, context.req.param('workspaceId'))
})
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -101,7 +102,7 @@ export function createDocumentRoutes(
)
return context.json({ document }, 201)
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -112,7 +113,7 @@ export function createDocumentRoutes(
await service.remove(context.get('actor').userId, context.req.param('documentId'))
return context.body(null, 204)
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -123,7 +124,7 @@ export function createDocumentRoutes(
access: await service.access(context.get('actor').userId, context.req.param('documentId'))
})
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -137,7 +138,7 @@ export function createDocumentRoutes(
)
})
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -151,7 +152,7 @@ export function createDocumentRoutes(
)
return context.json(result, 201)
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
@@ -165,7 +166,7 @@ export function createDocumentRoutes(
)
return context.json({ document })
} catch (error) {
- const response = domainError(context, error)
+ const response = documentDomainError(context, error)
if (response) return response
throw error
}
diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.ts
index d07fbac52..ed34f97a0 100644
--- a/packages/cloud/src/server/documents/service.ts
+++ b/packages/cloud/src/server/documents/service.ts
@@ -22,6 +22,7 @@ import {
} from '#cloud/server/documents/repository'
import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'
import type { CreateDocumentUploadResult } from '#cloud/server/documents/types'
+import { 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 { CloudPolicy } from '#cloud/server/policy/policy'
@@ -391,6 +392,13 @@ export function createDocumentService(
})
.where('id', '=', upload.documentId)
.execute()
+ await recordCheckpoint(transaction, {
+ documentId: upload.documentId,
+ previousRevisionId: document.currentRevisionId,
+ revisionId,
+ userId,
+ now: new Date()
+ })
await transaction
.updateTable('upload')
.set({ status: 'committed', finalizationStartedAt: null })
diff --git a/packages/cloud/src/server/documents/versions/checkpoint.ts b/packages/cloud/src/server/documents/versions/checkpoint.ts
new file mode 100644
index 000000000..2add3234d
--- /dev/null
+++ b/packages/cloud/src/server/documents/versions/checkpoint.ts
@@ -0,0 +1,80 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import type { Transaction } from 'kysely'
+
+/** How long the newest version may be old before a save keeps the state it replaces. */
+export const CHECKPOINT_INTERVAL_MS = 30 * 60_000
+
+/** Keeps a revision in the history, unless a version already keeps it. */
+export async function keepRevision(
+ transaction: Transaction<CloudDatabase>,
+ input: {
+ documentId: string
+ revisionId: string
+ createdBy: string
+ createdAt: Date
+ restoredFromVersionId?: string
+ }
+): Promise<void> {
+ await transaction
+ .insertInto('documentVersion')
+ .values({
+ id: crypto.randomUUID(),
+ documentId: input.documentId,
+ revisionId: input.revisionId,
+ kind: 'checkpoint',
+ name: null,
+ description: null,
+ createdBy: input.createdBy,
+ restoredFromVersionId: input.restoredFromVersionId ?? null,
+ createdAt: input.createdAt
+ })
+ .onConflict((conflict) => conflict.column('revisionId').doNothing())
+ .execute()
+}
+
+/**
+ * Records the history's checkpoints as a save lands: the document's first save, and the state a
+ * save replaces once the newest version is half an hour old. Each stretch of editing, and how the
+ * document was left at the end of every session, stays in the history; the saves between them are
+ * compacted later.
+ */
+export async function recordCheckpoint(
+ transaction: Transaction<CloudDatabase>,
+ input: {
+ documentId: string
+ previousRevisionId: string | null
+ revisionId: string
+ userId: string
+ now: Date
+ }
+): Promise<void> {
+ if (!input.previousRevisionId) {
+ await keepRevision(transaction, {
+ documentId: input.documentId,
+ revisionId: input.revisionId,
+ createdBy: input.userId,
+ createdAt: input.now
+ })
+ return
+ }
+ const newest = await transaction
+ .selectFrom('documentVersion')
+ .select('createdAt')
+ .where('documentId', '=', input.documentId)
+ .orderBy('createdAt', 'desc')
+ .limit(1)
+ .executeTakeFirst()
+ if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) return
+ const previous = await transaction
+ .selectFrom('documentRevision')
+ .select(['createdBy', 'createdAt'])
+ .where('id', '=', input.previousRevisionId)
+ .executeTakeFirst()
+ if (!previous) return
+ await keepRevision(transaction, {
+ documentId: input.documentId,
+ revisionId: input.previousRevisionId,
+ createdBy: previous.createdBy,
+ createdAt: previous.createdAt
+ })
+}
diff --git a/packages/cloud/src/server/documents/versions/history.ts b/packages/cloud/src/server/documents/versions/history.ts
new file mode 100644
index 000000000..44da96a91
--- /dev/null
+++ b/packages/cloud/src/server/documents/versions/history.ts
@@ -0,0 +1,25 @@
+import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from '#cloud/server/policy/keys'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+
+/** How far back a workspace without full revision history keeps its versions. */
+export const LIMITED_HISTORY_DAYS = 30
+
+/**
+ * The oldest moment a workspace's history reaches, or null when it keeps everything: with the
+ * `revisionHistory` entitlement off, only the last 30 days, as on a free plan.
+ */
+export async function historyStart(
+ policy: CloudPolicy | undefined,
+ deploymentMode: CloudPolicyContext['deploymentMode'],
+ workspaceId: string,
+ now: Date
+): Promise<Date | null> {
+ const full = policy
+ ? await policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, true, {
+ targetingKey: workspaceId,
+ workspaceId,
+ deploymentMode
+ })
+ : true
+ return full ? null : new Date(now.getTime() - LIMITED_HISTORY_DAYS * 24 * 60 * 60_000)
+}
diff --git a/packages/cloud/src/server/documents/versions/index.ts b/packages/cloud/src/server/documents/versions/index.ts
new file mode 100644
index 000000000..c77c382d2
--- /dev/null
+++ b/packages/cloud/src/server/documents/versions/index.ts
@@ -0,0 +1,4 @@
+export { CHECKPOINT_INTERVAL_MS } from './checkpoint'
+export { LIMITED_HISTORY_DAYS, historyStart } from './history'
+export { createDocumentVersionRoutes } from './routes'
+export { createDocumentVersionService, type DocumentVersionService } from './service'
diff --git a/packages/cloud/src/server/documents/versions/routes.ts b/packages/cloud/src/server/documents/versions/routes.ts
new file mode 100644
index 000000000..173b216ef
--- /dev/null
+++ b/packages/cloud/src/server/documents/versions/routes.ts
@@ -0,0 +1,112 @@
+import {
+ parseDuplicateDocumentVersion,
+ parseSaveDocumentVersion,
+ parseUpdateDocumentVersion
+} from '#cloud/contract'
+import { documentDomainError, type DocumentRouteEnvironment } from '#cloud/server/documents/routes'
+import { validatedJSON, validatedQuery } from '#cloud/server/validation'
+import { Hono, type Context } from 'hono'
+import * as v from 'valibot'
+
+import type { DocumentVersionService } from './service'
+
+const pageSchema = v.object({
+ before: v.optional(v.pipe(v.string(), v.uuid())),
+ limit: v.optional(v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(1)))
+})
+const parsePage = (input: unknown) => v.parse(pageSchema, input)
+
+async function answer(context: Context, run: () => Promise<Response>): Promise<Response> {
+ try {
+ return await run()
+ } catch (error) {
+ const response = documentDomainError(context, error)
+ if (response) return response
+ throw error
+ }
+}
+
+/** A document's version history: listing, naming, opening, restoring, and duplicating versions. */
+export function createDocumentVersionRoutes(service: DocumentVersionService) {
+ return new Hono<DocumentRouteEnvironment>()
+ .get('/documents/:documentId/versions', validatedQuery(parsePage), (context) =>
+ answer(context, async () =>
+ context.json(
+ await service.list(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('query')
+ )
+ )
+ )
+ )
+ .post('/documents/:documentId/versions', validatedJSON(parseSaveDocumentVersion), (context) =>
+ answer(context, async () =>
+ context.json(
+ {
+ version: await service.save(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.valid('json')
+ )
+ },
+ 201
+ )
+ )
+ )
+ .patch(
+ '/documents/:documentId/versions/:versionId',
+ validatedJSON(parseUpdateDocumentVersion),
+ (context) =>
+ answer(context, async () =>
+ context.json({
+ version: await service.update(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('versionId'),
+ context.req.valid('json')
+ )
+ })
+ )
+ )
+ .get('/documents/:documentId/versions/:versionId', (context) =>
+ answer(context, async () =>
+ context.json({
+ document: await service.download(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('versionId')
+ )
+ })
+ )
+ )
+ .post('/documents/:documentId/versions/:versionId/restore', (context) =>
+ answer(context, async () =>
+ context.json(
+ await service.restore(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('versionId')
+ )
+ )
+ )
+ )
+ .post(
+ '/documents/:documentId/versions/:versionId/duplicate',
+ validatedJSON(parseDuplicateDocumentVersion),
+ (context) =>
+ answer(context, async () =>
+ context.json(
+ {
+ document: await service.duplicate(
+ context.get('actor').userId,
+ context.req.param('documentId'),
+ context.req.param('versionId'),
+ context.req.valid('json')
+ )
+ },
+ 201
+ )
+ )
+ )
+}
diff --git a/packages/cloud/src/server/documents/versions/service.ts b/packages/cloud/src/server/documents/versions/service.ts
new file mode 100644
index 000000000..1e77f3d56
--- /dev/null
+++ b/packages/cloud/src/server/documents/versions/service.ts
@@ -0,0 +1,376 @@
+import type {
+ DocumentDownload,
+ DocumentSummary,
+ DocumentVersion,
+ DocumentVersions,
+ DuplicateDocumentVersionInput,
+ SaveDocumentVersionInput,
+ UpdateDocumentVersionInput
+} from '#cloud/contract'
+import type { CloudDatabase } from '#cloud/server/db'
+import { canEditDocument, resolveDocumentAccess } from '#cloud/server/documents/access'
+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'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import type { Kysely, Transaction } from 'kysely'
+
+import { keepRevision } from './checkpoint'
+import { historyStart } from './history'
+
+const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
+const DEFAULT_PAGE_SIZE = 50
+const MAXIMUM_PAGE_SIZE = 100
+const WRITABLE_ROLES = new Set(['admin', 'editor'])
+
+type VersionRow = {
+ id: string
+ revisionId: string
+ kind: 'checkpoint' | 'named'
+ name: string | null
+ description: string | null
+ createdAt: Date
+ createdBy: string
+ createdByName: string | null
+ restoredFromVersionId: string | null
+}
+
+function versionOf(row: VersionRow, currentRevisionId: string | null): DocumentVersion {
+ return {
+ id: row.id,
+ revisionId: row.revisionId,
+ kind: row.kind,
+ name: row.name,
+ description: row.description,
+ createdAt: row.createdAt.toISOString(),
+ createdBy: { id: row.createdBy, name: row.createdByName },
+ restoredFromVersionId: row.restoredFromVersionId,
+ current: row.revisionId === currentRevisionId
+ }
+}
+
+/**
+ * A document's version history: its checkpoints and named versions, newest first, and what can be
+ * done with one. Anyone who can open the document sees its history; editors name and restore.
+ */
+export function createDocumentVersionService(
+ database: Kysely<CloudDatabase>,
+ objects: ObjectStore,
+ options: { policy?: CloudPolicy; deploymentMode?: CloudPolicyContext['deploymentMode'] } = {}
+) {
+ const deploymentMode = options.deploymentMode ?? 'self-hosted'
+ function versions() {
+ return database
+ .selectFrom('documentVersion')
+ .leftJoin('user', (join) =>
+ join.on((expression) =>
+ expression(
+ expression.cast(expression.ref('user.id'), 'text'),
+ '=',
+ expression.ref('documentVersion.createdBy')
+ )
+ )
+ )
+ .select([
+ 'documentVersion.id',
+ 'documentVersion.revisionId',
+ 'documentVersion.kind',
+ 'documentVersion.name',
+ 'documentVersion.description',
+ 'documentVersion.createdAt',
+ 'documentVersion.createdBy',
+ 'user.name as createdByName',
+ 'documentVersion.restoredFromVersionId'
+ ])
+ }
+
+ /** The document the person may see the history of, and where that history starts. */
+ async function openHistory(userId: string, documentId: string, edit: boolean) {
+ const access = await resolveDocumentAccess(database, userId, documentId)
+ if (!access) throw new DocumentNotFoundError()
+ if (edit && !canEditDocument(access)) throw new DocumentForbiddenError()
+ const document = await getDocumentSummaryRow(database, documentId)
+ if (!document) throw new DocumentNotFoundError()
+ return {
+ document,
+ start: await historyStart(options.policy, deploymentMode, document.workspaceId, new Date())
+ }
+ }
+
+ async function findVersion(documentId: string, versionId: string, start: Date | null) {
+ let query = versions()
+ .where('documentVersion.documentId', '=', documentId)
+ .where('documentVersion.id', '=', versionId)
+ if (start) query = query.where('documentVersion.createdAt', '>=', start)
+ const row = await query.executeTakeFirst()
+ if (!row) throw new DocumentNotFoundError()
+ return row
+ }
+
+ /** The stored file of a revision; read under the document's lock before reusing it. */
+ async function storedRevision(
+ source: Kysely<CloudDatabase> | Transaction<CloudDatabase>,
+ revisionId: string
+ ) {
+ const stored = await source
+ .selectFrom('documentRevision')
+ .innerJoin('storageObject', 'storageObject.id', 'documentRevision.storageObjectId')
+ .select([
+ 'documentRevision.storageObjectId',
+ 'storageObject.objectKey',
+ 'storageObject.byteSize',
+ 'storageObject.checksum',
+ 'storageObject.contentType'
+ ])
+ .where('documentRevision.id', '=', revisionId)
+ .executeTakeFirst()
+ if (!stored) throw new DocumentNotFoundError()
+ return stored
+ }
+
+ return {
+ async list(
+ userId: string,
+ documentId: string,
+ page: { before?: string; limit?: number } = {}
+ ): Promise<DocumentVersions> {
+ const { document, start } = await openHistory(userId, documentId, false)
+ const limit = Math.min(Math.max(page.limit ?? DEFAULT_PAGE_SIZE, 1), MAXIMUM_PAGE_SIZE)
+ let query = versions().where('documentVersion.documentId', '=', documentId)
+ if (start) query = query.where('documentVersion.createdAt', '>=', start)
+ if (page.before) {
+ const cursor = await findVersion(documentId, page.before, start)
+ query = query.where((expression) =>
+ expression.or([
+ expression('documentVersion.createdAt', '<', cursor.createdAt),
+ expression.and([
+ expression('documentVersion.createdAt', '=', cursor.createdAt),
+ expression('documentVersion.id', '<', cursor.id)
+ ])
+ ])
+ )
+ }
+ const rows = await query
+ .orderBy('documentVersion.createdAt', 'desc')
+ .orderBy('documentVersion.id', 'desc')
+ .limit(limit + 1)
+ .execute()
+ const shown = rows.slice(0, limit)
+ return {
+ versions: shown.map((row) => versionOf(row, document.currentRevisionId)),
+ nextCursor: rows.length > limit ? (shown.at(-1)?.id ?? null) : null
+ }
+ },
+
+ /** Names the document as it is now, as Save to version history does. */
+ async save(
+ userId: string,
+ documentId: string,
+ input: SaveDocumentVersionInput
+ ): Promise<DocumentVersion> {
+ const { document } = await openHistory(userId, documentId, true)
+ const revisionId = document.currentRevisionId
+ if (!revisionId) throw new DocumentNotFoundError()
+ const description = input.description || null
+ await database
+ .insertInto('documentVersion')
+ .values({
+ id: crypto.randomUUID(),
+ documentId,
+ revisionId,
+ kind: 'named',
+ name: input.name,
+ description,
+ createdBy: userId,
+ restoredFromVersionId: null
+ })
+ .onConflict((conflict) =>
+ conflict
+ .column('revisionId')
+ .doUpdateSet({ kind: 'named', name: input.name, description })
+ )
+ .execute()
+ const row = await versions()
+ .where('documentVersion.revisionId', '=', revisionId)
+ .executeTakeFirstOrThrow()
+ return versionOf(row, revisionId)
+ },
+
+ /** Names a version, renames it, or with a null name deletes its info so it is a checkpoint. */
+ async update(
+ userId: string,
+ documentId: string,
+ versionId: string,
+ input: UpdateDocumentVersionInput
+ ): Promise<DocumentVersion> {
+ const { document, start } = await openHistory(userId, documentId, true)
+ await findVersion(documentId, versionId, start)
+ await database
+ .updateTable('documentVersion')
+ .set(
+ input.name
+ ? { kind: 'named', name: input.name, description: input.description || null }
+ : { kind: 'checkpoint', name: null, description: null }
+ )
+ .where('id', '=', versionId)
+ .execute()
+ return versionOf(await findVersion(documentId, versionId, start), document.currentRevisionId)
+ },
+
+ async download(
+ userId: string,
+ documentId: string,
+ versionId: string
+ ): Promise<DocumentDownload> {
+ const { document, start } = await openHistory(userId, documentId, false)
+ const version = await findVersion(documentId, versionId, start)
+ const stored = await storedRevision(database, version.revisionId)
+ return {
+ document: documentSummary(document),
+ revisionId: version.revisionId,
+ 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)
+ })
+ }
+ },
+
+ /**
+ * Makes a version the document's current state without losing anything: the state it replaces
+ * is kept as a checkpoint, the restored state becomes a new revision of the same stored file,
+ * and the document's live room starts over so everyone has the restored version.
+ */
+ async restore(
+ userId: string,
+ documentId: string,
+ versionId: string
+ ): Promise<{ document: DocumentSummary; version: DocumentVersion }> {
+ const { start } = await openHistory(userId, documentId, true)
+ const version = await findVersion(documentId, versionId, start)
+ const revisionId = crypto.randomUUID()
+ const now = new Date()
+ await database.transaction().execute(async (transaction) => {
+ const locked = await transaction
+ .selectFrom('document')
+ .select(['currentRevisionId', 'deletedAt'])
+ .where('id', '=', documentId)
+ .forUpdate()
+ .executeTakeFirst()
+ if (!locked || locked.deletedAt) throw new DocumentNotFoundError()
+ // Compaction locks the document too, so the version's file cannot go while it is reused.
+ const stored = await storedRevision(transaction, version.revisionId)
+ if (locked.currentRevisionId) {
+ const current = await transaction
+ .selectFrom('documentRevision')
+ .select('createdBy')
+ .where('id', '=', locked.currentRevisionId)
+ .executeTakeFirstOrThrow()
+ await keepRevision(transaction, {
+ documentId,
+ revisionId: locked.currentRevisionId,
+ createdBy: current.createdBy,
+ createdAt: now
+ })
+ }
+ await transaction
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId,
+ parentRevisionId: locked.currentRevisionId,
+ storageObjectId: stored.storageObjectId,
+ createdBy: userId
+ })
+ .execute()
+ await transaction
+ .updateTable('document')
+ .set({
+ currentRevisionId: revisionId,
+ version: (expression) => expression('version', '+', 1),
+ collaborationEpoch: (expression) => expression('collaborationEpoch', '+', 1)
+ })
+ .where('id', '=', documentId)
+ .execute()
+ // A moment after the state it replaces, so the history lists it first.
+ await keepRevision(transaction, {
+ documentId,
+ revisionId,
+ createdBy: userId,
+ createdAt: new Date(now.getTime() + 1),
+ restoredFromVersionId: versionId
+ })
+ })
+ const document = await findDocument(database, userId, documentId)
+ if (!document) throw new DocumentNotFoundError()
+ const restored = await versions()
+ .where('documentVersion.revisionId', '=', revisionId)
+ .executeTakeFirstOrThrow()
+ return { document, version: versionOf(restored, revisionId) }
+ },
+
+ /** Makes a new document in the same workspace from a version, sharing its stored file. */
+ async duplicate(
+ userId: string,
+ documentId: string,
+ versionId: string,
+ input: DuplicateDocumentVersionInput
+ ): Promise<DocumentSummary> {
+ const { document, start } = await openHistory(userId, documentId, false)
+ const role = await workspaceRole(database, userId, document.workspaceId)
+ if (!role) throw new DocumentNotFoundError()
+ if (!WRITABLE_ROLES.has(role)) throw new DocumentForbiddenError()
+ const version = await findVersion(documentId, versionId, start)
+ const copyId = crypto.randomUUID()
+ const revisionId = crypto.randomUUID()
+ await database.transaction().execute(async (transaction) => {
+ // Deleted-document cleanup removes files its document alone uses; holding the source
+ // until the copy refers to the file means cleanup either finishes first or sees the copy.
+ const source = await transaction
+ .selectFrom('document')
+ .select(['deletedAt', 'cleanupClaimId'])
+ .where('id', '=', documentId)
+ .forUpdate()
+ .executeTakeFirst()
+ if (!source || source.deletedAt || source.cleanupClaimId) throw new DocumentNotFoundError()
+ const stored = await storedRevision(transaction, version.revisionId)
+ await insertDocument(transaction, {
+ id: copyId,
+ workspaceId: document.workspaceId,
+ name: input.name,
+ createdBy: userId
+ })
+ await transaction
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId: copyId,
+ parentRevisionId: null,
+ storageObjectId: stored.storageObjectId,
+ createdBy: userId
+ })
+ .execute()
+ await transaction
+ .updateTable('document')
+ .set({ currentRevisionId: revisionId, version: 1 })
+ .where('id', '=', copyId)
+ .execute()
+ await keepRevision(transaction, {
+ documentId: copyId,
+ revisionId,
+ createdBy: userId,
+ createdAt: new Date()
+ })
+ })
+ const copy = await findDocument(database, userId, copyId)
+ if (!copy) throw new DocumentNotFoundError()
+ return copy
+ }
+ }
+}
+
+export type DocumentVersionService = ReturnType<typeof createDocumentVersionService>
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
index 452564b64..6c7bce807 100644
--- a/packages/cloud/src/server/index.ts
+++ b/packages/cloud/src/server/index.ts
@@ -55,7 +55,9 @@ export {
} from './app'
export {
createDocumentCleanupService,
+ createRevisionCompactionService,
createUploadCleanupService,
+ REVISION_COMPACTION_GRACE_MS,
startCleanupWorker,
type CleanupResult,
type CleanupServices,
@@ -141,6 +143,13 @@ export {
type DocumentRouteEnvironment,
type DocumentService
} from './documents'
+export {
+ CHECKPOINT_INTERVAL_MS,
+ createDocumentVersionRoutes,
+ createDocumentVersionService,
+ LIMITED_HISTORY_DAYS,
+ type DocumentVersionService
+} from './documents/versions'
export {
createInvitationOutbox,
createTransactionalEmailService,
diff --git a/packages/cloud/src/server/policy/policy.ts b/packages/cloud/src/server/policy/policy.ts
index 24fb5f681..0763092a8 100644
--- a/packages/cloud/src/server/policy/policy.ts
+++ b/packages/cloud/src/server/policy/policy.ts
@@ -1,10 +1,10 @@
import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES } from '#cloud/server/config'
import {
- OpenFeature,
+ DefaultLogger,
TypedInMemoryProvider,
- type Client,
type EvaluationContext,
- type Provider
+ type Provider,
+ type ResolutionDetails
} from '@openfeature/server-sdk'
import { CLOUD_FEATURE_KEYS, type CloudPolicyContext } from './keys'
@@ -64,20 +64,54 @@ function evaluationContext(context: CloudPolicyContext): EvaluationContext {
return evaluation
}
+const logger = new DefaultLogger()
+
+/** A flag's value, or the default when the provider failed or reported an error, as a client does. */
+async function resolved<T>(evaluation: () => Promise<ResolutionDetails<T>>, defaultValue: T) {
+ try {
+ const details = await evaluation()
+ return details.errorCode ? defaultValue : details.value
+ } catch {
+ return defaultValue
+ }
+}
+
+/**
+ * Answers entitlement questions from one OpenFeature provider. It asks the provider directly
+ * rather than through the global `OpenFeature` API: each app has its own provider, and the API
+ * keeps every provider registered under a domain reachable for the life of the process, with the
+ * database its entitlement source holds.
+ */
export class CloudPolicy {
- constructor(private readonly client: Client) {}
+ constructor(private readonly provider: Provider) {}
boolean(key: string, defaultValue: boolean, context: CloudPolicyContext): Promise<boolean> {
- return this.client.getBooleanValue(key, defaultValue, evaluationContext(context))
+ return resolved(
+ () =>
+ this.provider.resolveBooleanEvaluation(
+ key,
+ defaultValue,
+ evaluationContext(context),
+ logger
+ ),
+ defaultValue
+ )
}
number(key: string, defaultValue: number, context: CloudPolicyContext): Promise<number> {
- return this.client.getNumberValue(key, defaultValue, evaluationContext(context))
+ return resolved(
+ () =>
+ this.provider.resolveNumberEvaluation(
+ key,
+ defaultValue,
+ evaluationContext(context),
+ logger
+ ),
+ defaultValue
+ )
}
}
export function createDefaultCloudPolicy(provider?: Provider): CloudPolicy {
- const domain = `openpencil-cloud-${crypto.randomUUID()}`
- OpenFeature.setProvider(domain, provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))
- return new CloudPolicy(OpenFeature.getClient(domain))
+ return new CloudPolicy(provider ?? new TypedInMemoryProvider(DEFAULT_FLAGS))
}
diff --git a/packages/cloud/tests/client/api.test.ts b/packages/cloud/tests/client/api.test.ts
index ba117942e..6f9882b45 100644
--- a/packages/cloud/tests/client/api.test.ts
+++ b/packages/cloud/tests/client/api.test.ts
@@ -44,6 +44,34 @@ describe('createCloudAPIClient', () => {
expect(requests[0]?.credentials).toBe('include')
})
+ test('pages through the version history of a document', async () => {
+ const version = {
+ id: '44444444-4444-4444-8444-444444444444',
+ revisionId,
+ kind: 'named' as const,
+ name: 'Hand-off',
+ description: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ createdBy: { id: 'alice', name: 'Alice' },
+ restoredFromVersionId: null,
+ current: true
+ }
+ const requests: Request[] = []
+ const client = createCloudAPIClient('https://cloud.example.com/api', {
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init))
+ return Response.json({ versions: [version], nextCursor: null })
+ }
+ })
+
+ expect(
+ await client.listDocumentVersions(documentId, { before: version.id, limit: 20 })
+ ).toEqual({ versions: [version], nextCursor: null })
+ const url = new URL(requests[0]?.url ?? '')
+ expect(url.pathname).toBe(`/api/documents/${documentId}/versions`)
+ expect(Object.fromEntries(url.searchParams)).toEqual({ before: version.id, limit: '20' })
+ })
+
test('lists documents shared with the person and rejects malformed entries', async () => {
const shared = {
...document,
diff --git a/packages/cloud/tests/integration/server/db/document-versions.test.ts b/packages/cloud/tests/integration/server/db/document-versions.test.ts
new file mode 100644
index 000000000..1928ae708
--- /dev/null
+++ b/packages/cloud/tests/integration/server/db/document-versions.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { keepCurrentRevisions } from '#cloud/server/db/migrations/021_document_versions'
+
+describe('migration 021', () => {
+ test('starts each document’s history with its current revision', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const { database } = runtime
+ const workspaceId = crypto.randomUUID()
+ const saved = crypto.randomUUID()
+ const empty = crypto.randomUUID()
+ const objectId = crypto.randomUUID()
+ const revisionId = crypto.randomUUID()
+ const savedAt = new Date('2026-09-01T12:00:00.000Z')
+ await database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'Studio', slug: 'studio', createdBy: 'alice' })
+ .execute()
+ await database
+ .insertInto('document')
+ .values([
+ { id: saved, workspaceId, name: 'Poster', createdBy: 'alice' },
+ { id: empty, workspaceId, name: 'Blank', createdBy: 'alice' }
+ ])
+ .execute()
+ await database
+ .insertInto('storageObject')
+ .values({
+ id: objectId,
+ objectKey: 'documents/poster.fig',
+ checksum: `${'A'.repeat(43)}=`,
+ byteSize: 128,
+ contentType: 'application/octet-stream'
+ })
+ .execute()
+ await database
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId: saved,
+ parentRevisionId: null,
+ storageObjectId: objectId,
+ createdBy: 'bob',
+ createdAt: savedAt
+ })
+ .execute()
+ await database
+ .updateTable('document')
+ .set({ currentRevisionId: revisionId })
+ .where('id', '=', saved)
+ .execute()
+
+ await keepCurrentRevisions(database)
+
+ const versions = await database
+ .selectFrom('documentVersion')
+ .select(['documentId', 'revisionId', 'kind', 'createdBy', 'createdAt'])
+ .execute()
+ expect(versions).toEqual([
+ { documentId: saved, revisionId, kind: 'checkpoint', createdBy: 'bob', createdAt: savedAt }
+ ])
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/documents/versions.test.ts b/packages/cloud/tests/integration/server/documents/versions.test.ts
new file mode 100644
index 000000000..32c6c693b
--- /dev/null
+++ b/packages/cloud/tests/integration/server/documents/versions.test.ts
@@ -0,0 +1,484 @@
+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 {
+ CLOUD_FEATURE_KEYS,
+ createBetterAuthAdapter,
+ createCloudApp,
+ createDefaultCloudPolicy,
+ createRevisionCompactionService,
+ EntitlementOpenFeatureProvider,
+ parseCloudServerConfig,
+ StaticEntitlementSource,
+ 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 versionSchema = v.object({
+ id: v.string(),
+ revisionId: v.string(),
+ kind: v.picklist(['checkpoint', 'named']),
+ name: v.nullable(v.string()),
+ description: v.nullable(v.string()),
+ current: v.boolean(),
+ restoredFromVersionId: v.nullable(v.string()),
+ createdBy: v.object({ id: v.string(), name: v.nullable(v.string()) })
+})
+const versionsSchema = v.object({
+ versions: v.array(versionSchema),
+ nextCursor: v.nullable(v.string())
+})
+const documentSchema = v.object({
+ document: v.object({ id: v.string(), currentRevisionId: v.nullable(v.string()) })
+})
+
+async function testApp(options: { fullHistory?: boolean } = {}) {
+ const runtime = await createCloudTestDatabase()
+ const objects = createMemoryObjectStore()
+ const policy =
+ options.fullHistory === false
+ ? createDefaultCloudPolicy(
+ new EntitlementOpenFeatureProvider(
+ new StaticEntitlementSource({ [CLOUD_FEATURE_KEYS.revisionHistory]: false })
+ )
+ )
+ : undefined
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: createBetterAuthAdapter(config, runtime.database),
+ objects: objects.store,
+ policy,
+ 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 saves = 0
+ let current: string | null = null
+
+ /** Saves the document the way the editor does: an upload, then its commit. */
+ async function save(): Promise<string> {
+ saves++
+ const checksum = `${String.fromCharCode(64 + saves).repeat(43)}=`
+ const upload = await responseJSON(
+ await request(`/documents/${documentId}/uploads`, {
+ method: 'POST',
+ json: {
+ baseRevisionId: current,
+ byteSize: FILE_BYTES,
+ checksum,
+ contentType: 'application/octet-stream'
+ }
+ }),
+ v.object({ id: v.string() })
+ )
+ const row = await runtime.database
+ .selectFrom('upload')
+ .select('objectKey')
+ .where('id', '=', upload.id)
+ .executeTakeFirstOrThrow()
+ objects.put(row.objectKey, {
+ byteSize: FILE_BYTES,
+ checksum,
+ checksumVerification: 'native',
+ contentType: 'application/octet-stream'
+ })
+ const committed = await responseJSON(
+ await request(`/uploads/${upload.id}/commit`, { method: 'POST', json: { checksum } }),
+ documentSchema
+ )
+ current = committed.document.currentRevisionId
+ if (!current) throw new Error('The save left no revision')
+ return current
+ }
+
+ /** Moves the whole history back in time, as if it 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()
+ }
+ }
+ }
+
+ async function history() {
+ return responseJSON(await request(`/documents/${documentId}/versions`), versionsSchema)
+ }
+
+ return {
+ runtime,
+ objects,
+ policy,
+ request,
+ workspaceId: workspace.workspace.id,
+ documentId,
+ save,
+ age,
+ history,
+ current: () => current
+ }
+}
+
+describe('Cloud version history', () => {
+ test('keeps the first save, and the state each half hour of editing ends on', async () => {
+ const context = await testApp()
+ try {
+ const first = await context.save()
+ await context.save()
+ const ended = await context.save()
+ expect((await context.history()).versions.map((version) => version.revisionId)).toEqual([
+ first
+ ])
+
+ // Half an hour on, the next save keeps the state it replaces.
+ await context.age(31 * 60_000)
+ const latest = await context.save()
+ const { versions } = await context.history()
+ expect(versions.map((version) => version.revisionId)).toEqual([ended, first])
+ expect(versions.every((version) => version.kind === 'checkpoint')).toBe(true)
+ expect(versions.some((version) => version.current)).toBe(false)
+ expect(latest).not.toBe(ended)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('names the current state, and deleting its info leaves a checkpoint', async () => {
+ const context = await testApp()
+ try {
+ await context.save()
+ const current = await context.save()
+ const named = await responseJSON(
+ await context.request(`/documents/${context.documentId}/versions`, {
+ method: 'POST',
+ json: { name: 'Hand-off', description: 'Ready for review' }
+ }),
+ v.object({ version: versionSchema })
+ )
+ expect(named.version).toMatchObject({
+ revisionId: current,
+ kind: 'named',
+ name: 'Hand-off',
+ description: 'Ready for review',
+ current: true,
+ createdBy: { id: 'alice' }
+ })
+
+ const cleared = await responseJSON(
+ await context.request(`/documents/${context.documentId}/versions/${named.version.id}`, {
+ method: 'PATCH',
+ json: { name: null }
+ }),
+ v.object({ version: versionSchema })
+ )
+ expect(cleared.version).toMatchObject({ kind: 'checkpoint', name: null, description: null })
+ expect((await context.history()).versions).toHaveLength(2)
+
+ const empty = await context.request(`/documents/${context.documentId}/versions`, {
+ method: 'POST',
+ json: { name: ' ' }
+ })
+ expect(empty.status).toBe(400)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('restores a version without losing the state it replaces', async () => {
+ const context = await testApp()
+ try {
+ const first = await context.save()
+ const replaced = await context.save()
+ const [original] = (await context.history()).versions
+ if (!original) throw new Error('No first version')
+ const before = await context.runtime.database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', context.documentId)
+ .executeTakeFirstOrThrow()
+
+ const restored = await responseJSON(
+ await context.request(`/documents/${context.documentId}/versions/${original.id}/restore`, {
+ method: 'POST'
+ }),
+ v.object({
+ document: v.object({ currentRevisionId: v.string() }),
+ version: versionSchema
+ })
+ )
+ expect(restored.version).toMatchObject({ current: true, restoredFromVersionId: original.id })
+ expect([first, replaced]).not.toContain(restored.document.currentRevisionId)
+ expect((await context.history()).versions.map((version) => version.revisionId)).toEqual([
+ restored.document.currentRevisionId,
+ replaced,
+ first
+ ])
+
+ // Everyone in the live room starts over on the restored version.
+ const after = await context.runtime.database
+ .selectFrom('document')
+ .select('collaborationEpoch')
+ .where('id', '=', context.documentId)
+ .executeTakeFirstOrThrow()
+ expect(after.collaborationEpoch).toBe(before.collaborationEpoch + 1)
+
+ // The restored state is the same stored file, so it opens as the original and costs nothing.
+ const [restoredDownload, originalDownload] = await Promise.all(
+ [restored.version.id, original.id].map(async (versionId) =>
+ responseJSON(
+ await context.request(`/documents/${context.documentId}/versions/${versionId}`),
+ v.object({ document: v.object({ download: v.object({ url: v.string() }) }) })
+ )
+ )
+ )
+ expect(restoredDownload?.document.download.url).toBe(originalDownload?.document.download.url)
+ const usage = await context.runtime.database
+ .selectFrom('workspaceStorageUsage')
+ .select('committedBytes')
+ .where('workspaceId', '=', context.workspaceId)
+ .executeTakeFirstOrThrow()
+ expect(Number(usage.committedBytes)).toBe(2 * FILE_BYTES)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('duplicates a version into a new document with a history of its own', async () => {
+ const context = await testApp()
+ try {
+ await context.save()
+ const [version] = (await context.history()).versions
+ if (!version) throw new Error('No version')
+ const copy = await responseJSON(
+ await context.request(`/documents/${context.documentId}/versions/${version.id}/duplicate`, {
+ method: 'POST',
+ json: { name: 'Poster copy' }
+ }),
+ documentSchema
+ )
+ expect(copy.document.id).not.toBe(context.documentId)
+ const copied = await responseJSON(
+ await context.request(`/documents/${copy.document.id}/versions`),
+ versionsSchema
+ )
+ expect(copied.versions).toHaveLength(1)
+ expect(copied.versions[0]?.current).toBe(true)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('refuses to duplicate a version of a deleted document', async () => {
+ const context = await testApp()
+ try {
+ await context.save()
+ const [version] = (await context.history()).versions
+ if (!version) throw new Error('No version')
+ await context.request(`/documents/${context.documentId}`, { method: 'DELETE' })
+ const copy = await context.request(
+ `/documents/${context.documentId}/versions/${version.id}/duplicate`,
+ { method: 'POST', json: { name: 'Poster copy' } }
+ )
+ expect(copy.status).toBe(404)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('pages through a long history, newest first', async () => {
+ const context = await testApp()
+ try {
+ for (let index = 0; index < 4; index++) {
+ await context.save()
+ await context.age(31 * 60_000)
+ }
+ const first = await responseJSON(
+ await context.request(`/documents/${context.documentId}/versions?limit=2`),
+ versionsSchema
+ )
+ expect(first.versions).toHaveLength(2)
+ if (!first.nextCursor) throw new Error('Expected another page')
+ const second = await responseJSON(
+ await context.request(
+ `/documents/${context.documentId}/versions?limit=2&before=${first.nextCursor}`
+ ),
+ versionsSchema
+ )
+ const all = (await context.history()).versions.map((version) => version.id)
+ expect([...first.versions, ...second.versions].map((version) => version.id)).toEqual(
+ all.slice(0, first.versions.length + second.versions.length)
+ )
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
+
+describe('Cloud revision compaction', () => {
+ test('deletes the saves between versions once they are old, and returns their bytes', async () => {
+ const context = await testApp()
+ try {
+ const first = await context.save()
+ await context.save()
+ await context.save()
+ const current = await context.save()
+ await context.age(2 * DAY_MS)
+
+ const result = await createRevisionCompactionService(
+ context.runtime.database,
+ context.objects.store
+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })
+ expect(result).toMatchObject({
+ revisionsDeleted: 2,
+ objectsDeleted: 2,
+ bytesReclaimed: 2 * FILE_BYTES,
+ failed: 0
+ })
+ const kept = await context.runtime.database
+ .selectFrom('documentRevision')
+ .select('id')
+ .execute()
+ expect(kept.map((revision) => revision.id).sort()).toEqual([first, current].sort())
+ const usage = await context.runtime.database
+ .selectFrom('workspaceStorageUsage')
+ .select('committedBytes')
+ .where('workspaceId', '=', context.workspaceId)
+ .executeTakeFirstOrThrow()
+ expect(Number(usage.committedBytes)).toBe(2 * FILE_BYTES)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('deletes no more saves in one pass than its batch allows', async () => {
+ const context = await testApp()
+ try {
+ for (let index = 0; index < 7; index++) await context.save()
+ await context.age(2 * DAY_MS)
+ const compaction = createRevisionCompactionService(
+ context.runtime.database,
+ context.objects.store
+ )
+ const passes = []
+ for (let index = 0; index < 3; index++) {
+ passes.push(
+ (await compaction.compactRevisions({ batchSize: 2, graceMs: DAY_MS })).revisionsDeleted
+ )
+ }
+ expect(passes).toEqual([2, 2, 1])
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('tries a file again when the object store failed to delete it', async () => {
+ const context = await testApp()
+ try {
+ await context.save()
+ await context.save()
+ await context.save()
+ await context.age(2 * DAY_MS)
+ const failing = {
+ ...context.objects.store,
+ delete: async () => {
+ throw new Error('The object store is unavailable')
+ }
+ }
+ const first = await createRevisionCompactionService(
+ context.runtime.database,
+ failing
+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })
+ expect(first).toMatchObject({ revisionsDeleted: 1, objectsDeleted: 0, failed: 1 })
+ expect(first.bytesReclaimed).toBe(FILE_BYTES)
+
+ const second = await createRevisionCompactionService(
+ context.runtime.database,
+ context.objects.store
+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })
+ expect(second).toMatchObject({ revisionsDeleted: 0, objectsDeleted: 1, failed: 0 })
+ const rows = await context.runtime.database.selectFrom('storageObject').select('id').execute()
+ expect(rows).toHaveLength(2)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('leaves recent saves alone', async () => {
+ const context = await testApp()
+ try {
+ await context.save()
+ await context.save()
+ await context.save()
+ const result = await createRevisionCompactionService(
+ context.runtime.database,
+ context.objects.store
+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })
+ expect(result.revisionsDeleted).toBe(0)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('a workspace without full history keeps 30 days of versions', async () => {
+ const context = await testApp({ fullHistory: false })
+ try {
+ await context.save()
+ await context.age(40 * DAY_MS)
+ const recent = await context.save()
+ await context.age(31 * 60_000)
+ await context.save()
+ expect((await context.history()).versions.map((version) => version.revisionId)).toEqual([
+ recent
+ ])
+
+ const result = await createRevisionCompactionService(
+ context.runtime.database,
+ context.objects.store,
+ { policy: context.policy }
+ ).compactRevisions({ batchSize: 100, graceMs: DAY_MS })
+ expect(result.versionsPruned).toBe(1)
+ expect(result.revisionsDeleted).toBe(1)
+ } 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 c3dadb8ee..56b6964d2 100644
--- a/packages/cloud/tests/server/api/router.test.ts
+++ b/packages/cloud/tests/server/api/router.test.ts
@@ -50,6 +50,14 @@ function services() {
throw new Error('not used')
}
},
+ versions: {
+ list: notUsed,
+ save: notUsed,
+ update: notUsed,
+ download: notUsed,
+ restore: notUsed,
+ duplicate: notUsed
+ },
sharing: {
lookupUser: async () => null,
userProfile: async () => null,
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index c73a12a3b..9d7c909e5 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -47,6 +47,25 @@ revision has its own object key.
- Deleting a document is immediate for users; the cleanup worker removes revisions and objects once
the retention period passes.
+### Version history
+
+Every save is a revision, but the history a person sees is its versions: checkpoints the server
+keeps on its own, and versions someone named (`document_version`, one per revision).
+
+- When a save lands and the newest version is half an hour old, the server keeps the revision that
+ save replaces as a checkpoint, so each stretch of editing and the state every session ended on stay
+ in the history. A document's first save is always one.
+- Naming the current state, or naming any version, makes it a named version; deleting its info turns
+ it back into a checkpoint. Viewers see the history; editors name, restore, and duplicate.
+- Restoring keeps the replaced state as a checkpoint, adds a revision that points at the restored
+ version's stored file, and advances the collaboration epoch, so the live room starts over on it.
+ Duplicating makes a new document in the same workspace from the same file. Neither uploads
+ anything or uses more storage.
+- The cleanup worker compacts saves that are neither current nor a version once they are a day old,
+ a batch at a time, and returns the bytes of files nothing else uses to the workspace's usage. A
+ freed file's row stays until the object store deletes it, so a failed delete is retried. With
+ the `revision_history` entitlement off, a workspace keeps 30 days of versions, as on a free plan.
+
## Authentication and authorization
Better Auth owns users, sessions, social sign-in, email and password, passkeys, TOTP, and recovery
@@ -164,7 +183,7 @@ looser.
## Policy, entitlements, and quotas
OpenFeature answers concrete questions such as whether capability links, anonymous viewing, or
-revision history are available, and what a numeric limit is. Its provider reads one entitlement
+full revision history is kept, and what a numeric limit is. Its provider reads one entitlement
source, chosen by `[entitlements] source`: the static table in the deployment TOML, which applies to
every workspace, or per-workspace rows in the database that the `entitlements` command sets. The two
are alternatives, not layers. Technical limits cap the file size and participant limits the source
@@ -290,3 +309,10 @@ in `contract` and `client` stays MIT, so the editor and other clients stay MIT.
the paths rather than a separate package, which would have moved the protocol out of
`packages/cloud` for no legal gain. `VITE_OPENPENCIL_CLOUD=off` swaps Cloud's two entry points for
stand-ins, and `check:cloud-off` proves that build bundles none of Cloud.
+
+**2026-10 · History is versions over revisions, compacted on the server.** Every save stays a
+revision so saving and conflicts work as before, but the history lists only server-made checkpoints
+and named versions, and saves between them are compacted after a day. Checkpoints are made when a
+save lands rather than on a timer, so they need no client clock and cover every writer. History stores
+`.fig` revisions rather than Yjs snapshots: snapshots would need garbage collection off in every room
+and a version would still have to become a file to open, restore, or duplicate.