ask(): ASK 2
segment · lines 552–557View on GitHubReserves one question atomically.
Calls json() Shared helpers
// ASK 2 · reserve one of the demo's ten questions // The reservation is the limit: one statement, so two asks for the last question cannot both pass. const reserved = await env.DB.prepare("UPDATE demos SET asks_used = asks_used + 1, used_at = datetime('now') WHERE id = ? AND asks_used < ? RETURNING asks_used") .bind(demo.id, LIMITS.asks).first<{ asks_used: number }>()Check and increment in one statement Query time
WhatOne D1 prepared statement adds 1 to asks_used and sets used_at, only where the demo account's row still has asks_used below LIMITS.asks (10). RETURNING gives back the new asks_used, and .first() returns that row, or null when the WHERE matched nothing.
WhyA SELECT followed by an UPDATE would let two asks both read 9 and both pass. One statement leaves no gap between the check and the increment. D1 runs it atomically, so only one of two concurrent asks for the last question matches asks_used < 10. RETURNING returns the new count without a second query. used_at records that the account is in use, and the idle purge (IDLE_DAYS = 10) reads it. The reservation comes before any model call. It is undone only if the answer model fails before anything is shown (app.ts 805), and a fallback still counts as a question.
LIMITS.asks = 10table: demos
if (reserved === null) return json(429, { error: "You've used your ten questions.", left: 0 })No question left: 429 Query time
WhatWhen no row came back, the ask answers 429 with the error and left: 0 in JSON.
WhyThe page checks for 429 Too Many Requests and, when it sees one, replaces the form with the offer instead of showing an error line. When a row came back, the ask continues. app.ts 566 passes LIMITS.asks − reserved.asks_used to answering() as left, the count after this question. The done and fallback events carry that count, and the error event, which gives the question back, carries left + 1.
status 429left: 0