Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions apps/editor/lib/local-asset-gc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import 'fake-indexeddb/auto'
import { describe, expect, test } from 'bun:test'
import { deleteAsset, loadAssetUrl, saveAsset } from '@pascal-app/core'
import { collectNodeAssetUrlList, runLocalAssetGc } from './local-asset-gc'

type FetchHandler = (url: string) => Response | Promise<Response>

function mockFetch(handler: FetchHandler): () => void {
const original = globalThis.fetch
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString()
return handler(url)
}) as typeof fetch
return () => {
globalThis.fetch = original
}
}

function json(body: unknown, ok = true, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}

describe('local-asset-gc collectors', () => {
test('collectNodeAssetUrlList walks url and src', () => {
const urls = collectNodeAssetUrlList({
a: { url: 'asset://guide' },
b: { src: 'asset://model' },
c: { src: 'https://cdn.example.com/x.glb' },
})
expect(urls.sort()).toEqual(['asset://guide', 'asset://model'])
})
})

describe('runLocalAssetGc safety', () => {
test('skips GC when the scene list is truncated at the API limit', async () => {
const scenes = Array.from({ length: 500 }, (_, i) => ({ id: `scene-${i}` }))
const restore = mockFetch((url) => {
if (url.includes('/api/scenes?')) return json({ scenes })
return json({ graph: { nodes: {} } })
})
try {
const result = await runLocalAssetGc(() => ({ nodes: {} }))
expect(result).toBeNull()
} finally {
restore()
}
})

test('skips GC when listing scenes fails', async () => {
const restore = mockFetch(() => json({ error: 'no' }, false, 500))
try {
expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull()
} finally {
restore()
}
})

test('skips GC when the scene inventory is malformed', async () => {
for (const body of [{}, { scenes: [{ id: null }] }]) {
const restore = mockFetch(() => json(body))
try {
expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull()
} finally {
restore()
}
}
})

test('skips GC when a listed scene has no graph', async () => {
const restore = mockFetch((url) =>
url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({}),
)
try {
expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull()
} finally {
restore()
}
})

test('skips a graph with a missing or malformed node map', async () => {
const asset = await saveAsset(new File(['keep'], 'keep.txt'))
try {
for (const graph of [{}, { nodes: null }, { nodes: [] }]) {
const restore = mockFetch((url) =>
url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({ graph }),
)
try {
expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull()
expect(await loadAssetUrl(asset)).not.toBeNull()
} finally {
restore()
}
}
} finally {
await deleteAsset(asset)
}
})

test('keeps deeply nested references and references outside nodes and materials', async () => {
const deepAsset = await saveAsset(new File(['deep'], 'deep.txt'))
const collectionAsset = await saveAsset(new File(['collection'], 'collection.txt'))
let nested: unknown = deepAsset
for (let depth = 0; depth < 12; depth++) nested = { nested }
const graph = { nodes: { plugin: { nested } }, collections: { preview: collectionAsset } }
const restore = mockFetch((url) =>
url.includes('/api/scenes?') ? json({ scenes: [{ id: 'scene-1' }] }) : json({ graph }),
)
try {
await runLocalAssetGc(() => ({ nodes: {} }))
expect(await loadAssetUrl(deepAsset)).not.toBeNull()
expect(await loadAssetUrl(collectionAsset)).not.toBeNull()
} finally {
restore()
await deleteAsset(deepAsset)
await deleteAsset(collectionAsset)
}
})

test('skips GC when the local scene cannot be parsed', async () => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: { getItem: () => '{not-json' },
})
const restore = mockFetch(() => json({ scenes: [] }))
try {
expect(await runLocalAssetGc(() => ({ nodes: {} }))).toBeNull()
} finally {
restore()
if (previous) Object.defineProperty(globalThis, 'localStorage', previous)
else Reflect.deleteProperty(globalThis, 'localStorage')
}
})

test('re-reads live nodes so mid-GC uploads stay in the keep-set', async () => {
// Live graph is empty when GC starts, then gains a guide during the
// per-scene fetch — the File must survive the sweep.
let live: Record<string, unknown> = {}
const lateAsset = 'asset://uploaded-mid-gc'
const restore = mockFetch(async (url) => {
if (url.includes('/api/scenes?')) {
// Simulate latency while the user uploads.
live = { guide: { url: lateAsset } }
return json({ scenes: [] })
}
return json({ graph: { nodes: {} } })
})
try {
const result = await runLocalAssetGc(() => ({ nodes: live }))
// Keep-set included the late upload, so sweep ran but did not need to
// delete it (result is a count of removals — File itself is not present
// in this unit test's IDB; the contract is "keep-set includes live URLs").
expect(result).not.toBeNull()
expect(collectNodeAssetUrlList(live)).toContain(lateAsset)
} finally {
restore()
}
})

test('keeps a material texture added to the live graph during inventory', async () => {
const assetUrl = await saveAsset(new File(['texture'], 'texture.png'))
let materials: unknown = {}
const restore = mockFetch((url) => {
if (url.includes('/api/scenes?')) {
materials = { floor: { texture: { url: assetUrl } } }
return json({ scenes: [] })
}
return json({ graph: { nodes: {} } })
})
try {
await runLocalAssetGc(() => ({ nodes: {}, materials }))
expect(await loadAssetUrl(assetUrl)).not.toBeNull()
} finally {
restore()
await deleteAsset(assetUrl)
}
})
})
132 changes: 132 additions & 0 deletions apps/editor/lib/local-asset-gc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {
collectLocalAssetUrls,
collectNodeAssetUrls,
sweepLocalAssetsExcept,
} from '@pascal-app/core'

const LOCAL_STORAGE_SCENE_KEY = 'pascal-editor-scene'
/** Must match apps/editor/app/api/scenes/route.ts listQuerySchema max. */
const SCENES_LIST_MAX = 500

type SceneGraphLike = {
nodes?: Record<string, unknown>
materials?: unknown
}

function collectGraphAssetUrls(graph: unknown): string[] | null {
if (!graph || typeof graph !== 'object' || !('nodes' in graph)) return null
const nodes = graph.nodes
if (!nodes || typeof nodes !== 'object' || Array.isArray(nodes)) return null
return collectLocalAssetUrls(graph)
}

/** Asset URLs still referenced by the browser's localStorage scene, if any. */
export function collectLocalStorageSceneAssetUrls(): string[] | null {
if (typeof localStorage === 'undefined') return []
try {
const raw = localStorage.getItem(LOCAL_STORAGE_SCENE_KEY)
if (raw === null) return []
return collectGraphAssetUrls(JSON.parse(raw))
} catch {
return null
}
}

/**
* Union of asset URLs across every graph this origin can still open.
* Returns null when the inventory cannot be proven complete — callers must
* skip GC rather than sweep from a partial keep-set.
*/
export async function collectAllPersistedAssetUrls(
currentGraph: SceneGraphLike,
): Promise<string[] | null> {
const currentUrls = collectGraphAssetUrls(currentGraph)
if (currentUrls === null) return null
const keep = new Set(currentUrls)
const localUrls = collectLocalStorageSceneAssetUrls()
if (localUrls === null) return null
for (const url of localUrls) keep.add(url)

// Server-side scenes may share the same asset:// handles after duplication.
// If listing fails or is truncated we cannot prove the keep-set is complete.
let scenesJson: { data?: { scenes?: unknown[] }; scenes?: unknown[] } | null = null
try {
const res = await fetch(`/api/scenes?limit=${SCENES_LIST_MAX}`)
if (!res.ok) return null
scenesJson = (await res.json()) as {
data?: { scenes?: unknown[] }
scenes?: unknown[]
}
} catch {
return null
}

const list = scenesJson?.data?.scenes ?? scenesJson?.scenes
if (!Array.isArray(list)) return null
// The API has no cursor/total. A full page means older scenes were dropped
// by `limit` — treating it as complete would delete their Files.
if (list.length >= SCENES_LIST_MAX) return null

for (const entry of list) {
const id = (entry as { id?: unknown } | null)?.id
if (typeof id !== 'string' || !id) return null
try {
const res = await fetch(`/api/scenes/${encodeURIComponent(id)}`)
if (!res.ok) return null
const body = (await res.json()) as {
data?: { graph?: SceneGraphLike; scene?: { graph?: SceneGraphLike } }
graph?: SceneGraphLike
}
const graph = body.data?.graph ?? body.data?.scene?.graph ?? body.graph ?? null
const urls = collectGraphAssetUrls(graph)
if (urls === null) return null
for (const url of urls) keep.add(url)
} catch {
return null
}
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

return [...keep]
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

/**
* Explicit GC: delete IndexedDB Files that no persisted scene references.
*
* **Do not call this from scene mount / load.** Automatic mount-time GC races
* keepalive flushes, other tabs, and uploads that have hit IndexedDB but are
* not yet on a node; a sequential GET per scene also burns the shared API rate
* bucket used by autosave (#733 review). Call only when the host can prove:
* no in-flight writes, a complete scene inventory, and spare rate budget.
* Pass references from any other recoverable snapshots in extraKeepUrls.
*
* `getLiveGraph` is re-read immediately before sweeping so both nodes and
* unsaved material texture references survive.
* No-ops when the full keep-set cannot be built (never partial-sweeps).
*/
export async function runLocalAssetGc(
getLiveGraph: () => SceneGraphLike,
extraKeepUrls: Iterable<string> = [],
): Promise<number | null> {
const keep = await collectAllPersistedAssetUrls(getLiveGraph())
if (keep === null) return null

const finalKeep = new Set<string>(keep)
const liveUrls = collectGraphAssetUrls(getLiveGraph())
if (liveUrls === null) return null
for (const url of liveUrls) {
finalKeep.add(url)
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
for (const url of extraKeepUrls) {
if (typeof url === 'string' && url.startsWith('asset://')) finalKeep.add(url)
}
return sweepLocalAssetsExcept(finalKeep)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

/** For tests: collect urls from an arbitrary node map. */
export function collectNodeAssetUrlList(nodes: Record<string, unknown>): string[] {
const urls: string[] = []
for (const node of Object.values(nodes)) {
urls.push(...collectNodeAssetUrls(node as never))
}
return urls
}
1 change: 1 addition & 0 deletions apps/editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"agentation": "^3.1.2",
"fake-indexeddb": "^6.2.6",
"react-grab": "^0.2.0",
"react-scan": "^0.5.7",
"typescript": "7.0.2"
Expand Down
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 13 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,13 @@ export {
type ResolvedAssemblyLayer,
resolveAssemblyStack,
} from './lib/assembly-stack'
export { loadAssetUrl, saveAsset } from './lib/asset-storage'
export {
deleteAsset,
listLocalAssetUrls,
loadAssetUrl,
saveAsset,
sweepLocalAssetsExcept,
} from './lib/asset-storage'
export {
BEAM_MATERIAL_LABELS,
BEAM_MATERIAL_LIBRARY_REFS,
Expand Down Expand Up @@ -491,6 +497,12 @@ export {
roomClearPolygon,
} from './lib/level-footprints'
export { getDefaultLevelName, getLevelDisplayName } from './lib/level-name'
export {
collectGraphAssetUrlsFromParts,
collectLocalAssetUrls,
collectNodeAssetUrls,
collectSceneAssetUrls,
} from './lib/local-asset-lifecycle'
export {
areMeasurementPointsCoplanar,
closestMeasurementFeatureBinding,
Expand Down
Loading
Loading