upload(): INGEST 2
segment · lines 292–305View on GitHubInserts the file row as a claim on the name, and defines how to release it.
Called by upload(): INGEST 3 Check the limitsCalls json() Shared helpers
// INGEST 2 · claim the file name (one row per file) // The file's row first: its primary key is what stops two uploads of one name at once.The row first Never runs
WhatThe stage marker, and a comment explaining why the file row is written first.
WhyThe claim comes before the limit check (INGEST 3) and before any chunk is written, so a duplicate is refused before it takes any room or stores any text.
try { await env.DB.prepare('INSERT INTO files (demo_id, name, pages, chars, skipped) VALUES (?, ?, ?, ?, ?)') .bind(demo.id, name, pageCount, chars, JSON.stringify(skipped)).run()INSERT INTO files: claim the name Ingestion
WhatOne INSERT INTO files, bound to the demo account's id, the name, pageCount, chars and skipped as a JSON array.
WhyA single INSERT against PRIMARY KEY (demo_id, name) is atomic, so of two concurrent uploads of x.pdf exactly one inserts. A SELECT-then-INSERT check would let both see no row and both go on to store chunks. The row records pages and chars so that a later removal gives back exactly that much room.
table: filesPRIMARY KEY (demo_id, name)skipped: JSON array of page numbers (JSON.stringify(skipped))
} catch (error) { // A second upload of the same name hits the primary key and is refused; any other error is a real failure. if (String(error).includes('UNIQUE')) return json(409, { error: `${name} is already uploaded.` }) throw error }Duplicate name: 409 Ingestion
WhatWhen the error's text contains UNIQUE (SQLite's "UNIQUE constraint failed"), the upload is answered 409 "<name> is already uploaded." Any other error is rethrown.
WhyA visitor who wants to replace a file removes it first; a silent overwrite would leave the old file's chunks and vectors behind. On the upload route, a rethrown error reaches createApp's fetch, which answers 500 "Something went wrong. Please try again in a minute." Nothing has been written at that point.
// Undoes INGEST 2, for when INGEST 3 finds no room. const forget = () => env.DB.prepare('DELETE FROM files WHERE demo_id = ? AND name = ?').bind(demo.id, name).run()forget: release the claim Ingestion
Whatforget is a closure that deletes this file's row. It is defined here, and INGEST 3 calls it when the file does not fit.
WhyThe claim holds until forget runs. In that window a concurrent upload of the same name is answered 409, even if this upload is then refused for lack of room.