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
45 changes: 45 additions & 0 deletions src/components/load3d/modelThumbnail.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@ vi.mock('@/platform/assets/utils/assetPreviewUtil', () => ({
persistThumbnail
}))

const reportError = vi.hoisted(() => vi.fn())
vi.mock('@/platform/telemetry/reportError', () => ({ reportError }))

const createLoad3d = vi.hoisted(() => vi.fn())
vi.mock('@/extensions/core/load3d/createLoad3d', () => ({ createLoad3d }))

function mockInstance(overrides: Record<string, unknown> = {}) {
const invalidate = vi.fn()
return {
loadModel: vi.fn().mockResolvedValue(undefined),
captureThumbnail: vi.fn().mockResolvedValue('data:image/png;base64,thumb'),
remove: vi.fn(),
getLoaderManager: vi.fn(() => ({ invalidate })),
...overrides
}
}
Expand All @@ -26,6 +31,7 @@ describe('generateModelThumbnail', () => {
createLoad3d.mockReset()
isAssetPreviewSupported.mockReset().mockReturnValue(false)
persistThumbnail.mockReset()
reportError.mockReset()
})

it('renders offscreen, returns the data url, and disposes the instance', async () => {
Expand Down Expand Up @@ -109,5 +115,44 @@ describe('generateModelThumbnail', () => {
await expect(nextRun).resolves.toBe('data:image/png;base64,thumb')
expect(stuck.remove).toHaveBeenCalledTimes(1)
expect(next.loadModel).toHaveBeenCalledWith('/next.glb')
expect(reportError).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
errorType: 'load3d_thumbnail_generation_failed'
})
)
})

it('invalidates the loader before disposing on timeout, so a load that resolves afterward cannot publish', async () => {
vi.useFakeTimers()
const invalidate = vi.fn()
const order: string[] = []
const stuck = mockInstance({
loadModel: vi.fn(() => new Promise<void>(() => {})),
remove: vi.fn(() => order.push('remove')),
getLoaderManager: vi.fn(() => ({
invalidate: () => {
order.push('invalidate')
invalidate()
}
})),
captureThumbnail: vi.fn(() => {
// Would only run if the abandoned load were (incorrectly) awaited
// past the timeout; asserting it never fires is the regression
// check for the resource leak this fix closes.
throw new Error('must not capture a thumbnail for an invalidated load')
})
})
createLoad3d.mockReturnValueOnce(stuck)

const stuckRun = generateModelThumbnail('/stuck.glb', 'stuck.glb')
await vi.waitFor(() => expect(createLoad3d).toHaveBeenCalledTimes(1))
await vi.advanceTimersByTimeAsync(15_000)

await expect(stuckRun).resolves.toBeNull()
expect(invalidate).toHaveBeenCalledTimes(1)
expect(stuck.remove).toHaveBeenCalledTimes(1)
expect(order).toEqual(['invalidate', 'remove'])
expect(stuck.captureThumbnail).not.toHaveBeenCalled()
})
})
44 changes: 30 additions & 14 deletions src/components/load3d/modelThumbnail.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { withTimeout } from 'es-toolkit'

import type Load3d from '@/extensions/core/load3d/Load3d'
import {
isAssetPreviewSupported,
persistThumbnail
} from '@/platform/assets/utils/assetPreviewUtil'
import { reportError } from '@/platform/telemetry/reportError'

let queue: Promise<unknown> = Promise.resolve()
const MODEL_LOAD_TIMEOUT_MS = 15_000
Expand All @@ -27,28 +29,42 @@ async function renderThumbnail(
modelUrl: string,
assetName: string
): Promise<string | null> {
// Bounds the whole offscreen render (dynamic import, WebGL context
// creation, load, and capture), not just the load step β€” a stall in any
// of them would otherwise wedge `queue` (module-global, never reset) for
// the rest of the session, which is the exact head-of-line failure this
// module exists to prevent.
const holder: { current: Load3d | null } = { current: null }
try {
const { createLoad3d } =
await import('@/extensions/core/load3d/createLoad3d')
const load3d = createLoad3d(document.createElement('div'), {
width: 256,
height: 256,
isViewerMode: true
})
try {
await withTimeout(() => load3d.loadModel(modelUrl), MODEL_LOAD_TIMEOUT_MS)
const dataUrl = await load3d.captureThumbnail(256, 256)
return await withTimeout(async () => {
const { createLoad3d } =
await import('@/extensions/core/load3d/createLoad3d')
const instance = createLoad3d(document.createElement('div'), {
width: 256,
height: 256,
isViewerMode: true
})
holder.current = instance
await instance.loadModel(modelUrl)
const dataUrl = await instance.captureThumbnail(256, 256)
if (isAssetPreviewSupported()) {
void fetch(dataUrl)
.then((response) => response.blob())
.then((blob) => persistThumbnail(assetName, blob))
.catch(() => {})
}
return dataUrl
} finally {
load3d.remove()
}
} catch {
}, MODEL_LOAD_TIMEOUT_MS)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: (non-blocking) withTimeout here is called without a signal, and es-toolkit's timeout(ms) only clears its setTimeout on abort. When run() wins the race the timer stays armed for the full MODEL_LOAD_TIMEOUT_MS. Nothing rejects visibly, since the settled Promise.race swallows the later TimeoutError, but widening the wrapper to cover the whole render means every successful thumbnail now leaves a 15s timer behind, and a bulk asset import queues one per model. Would it be cleaner to pass a controller and abort it in the existing finally, next to getLoaderManager().invalidate()?

const timeoutController = new AbortController()
try {
  return await withTimeout(async () => { /* ... */ }, MODEL_LOAD_TIMEOUT_MS, {
    signal: timeoutController.signal
  })
} catch (error) {
  // ...
} finally {
  timeoutController.abort()
  holder.current?.getLoaderManager().invalidate()
  holder.current?.remove()
}

Aborting after the race has already settled is safe in both directions: on the timeout path abortHandler calls clearTimeout on an already-fired timer, and on the success path it cancels the pending one. It should not disturb the fake-timer regression, which advances past the deadline before the abort runs.

} catch (error) {
reportError(error, { errorType: 'load3d_thumbnail_generation_failed' })
return null
} finally {
// The timeout only rejects the wrapper β€” it cannot cancel whatever step
// is still in flight inside it. Invalidate the load before disposing so
// an abandoned `loadModel` that resolves afterward is a no-op (same
// staleness check that already guards overlapping loads on one
// instance) instead of calling setupModel() on a disposed manager.
holder.current?.getLoaderManager().invalidate()
holder.current?.remove()
}
}
12 changes: 12 additions & 0 deletions src/extensions/core/load3d/LoaderManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ export class LoaderManager implements LoaderManagerInterface {

dispose(): void {}

/**
* Mark any in-flight `loadModel()` call as stale without waiting for it.
* Bumps `currentLoadId` so the abandoned load's own staleness check (the
* same one that already protects against overlapping `loadModel` calls)
* makes it a no-op on completion β€” it will neither publish its adapter nor
* call `modelManager.setupModel()`. Callers that give up on a load (e.g. a
* timeout) but keep this manager instance alive must call this first.
*/
invalidate(): void {
this.currentLoadId++
}

async loadModel(
url: string,
originalFileName?: string,
Expand Down
Loading