Skip to content
← Public packages

@kentcdodds/photo-portfolio

A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.

FollowFork

Files

site-store.ts

304 lines · 9.3 KB · TypeScript
import { diffContent, storedPhotoIds } from '../domain/content.ts'
import { defaultContent } from '../domain/defaults.ts'
import { contentTypes, variantFileName } from '../domain/image-plan.ts'
import type { SiteContent } from '../domain/types.ts'
import {
	emptyVersionIndex,
	recordVersion,
	requireVersion,
	type VersionEntry,
	type VersionIndex,
} from '../domain/versions.ts'
import type { ProcessedFile } from '../images/process.ts'
import { base64ToBytes, bytesToBase64 } from './base64.ts'

/**
 * The slice of `packageStorage()` this package uses. Exports pass
 * `packageStorage()`, the app passes `context.get(KodyRuntime).packageStorage()`.
 */
export interface SiteStorage {
	get(key: string): Promise<unknown>
	set(key: string, value: any): Promise<unknown>
	delete(key: string): Promise<unknown>
}

export const storageKeys = {
	draft: 'site/draft',
	live: 'site/live',
	versions: 'site/versions',
	version: (n: number) => `site/version/${n}`,
	previewToken: 'site/preview-token',
	hostedUrl: 'site/hosted-url',
	mediaIndex: 'media/index',
	media: (photoId: string) => `media/${photoId}`,
	mediaChunk: (photoId: string, file: string, chunk: number) =>
		`media/${photoId}/${file}/${chunk}`,
	inquiries: 'inquiries',
	notificationBudget: 'inquiries/notification-budget',
} as const

/** Base64 characters per storage value (well under the per-value limit). */
export const mediaChunkSize = 512 * 1024

function isContent(value: unknown): value is SiteContent {
	return Boolean(
		value &&
		typeof value === 'object' &&
		'config' in value &&
		'galleries' in value,
	)
}

/**
 * Stored content merged over current defaults, so config fields added in a
 * later package version get their default instead of `undefined`.
 */
function normalize(content: SiteContent): SiteContent {
	return { ...content, config: { ...defaultContent.config, ...content.config } }
}

export async function readDraft(storage: SiteStorage): Promise<SiteContent> {
	const draft = await storage.get(storageKeys.draft)
	if (isContent(draft)) return normalize(draft)
	return readLive(storage)
}

export async function readLive(storage: SiteStorage): Promise<SiteContent> {
	const live = await storage.get(storageKeys.live)
	return isContent(live) ? normalize(live) : defaultContent
}

export async function writeDraft(storage: SiteStorage, content: SiteContent) {
	await storage.set(storageKeys.draft, content)
}

export async function readVersionIndex(
	storage: SiteStorage,
): Promise<VersionIndex> {
	const index = await storage.get(storageKeys.versions)
	return index && typeof index === 'object' && 'entries' in index
		? (index as VersionIndex)
		: emptyVersionIndex
}

export async function pendingChanges(storage: SiteStorage) {
	const [draft, live] = await Promise.all([
		readDraft(storage),
		readLive(storage),
	])
	return diffContent(live, draft)
}

async function snapshotLive(
	storage: SiteStorage,
	content: SiteContent,
	input: {
		kind: VersionEntry['kind']
		note?: string
		restoredFrom?: number
		now: string
	},
) {
	const recorded = recordVersion(
		await readVersionIndex(storage),
		content,
		input,
	)
	await storage.set(storageKeys.version(recorded.entry.version), content)
	await storage.set(storageKeys.live, content)
	await storage.set(storageKeys.draft, content)
	await storage.set(storageKeys.versions, recorded.index)
	for (const version of recorded.pruned)
		await storage.delete(storageKeys.version(version))
	return recorded.entry
}

/** Make the draft live and record it as a new version. */
export async function publishDraft(
	storage: SiteStorage,
	input: { note?: string; now: string },
) {
	const [draft, live] = await Promise.all([
		readDraft(storage),
		readLive(storage),
	])
	const diff = diffContent(live, draft)
	const entry = await snapshotLive(storage, draft, {
		kind: 'publish',
		...input,
	})
	const cleanup = await collectGarbage(storage)
	return { entry, diff, cleanup }
}

/** Restore an earlier version as both the live site and the draft, recorded as a new version. */
export async function rollbackTo(
	storage: SiteStorage,
	input: { version: number; now: string },
) {
	const index = await readVersionIndex(storage)
	requireVersion(index, input.version)
	const snapshot = await storage.get(storageKeys.version(input.version))
	if (!isContent(snapshot))
		throw new Error(`Version ${input.version} has no stored snapshot.`)
	const live = await readLive(storage)
	const diff = diffContent(live, normalize(snapshot))
	const entry = await snapshotLive(storage, normalize(snapshot), {
		kind: 'rollback',
		restoredFrom: input.version,
		note: `Rolled back to version ${input.version}`,
		now: input.now,
	})
	return { entry, diff }
}

/** Throw away unpublished changes: the draft goes back to what is live. */
export async function discardDraft(storage: SiteStorage) {
	await storage.delete(storageKeys.draft)
	return collectGarbage(storage)
}

/**
 * The Kody-hosted app URL, as last recorded by the app. Exports run outside the
 * app, where the platform does not expose it, so the app writes it down.
 */
export async function readHostedUrl(storage: SiteStorage) {
	const stored = await storage.get(storageKeys.hostedUrl)
	return typeof stored === 'string' && stored ? stored : undefined
}

export async function recordHostedUrl(storage: SiteStorage, url: string) {
	if ((await readHostedUrl(storage)) !== url) {
		await storage.set(storageKeys.hostedUrl, url)
	}
}

export async function getPreviewToken(storage: SiteStorage, rotate = false) {
	const existing = await storage.get(storageKeys.previewToken)
	if (typeof existing === 'string' && existing && !rotate) return existing
	const bytes = crypto.getRandomValues(new Uint8Array(18))
	const token = bytesToBase64(bytes)
		.replace(/\+/g, '-')
		.replace(/\//g, '_')
		.replace(/=+$/, '')
	await storage.set(storageKeys.previewToken, token)
	return token
}

type MediaFileRecord = {
	file: string
	contentType: string
	bytes: number
	chunks: number
}
type MediaRecord = { photoId: string; files: Array<MediaFileRecord> }

async function readMediaIndex(storage: SiteStorage): Promise<Array<string>> {
	const index = await storage.get(storageKeys.mediaIndex)
	return Array.isArray(index) ? (index as Array<string>) : []
}

/** Store every encoded file for one photo (base64, chunked) and register it for cleanup. */
export async function saveMedia(
	storage: SiteStorage,
	photoId: string,
	files: Array<ProcessedFile>,
) {
	const record: MediaRecord = { photoId, files: [] }
	for (const { variant, bytes } of files) {
		const file = variantFileName(variant)
		const base64 = bytesToBase64(bytes)
		const chunks = Math.max(1, Math.ceil(base64.length / mediaChunkSize))
		for (let i = 0; i < chunks; i += 1) {
			await storage.set(
				storageKeys.mediaChunk(photoId, file, i),
				base64.slice(i * mediaChunkSize, (i + 1) * mediaChunkSize),
			)
		}
		record.files.push({
			file,
			contentType: contentTypes[variant.format],
			bytes: bytes.length,
			chunks,
		})
	}
	await storage.set(storageKeys.media(photoId), record)
	const index = await readMediaIndex(storage)
	if (!index.includes(photoId))
		await storage.set(storageKeys.mediaIndex, [...index, photoId])
}

export async function readMediaFile(
	storage: SiteStorage,
	photoId: string,
	file: string,
) {
	const record = (await storage.get(
		storageKeys.media(photoId),
	)) as MediaRecord | null
	const entry = record?.files.find((f) => f.file === file)
	if (!entry) return null
	const parts = await Promise.all(
		Array.from({ length: entry.chunks }, (_, i) =>
			storage.get(storageKeys.mediaChunk(photoId, file, i)),
		),
	)
	if (parts.some((part) => typeof part !== 'string')) return null
	return {
		bytes: base64ToBytes(parts.join('')),
		contentType: entry.contentType,
	}
}

async function deleteMedia(storage: SiteStorage, photoId: string) {
	const record = (await storage.get(
		storageKeys.media(photoId),
	)) as MediaRecord | null
	for (const entry of record?.files ?? []) {
		for (let i = 0; i < entry.chunks; i += 1)
			await storage.delete(storageKeys.mediaChunk(photoId, entry.file, i))
	}
	await storage.delete(storageKeys.media(photoId))
}

/**
 * Delete stored photos that no draft, live site, or retained version uses.
 * Runs after publish, rollback, discard, and removals.
 */
export async function collectGarbage(storage: SiteStorage) {
	const index = await readMediaIndex(storage)
	if (index.length === 0) return { deletedPhotos: 0 }
	const versions = await readVersionIndex(storage)
	const snapshots = await Promise.all(
		versions.entries.map((e) => storage.get(storageKeys.version(e.version))),
	)
	const contents = [
		await readDraft(storage),
		await readLive(storage),
		...snapshots.filter(isContent),
	]
	const referenced = new Set<string>()
	for (const content of contents)
		for (const id of storedPhotoIds(content)) referenced.add(id)
	const unused = index.filter((id) => !referenced.has(id))
	for (const id of unused) await deleteMedia(storage, id)
	if (unused.length > 0)
		await storage.set(
			storageKeys.mediaIndex,
			index.filter((id) => referenced.has(id)),
		)
	return { deletedPhotos: unused.length }
}

/** Remove media for photos that were processed but never made it into the draft (failed batch). */
export async function discardMedia(
	storage: SiteStorage,
	photoIds: Array<string>,
) {
	for (const id of photoIds) await deleteMedia(storage, id)
	const index = await readMediaIndex(storage)
	await storage.set(
		storageKeys.mediaIndex,
		index.filter((id) => !photoIds.includes(id)),
	)
}