Files
faunosteo/apps/app/tests/unit/routes.HomeRoute.rescueCopy.test.tsx
bchanot e659924ec0 feat(app): R4.3a the page reads the file chunk by chunk and streams it to the worker's sink
Measured at R4.3a (RUST.md §10.5): reading a file inside a WebKit worker costs about
180 MiB of content RSS whatever the method (arrayBuffer, stream, BYOB), 14 MiB on the
page; a page-side BYOB read feeding the worker's FileBytes gives 106 MiB on a 50 MiB file
against 272 in the worker and 76 for the TypeScript. Protocol v1 gains chunk / ack / end:
one 1 MiB buffer travels (transferred) and comes back after each push, so the page holds
one chunk and the worker's sink the only whole copy; no byte is parsed on the page. The
worker refuses an oversize announced before any chunk and a size that changes while
reading. Tests adapted (handler, client with a scripted ack, read failure on the page).
2026-10-18 18:57:55 +02:00

205 lines
6.6 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The rescue copy (`JSON.stringify(report)`, the downloaded format) imported from Home:
* routed by content from the first KiB, read in the import worker by the core's copy
* restore (strict UTF-8, one BOM dropped; the real worker logic in-process on the shipped
* module, R4.3), opened as the original report; every refusal leaves the store and the
* tab's slots untouched.
*/
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import HomeRoute from '@/app/routes/HomeRoute'
import { MAX_COPY_BYTES } from '@/core/worker/handler'
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { buildGoldenReports, GOLDEN_REPORTS } from '../helpers/goldenReports'
import {
answeringEngineLoader,
useInProcessImportWorker,
type FakeWorker,
} from '../helpers/importWorker'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
let sheet: SheetIndex
let workers: FakeWorker[]
let restoreSpawn: () => void
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
useReportStore.setState({
report: null,
archive: null,
activeObservationIndex: 0,
})
useReportStore.getState().clearTrapped()
vi.stubGlobal('alert', vi.fn())
;({ workers, restore: restoreSpawn } = useInProcessImportWorker())
})
afterEach(() => {
restoreSpawn()
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
async function pick(file: File) {
render(
<MemoryRouter initialEntries={['/']}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/editor" element={<p data-testid="editor-route" />} />
</Routes>
</MemoryRouter>,
)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
}
const copyFile = (text: string, name = 'faunosteo-brouillon.json') =>
new File([text], name, { type: 'application/json' })
describe('opening a rescue copy', () => {
it.each(GOLDEN_REPORTS)(
'reopens the %s report equal to the original',
async (name) => {
const { reports } = buildGoldenReports(sheet)
await pick(copyFile(JSON.stringify(reports[name])))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(reports[name])
expect(useReportStore.getState().archive).toBeNull()
},
)
it('routes by content: no .json name, no type, leading blanks and a BOM', async () => {
const report = minimalReport(sheet, { conclusion: 'sniffed' })
const text = ` \n${JSON.stringify(report)}`
await pick(new File([text], 'secours'))
await screen.findByTestId('editor-route')
expect(useReportStore.getState().report).toEqual(report)
})
it('announces a copy rebased on another sheet revision', async () => {
const stale = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'c'.repeat(64) },
observations: [
{
id: 'o',
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [],
freeTextFindings: [],
comment: '',
},
],
})
await pick(copyFile(JSON.stringify(stale)))
await screen.findByTestId('editor-route')
expect(window.alert).toHaveBeenCalledWith(
fr['editor.draft_rebased']!.replace('{count}', '1'),
)
})
it('still sends a PDF down the PDF path', async () => {
await pick(
new File(['%PDF-1.7 not really'], 'bilan.pdf', {
type: 'application/pdf',
}),
)
await screen.findByText(fr['home.import.error_no_attachment']!)
expect(screen.queryByText(fr['home.import.error_invalid_copy']!)).toBeNull()
})
})
describe('refusing a file', () => {
const unreadable = JSON.stringify({ version: 7 })
const refused: [string, () => File][] = [
['invalid JSON', () => copyFile('{not json')],
['an unsupported version', () => copyFile(JSON.stringify({ version: 1 }))],
[
'a lone surrogate',
() =>
copyFile(
JSON.stringify(minimalReport(sheet, { conclusion: 'a\ud800b' })),
),
],
[
'invalid UTF-8',
() => new File([new Uint8Array([0x7b, 0xff, 0xfe, 0x7d])], 'copie.json'),
],
]
async function expectUntouched() {
await screen.findByText(fr['home.import.error_invalid_copy']!)
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(unreadable)
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
expect(window.alert).not.toHaveBeenCalled()
expect(screen.queryByTestId('editor-route')).toBeNull()
}
it.each(refused)(
'%s: error line, nothing changed, nothing held',
async (_label, make) => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
await pick(make())
await expectUntouched()
expect(workers).toHaveLength(1)
},
)
it('an over-cap file is refused before any full read', async () => {
sessionStorage.setItem(DRAFT_KEY, unreadable)
const file = copyFile('{"version":3}')
Object.defineProperty(file, 'size', { value: MAX_COPY_BYTES + 1 })
const read = vi.spyOn(file, 'arrayBuffer')
const stream = vi.spyOn(file, 'stream')
await pick(file)
await expectUntouched()
expect(read).not.toHaveBeenCalled()
expect(stream).not.toHaveBeenCalled()
expect(workers).toHaveLength(0)
})
it.each(['internal', 'rebase_failed'])(
'the core kind %s takes the engine message path, not the copy message',
async (kind) => {
// The worker's core answers the kind (the seam replaced; afterEach restores it).
const refusal = JSON.stringify({ ok: false, kind, detail: '' })
;({ workers, restore: restoreSpawn } = useInProcessImportWorker(
answeringEngineLoader(refusal),
))
await pick(copyFile(JSON.stringify(minimalReport(sheet))))
await screen.findByText(fr['home.import.error_core_unavailable']!)
// The worker answered: the line is the core's kind, not a worker failure.
expect(workers[0]!.sequence()).toEqual(['ready', 'result'])
expect(
screen.queryByText(fr['home.import.error_invalid_copy']!),
).toBeNull()
expect(useReportStore.getState().report).toBeNull()
},
)
})