app/server.mjs:20 createServer [current]
Creates the HTTP server for the poll app. Every request it receives goes to the request handler, which uses the given data file for storage.
Source
function createServer({ dataFile }) {
const context = { dataFile, queue: Promise.resolve() };
return createHttpServer(function handleRequest(req, res) {
serveRequest(context, req, res);
});
}
app/server.mjs:22 handleRequest [current]
Hands each incoming request to serveRequest. The handler does not wait for it, because serveRequest sends the response itself.
Source
function handleRequest(req, res) {
serveRequest(context, req, res);
}
app/server.mjs:27 closeServer [current]
Stops accepting new connections, closes open ones, and exits the process with code 0 once the server has closed.
Source
function closeServer(server) {
server.closeAllConnections();
server.close(function exitAfterClose() {
process.exit(0);
});
}
app/server.mjs:29 exitAfterClose [current]
Exits the process with code 0 once the server has finished closing.
Source
function exitAfterClose() {
process.exit(0);
}
app/server.mjs:34 serveRequest [current]
Routes one request and turns any error into a response. Known errors send their own status code, and anything else becomes a 500 that the server logs.
Source
async function serveRequest(context, req, res) {
try {
await routeRequest(context, req, res);
} catch (error) {
if (error.status) {
sendJson(res, error.status, { error: error.code });
return;
}
console.error(error);
if (res.headersSent) {
res.end();
} else {
sendJson(res, 500, { error: "server_error" });
}
}
}
app/server.mjs:51 routeRequest [current]
Matches the request method and path to the right handler: the page, the poll list, creating a poll, or voting. The poll list and the vote route receive the browser voter id from its cookie. Unknown routes get a 404.
Source
async function routeRequest(context, req, res) {
const url = new URL(req.url, "http://localhost");
const voterId = ensureVoter(req, res);
if (req.method === "GET" && STATIC_FILES.has(url.pathname)) {
return sendStatic(res, STATIC_FILES.get(url.pathname));
}
if (url.pathname === "/api/polls" && req.method === "GET") {
return sendPolls(context, res, voterId);
}
if (url.pathname === "/api/polls" && req.method === "POST") {
return addPollRoute(context, req, res);
}
const vote = VOTE_ROUTE.exec(url.pathname);
if (vote && req.method === "POST") {
return votePollRoute(context, req, res, vote[1], voterId);
}
return sendJson(res, 404, { error: "not_found" });
}
app/server.mjs:70 ensureVoter [current]
Returns the voter id from the browser cookie. A browser without a valid cookie gets a new id, and the response sets the cookie.
Source
function ensureVoter(req, res) {
const existing = readCookie(req.headers.cookie, VOTER_COOKIE);
if (existing && VOTER_ID.test(existing)) return existing;
const voterId = randomUUID();
res.setHeader("Set-Cookie", `${VOTER_COOKIE}=${voterId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000`);
return voterId;
}
app/server.mjs:78 readCookie [current]
Finds one named value in a Cookie header and returns it, or null when the cookie is missing.
Source
function readCookie(header, name) {
if (!header) return null;
for (const part of header.split(";")) {
const [key, ...value] = part.trim().split("=");
if (key === name) return value.join("=");
}
return null;
}
app/server.mjs:87 sendStatic [current]
Sends one file from the public folder with its content type and a no-store cache header.
Source
async function sendStatic(res, entry) {
const body = await readFile(join(PUBLIC_DIR, entry.file));
res.writeHead(200, { "content-type": entry.type, "cache-control": "no-store" });
res.end(body);
}
app/server.mjs:93 sendPolls [current]
Reads the poll list from the data file and sends it to the browser in the public shape. Only the browser that asks sees its own choice, marked as yourVote.
Source
async function sendPolls(context, res, voterId) {
const polls = await loadPolls(context.dataFile);
sendJson(res, 200, { polls: listPolls(polls, voterId) });
}
app/server.mjs:98 addPollRoute [current]
Reads the new poll from the request body and saves it. It answers 201 with the poll, or 400 with the validation message when the input is not usable.
Source
async function addPollRoute(context, req, res) {
const body = await readJsonBody(req);
try {
const poll = await runExclusive(context, addPollTask, body);
sendJson(res, 201, { poll: publicPoll(poll) });
} catch (error) {
if (error.name !== "ValidationError") throw error;
sendJson(res, 400, { error: error.message });
}
}
app/server.mjs:119 readJsonBody [current]
Reads the request body, enforces a 10 KB size limit, and parses it as JSON. An empty body counts as an empty object. A body that is too large or not valid JSON becomes an error with a status code.
Source
async function readJsonBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > BODY_LIMIT) throw Object.assign(new Error("body_too_large"), { status: 413, code: "body_too_large" });
chunks.push(chunk);
}
const text = Buffer.concat(chunks).toString("utf8");
if (text.length === 0) return {};
try {
return JSON.parse(text);
} catch {
throw Object.assign(new Error("bad_json"), { status: 400, code: "bad_json" });
}
}
app/server.mjs:136 runExclusive [current]
Runs one data task after the task before it finishes, so two writes never overlap. It returns the result of the task, or its error.
Source
function runExclusive(context, task, input) {
const previous = context.queue;
let release;
context.queue = new Promise(function holdQueue(resolve) {
release = resolve;
});
return previous.then(function runTask() {
return task(context.dataFile, input);
}).finally(function releaseQueue() {
release();
});
}
app/server.mjs:139 holdQueue [current]
Stores the release function for the current task, so the next queued task waits until this one finishes.
Source
function holdQueue(resolve) {
release = resolve;
}
app/server.mjs:142 runTask [current]
Runs the queued data task once the task before it has finished.
Source
function runTask() {
return task(context.dataFile, input);
}
app/server.mjs:144 releaseQueue [current]
Releases the queue after the task finishes, whether it succeeded or failed, so the next queued task can start.
Source
function releaseQueue() {
release();
}
app/server.mjs:149 addPollTask [current]
Loads the poll list, adds the new poll, saves the list, and returns the new poll. It runs inside the write queue.
Source
async function addPollTask(dataFile, input) {
const polls = await loadPolls(dataFile);
const poll = createPoll(polls, input);
await savePolls(dataFile, polls);
return poll;
}
app/server.mjs:163 sendJson [current]
Sends a JSON response with the given status code and a correct content length.
Source
function sendJson(res, status, payload) {
const body = JSON.stringify(payload);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"content-length": Buffer.byteLength(body)
});
res.end(body);
}
app/server.mjs:176 startFromEnvironment [current]
Reads PORT and DATA_FILE from the environment, starts the server, and stops it cleanly on SIGTERM or SIGINT.
Source
function startFromEnvironment() {
const port = Number(process.env.PORT || 3000);
const dataFile = process.env.DATA_FILE || "data/polls.json";
const server = createServer({ dataFile });
function stopOnSignal() {
closeServer(server);
}
process.on("SIGTERM", stopOnSignal);
process.on("SIGINT", stopOnSignal);
server.listen(port, function announceListening() {
console.log(`listening on http://localhost:${server.address().port}`);
});
}
app/server.mjs:180 stopOnSignal [current]
Closes the server when the process gets SIGTERM or SIGINT, so the process exits cleanly with code 0.
Source
function stopOnSignal() {
closeServer(server);
}
app/server.mjs:185 announceListening [current]
Prints the address the server listens on once the port is open.
Source
function announceListening() {
console.log(`listening on http://localhost:${server.address().port}`);
}
app/store.mjs:10 loadPolls [current]
Reads the poll list from the JSON data file. A missing file counts as an empty list, and a file that does not hold a list is an error. Each poll is brought up to the current ballot format on the way in.
Source
async function loadPolls(file) {
let text;
try {
text = await readFile(file, "utf8");
} catch (error) {
if (error.code === "ENOENT") return [];
throw error;
}
const polls = JSON.parse(text);
if (!Array.isArray(polls)) throw new Error(`${file} does not hold a list of polls`);
return polls.map(upgradeBallots);
}
app/store.mjs:23 savePolls [current]
Writes the poll list to the data file. It writes a temporary file first and then renames it, so a crash cannot leave a half-written file.
Source
async function savePolls(file, polls) {
await mkdir(dirname(file), { recursive: true });
const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
await writeFile(temp, `${JSON.stringify(polls, null, 2)}\n`);
await rename(temp, file);
}
app/store.mjs:30 createPoll [current]
Checks the question and options, adds a new poll with zero votes and an empty ballot map to the list, and returns it. It throws a validation error when the input is not usable.
Source
function createPoll(polls, input) {
const poll = {
id: randomUUID(),
question: cleanText(input?.question, "question", QUESTION_MAX),
options: cleanOptions(input?.options).map(startTally),
ballots: {},
createdAt: new Date().toISOString()
};
polls.push(poll);
return poll;
}
app/store.mjs:61 listPolls [current]
Returns every poll in a form safe to send to the browser, without voter ids, with the newest poll first. Each poll says which option the given voter chose, or null when that voter has not chosen one or no voter is given.
Source
function listPolls(polls, voterId) {
return polls.toReversed().map(function viewFor(poll) {
return publicPoll(poll, voterId);
});
}
app/store.mjs:62 viewFor [current]
Shapes one poll for the voter who asked for the list. listPolls applies it to every poll in the list.
Source
function viewFor(poll) {
return publicPoll(poll, voterId);
}
app/store.mjs:67 publicPoll [current]
Copies one poll into the public shape: id, question, option tallies, total votes, the choice of the given voter, and the creation time. The choice is null when no voter is given.
Source
function publicPoll(poll, voterId) {
return {
id: poll.id,
question: poll.question,
options: poll.options.map(copyTally),
totalVotes: poll.options.reduce(addVotes, 0),
yourVote: ballotOf(poll, voterId),
createdAt: poll.createdAt
};
}
app/store.mjs:78 cleanText [current]
Trims a text value and rejects it when it is missing, empty, not text, or longer than the limit.
Source
function cleanText(value, label, max) {
if (typeof value !== "string") throw invalid(`${label} must be text`);
const text = value.trim();
if (text.length === 0) throw invalid(`${label} is required`);
if (text.length > max) throw invalid(`${label} must be ${max} characters or fewer`);
return text;
}
app/store.mjs:86 cleanOptions [current]
Checks that the options are a list of two to ten valid option labels, and returns them cleaned. Two labels that match without regard to case or outer spaces are refused.
Source
function cleanOptions(value) {
if (!Array.isArray(value)) throw invalid("options must be a list");
if (value.length < OPTIONS_MIN || value.length > OPTIONS_MAX) {
throw invalid(`options must have ${OPTIONS_MIN} to ${OPTIONS_MAX} entries`);
}
const options = value.map(cleanOption);
if (new Set(options.map(lowerLabel)).size < options.length) {
throw invalid("options must be different from each other");
}
return options;
}
app/store.mjs:98 cleanOption [current]
Cleans one option label using the option length limit.
Source
function cleanOption(value) {
return cleanText(value, "option", OPTION_MAX);
}
app/store.mjs:102 lowerLabel [current]
Makes an option label ready for the repeat check. Each run of spaces or tabs becomes one space, and letters become lowercase, so labels that read the same compare equal.
Source
function lowerLabel(label) {
return label.replace(/\s+/g, " ").toLowerCase();
}
app/store.mjs:106 startTally [current]
Turns one option label into a tally with zero votes.
Source
function startTally(label) {
return { label, votes: 0 };
}
app/store.mjs:110 copyTally [current]
Copies one option tally so that callers cannot change the stored poll.
Source
function copyTally(tally) {
return { label: tally.label, votes: tally.votes };
}
app/store.mjs:114 addVotes [current]
Adds the votes of one option to a running total. It counts all votes in a poll.
Source
function addVotes(total, tally) {
return total + tally.votes;
}
app/store.mjs:118 upgradeBallots [current]
Gives a poll saved with the old voter list a ballot map. Each old voter gets an entry with a null choice, because the old format did not record which option they picked. A poll that already has a ballot map is returned unchanged.
Source
function upgradeBallots(poll) {
if (poll.ballots) return poll;
const { voters = [], ...rest } = poll;
const ballots = {};
for (const voterId of voters) ballots[voterId] = null;
return { ...rest, ballots };
}
app/store.mjs:126 ballotOf [current]
Returns the option index that one voter chose in a poll. It returns null when the voter has not voted, and also for an old voter whose choice was never recorded.
Source
function ballotOf(poll, voterId) {
return Object.hasOwn(poll.ballots, voterId) ? poll.ballots[voterId] : null;
}