Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
290 lines (253 loc) · 12.8 KB
/
Copy pathindex.js
File metadata and controls
290 lines (253 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// A notes app backed by managed Postgres.
//
// The point of this template is the wiring: how an app on velixir finds its database, keeps
// its schema in step, and stays healthy. The notes themselves are the least interesting part.
//
// Deploy it from the velixir gallery and a managed Postgres is created and bound for you, so
// DATABASE_URL is in the environment on the first boot. Nothing here hardcodes a host, so the
// same code runs locally against a container and in production against the managed instance.
const express = require('express');
const { Pool } = require('pg');
const { pgConfig } = require('./db');
const app = express();
const port = process.env.PORT || 8080;
const connectionString = process.env.DATABASE_URL;
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// The process runs as PID 1 in its container (the Procfile starts node directly, so a redeploy's
// SIGTERM reaches it rather than stopping at npm). PID 1 gets no default signal handling, though:
// without this it would ignore SIGTERM and only go when the platform's grace period ran out.
// Finish what is in flight, then go.
function stopOnSignal(server, cleanup = async () => {}) {
for (const signal of ['SIGTERM', 'SIGINT']) {
process.once(signal, () => {
server.close(() => cleanup().finally(() => process.exit(0)));
server.closeIdleConnections(); // idle keep-alive sockets would otherwise hold close() open
setTimeout(() => process.exit(0), 10000).unref();
});
}
}
// Everything that reaches the browser goes through this. Notes are user input, so they are
// escaped on the way out rather than trusted.
const escapeHtml = (s) =>
String(s).replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
})[c]);
// ─── Setup mode ─────────────────────────────────────────────────────────────
// No database bound yet. Rather than exiting (a crash loop reads as "the platform is
// broken"), serve a page that says exactly what is missing and how to fix it, and keep the
// health check green so the page stays reachable.
if (!connectionString) {
console.log(
'DATABASE_URL is not set, so this app is serving its setup page.\n' +
'On velixir: create a managed Postgres, bind it to this app as DATABASE_URL, then redeploy.\n' +
'Locally: DATABASE_URL=postgres://user:pass@localhost:5432/notes npm start'
);
app.get('/healthz', (_req, res) => res.type('text/plain').send('ok (setup mode: no database bound)'));
app.use('/api', (_req, res) =>
res.status(503).json({ error: 'No database is bound to this app yet. Bind a managed Postgres as DATABASE_URL and redeploy.' }));
app.use((_req, res) => res.type('text/html').send(page('Connect a database', setupBody())));
stopOnSignal(app.listen(port, '0.0.0.0', () => console.log(`setup page listening on ${port}`)));
return; // CommonJS allows a top-level return; nothing below runs without a database.
}
// ─── Database ───────────────────────────────────────────────────────────────
const pool = new Pool({
// See db.js: velixir's sslmode=require means "encrypt, do not verify", which node-postgres
// does not do on its own.
...pgConfig(connectionString),
// Keep the pool small. An app that scales to several replicas multiplies this by the
// replica count, and a managed instance has a connection cap.
max: 5,
});
// A broken connection in the idle pool emits here. Without a listener it crashes the process.
pool.on('error', (err) => console.error('idle database connection failed:', err.message));
const state = { ready: false, lastError: null };
// Migrating on boot is fine for one table and one replica. Past that, run migrations as a
// deliberate step instead: several replicas starting at once will race this.
async function migrate() {
await pool.query(`
CREATE TABLE IF NOT EXISTS notes (
id BIGSERIAL PRIMARY KEY,
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
`);
}
// Keep trying rather than exiting. A database that is briefly unreachable (a failover, a
// rotated password waiting for a redeploy) gets an explanation on the page instead of a
// crash loop, and the app recovers by itself when the database comes back.
async function connect(attempt = 1) {
try {
await migrate();
state.ready = true;
state.lastError = null;
console.log('database ready');
} catch (err) {
state.lastError = err.message;
if (attempt === 1 || attempt % 12 === 0) {
console.error(`database not reachable yet (attempt ${attempt}): ${err.message}`);
}
setTimeout(() => connect(attempt + 1), 5000);
}
}
// ─── Health ─────────────────────────────────────────────────────────────────
// Liveness AND readiness: this app is useless without its database, so a failed query takes
// it out of rotation rather than letting it serve errors.
app.get('/healthz', async (_req, res) => {
if (!state.ready) return res.status(503).type('text/plain').send('waiting for the database');
try {
await pool.query('SELECT 1');
res.type('text/plain').send('ok');
} catch (err) {
console.error('health check failed:', err.message);
res.status(503).type('text/plain').send('database unreachable');
}
});
// Until the first successful connection, every other route explains the wait. The driver's
// error stays in the log: it can name the database's internal address and user, which is
// nobody else's business.
app.use((req, res, next) => {
if (state.ready) return next();
if (req.path.startsWith('/api/')) {
return res.status(503).json({ error: 'Waiting for the database. The app log has the details.' });
}
res.status(503).type('text/html').send(page('Waiting for the database', waitingBody()));
});
// ─── API ────────────────────────────────────────────────────────────────────
// Express 5 passes a rejected promise from an async handler to the error handler at the
// bottom. (Express 4 did not: the rejection went unhandled, and on current Node that ends
// the process, so one failed query during a database restart took the whole app down.)
app.get('/api/notes', async (_req, res) => {
const { rows } = await pool.query(
'SELECT id, body, created_at FROM notes ORDER BY created_at DESC LIMIT 100'
);
res.json(rows);
});
app.post('/api/notes', async (req, res) => {
const body = (req.body?.body ?? '').toString().trim();
if (!body) return res.status(400).json({ error: 'body is required' });
// Parameterised, always. String-building a query with user input is how this kind of
// app ends up owned.
const { rows } = await pool.query(
'INSERT INTO notes (body) VALUES ($1) RETURNING id, body, created_at',
[body.slice(0, 2000)]
);
res.status(201).json(rows[0]);
});
app.post('/notes', async (req, res) => {
const body = (req.body?.body ?? '').toString().trim();
if (body) {
await pool.query('INSERT INTO notes (body) VALUES ($1)', [body.slice(0, 2000)]);
}
res.redirect('/');
});
app.post('/notes/:id/delete', async (req, res) => {
const id = Number.parseInt(req.params.id, 10);
if (Number.isSafeInteger(id)) await pool.query('DELETE FROM notes WHERE id = $1', [id]);
res.redirect('/');
});
app.get('/', async (_req, res) => {
const { rows } = await pool.query(
'SELECT id, body, created_at FROM notes ORDER BY created_at DESC LIMIT 100'
);
res.type('text/html').send(page('Notes on velixir', notesBody(rows)));
});
app.use((err, _req, res, _next) => {
console.error(err);
res.status(500).type('text/plain').send('Something went wrong.');
});
// ─── Pages ──────────────────────────────────────────────────────────────────
function notesBody(notes) {
const items = notes.length
? notes.map((n) => `
<li>
<div>
<p>${escapeHtml(n.body)}</p>
<time>${new Date(n.created_at).toISOString().replace('T', ' ').slice(0, 19)} UTC</time>
</div>
<form method="post" action="/notes/${n.id}/delete">
<button type="submit" class="del" aria-label="Delete note">×</button>
</form>
</li>`).join('')
: '<li class="empty">No notes yet. Write one above.</li>';
return `
<h1>Notes</h1>
<p class="sub">Stored in managed Postgres, reached through <code>DATABASE_URL</code>.</p>
<form class="new" method="post" action="/notes">
<input type="text" name="body" placeholder="Write a note" maxlength="2000" required autofocus>
<button type="submit">Add</button>
</form>
<ul>${items}</ul>`;
}
function setupBody() {
return `
<h1>Connect a database</h1>
<p class="sub">This app keeps its notes in Postgres, and no database is bound to it yet.</p>
<ol class="steps">
<li><strong>Create a managed Postgres</strong> from the Databases page, or run
<code>velixir db create</code>.</li>
<li><strong>Bind it to this app</strong> as <code>DATABASE_URL</code>: on the database's page
under Bound apps, or <code>velixir db bind <database-id> --app <app-id></code>.</li>
<li><strong>Redeploy</strong> with the Redeploy button on the live release (Deploys tab).
The table is created on the next boot.</li>
</ol>
<p class="note">Deploying this template from the velixir gallery does all three for you.</p>`;
}
function waitingBody() {
return `
<h1>Waiting for the database</h1>
<p class="sub">The app is running and retrying the connection every few seconds. The app log says why it cannot connect.</p>
<p class="note">If the database password was rotated, redeploy the app to pick up the new one.</p>`;
}
function page(title, body) {
return `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body { margin:0; min-height:100vh; background:#0b0b10; color:#e8e8ef;
font:15px/1.6 ui-sans-serif,system-ui,-apple-system,Segoe UI,sans-serif; }
.wrap { max-width:38rem; margin:0 auto; padding:3rem 1.25rem 4rem; }
h1 { font-size:1.5rem; margin:0 0 .25rem; letter-spacing:-.02em; }
.sub { color:#7a7a8c; font-size:.8125rem; margin:0 0 2rem; }
code { background:#16161f; border:1px solid #26263a; border-radius:5px;
padding:.1rem .35rem; color:#c7d2fe; font-size:.8125rem; overflow-wrap:anywhere; }
form.new { display:flex; gap:.5rem; margin-bottom:2rem; }
input[type=text] { flex:1; min-width:0; padding:.7rem .85rem; border-radius:8px; background:#13131c;
border:1px solid #26263a; color:#e8e8ef; font:inherit; }
input[type=text]:focus { outline:none; border-color:#6366f1; }
button { padding:.7rem 1.1rem; border-radius:8px; border:0; background:#6366f1;
color:#fff; font:inherit; font-weight:600; cursor:pointer; }
ul { list-style:none; margin:0; padding:0; }
ul li { display:flex; align-items:flex-start; justify-content:space-between; gap:1rem;
border:1px solid #1f1f2e; border-radius:10px; padding:.875rem 1rem; margin-bottom:.5rem; }
ul li p { margin:0; overflow-wrap:anywhere; }
ul li time { color:#4b4b5c; font-size:.75rem; font-variant-numeric:tabular-nums; }
ul li.empty { color:#4b4b5c; justify-content:center; border-style:dashed; }
button.del { background:transparent; color:#4b4b5c; padding:.15rem .45rem; font-size:1.1rem; }
button.del:hover { color:#fca5a5; }
ol.steps { padding-left:1.25rem; margin:0 0 1.5rem; }
ol.steps li { margin-bottom:.9rem; }
.note { color:#7a7a8c; font-size:.8125rem; }
footer { color:#4b4b5c; font-size:.75rem; margin-top:2.5rem; text-align:center; }
footer a { color:#7a7a8c; }
</style>
<div class="wrap">
${body}
<footer>
<a href="/api/notes">JSON API</a> · running on <a href="https://velixir.net">velixir</a>
</footer>
</div>
</html>`;
}
// ─── Start ──────────────────────────────────────────────────────────────────
// Listen first, then connect: the waiting page needs a server to be seen on.
// 0.0.0.0, not localhost: the platform health check comes from outside the container.
const server = app.listen(port, '0.0.0.0', () => {
console.log(`listening on ${port}`);
connect();
});
stopOnSignal(server, () => pool.end());