@mandujs/core 0.9.46 → 0.11.0
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/README.md +79 -10
- package/package.json +1 -1
- package/src/brain/doctor/config-analyzer.ts +498 -0
- package/src/brain/doctor/index.ts +10 -0
- package/src/change/snapshot.ts +46 -1
- package/src/change/types.ts +13 -0
- package/src/config/index.ts +9 -2
- package/src/config/mcp-ref.ts +348 -0
- package/src/config/mcp-status.ts +348 -0
- package/src/config/metadata.test.ts +308 -0
- package/src/config/metadata.ts +293 -0
- package/src/config/symbols.ts +144 -0
- package/src/config/validate.ts +122 -65
- package/src/config/watcher.ts +311 -0
- package/src/contract/index.ts +26 -25
- package/src/contract/protection.ts +364 -0
- package/src/error/domains.ts +265 -0
- package/src/error/index.ts +25 -13
- package/src/errors/extractor.ts +409 -0
- package/src/errors/index.ts +19 -0
- package/src/filling/context.ts +29 -1
- package/src/filling/deps.ts +238 -0
- package/src/filling/filling.ts +94 -8
- package/src/filling/index.ts +18 -0
- package/src/guard/analyzer.ts +7 -2
- package/src/guard/config-guard.ts +281 -0
- package/src/guard/decision-memory.test.ts +293 -0
- package/src/guard/decision-memory.ts +532 -0
- package/src/guard/healing.test.ts +259 -0
- package/src/guard/healing.ts +874 -0
- package/src/guard/index.ts +119 -0
- package/src/guard/negotiation.test.ts +282 -0
- package/src/guard/negotiation.ts +975 -0
- package/src/guard/semantic-slots.test.ts +379 -0
- package/src/guard/semantic-slots.ts +796 -0
- package/src/index.ts +4 -1
- package/src/lockfile/generate.ts +259 -0
- package/src/lockfile/index.ts +186 -0
- package/src/lockfile/lockfile.test.ts +410 -0
- package/src/lockfile/types.ts +184 -0
- package/src/lockfile/validate.ts +308 -0
- package/src/logging/index.ts +22 -0
- package/src/logging/transports.ts +365 -0
- package/src/plugins/index.ts +38 -0
- package/src/plugins/registry.ts +377 -0
- package/src/plugins/types.ts +363 -0
- package/src/runtime/security.ts +155 -0
- package/src/runtime/server.ts +318 -256
- package/src/runtime/session-key.ts +328 -0
- package/src/utils/differ.test.ts +342 -0
- package/src/utils/differ.ts +482 -0
- package/src/utils/hasher.test.ts +326 -0
- package/src/utils/hasher.ts +319 -0
- package/src/utils/index.ts +29 -0
- package/src/utils/safe-io.ts +188 -0
- package/src/utils/string-safe.ts +298 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mandu Lockfile 검증 ✅
|
|
3
|
+
*
|
|
4
|
+
* Lockfile과 현재 설정의 일치 여부 검증
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { diffConfig } from "../utils/differ.js";
|
|
8
|
+
import { computeCurrentHashes, resolveMcpSources } from "./generate.js";
|
|
9
|
+
import {
|
|
10
|
+
type ManduLockfile,
|
|
11
|
+
type LockfileValidationResult,
|
|
12
|
+
type LockfileError,
|
|
13
|
+
type LockfileWarning,
|
|
14
|
+
type LockfileMode,
|
|
15
|
+
type LockfilePolicyOptions,
|
|
16
|
+
DEFAULT_POLICIES,
|
|
17
|
+
LOCKFILE_SCHEMA_VERSION,
|
|
18
|
+
BYPASS_ENV_VAR,
|
|
19
|
+
} from "./types.js";
|
|
20
|
+
|
|
21
|
+
// ============================================
|
|
22
|
+
// 검증
|
|
23
|
+
// ============================================
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Lockfile 검증
|
|
27
|
+
*
|
|
28
|
+
* @param config 현재 설정
|
|
29
|
+
* @param lockfile Lockfile 데이터
|
|
30
|
+
* @returns 검증 결과
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* const lockfile = await readLockfile(projectRoot);
|
|
35
|
+
* if (lockfile) {
|
|
36
|
+
* const result = validateLockfile(config, lockfile);
|
|
37
|
+
* if (!result.valid) {
|
|
38
|
+
* console.error("Lockfile mismatch:", result.errors);
|
|
39
|
+
* }
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function validateLockfile(
|
|
44
|
+
config: Record<string, unknown>,
|
|
45
|
+
lockfile: ManduLockfile,
|
|
46
|
+
mcpConfig?: Record<string, unknown> | null
|
|
47
|
+
): LockfileValidationResult {
|
|
48
|
+
const errors: LockfileError[] = [];
|
|
49
|
+
const warnings: LockfileWarning[] = [];
|
|
50
|
+
|
|
51
|
+
// 현재 해시 계산
|
|
52
|
+
const { configHash, mcpConfigHash } = computeCurrentHashes(config, mcpConfig);
|
|
53
|
+
const { mcpServers } = resolveMcpSources(config, mcpConfig);
|
|
54
|
+
|
|
55
|
+
// 1. 스키마 버전 체크
|
|
56
|
+
if (lockfile.schemaVersion !== LOCKFILE_SCHEMA_VERSION) {
|
|
57
|
+
warnings.push({
|
|
58
|
+
code: "LOCKFILE_OUTDATED",
|
|
59
|
+
message: `Lockfile schema version mismatch: expected ${LOCKFILE_SCHEMA_VERSION}, got ${lockfile.schemaVersion}`,
|
|
60
|
+
details: {
|
|
61
|
+
expected: LOCKFILE_SCHEMA_VERSION,
|
|
62
|
+
actual: lockfile.schemaVersion,
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 2. 설정 해시 비교
|
|
68
|
+
if (configHash !== lockfile.configHash) {
|
|
69
|
+
errors.push({
|
|
70
|
+
code: "CONFIG_HASH_MISMATCH",
|
|
71
|
+
message: "Configuration has changed since lockfile was generated",
|
|
72
|
+
details: {
|
|
73
|
+
expected: lockfile.configHash,
|
|
74
|
+
actual: configHash,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 3. MCP 설정 해시 비교 (있는 경우)
|
|
80
|
+
if (lockfile.mcpConfigHash && mcpConfigHash !== lockfile.mcpConfigHash) {
|
|
81
|
+
errors.push({
|
|
82
|
+
code: "MCP_CONFIG_HASH_MISMATCH",
|
|
83
|
+
message: "MCP configuration has changed since lockfile was generated",
|
|
84
|
+
details: {
|
|
85
|
+
expected: lockfile.mcpConfigHash,
|
|
86
|
+
actual: mcpConfigHash,
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 4. MCP 서버 변경 감지
|
|
92
|
+
if (lockfile.mcpServers && mcpServers) {
|
|
93
|
+
const lockedServers = new Set(Object.keys(lockfile.mcpServers));
|
|
94
|
+
const currentServers = new Set(Object.keys(mcpServers));
|
|
95
|
+
|
|
96
|
+
// 추가된 서버
|
|
97
|
+
for (const server of currentServers) {
|
|
98
|
+
if (!lockedServers.has(server)) {
|
|
99
|
+
warnings.push({
|
|
100
|
+
code: "MCP_SERVER_ADDED",
|
|
101
|
+
message: `MCP server "${server}" was added`,
|
|
102
|
+
details: { server },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 삭제된 서버
|
|
108
|
+
for (const server of lockedServers) {
|
|
109
|
+
if (!currentServers.has(server)) {
|
|
110
|
+
warnings.push({
|
|
111
|
+
code: "MCP_SERVER_REMOVED",
|
|
112
|
+
message: `MCP server "${server}" was removed`,
|
|
113
|
+
details: { server },
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 5. 스냅샷 누락 경고
|
|
120
|
+
if (!lockfile.snapshot) {
|
|
121
|
+
warnings.push({
|
|
122
|
+
code: "SNAPSHOT_MISSING",
|
|
123
|
+
message: "Lockfile does not include configuration snapshot",
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 6. Diff 계산 (오류가 있는 경우에만)
|
|
128
|
+
let diff;
|
|
129
|
+
if (errors.length > 0 && lockfile.snapshot) {
|
|
130
|
+
const configForDiff = mcpServers
|
|
131
|
+
? { ...config, mcpServers }
|
|
132
|
+
: config;
|
|
133
|
+
diff = diffConfig(lockfile.snapshot.config, configForDiff);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
valid: errors.length === 0,
|
|
138
|
+
errors,
|
|
139
|
+
warnings,
|
|
140
|
+
diff,
|
|
141
|
+
currentHash: configHash,
|
|
142
|
+
lockedHash: lockfile.configHash,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ============================================
|
|
147
|
+
// 정책 기반 검증
|
|
148
|
+
// ============================================
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 환경 정책에 따른 검증 수행
|
|
152
|
+
*/
|
|
153
|
+
export function validateWithPolicy(
|
|
154
|
+
config: Record<string, unknown>,
|
|
155
|
+
lockfile: ManduLockfile | null,
|
|
156
|
+
mode?: LockfileMode,
|
|
157
|
+
mcpConfig?: Record<string, unknown> | null
|
|
158
|
+
): {
|
|
159
|
+
result: LockfileValidationResult | null;
|
|
160
|
+
action: "pass" | "warn" | "error" | "block";
|
|
161
|
+
bypassed: boolean;
|
|
162
|
+
} {
|
|
163
|
+
const resolvedMode = mode ?? detectMode();
|
|
164
|
+
const policy = DEFAULT_POLICIES[resolvedMode];
|
|
165
|
+
const bypassed = isBypassed();
|
|
166
|
+
|
|
167
|
+
// Lockfile 없는 경우
|
|
168
|
+
if (!lockfile) {
|
|
169
|
+
const action = bypassed ? "warn" : policy.onMissing;
|
|
170
|
+
return {
|
|
171
|
+
result: null,
|
|
172
|
+
action: action === "create" ? "warn" : action,
|
|
173
|
+
bypassed,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// 검증 수행
|
|
178
|
+
const result = validateLockfile(config, lockfile, mcpConfig);
|
|
179
|
+
|
|
180
|
+
// 통과
|
|
181
|
+
if (result.valid) {
|
|
182
|
+
return { result, action: "pass", bypassed };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 불일치 시 정책 적용
|
|
186
|
+
const action = bypassed ? "warn" : policy.onMismatch;
|
|
187
|
+
return { result, action, bypassed };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 현재 모드 감지
|
|
192
|
+
*/
|
|
193
|
+
export function detectMode(): LockfileMode {
|
|
194
|
+
// CI 환경
|
|
195
|
+
if (
|
|
196
|
+
process.env.CI === "true" ||
|
|
197
|
+
process.env.GITHUB_ACTIONS === "true" ||
|
|
198
|
+
process.env.GITLAB_CI === "true"
|
|
199
|
+
) {
|
|
200
|
+
return "ci";
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// 빌드 모드 (npm run build 등)
|
|
204
|
+
if (process.env.npm_lifecycle_event === "build") {
|
|
205
|
+
return "build";
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// 프로덕션
|
|
209
|
+
if (process.env.NODE_ENV === "production") {
|
|
210
|
+
return "production";
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return "development";
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 우회 환경변수 체크
|
|
218
|
+
*/
|
|
219
|
+
export function isBypassed(): boolean {
|
|
220
|
+
return process.env[BYPASS_ENV_VAR] === "1" || process.env[BYPASS_ENV_VAR] === "true";
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ============================================
|
|
224
|
+
// 빠른 검증
|
|
225
|
+
// ============================================
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* 해시만 빠르게 비교
|
|
229
|
+
*/
|
|
230
|
+
export function quickValidate(
|
|
231
|
+
config: Record<string, unknown>,
|
|
232
|
+
lockfile: ManduLockfile,
|
|
233
|
+
mcpConfig?: Record<string, unknown> | null
|
|
234
|
+
): boolean {
|
|
235
|
+
const { configHash } = computeCurrentHashes(config, mcpConfig);
|
|
236
|
+
return configHash === lockfile.configHash;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Lockfile이 최신인지 확인
|
|
241
|
+
*/
|
|
242
|
+
export function isLockfileStale(
|
|
243
|
+
config: Record<string, unknown>,
|
|
244
|
+
lockfile: ManduLockfile,
|
|
245
|
+
mcpConfig?: Record<string, unknown> | null
|
|
246
|
+
): boolean {
|
|
247
|
+
return !quickValidate(config, lockfile, mcpConfig);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ============================================
|
|
251
|
+
// 검증 결과 포맷팅
|
|
252
|
+
// ============================================
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 검증 결과를 콘솔 메시지로 변환
|
|
256
|
+
*/
|
|
257
|
+
export function formatValidationResult(
|
|
258
|
+
result: LockfileValidationResult
|
|
259
|
+
): string {
|
|
260
|
+
const lines: string[] = [];
|
|
261
|
+
|
|
262
|
+
if (result.valid) {
|
|
263
|
+
lines.push("✅ Lockfile 검증 통과");
|
|
264
|
+
lines.push(` 해시: ${result.currentHash}`);
|
|
265
|
+
} else {
|
|
266
|
+
lines.push("❌ Lockfile 검증 실패");
|
|
267
|
+
lines.push("");
|
|
268
|
+
|
|
269
|
+
for (const error of result.errors) {
|
|
270
|
+
lines.push(` 🔴 ${error.message}`);
|
|
271
|
+
if (error.details) {
|
|
272
|
+
lines.push(` 예상: ${error.details.expected}`);
|
|
273
|
+
lines.push(` 실제: ${error.details.actual}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (result.warnings.length > 0) {
|
|
279
|
+
lines.push("");
|
|
280
|
+
lines.push(" 경고:");
|
|
281
|
+
for (const warning of result.warnings) {
|
|
282
|
+
lines.push(` ⚠️ ${warning.message}`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return lines.join("\n");
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* 정책 액션에 따른 메시지 생성
|
|
291
|
+
*/
|
|
292
|
+
export function formatPolicyAction(
|
|
293
|
+
action: "pass" | "warn" | "error" | "block",
|
|
294
|
+
bypassed: boolean
|
|
295
|
+
): string {
|
|
296
|
+
const bypassNote = bypassed ? " (우회됨)" : "";
|
|
297
|
+
|
|
298
|
+
switch (action) {
|
|
299
|
+
case "pass":
|
|
300
|
+
return "✅ Lockfile 검증 통과";
|
|
301
|
+
case "warn":
|
|
302
|
+
return `⚠️ Lockfile 불일치 - 경고${bypassNote}`;
|
|
303
|
+
case "error":
|
|
304
|
+
return `❌ Lockfile 불일치 - 빌드 실패${bypassNote}`;
|
|
305
|
+
case "block":
|
|
306
|
+
return `🛑 Lockfile 불일치 - 서버 시작 차단${bypassNote}`;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DNA-008: Structured Logging System
|
|
3
|
+
*
|
|
4
|
+
* 구조화된 로깅 시스템
|
|
5
|
+
* - Transport 기반 다중 출력
|
|
6
|
+
* - 동적 전송 추가/제거
|
|
7
|
+
* - 레벨별 필터링
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
transportRegistry,
|
|
12
|
+
attachLogTransport,
|
|
13
|
+
detachLogTransport,
|
|
14
|
+
entryToTransportRecord,
|
|
15
|
+
createConsoleTransport,
|
|
16
|
+
createBufferTransport,
|
|
17
|
+
createFilteredTransport,
|
|
18
|
+
createBatchTransport,
|
|
19
|
+
type LogTransport,
|
|
20
|
+
type LogTransportRecord,
|
|
21
|
+
type TransportRegistration,
|
|
22
|
+
} from "./transports.js";
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DNA-008: Structured Logging - Transport System
|
|
3
|
+
*
|
|
4
|
+
* 로그 전송 레지스트리
|
|
5
|
+
* - 다중 전송 지원 (콘솔, 파일, 외부 서비스)
|
|
6
|
+
* - 동적 전송 추가/제거
|
|
7
|
+
* - 레벨별 필터링
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { LogLevel, LogEntry } from "../runtime/logger.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 로그 전송 레코드 (Transport에 전달되는 데이터)
|
|
14
|
+
*/
|
|
15
|
+
export interface LogTransportRecord {
|
|
16
|
+
/** 타임스탬프 (ISO 문자열) */
|
|
17
|
+
timestamp: string;
|
|
18
|
+
/** 로그 레벨 */
|
|
19
|
+
level: LogLevel;
|
|
20
|
+
/** 요청 ID */
|
|
21
|
+
requestId?: string;
|
|
22
|
+
/** HTTP 메서드 */
|
|
23
|
+
method?: string;
|
|
24
|
+
/** 요청 경로 */
|
|
25
|
+
path?: string;
|
|
26
|
+
/** HTTP 상태 코드 */
|
|
27
|
+
status?: number;
|
|
28
|
+
/** 응답 시간 (ms) */
|
|
29
|
+
duration?: number;
|
|
30
|
+
/** 에러 정보 */
|
|
31
|
+
error?: {
|
|
32
|
+
message: string;
|
|
33
|
+
stack?: string;
|
|
34
|
+
code?: string;
|
|
35
|
+
};
|
|
36
|
+
/** 커스텀 메타데이터 */
|
|
37
|
+
meta?: Record<string, unknown>;
|
|
38
|
+
/** 느린 요청 여부 */
|
|
39
|
+
slow?: boolean;
|
|
40
|
+
/** 원본 LogEntry (필요시 접근) */
|
|
41
|
+
raw?: LogEntry;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 로그 전송 함수 타입
|
|
46
|
+
*/
|
|
47
|
+
export type LogTransport = (record: LogTransportRecord) => void | Promise<void>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 전송 등록 정보
|
|
51
|
+
*/
|
|
52
|
+
export interface TransportRegistration {
|
|
53
|
+
/** 전송 ID */
|
|
54
|
+
id: string;
|
|
55
|
+
/** 전송 함수 */
|
|
56
|
+
transport: LogTransport;
|
|
57
|
+
/** 최소 로그 레벨 (이 레벨 이상만 전송) */
|
|
58
|
+
minLevel?: LogLevel;
|
|
59
|
+
/** 활성화 여부 */
|
|
60
|
+
enabled: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 로그 레벨 우선순위
|
|
65
|
+
*/
|
|
66
|
+
const LEVEL_PRIORITY: Record<LogLevel, number> = {
|
|
67
|
+
debug: 0,
|
|
68
|
+
info: 1,
|
|
69
|
+
warn: 2,
|
|
70
|
+
error: 3,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 전역 전송 레지스트리
|
|
75
|
+
*/
|
|
76
|
+
class TransportRegistry {
|
|
77
|
+
private transports = new Map<string, TransportRegistration>();
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 전송 추가
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* attachLogTransport("file", async (record) => {
|
|
85
|
+
* await appendFile("app.log", JSON.stringify(record) + "\n");
|
|
86
|
+
* });
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
attach(
|
|
90
|
+
id: string,
|
|
91
|
+
transport: LogTransport,
|
|
92
|
+
options: { minLevel?: LogLevel; enabled?: boolean } = {}
|
|
93
|
+
): void {
|
|
94
|
+
this.transports.set(id, {
|
|
95
|
+
id,
|
|
96
|
+
transport,
|
|
97
|
+
minLevel: options.minLevel,
|
|
98
|
+
enabled: options.enabled ?? true,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 전송 제거
|
|
104
|
+
*/
|
|
105
|
+
detach(id: string): boolean {
|
|
106
|
+
return this.transports.delete(id);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 전송 활성화/비활성화
|
|
111
|
+
*/
|
|
112
|
+
setEnabled(id: string, enabled: boolean): void {
|
|
113
|
+
const registration = this.transports.get(id);
|
|
114
|
+
if (registration) {
|
|
115
|
+
registration.enabled = enabled;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 모든 전송에 로그 전달
|
|
121
|
+
*/
|
|
122
|
+
async dispatch(record: LogTransportRecord): Promise<void> {
|
|
123
|
+
const recordLevel = LEVEL_PRIORITY[record.level];
|
|
124
|
+
|
|
125
|
+
const promises: Promise<void>[] = [];
|
|
126
|
+
|
|
127
|
+
for (const registration of this.transports.values()) {
|
|
128
|
+
if (!registration.enabled) continue;
|
|
129
|
+
|
|
130
|
+
// 레벨 필터링
|
|
131
|
+
if (registration.minLevel) {
|
|
132
|
+
const minLevel = LEVEL_PRIORITY[registration.minLevel];
|
|
133
|
+
if (recordLevel < minLevel) continue;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
const result = registration.transport(record);
|
|
138
|
+
if (result instanceof Promise) {
|
|
139
|
+
promises.push(result.catch((err) => {
|
|
140
|
+
console.error(`[Log Transport] Error in ${registration.id}:`, err);
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
} catch (err) {
|
|
144
|
+
console.error(`[Log Transport] Error in ${registration.id}:`, err);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
await Promise.all(promises);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 동기적으로 모든 전송에 로그 전달 (비동기 전송은 fire-and-forget)
|
|
153
|
+
*/
|
|
154
|
+
dispatchSync(record: LogTransportRecord): void {
|
|
155
|
+
const recordLevel = LEVEL_PRIORITY[record.level];
|
|
156
|
+
|
|
157
|
+
for (const registration of this.transports.values()) {
|
|
158
|
+
if (!registration.enabled) continue;
|
|
159
|
+
|
|
160
|
+
if (registration.minLevel) {
|
|
161
|
+
const minLevel = LEVEL_PRIORITY[registration.minLevel];
|
|
162
|
+
if (recordLevel < minLevel) continue;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
const result = registration.transport(record);
|
|
167
|
+
if (result instanceof Promise) {
|
|
168
|
+
// 비동기 결과는 무시 (fire-and-forget)
|
|
169
|
+
result.catch((err) => {
|
|
170
|
+
console.error(`[Log Transport] Error in ${registration.id}:`, err);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
} catch (err) {
|
|
174
|
+
console.error(`[Log Transport] Error in ${registration.id}:`, err);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 등록된 전송 목록
|
|
181
|
+
*/
|
|
182
|
+
list(): TransportRegistration[] {
|
|
183
|
+
return Array.from(this.transports.values());
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* 전송 존재 여부
|
|
188
|
+
*/
|
|
189
|
+
has(id: string): boolean {
|
|
190
|
+
return this.transports.has(id);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 모든 전송 제거
|
|
195
|
+
*/
|
|
196
|
+
clear(): void {
|
|
197
|
+
this.transports.clear();
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 전송 개수
|
|
202
|
+
*/
|
|
203
|
+
get size(): number {
|
|
204
|
+
return this.transports.size;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* 전역 전송 레지스트리 인스턴스
|
|
210
|
+
*/
|
|
211
|
+
export const transportRegistry = new TransportRegistry();
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 로그 전송 추가 (편의 함수)
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```ts
|
|
218
|
+
* // 파일 전송
|
|
219
|
+
* attachLogTransport("file", async (record) => {
|
|
220
|
+
* await fs.appendFile("app.log", JSON.stringify(record) + "\n");
|
|
221
|
+
* }, { minLevel: "info" });
|
|
222
|
+
*
|
|
223
|
+
* // 외부 서비스 전송
|
|
224
|
+
* attachLogTransport("datadog", async (record) => {
|
|
225
|
+
* await fetch("https://http-intake.logs.datadoghq.com/...", {
|
|
226
|
+
* method: "POST",
|
|
227
|
+
* body: JSON.stringify(record),
|
|
228
|
+
* });
|
|
229
|
+
* }, { minLevel: "warn" });
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
export function attachLogTransport(
|
|
233
|
+
id: string,
|
|
234
|
+
transport: LogTransport,
|
|
235
|
+
options?: { minLevel?: LogLevel; enabled?: boolean }
|
|
236
|
+
): void {
|
|
237
|
+
transportRegistry.attach(id, transport, options);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 로그 전송 제거 (편의 함수)
|
|
242
|
+
*/
|
|
243
|
+
export function detachLogTransport(id: string): boolean {
|
|
244
|
+
return transportRegistry.detach(id);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* LogEntry를 LogTransportRecord로 변환
|
|
249
|
+
*/
|
|
250
|
+
export function entryToTransportRecord(entry: LogEntry): LogTransportRecord {
|
|
251
|
+
return {
|
|
252
|
+
timestamp: entry.timestamp,
|
|
253
|
+
level: entry.level,
|
|
254
|
+
requestId: entry.requestId,
|
|
255
|
+
method: entry.method,
|
|
256
|
+
path: entry.path,
|
|
257
|
+
status: entry.status,
|
|
258
|
+
duration: entry.duration,
|
|
259
|
+
error: entry.error ? {
|
|
260
|
+
message: entry.error.message,
|
|
261
|
+
stack: entry.error.stack,
|
|
262
|
+
} : undefined,
|
|
263
|
+
slow: entry.slow,
|
|
264
|
+
raw: entry,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ============================================
|
|
269
|
+
// Built-in Transports
|
|
270
|
+
// ============================================
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* 콘솔 전송 (기본)
|
|
274
|
+
*/
|
|
275
|
+
export function createConsoleTransport(options: {
|
|
276
|
+
format?: "json" | "pretty";
|
|
277
|
+
} = {}): LogTransport {
|
|
278
|
+
const { format = "pretty" } = options;
|
|
279
|
+
|
|
280
|
+
return (record) => {
|
|
281
|
+
const output = format === "json"
|
|
282
|
+
? JSON.stringify(record)
|
|
283
|
+
: `[${record.timestamp}] ${record.level.toUpperCase()} ${record.method ?? ""} ${record.path ?? ""} ${record.status ?? ""} ${record.duration ? record.duration.toFixed(0) + "ms" : ""}`;
|
|
284
|
+
|
|
285
|
+
switch (record.level) {
|
|
286
|
+
case "error":
|
|
287
|
+
console.error(output);
|
|
288
|
+
break;
|
|
289
|
+
case "warn":
|
|
290
|
+
console.warn(output);
|
|
291
|
+
break;
|
|
292
|
+
default:
|
|
293
|
+
console.log(output);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* 메모리 버퍼 전송 (테스트용)
|
|
300
|
+
*/
|
|
301
|
+
export function createBufferTransport(buffer: LogTransportRecord[]): LogTransport {
|
|
302
|
+
return (record) => {
|
|
303
|
+
buffer.push(record);
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 필터링 전송 래퍼
|
|
309
|
+
*/
|
|
310
|
+
export function createFilteredTransport(
|
|
311
|
+
transport: LogTransport,
|
|
312
|
+
filter: (record: LogTransportRecord) => boolean
|
|
313
|
+
): LogTransport {
|
|
314
|
+
return (record) => {
|
|
315
|
+
if (filter(record)) {
|
|
316
|
+
return transport(record);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* 배치 전송 (성능 최적화)
|
|
323
|
+
*/
|
|
324
|
+
export function createBatchTransport(
|
|
325
|
+
flush: (records: LogTransportRecord[]) => void | Promise<void>,
|
|
326
|
+
options: {
|
|
327
|
+
maxSize?: number;
|
|
328
|
+
flushInterval?: number;
|
|
329
|
+
} = {}
|
|
330
|
+
): { transport: LogTransport; flush: () => Promise<void>; stop: () => void } {
|
|
331
|
+
const { maxSize = 100, flushInterval = 5000 } = options;
|
|
332
|
+
|
|
333
|
+
const buffer: LogTransportRecord[] = [];
|
|
334
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
335
|
+
|
|
336
|
+
const doFlush = async () => {
|
|
337
|
+
if (buffer.length === 0) return;
|
|
338
|
+
const records = buffer.splice(0, buffer.length);
|
|
339
|
+
await flush(records);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
timer = setInterval(() => {
|
|
343
|
+
doFlush().catch((err) => {
|
|
344
|
+
console.error("[Batch Transport] Flush error:", err);
|
|
345
|
+
});
|
|
346
|
+
}, flushInterval);
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
transport: (record) => {
|
|
350
|
+
buffer.push(record);
|
|
351
|
+
if (buffer.length >= maxSize) {
|
|
352
|
+
doFlush().catch((err) => {
|
|
353
|
+
console.error("[Batch Transport] Flush error:", err);
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
},
|
|
357
|
+
flush: doFlush,
|
|
358
|
+
stop: () => {
|
|
359
|
+
if (timer) {
|
|
360
|
+
clearInterval(timer);
|
|
361
|
+
timer = null;
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
}
|