forked from blackjackshellac/kitchenTimer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference_api_server.mjs
More file actions
214 lines (190 loc) · 6.1 KB
/
Copy pathreference_api_server.mjs
File metadata and controls
214 lines (190 loc) · 6.1 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
#!/usr/bin/env node
/**
* Minimal reference HTTP API for verifying docs (Tasks 79–81).
* NOT production — login, tasks, probes, Prometheus /metrics.
*/
import http from 'node:http';
import {
normalizeRoute,
recordHttpRequest,
renderPrometheusText,
} from './prometheus_metrics.mjs';
const HOST = process.env.REFERENCE_API_HOST || '127.0.0.1';
const PORT = Number(process.env.REFERENCE_API_PORT || 3000);
const PREFIX = '/api/v1';
const DEMO_EMAIL = 'admin@example.com';
const DEMO_PASSWORD = 'secret';
const DEMO_TOKEN = 'reference-demo-access-token';
const DEMO_USER = {
id: '550e8400-e29b-41d4-a716-446655440001',
email: DEMO_EMAIL,
display_name: 'Admin',
role: 'admin',
};
const DEMO_TASKS = {
items: [
{
id: '660e8400-e29b-41d4-a716-446655440002',
title: 'Example task',
description: 'From reference API server',
status: 'todo',
project_id: '770e8400-e29b-41d4-a716-446655440003',
due_at: null,
created_at: '2026-05-27T12:00:00.000Z',
updated_at: '2026-05-27T12:00:00.000Z',
},
],
total_count: 1,
limit: 25,
offset: 0,
sort: 'created_at',
order: 'desc',
};
function dbConfiguredOk() {
const v = String(process.env.REFERENCE_API_DB_OK ?? '1').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'no';
}
async function pingDatabase() {
if (!dbConfiguredOk()) {
throw new Error('database unreachable');
}
return true;
}
function sendRaw(res, status, contentType, body, extraHeaders = {}) {
const payload = typeof body === 'string' ? body : String(body);
res.writeHead(status, {
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(payload),
'Cache-Control': 'no-store',
'X-Correlation-ID': extraHeaders['X-Correlation-ID'] || 'ref-server',
...extraHeaders,
});
res.end(payload);
}
function sendJson(res, status, body, extraHeaders = {}) {
sendRaw(res, status, 'application/json; charset=utf-8', JSON.stringify(body), extraHeaders);
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', (c) => chunks.push(c));
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
if (!raw.trim()) {
resolve(null);
return;
}
try {
resolve(JSON.parse(raw));
} catch (e) {
reject(e);
}
});
req.on('error', reject);
});
}
function pathname(url) {
return new URL(url || '/', 'http://localhost').pathname;
}
function apiSubPath(url) {
const path = pathname(url);
if (!path.startsWith(PREFIX)) {
return null;
}
return path.slice(PREFIX.length) || '/';
}
function bearerToken(req) {
const h = req.headers.authorization || '';
const m = /^Bearer\s+(.+)$/i.exec(h);
return m ? m[1].trim() : null;
}
async function handleOps(req, res, path) {
if (req.method === 'GET' && path === '/health') {
sendJson(res, 200, { status: 'ok' });
return true;
}
if (req.method === 'GET' && path === '/readyz') {
try {
await pingDatabase();
sendJson(res, 200, {
status: 'ready',
checks: { database: 'ok' },
});
} catch (_e) {
sendJson(res, 503, {
status: 'not_ready',
checks: { database: 'unreachable' },
error_code: 'SERVICE_UNAVAILABLE',
});
}
return true;
}
if (req.method === 'GET' && path === '/metrics') {
sendRaw(res, 200, 'text/plain; version=0.0.4; charset=utf-8', renderPrometheusText());
return true;
}
return false;
}
const server = http.createServer(async (req, res) => {
const started = process.hrtime.bigint();
const path = pathname(req.url);
const route = normalizeRoute(path);
let status = 500;
const finish = () => {
const elapsedNs = process.hrtime.bigint() - started;
const durationSec = Number(elapsedNs) / 1e9;
if (route !== '/metrics') {
recordHttpRequest(req.method || 'GET', route, status, durationSec);
}
};
res.on('finish', finish);
try {
if (await handleOps(req, res, path)) {
status = res.statusCode || 200;
return;
}
const sub = apiSubPath(req.url);
if (sub === null) {
status = 404;
sendJson(res, status, { error_code: 'NOT_FOUND', message: 'Not found' });
return;
}
if (req.method === 'POST' && sub === '/auth/login') {
const body = await readBody(req);
if (!body || body.email !== DEMO_EMAIL || body.password !== DEMO_PASSWORD) {
status = 401;
sendJson(res, status, { error_code: 'UNAUTHORIZED', message: 'Invalid credentials' });
return;
}
status = 200;
sendJson(res, status, {
access_token: DEMO_TOKEN,
token_type: 'Bearer',
expires_in: 900,
user: DEMO_USER,
});
return;
}
if (req.method === 'GET' && sub === '/tasks') {
const token = bearerToken(req);
if (token !== DEMO_TOKEN) {
status = 401;
sendJson(res, status, { error_code: 'UNAUTHORIZED', message: 'Missing or invalid token' });
return;
}
status = 200;
sendJson(res, status, DEMO_TASKS);
return;
}
status = 404;
sendJson(res, status, { error_code: 'NOT_FOUND', message: 'Not found' });
} catch (e) {
status = 422;
sendJson(res, status, { error_code: 'VALIDATION_ERROR', message: String(e.message || e) });
}
});
server.listen(PORT, HOST, () => {
process.stdout.write(
`reference_api_server listening on http://${HOST}:${PORT} (/health, /readyz, /metrics, ${PREFIX})\n`,
);
});