@dokebi/web 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI.md +4 -2
- package/README.md +1 -1
- package/dist/index.js +119 -8
- package/package.json +2 -2
package/AI.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# AI 작업 안내 — @dokebi/web 0.1.
|
|
1
|
+
# AI 작업 안내 — @dokebi/web 0.1.2
|
|
2
2
|
|
|
3
3
|
Fastify 5 HTTP 서버를 앱이 소유하게 하는 플러그인이다. 준비 전·종료 중 요청 차단(503), health 경로, 진행 요청을 기다리는 drain, cluster 워커의 무중단 교체, 신뢰 프락시를 맡는다. 라우터·컨트롤러·뷰·DB는 필수가 아니다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
|
|
4
4
|
|
|
@@ -66,7 +66,9 @@ http.route({ method: 'POST', url: '/import', handler: async (request, reply) =>
|
|
|
66
66
|
|
|
67
67
|
## 6. 오류
|
|
68
68
|
|
|
69
|
-
`WebError`(`INVALID_OPTIONS`·`FROZEN`·`CLOSED`). 기본 오류 응답은 내부 메시지를
|
|
69
|
+
`WebError`(`INVALID_OPTIONS`·`FROZEN`·`CLOSED`). 기본 오류 응답은 내부 메시지를 숨긴다. 500은 `error` 로그 `HTTP request failed`(`code: WEB_REQUEST_FAILED`·`requestId`·`method`·`route`(라우트 패턴, 쿼리 없음)·`error`(이름·전체 메시지·스택·`Caused by:` 원인, URL 인증 정보만 `//***@`로 지우고 16KB 넘으면 잘라 표시))를 남기고, 같은 라우트·오류 이름은 10초에 한 번만 남기며 사이 횟수는 다음 로그의 `repeated`로 알린다(D-0047). 4xx는 debug `HTTP request rejected`(`status`·`route`·`error` 전체 글·Fastify 코드 `errorCode`). 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다.
|
|
70
|
+
|
|
71
|
+
debug 로그(`DOKEBI_LOG_LEVEL=debug`): `Web server configured`(옵션, trustProxy는 개수만)·`Web routes frozen`·`Web server listening`(주소·ms)·`Web drain started`·`Web worker stopped listening`·`Web drain cut connections`·`Web drain finished`·`Web server closed`, 요청마다는 `HTTP request refused`(이유·메서드·쿼리 뺀 경로; debug가 켜졌을 때만 만든다).
|
|
70
72
|
|
|
71
73
|
## 7. 주의 사항
|
|
72
74
|
|
package/README.md
CHANGED
package/dist/index.js
CHANGED
|
@@ -45,6 +45,58 @@ function dataRecord(input, keys) {
|
|
|
45
45
|
return result;
|
|
46
46
|
}
|
|
47
47
|
const ROUTE_PATH = /^\/[^?#\s]{0,2047}$/;
|
|
48
|
+
/**
|
|
49
|
+
* The full text of a caught value for the `error` log field (D-0047): name, whole message and
|
|
50
|
+
* stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
|
|
51
|
+
* removed; a text over 16 KB is cut and marked.
|
|
52
|
+
*/
|
|
53
|
+
function errorText(error) {
|
|
54
|
+
const parts = [];
|
|
55
|
+
let current = error;
|
|
56
|
+
for (let depth = 0; current !== undefined && depth < 5; depth++) {
|
|
57
|
+
let text;
|
|
58
|
+
if (current instanceof Error)
|
|
59
|
+
text = current.stack ?? `${current.name}: ${current.message}`;
|
|
60
|
+
else if (typeof current === 'string')
|
|
61
|
+
text = current;
|
|
62
|
+
else {
|
|
63
|
+
try {
|
|
64
|
+
text = `NonError: ${JSON.stringify(current)}`;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
parts.push(depth ? `Caused by: ${text}` : text);
|
|
71
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
72
|
+
}
|
|
73
|
+
const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
|
|
74
|
+
return text.length > 16_384
|
|
75
|
+
? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
|
|
76
|
+
: text;
|
|
77
|
+
}
|
|
78
|
+
/** How often a repeating error of the same kind is logged; repeats in between are counted. */
|
|
79
|
+
const REPEAT_INTERVAL_MS = 10_000;
|
|
80
|
+
/**
|
|
81
|
+
* Counts repeats of the same error key so a hot path logs it once per interval (D-0047). The
|
|
82
|
+
* first occurrence is logged; later ones inside the interval are only counted and reported with
|
|
83
|
+
* the next logged occurrence of that key.
|
|
84
|
+
*/
|
|
85
|
+
class Repeats {
|
|
86
|
+
#keys = new Map();
|
|
87
|
+
/** The repeats to report with this occurrence, or undefined when it is only counted. */
|
|
88
|
+
take(key, now = Date.now()) {
|
|
89
|
+
const entry = this.#keys.get(key);
|
|
90
|
+
if (entry && now < entry.until) {
|
|
91
|
+
entry.repeated++;
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
if (!entry && this.#keys.size >= 256)
|
|
95
|
+
this.#keys.clear();
|
|
96
|
+
this.#keys.set(key, { until: now + REPEAT_INTERVAL_MS, repeated: 0 });
|
|
97
|
+
return entry?.repeated ?? 0;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
48
100
|
/**
|
|
49
101
|
* How long a draining node:cluster worker stays up after it stops listening: enough for any
|
|
50
102
|
* connection the primary was already handing it to be answered "not accepted" and passed on.
|
|
@@ -140,11 +192,43 @@ class WebOwner {
|
|
|
140
192
|
...(options.trustProxy.length ? { trustProxy: [...options.trustProxy] } : {}),
|
|
141
193
|
});
|
|
142
194
|
const owner = this;
|
|
195
|
+
context.logger.log('debug', 'Web server configured', {
|
|
196
|
+
host: options.host,
|
|
197
|
+
port: options.port,
|
|
198
|
+
bodyLimit: options.bodyLimit,
|
|
199
|
+
requestTimeout: options.requestTimeout,
|
|
200
|
+
healthRoutes: options.healthRoutes ? { ...options.healthRoutes } : false,
|
|
201
|
+
trustProxy: options.trustProxy.length,
|
|
202
|
+
health: health !== undefined,
|
|
203
|
+
cluster: cluster.isWorker ? 'worker' : 'none',
|
|
204
|
+
});
|
|
205
|
+
const failures = new Repeats();
|
|
143
206
|
this.server.setErrorHandler((error, request, reply) => {
|
|
144
207
|
const code = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined;
|
|
145
208
|
const status = typeof code === 'number' && code >= 400 && code < 500 ? code : 500;
|
|
146
|
-
if (status === 500)
|
|
147
|
-
|
|
209
|
+
if (status === 500) {
|
|
210
|
+
// The route pattern, not the requested URL: no query values in the log (D-0047).
|
|
211
|
+
const route = request.routeOptions.url ?? 'unmatched';
|
|
212
|
+
const name = error instanceof Error ? error.name : typeof error;
|
|
213
|
+
const repeated = failures.take(`${request.method} ${route} ${name}`);
|
|
214
|
+
if (repeated !== undefined)
|
|
215
|
+
context.logger.log('error', 'HTTP request failed', {
|
|
216
|
+
code: 'WEB_REQUEST_FAILED',
|
|
217
|
+
requestId: request.id,
|
|
218
|
+
method: request.method,
|
|
219
|
+
route,
|
|
220
|
+
error: errorText(error),
|
|
221
|
+
...(repeated ? { repeated } : {}),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
else if (context.logger.isEnabled('debug'))
|
|
225
|
+
context.logger.log('debug', 'HTTP request rejected', {
|
|
226
|
+
status,
|
|
227
|
+
method: request.method,
|
|
228
|
+
route: request.routeOptions.url ?? 'unmatched',
|
|
229
|
+
error: errorText(error),
|
|
230
|
+
errorCode: error?.code,
|
|
231
|
+
});
|
|
148
232
|
reply
|
|
149
233
|
.code(status)
|
|
150
234
|
.send({ error: status === 500 ? 'INTERNAL_SERVER_ERROR' : 'INVALID_REQUEST' });
|
|
@@ -169,11 +253,12 @@ class WebOwner {
|
|
|
169
253
|
: undefined;
|
|
170
254
|
if (reason) {
|
|
171
255
|
// Why a request was turned away: drain, start not finished, or health not ready.
|
|
172
|
-
context.logger.
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
256
|
+
if (context.logger.isEnabled('debug'))
|
|
257
|
+
context.logger.log('debug', 'HTTP request refused', {
|
|
258
|
+
reason,
|
|
259
|
+
method: request.method,
|
|
260
|
+
url: request.url.split('?', 1)[0]?.slice(0, 200),
|
|
261
|
+
});
|
|
177
262
|
return reply
|
|
178
263
|
.code(503)
|
|
179
264
|
.header('connection', 'close')
|
|
@@ -271,6 +356,7 @@ class WebOwner {
|
|
|
271
356
|
}
|
|
272
357
|
#watch(promise) {
|
|
273
358
|
this.#pending.add(promise);
|
|
359
|
+
// Bookkeeping only: the caller holds the same promise and sees its rejection (D-0047).
|
|
274
360
|
void promise.then(() => this.#pending.delete(promise), () => this.#pending.delete(promise));
|
|
275
361
|
return promise;
|
|
276
362
|
}
|
|
@@ -341,7 +427,11 @@ class WebOwner {
|
|
|
341
427
|
}
|
|
342
428
|
async start() {
|
|
343
429
|
this.#frozen = true;
|
|
430
|
+
const started = performance.now();
|
|
344
431
|
await this.server.ready();
|
|
432
|
+
this.context.logger.log('debug', 'Web routes frozen', {
|
|
433
|
+
ms: Math.round(performance.now() - started),
|
|
434
|
+
});
|
|
345
435
|
this.context.signal.throwIfAborted();
|
|
346
436
|
// node:cluster shares the port: the primary hands connections to a worker as soon as it
|
|
347
437
|
// listens, so a worker listens only once the whole application is ready (`ready`, D-0034).
|
|
@@ -352,11 +442,22 @@ class WebOwner {
|
|
|
352
442
|
async listen() {
|
|
353
443
|
if (this.#address !== undefined)
|
|
354
444
|
return;
|
|
445
|
+
const started = performance.now();
|
|
355
446
|
this.#address = await this.server.listen({ host: this.options.host, port: this.options.port });
|
|
447
|
+
this.context.logger.log('debug', 'Web server listening', {
|
|
448
|
+
address: this.#address,
|
|
449
|
+
ms: Math.round(performance.now() - started),
|
|
450
|
+
});
|
|
356
451
|
}
|
|
357
452
|
async drain(signal) {
|
|
358
453
|
this.#draining = true;
|
|
359
454
|
this.#frozen = true;
|
|
455
|
+
const started = performance.now();
|
|
456
|
+
const logger = this.context.logger;
|
|
457
|
+
logger.log('debug', 'Web drain started', {
|
|
458
|
+
pending: this.#pending.size,
|
|
459
|
+
clusterWorker: cluster.isWorker,
|
|
460
|
+
});
|
|
360
461
|
// The node:cluster primary keeps handing new connections to a worker while it listens, so a
|
|
361
462
|
// draining worker stops listening first; new connections go to the other workers. A single
|
|
362
463
|
// process keeps listening and answers 503 so a load balancer's health check sees the drain
|
|
@@ -372,6 +473,7 @@ class WebOwner {
|
|
|
372
473
|
if (cluster.isWorker && this.server.server.listening) {
|
|
373
474
|
Server.prototype.close.call(this.server.server);
|
|
374
475
|
grace = delay(CLOSE_GRACE_MS);
|
|
476
|
+
logger.log('debug', 'Web worker stopped listening', { graceMs: CLOSE_GRACE_MS });
|
|
375
477
|
}
|
|
376
478
|
const listening = new AbortController();
|
|
377
479
|
const aborted = new Promise((resolve) => {
|
|
@@ -385,6 +487,10 @@ class WebOwner {
|
|
|
385
487
|
await Promise.race([Promise.allSettled([...this.#pending]), aborted]);
|
|
386
488
|
if (signal.aborted) {
|
|
387
489
|
// Deadline or forced stop: cut the remaining connections; core records the timeout.
|
|
490
|
+
logger.log('debug', 'Web drain cut connections', {
|
|
491
|
+
pending: this.#pending.size,
|
|
492
|
+
ms: Math.round(performance.now() - started),
|
|
493
|
+
});
|
|
388
494
|
this.server.server.closeAllConnections();
|
|
389
495
|
return;
|
|
390
496
|
}
|
|
@@ -393,6 +499,7 @@ class WebOwner {
|
|
|
393
499
|
}
|
|
394
500
|
if (grace)
|
|
395
501
|
await Promise.race([grace, aborted]);
|
|
502
|
+
logger.log('debug', 'Web drain finished', { ms: Math.round(performance.now() - started) });
|
|
396
503
|
}
|
|
397
504
|
finally {
|
|
398
505
|
listening.abort();
|
|
@@ -400,7 +507,11 @@ class WebOwner {
|
|
|
400
507
|
}
|
|
401
508
|
async close() {
|
|
402
509
|
this.#closed = true;
|
|
510
|
+
const started = performance.now();
|
|
403
511
|
await this.server.close();
|
|
512
|
+
this.context.logger.log('debug', 'Web server closed', {
|
|
513
|
+
ms: Math.round(performance.now() - started),
|
|
514
|
+
});
|
|
404
515
|
}
|
|
405
516
|
}
|
|
406
517
|
const HEALTH = 'dokebi-health';
|
|
@@ -470,7 +581,7 @@ class WebRuntime {
|
|
|
470
581
|
}
|
|
471
582
|
export const createPlugin = definePlugin({
|
|
472
583
|
name: 'dokebi-web',
|
|
473
|
-
version: '0.1.
|
|
584
|
+
version: '0.1.2',
|
|
474
585
|
core: '^0.2.0',
|
|
475
586
|
options: normalize,
|
|
476
587
|
entry: parseEntry,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/web",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"@dokebi/core": "^0.2.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@dokebi/health": "0.1.
|
|
35
|
+
"@dokebi/health": "0.1.2"
|
|
36
36
|
},
|
|
37
37
|
"dokebi": {
|
|
38
38
|
"schemaVersion": 2,
|