Poll
Poll is a small web app for live polls. You write a question and its answers, and the app saves them in a SQLite database. Each visitor clicks an answer to vote. Every open page of the poll then shows the new results at once, without a reload.
The live results use server-sent events. An event stream is a response that stays open, so the
server can send new data whenever it has some. The browser reads it with EventSource, which every
browser has. Novis serves the pages, the votes and the event streams from one process. You need no
separate push server, no message queue and no JavaScript library.
The app shows how these parts work together:
- An ordinary request saves the vote and tells every open page with
Core\Topic::publish. Core\Sse::upgradeturns a request into an event stream that stays open.- Each stream joins the topic of its poll and sends every update to its browser.
- The browser script uses
EventSourceand changes only the numbers on the page. - Voting also works without JavaScript, because each answer is a normal form button.
The code
Section titled “The code”Each tab shows one file of the app. These are the same files that you download below.
- nvs.toml
- public/index.nvs
- public/poll.js
- public/style.css
- src/Answer.nvs
- src/App.nvs
- src/AppTest.nvs
- src/Draft.nvs
- src/DraftTest.nvs
- src/Gate.nvs
- src/LiveTest.nvs
- src/Pages.nvs
- src/Question.nvs
- src/Results.nvs
- src/Store.nvs
- src/StoreTest.nvs
- src/Voter.nvs
- deploy/Caddyfile
- deploy/nginx.conf
- deploy/production.toml
- README.md
# The server listens on port 8145. The other apps in this repository use other ports,# so all of them can run at the same time.[server]listen = ["127.0.0.1:8145"]
# The browser may load scripts, styles and images only from this server, and open# connections only to this server. The pages have no inline script, so this strict policy works.# Novis adds `frame-ancestors 'none'` by itself, so no other website can show the pages in a frame.[http.headers]content_security_policy = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'"
# The polls and the votes are kept in the SQLite file `poll.sqlite`, next to this file.# Novis creates the file when the first request opens the database.[db.poll]driver = "sqlite"path = "poll.sqlite"
# The tests use this database. It is kept in memory and deleted when the tests end.[db.scratch]driver = "sqlite"path = ":memory:"
# The program may open these two databases and no other.[capabilities.db]connect = ["poll", "scratch"]<?nvs// This is the entry file. `nvs serve public/index.nvs` runs it once for each request.// The `autoload` line reads each class `Poll\...` from the folder `src`.autoload 'Poll' from '../src';
// `dispatch` finds the route for the request and calls its method.// `Poll\Gate` decides if the method may run, and it shows the error pages.Core\Router::dispatch(new Poll\Gate());// Updates the results of a poll page while it is open. It uses the browser's own// EventSource, so the page needs no library.const form = document.getElementById('vote')const total = document.getElementById('total')const status = document.getElementById('status')
// EventSource opens the stream and connects again by itself when the connection breaks.const source = new EventSource(form.dataset.events)
// The server sends a `results` event when the page connects, and again after each vote.// The data is JSON, such as {"total": 3, "answers": [{"id": 1, "votes": 2}, {"id": 2, "votes": 1}]}.source.addEventListener('results', (event) => { const results = JSON.parse(event.data) total.textContent = String(results.total) for (const answer of results.answers) { const item = form.querySelector(`[data-answer="${answer.id}"]`) if (item === null) continue const bar = item.querySelector('progress') bar.max = Math.max(results.total, 1) bar.value = answer.votes item.querySelector('.votes').textContent = String(answer.votes) }})
source.addEventListener('open', () => { status.textContent = 'The results update live.'})
source.addEventListener('error', () => { status.textContent = 'Connecting again...'})
// A click on an answer sends the vote with fetch, so the page stays open.// The new numbers then arrive as a `results` event, the same way they arrive for every other visitor.form.addEventListener('submit', async (event) => { event.preventDefault() const chosen = event.submitter const body = new URLSearchParams({ answer: chosen.value }) // After a vote, the server sends a redirect to the poll page. With `manual`, fetch does not load that page. // The response also sets the cookie `voter` the first time, and the browser keeps it. await fetch(form.action, { method: 'POST', body, redirect: 'manual' }) // The class `chosen` moves to the answer this browser voted for. for (const button of form.querySelectorAll('button.chosen')) button.classList.remove('chosen') chosen.classList.add('chosen')})/* The styles of every page of the poll. */body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem;}.answers { list-style: none; padding: 0;}.answers li { display: grid; grid-template-columns: 12rem 1fr 3rem; gap: 0.5rem; align-items: center; margin: 0.5rem 0;}.answers button { text-align: left; padding: 0.4rem 0.6rem;}/* The answer that this browser voted for. */.answers button.chosen { font-weight: bold; outline: 2px solid #1a73e8;}progress { width: 100%;}textarea,input { width: 100%; box-sizing: border-box;}.errors { color: #b00020;}<?nvsnamespace Poll;
// One answer of a poll and the number of votes it has.final class Answer{ public uint $id; public tainted string $label; public uint $votes;
public function constructor(uint $id, tainted string $label, uint $votes) { $this->id = $id; $this->label = $label; $this->votes = $votes; }}<?nvsnamespace Poll;
use Core\Access;use Core\Audience;use Core\Db;use Core\Http\Method;use Core\Request;use Core\Response;use Core\Route;use Core\Router;use Core\Sse;use Core\Topic;use ParseError;
// The routes of the app. Each method with a `Route` handles one kind of request.final class App{ // Shows every poll and the form for a new one. #[Route(path: '/', method: Method::Get)] #[Access(allow: Audience::Public)] public static function home(): void { Response::sendHtml(Pages::home(App::store()->all(), new Draft('', ''), [])); }
// Saves the poll from the form and goes to its page. // If the form is not valid, it shows the form again with the problems. #[Route(path: '/polls', method: Method::Post)] #[Access(allow: Audience::Public)] public static function create(): void { var $store = App::store(); Draft $draft = new Draft('', ''); array<string> $problems = []; try { $draft = Request::formFieldsAs<Draft>(); $problems = $draft->problems(); } catch (ParseError $error) { $problems = ['Please fill in the form.']; } if (Core\Arr::count($problems) > 0) { Response::setStatus(422); Response::sendHtml(Pages::home($store->all(), $draft, $problems)); return; } uint $id = $store->add($draft); Response::redirect(Router::url(App::show, ['id' => $id])); }
// Shows one poll: a button for each answer and the results. #[Route(path: '/polls/{id}', method: Method::Get)] #[Access(allow: Audience::Public)] public static function show(uint $id): void { var $store = App::store(); ?Question $poll = $store->find($id); if ($poll == null) { App::notFound(); return; } // A browser that already voted sees its own choice. This page does not set a cookie. ?tainted string $voter = Voter::current(); ?uint $chosen = $voter == null ? null : $store->choiceOf($id, $voter); Response::sendHtml(Pages::poll($poll, $chosen)); }
// Saves the vote of this browser, tells every open page of this poll, and goes back to the poll. // A second vote from the same browser changes its vote and does not add one. #[Route(path: '/polls/{id}/vote', method: Method::Post)] #[Access(allow: Audience::Public)] public static function vote(uint $id): void { var $store = App::store(); // The form sends the number of the answer in the field `answer`. ?uint $answer = Request::formField('answer') as ?uint; if ($answer == null || !$store->vote($id, $answer, Voter::currentOrNew())) { App::notFound(); return; } // Every event stream of this poll subscribed to this topic, and each one receives the new results. // `$id` is a number from the route, so the topic name contains nothing the user typed. Topic::publish('poll:' . $id, $store->results($id)); Response::redirect(Router::url(App::show, ['id' => $id])); }
// Opens an event stream with the results of one poll. // The stream starts when this request ends, and runs `Results::run` until the browser leaves. #[Route(path: '/polls/{id}/events', method: Method::Get)] #[Access(allow: Audience::Public)] public static function events(uint $id): void { if (App::store()->find($id) == null) { App::notFound(); return; } // Each open stream may use at most 8 MB of memory. Sse::upgrade(Results::run, arguments: ['id' => $id], limits: { memory: '8M' }); }
// Sends the script of the poll page. A server in production mode sends no file by itself, so this route sends it. #[Route(path: '/poll.js', method: Method::Get)] #[Access(allow: Audience::Public)] public static function script(): void { // The path starts at the folder of this file. A request may read the files in `public`. Response::sendFile('../public/poll.js'); }
// Sends the style sheet of every page. #[Route(path: '/style.css', method: Method::Get)] #[Access(allow: Audience::Public)] public static function style(): void { Response::sendFile('../public/style.css'); }
// Opens the database `poll` from `nvs.toml` and creates the tables when they are missing. public static function store(): Store { var $store = new Store(Db::connect('poll')); $store->setUp(); return $store; }
private static function notFound(): void { Response::setStatus(404); Response::sendHtml(Pages::notFound()); }}<?nvsnamespace Poll;
use Core\Config;use Core\Db;use Core\Http\Method;use Core\Str;use Core\Test;
// Tests that send requests to the app. `Test::request` runs the app without a server.final class AppTest{ #[Test] public function theHomePageShowsTheForm(): void { var $response = Test::request(Method::Get, '/'); Test::assertEquals($response->status(), 200); Test::assertTrue(Str::contains($response->body(), "<form method=\"post\" action=\"/polls\">")); }
#[Test] public function aPollWithOneAnswerShowsTheProblem(): void { array<string> $headers = ['content-type' => 'application/x-www-form-urlencoded']; var $response = Test::request(Method::Post, '/polls', { headers: $headers, body: 'question=Lunch%3F&answers=Pizza' }); Test::assertEquals($response->status(), 422); Test::assertTrue(Str::contains($response->body(), 'Please enter at least two answers')); }
#[Test] public function aMissingPollIsNotFound(): void { Test::assertEquals(Test::request(Method::Get, '/polls/999999')->status(), 404); // A stream for a poll that does not exist is not opened. Test::assertEquals(Test::request(Method::Get, '/polls/999999/events')->status(), 404); }
#[Test] public function thePollPageShowsAButtonForEachAnswer(): void { uint $id = AppTest::addPoll(); var $response = Test::request(Method::Get, '/polls/' . $id); AppTest::removePoll($id); Test::assertEquals($response->status(), 200); Test::assertEquals(Str::countOf($response->body(), '<button name="answer"'), 2); Test::assertTrue(Str::contains($response->body(), "data-events=\"/polls/{$id}/events\"")); }
#[Test] public function aVoteGoesBackToThePollAndGivesTheBrowserAnId(): void { uint $id = AppTest::addPoll(); uint $first = AppTest::answerIds(App::store(), $id)[0]; var $response = Test::request(Method::Post, "/polls/{$id}/vote", { headers: AppTest::form(''), body: "answer={$first}" }); uint $total = App::store()->find($id)?->total() ?? 0; AppTest::removePoll($id); Test::assertEquals($response->status(), 303); Test::assertEquals($response->header('location'), "/polls/{$id}"); Test::assertEquals($total, 1); // The browser had no cookie `voter`, so the response gives it a new id of 32 characters. Test::assertEquals(Str::length($response->cookies()['voter'] ?? ''), 32); }
#[Test] public function aSecondVoteFromTheSameBrowserChangesItsVote(): void { uint $id = AppTest::addPoll(); array<uint> $answers = AppTest::answerIds(App::store(), $id); string $voter = '0123456789abcdef0123456789abcdef'; Test::request(Method::Post, "/polls/{$id}/vote", { headers: AppTest::form($voter), body: "answer={$answers[0]}" }); var $second = Test::request(Method::Post, "/polls/{$id}/vote", { headers: AppTest::form($voter), body: "answer={$answers[1]}" }); var $page = Test::request(Method::Get, "/polls/{$id}", { headers: ['cookie' => 'voter=' . $voter] }); var $results = App::store()->results($id); AppTest::removePoll($id); Test::assertEquals($second->status(), 303); // The browser keeps its id, so the second response sets no new cookie. Test::assertNull($second->cookies()['voter'] ?? null); Test::assertEquals($results['total'], 1); // The page marks the answer this browser chose. Test::assertTrue(Str::contains($page->body(), "value=\"{$answers[1]}\" class=\"chosen\"")); }
#[Test] public function thePagesMayLoadFilesOnlyFromThisServer(): void { // The server adds this header to every response. `Test::request` returns only the headers // that the program sets, so the test reads the setting from `nvs.toml`. string $policy = Config::get('http.headers.content_security_policy') ?? ''; Test::assertTrue(Str::contains($policy, "default-src 'none'")); Test::assertTrue(Str::contains($policy, "connect-src 'self'")); Test::assertSame(Str::contains($policy, 'unsafe-inline'), false); }
#[Test] public function theScriptAndTheStylesAreSent(): void { var $script = Test::request(Method::Get, '/poll.js'); Test::assertEquals($script->status(), 200); Test::assertSame($script->header('content-type'), 'text/javascript; charset=utf-8'); Test::assertTrue(Str::contains($script->body(), 'new EventSource(')); Test::assertSame(Test::request(Method::Get, '/style.css')->header('content-type'), 'text/css; charset=utf-8'); }
#[Test] public function aVoteForAnAnswerThatDoesNotExistIsNotFound(): void { uint $id = AppTest::addPoll(); array<string> $headers = ['content-type' => 'application/x-www-form-urlencoded']; var $response = Test::request(Method::Post, "/polls/{$id}/vote", { headers: $headers, body: 'answer=abc' }); AppTest::removePoll($id); Test::assertEquals($response->status(), 404); }
#[Test] public function aVoteFromAnotherSiteIsRefused(): void { uint $id = AppTest::addPoll(); uint $first = AppTest::answerIds(App::store(), $id)[0]; // The `origin` header shows that another website sent the form. array<string> $headers = [ 'content-type' => 'application/x-www-form-urlencoded', 'origin' => 'https://example.com', ]; var $response = Test::request(Method::Post, "/polls/{$id}/vote", { headers: $headers, body: "answer={$first}" }); uint $total = App::store()->find($id)?->total() ?? 0; AppTest::removePoll($id); Test::assertEquals($response->status(), 403); Test::assertEquals($total, 0); }
// Saves a poll with two answers in the database `poll` and returns its number. public static function addPoll(): uint { return App::store()->add(new Draft('Lunch?', "Pizza\nSoup")); }
// Returns the numbers of the answers of a poll, in their order. public static function answerIds(Store $store, uint $id): array<uint> { array<uint> $ids = []; ?Question $poll = $store->find($id); if ($poll != null) { foreach ($poll->answers as Answer $answer) { $ids[] = $answer->id; } } return $ids; }
// The headers of a form that a browser sends. `$voter` is the id in the cookie `voter`, or empty for no cookie. private static function form(string $voter): array<string> { array<string> $headers = ['content-type' => 'application/x-www-form-urlencoded']; if ($voter != '') { $headers['cookie'] = 'voter=' . $voter; } return $headers; }
// Deletes the poll that `addPoll` saved and its votes, so the tests leave no poll behind. public static function removePoll(uint $id): void { var $db = Db::connect('poll'); $db->execute('delete from votes where poll_id = ?', [$id]); $db->execute('delete from answers where poll_id = ?', [$id]); $db->execute('delete from polls where id = ?', [$id]); }}<?nvsnamespace Poll;
use Core\Arr;use Core\Str;
// A new poll from the form, before it is saved.// The text comes from the user, so it is `tainted`.#[Core\Json\Derive]final class Draft{ // The question, such as "Where do we eat on Friday?". public tainted string $question; // The answers, one on each line. public tainted string $answers;
public function constructor(tainted string $question, tainted string $answers) { $this->question = $question; $this->answers = $answers; }
// Returns the answers without the spaces around them. Empty lines are left out. public function choices(): array<tainted string> { array<tainted string> $choices = []; foreach (Str::lines($this->answers) as tainted string $line) { tainted string $label = Str::trim($line); if ($label != '') { $choices[] = $label; } } return $choices; }
// Returns one message for each problem. An empty array means the draft is valid. public function problems(): array<string> { array<string> $problems = []; if (Str::trim($this->question) == '') { $problems[] = 'Please enter a question.'; } elseif (Str::length($this->question) > 200) { $problems[] = 'The question can have at most 200 characters.'; } var $choices = $this->choices(); if (Arr::count($choices) < 2) { $problems[] = 'Please enter at least two answers, one on each line.'; } elseif (Arr::count($choices) > 6) { $problems[] = 'A poll can have at most six answers.'; } foreach ($choices as tainted string $choice) { if (Str::length($choice) > 80) { $problems[] = 'An answer can have at most 80 characters.'; break; } } return $problems; }}<?nvsnamespace Poll;
use Core\Str;use Core\Test;
// Tests for the checks on a new poll.final class DraftTest{ #[Test] public function aQuestionAndTwoAnswersAreValid(): void { Test::assertCount((new Draft('Lunch?', "Pizza\nSoup"))->problems(), 0); }
#[Test] public function emptyLinesAndSpacesAreLeftOut(): void { var $draft = new Draft('Lunch?', " Pizza \n\n \nSoup\n"); Test::assertEqualsDeep($draft->choices() as array<string>, ['Pizza', 'Soup']); }
#[Test] public function aQuestionWithOnlySpacesIsNotValid(): void { Test::assertEqualsDeep((new Draft(' ', "Pizza\nSoup"))->problems(), ['Please enter a question.']); }
#[Test] public function oneAnswerIsNotEnough(): void { var $problems = (new Draft('Lunch?', 'Pizza'))->problems(); Test::assertEqualsDeep($problems, ['Please enter at least two answers, one on each line.']); }
#[Test] public function sevenAnswersAreTooMany(): void { var $problems = (new Draft('Day?', "Mon\nTue\nWed\nThu\nFri\nSat\nSun"))->problems(); Test::assertEqualsDeep($problems, ['A poll can have at most six answers.']); }
#[Test] public function aLongAnswerIsNotValid(): void { var $problems = (new Draft('Lunch?', "Pizza\n" . Str::repeat('a', 81)))->problems(); Test::assertEqualsDeep($problems, ['An answer can have at most 80 characters.']); }}<?nvsnamespace Poll;
use Core\Audience;use Core\Response;use Core\Router\Refusal;use Throwable;
// The gate of the app. `Core\Router::dispatch` calls it for every request.// It decides if a route method may run, and it shows the error pages.final class Gate implements Core\Router\Gate{ // Runs before each route method. The method runs only when this returns `true`. // Every route of this app is public, so this checks for `Audience::Public`. public function allows(Core\Router\Match $route): bool { return $route->accessAs<Audience>() == Audience::Public; }
// Shows a page when no route method can handle the request. // `dispatch` has already set the status code, such as 404 or 405. public function refused(Refusal $reason, ?Core\Router\Match $route): void { if ($reason == Refusal::NotFound) { Response::sendHtml(Pages::notFound()); return; } string $text = match ($reason) { Refusal::MethodNotAllowed => 'This address does not accept this kind of request.', Refusal::Csrf => 'The form was not sent from this website, so nothing was saved.', Refusal::BodyTooLarge => 'The form is too large.', default => 'This request is not allowed.', }; Response::sendHtml(Pages::problem('Not possible', $text)); }
// Shows a page when a route method throws an error. The status code is 500. public function failed(?Core\Router\Match $route, ?Throwable $error): void { Response::sendHtml(Pages::failed()); }}<?nvsnamespace Poll;
use Core\Http\Client;use Core\Http\Event;use Core\Http\Method;use Core\Test;
// A test of the live results over a real network connection.// `server: true` starts a server for the test. The test reads the event stream like a browser does.final class LiveTest{ #[Test(server: true)] public function aVoteReachesAnOpenStream(): void { string $base = Test::serverUrl() ?? ''; uint $id = AppTest::addPoll(); uint $soup = AppTest::answerIds(App::store(), $id)[1]; array<tainted string> $seen = []; try { // `idle: 5s` stops the test if no event arrives for 5 seconds. var $stream = Client::openStream(Method::Get, "{$base}/polls/{$id}/events", { headers: ['accept' => 'text/event-stream'], idle: 5s }); foreach ($stream->events() as Event $event) { $seen[] = $event->data(); if (Core\Arr::count($seen) == 1) { // The first event is the results when the stream opens. Now the test votes. Client::post("{$base}/polls/{$id}/vote", { form: ['answer' => $soup as string] }); } else { break; } } } finally { AppTest::removePoll($id); } uint $pizza = $soup - 1; Test::assertEqualsDeep($seen, [ "{\"total\":0,\"answers\":[{\"id\":{$pizza},\"votes\":0},{\"id\":{$soup},\"votes\":0}]}", "{\"total\":1,\"answers\":[{\"id\":{$pizza},\"votes\":0},{\"id\":{$soup},\"votes\":1}]}", ]); }}<?nvsnamespace Poll;
use Core\Arr;use Core\Html\Markup;use Core\Router;
// Builds the HTML pages. Each `{$name}` in an `html` literal is escaped, so a `<` in a question prints as `<`.final class Pages{ // The home page: every poll, then a form for a new poll. public static function home(array<Question> $polls, Draft $draft, array<string> $problems): Markup { var $list = html``; foreach ($polls as Question $poll) { string $link = Router::url(App::show, ['id' => $poll->id]); tainted string $text = $poll->text; $list = $list + html`<li><a href="{$link}">{$text}</a></li>`; } tainted string $question = $draft->question; tainted string $answers = $draft->answers; var $form = html`<form method="post" action="/polls"><h2>New poll</h2><?= Pages::errorList($problems) ?><p><label>Question <input name="question" value="{$question}"></label></p><p><label>Answers, one on each line <textarea name="answers" rows="6">{$answers}</textarea></label></p><p><button>Create the poll</button></p></form>`; return Pages::layout('Polls', html`<h1>Polls</h1><ul>{$list}</ul>{$form}`); }
// The page of one poll. Each answer is a button that sends the form, so voting works without JavaScript. // `$chosen` is the answer this browser voted for, or `null`. Its button has the class `chosen`. public static function poll(Question $poll, ?uint $chosen): Markup { uint $total = $poll->total(); // A progress bar needs a maximum above 0, also before the first vote. uint $max = $total > 0 ? $total : 1; var $items = html``; foreach ($poll->answers as Answer $answer) { tainted string $label = $answer->label; uint $votes = $answer->votes; uint $answerId = $answer->id; var $button = $answerId == $chosen ? html`<button name="answer" value="{$answerId}" class="chosen">{$label}</button>` : html`<button name="answer" value="{$answerId}">{$label}</button>`; $items = $items + html`<li data-answer="{$answerId}">{$button}<progress max="{$max}" value="{$votes}"></progress> <span class="votes">{$votes}</span></li>`; } string $vote = Router::url(App::vote, ['id' => $poll->id]); // `poll.js` reads `data-events` and updates the numbers while the page is open. string $events = Router::url(App::events, ['id' => $poll->id]); tainted string $question = $poll->text; return Pages::layout($question, html`<h1>{$question}</h1><form method="post" action="{$vote}" id="vote" data-events="{$events}"><ul class="answers">{$items}</ul></form><p><span id="total">{$total}</span> votes. Click another answer to change your vote. <span id="status"></span></p><p><a href="/">All polls</a></p><script src="/poll.js" defer></script>`); }
// The page for a path that has no route, or for a poll that does not exist. public static function notFound(): Markup { return Pages::problem('Not found', 'There is no page at this address.'); }
// The page for an error in the app. public static function failed(): Markup { return Pages::problem('Something went wrong', 'Please try again later.'); }
// A page with a title, one sentence and a link to the home page. public static function problem(string $title, string $text): Markup { return Pages::layout($title, html`<h1>{$title}</h1><p>{$text}</p><p><a href="/">All polls</a></p>`); }
// Returns a list of the problems, or nothing when there are none. private static function errorList(array<string> $problems): Markup { if (Arr::count($problems) == 0) { return html``; } var $items = html``; foreach ($problems as string $problem) { $items = $items + html`<li>{$problem}</li>`; } return html`<ul class="errors">{$items}</ul>`; }
private static function layout(tainted string $title, Markup $content): Markup { return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{$title}</title><link rel="stylesheet" href="/style.css"></head><body>{$content}</body></html>`; }}<?nvsnamespace Poll;
// A saved poll: its number, its question and its answers.// A user wrote the question, so it is `tainted`, also after it is saved.final class Question{ public uint $id; public tainted string $text; public array<Answer> $answers;
public function constructor(uint $id, tainted string $text, array<Answer> $answers) { $this->id = $id; $this->text = $text; $this->answers = $answers; }
// Returns the number of votes for all answers together. public function total(): uint { uint $total = 0; foreach ($this->answers as Answer $answer) { $total = $total + $answer->votes; } return $total; }}<?nvsnamespace Poll;
use Core\Sse;use Core\Topic;
// The event stream of one poll. `App::events` starts it, and it runs until the browser leaves.final class Results{ // `arguments:` in `App::events` gives `$id`, the number of the poll. public static function run(uint $id): void { Sse $sse = Sse::current(); // The stream joins the topic first, so a vote that arrives during the next lines is not lost. Topic::subscribe('poll:' . $id);
// The first event has the results as they are now. // A browser that connects again gets them too, so it never misses a vote. $sse->send(App::store()->results($id), event: 'results');
// `receive` waits for the next results that `App::vote` publishes. // It returns `null` when the browser closes the page. ?Core\Sse\Message $message = $sse->receive(); while ($message != null) { $sse->send($message->value(), event: 'results'); $message = $sse->receive(); } }}<?nvsnamespace Poll;
use Core\Db\Connection;use Core\Db\Row;use Core\Db\Transaction;use Core\Str;
// Reads and saves polls and votes in a database.// Each `?` in the SQL is a placeholder. The database gets the values apart from the SQL.final class Store{ private Connection $db;
public function constructor(Connection $db) { $this->db = $db; }
// Creates the tables `polls`, `answers` and `votes` if they do not exist yet. // `votes` has one row for each browser in each poll. The primary key makes sure of that. public function setUp(): void { $this->db->execute('create table if not exists polls (id integer primary key, question text not null)', []); $this->db->execute('create table if not exists answers (id integer primary key, poll_id integer not null, label text not null)', []); $this->db->execute('create table if not exists votes (poll_id integer not null, voter text not null, answer_id integer not null, primary key (poll_id, voter))', []); $this->db->execute('create index if not exists votes_by_answer on votes (answer_id)', []); }
// Returns every poll without its answers. The newest poll is first. public function all(): array<Question> { array<Question> $polls = []; foreach ($this->db->query('select id, question from polls order by id desc', []) as Row $row) { $polls[] = new Question($row->uint('id') ?? 0, $row->string('question') ?? '', []); } return $polls; }
// Returns the poll with this number and its answers. If there is none, the result is `null`. public function find(uint $id): ?Question { foreach ($this->db->query('select id, question from polls where id = ?', [$id]) as Row $row) { array<Answer> $answers = []; foreach ($this->counts($id) as Row $answer) { $answers[] = new Answer($answer->uint('id') ?? 0, $answer->string('label') ?? '', $answer->uint('votes') ?? 0); } return new Question($id, $row->string('question') ?? '', $answers); } return null; }
// Saves a valid draft and returns the number of the new poll. // The poll and its answers are saved in one transaction, so either all of them are saved or none. public function add(Draft $draft): uint { tainted string $question = Str::trim($draft->question); var $choices = $draft->choices(); return $this->db->runTransaction(fn(Transaction $tx): uint => { uint $id = $tx->execute('insert into polls (question) values (?)', [$question])->lastId() ?? 0; foreach ($choices as tainted string $label) { $tx->execute('insert into answers (poll_id, label) values (?, ?)', [$id, $label]); } return $id; }); }
// Saves the vote of one browser. A second vote from the same browser replaces its first vote. // Returns `false` when the poll has no such answer. public function vote(uint $poll, uint $answer, tainted string $voter): bool { var $found = $this->db->query('select id from answers where id = ? and poll_id = ?', [$answer, $poll]); foreach ($found as Row $row) { // `on conflict` changes the row of this browser if it already has one. $this->db->execute('insert into votes (poll_id, voter, answer_id) values (?, ?, ?) on conflict (poll_id, voter) do update set answer_id = excluded.answer_id', [$poll, $voter, $answer]); return true; } return false; }
// Returns the answer that this browser chose in a poll, or `null` when it has not voted. public function choiceOf(uint $poll, tainted string $voter): ?uint { foreach ($this->db->query('select answer_id from votes where poll_id = ? and voter = ?', [$poll, $voter]) as Row $row) { return $row->uint('answer_id'); } return null; }
// Returns the votes of a poll as numbers only, such as // `{"total": 3, "answers": [{"id": 1, "votes": 2}, {"id": 2, "votes": 1}]}`. public function results(uint $poll): array<mixed> { uint $total = 0; array<mixed> $answers = []; foreach ($this->counts($poll) as Row $row) { uint $votes = $row->uint('votes') ?? 0; $answers[] = ['id' => $row->uint('id') ?? 0, 'votes' => $votes]; $total = $total + $votes; } return ['total' => $total, 'answers' => $answers]; }
// Returns each answer of a poll with its label and its number of votes, in the order of the answers. private function counts(uint $poll): Core\Db\Rows<Row> { return $this->db->query('select a.id, a.label, count(v.voter) as votes from answers a left join votes v on v.answer_id = a.id and v.poll_id = a.poll_id where a.poll_id = ? group by a.id order by a.id', [$poll]); }}<?nvsnamespace Poll;
use Core\Db;use Core\Test;
// Tests for saving polls and counting votes. They use the database `scratch`, which is kept in memory.final class StoreTest{ #[Test] public function aSavedPollHasItsAnswersInOrder(): void { var $store = StoreTest::emptyStore(); uint $id = $store->add(new Draft(' Lunch? ', "Pizza\nSoup")); Question $poll = $store->find($id) ?? new Question(0, '', []); // `add` removes the spaces around the question. Test::assertSame($poll->text as string, 'Lunch?'); Test::assertCount($poll->answers, 2); Test::assertSame($poll->answers[1]->label as string, 'Soup'); }
#[Test] public function twoBrowsersCountTwice(): void { var $store = StoreTest::emptyStore(); uint $id = $store->add(new Draft('Lunch?', "Pizza\nSoup")); uint $soup = AppTest::answerIds($store, $id)[1]; Test::assertTrue($store->vote($id, $soup, 'browser-a')); Test::assertTrue($store->vote($id, $soup, 'browser-b')); Test::assertEqualsDeep($store->results($id), ['total' => 2, 'answers' => [['id' => $soup - 1, 'votes' => 0], ['id' => $soup, 'votes' => 2]]]); }
#[Test] public function aSecondVoteFromTheSameBrowserChangesIt(): void { var $store = StoreTest::emptyStore(); uint $id = $store->add(new Draft('Lunch?', "Pizza\nSoup")); uint $pizza = AppTest::answerIds($store, $id)[0]; uint $soup = AppTest::answerIds($store, $id)[1]; $store->vote($id, $pizza, 'browser-a'); $store->vote($id, $soup, 'browser-a'); // The total stays 1, and the vote moved from Pizza to Soup. Test::assertEqualsDeep($store->results($id), ['total' => 1, 'answers' => [['id' => $pizza, 'votes' => 0], ['id' => $soup, 'votes' => 1]]]); Test::assertEquals($store->choiceOf($id, 'browser-a'), $soup); Test::assertNull($store->choiceOf($id, 'browser-b')); }
#[Test] public function aVoteForAnAnswerOfAnotherPollIsNotCounted(): void { var $store = StoreTest::emptyStore(); uint $lunch = $store->add(new Draft('Lunch?', "Pizza\nSoup")); uint $day = $store->add(new Draft('Day?', "Monday\nFriday")); uint $pizza = AppTest::answerIds($store, $lunch)[0]; Test::assertTrue(!$store->vote($day, $pizza, 'browser-a')); Test::assertEquals($store->find($lunch)?->total(), 0); }
#[Test] public function aMissingPollIsNull(): void { Test::assertNull(StoreTest::emptyStore()->find(42)); }
// Returns a store with no polls. All tests share the `scratch` database, so this deletes the polls of the last test. private static function emptyStore(): Store { var $db = Db::connect('scratch'); var $store = new Store($db); $store->setUp(); $db->execute('delete from votes', []); $db->execute('delete from answers', []); $db->execute('delete from polls', []); return $store; }}<?nvsnamespace Poll;
use Core\Random;use Core\Regex;use Core\Request;use Core\Response;
// The id of one browser, kept in the cookie `voter`. The app counts one vote for each id in each poll.// A browser that deletes its cookies gets a new id. A login is the way to count one vote for each person.final class Voter{ // Returns the id from the cookie, or `null` when the browser has no valid id. // A valid id has 32 characters from `0` to `9` and `a` to `f`. Any other value is ignored. public static function current(): ?tainted string { ?tainted string $id = Request::cookie('voter'); if ($id == null || !Regex::matches($id, Regex::compile('^[0-9a-f]{32}$'))) { return null; } return $id; }
// Returns the id of this browser. A browser without a valid id gets a new one. // The cookie is kept for one year. Nobody can guess an id, because `Random::token` makes it. public static function currentOrNew(): tainted string { ?tainted string $id = Voter::current(); if ($id != null) { return $id; } string $new = Random::token(16); Response::addCookie('voter', $new, { maxAge: 365d }); return $new; }}# The proxy for the poll on Caddy. Copy this file to /etc/caddy/Caddyfile.# Change poll.example.com to the host name of your server.# Caddy gets a certificate from Let's Encrypt, sends HTTP to HTTPS, and speaks HTTP/2 and HTTP/3.poll.example.com { # Novis listens on this Unix socket. It is `listen` in deploy/production.toml. # For a server on TCP, write `reverse_proxy 127.0.0.1:8145` here. reverse_proxy unix//run/poll/nvs.sock { transport http { # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive 60s } }}
# Caddy sends `Host`, `X-Forwarded-For` and `X-Forwarded-Proto` to Novis.# Caddy sends each event of a stream to the browser at once, with no setting.# The proxy for the poll on nginx. Copy this file to /etc/nginx/conf.d/poll.conf.# Change poll.example.com to the host name of your server, and the paths of the certificate.
upstream poll { # Novis listens on this Unix socket. It is `listen` in deploy/production.toml. # For a server on TCP, write `server 127.0.0.1:8145;` here. server unix:/run/poll/nvs.sock;
# Keep up to 16 unused connections to Novis open for each nginx worker. keepalive 16; # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive_timeout 60s;}
# Plain HTTP only sends the browser to HTTPS.server { listen 80; listen [::]:80; server_name poll.example.com; return 301 https://$host$request_uri;}
server { listen 443 ssl; listen [::]:443 ssl; http2 on; server_name poll.example.com; server_tokens off;
ssl_certificate /etc/letsencrypt/live/poll.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/poll.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3;
# A new poll or a vote is a small form. Novis allows larger bodies, but this app needs no more. client_max_body_size 64k;
location / { proxy_pass http://poll; # These two lines keep the connections to Novis open. proxy_http_version 1.1; proxy_set_header Connection ""; # Novis compares `Origin` with this host and this scheme. Keep both lines. proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $remote_addr; }}
# Event streams need no setting. Novis sends `X-Accel-Buffering: no`, so nginx sends each event at once.# On a quiet stream, Novis writes a keep-alive line every 15 seconds with the default settings.# So nginx does not close a stream when nobody votes for a while.# The settings for a server on the internet, behind a proxy on the same machine.# Start the server with `--config nvs.toml --config deploy/production.toml`.# The server reads the two files in this order. Each setting below replaces the one from `nvs.toml`.
# Production is the default mode. This line makes the choice visible.# An error page then says only that something went wrong.[mode]default = "production"
[server]# Novis listens on a Unix socket. Only the proxy may connect to it.# On Windows, write `listen = ["127.0.0.1:8145"]` here, and change the proxy to match.listen = ["/run/poll/nvs.sock"]# The account of the server and the members of its group may connect.# Add the account of the proxy to that group.socket_mode = "0660"# Novis reads `X-Forwarded-For` and `X-Forwarded-Proto` from the proxy.# Without this line, every vote from a browser gets the status 403.trusted_proxies = ["127.0.0.1"]
# The votes are kept outside the folder of the code, so a new version of the code does not touch them.# The account of the server must be able to write to this folder.[db.poll]driver = "sqlite"path = "/var/lib/poll/poll.sqlite"
# The server opens only the database of the polls. The tests use `scratch`, and they do not run here.[capabilities.db]connect = ["poll"]
# Each request and each event stream may use at most 32 MB of memory and 5 seconds of CPU time.# A program cannot raise these limits. Each stream also has its own memory limit of 8 MB.# A request may run for at most 30 seconds. This also ends the request that opens an event stream.# The stream stays open. `[server.connection] max_lifetime` closes it after one day.[limits]memory = "32M"cpu_time = "5s"wall_time = "30s"
[limits.hard]memory = "32M"cpu_time = "5s"
# A failure that Novis reports itself goes to this file. Read it after each deploy.# The account of the server must be able to write to this folder.[log]target = "file:/var/log/poll/nvs.log"# Poll
A live poll written in Novis. Votes are saved in SQLite, and every open poll page shows the new results at once, with server-sent events.
Run these commands in this folder:
```shnvs serve public/index.nvs # open http://127.0.0.1:8145/nvs test . # runs the tests```
In a clone of the repository, `bun nv app poll` starts the app from any folder.
The folder `deploy` has the production settings and the proxy files for Caddy and nginx. On aserver, start the app with both configuration files:
```shnvs serve public/index.nvs --config nvs.toml --config deploy/production.toml```
The page [Example apps: Poll](https://novis-lang.org/guides/example-apps/poll/) explains each fileand each step of the deploy.Get it running
Section titled “Get it running”Install Novis first. Then download only the folder apps/poll of the Novis
repository. A sparse clone (a clone that checks out only the folders you name) does this:
git clone --depth 1 --filter=blob:none --sparse https://github.com/novis-lang/novis.gitcd novisgit sparse-checkout set apps/pollcd apps/pollStart the server from the folder apps/poll:
nvs serve public/index.nvsOpen http://127.0.0.1:8145/ and create a poll. Then open the poll in a second browser window and
vote in the first one. The second window shows the vote at once.
The first request creates the file poll.sqlite in the same folder. Your polls are kept there, so
they are still there after a restart.
Run the tests
Section titled “Run the tests”nvs test .nvs test . reads every .nvs file in the folder as one program and runs each #[Test] method:
Poll\AppTest ✓ theHomePageShowsTheForm 5.3 ms ✓ aPollWithOneAnswerShowsTheProblem 5.4 ms ✓ aMissingPollIsNotFound 5.4 ms ✓ thePollPageShowsAButtonForEachAnswer 119.0 ms ✓ aVoteGoesBackToThePollAndGivesTheBrowserAnId 78.2 ms ✓ aSecondVoteFromTheSameBrowserChangesItsVote 47.6 ms ✓ thePagesMayLoadFilesOnlyFromThisServer 0.1 ms ✓ theScriptAndTheStylesAreSent 0.8 ms ✓ aVoteForAnAnswerThatDoesNotExistIsNotFound 27.0 ms ✓ aVoteFromAnotherSiteIsRefused 7.7 ms Poll\DraftTest ✓ aQuestionAndTwoAnswersAreValid 0.0 ms ✓ emptyLinesAndSpacesAreLeftOut 0.1 ms ✓ aQuestionWithOnlySpacesIsNotValid 0.0 ms ✓ oneAnswerIsNotEnough 0.1 ms ✓ sevenAnswersAreTooMany 0.0 ms ✓ aLongAnswerIsNotValid 0.0 ms Poll\LiveTest ✓ aVoteReachesAnOpenStream 84.3 ms Poll\StoreTest ✓ aSavedPollHasItsAnswersInOrder 0.9 ms ✓ twoBrowsersCountTwice 1.0 ms ✓ aSecondVoteFromTheSameBrowserChangesIt 1.1 ms ✓ aVoteForAnAnswerOfAnotherPollIsNotCounted 0.9 ms ✓ aMissingPollIsNull 0.6 ms
0 failed, 22 passed, 0 skipped, 0 flaky in 126 msThe tests in AppTest and LiveTest save a poll in poll.sqlite and delete it again at the end.
LiveTest reads a real event stream. #[Test(server: true)] starts a server for the test, and
Core\Http\Client::openStream reads the events the way a browser does. The test votes, and then
checks that the new results arrive on the stream.
What each file does
Section titled “What each file does”poll/ nvs.toml the configuration: the port, the security policy, the two databases and the permission to open them public/ index.nvs the entry file: every request starts here poll.js the browser script: opens the event stream and updates the numbers style.css the styles of the pages deploy/ production.toml the settings for a server on the internet Caddyfile the proxy configuration for Caddy nginx.conf the proxy configuration for nginx src/ Answer.nvs one answer of a poll and its votes App.nvs the routes: one method for each kind of request AppTest.nvs sends requests to the app and checks the responses Draft.nvs a new poll from the form, and the checks on it DraftTest.nvs tests the checks on a new poll Gate.nvs decides which routes may run, and shows the error pages LiveTest.nvs reads a real event stream and votes Pages.nvs the HTML pages Question.nvs a saved poll with its answers Results.nvs the event stream of one poll Store.nvs reads and saves polls and votes in the database StoreTest.nvs tests saving polls and counting votes Voter.nvs the id of a browser, kept in the cookie `voter`[server] listen in nvs.toml sets the port of the server to 8145. The other example apps use
other ports, so you can run them at the same time.
src/App.nvs has one method for each route. App::vote saves the vote in the database. Then it
calls Topic::publish with the new results of the poll. A topic is a name that open streams can
join, here poll: and the number of the poll.
src/Voter.nvs gives each browser an id: 32 random characters in the cookie voter, kept for one
year. The table votes has one row for each browser in each poll. A second vote from the same
browser changes that row, so the browser changes its vote and does not add one. The poll page marks
the answer that this browser chose.
App::events checks that the poll exists. Then it calls Sse::upgrade. The request ends, and the
connection stays open as an event stream. The stream runs Results::run in its own isolate (a
separate copy of the program that shares no memory with the request).
src/Results.nvs is the event stream. It joins the topic of its poll first. Then it sends the
results as they are now. After that, receive() waits for the next update and the stream sends it
to the browser. When the browser closes the page, receive() returns null and the stream ends.
public/poll.js opens the stream with new EventSource(...). For each results event, it changes
the numbers and the bars on the page. It writes only with textContent, so no text from the server
can become HTML. A click on an answer sends the vote with fetch, so the page stays open.
App::script and App::style send poll.js and style.css. In development, nvs serve also
sends files from public by itself. A server in production mode sends no file by itself, so the
routes are needed there.
[http.headers] content_security_policy in nvs.toml sets the header Content-Security-Policy
on every response, the error pages and the files too. The browser then loads scripts, styles and
event streams from this website only. The pages have no inline script and no inline style, so this
strict policy works. A script that an attacker puts into a page does not run.
The routes
Section titled “The routes”| Method and path | What it does |
|---|---|
GET / |
Shows every poll, newest first, and the form for a new poll. |
POST /polls |
Saves the poll from the form, then goes to its page. If the form is not valid, it shows the form again with the status 422. |
GET /polls/{id} |
Shows one poll, with a button for each answer and the results. |
POST /polls/{id}/vote |
Saves the vote of this browser, sends the new results to every open page, then goes back to the poll. A browser without the cookie voter gets one. |
GET /polls/{id}/events |
Opens the event stream of the poll. A poll that does not exist gets the status 404. |
GET /poll.js |
Sends the browser script. |
GET /style.css |
Sends the styles. |
You can read the stream with curl while the server runs. -N prints each event as it arrives:
curl -N http://127.0.0.1:8145/polls/1/eventsVote in the browser, and a new results event appears in the terminal:
retry: 2238
event: resultsdata: {"total":0,"answers":[{"id":1,"votes":0},{"id":2,"votes":0}]}
event: resultsdata: {"total":1,"answers":[{"id":1,"votes":0},{"id":2,"votes":1}]}How the live updates work
Section titled “How the live updates work”These five steps send a vote to every open page:
- The browser sends
POST /polls/7/vote. This is an ordinary request. App::votesaves the vote and callsTopic::publish('poll:7', $results).- Every stream that joined
poll:7receives a copy of the results. - Each stream sends the results to its browser as a
resultsevent. poll.jsin each browser reads the event and changes the numbers.
All five steps happen in one Novis process. Topic::publish returns at once and never waits for a
slow browser.
EventSource connects again by itself when the connection breaks. The retry: line tells the
browser how many milliseconds to wait first. Novis chooses a slightly different time for each
stream. So after a restart, the browsers do not all come back at the same moment.
A stream always sends the current results first. So a browser that connects again never misses a vote, even a vote that happened while it was away. The stream joins the topic before it reads the database. A vote that arrives between the two steps is then still sent.
Each stream has a queue for the updates that it has not sent yet. A browser that reads too slowly fills its queue. Novis then closes that one stream, and the other streams are not affected. The browser connects again and gets the current results.
Deploy it
Section titled “Deploy it”The folder deploy has the files for a server on the internet. They are written for Linux with
systemd, a proxy on the same machine and the app in /srv/poll. Change these names for your server.
| File | What it does |
|---|---|
deploy/production.toml |
Changes the settings of nvs.toml for production: a Unix socket, trusted_proxies, the database and the log outside the folder of the code, and the limits. |
deploy/Caddyfile |
The proxy for Caddy. Caddy also gets the certificate. |
deploy/nginx.conf |
The proxy for nginx. |
Novis reads both configuration files when you name each with --config. It reads them in that order,
so each setting in production.toml replaces the one in nvs.toml.
-
Copy the folder of the app to
/srv/poll. Onlyrootmay change the files, so the service cannot change its own code or settings. -
Create the account of the service and its folders.
/runis empty after each boot, sotmpfiles.dcreates the folder of the socket again at every boot:Terminal window useradd --system --no-create-home pollmkdir -p /var/lib/poll /var/log/pollchown poll:poll /var/lib/poll /var/log/pollecho 'd /run/poll 0750 poll poll -' > /etc/tmpfiles.d/poll.confsystemd-tmpfiles --create -
Check the settings. The command reports each problem, and it starts nothing:
Terminal window nvs config check --config /srv/poll/nvs.toml --config /srv/poll/deploy/production.toml -
Install the service and start it. Run as a service explains each option:
Terminal window nvs service install poll --account poll -- serve /srv/poll/public/index.nvs --config /srv/poll/nvs.toml --config /srv/poll/deploy/production.tomlnvs service start poll -
Add the account of the proxy to the group
poll, so the proxy may open the socket. Then copy the configuration of your proxy and restart it:Terminal window usermod -aG poll caddy # for Caddycp /srv/poll/deploy/Caddyfile /etc/caddy/Caddyfileusermod -aG poll www-data # for nginx on Debian and Ubuntucp /srv/poll/deploy/nginx.conf /etc/nginx/conf.d/poll.conf
Event streams need no special setting in the proxy. Novis sends the header X-Accel-Buffering: no
with each stream, so nginx sends each event at once. On a quiet stream, Novis writes a small
keep-alive line every 15 seconds. So the proxy does not close a stream when nobody votes for a while.
trusted_proxies in production.toml is important. The browser sends the header Origin: https://poll.example.com with each vote. Novis compares it with the scheme and the host of the
request. Without trusted_proxies, Novis does not read X-Forwarded-Proto, so it sees http. The
two do not match, and every vote gets the status 403.
production.toml sets wall_time to 30 seconds. This limit ends a request that runs too long. It
does not close an event stream, which stays open after its request ends. [server.connection] max_lifetime closes a stream after one day, and the browser then connects again.
With HTTP/1.1, a browser opens at most six connections to one host. Each open poll page uses one of them. Through HTTP/2, all pages share one connection, so a visitor can open many polls at once. Both proxy files turn on HTTP/2.
Behind a reverse proxy explains each proxy setting, and the security checklist lists what to check before the first request.
Limits and security
Section titled “Limits and security”- Each stream has its own memory limit.
Sse::upgradegetslimits: { memory: '8M' }. A stream that needs more is stopped, and the other streams keep running. - A topic name never contains user input.
$idis a number from the route, so'poll:' . $idcan only be the topic of a poll. A topic name that istaintedis not allowed. - A published value has only numbers. The results are the number of each answer and its votes. No text that a user wrote is sent to the streams.
- A form from another website is not accepted. Novis checks the
Originheader of eachPOST. A vote sent from another website gets the status403, andGate::refusedshows the page. - The pages run only their own scripts. The
Content-Security-Policyinnvs.tomlallows scripts, styles and event streams from this website only. - Each browser has one vote in each poll. A browser that deletes its cookies gets a new id and a new vote. A second browser does too. So this is good for a team poll, and not for an election. For a real vote, add a login, and use the id of the user in place of the cookie.
- Topics work inside one process. All streams and all votes must reach the same
nvs serve. If you run your app on several machines, send each update to the other machines in your own code. A message queue such as Redis or NATS can do this.
Start your own app from it
Section titled “Start your own app from it”- Copy the folder
apps/polland give it the name of your app. - Choose a namespace for your app, for example
Board. Changenamespace Poll;in each file undersrc/, and theautoloadline andPoll\Gateinpublic/index.nvs. - In
nvs.tomlanddeploy/production.toml, rename the databasepolland its file. Change the name in[capabilities.db]and in the call toCore\Db::connectinsrc/App.nvs. - In the files under
deploy, changepollin the paths andpoll.example.comto your names. - Use the same pattern for each live part of your app. A request saves the change and publishes it. A stream sends the current state first, and then each update.
- Run
nvs test .after each change.
Read more
Section titled “Read more”- Live updates explains when to use an event stream and when a WebSocket.
Core\Sse::upgradeexplains the event stream and its options.Core\Topic::publishexplains what happens to each subscriber.- Chat is a chat app with WebSockets. A WebSocket can also send messages from the browser to the server.
