feat(app): R4.3b/c import worker, client, controller; HomeRoute on the disposable worker
Protocol v1 (task → ready → result | failed with phase and kind), the worker entry with the glue bundled statically and the page's compiled Module posted, the file streamed into the module's memory; client with start and task timers (paused while hidden), settle-once, terminate always, error events never masked; module-level controller (one import at a time, cancel on leaving Home, worker chunk prefetched once the engine is loaded); the settlement mapped to the B.1.8 messages (OD-5: a trap, a timeout or an unreadable file is « Erreur de lecture du PDF. », never a corrupt PDF). HomeRoute keeps its routing and size pre-checks, loads its own index after acceptance, drops a result when the session changed. Tests: handler and client in-process, the corpus message test (O8 51, O7 stored inputs, O2/O3/Step 5), the six existing suites migrated to the real worker logic.
This commit is contained in:
1 parent
52471dbbc0
commit
6d1cce6e06
26 files changed
+2164
-247
No files matched your search
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* R4.3: the Home import's message on every file of the frozen corpora, through the real
|
||||
* worker logic in-process on the shipped module (plan §B.1.8, OD-5). O8 (the full R3
|
||||
* path, 51 PDFs: expected outcome from `tolerance.json`, the declared OD-3 / OD-4
|
||||
* differences applied), O7 (the stored reader inputs: expected from `readReportArchive`),
|
||||
* the O2 PDFs of the R3 build, the O3 envelopes and the Step 5 fixtures (all open the
|
||||
* editor). A technical failure of the worker is never shown as a corrupt PDF: a trap, a
|
||||
* timeout and an unreadable file give « Erreur de lecture du PDF. », a worker that
|
||||
* cannot start the engine message.
|
||||
*/
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
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 { coreRuntime } from '@/core/runtime'
|
||||
import { setImportWorkerSpawn } from '@/core/worker/controller'
|
||||
import { useReportStore } from '@/state/reportStore'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import { FIXTURES_DIR } from '../helpers/goldens'
|
||||
import {
|
||||
throwingEngineLoader,
|
||||
useInProcessImportWorker,
|
||||
} from '../helpers/importWorker'
|
||||
|
||||
const ROOT = resolve(FIXTURES_DIR, '../../../..')
|
||||
const oracle = (name: string) =>
|
||||
JSON.parse(
|
||||
readFileSync(join(ROOT, 'crates/core/tests/oracles/r4', name), 'utf8'),
|
||||
)
|
||||
|
||||
/** The message of a failure kind (plan §B.1.8), `editor` for a success. */
|
||||
function expectedOf(outcome: {
|
||||
ok: boolean
|
||||
kind?: string
|
||||
foundVersion?: number
|
||||
}): string {
|
||||
if (outcome.ok) return 'editor'
|
||||
switch (outcome.kind) {
|
||||
case 'incompatible_version':
|
||||
return fr['home.import.error_incompatible_version']!.replace(
|
||||
'{version}',
|
||||
String(outcome.foundVersion),
|
||||
)
|
||||
case 'invalid_pdf':
|
||||
return fr['home.import.error_invalid_pdf']!
|
||||
case 'attachment_stripped':
|
||||
return fr['home.import.error_attachment_stripped']!
|
||||
case 'no_attachment':
|
||||
return fr['home.import.error_no_attachment']!
|
||||
case 'lone_surrogate':
|
||||
return fr['home.import.error_lone_surrogate']!
|
||||
default:
|
||||
throw new Error(`unexpected kind ${outcome.kind}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Rust outcomes that differ from the R3 path on purpose (RUST.md §10.3). */
|
||||
const DECLARED: Record<string, { ok: boolean; kind?: string }> = {
|
||||
'values-1m': { ok: false, kind: 'attachment_stripped' },
|
||||
'surrogate-content-overwritten': { ok: false, kind: 'lone_surrogate' },
|
||||
'surrogate-version-overwritten': { ok: false, kind: 'lone_surrogate' },
|
||||
'two-files-decoy-first': { ok: false, kind: 'lone_surrogate' },
|
||||
}
|
||||
|
||||
const ERRORS = [
|
||||
'home.import.error_incompatible_version',
|
||||
'home.import.error_invalid_pdf',
|
||||
'home.import.error_attachment_stripped',
|
||||
'home.import.error_no_attachment',
|
||||
'home.import.error_lone_surrogate',
|
||||
'home.import.error_invalid_copy',
|
||||
'home.import.error_generic',
|
||||
'home.import.error_core_unavailable',
|
||||
] as const
|
||||
|
||||
function renderHome() {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomeRoute />} />
|
||||
<Route path="/editor" element={<p data-testid="editor-route" />} />
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
/** Picks `file` on a fresh Home and returns `editor` or the error line shown. */
|
||||
async function outcomeOf(file: File): Promise<string> {
|
||||
cleanup()
|
||||
// A fresh tab for every file: the previous import's draft would be a held text.
|
||||
sessionStorage.clear()
|
||||
useReportStore.getState().clearTrapped()
|
||||
useReportStore.setState({
|
||||
report: null,
|
||||
archive: null,
|
||||
activeObservationIndex: 0,
|
||||
})
|
||||
renderHome()
|
||||
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 shown = await waitFor(
|
||||
() => {
|
||||
if (screen.queryByTestId('editor-route')) return 'editor'
|
||||
// A message with a placeholder is matched on its text before it.
|
||||
const error = ERRORS.map((key) => fr[key]!.split('{')[0]!).find((text) =>
|
||||
screen.queryByText(text, { exact: false }),
|
||||
)
|
||||
if (!error) throw new Error(`pending (${file.name})`)
|
||||
return screen.getByText(error, { exact: false }).textContent ?? error
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
return shown
|
||||
}
|
||||
|
||||
const pdfFile = (path: string, name = path.split('/').pop() ?? 'bilan.pdf') =>
|
||||
new File([readFileSync(path)], name, { type: 'application/pdf' })
|
||||
|
||||
beforeAll(() => {
|
||||
useInProcessImportWorker()
|
||||
})
|
||||
beforeEach(() => {
|
||||
useLocaleStore.setState({ locale: 'fr' })
|
||||
sessionStorage.clear()
|
||||
vi.stubGlobal('alert', vi.fn())
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('Home import messages on the frozen corpora (real worker logic, shipped module)', () => {
|
||||
it('O8: every tolerance case gives the R3 message, outside the declared differences', async () => {
|
||||
const cases = oracle('tolerance.json').cases as Array<{
|
||||
id: string
|
||||
pdf: string
|
||||
outcome: { ok: boolean; kind?: string; foundVersion?: number }
|
||||
}>
|
||||
expect(cases).toHaveLength(51)
|
||||
const mismatches: string[] = []
|
||||
for (const c of cases) {
|
||||
const expected = expectedOf(DECLARED[c.id] ?? c.outcome)
|
||||
const shown = await outcomeOf(pdfFile(join(ROOT, c.pdf)))
|
||||
if (shown !== expected)
|
||||
mismatches.push(`${c.id}: expected ${expected}, shown ${shown}`)
|
||||
}
|
||||
expect(mismatches).toEqual([])
|
||||
}, 120_000)
|
||||
|
||||
it('O7: every stored reader input gives the reader outcome message', async () => {
|
||||
const inputs = oracle('read.json').inputs as Array<{
|
||||
file: string
|
||||
kind: string
|
||||
stored: string
|
||||
outcomes: {
|
||||
readReportArchive?: {
|
||||
ok: boolean
|
||||
kind?: string
|
||||
foundVersion?: number
|
||||
}
|
||||
}
|
||||
}>
|
||||
const mismatches: string[] = []
|
||||
let count = 0
|
||||
for (const input of inputs) {
|
||||
const expected = input.outcomes.readReportArchive
|
||||
if (input.kind !== 'pdf' || input.stored !== 'bytes' || !expected)
|
||||
continue
|
||||
count += 1
|
||||
const shown = await outcomeOf(
|
||||
pdfFile(join(FIXTURES_DIR, 'pdf/r4/read', input.file)),
|
||||
)
|
||||
if (shown !== expectedOf(expected)) {
|
||||
mismatches.push(
|
||||
`${input.file}: expected ${expectedOf(expected)}, shown ${shown}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
expect(mismatches).toEqual([])
|
||||
expect(count).toBeGreaterThan(130)
|
||||
}, 180_000)
|
||||
|
||||
it('O2, O3 and the Step 5 fixtures open the editor', async () => {
|
||||
const files = [
|
||||
join(FIXTURES_DIR, 'report-v2.full.pdf'),
|
||||
join(FIXTURES_DIR, 'report-v2.minimal.pdf'),
|
||||
join(FIXTURES_DIR, 'report-v3.bare.pdf'),
|
||||
...readdirSync(join(FIXTURES_DIR, 'pdf/r3'), {
|
||||
recursive: true,
|
||||
encoding: 'utf8',
|
||||
})
|
||||
.filter((n) => n.endsWith('.pdf'))
|
||||
.map((n) => join(FIXTURES_DIR, 'pdf/r3', n)),
|
||||
...readdirSync(join(FIXTURES_DIR, 'pdf/step6'))
|
||||
.filter((n) => n.endsWith('.pdf'))
|
||||
.map((n) => join(FIXTURES_DIR, 'pdf/step6', n)),
|
||||
]
|
||||
expect(files.length).toBeGreaterThanOrEqual(20)
|
||||
for (const file of files) {
|
||||
expect(await outcomeOf(pdfFile(file)), file).toBe('editor')
|
||||
expect(useReportStore.getState().report?.version).toBe(3)
|
||||
}
|
||||
}, 60_000)
|
||||
|
||||
it('a worker trap or an unreadable file is « Erreur de lecture du PDF. », never a corrupt-PDF message', async () => {
|
||||
const trapping = useInProcessImportWorker(
|
||||
throwingEngineLoader(new WebAssembly.RuntimeError('unreachable')),
|
||||
)
|
||||
try {
|
||||
expect(
|
||||
await outcomeOf(pdfFile(join(FIXTURES_DIR, 'report-v3.bare.pdf'))),
|
||||
).toBe(fr['home.import.error_generic'])
|
||||
// The worker's trap never touches the page's own runtime (plan §B.3 isolation).
|
||||
expect(coreRuntime().status).toBe('ready')
|
||||
} finally {
|
||||
trapping.restore()
|
||||
useInProcessImportWorker()
|
||||
}
|
||||
const unreadable = pdfFile(join(FIXTURES_DIR, 'report-v3.bare.pdf'))
|
||||
Object.defineProperty(unreadable, 'stream', {
|
||||
value: () => ({
|
||||
getReader: () => ({
|
||||
read: () =>
|
||||
Promise.reject(new DOMException('gone', 'NotReadableError')),
|
||||
cancel: async () => {},
|
||||
}),
|
||||
}),
|
||||
})
|
||||
expect(await outcomeOf(unreadable)).toBe(fr['home.import.error_generic'])
|
||||
})
|
||||
|
||||
it('a worker that cannot start gives the engine message', async () => {
|
||||
setImportWorkerSpawn(() => {
|
||||
throw new DOMException('blocked', 'SecurityError')
|
||||
})
|
||||
try {
|
||||
expect(
|
||||
await outcomeOf(pdfFile(join(FIXTURES_DIR, 'report-v3.bare.pdf'))),
|
||||
).toBe(fr['home.import.error_core_unavailable'])
|
||||
} finally {
|
||||
useInProcessImportWorker()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user