upload(): INGEST 5
segment · lines 338–369View on GitHubWrites the archive and the chunks in D1 batches.
Calls json() Shared helpers keeps() Consent and the archive
// INGEST 5 · store the chunks (and archived pages) in D1 // With consent, each page's text is archived beside its chunks; a re-upload of the file replaces it.Chunks, and the archive with consent Never runs
WhatThe stage marker, and a comment stating the archive rule.
WhyThe chunks are deleted with the documents after 10 idle days. The archive is the copy kept for up to 25 months for analysis and golden sets, so it is written only for visitors the site may record.
const archive = keeps(request) ? [ env.DB.prepare('DELETE FROM archived_pages WHERE demo_id = ? AND file = ?').bind(demo.id, name), ...pages.map((p) => env.DB.prepare('INSERT INTO archived_pages (demo_id, file, page, text) VALUES (?, ?, ?, ?)').bind(demo.id, name, p.page, p.text)), ] : []The archive statements Ingestion
WhatWhen keeps(request) is true (X-Demo-Keep is exactly '1'), the list holds a DELETE of this file's archived pages followed by one INSERT INTO archived_pages per page with text; otherwise the list is empty. The statements are prepared here and run in the batches at line 355.
WhyThe idle purge deletes chunks and file rows but never archived_pages, so a file uploaded again after a purge would violate the archive's PRIMARY KEY (demo_id, file, page). Running the DELETE first makes the re-upload replace the old archive. In this repository the site's mayRecord (functions/_lib/track.ts) always returns false, so the site's Pages Function always sends X-Demo-Keep: 0 and the list is always empty.
table: archived_pagesPRIMARY KEY (demo_id, file, page)KEEP_MONTHS = 25
Lines 340–346 on GitHubPages Function: where X-Demo-Keep is set
try { // The archive first, then one insert per chunk. const statements = [ ...archive, ...chunks.map((c) => env.DB.prepare('INSERT INTO chunks (id, demo_id, file, page, text, seq) VALUES (?, ?, ?, ?, ?, ?)').bind(c.id, demo.id, c.file, c.page, c.text, c.seq)), ]One INSERT per chunk Ingestion
WhatInside a try, the statement list is the archive statements followed by one INSERT INTO chunks per chunk.
WhyThe archive's DELETE must run before its INSERTs, and putting the archive first places the DELETE in the first batch. The chunk ids are new (INGEST 4's random prefix), so the INSERTs need no conflict clause.
table: chunksindex: chunks_demo ON chunks(demo_id)
// In batches of 100 statements; a failure part-way, whichever batch, is undone below. for (let i = 0; i < statements.length; i += 100) await env.DB.batch(statements.slice(i, i + 100))Batches of 100 Ingestion
WhatThe statements go to env.DB.batch 100 at a time, and each batch is awaited before the next.
WhyD1 runs a batch as one SQL transaction, so a failing statement rolls back its whole batch. Consecutive batches are separate transactions, so a failure in the third batch leaves the first two committed, and the catch at line 356 undoes them. A demo account may hold 500,000 characters (LIMITS.chars) at up to 900 a chunk (CHUNK_CHARS), so a large upload can need several hundred chunk INSERTs and several batches.
} catch (error) { console.error('demo upload: the chunks could not be stored', error)Log the failure Ingestion
WhatAny error in the try, from preparing and binding the statements or from a batch, is caught and logged with console.error.
WhyThe log line names the stage, so a storage failure can be told apart from an embedding failure (INGEST 6), which has its own log line and does not fail the upload.
// Undo everything of this upload: its archive, its chunks (by the upload's prefix), its file row and its room. await env.DB.batch([ ...(archive.length > 0 ? [env.DB.prepare('DELETE FROM archived_pages WHERE demo_id = ? AND file = ?').bind(demo.id, name)] : []), env.DB.prepare('DELETE FROM chunks WHERE demo_id = ? AND id LIKE ?').bind(demo.id, `${demo.id}-${upload}-%`), env.DB.prepare('DELETE FROM files WHERE demo_id = ? AND name = ?').bind(demo.id, name), env.DB.prepare('UPDATE demos SET files = files - 1, pages = pages - ?, chars = chars - ?, uploads = uploads - 1 WHERE id = ?').bind(pageCount, chars, demo.id), ])Undo the whole upload, in one transaction Ingestion
WhatOne batch deletes this file's archive (only when an archive was attempted), the chunks whose id starts with this upload's prefix, and the file row, and takes the file, its pages, its characters and the upload back off the demo account's totals.
WhyBecause the undo is one batch, it is atomic: the room is never given back without the rows going, and the rows never go without the room. The LIKE on the upload's prefix deletes exactly the chunks this upload committed and no other file's. uploads is decremented so that, after a failed first upload, the next upload still counts as the account's first at INGEST 7. used_at and cleared_at are not restored. An older archive of the same file name is gone either way. If the first batch failed, its DELETE was rolled back and this DELETE removes the old archive; if a later batch failed, the first batch's DELETE already removed it. If this undo batch itself throws, the error reaches createApp's fetch, which answers a generic 500 and leaves the partial upload in place.
return json(500, { error: `${name} could not be stored. Please try again.` }) }500, try again Ingestion
WhatAnswers 500 "<name> could not be stored. Please try again."
WhyAfter the undo, the upload's chunks, file row and room are gone, the claim on its name included, so the same file can be uploaded again at once. Only used_at and cleared_at keep the values INGEST 3 set.