@dokebi/web 0.0.0-stage → 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 +80 -0
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/dist/index.d.ts +49 -0
- package/dist/index.js +604 -0
- package/options.schema.json +71 -0
- package/package.json +62 -4
- package/templates/web.ts +4 -0
package/AI.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# AI 작업 안내 — @dokebi/web 0.1.2
|
|
2
|
+
|
|
3
|
+
Fastify 5 HTTP 서버를 앱이 소유하게 하는 플러그인이다. 준비 전·종료 중 요청 차단(503), health 경로, 진행 요청을 기다리는 drain, cluster 워커의 무중단 교체, 신뢰 프락시를 맡는다. 라우터·컨트롤러·뷰·DB는 필수가 아니다. Node >=24.0.0, core ^0.2.0. 세부는 [README](README.md)다.
|
|
4
|
+
|
|
5
|
+
## 1. 설치와 설정
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npx dokebi add @dokebi/web # src/infra/web/requires.ts(onClose에서 쓰는 자원 목록)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```yaml
|
|
12
|
+
dokebi-web:
|
|
13
|
+
host: 127.0.0.1 # 기본. 외부에서 받으려면 0.0.0.0(앞단 프락시 권장)
|
|
14
|
+
port: 3000 # 기본 0(임시 포트), 0..65535
|
|
15
|
+
bodyLimit: 1048576 # 1 B..64 MiB
|
|
16
|
+
requestTimeout: 30000 # 요청 수신 제한(업무 실행 제한이 아님)
|
|
17
|
+
healthRoutes: { live: /health/live, ready: /health/ready } # false면 등록 안 함
|
|
18
|
+
trustProxy: [127.0.0.1, "::1"] # 정확한 IP만, 최대 64개
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
TLS·HTTP2·임의 Fastify 생성 옵션은 아직 공개하지 않는다(앞단 프락시에서 TLS).
|
|
22
|
+
|
|
23
|
+
## 2. 사용
|
|
24
|
+
|
|
25
|
+
보통은 @dokebi/app·module·router가 web 위에 라우트를 만든다. 직접 쓸 때:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import cors from '@fastify/cors';
|
|
29
|
+
import { dependency as web } from '@dokebi/web';
|
|
30
|
+
// dependencies/requires에 web을 넣고 setup에서:
|
|
31
|
+
const http = context.getDependency(web);
|
|
32
|
+
http.route({ method: 'GET', url: '/ping', handler: async () => ({ ok: true }) });
|
|
33
|
+
http.register(cors, { origin: ['https://a.com'] }); // Fastify 확장(옵션 필수, 없으면 {})
|
|
34
|
+
http.route({ method: 'POST', url: '/import', handler: async (request, reply) => {
|
|
35
|
+
void http.track(() => importLater(request.body)); // 응답 뒤 계속되는 업무는 track으로 drain 대상에
|
|
36
|
+
return reply.code(202).send({ accepted: true });
|
|
37
|
+
}});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
| API | 뜻 |
|
|
41
|
+
|---|---|
|
|
42
|
+
| `route(options)` | Fastify RouteOptions(타입·schema 유지). setup 중에만, 이후 `FROZEN` |
|
|
43
|
+
| `register(plugin, options)` | Fastify async·callback 플러그인(scope·decorator·hook 유지). setup 중에만 |
|
|
44
|
+
| `constraint(strategy)` | 라우트 제약 전략 추가(@dokebi/app의 `dokebiApp`). 그 제약을 쓰는 라우트보다 먼저, setup 중에만 |
|
|
45
|
+
| `track(() => work)` | HTTP 응답과 수명이 다른 업무를 drain이 기다리게 함 |
|
|
46
|
+
| `requestHost(request)` | 신뢰 프락시 규칙을 적용한 요청 호스트(소문자, 포트 유지) |
|
|
47
|
+
| `address` | listen 뒤 실제 주소(그 전 undefined). cluster 워커에서는 core `ready` 뒤에 정해지므로 다른 플러그인은 `ready`에서 읽는다 |
|
|
48
|
+
|
|
49
|
+
## 3. 시작과 요청 차단
|
|
50
|
+
|
|
51
|
+
- 모든 setup 뒤 web start에서 listen한다. **cluster 워커는 core `ready` 훅에서 listen**한다(D-0034). 앱 전체가 준비된 워커만 연결을 받게 하기 위해서다.
|
|
52
|
+
- 앱 start 완료와 health ready 전에는 업무 요청에 503 `{ error: 'SERVICE_UNAVAILABLE', reason }`(reason: `STARTING`·`NOT_READY`·`DRAINING`).
|
|
53
|
+
- health 경로: live 200/503, ready 200/503(앱 상태와 health check). 앱마다 독립이고 cluster 전체 집계가 아니다.
|
|
54
|
+
|
|
55
|
+
## 4. 종료(drain)
|
|
56
|
+
|
|
57
|
+
- 단일 프로세스: 새 요청을 503으로 막고 진행 응답·handler Promise·요청 훅·`track` 업무를 기다린다. core drain 기한(기본 20초)이 지나거나 `stop({ force: true })`면 남은 연결을 끊고 반환한다(core가 `DRAIN_TIMEOUT` 기록). 모든 drain 성공 뒤 cleanup에서 `Fastify.close`(onClose 실행).
|
|
58
|
+
- cluster 워커(D-0036): listen 소켓부터 닫아 primary가 새 연결을 다른 워커로 보내게 하고, 열린 keep-alive 연결의 요청은 처리한 뒤 `Connection: close`로 닫는다. 최소 100ms 살아 있는다. 쉬는 keep-alive가 닫히는 순간 보낸 요청은 `ECONNRESET`일 수 있다(HTTP 본질). 브라우저가 아닌 클라이언트는 재사용 소켓의 멱등 요청을 한 번 재시도한다.
|
|
59
|
+
|
|
60
|
+
## 5. 소유권 규칙(중요)
|
|
61
|
+
|
|
62
|
+
- **Fastify `onClose`에서 쓰는 Dokebi 자원은 `entry.requires`(CLI 프로젝트는 `src/infra/web/requires.ts`의 `requires`)에 넣는다.** cleanup은 초기화 역순이라, web이 그 자원에 의존해야 Fastify.close 뒤에 자원이 닫힌다.
|
|
63
|
+
- 빌린 DB 풀 등을 handler에서 닫지 않는다.
|
|
64
|
+
- callback 훅은 done 또는 응답 종료, async 훅은 반환 Promise가 완료 경계다. async와 done을 섞지 않는다. raw stream·타이머·외부 이벤트로 이어지는 작업은 `track`이나 소유 플러그인 drain으로 기다린다.
|
|
65
|
+
- `listen`·`close` 직접 호출, 루트 훅 덮어쓰기, `dokebiHealth` 예약 config 우회는 계약 밖이다.
|
|
66
|
+
|
|
67
|
+
## 6. 오류
|
|
68
|
+
|
|
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가 켜졌을 때만 만든다).
|
|
72
|
+
|
|
73
|
+
## 7. 주의 사항
|
|
74
|
+
|
|
75
|
+
- 프락시 뒤에서는 `trustProxy`에 **프락시 주소만** 적고, Host·X-Forwarded-* 헤더를 직접 믿지 말고 `requestHost(request)`를 쓴다.
|
|
76
|
+
- 인증·rate limit·CORS·보안 헤더는 앱이 Fastify 확장으로 고른다(기본 제공 없음).
|
|
77
|
+
- `requestTimeout`은 업무 시간 제한이 아니다. 긴 작업은 job으로 보낸다.
|
|
78
|
+
- 응답 종료·클라이언트 연결 끊김을 업무 완료로 보지 않는다.
|
|
79
|
+
|
|
80
|
+
근거: `examples/22-web`(API·HTML), `examples/12-cluster`·`24-template-inertia --cluster`(순차 교체), `examples/21-db`(DB와 drain), `examples/25-playground`, D-0034·D-0036.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dokebi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dokebi/web 0.1.2
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node >=24.0.0, core ^0.2.0의 선택 패키지다(npm 공개). Fastify 5.12.7로 HTTP 서버를 소유하며 DB·라우터·컨트롤러·뷰는 필수가 아니다.
|
|
4
|
+
|
|
5
|
+
## 공개 계약
|
|
6
|
+
|
|
7
|
+
플러그인 계약 v2([D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md))를 따른다. `createPlugin({ app, options?, entry? })` → `app.register(plugin)` → `app.start()` → `app.get(plugin)` 순서로 사용한다. `app`(Application의 `app.view`)은 필수다. `options`를 생략하면 `app.config['dokebi-web']`을, 그것도 없으면 `{}`를 쓴다. 플러그인 인스턴스는 Application마다 새로 만든다. 예전 `health`·`requires`·`dependencies` 입력은 없다.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { Application } from '@dokebi/core';
|
|
11
|
+
import { createPlugin as createWeb } from '@dokebi/web';
|
|
12
|
+
|
|
13
|
+
const app = new Application({ config: { 'dokebi-web': { port: 3000 } } });
|
|
14
|
+
const web = createWeb({ app: app.view, entry: { requires: [sessionStore] } });
|
|
15
|
+
app.register(web);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- 의존성: `dokebi-health`는 선택 의존성(`optionalDependency`)이다. 같은 앱에 health가 등록되어 있으면 자동으로 연결되고 없으면 앱 상태만으로 판단한다. 직접 지정하려면 `app.register(createHealth({ app: app.view }))`처럼 같은 이름으로 먼저 등록한다.
|
|
19
|
+
- `entry.requires`: Fastify `onClose`에서 쓰는 Dokebi 자원 목록이다. 플러그인 인스턴스(core `dependencyOf`로 변환) 또는 `PluginDependency` descriptor를 넣는다. 아래 "시작·종료와 소유권"을 본다. `dokebi-health`를 인스턴스로 넣으면 선택 의존성 대신 그 인스턴스를 필수로 쓴다.
|
|
20
|
+
- 다른 플러그인용 descriptor: `import { dependency } from '@dokebi/web'`. 공급자가 없으면 이 패키지에서 web을 만든다. 공식 소비자(router·template-inertia)는 자기 패키지에서 같은 descriptor를 직접 만든다.
|
|
21
|
+
|
|
22
|
+
- `route<T>(options)`: Fastify RouteOptions와 Params/Body/Reply 타입을 유지한다. setup에서 등록한다.
|
|
23
|
+
- `register(plugin, options)`: Fastify async 또는 callback 플러그인과 옵션을 전달한다. 옵션이 없으면 `{}`를 전달한다. 네이티브 플러그인의 scope/decorator/schema/hook을 보존한다.
|
|
24
|
+
- `address`: listen 이후 실제 주소이며 그 전에는 undefined다. node:cluster 워커에서는 core `ready` 이후에야 정해진다(D-0034). 다른 플러그인은 `start`가 아니라 `ready`에서 읽는다. 종료 후에는 마지막 주소가 남으므로 가용 상태로 사용하지 않는다.
|
|
25
|
+
- `track(() => work)`: HTTP 응답과 수명이 다른 명시 업무를 drain 대상에 넣고 Promise를 반환한다. 호출자는 실패를 처리하고 새 작업 유입을 멈춰야 한다.
|
|
26
|
+
|
|
27
|
+
모든 Dokebi setup 이후 web.start에서 ready/listen한다. 단 `node:cluster` 워커에서는 core `ready` 훅에서 listen한다([D-0034](../../docs/decisions/D-0034-ready-before-traffic.md)). primary는 listen한 워커에 바로 연결을 나눠 주기 때문에, 앱 전체가 준비된 워커만 연결을 받게 하려는 것이다. 이후 route/register는 FROZEN이다. Fastify 등록 함수 안에서는 전달받은 scope에 라우트를 등록한다. 실행 중 확장 추가는 지원하지 않는다.
|
|
28
|
+
|
|
29
|
+
## YAML 옵션
|
|
30
|
+
|
|
31
|
+
```yaml
|
|
32
|
+
options:
|
|
33
|
+
dokebi-web:
|
|
34
|
+
host: 127.0.0.1
|
|
35
|
+
port: 3000
|
|
36
|
+
bodyLimit: 1048576
|
|
37
|
+
requestTimeout: 30000
|
|
38
|
+
healthRoutes: # false면 health 라우트를 등록하지 않는다
|
|
39
|
+
live: /health/live
|
|
40
|
+
ready: /health/ready
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
기본 host는 127.0.0.1, port는 0(임시 포트), bodyLimit는 1 MiB, requestTimeout은 30초다. port 0..65535, bodyLimit 1..64 MiB, requestTimeout 1..2147483647ms를 허용한다. requestTimeout은 요청 수신 제한이며 업무 실행 시간 제한이나 DB 취소가 아니다. TLS/HTTP2/임의 Fastify 생성 옵션을 아직 공개하지 않는다.
|
|
44
|
+
|
|
45
|
+
`healthRoutes`의 기본값은 `{ live: '/health/live', ready: '/health/ready' }`다. 객체에서 빠진 키는 기본 경로를 쓴다. 경로는 `/`로 시작하고 `?`·`#`·공백이 없어야 하며 live와 ready가 같으면 안 된다. `false`면 두 라우트를 모두 등록하지 않는다(외부 health 서버를 쓸 때). 잘못된 옵션은 팩토리에서 `CoreError('INVALID_PLUGIN_OPTIONS')`(cause는 `WebError('INVALID_OPTIONS')`)로 실패한다.
|
|
46
|
+
|
|
47
|
+
## 시작·종료와 소유권
|
|
48
|
+
|
|
49
|
+
Application 전체 start 완료 및 선택 health.ready 전에는 업무 요청에 503을 반환한다. 본문은 `{ error: 'SERVICE_UNAVAILABLE', reason }`이고 reason은 `DRAINING`·`STARTING`·`NOT_READY` 중 하나다. 같은 이유를 debug 로그 `HTTP request refused`에도 남긴다. health 라우트(기본 `/health/live`, `/health/ready`)는 예약 경로이며 각각 200/503을 반환한다. health는 앱마다 독립적이고 부모 cluster 전체 집계가 아니다.
|
|
50
|
+
|
|
51
|
+
**node:cluster 워커**(D-0036)에서는 drain을 시작하면 listen 소켓을 먼저 닫아 primary가 새 연결을 다른 워커로 보내게 한다. 이미 열린 keep-alive 연결로 오는 요청은 503 대신 처리하고 `Connection: close`로 닫는다. listen을 닫은 뒤 최소 100ms는 살아 있어, primary가 넘기던 연결이 버려지지 않게 한다. 쉬는 keep-alive 연결이 닫히는 순간 그 연결로 보낸 요청은 `ECONNRESET`을 받을 수 있다. HTTP의 본질적 경합이므로 브라우저가 아닌 클라이언트는 재사용 소켓의 멱등 요청을 한 번 재시도한다(Node 문서 권고). 단일 프로세스는 아래처럼 listen을 유지하고 503을 준다(로드밸런서가 health로 뺀다).
|
|
52
|
+
|
|
53
|
+
단일 프로세스의 drain은 새 요청을 503으로 차단한 뒤 응답, handler Promise, 등록한 요청 생명주기 훅, track 업무를 기다린다. core의 drain 기한(`shutdown.drainTimeoutMs`, 기본 20초)이 지나거나 `stop({ force: true })`로 `context.drainSignal`이 abort되면 기다림을 멈추고 `server.closeAllConnections()`로 남은 연결을 끊은 뒤 반환한다. 이때 core가 `DRAIN_TIMEOUT`을 기록한다. 클라이언트 연결 해제로 handler/hook 업무를 완료 처리하지 않는다. 전체 플러그인의 drain이 성공한 뒤에만 deferred cleanup에서 Fastify.close를 호출한다. 네이티브 onClose도 그때 실행된다. 종료 실패·지연을 감추거나 미완료 업무보다 먼저 DB를 닫지 않는다. cluster의 최종 강제 종료는 프로세스 정책이며 정상 drain 성공이 아니다.
|
|
54
|
+
|
|
55
|
+
**규칙: Fastify `onClose`에서 쓰는 Dokebi 자원은 반드시 `entry.requires`에 넣는다.** 예: `createWeb({ app: app.view, entry: { requires: [dbPlugin] } })`. cleanup은 초기화 역순이므로 web이 그 자원에 의존해야 Fastify.close 이후에 자원이 정리된다. 반대로 자원 쪽이 web에 의존하면 자원이 먼저 닫힌다. 업무 모듈은 자신이 사용하는 web/router/controller/DB를 직접 requires로 선언한다. 빌린 풀을 임의로 close하지 않는다.
|
|
56
|
+
|
|
57
|
+
네이티브 callback 훅은 done 또는 정상 응답 종료가 업무 완료 경계다. async 훅은 반환 Promise까지 기다린다. 응답을 보낸 뒤에도 계속되는 작업, 사용자 raw stream·parser·custom error handler·타이머·외부 이벤트의 비동기 작업은 자동 추적을 가정하지 말고 track 또는 소유 플러그인의 drain으로 기다린다. hook에서 async와 done을 혼용하지 않는다. `listen/close`, 루트 훅 덮어쓰기, `dokebiHealth` 예약 config 우회는 확장 계약 밖이다.
|
|
58
|
+
|
|
59
|
+
기본 오류 응답은 내부 메시지를 숨기며 500은 최소 로거에 requestId만 남긴다. 사용자 오류 처리기를 등록하면 그 보안 책임도 사용자에게 있다. HTTP 인증·rate limit·CORS 등은 앱이 필요한 Fastify 확장으로 선택한다.
|
|
60
|
+
|
|
61
|
+
## 설치·실행
|
|
62
|
+
|
|
63
|
+
`dokebi add`는 정적 설치 선언으로 진입 파일 `src/infra/web/requires.ts`(`export const requires = [] as const;`)를 만든다. 생성 코드가 이 모듈을 `entry`로 넘긴다. 사용자 main에서 직접 조합할 때 자동 생성 파일을 편집하거나 같은 ID를 중복 등록하지 않는다. 저장소 실행 예제는 examples/22-web/main.ts, 실제 DB/cluster 예제는 examples/21-db/main.ts다.
|
|
64
|
+
|
|
65
|
+
진입 파일을 가진 플러그인은 생성 코드의 manifest 의존 검사에서 제외되므로 CLI 경로에서도 진입 파일의 `requires`를 쓸 수 있다(같은 생성 코드 규칙을 2026-10-14 controller·module 진입 파일로 실행 확인, [ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-04). 진입 파일로 더한 의존은 CLI의 remove·doctor 판단에 보이지 않으며 빠지면 실행 시 `MISSING_DEPENDENCY`로 드러난다.
|
|
66
|
+
|
|
67
|
+
## 라우트 제약 전략 (D-0030)
|
|
68
|
+
|
|
69
|
+
`constraint(strategy)`는 setup 단계에서 Fastify 라우트 제약 전략(`addConstraintStrategy`)을 더한다. 그 제약을 쓰는 라우트보다 먼저 호출한다. @dokebi/app이 Host → 앱 선택(`dokebiApp`)에 쓰며, 같은 경로를 여러 라우트가 제약 값별로 나눠 가질 수 있다. start 이후 호출은 `FROZEN`이다.
|
|
70
|
+
|
|
71
|
+
## 신뢰 프락시 (2026-10-14)
|
|
72
|
+
|
|
73
|
+
`trustProxy: [주소...]`(정확한 IPv4·IPv6 주소, 최대 64개)에서 온 요청만 `X-Forwarded-Host`(·For·Proto)를 믿는다. Fastify `trustProxy`에도 같은 목록을 넘긴다. `requestHost(request)`는 그 규칙으로 요청이 원한 호스트를 소문자로 돌려준다(포트 유지). @dokebi/app의 도메인 판단과 @dokebi/websocket의 Origin 검사가 이를 쓴다. 예: 같은 컴퓨터의 Cloudflare 터널은 `[127.0.0.1, ::1]`([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-20).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Awaitable, type Plugin, type PluginDependency } from '@dokebi/core';
|
|
2
|
+
import { type FastifyInstance, type FastifyPluginAsync, type FastifyPluginCallback, type FastifyPluginOptions, type FastifyRegisterOptions, type RawReplyDefaultExpression, type RawRequestDefaultExpression, type RawServerDefault, type RouteGenericInterface, type RouteOptions } from 'fastify';
|
|
3
|
+
export type WebRoute<T extends RouteGenericInterface = RouteGenericInterface> = RouteOptions<RawServerDefault, RawRequestDefaultExpression<RawServerDefault>, RawReplyDefaultExpression<RawServerDefault>, T>;
|
|
4
|
+
export interface WebHealth {
|
|
5
|
+
readonly ready: boolean;
|
|
6
|
+
readonly live: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface WebApi {
|
|
9
|
+
readonly address: string | undefined;
|
|
10
|
+
route<T extends RouteGenericInterface = RouteGenericInterface>(options: WebRoute<T>): void;
|
|
11
|
+
register<T extends FastifyPluginOptions>(plugin: FastifyPluginAsync<T>, options: FastifyRegisterOptions<T>): void;
|
|
12
|
+
register<T extends FastifyPluginOptions>(plugin: FastifyPluginCallback<T>, options: FastifyRegisterOptions<T>): void;
|
|
13
|
+
track<T>(work: () => Awaitable<T>): Promise<T>;
|
|
14
|
+
/**
|
|
15
|
+
* Adds a Fastify route constraint strategy (for example the host-to-app mapping of
|
|
16
|
+
* @dokebi/app). Setup only, before any route that uses it.
|
|
17
|
+
*/
|
|
18
|
+
constraint(strategy: WebConstraintStrategy): void;
|
|
19
|
+
/**
|
|
20
|
+
* The host a client asked for: `X-Forwarded-Host` when the request comes from an address in
|
|
21
|
+
* `trustProxy`, otherwise `Host`. Lower case, port kept. Takes a raw or Fastify request.
|
|
22
|
+
*/
|
|
23
|
+
requestHost(request: WebRequestLike): string;
|
|
24
|
+
}
|
|
25
|
+
export interface WebRequestLike {
|
|
26
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
27
|
+
readonly socket?: {
|
|
28
|
+
readonly remoteAddress?: string | undefined;
|
|
29
|
+
} | null;
|
|
30
|
+
}
|
|
31
|
+
/** A Fastify constraint strategy; see Fastify `addConstraintStrategy`. */
|
|
32
|
+
export type WebConstraintStrategy = Parameters<FastifyInstance['addConstraintStrategy']>[0];
|
|
33
|
+
export declare class WebError extends Error {
|
|
34
|
+
readonly code: 'INVALID_OPTIONS' | 'FROZEN' | 'CLOSED';
|
|
35
|
+
constructor(code: 'INVALID_OPTIONS' | 'FROZEN' | 'CLOSED');
|
|
36
|
+
}
|
|
37
|
+
export interface WebHealthRoutes {
|
|
38
|
+
readonly live: string;
|
|
39
|
+
readonly ready: string;
|
|
40
|
+
}
|
|
41
|
+
/** Plugin instances or descriptors that must outlive Fastify close (native onClose users). */
|
|
42
|
+
export type WebRequirement = Plugin<unknown> | PluginDependency;
|
|
43
|
+
export interface WebEntry {
|
|
44
|
+
readonly requires?: readonly WebRequirement[];
|
|
45
|
+
}
|
|
46
|
+
export declare const createPlugin: import("@dokebi/core").PluginFactory<WebApi>;
|
|
47
|
+
/** Declares dokebi-web as a required provider; it is created from this package when absent. */
|
|
48
|
+
export declare const dependency: PluginDependency<WebApi>;
|
|
49
|
+
export type { RouteGenericInterface } from 'fastify';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
import cluster from 'node:cluster';
|
|
2
|
+
import { isIP, Server } from 'node:net';
|
|
3
|
+
import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
|
|
4
|
+
import { types } from 'node:util';
|
|
5
|
+
import { definePlugin, dependencyOf, optionalDependency, providerDependency, } from '@dokebi/core';
|
|
6
|
+
import Fastify, {} from 'fastify';
|
|
7
|
+
export class WebError extends Error {
|
|
8
|
+
code;
|
|
9
|
+
constructor(code) {
|
|
10
|
+
super(`Web: ${code}`);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.name = 'WebError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** IPv4-mapped IPv6 (`::ffff:127.0.0.1`) compares as plain IPv4. */
|
|
16
|
+
const plainAddress = (address) => address.replace(/^::ffff:(?=\d+\.\d+\.\d+\.\d+$)/, '');
|
|
17
|
+
function trustProxy(input) {
|
|
18
|
+
if (input === undefined)
|
|
19
|
+
return Object.freeze([]);
|
|
20
|
+
if (!Array.isArray(input) ||
|
|
21
|
+
input.length > 64 ||
|
|
22
|
+
!input.every((item) => typeof item === 'string' && isIP(item)))
|
|
23
|
+
throw new WebError('INVALID_OPTIONS');
|
|
24
|
+
return Object.freeze([...new Set(input.map((item) => plainAddress(item)))]);
|
|
25
|
+
}
|
|
26
|
+
const DEFAULT_HEALTH_ROUTES = Object.freeze({
|
|
27
|
+
live: '/health/live',
|
|
28
|
+
ready: '/health/ready',
|
|
29
|
+
});
|
|
30
|
+
/** Copies own string-keyed data properties; Proxies and accessors are rejected unevaluated. */
|
|
31
|
+
function dataRecord(input, keys) {
|
|
32
|
+
if (!input ||
|
|
33
|
+
typeof input !== 'object' ||
|
|
34
|
+
Array.isArray(input) ||
|
|
35
|
+
types.isProxy(input) ||
|
|
36
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
37
|
+
return undefined;
|
|
38
|
+
const result = Object.create(null);
|
|
39
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
40
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
41
|
+
if (typeof key !== 'string' || !descriptor || !('value' in descriptor) || !keys.includes(key))
|
|
42
|
+
return undefined;
|
|
43
|
+
result[key] = descriptor.value;
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
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
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* How long a draining node:cluster worker stays up after it stops listening: enough for any
|
|
102
|
+
* connection the primary was already handing it to be answered "not accepted" and passed on.
|
|
103
|
+
*/
|
|
104
|
+
const CLOSE_GRACE_MS = 100;
|
|
105
|
+
function healthRoutes(input) {
|
|
106
|
+
if (input === undefined)
|
|
107
|
+
return DEFAULT_HEALTH_ROUTES;
|
|
108
|
+
if (input === false)
|
|
109
|
+
return false;
|
|
110
|
+
const value = dataRecord(input, ['live', 'ready']);
|
|
111
|
+
if (!value)
|
|
112
|
+
throw new WebError('INVALID_OPTIONS');
|
|
113
|
+
const live = value.live === undefined ? DEFAULT_HEALTH_ROUTES.live : value.live;
|
|
114
|
+
const ready = value.ready === undefined ? DEFAULT_HEALTH_ROUTES.ready : value.ready;
|
|
115
|
+
if (typeof live !== 'string' ||
|
|
116
|
+
typeof ready !== 'string' ||
|
|
117
|
+
!ROUTE_PATH.test(live) ||
|
|
118
|
+
!ROUTE_PATH.test(ready) ||
|
|
119
|
+
live === ready)
|
|
120
|
+
throw new WebError('INVALID_OPTIONS');
|
|
121
|
+
return Object.freeze({ live, ready });
|
|
122
|
+
}
|
|
123
|
+
function normalize(input) {
|
|
124
|
+
const value = dataRecord(input, [
|
|
125
|
+
'host',
|
|
126
|
+
'port',
|
|
127
|
+
'bodyLimit',
|
|
128
|
+
'requestTimeout',
|
|
129
|
+
'healthRoutes',
|
|
130
|
+
'trustProxy',
|
|
131
|
+
]);
|
|
132
|
+
if (!value)
|
|
133
|
+
throw new WebError('INVALID_OPTIONS');
|
|
134
|
+
const host = value.host === undefined ? '127.0.0.1' : value.host, port = value.port === undefined ? 0 : value.port, bodyLimit = value.bodyLimit === undefined ? 1048576 : value.bodyLimit, requestTimeout = value.requestTimeout === undefined ? 30000 : value.requestTimeout;
|
|
135
|
+
if (typeof host !== 'string' ||
|
|
136
|
+
!host ||
|
|
137
|
+
host.length > 253 ||
|
|
138
|
+
typeof port !== 'number' ||
|
|
139
|
+
!Number.isInteger(port) ||
|
|
140
|
+
port < 0 ||
|
|
141
|
+
port > 65535 ||
|
|
142
|
+
typeof bodyLimit !== 'number' ||
|
|
143
|
+
!Number.isSafeInteger(bodyLimit) ||
|
|
144
|
+
bodyLimit < 1 ||
|
|
145
|
+
bodyLimit > 67108864 ||
|
|
146
|
+
typeof requestTimeout !== 'number' ||
|
|
147
|
+
!Number.isSafeInteger(requestTimeout) ||
|
|
148
|
+
requestTimeout < 1 ||
|
|
149
|
+
requestTimeout > 2147483647)
|
|
150
|
+
throw new WebError('INVALID_OPTIONS');
|
|
151
|
+
return {
|
|
152
|
+
host,
|
|
153
|
+
port,
|
|
154
|
+
bodyLimit,
|
|
155
|
+
requestTimeout,
|
|
156
|
+
healthRoutes: healthRoutes(value.healthRoutes),
|
|
157
|
+
trustProxy: trustProxy(value.trustProxy),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
const hooks = new Map([
|
|
161
|
+
['onRequest', 2],
|
|
162
|
+
['preParsing', 3],
|
|
163
|
+
['preValidation', 2],
|
|
164
|
+
['preHandler', 2],
|
|
165
|
+
['preSerialization', 3],
|
|
166
|
+
['onSend', 3],
|
|
167
|
+
['onResponse', 2],
|
|
168
|
+
['onError', 3],
|
|
169
|
+
['onTimeout', 2],
|
|
170
|
+
['onRequestAbort', 1],
|
|
171
|
+
]);
|
|
172
|
+
class WebOwner {
|
|
173
|
+
context;
|
|
174
|
+
options;
|
|
175
|
+
server;
|
|
176
|
+
#pending = new Set();
|
|
177
|
+
#wrapped = new WeakSet();
|
|
178
|
+
#closed = false;
|
|
179
|
+
#frozen = false;
|
|
180
|
+
#draining = false;
|
|
181
|
+
#address;
|
|
182
|
+
api;
|
|
183
|
+
constructor(context, options, health) {
|
|
184
|
+
this.context = context;
|
|
185
|
+
this.options = options;
|
|
186
|
+
this.server = Fastify({
|
|
187
|
+
logger: false,
|
|
188
|
+
bodyLimit: options.bodyLimit,
|
|
189
|
+
requestTimeout: options.requestTimeout,
|
|
190
|
+
return503OnClosing: true,
|
|
191
|
+
forceCloseConnections: 'idle',
|
|
192
|
+
...(options.trustProxy.length ? { trustProxy: [...options.trustProxy] } : {}),
|
|
193
|
+
});
|
|
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();
|
|
206
|
+
this.server.setErrorHandler((error, request, reply) => {
|
|
207
|
+
const code = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined;
|
|
208
|
+
const status = typeof code === 'number' && code >= 400 && code < 500 ? code : 500;
|
|
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
|
+
});
|
|
232
|
+
reply
|
|
233
|
+
.code(status)
|
|
234
|
+
.send({ error: status === 500 ? 'INTERNAL_SERVER_ERROR' : 'INVALID_REQUEST' });
|
|
235
|
+
});
|
|
236
|
+
this.server.addHook('onRequest', async (request, reply) => {
|
|
237
|
+
if (request.routeOptions.config.dokebiHealth === true)
|
|
238
|
+
return;
|
|
239
|
+
// A draining node:cluster worker no longer listens; a request still arriving on one of its
|
|
240
|
+
// open keep-alive connections is served and that connection then closes, so the client's
|
|
241
|
+
// next request goes to another worker instead of seeing 503 (D-0036).
|
|
242
|
+
const servesWhileDraining = this.#draining && cluster.isWorker;
|
|
243
|
+
if (servesWhileDraining)
|
|
244
|
+
reply.header('connection', 'close');
|
|
245
|
+
const reason = this.#draining
|
|
246
|
+
? servesWhileDraining
|
|
247
|
+
? undefined
|
|
248
|
+
: 'DRAINING'
|
|
249
|
+
: context.app.state !== 'running'
|
|
250
|
+
? 'STARTING'
|
|
251
|
+
: health && !health.ready
|
|
252
|
+
? 'NOT_READY'
|
|
253
|
+
: undefined;
|
|
254
|
+
if (reason) {
|
|
255
|
+
// Why a request was turned away: drain, start not finished, or health not ready.
|
|
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
|
+
});
|
|
262
|
+
return reply
|
|
263
|
+
.code(503)
|
|
264
|
+
.header('connection', 'close')
|
|
265
|
+
.send({ error: 'SERVICE_UNAVAILABLE', reason });
|
|
266
|
+
}
|
|
267
|
+
let release;
|
|
268
|
+
const done = new Promise((resolve) => {
|
|
269
|
+
release = resolve;
|
|
270
|
+
});
|
|
271
|
+
const finish = () => {
|
|
272
|
+
reply.raw.off('finish', finish);
|
|
273
|
+
reply.raw.off('close', finish);
|
|
274
|
+
release();
|
|
275
|
+
if (this.#draining && cluster.isWorker)
|
|
276
|
+
this.server.server.closeIdleConnections();
|
|
277
|
+
};
|
|
278
|
+
reply.raw.once('finish', finish);
|
|
279
|
+
reply.raw.once('close', finish);
|
|
280
|
+
this.#watch(done);
|
|
281
|
+
});
|
|
282
|
+
// Responses already under way when a cluster worker starts draining close their connection
|
|
283
|
+
// too, instead of leaving it idle for the client to reuse (D-0036).
|
|
284
|
+
this.server.addHook('onSend', async (_request, reply, payload) => {
|
|
285
|
+
if (this.#draining && cluster.isWorker)
|
|
286
|
+
reply.header('connection', 'close');
|
|
287
|
+
return payload;
|
|
288
|
+
});
|
|
289
|
+
this.server.addHook('onRoute', (route) => {
|
|
290
|
+
if (route.config?.dokebiHealth === true)
|
|
291
|
+
return;
|
|
292
|
+
const original = route.handler;
|
|
293
|
+
route.handler = function (request, reply) {
|
|
294
|
+
return owner.track(() => original.call(this, request, reply));
|
|
295
|
+
};
|
|
296
|
+
const fields = route;
|
|
297
|
+
for (const name of hooks.keys()) {
|
|
298
|
+
const hook = fields[name];
|
|
299
|
+
if (Array.isArray(hook))
|
|
300
|
+
fields[name] = hook.map((fn) => owner.#hook(name, fn));
|
|
301
|
+
else if (typeof hook === 'function')
|
|
302
|
+
fields[name] = owner.#hook(name, hook);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
// Wrap the public hook registration method; child scopes inherit this with their own receiver.
|
|
306
|
+
const addHook = this.server.addHook;
|
|
307
|
+
this.server.addHook = function (name, hook) {
|
|
308
|
+
return addHook.call(this, name, owner.#hook(name, hook));
|
|
309
|
+
};
|
|
310
|
+
const routes = options.healthRoutes;
|
|
311
|
+
if (routes) {
|
|
312
|
+
this.server.get(routes.live, { config: { dokebiHealth: true } }, async (_request, reply) => {
|
|
313
|
+
const live = health ? health.live : !['failed', 'stopped'].includes(context.app.state);
|
|
314
|
+
return reply.code(live ? 200 : 503).send({ live });
|
|
315
|
+
});
|
|
316
|
+
this.server.get(routes.ready, { config: { dokebiHealth: true } }, async (_request, reply) => {
|
|
317
|
+
const ready = !this.#draining && context.app.state === 'running' && (!health || health.ready);
|
|
318
|
+
return reply.code(ready ? 200 : 503).send({ ready });
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
this.api = Object.freeze({
|
|
322
|
+
get address() {
|
|
323
|
+
return owner.#address;
|
|
324
|
+
},
|
|
325
|
+
route: (route) => {
|
|
326
|
+
this.#assertMutable();
|
|
327
|
+
this.server.route(route);
|
|
328
|
+
},
|
|
329
|
+
register: (plugin, options) => {
|
|
330
|
+
this.#assertMutable();
|
|
331
|
+
this.server.register(plugin, options);
|
|
332
|
+
},
|
|
333
|
+
track: (work) => this.track(work),
|
|
334
|
+
constraint: (strategy) => {
|
|
335
|
+
this.#assertMutable();
|
|
336
|
+
this.server.addConstraintStrategy(strategy);
|
|
337
|
+
},
|
|
338
|
+
requestHost: (request) => {
|
|
339
|
+
const raw = request.raw ?? request;
|
|
340
|
+
const remote = raw.socket?.remoteAddress;
|
|
341
|
+
const forwarded = raw.headers['x-forwarded-host'];
|
|
342
|
+
const value = forwarded !== undefined &&
|
|
343
|
+
remote !== undefined &&
|
|
344
|
+
options.trustProxy.includes(plainAddress(remote))
|
|
345
|
+
? String(Array.isArray(forwarded) ? forwarded[0] : forwarded).split(',')[0]
|
|
346
|
+
: raw.headers.host;
|
|
347
|
+
return String(value ?? '')
|
|
348
|
+
.trim()
|
|
349
|
+
.toLowerCase();
|
|
350
|
+
},
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
#assertMutable() {
|
|
354
|
+
if (this.#frozen || this.#closed)
|
|
355
|
+
throw new WebError('FROZEN');
|
|
356
|
+
}
|
|
357
|
+
#watch(promise) {
|
|
358
|
+
this.#pending.add(promise);
|
|
359
|
+
// Bookkeeping only: the caller holds the same promise and sees its rejection (D-0047).
|
|
360
|
+
void promise.then(() => this.#pending.delete(promise), () => this.#pending.delete(promise));
|
|
361
|
+
return promise;
|
|
362
|
+
}
|
|
363
|
+
track(work) {
|
|
364
|
+
if (this.#closed)
|
|
365
|
+
return Promise.reject(new WebError('CLOSED'));
|
|
366
|
+
return this.#watch(Promise.resolve().then(work));
|
|
367
|
+
}
|
|
368
|
+
#hook(name, fn) {
|
|
369
|
+
const count = hooks.get(name);
|
|
370
|
+
if (count === undefined || typeof fn !== 'function' || this.#wrapped.has(fn))
|
|
371
|
+
return fn;
|
|
372
|
+
if (fn.constructor.name === 'AsyncFunction' &&
|
|
373
|
+
(fn.length === count + 1 || (name === 'onRequestAbort' && fn.length !== 1))) {
|
|
374
|
+
throw new TypeError('Async Fastify hooks must not accept a done callback');
|
|
375
|
+
}
|
|
376
|
+
const owner = this;
|
|
377
|
+
function invoke(instance, args) {
|
|
378
|
+
return owner.track(() => new Promise((resolve, reject) => {
|
|
379
|
+
const reply = name === 'onRequestAbort' ? undefined : args[1];
|
|
380
|
+
let finish;
|
|
381
|
+
let settled = false;
|
|
382
|
+
const clear = () => {
|
|
383
|
+
if (finish)
|
|
384
|
+
reply?.raw.off('finish', finish);
|
|
385
|
+
};
|
|
386
|
+
const done = (error, value) => {
|
|
387
|
+
settled = true;
|
|
388
|
+
clear();
|
|
389
|
+
if (error)
|
|
390
|
+
reject(error);
|
|
391
|
+
else
|
|
392
|
+
resolve(value);
|
|
393
|
+
};
|
|
394
|
+
try {
|
|
395
|
+
const result = fn.apply(instance, [...args, done]);
|
|
396
|
+
if (result && typeof result.then === 'function') {
|
|
397
|
+
Promise.resolve(result).then(resolve, reject);
|
|
398
|
+
}
|
|
399
|
+
else if (!settled && reply && name !== 'onResponse' && name !== 'onError') {
|
|
400
|
+
// Callback hooks may terminate a request by sending a response without done().
|
|
401
|
+
// A socket close alone must never release still-running callback work.
|
|
402
|
+
finish = () => {
|
|
403
|
+
clear();
|
|
404
|
+
resolve(undefined);
|
|
405
|
+
};
|
|
406
|
+
if (reply.raw.writableFinished)
|
|
407
|
+
finish();
|
|
408
|
+
else
|
|
409
|
+
reply.raw.once('finish', finish);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
clear();
|
|
414
|
+
reject(error);
|
|
415
|
+
}
|
|
416
|
+
}));
|
|
417
|
+
}
|
|
418
|
+
const wrapped = name === 'onRequestAbort'
|
|
419
|
+
? async function (request) {
|
|
420
|
+
return invoke(this, [request]);
|
|
421
|
+
}
|
|
422
|
+
: async function (...args) {
|
|
423
|
+
return invoke(this, args.slice(0, count));
|
|
424
|
+
};
|
|
425
|
+
this.#wrapped.add(wrapped);
|
|
426
|
+
return wrapped;
|
|
427
|
+
}
|
|
428
|
+
async start() {
|
|
429
|
+
this.#frozen = true;
|
|
430
|
+
const started = performance.now();
|
|
431
|
+
await this.server.ready();
|
|
432
|
+
this.context.logger.log('debug', 'Web routes frozen', {
|
|
433
|
+
ms: Math.round(performance.now() - started),
|
|
434
|
+
});
|
|
435
|
+
this.context.signal.throwIfAborted();
|
|
436
|
+
// node:cluster shares the port: the primary hands connections to a worker as soon as it
|
|
437
|
+
// listens, so a worker listens only once the whole application is ready (`ready`, D-0034).
|
|
438
|
+
// A single process listens here and answers 503 until then (health checks see it start).
|
|
439
|
+
if (!cluster.isWorker)
|
|
440
|
+
await this.listen();
|
|
441
|
+
}
|
|
442
|
+
async listen() {
|
|
443
|
+
if (this.#address !== undefined)
|
|
444
|
+
return;
|
|
445
|
+
const started = performance.now();
|
|
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
|
+
});
|
|
451
|
+
}
|
|
452
|
+
async drain(signal) {
|
|
453
|
+
this.#draining = true;
|
|
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
|
+
});
|
|
461
|
+
// The node:cluster primary keeps handing new connections to a worker while it listens, so a
|
|
462
|
+
// draining worker stops listening first; new connections go to the other workers. A single
|
|
463
|
+
// process keeps listening and answers 503 so a load balancer's health check sees the drain
|
|
464
|
+
// (D-0023, D-0036).
|
|
465
|
+
// The primary may already be handing this worker a connection when it learns the server
|
|
466
|
+
// closed; the worker answers "not accepted" and the primary passes it on, but only if the
|
|
467
|
+
// worker is still alive. A worker that exited meanwhile strands that connection (the
|
|
468
|
+
// primary never hears back), so a draining worker stays at least CLOSE_GRACE_MS (D-0036).
|
|
469
|
+
// Only the listening socket closes (net level): http's close() would also drop idle
|
|
470
|
+
// keep-alive connections at once, racing clients that are just reusing them. Those
|
|
471
|
+
// connections stay; their next request is served with `Connection: close`.
|
|
472
|
+
let grace;
|
|
473
|
+
if (cluster.isWorker && this.server.server.listening) {
|
|
474
|
+
Server.prototype.close.call(this.server.server);
|
|
475
|
+
grace = delay(CLOSE_GRACE_MS);
|
|
476
|
+
logger.log('debug', 'Web worker stopped listening', { graceMs: CLOSE_GRACE_MS });
|
|
477
|
+
}
|
|
478
|
+
const listening = new AbortController();
|
|
479
|
+
const aborted = new Promise((resolve) => {
|
|
480
|
+
if (signal.aborted)
|
|
481
|
+
resolve();
|
|
482
|
+
else
|
|
483
|
+
signal.addEventListener('abort', () => resolve(), { once: true, signal: listening.signal });
|
|
484
|
+
});
|
|
485
|
+
try {
|
|
486
|
+
while (this.#pending.size) {
|
|
487
|
+
await Promise.race([Promise.allSettled([...this.#pending]), aborted]);
|
|
488
|
+
if (signal.aborted) {
|
|
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
|
+
});
|
|
494
|
+
this.server.server.closeAllConnections();
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
// Fastify can schedule serialization/response hooks after a handler promise resolves.
|
|
498
|
+
await immediate();
|
|
499
|
+
}
|
|
500
|
+
if (grace)
|
|
501
|
+
await Promise.race([grace, aborted]);
|
|
502
|
+
logger.log('debug', 'Web drain finished', { ms: Math.round(performance.now() - started) });
|
|
503
|
+
}
|
|
504
|
+
finally {
|
|
505
|
+
listening.abort();
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
async close() {
|
|
509
|
+
this.#closed = true;
|
|
510
|
+
const started = performance.now();
|
|
511
|
+
await this.server.close();
|
|
512
|
+
this.context.logger.log('debug', 'Web server closed', {
|
|
513
|
+
ms: Math.round(performance.now() - started),
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const HEALTH = 'dokebi-health';
|
|
518
|
+
const health = optionalDependency({ name: HEALTH, version: '^0.1.0' });
|
|
519
|
+
function requirement(value) {
|
|
520
|
+
if (value === null || typeof value !== 'object')
|
|
521
|
+
throw new TypeError('Invalid web requirement');
|
|
522
|
+
if (typeof value.setup === 'function')
|
|
523
|
+
return dependencyOf(value);
|
|
524
|
+
if (typeof value.name !== 'string')
|
|
525
|
+
throw new TypeError('Invalid web requirement');
|
|
526
|
+
return value;
|
|
527
|
+
}
|
|
528
|
+
/** Accepts a plain object or the namespace of the user entry module (src/web/index.ts). */
|
|
529
|
+
function parseEntry(input) {
|
|
530
|
+
if (input === undefined)
|
|
531
|
+
return { requires: [] };
|
|
532
|
+
if (input === null ||
|
|
533
|
+
typeof input !== 'object' ||
|
|
534
|
+
Array.isArray(input) ||
|
|
535
|
+
types.isProxy(input) ||
|
|
536
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
537
|
+
throw new TypeError('Invalid web entry');
|
|
538
|
+
let list;
|
|
539
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
540
|
+
// Module namespaces carry Symbol.toStringTag; only string exports are entry fields.
|
|
541
|
+
if (typeof key !== 'string')
|
|
542
|
+
continue;
|
|
543
|
+
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
544
|
+
if (key !== 'requires' || !descriptor || !('value' in descriptor))
|
|
545
|
+
throw new TypeError('Invalid web entry');
|
|
546
|
+
list = descriptor.value;
|
|
547
|
+
}
|
|
548
|
+
if (list === undefined)
|
|
549
|
+
return { requires: [] };
|
|
550
|
+
if (!Array.isArray(list) || list.length > 256)
|
|
551
|
+
throw new TypeError('Invalid web requires');
|
|
552
|
+
const requires = list.map(requirement);
|
|
553
|
+
const names = new Set(requires.map((dependency) => dependency.name));
|
|
554
|
+
if (names.size !== requires.length || names.has('dokebi-web'))
|
|
555
|
+
throw new TypeError('Duplicate web requirement');
|
|
556
|
+
return { requires };
|
|
557
|
+
}
|
|
558
|
+
class WebRuntime {
|
|
559
|
+
options;
|
|
560
|
+
health;
|
|
561
|
+
#owner;
|
|
562
|
+
constructor(options, health) {
|
|
563
|
+
this.options = options;
|
|
564
|
+
this.health = health;
|
|
565
|
+
}
|
|
566
|
+
setup(context) {
|
|
567
|
+
const owner = new WebOwner(context, this.options, context.getOptionalDependency(this.health));
|
|
568
|
+
this.#owner = owner;
|
|
569
|
+
context.defer(() => owner.close());
|
|
570
|
+
return owner.api;
|
|
571
|
+
}
|
|
572
|
+
start() {
|
|
573
|
+
return this.#owner?.start();
|
|
574
|
+
}
|
|
575
|
+
ready() {
|
|
576
|
+
return cluster.isWorker ? this.#owner?.listen() : undefined;
|
|
577
|
+
}
|
|
578
|
+
drain(context) {
|
|
579
|
+
return this.#owner?.drain(context.drainSignal);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
export const createPlugin = definePlugin({
|
|
583
|
+
name: 'dokebi-web',
|
|
584
|
+
version: '0.1.2',
|
|
585
|
+
core: '^0.2.0',
|
|
586
|
+
options: normalize,
|
|
587
|
+
entry: parseEntry,
|
|
588
|
+
// A required dokebi-health in entry.requires replaces the optional link.
|
|
589
|
+
dependencies: ({ entry }) => {
|
|
590
|
+
const requires = entry?.requires ?? [];
|
|
591
|
+
return requires.some((dependency) => dependency.name === HEALTH)
|
|
592
|
+
? requires
|
|
593
|
+
: [...requires, health];
|
|
594
|
+
},
|
|
595
|
+
instance: ({ options, dependencies }) => new WebRuntime(options, (dependencies.find((dependency) => dependency.name === HEALTH) ??
|
|
596
|
+
health)),
|
|
597
|
+
});
|
|
598
|
+
/** Declares dokebi-web as a required provider; it is created from this package when absent. */
|
|
599
|
+
export const dependency = providerDependency({
|
|
600
|
+
name: 'dokebi-web',
|
|
601
|
+
packageName: '@dokebi/web',
|
|
602
|
+
version: '^0.1.0',
|
|
603
|
+
load: () => import('./index.js'),
|
|
604
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"type": "object",
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"properties": {
|
|
6
|
+
"host": {
|
|
7
|
+
"type": "string",
|
|
8
|
+
"minLength": 1,
|
|
9
|
+
"maxLength": 253,
|
|
10
|
+
"default": "127.0.0.1"
|
|
11
|
+
},
|
|
12
|
+
"port": {
|
|
13
|
+
"type": "integer",
|
|
14
|
+
"minimum": 0,
|
|
15
|
+
"maximum": 65535,
|
|
16
|
+
"default": 0
|
|
17
|
+
},
|
|
18
|
+
"bodyLimit": {
|
|
19
|
+
"type": "integer",
|
|
20
|
+
"minimum": 1,
|
|
21
|
+
"maximum": 67108864,
|
|
22
|
+
"default": 1048576
|
|
23
|
+
},
|
|
24
|
+
"requestTimeout": {
|
|
25
|
+
"type": "integer",
|
|
26
|
+
"minimum": 1,
|
|
27
|
+
"maximum": 2147483647,
|
|
28
|
+
"default": 30000
|
|
29
|
+
},
|
|
30
|
+
"healthRoutes": {
|
|
31
|
+
"default": {
|
|
32
|
+
"live": "/health/live",
|
|
33
|
+
"ready": "/health/ready"
|
|
34
|
+
},
|
|
35
|
+
"oneOf": [
|
|
36
|
+
{
|
|
37
|
+
"const": false
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"type": "object",
|
|
41
|
+
"additionalProperties": false,
|
|
42
|
+
"properties": {
|
|
43
|
+
"live": {
|
|
44
|
+
"type": "string",
|
|
45
|
+
"pattern": "^/[^?#\\s]{0,2047}$",
|
|
46
|
+
"default": "/health/live"
|
|
47
|
+
},
|
|
48
|
+
"ready": {
|
|
49
|
+
"type": "string",
|
|
50
|
+
"pattern": "^/[^?#\\s]{0,2047}$",
|
|
51
|
+
"default": "/health/ready"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
]
|
|
56
|
+
},
|
|
57
|
+
"trustProxy": {
|
|
58
|
+
"type": "array",
|
|
59
|
+
"maxItems": 64,
|
|
60
|
+
"uniqueItems": true,
|
|
61
|
+
"items": {
|
|
62
|
+
"type": "string",
|
|
63
|
+
"minLength": 2,
|
|
64
|
+
"maxLength": 45,
|
|
65
|
+
"description": "IPv4 or IPv6 address"
|
|
66
|
+
},
|
|
67
|
+
"default": [],
|
|
68
|
+
"description": "Proxy addresses whose X-Forwarded-Host/For/Proto are trusted, e.g. [127.0.0.1, ::1] for a local tunnel"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"templates",
|
|
18
|
+
"options.schema.json",
|
|
19
|
+
"README.md",
|
|
20
|
+
"AI.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=24.0.0"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsc -p tsconfig.json",
|
|
28
|
+
"typecheck": "tsc -p tsconfig.test.json --noEmit",
|
|
29
|
+
"test": "tsc -p tsconfig.test.json && node --test .tmp/tests/tests/*.test.js"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@dokebi/core": "^0.2.0"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@dokebi/health": "0.1.2"
|
|
36
|
+
},
|
|
37
|
+
"dokebi": {
|
|
38
|
+
"schemaVersion": 2,
|
|
39
|
+
"id": "dokebi-web",
|
|
40
|
+
"core": "^0.2.0",
|
|
41
|
+
"dependencies": [
|
|
42
|
+
{
|
|
43
|
+
"name": "dokebi-health",
|
|
44
|
+
"version": "^0.1.0",
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
],
|
|
48
|
+
"install": {
|
|
49
|
+
"entry": {
|
|
50
|
+
"source": "templates/web.ts",
|
|
51
|
+
"target": "src/infra/web/requires.ts"
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"optionsSchema": "options.schema.json",
|
|
55
|
+
"documentation": "AI.md"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"fastify": "5.12.7"
|
|
59
|
+
},
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public",
|
|
62
|
+
"registry": "https://registry.npmjs.org/"
|
|
63
|
+
}
|
|
64
|
+
}
|
package/templates/web.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// dokebi-web entry (src/infra/web/requires.ts). List Dokebi plugins (instances or dependency
|
|
2
|
+
// descriptors) that Fastify onClose hooks still use, so they are cleaned up only after the web
|
|
3
|
+
// server has closed. Most projects leave this empty.
|
|
4
|
+
export const requires = [] as const;
|