-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
651 lines (599 loc) · 17.5 KB
/
Copy pathserver.js
File metadata and controls
651 lines (599 loc) · 17.5 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
'use strict';
const http = require('http');
const net = require('net');
const { URL } = require('url');
function orFallback(value, fallback) {
if (value === undefined || value === null || value === '') return fallback;
return value;
}
function backendPortFor(target) {
return +(orFallback(target.port, target.protocol === 'https:' ? '443' : '80'));
}
if (!process.env.BACKEND_URL) {
console.error('BACKEND_URL required');
process.exit(1);
}
const PORT = +(orFallback(process.env.PORT, 3000));
const BIND = orFallback(process.env.BIND, '0.0.0.0');
const BACKEND = process.env.BACKEND_URL;
const TTL_MS = +(orFallback(process.env.CACHE_TTL_MS, 300000));
const CACHE_MAX = +(orFallback(process.env.CACHE_MAX, 500));
const MAX_RESPONSE_MS = 100;
function outboundTimeoutMs(raw) {
const n = +raw;
if (!Number.isFinite(n) || n <= 0) return MAX_RESPONSE_MS;
return Math.min(MAX_RESPONSE_MS, n);
}
const REQUEST_TIMEOUT_MS = outboundTimeoutMs(orFallback(process.env.REQUEST_TIMEOUT_MS, MAX_RESPONSE_MS));
const STARTED = new Date().toISOString();
// Public GET list roots this layer may answer from cache. Authenticated
// requests are never cached.
const CACHE_PREFIXES = [
'/v1/asset',
'/v1/fiat',
'/v1/country',
'/v1/language',
'/v1/statistic',
'/v1/coin',
'/v1/setting',
'/v1/bank',
'/v1/app',
];
const cache = new Map();
let swaggerSpec = null;
let pool = null;
try {
if (process.env.SQL_HOST) {
if (!process.env.SQL_PORT || !process.env.SQL_DB || !process.env.SQL_USERNAME || process.env.SQL_PASSWORD === undefined) {
console.error('SQL_HOST set but SQL_PORT/SQL_DB/SQL_USERNAME/SQL_PASSWORD missing');
process.exit(1);
}
const { Pool } = require('pg');
const sslOn = String(process.env.SQL_SSL || '') === 'true';
pool = new Pool({
host: process.env.SQL_HOST,
port: +process.env.SQL_PORT,
user: process.env.SQL_USERNAME,
password: process.env.SQL_PASSWORD,
database: process.env.SQL_DB,
ssl: sslOn ? { rejectUnauthorized: false } : false,
max: 4,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 90,
});
pool.on('error', (err) => console.error('pg pool', err.message));
attachPoolGuards(pool);
}
} catch (err) {
console.error('pg init failed:', err.message);
process.exit(1);
}
function cacheKey(req) {
const method = req.method === 'HEAD' ? 'GET' : req.method;
return method + ' ' + (req.url ?? '/').split('?')[0];
}
function isCacheable(req) {
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
if (req.headers.authorization) return false;
const path = (req.url ?? '/').split('?')[0];
if (path === '/') return false;
return isServedPath(path);
}
function getCached(key) {
return cache.get(key) || null;
}
function embeddedStatisticStatus(body) {
try {
const raw = Buffer.isBuffer(body) ? body.toString('utf8') : String(body);
const json = JSON.parse(raw);
if (!json || typeof json !== 'object' || Array.isArray(json)) return null;
const nested = json.status;
if (!nested || typeof nested !== 'object' || Array.isArray(nested)) return null;
return nested;
} catch {
return null;
}
}
function putCache(key, status, headers, body) {
if (cache.size >= CACHE_MAX) {
const oldest = cache.keys().next().value;
if (oldest !== undefined) cache.delete(oldest);
}
cache.set(key, { status, headers, body, exp: Date.now() + TTL_MS });
if (key !== 'GET /v1/statistic' || status !== 200) return;
const nested = embeddedStatisticStatus(body);
if (!nested) {
cache.delete('GET /v1/statistic/status');
return;
}
putCache('GET /v1/statistic/status', 200, headers, Buffer.from(JSON.stringify(nested)));
}
function localVersion() {
return { commit: 'front-api', startedAt: STARTED };
}
function attachRequestTimeout(req, ms, onTimeout) {
req.setTimeout(ms, onTimeout);
}
function canWrite(res) {
return !res.headersSent && !res.writableEnded && !res.destroyed;
}
function logDeadlineError(req) {
console.error('ERROR response exceeded ' + MAX_RESPONSE_MS + 'ms', req.method, req.url);
}
function attachResponseBudget(req, res, budgetMs) {
const asked = budgetMs === undefined ? MAX_RESPONSE_MS : budgetMs;
const limit = Math.min(MAX_RESPONSE_MS, asked);
const fireAt = Math.max(1, limit - 10);
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
};
const timer = setTimeout(() => {
if (settled) return;
logDeadlineError(req);
if (!res.headersSent) {
sendJson(res, 503, { statusCode: 503, message: 'response deadline exceeded', retryAfter: 1 }, 'local', {
connection: 'close',
'retry-after': '1',
});
return;
}
if (!res.destroyed) req.destroy();
}, fireAt);
const hard = setTimeout(() => {
if (settled) return;
logDeadlineError(req);
if (!res.destroyed) req.destroy();
finish();
}, limit);
timer.unref();
hard.unref();
res.on('finish', finish);
res.on('close', finish);
return true;
}
function onPoolConnect(client) {
return client.query('SET statement_timeout TO 90');
}
function attachPoolGuards(p) {
p.on('connect', (client) => {
Promise.resolve(onPoolConnect(client)).catch((err) => {
console.error('pg statement_timeout', err.message);
if (typeof client.release === 'function') client.release(true);
else if (typeof client.end === 'function') client.end();
});
});
return p;
}
function getBackendJson(urlPath) {
return new Promise((resolve, reject) => {
const target = new URL(BACKEND);
const req = http.request(
{
hostname: target.hostname,
port: backendPortFor(target),
path: urlPath,
method: 'GET',
},
(resp) => {
const chunks = [];
resp.on('data', (c) => chunks.push(c));
resp.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
try {
resolve({ status: resp.statusCode, json: JSON.parse(raw) });
} catch (err) {
reject(err);
}
});
},
);
req.on('error', reject);
attachRequestTimeout(req, REQUEST_TIMEOUT_MS, () => {
req.destroy();
reject(new Error('timeout'));
});
req.end();
});
}
const EXACT_GET_PATHS = [
'/',
'/version',
'/swagger',
'/swagger/',
'/swagger-json',
'/swagger-json/',
'/swagger-ui',
'/swagger-ui/',
];
function isServedPath(path) {
const p = (path ?? '/').split('?')[0];
if (EXACT_GET_PATHS.includes(p)) return true;
return CACHE_PREFIXES.some((prefix) => p === prefix || p.startsWith(prefix + '/'));
}
function isKnownLocalRequest(req) {
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
const path = (req.url ?? '/').split('?')[0];
return isServedPath(path);
}
async function refreshSwagger() {
try {
const got = await getBackendJson('/swagger-json');
if (!got.json || !got.json.paths) return;
const paths = {};
for (const [p, ops] of Object.entries(got.json.paths)) {
if (!isServedPath(p)) continue;
paths[p] = ops;
}
swaggerSpec = { ...got.json, paths, info: { ...(got.json.info ?? {}), title: 'DFX API' } };
} catch (err) {
console.error('swagger refresh', err.message);
}
}
function swaggerHtml() {
return `<!doctype html>
<html><head><meta charset="utf-8"><title>DFX API</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
</head><body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
window.ui = SwaggerUIBundle({ url: '/swagger-json', dom_id: '#swagger-ui' });
</script>
</body></html>
`;
}
function sendJson(res, status, body, via, extraHeaders) {
if (!canWrite(res)) return;
let buf;
if (Buffer.isBuffer(body)) {
try {
buf = Buffer.from(JSON.stringify(JSON.parse(body.toString('utf8')), null, 2) + '\n');
} catch {
buf = body;
}
} else {
buf = Buffer.from(JSON.stringify(body, null, 2) + '\n');
}
res.writeHead(status, Object.assign({
'content-type': 'application/json; charset=utf-8',
'content-length': buf.length,
'x-content-type-options': 'nosniff',
'x-front-api': via,
'access-control-allow-origin': '*',
}, extraHeaders ?? {}));
if (res.req && res.req.method === 'HEAD') {
res.end();
return;
}
res.end(buf);
}
function highlightJson(obj) {
return JSON.stringify(obj, null, 2)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"(?:\\.|[^"\\])*"(?=\s*:)/g, '<span class="k">$&</span>')
.replace(/: ("(?:\\.|[^"\\])*")/g, ': <span class="s">$1</span>');
}
function sendVersion(req, res, obj, via) {
if (!canWrite(res)) return;
if (String(req.headers.accept ?? '').includes('text/html')) {
const html = Buffer.from(
'<!doctype html><html lang="en"><head><meta charset="utf-8"><title></title>' +
'<style>' +
'html,body{margin:0;min-height:100%;background:#1e1e1e;color:#d4d4d4}' +
'pre{margin:0;padding:16px;font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}' +
'.k{color:#9cdcfe}.s{color:#ce9178}' +
'</style></head><body><pre>' +
highlightJson(obj) +
'</pre></body></html>\n',
);
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
'content-length': html.length,
'x-front-api': via,
});
if (req.method === 'HEAD') {
res.end();
return;
}
res.end(html);
return;
}
sendJson(res, 200, obj, via);
}
function countryDto(row) {
return {
id: row.id,
symbol: row.symbol,
name: row.name,
foreignName: row.foreignName,
locationAllowed: !!row.ipEnable,
ibanAllowed: !!row.fatfEnable,
kycAllowed: !!row.dfxEnable,
kycOrganizationAllowed: !!row.dfxOrganizationEnable,
nationalityAllowed: !!row.nationalityStepEnable,
bankAllowed: !!(row.bankEnable && row.dfxEnable),
cardAllowed: !!(row.checkoutEnable && row.fatfEnable),
cryptoAllowed: !!row.cryptoEnable,
};
}
function languageDto(row) {
return {
id: row.id,
name: row.name,
symbol: row.symbol,
foreignName: row.foreignName,
enable: !!row.enable,
};
}
const DB_READ = {
'/v1/country': {
sql:
'SELECT id, symbol, name, "foreignName", "ipEnable", "fatfEnable", "dfxEnable", ' +
'"dfxOrganizationEnable", "nationalityStepEnable", "bankEnable", "checkoutEnable", "cryptoEnable" ' +
'FROM country ORDER BY id',
map: (rows) => rows.map(countryDto),
},
'/v1/language': {
sql: 'SELECT id, name, symbol, "foreignName", enable FROM language ORDER BY id',
map: (rows) => rows.map(languageDto),
},
};
async function tryDbRead(path) {
if (!pool) return null;
const spec = DB_READ[path];
if (!spec) return null;
const result = await pool.query(spec.sql);
if (!result || !result.rows) return null;
return Buffer.from(JSON.stringify(spec.map(result.rows)));
}
function rejectUnserved(res) {
sendJson(res, 503, { statusCode: 503, message: 'not served', retryAfter: 1 }, 'local', {
connection: 'close',
'retry-after': '1',
});
}
function proxy(req, res) {
if (!canWrite(res)) return;
const target = new URL(BACKEND);
const opts = {
hostname: target.hostname,
port: backendPortFor(target),
path: req.url ?? '/',
method: req.method,
headers: { ...req.headers, host: target.host },
};
const p = http.request(opts, (up) => {
const chunks = [];
up.on('data', (c) => chunks.push(c));
up.on('end', () => {
if (!canWrite(res)) return;
const body = Buffer.concat(chunks);
const headers = { ...up.headers };
delete headers['transfer-encoding'];
res.writeHead(up.statusCode, headers);
res.end(body);
});
});
p.on('error', (err) => {
console.error('proxy error', err.message);
if (!canWrite(res)) return;
res.writeHead(503, {
'content-type': 'application/json',
'retry-after': '30',
'access-control-allow-origin': '*',
});
res.end(JSON.stringify({ statusCode: 503, message: 'backend-api unavailable', retryAfter: 30 }));
});
res.on('finish', () => p.destroy());
res.on('close', () => p.destroy());
req.on('aborted', () => p.destroy());
req.pipe(p);
}
function cacheRefreshPaths() {
const roots = [...CACHE_PREFIXES];
const paths = swaggerSpec?.paths;
if (!paths) return roots;
return [...new Set([...roots, ...Object.keys(paths).filter((path) => isServedPath(path) && path !== '/')])];
}
async function refreshCache() {
for (const p of cacheRefreshPaths()) {
try {
const got = await getBackendJson(p);
if (got.status !== 200) continue;
putCache('GET ' + p, 200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }, Buffer.from(JSON.stringify(got.json)));
} catch (err) {
console.error('cache refresh', p, err.message);
}
}
}
const server = http.createServer((req, res) => {
if (!isKnownLocalRequest(req)) {
proxy(req, res);
return;
}
attachResponseBudget(req, res);
const path = (req.url ?? '/').split('?')[0];
if (path === '/version') {
sendVersion(req, res, localVersion(), 'local');
return;
}
if (path === '/') {
if (!canWrite(res)) return;
res.writeHead(302, {
location: 'swagger',
'x-front-api': 'local',
'access-control-allow-origin': '*',
});
res.end();
return;
}
if (path === '/swagger' || path === '/swagger/' || path === '/swagger-ui' || path === '/swagger-ui/') {
if (!swaggerSpec) {
sendJson(res, 503, { statusCode: 503, message: 'swagger snapshot empty' }, 'local');
return;
}
const html = Buffer.from(swaggerHtml());
if (!canWrite(res)) return;
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': html.length, 'x-front-api': 'local' });
if (req.method === 'HEAD') {
res.end();
return;
}
res.end(html);
return;
}
if (path === '/swagger-json' || path === '/swagger-json/') {
if (!swaggerSpec) {
sendJson(res, 503, { statusCode: 503, message: 'swagger snapshot empty' }, 'local');
return;
}
sendJson(res, 200, swaggerSpec, 'local');
return;
}
const cacheable = isCacheable(req);
const key = cacheKey(req);
if (cacheable) {
const hit = getCached(key);
if (hit && Date.now() <= hit.exp) {
if (!canWrite(res)) return;
const headers = { ...hit.headers, 'content-length': hit.body.length, 'x-front-api': 'hit' };
res.writeHead(hit.status, headers);
if (req.method === 'HEAD') {
res.end();
return;
}
res.end(hit.body);
return;
}
}
if (pool && DB_READ[path]) {
tryDbRead(path)
.then((body) => {
if (!body) {
rejectUnserved(res);
return;
}
if (cacheable) {
putCache(key, 200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }, body);
}
sendJson(res, 200, body, 'db');
})
.catch((err) => {
console.error('db-read', path, err.message);
rejectUnserved(res);
});
return;
}
rejectUnserved(res);
});
server.on('upgrade', (req, socket, head) => {
if (isKnownLocalRequest(req)) {
if (!socket.destroyed) socket.destroy();
return;
}
const target = new URL(BACKEND);
const port = backendPortFor(target);
const up = net.connect(port, target.hostname, () => {
if (socket.destroyed) {
up.destroy();
return;
}
const lines = [`${req.method} ${req.url} HTTP/${req.httpVersion}`];
const headers = { ...req.headers, host: target.host };
for (const [k, v] of Object.entries(headers)) {
if (v === undefined) continue;
if (Array.isArray(v)) {
for (const item of v) lines.push(`${k}: ${item}`);
} else {
lines.push(`${k}: ${v}`);
}
}
up.write(lines.join('\r\n') + '\r\n\r\n');
if (head && head.length) up.write(head);
up.pipe(socket);
socket.pipe(up);
});
up.on('error', () => socket.destroy());
socket.on('error', () => up.destroy());
socket.once('close', () => up.destroy());
up.once('close', () => socket.destroy());
});
function boot() {
server.listen(PORT, BIND, () => {
console.log(`front-api listening on ${BIND}:${PORT}` + (pool ? ' db-read on' : ''));
refreshSwagger().then(() => refreshCache());
setInterval(refreshSwagger, 10 * 60 * 1000).unref();
setInterval(refreshCache, 60 * 1000).unref();
});
}
function maybeExitAfterBoot() {
if (process.env.FRONT_API_EXIT_AFTER_BOOT !== '1') return false;
server.once('listening', () => {
setTimeout(() => process.exit(0), 200);
});
server.once('error', () => process.exit(1));
return true;
}
if (require.main === module) {
maybeExitAfterBoot();
boot();
}
function setSwaggerSpec(value) {
swaggerSpec = value;
}
function getSwaggerSpec() {
return swaggerSpec;
}
function setPool(value) {
pool = value;
}
function getPool() {
return pool;
}
module.exports = {
orFallback,
backendPortFor,
CACHE_MAX,
CACHE_PREFIXES,
EXACT_GET_PATHS,
cache,
isServedPath,
isKnownLocalRequest,
isCacheable,
cacheKey,
refreshSwagger,
refreshCache,
cacheRefreshPaths,
rejectUnserved,
proxy,
swaggerHtml,
countryDto,
languageDto,
tryDbRead,
putCache,
getCached,
highlightJson,
localVersion,
sendJson,
sendVersion,
attachRequestTimeout,
attachResponseBudget,
attachPoolGuards,
onPoolConnect,
canWrite,
logDeadlineError,
MAX_RESPONSE_MS,
outboundTimeoutMs,
setSwaggerSpec,
getSwaggerSpec,
setPool,
getPool,
boot,
maybeExitAfterBoot,
REQUEST_TIMEOUT_MS,
server,
};