summaryrefslogtreecommitdiff
path: root/apps/web/src/versions/versions-manager.ts
blob: 6dba0c8c3f62a33f769b445038b9fe1bb24c8ec1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import type { EditorCore } from "@/core";
import { toast } from "sonner";
import { generateUUID } from "@/utils/id";
import type { TProject } from "@/project/types";
import {
	deserializeProject,
	serializeProject,
} from "@/services/storage/service";
import { isStorageQuotaExceededError } from "@/services/storage/quota";
import { getProjectDurationFromScenes } from "@/timeline/scenes";
import { ZERO_MEDIA_TIME } from "@/wasm";
import { getReferencedMediaIds } from "./media-references";
import {
	IndexedDBVersionStore,
	InMemoryVersionStore,
	type VersionStore,
} from "./store";
import type { ProjectVersion } from "./types";

export const AUTO_CHECKPOINT_RETENTION = 20;
export const AUTO_CHECKPOINT_MIN_INTERVAL_MS = 60_000;

const VERSION_THUMBNAIL_MAX_WIDTH = 320;

async function captureVersionThumbnail({
	editor,
}: {
	editor: EditorCore;
}): Promise<string | undefined> {
	try {
		const blob = await editor.renderer.captureFrame();
		if (!blob) return undefined;

		const bitmap = await createImageBitmap(blob);
		const scale = Math.min(1, VERSION_THUMBNAIL_MAX_WIDTH / bitmap.width);
		const canvas = document.createElement("canvas");
		canvas.width = Math.max(1, Math.round(bitmap.width * scale));
		canvas.height = Math.max(1, Math.round(bitmap.height * scale));
		const context = canvas.getContext("2d");
		if (!context) {
			bitmap.close();
			return undefined;
		}
		context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
		bitmap.close();
		return canvas.toDataURL("image/jpeg", 0.75);
	} catch (error) {
		console.error("Failed to capture version thumbnail:", error);
		return undefined;
	}
}

/**
 * Named checkpoints + throttled auto-checkpoints (ring buffer) per project.
 * Restore is a wholesale document swap that deliberately bypasses undo/redo:
 * undoing a restore = the safety auto-checkpoint written before the jump.
 * See notes/project-versioning.md.
 */
export class VersionsManager {
	private versionsByProject = new Map<string, ProjectVersion[]>();
	private pinnedMediaByProject = new Map<string, Set<string>>();
	private lastAutoCheckpointAt = new Map<string, number>();
	private hydratedProjectId: string | null = null;
	private listeners = new Set<() => void>();
	private store: VersionStore;
	private now: () => number;

	constructor({
		editor,
		store,
		now,
	}: {
		editor: EditorCore;
		store?: VersionStore;
		now?: () => number;
	}) {
		this.editor = editor;
		// Without IndexedDB (unit tests, unsupported browsers) persistence is
		// impossible; fall back to the in-memory store instead of failing.
		this.store =
			store ??
			(typeof indexedDB === "undefined"
				? new InMemoryVersionStore()
				: new IndexedDBVersionStore());
		this.now = now ?? (() => Date.now());

		this.editor.project.subscribe(() => {
			const activeProjectId =
				this.editor.project.getActiveOrNull()?.metadata.id ?? null;
			if (activeProjectId === this.hydratedProjectId) return;
			this.hydratedProjectId = activeProjectId;
			if (activeProjectId) {
				this.listVersions({ projectId: activeProjectId }).catch((error) => {
					console.error("Failed to load project versions:", error);
				});
			}
		});
	}

	private editor: EditorCore;

	/** Test seam: swap the persistence backend / clock. */
	setStore({ store }: { store: VersionStore }): void {
		this.store = store;
	}

	setNow({ now }: { now: () => number }): void {
		this.now = now;
	}

	subscribe(listener: () => void): () => void {
		this.listeners.add(listener);
		return () => this.listeners.delete(listener);
	}

	private notify(): void {
		this.listeners.forEach((listener) => {
			listener();
		});
	}

	/** Cached versions for a project, newest first. */
	getVersions({ projectId }: { projectId: string }): ProjectVersion[] {
		return this.versionsByProject.get(projectId) ?? [];
	}

	/** Reloads versions for a project from the store into the cache. */
	async listVersions({
		projectId,
	}: {
		projectId: string;
	}): Promise<ProjectVersion[]> {
		try {
			const versions = sortNewestFirst({
				versions: await this.store.getAllForProject({ projectId }),
			});
			this.setProjectVersions({ projectId, versions });
			return versions;
		} catch (error) {
			console.error("Failed to list project versions:", error);
			return this.getVersions({ projectId });
		}
	}

	async createNamedCheckpoint({
		name,
	}: {
		name: string;
	}): Promise<ProjectVersion | null> {
		const trimmedName = name.trim();
		if (!trimmedName) {
			toast.error("Checkpoint needs a name");
			return null;
		}

		const thumbnail = await captureVersionThumbnail({ editor: this.editor });
		const version = this.buildSnapshot({
			kind: "named",
			name: trimmedName,
			thumbnail,
		});
		if (!version) return null;

		const didWrite = await this.putVersion({ version });
		if (!didWrite) return null;

		toast.success(`Checkpoint "${trimmedName}" created`);
		return version;
	}

	/**
	 * Writes an auto-checkpoint of the current head, throttled to at most one
	 * per AUTO_CHECKPOINT_MIN_INTERVAL_MS and project. `force` skips the
	 * throttle (used for the safety checkpoint before a restore jump).
	 * Returns false when throttled, when there is nothing to snapshot, or when
	 * the write failed.
	 */
	async writeAutoCheckpoint({
		force = false,
	}: { force?: boolean } = {}): Promise<boolean> {
		const activeProject = this.editor.project.getActiveOrNull();
		if (!activeProject) return false;

		const projectId = activeProject.metadata.id;
		const nowMs = this.now();
		const lastAt = this.lastAutoCheckpointAt.get(projectId);
		if (
			!force &&
			lastAt !== undefined &&
			nowMs - lastAt < AUTO_CHECKPOINT_MIN_INTERVAL_MS
		) {
			return false;
		}

		const version = this.buildSnapshot({ kind: "auto" });
		if (!version) return false;

		const didWrite = await this.putVersion({ version });
		if (!didWrite) return false;

		this.lastAutoCheckpointAt.set(projectId, nowMs);
		await this.rotateAutoCheckpoints({ projectId });
		return true;
	}

	/**
	 * Jumps head to a stored version: writes a safety auto-checkpoint of the
	 * current head first, then swaps the document wholesale (bypassing
	 * undo/redo — undo of a restore = that safety checkpoint).
	 */
	async restoreVersion({ versionId }: { versionId: string }): Promise<boolean> {
		const activeProject = this.editor.project.getActiveOrNull();
		if (!activeProject) return false;

		const version = this.getVersions({
			projectId: activeProject.metadata.id,
		}).find((candidate) => candidate.id === versionId);
		if (!version) {
			toast.error("Version not found");
			return false;
		}

		const didWriteSafetyCheckpoint = await this.writeAutoCheckpoint({
			force: true,
		});
		if (!didWriteSafetyCheckpoint) {
			toast.error("Couldn't save a safety checkpoint of the current state", {
				description: "Restore aborted so no work is lost.",
			});
			return false;
		}

		const project = deserializeProject({ serialized: version.project });
		this.editor.project.setActiveProject({ project });
		this.editor.scenes.initializeScenes({
			scenes: project.scenes,
			currentSceneId: project.currentSceneId,
		});
		this.editor.playback.seek({ time: ZERO_MEDIA_TIME });
		this.editor.command.clear();
		this.editor.selection.clearSelection();
		this.editor.save.markDirty({ force: true });
		this.notify();

		toast.success(`Restored ${getVersionLabel({ version })}`, {
			description: "Previous state saved as an auto-checkpoint.",
		});
		return true;
	}

	async renameVersion({
		versionId,
		name,
	}: {
		versionId: string;
		name: string;
	}): Promise<boolean> {
		const trimmedName = name.trim();
		if (!trimmedName) {
			toast.error("Checkpoint needs a name");
			return false;
		}

		const found = this.findVersion({ versionId });
		if (!found) {
			toast.error("Version not found");
			return false;
		}
		if (found.version.kind !== "named") {
			toast.error("Auto-checkpoints can't be renamed");
			return false;
		}

		const renamed: ProjectVersion = { ...found.version, name: trimmedName };
		try {
			await this.store.put({ version: renamed });
		} catch (error) {
			this.toastStoreError({ error, fallback: "Failed to rename checkpoint" });
			return false;
		}

		this.replaceCachedVersion({ version: renamed });
		return true;
	}

	/** Deletes a named checkpoint. Auto-checkpoints only leave via rotation. */
	async deleteVersion({ versionId }: { versionId: string }): Promise<boolean> {
		const found = this.findVersion({ versionId });
		if (!found) {
			toast.error("Version not found");
			return false;
		}
		if (found.version.kind !== "named") {
			toast.error("Auto-checkpoints can't be deleted", {
				description: "They rotate out automatically.",
			});
			return false;
		}

		try {
			await this.store.delete({ id: versionId });
		} catch (error) {
			this.toastStoreError({ error, fallback: "Failed to delete checkpoint" });
			return false;
		}

		const remaining = this.getVersions({ projectId: found.projectId }).filter(
			(version) => version.id !== versionId,
		);
		this.setProjectVersions({ projectId: found.projectId, versions: remaining });
		return true;
	}

	async deleteVersionsForProject({
		projectId,
	}: {
		projectId: string;
	}): Promise<void> {
		try {
			await this.store.deleteForProject({ projectId });
		} catch (error) {
			console.error("Failed to delete project versions:", error);
		}
		this.versionsByProject.delete(projectId);
		this.pinnedMediaByProject.delete(projectId);
		this.lastAutoCheckpointAt.delete(projectId);
		this.notify();
	}

	/**
	 * Sync pin check backed by the cached version list (hydrated on project
	 * load). Deleting a pinned media asset is blocked so a restore can never
	 * hit a missing blob.
	 */
	isMediaIdPinned({
		projectId,
		mediaId,
	}: {
		projectId: string;
		mediaId: string;
	}): boolean {
		return this.pinnedMediaByProject.get(projectId)?.has(mediaId) ?? false;
	}

	private buildSnapshot({
		kind,
		name,
		thumbnail,
	}: {
		kind: ProjectVersion["kind"];
		name?: string;
		thumbnail?: string;
	}): ProjectVersion | null {
		const activeProject = this.editor.project.getActiveOrNull();
		if (!activeProject) return null;

		const scenes = this.editor.scenes.getScenes();
		const project: TProject = {
			...activeProject,
			scenes,
			metadata: {
				...activeProject.metadata,
				duration: getProjectDurationFromScenes({ scenes }),
				updatedAt: new Date(this.now()),
			},
		};

		return {
			id: generateUUID(),
			projectId: activeProject.metadata.id,
			kind,
			...(name !== undefined && { name }),
			createdAt: new Date(this.now()),
			project: serializeProject({ project }),
			...(thumbnail !== undefined && { thumbnail }),
		};
	}

	/** Persists a version and reflects it in the cache. Returns false on failure. */
	private async putVersion({
		version,
	}: {
		version: ProjectVersion;
	}): Promise<boolean> {
		try {
			await this.store.put({ version });
		} catch (error) {
			this.toastStoreError({ error, fallback: "Failed to save checkpoint" });
			return false;
		}

		const versions = [
			version,
			...this.getVersions({ projectId: version.projectId }),
		];
		this.setProjectVersions({
			projectId: version.projectId,
			versions: sortNewestFirst({ versions }),
		});
		return true;
	}

	/** Ring buffer: keep the newest AUTO_CHECKPOINT_RETENTION autos per project. */
	private async rotateAutoCheckpoints({
		projectId,
	}: {
		projectId: string;
	}): Promise<void> {
		const versions = this.getVersions({ projectId });
		const autoVersions = versions.filter((version) => version.kind === "auto");
		const evicted = autoVersions.slice(AUTO_CHECKPOINT_RETENTION);
		if (evicted.length === 0) return;

		await Promise.all(
			evicted.map(async (version) => {
				try {
					await this.store.delete({ id: version.id });
				} catch (error) {
					console.error("Failed to rotate auto-checkpoint:", error);
				}
			}),
		);

		const evictedIds = new Set(evicted.map((version) => version.id));
		this.setProjectVersions({
			projectId,
			versions: versions.filter((version) => !evictedIds.has(version.id)),
		});
	}

	private findVersion({
		versionId,
	}: {
		versionId: string;
	}): { projectId: string; version: ProjectVersion } | null {
		for (const [projectId, versions] of this.versionsByProject) {
			const version = versions.find((candidate) => candidate.id === versionId);
			if (version) return { projectId, version };
		}
		return null;
	}

	private replaceCachedVersion({ version }: { version: ProjectVersion }): void {
		const versions = this.getVersions({ projectId: version.projectId }).map(
			(candidate) => (candidate.id === version.id ? version : candidate),
		);
		this.setProjectVersions({ projectId: version.projectId, versions });
	}

	private setProjectVersions({
		projectId,
		versions,
	}: {
		projectId: string;
		versions: ProjectVersion[];
	}): void {
		this.versionsByProject.set(projectId, versions);
		const pinned = new Set<string>();
		for (const version of versions) {
			for (const mediaId of getReferencedMediaIds({
				project: version.project,
			})) {
				pinned.add(mediaId);
			}
		}
		this.pinnedMediaByProject.set(projectId, pinned);
		this.notify();
	}

	private toastStoreError({
		error,
		fallback,
	}: {
		error: unknown;
		fallback: string;
	}): void {
		if (isStorageQuotaExceededError({ error })) {
			toast.error("Not enough browser storage", {
				description: error instanceof Error ? error.message : undefined,
			});
			return;
		}
		console.error(`${fallback}:`, error);
		toast.error(fallback);
	}
}

function sortNewestFirst({
	versions,
}: {
	versions: ProjectVersion[];
}): ProjectVersion[] {
	return [...versions].sort(
		(a, b) =>
			new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
	);
}

function getVersionLabel({ version }: { version: ProjectVersion }): string {
	return version.kind === "named" && version.name
		? `"${version.name}"`
		: "auto-checkpoint";
}