// One design test's turn with the server (api/design): a slot for the test worker, asked for before any picture is // sent (a ticket keeps the page's place while another design is tested); the picture sent under it, as for a reading // (upload.js); the server's facts checked against the first reading's; then the polls, about once a second, while // this browser's scanner, where it joins, reads the test's scenes here (scanner.js). It resolves to how the turn // ended; test.js keeps the queue and shows it. The server only ever answers with words: never reads or counts. import { t } from './copy.js'; import { ending, linked, sleep } from './frames.js'; import { readsContent, runBrowserPart } from './scanner.js'; import { failure, prepare, upload } from './upload.js'; const ID = /^[0-9a-f]{32}$/; // the server's ids, for tests, slots and tickets alike const HEX = /^[0-9a-f]{64}$/; const WHY = ['facts', 'version', 'small', 'big', 'inverted', 'mirrored', 'several', 'twin']; // the server's refusals const ANSWERS = ['like', 'worse', 'close', 'few']; let S = null; // web/data/test.json let on = null; // test.js: { paint(p), tell(p, rec, what), joined() } /** test.js, once test.json is in. */ export function useTurn(settings, hooks) { S = settings; on = hooks; } /** A turn that ends without an answer: the deadline's line, with Try again. */ export const late = () => ({ state: 'failed', line: t('test.late'), retry: true }); /** The page's own reasons a picture can't be tested, in order, or '': zxing-cpp's error correction, mask or raw bytes * unknown; light on dark; under {min} pixels per square in the file; over max_pixels; over max_version. (A record's * square check would add "mirrored" after light on dark.) The server checks each again itself. */ export function refusal(r, drawn) { const c = r.checks; const L = S.limits; const mask = Number.isInteger(r.mask) && r.mask >= 0 && r.mask <= 7; if (!['L', 'M', 'Q', 'H'].includes(r.ec_level) || !mask || !HEX.test(r.raw_sha256 || '')) return 'facts'; if (c.contrast?.inverted === true) return 'inverted'; if (Number.isFinite(c.ppm?.native) && c.ppm.native < (c.version === 1 ? L.min_ppm_v1 : L.min_ppm)) return drawn ? 'small_svg' : 'small'; // an SVG drawn here: a crop helps, not a bigger export if (r.size?.[0] * r.size?.[1] > L.max_pixels) return 'big'; // no size known: the server checks it return c.version > L.max_version ? 'version' : ''; } /** Whether the first reading (r) already shows that the test's two truths will differ (started): zxing-cpp's raw bytes * (raw_bytes, raw_sha256) aren't UTF-8 text, so Chrome on Android keeps its scanner out from the start. Only for a * content the reading gives whole (its text printable, not cut). zxing-cpp's read counts for a content only as the * same bytes, or as raw bytes and a text made of them, one way or the other (reading_content.py _same), and a text is * made only of raw bytes that aren't UTF-8. So when the content is that text (its bytes the text's UTF-8 length), raw * bytes of another length aren't UTF-8; when it is raw bytes that aren't UTF-8 (its text then their ISO-8859-1 * reading), they are zxing-cpp's when the SHA-256s match. Else false, and the 202's truths decide, as for Shift JIS * text whose characters take as many bytes in UTF-8 (Greek, say). */ export function rawNotText(r) { const c = r?.content; const whole = typeof c?.text === 'string' && !c.cut && Number.isInteger(c.bytes); if (!whole || !Number.isInteger(r.raw_bytes)) return false; const n = new TextEncoder().encode(c.text).length; return c.bytes === n ? r.raw_bytes !== n : c.sha256 === r.raw_sha256; } /** DELETE what the server holds for a test, whichever is live: its test, its slot or its ticket (keepalive as the * page goes). The server drops it at once, and a running test's worker stops after the scene in hand. */ export function leave(rec, keepalive = false) { for (const id of [rec.id, rec.slot, rec.ticket]) { if (id) fetch(`api/design/${id}`, { method: 'DELETE', keepalive, cache: 'no-store' }).catch(() => {}); } rec.id = rec.slot = rec.ticket = null; } const body = (res) => res.json().catch(() => null); async function call(url, signal, method = 'GET') { try { return await fetch(url, { method, signal, cache: 'no-store' }); } catch (err) { if (signal.aborted) throw err; throw failure(t('errors.unreachable'), true); } } /** request(signal)'s response and its body read, [res, j], within s seconds (test.json): past them, as on a network * failure, the server can't be reached, with Try again, and no progress line is left running. The page leaving the * test still rejects as aborted. */ async function within(s, signal, request) { const ctl = linked(signal); const timer = setTimeout(() => ctl.abort(), s * 1000); try { const res = await request(ctl.signal); const j = await body(res); if (signal.aborted || !ctl.signal.aborted) return [res, j]; } catch (err) { if (signal.aborted || !ctl.signal.aborted) throw err; } finally { clearTimeout(timer); } throw failure(t('errors.unreachable'), true); } /** test.js: /api/health's answer, or null, within the slot's hold (the server answers at once); past it, a failure. */ export const fetchHealth = () => within(S.server.slot_hold_s, new AbortController().signal, (s) => fetch('api/health', { cache: 'no-store', signal: s })).then(([res, j]) => (res.ok ? j : null)); /** One test's turn, once rec.part says what this browser's scanner does in it. Resolves to the turn's end: { state: * 'done', answers }, { state: 'cant', why }, { state: 'failed', line, retry }, { redo: 'drops' | 'conflicts' } (the * server dropped the test, or its slot), or { off: true }. Throws a failure (upload.js) when the server can't be * reached, and rejects as aborted when the page leaves the test. The page's own refusals come first, at every turn: * Try again after the unreachable line can come before they were checked. */ export async function turn(p, rec, signal) { const why = refusal(p.result, p.drawn); if (why) return { state: 'cant', why }; const blob = await prepare(p.file); // checked and converted first: a slow conversion never uses up the slot's hold const slot = await askSlot(p, rec, signal); if (!slot.id) return slot; rec.state = 'upload'; on.paint(p); const frames = rec.part.decision === 'joins' ? `&frames=${rec.part.frames}` : ''; const url = `api/design?slot=${slot.id}${frames}`; const [res, j] = await within(S.page_waits.upload_s, signal, (s) => upload(url, p.file, s, blob)); rec.slot = null; // used up, whatever the answer: until it is read, leaving DELETEs the slot, and the test with it if (signal.aborted) throw ending('aborted'); if (res.status === 202 && ID.test(j?.test)) return started(p, rec, j, signal); if (res.status === 200 && j?.verdict === 'cant' && WHY.includes(j.why)) { // the reading had its facts: 'differ' return { state: 'cant', why: j.why === 'facts' ? 'differ' : j.why }; } if (res.status === 409) return { redo: 'conflicts' }; if ([400, 413, 415, 422].includes(res.status)) return { state: 'failed', line: t('errors.unreadable'), retry: false }; return late(); } /** The test worker for this page: a slot, or, while another design is tested, the busy line and a ticket that keeps * the page's place, asked again after Retry-After (without the picture) for up to busy_total_s. The server answers * each request at once, so each is given the slot's own hold: a slot that came any later would have lapsed. */ async function askSlot(p, rec, signal) { let first = 0; for (;;) { const url = `api/design/slot${rec.ticket ? `?ticket=${rec.ticket}` : ''}`; const [res, j] = await within(S.server.slot_hold_s, signal, (s) => call(url, s, 'POST')); if (res.status === 200 && ID.test(j?.slot)) { rec.ticket = null; // used up by the slot rec.slot = j.slot; on.tell(p, rec, 'start'); return { id: j.slot }; } if (res.status === 503 && j?.error === 'off') return { off: true }; if (res.status !== 503 || j?.error !== 'busy') return late(); rec.ticket = ID.test(j.ticket) ? j.ticket : null; const [lo, hi] = S.server.retry_s; const header = Number(res.headers.get('Retry-After')); rec.n = Math.min(hi, Math.max(lo, Number.isInteger(header) && header > 0 ? header : Number(j.retry_s) || hi)); first ||= Date.now(); if (Date.now() + rec.n * 1000 - first > S.page_waits.busy_total_s * 1000) { leave(rec); return { state: 'failed', line: t('test.waiting'), retry: true }; } rec.state = 'busy'; on.tell(p, rec, 'busy'); on.paint(p); await sleep(rec.n * 1000, signal); } } /** Started: the server's facts must be the first reading's (version, error correction, mask and raw bytes), or the * test read its code differently; then the server's part, and this browser's where it joins with its scenes. A code * this browser's scanner can't read (scanner.js readsContent) keeps it out, whatever it would have done: line 2 then * says this browser has none the test can use, with no Try again. The record keeps whether the two truths differ * (known from the start where the first reading shows it: rawNotText, scanner.js partFor): Chrome on Android keeps * its scanner out of such a code, so line 2 in any browser never sends the visitor there. */ async function started(p, rec, j, signal) { rec.id = j.test; const r = p.result; const same = j.version === r.checks.version && j.ec_level === r.ec_level && j.mask === r.mask; if (!same || !Array.isArray(j.truths) || j.truths[0] !== r.raw_sha256) { leave(rec); return { state: 'cant', why: 'differ' }; } const part = rec.part; rec.truthsDiffer = j.truths[0] !== j.truths[1]; // raw bytes that aren't the text in UTF-8 (test_view.js lineTwo) if (!readsContent(rec.truthsDiffer)) part.decision = 'none'; // so nothing is fetched, read or counted for it const join = part.decision === 'joins'; if (join && !(j.scenes === S.scenes.s && j.frames === part.frames)) part.end = 'start'; // not given its scenes else if (join && !rec.added && !rec.counted) { rec.counted = true; on.joined(); // by itself: towards the page session's bound } rec.state = 'running'; rec.done = 0; const browser = join && !part.end ? browserPart(p, rec, j) : null; part.over = !browser; on.paint(p); return watch(p, rec, browser, signal); } /** This browser's part: its scanner reads the scenes as they come; once it is over, the polls carry frames=0. */ async function browserPart(p, rec, j) { const part = rec.part; part.ctl = new AbortController(); rec.ctl.signal.addEventListener('abort', () => part.ctl.abort(), { once: true }); part.running = true; part.k = 0; const out = await runBrowserPart({ base: `api/design/${j.test}`, truths: j.truths.filter((x) => HEX.test(x)), mode: part.frames, signal: part.ctl.signal, onScene: (k) => { part.k = k; on.paint(p); }, onMode: (m) => { part.frames = m; on.paint(p); }, }); const cut = part.end; // watch() stopped it first: it outlived the test const end = cut || (part.left && out.end === 'aborted' ? 'left' : out.end); Object.assign(part, { running: false, over: true, end, answer: cut ? null : out.answer || null }); on.paint(p); } /** Whether job (the browser's part) ended before signal aborted. */ const ended = (job, signal) => new Promise((resolve) => { if (signal.aborted) resolve(false); signal.addEventListener('abort', () => resolve(false), { once: true }); job.then(() => resolve(true), () => resolve(true)); }); /** The polls until the server's answers come; the last one carries frames=0, so the server keeps nothing more. A 404 * (the server dropped the test: with its answers in hand, the turn ends with them, unless the browser's part found * its scenes dropped too), "late", or the browser's part finding the test dropped, ends the turn. Nothing waits past * the test's life, the server's own time for it (deadline_s + after_deadline_s from its start): a poll that hasn't * come back by then gives the deadline's line, and a browser's part still reading, with the server's answers in, * stops partway (end() then leaves the test). A page that didn't run for over idle_s (frozen in the background: * the longest gap between its steps here) finds the test dropped, as its next poll would. */ async function watch(p, rec, browser, signal) { const part = rec.part; const life = linked(signal); const timer = setTimeout(() => life.abort(), (S.server.deadline_s + S.server.after_deadline_s) * 1000); let answers = null; let tick = Date.now(); let gap = 0; const beat = () => { gap = Math.max(gap, Date.now() - tick); tick = Date.now(); }; try { for (;;) { const zero = part.over; const res = await call(`api/design/${rec.id}${zero ? '?frames=0' : ''}`, life.signal); beat(); if (res.status === 404) return answers && part.end !== 'dropped' ? { state: 'done', answers } : { redo: 'drops' }; const j = await body(res); if (j?.state === 'late') { // read before a scene's 404: the server drops the scenes of a test it has lost rec.id = null; // dropped by the server with this answer return late(); } if (part.end === 'dropped') return { redo: 'drops' }; if (j?.state === 'running' && Number.isInteger(j.done)) rec.done = j.done; if (j?.state === 'done') { if (!ANSWERS.includes(j.scanners?.['zxing-cpp']) || !ANSWERS.includes(j.scanners?.wechat)) return late(); answers = j.scanners; rec.done = S.scenes.s; if (zero) { rec.id = null; // dropped by the server with the frames=0 poll that gave its answers return { state: 'done', answers }; } // the scenes stay on the server until the browser's part is over: then one last poll if (!(await ended(browser, life.signal))) throw ending('aborted'); continue; } on.paint(p); await sleep(S.page_waits.poll_s * 1000, life.signal); beat(); } } catch (err) { if (signal.aborted || !life.signal.aborted) throw err; beat(); if (!answers || part.end === 'dropped') return gap > S.server.idle_s * 1000 ? { redo: 'drops' } : late(); if (part.running) { Object.assign(part, { end: 'stopped', running: false, over: true }); part.ctl.abort(); } return { state: 'done', answers }; } finally { clearTimeout(timer); } }