Delete library stills from disk before the catalog write, and stop caching their media.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Towsty
2026-10-25 17:55:30 -05:00
co-authored by Cursor
parent 545a3d749b
commit 20359bfbd4
26 changed files with 635 additions and 247 deletions
+194 -27
View File
@@ -6,7 +6,7 @@ import { join } from 'node:path'
import { spawn } from 'node:child_process'
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import { promisify } from 'node:util'
import type { H3Event } from 'h3'
import { setHeader, type H3Event } from 'h3'
import { extractFirstFrame, extractFrameAt, extractLastFrame, probeDuration, remuxFaststart } from '~/server/utils/ffmpeg'
import { normalizePermanenceRefs, type PermanenceRef } from '~/utils/globalLocks'
import { normalizeStillSettings, type StillGenerationSettings } from '~/utils/libraryGeneration'
@@ -416,8 +416,22 @@ function writeCatalog(owner: string, catalog: Catalog) {
}
export function invalidateCatalogCache(owner?: string) {
if (owner) catalogCache.delete(owner)
else catalogCache.clear()
// Bump the epoch so a read that already parsed pre-wipe bytes cannot
// repopulate the cache. Do not trust catalog mtime for this.
if (owner) {
catalogCache.delete(owner)
catalogEpoch.set(owner, (catalogEpoch.get(owner) || 0) + 1)
return
}
catalogCache.clear()
for (const key of catalogEpoch.keys()) {
catalogEpoch.set(key, (catalogEpoch.get(key) || 0) + 1)
}
}
export function setLibraryMediaHeaders(event: H3Event) {
setHeader(event, 'Cache-Control', 'no-store, no-cache, must-revalidate')
setHeader(event, 'Pragma', 'no-cache')
}
function mutate<T>(owner: string, fn: (catalog: Catalog) => T): Promise<T> {
@@ -656,7 +670,8 @@ export function publicLibrary(event: H3Event, opts?: { light?: boolean }) {
drafts: catalog.drafts,
loraAliases: catalog.loraAliases || {},
loraTriggers: catalog.loraTriggers || {},
keepPrompts: catalog.keepPrompts || emptyKeepPrompts()
keepPrompts: catalog.keepPrompts || emptyKeepPrompts(),
catalogEpoch: catalogEpoch.get(owner) || 0
}
}
@@ -713,6 +728,7 @@ export function publicLibraryPage(
ext?: string
}
const epoch = catalogEpoch.get(owner) || 0
const rows: Row[] = []
if (typeFilter !== 'videos' && typeFilter !== 'music') {
for (const still of catalog.stills) {
@@ -724,7 +740,7 @@ export function publicLibraryPage(
name: still.name || still.filename || still.id,
type: 'still',
createdAt: still.createdAt || 0,
thumbUrl: `/api/library/stills/${still.id}/thumb`,
thumbUrl: `/api/library/stills/${still.id}/thumb?v=${epoch}`,
folderId: still.folderId,
prompt: still.prompt,
promptPre: still.promptPre,
@@ -746,7 +762,7 @@ export function publicLibraryPage(
name: clip.name || clip.id,
type: 'clip',
createdAt: clip.createdAt || 0,
thumbUrl: `/api/library/clips/${clip.id}/thumb`,
thumbUrl: `/api/library/clips/${clip.id}/thumb?v=${epoch}`,
folderId: clip.folderId,
prompt: clip.prompt,
promptPre: clip.promptPre,
@@ -814,7 +830,8 @@ export function publicLibraryPage(
loraAliases: catalog.loraAliases || {},
loraTriggers: catalog.loraTriggers || {},
keepPrompts: catalog.keepPrompts || emptyKeepPrompts(),
total: rows.length
total: rows.length,
catalogEpoch: epoch
}
}
@@ -885,13 +902,15 @@ export function deleteFolder(owner: string, id: string) {
const clips = catalog.clips.filter(clip => clip.folderId === id)
const stills = catalog.stills.filter(still => still.folderId === id)
const tracks = (catalog.tracks || []).filter(track => track.folderId === id)
const removed = removedEntries(clips, stills, tracks)
for (const clip of clips) unlinkVerified(clipDir(owner, clip.id), true)
for (const still of stills) removeStillFiles(owner, still.id)
for (const track of tracks) unlinkVerified(trackDir(owner, track.id), true)
assertRemovedEntries(owner, removed)
catalog.folders = catalog.folders.filter(item => item.id !== id)
catalog.clips = catalog.clips.filter(clip => clip.folderId !== id)
catalog.stills = catalog.stills.filter(still => still.folderId !== id)
catalog.tracks = (catalog.tracks || []).filter(track => track.folderId !== id)
for (const clip of clips) safeRm(clipDir(owner, clip.id), true)
for (const still of stills) removeStillFiles(owner, still.id)
for (const track of tracks) safeRm(trackDir(owner, track.id), true)
return { fallbackFolderId: catalog.folders[0].id }
})
}
@@ -929,6 +948,7 @@ function emptyFolderRows(catalog: Catalog, folderId: string) {
/** Delete every still, clip, and track in a folder — catalog rows and on-disk files. Keeps the folder. */
export function wipeFolderContents(owner: string, folderId: string) {
let removed: RemovedEntry[] = []
return mutate(owner, (catalog) => {
const folder = catalog.folders.find(item => item.id === folderId)
if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' })
@@ -940,11 +960,13 @@ export function wipeFolderContents(owner: string, folderId: string) {
...stills.map(item => item.id),
...tracks.map(item => item.id)
])
removed = removedEntries(clips, stills, tracks)
for (const clip of clips) unlinkVerified(clipDir(owner, clip.id), true)
for (const still of stills) removeStillFiles(owner, still.id)
for (const track of tracks) unlinkVerified(trackDir(owner, track.id), true)
assertRemovedEntries(owner, removed)
emptyFolderRows(catalog, folderId)
detachDraftStills(catalog, deletedIds)
for (const clip of clips) safeRm(clipDir(owner, clip.id), true)
for (const still of stills) removeStillFiles(owner, still.id)
for (const track of tracks) safeRm(trackDir(owner, track.id), true)
pruneMissingStillMasters(owner, catalog)
const remain = [
...catalog.clips.filter(item => sameFolder(item.folderId, folderId)),
@@ -955,6 +977,7 @@ export function wipeFolderContents(owner: string, folderId: string) {
console.error('[library] wipe left folder rows', folderId, remain.map(item => item.id))
emptyFolderRows(catalog, folderId)
}
assertRemovedEntries(owner, removed)
return {
folderId: folder.id,
folderName: folder.name,
@@ -965,6 +988,7 @@ export function wipeFolderContents(owner: string, folderId: string) {
tracks: tracks.length
}
}).then((result) => {
assertRemovedEntries(owner, removed)
invalidateCatalogCache(owner)
return result
})
@@ -998,8 +1022,8 @@ function pruneMissingStillMasters(owner: string, catalog: Catalog) {
keep.push(still)
continue
}
droppedIds.add(still.id)
removeStillFiles(owner, still.id)
droppedIds.add(still.id)
}
catalog.stills = keep.filter(still => beforeIds.has(still.id))
if (!droppedIds.size) return 0
@@ -1446,20 +1470,140 @@ export function existingStillPreviewPath(owner: string, id: string) {
return ''
}
/** Never throw — a locked thumb must not abort the catalog write. */
function safeRm(target: string, recursive = false) {
type RemovedEntry = { id: string, kind: 'still' | 'clip' | 'track' }
function removedEntries(clips: { id: string }[], stills: { id: string }[], tracks: { id: string }[]): RemovedEntry[] {
return [
...stills.map(item => ({ id: item.id, kind: 'still' as const })),
...clips.map(item => ({ id: item.id, kind: 'clip' as const })),
...tracks.map(item => ({ id: item.id, kind: 'track' as const }))
]
}
function pathRemains(target: string) {
try {
rmSync(target, recursive ? { recursive: true, force: true } : { force: true })
statSync(target)
return true
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code
if (code === 'ENOENT') return false
const message = error instanceof Error ? error.message : String(error)
console.error('[library] file remove failed', message)
console.error('[library] file stat failed', target, message)
return true
}
}
function stillFileRemains(target: string) {
try {
return statSync(target).isFile()
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code
if (code === 'ENOENT') return false
const message = error instanceof Error ? error.message : String(error)
console.error('[library] file stat failed', target, message)
return true
}
}
/** Log, retry once, then throw if the path is still there. Never swallow a failed unlink. */
function unlinkVerified(target: string, recursive = false) {
let mode: 'missing' | 'file' | 'dir' = 'missing'
try {
mode = statSync(target).isDirectory() ? 'dir' : 'file'
} catch (error) {
const code = (error as NodeJS.ErrnoException)?.code
if (code === 'ENOENT') return
const message = error instanceof Error ? error.message : String(error)
console.error('[library] file stat failed', target, message)
throw createError({ statusCode: 500, statusMessage: `Library delete left files on disk: ${target}` })
}
if (!recursive && mode === 'dir') return
const opts = recursive ? { recursive: true, force: true } : { force: true }
for (let attempt = 0; attempt < 2; attempt++) {
try {
rmSync(target, opts)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
console.error('[library] file remove failed', target, message)
}
if (!pathRemains(target)) return
}
console.error('[library] file still exists after remove', target)
throw createError({ statusCode: 500, statusMessage: `Library delete left files on disk: ${target}` })
}
function stillIdAllowed(id: string) {
return Boolean(id) && !id.includes('/') && !id.includes('\\') && !id.includes('..')
}
/** Master, thumb, preview, any `<id>` / `<id>.*` sibling, and the same names on the legacy roots. */
function stillArtifactPaths(owner: string, id: string) {
if (!stillIdAllowed(id)) {
throw createError({ statusCode: 400, statusMessage: 'Invalid still id' })
}
const paths: string[] = []
const seen = new Set<string>()
const add = (path: string) => {
if (!path || seen.has(path)) return
seen.add(path)
paths.push(path)
}
add(stillPath(owner, id))
add(stillThumbFile(owner, id))
add(stillPreviewFile(owner, id))
const dirs: string[] = []
try { dirs.push(join(ownerRoot(owner), 'stills')) } catch { /* owner root unavailable */ }
try {
const root = libraryRoot()
dirs.push(join(root, 'files'))
dirs.push(join(root, 'stills'))
for (const dir of [join(root, 'files'), join(root, 'stills')]) {
add(join(dir, id))
add(join(dir, `${id}.thumb.jpg`))
add(join(dir, `${id}.preview.jpg`))
}
} catch { /* legacy root unavailable */ }
for (const dir of dirs) {
let names: string[] = []
try {
if (existsSync(dir)) names = readdirSync(dir).map(name => String(name))
} catch { names = [] }
for (const name of names) {
if (name === id || name.startsWith(`${id}.`)) add(join(dir, name))
}
}
return paths
}
function entryPaths(owner: string, entry: RemovedEntry) {
if (entry.kind === 'clip') return [clipDir(owner, entry.id)]
if (entry.kind === 'track') return [trackDir(owner, entry.id)]
return stillArtifactPaths(owner, entry.id)
}
function assertRemovedEntries(owner: string, entries: RemovedEntry[]) {
const survived: string[] = []
for (const entry of entries) {
const paths = entryPaths(owner, entry)
const remains = entry.kind === 'still'
? paths.some(path => stillFileRemains(path))
: paths.some(path => pathRemains(path))
if (remains) survived.push(entry.id)
}
if (!survived.length) return
throw createError({
statusCode: 500,
statusMessage: `Library delete left files on disk: ${survived.join(',')}`
})
}
function assertStillFilesGone(owner: string, ids: string[]) {
assertRemovedEntries(owner, ids.map(id => ({ id, kind: 'still' as const })))
}
function removeStillFiles(owner: string, id: string) {
safeRm(stillPath(owner, id))
safeRm(stillThumbFile(owner, id))
safeRm(stillPreviewFile(owner, id))
for (const path of stillArtifactPaths(owner, id)) unlinkVerified(path)
assertStillFilesGone(owner, [id])
}
let thumbSlots = 0
@@ -1982,11 +2126,22 @@ export function getStill(owner: string, id: string) {
export function deleteStill(owner: string, id: string) {
return mutate(owner, (catalog) => {
const still = catalog.stills.find(item => item.id === id)
if (!still) throw createError({ statusCode: 404, statusMessage: 'Image not found' })
// A previous delete may have dropped the row and left the files. Unlink them, then 404.
if (!still) {
removeStillFiles(owner, id)
assertStillFilesGone(owner, [id])
throw createError({ statusCode: 404, statusMessage: 'Image not found' })
}
removeStillFiles(owner, id)
assertStillFilesGone(owner, [id])
catalog.stills = catalog.stills.filter(item => item.id !== id)
detachDraftStills(catalog, new Set([id]))
removeStillFiles(owner, id)
pruneMissingStillMasters(owner, catalog)
assertStillFilesGone(owner, [id])
return still
}).then((still) => {
assertStillFilesGone(owner, [id])
invalidateCatalogCache(owner)
return still
})
}
@@ -2003,15 +2158,27 @@ export function moveStill(owner: string, id: string, folderId: string) {
}
export function deleteStillFamily(owner: string, id: string) {
let ids: string[] = []
return mutate(owner, (catalog) => {
const still = catalog.stills.find(item => item.id === id)
if (!still) throw createError({ statusCode: 404, statusMessage: 'Image not found' })
if (!still) {
removeStillFiles(owner, id)
assertStillFilesGone(owner, [id])
throw createError({ statusCode: 404, statusMessage: 'Image not found' })
}
const family = stillsInSameFamily(catalog, still)
const ids = new Set(family.map(item => item.id))
catalog.stills = catalog.stills.filter(item => !ids.has(item.id))
detachDraftStills(catalog, ids)
ids = family.map(item => item.id)
const idSet = new Set(ids)
for (const item of family) removeStillFiles(owner, item.id)
assertStillFilesGone(owner, ids)
catalog.stills = catalog.stills.filter(item => !idSet.has(item.id))
detachDraftStills(catalog, idSet)
pruneMissingStillMasters(owner, catalog)
assertStillFilesGone(owner, ids)
return family
}).then((family) => {
assertStillFilesGone(owner, ids)
invalidateCatalogCache(owner)
return family
})
}