@k-msg/webhook 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/dist/index.d.cts DELETED
@@ -1,1135 +0,0 @@
1
- import { z } from 'zod';
2
- import { EventEmitter } from 'events';
3
-
4
- interface WebhookConfig {
5
- maxRetries: number;
6
- retryDelayMs: number;
7
- maxDelayMs?: number;
8
- backoffMultiplier?: number;
9
- jitter?: boolean;
10
- timeoutMs: number;
11
- enableSecurity: boolean;
12
- secretKey?: string;
13
- algorithm?: 'sha256' | 'sha1';
14
- signatureHeader?: string;
15
- signaturePrefix?: string;
16
- enabledEvents: WebhookEventType[];
17
- batchSize: number;
18
- batchTimeoutMs: number;
19
- }
20
- declare enum WebhookEventType {
21
- MESSAGE_SENT = "message.sent",
22
- MESSAGE_DELIVERED = "message.delivered",
23
- MESSAGE_FAILED = "message.failed",
24
- MESSAGE_CLICKED = "message.clicked",
25
- MESSAGE_READ = "message.read",
26
- TEMPLATE_CREATED = "template.created",
27
- TEMPLATE_APPROVED = "template.approved",
28
- TEMPLATE_REJECTED = "template.rejected",
29
- TEMPLATE_UPDATED = "template.updated",
30
- TEMPLATE_DELETED = "template.deleted",
31
- CHANNEL_CREATED = "channel.created",
32
- CHANNEL_VERIFIED = "channel.verified",
33
- SENDER_NUMBER_ADDED = "sender_number.added",
34
- SENDER_NUMBER_VERIFIED = "sender_number.verified",
35
- QUOTA_WARNING = "system.quota_warning",
36
- QUOTA_EXCEEDED = "system.quota_exceeded",
37
- PROVIDER_ERROR = "system.provider_error",
38
- SYSTEM_MAINTENANCE = "system.maintenance",
39
- ANOMALY_DETECTED = "analytics.anomaly_detected",
40
- THRESHOLD_EXCEEDED = "analytics.threshold_exceeded"
41
- }
42
- interface WebhookEvent<T = any> {
43
- id: string;
44
- type: WebhookEventType;
45
- timestamp: Date;
46
- data: T;
47
- metadata: {
48
- providerId?: string;
49
- channelId?: string;
50
- templateId?: string;
51
- messageId?: string;
52
- userId?: string;
53
- organizationId?: string;
54
- correlationId?: string;
55
- retryCount?: number;
56
- };
57
- version: string;
58
- }
59
- interface WebhookEndpoint {
60
- id: string;
61
- url: string;
62
- name?: string;
63
- description?: string;
64
- active: boolean;
65
- events: WebhookEventType[];
66
- headers?: Record<string, string>;
67
- secret?: string;
68
- retryConfig?: {
69
- maxRetries: number;
70
- retryDelayMs: number;
71
- backoffMultiplier: number;
72
- };
73
- filters?: {
74
- providerId?: string[];
75
- channelId?: string[];
76
- templateId?: string[];
77
- };
78
- createdAt: Date;
79
- updatedAt: Date;
80
- lastTriggeredAt?: Date;
81
- status: 'active' | 'inactive' | 'error' | 'suspended';
82
- }
83
- interface WebhookDelivery {
84
- id: string;
85
- endpointId: string;
86
- eventId: string;
87
- url: string;
88
- httpMethod: 'POST' | 'PUT' | 'PATCH';
89
- headers: Record<string, string>;
90
- payload: string;
91
- attempts: WebhookAttempt[];
92
- status: 'pending' | 'success' | 'failed' | 'exhausted';
93
- createdAt: Date;
94
- completedAt?: Date;
95
- nextRetryAt?: Date;
96
- }
97
- interface WebhookAttempt {
98
- attemptNumber: number;
99
- timestamp: Date;
100
- httpStatus?: number;
101
- responseBody?: string;
102
- responseHeaders?: Record<string, string>;
103
- error?: string;
104
- latencyMs: number;
105
- }
106
- interface WebhookSecurity {
107
- algorithm: 'sha256' | 'sha1';
108
- header: string;
109
- prefix?: string;
110
- }
111
- interface WebhookBatch {
112
- id: string;
113
- endpointId: string;
114
- events: WebhookEvent[];
115
- createdAt: Date;
116
- scheduledAt: Date;
117
- status: 'pending' | 'processing' | 'completed' | 'failed';
118
- }
119
- interface WebhookStats {
120
- endpointId: string;
121
- timeRange: {
122
- start: Date;
123
- end: Date;
124
- };
125
- totalDeliveries: number;
126
- successfulDeliveries: number;
127
- failedDeliveries: number;
128
- averageLatencyMs: number;
129
- successRate: number;
130
- eventBreakdown: Record<WebhookEventType, number>;
131
- errorBreakdown: Record<string, number>;
132
- }
133
- interface WebhookTestResult {
134
- endpointId: string;
135
- url: string;
136
- success: boolean;
137
- httpStatus?: number;
138
- responseTime: number;
139
- error?: string;
140
- testedAt: Date;
141
- }
142
- declare const WebhookEventSchema: z.ZodObject<{
143
- id: z.ZodString;
144
- type: z.ZodString;
145
- timestamp: z.ZodDate;
146
- data: z.ZodAny;
147
- metadata: z.ZodObject<{
148
- providerId: z.ZodOptional<z.ZodString>;
149
- channelId: z.ZodOptional<z.ZodString>;
150
- templateId: z.ZodOptional<z.ZodString>;
151
- messageId: z.ZodOptional<z.ZodString>;
152
- userId: z.ZodOptional<z.ZodString>;
153
- organizationId: z.ZodOptional<z.ZodString>;
154
- correlationId: z.ZodOptional<z.ZodString>;
155
- retryCount: z.ZodOptional<z.ZodNumber>;
156
- }, z.core.$strip>;
157
- version: z.ZodString;
158
- }, z.core.$strip>;
159
- declare const WebhookEndpointSchema: z.ZodObject<{
160
- id: z.ZodString;
161
- url: z.ZodString;
162
- name: z.ZodOptional<z.ZodString>;
163
- description: z.ZodOptional<z.ZodString>;
164
- active: z.ZodBoolean;
165
- events: z.ZodArray<z.ZodString>;
166
- headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
167
- secret: z.ZodOptional<z.ZodString>;
168
- retryConfig: z.ZodOptional<z.ZodObject<{
169
- maxRetries: z.ZodNumber;
170
- retryDelayMs: z.ZodNumber;
171
- backoffMultiplier: z.ZodNumber;
172
- }, z.core.$strip>>;
173
- filters: z.ZodOptional<z.ZodObject<{
174
- providerId: z.ZodOptional<z.ZodArray<z.ZodString>>;
175
- channelId: z.ZodOptional<z.ZodArray<z.ZodString>>;
176
- templateId: z.ZodOptional<z.ZodArray<z.ZodString>>;
177
- }, z.core.$strip>>;
178
- createdAt: z.ZodDate;
179
- updatedAt: z.ZodDate;
180
- lastTriggeredAt: z.ZodOptional<z.ZodDate>;
181
- status: z.ZodEnum<{
182
- active: "active";
183
- inactive: "inactive";
184
- error: "error";
185
- suspended: "suspended";
186
- }>;
187
- }, z.core.$strip>;
188
- declare const WebhookDeliverySchema: z.ZodObject<{
189
- id: z.ZodString;
190
- endpointId: z.ZodString;
191
- eventId: z.ZodString;
192
- url: z.ZodString;
193
- httpMethod: z.ZodEnum<{
194
- POST: "POST";
195
- PUT: "PUT";
196
- PATCH: "PATCH";
197
- }>;
198
- headers: z.ZodRecord<z.ZodString, z.ZodString>;
199
- payload: z.ZodString;
200
- attempts: z.ZodArray<z.ZodObject<{
201
- attemptNumber: z.ZodNumber;
202
- timestamp: z.ZodDate;
203
- httpStatus: z.ZodOptional<z.ZodNumber>;
204
- responseBody: z.ZodOptional<z.ZodString>;
205
- responseHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
206
- error: z.ZodOptional<z.ZodString>;
207
- latencyMs: z.ZodNumber;
208
- }, z.core.$strip>>;
209
- status: z.ZodEnum<{
210
- pending: "pending";
211
- success: "success";
212
- failed: "failed";
213
- exhausted: "exhausted";
214
- }>;
215
- createdAt: z.ZodDate;
216
- completedAt: z.ZodOptional<z.ZodDate>;
217
- nextRetryAt: z.ZodOptional<z.ZodDate>;
218
- }, z.core.$strip>;
219
- type WebhookEventData = z.infer<typeof WebhookEventSchema>;
220
- type WebhookEndpointData = z.infer<typeof WebhookEndpointSchema>;
221
- type WebhookDeliveryData = z.infer<typeof WebhookDeliverySchema>;
222
-
223
- declare class WebhookService {
224
- private config;
225
- private dispatcher;
226
- private registry;
227
- private securityManager;
228
- private retryManager;
229
- private eventQueue;
230
- private batchProcessor;
231
- constructor(config: WebhookConfig);
232
- /**
233
- * 웹훅 엔드포인트 등록
234
- */
235
- registerEndpoint(endpoint: Omit<WebhookEndpoint, 'id' | 'createdAt' | 'updatedAt' | 'status'>): Promise<WebhookEndpoint>;
236
- /**
237
- * 웹훅 엔드포인트 수정
238
- */
239
- updateEndpoint(endpointId: string, updates: Partial<WebhookEndpoint>): Promise<WebhookEndpoint>;
240
- /**
241
- * 웹훅 엔드포인트 삭제
242
- */
243
- deleteEndpoint(endpointId: string): Promise<void>;
244
- /**
245
- * 웹훅 엔드포인트 조회
246
- */
247
- getEndpoint(endpointId: string): Promise<WebhookEndpoint | null>;
248
- /**
249
- * 모든 웹훅 엔드포인트 조회
250
- */
251
- listEndpoints(): Promise<WebhookEndpoint[]>;
252
- /**
253
- * 이벤트 발생 (비동기 처리)
254
- */
255
- emit(event: WebhookEvent): Promise<void>;
256
- /**
257
- * 이벤트 발생 (동기 처리)
258
- */
259
- emitSync(event: WebhookEvent): Promise<WebhookDelivery[]>;
260
- /**
261
- * 웹훅 엔드포인트 테스트
262
- */
263
- testEndpoint(endpointId: string): Promise<WebhookTestResult>;
264
- /**
265
- * 웹훅 통계 조회
266
- */
267
- getStats(endpointId: string, timeRange: {
268
- start: Date;
269
- end: Date;
270
- }): Promise<WebhookStats>;
271
- /**
272
- * 실패한 웹훅 재시도
273
- */
274
- retryFailed(endpointId?: string, eventType?: WebhookEventType): Promise<number>;
275
- /**
276
- * 웹훅 일시 중단
277
- */
278
- pauseEndpoint(endpointId: string): Promise<void>;
279
- /**
280
- * 웹훅 재개
281
- */
282
- resumeEndpoint(endpointId: string): Promise<void>;
283
- /**
284
- * 웹훅 전달 내역 조회
285
- */
286
- getDeliveries(endpointId?: string, eventType?: WebhookEventType, status?: string, limit?: number): Promise<WebhookDelivery[]>;
287
- private processBatch;
288
- private getMatchingEndpoints;
289
- private validateEvent;
290
- private validateEndpointUrl;
291
- private generateEndpointId;
292
- private startBatchProcessor;
293
- /**
294
- * 서비스 종료 시 정리
295
- */
296
- shutdown(): Promise<void>;
297
- }
298
-
299
- declare class WebhookDispatcher {
300
- private config;
301
- constructor(config: WebhookConfig);
302
- dispatch(event: WebhookEvent, endpoint: WebhookEndpoint): Promise<WebhookDelivery>;
303
- private executeDelivery;
304
- private makeHttpRequest;
305
- private buildHeaders;
306
- private generateSignature;
307
- private calculateRetryDelay;
308
- private sleep;
309
- private generateDeliveryId;
310
- shutdown(): Promise<void>;
311
- }
312
-
313
- declare class WebhookRegistry {
314
- private endpoints;
315
- private deliveries;
316
- addEndpoint(endpoint: WebhookEndpoint): Promise<void>;
317
- updateEndpoint(endpointId: string, endpoint: WebhookEndpoint): Promise<void>;
318
- removeEndpoint(endpointId: string): Promise<void>;
319
- getEndpoint(endpointId: string): Promise<WebhookEndpoint | null>;
320
- listEndpoints(): Promise<WebhookEndpoint[]>;
321
- addDelivery(delivery: WebhookDelivery): Promise<void>;
322
- getDeliveries(endpointId?: string, timeRange?: {
323
- start: Date;
324
- end: Date;
325
- }, eventType?: WebhookEventType, status?: string, limit?: number): Promise<WebhookDelivery[]>;
326
- getFailedDeliveries(endpointId?: string, eventType?: WebhookEventType): Promise<WebhookDelivery[]>;
327
- }
328
-
329
- /**
330
- * Dispatcher Type Definitions
331
- */
332
-
333
- interface DispatchConfig {
334
- maxConcurrentRequests: number;
335
- requestTimeoutMs: number;
336
- defaultRetries: number;
337
- circuitBreakerThreshold: number;
338
- circuitBreakerTimeoutMs: number;
339
- }
340
- interface BatchConfig {
341
- maxBatchSize: number;
342
- batchTimeoutMs: number;
343
- maxConcurrentBatches: number;
344
- enablePrioritization: boolean;
345
- priorityLevels: number;
346
- }
347
- interface QueueConfig {
348
- maxQueueSize: number;
349
- persistToDisk: boolean;
350
- diskPath?: string;
351
- compressionEnabled: boolean;
352
- ttlMs: number;
353
- }
354
- interface LoadBalancerConfig {
355
- strategy: 'round-robin' | 'least-connections' | 'weighted' | 'random';
356
- healthCheckInterval: number;
357
- healthCheckTimeoutMs: number;
358
- weights?: Record<string, number>;
359
- }
360
- interface DispatchJob {
361
- id: string;
362
- event: WebhookEvent;
363
- endpoint: WebhookEndpoint;
364
- priority: number;
365
- createdAt: Date;
366
- scheduledAt: Date;
367
- attempts: number;
368
- maxAttempts: number;
369
- nextRetryAt?: Date;
370
- }
371
- interface CircuitBreakerState {
372
- endpointId: string;
373
- state: 'closed' | 'open' | 'half-open';
374
- failureCount: number;
375
- lastFailureTime?: Date;
376
- nextRetryTime?: Date;
377
- }
378
-
379
- /**
380
- * Batch Webhook Dispatcher
381
- * 대량 웹훅 요청을 효율적으로 처리하는 배치 디스패처
382
- */
383
-
384
- declare class BatchDispatcher extends EventEmitter {
385
- private config;
386
- private pendingJobs;
387
- private activeBatches;
388
- private batchProcessor;
389
- private defaultConfig;
390
- constructor(config?: Partial<BatchConfig>);
391
- /**
392
- * 배치 작업 추가
393
- */
394
- addJob(job: DispatchJob): Promise<void>;
395
- /**
396
- * 특정 엔드포인트의 배치 처리
397
- */
398
- processBatchForEndpoint(endpointId: string): Promise<WebhookBatch | null>;
399
- /**
400
- * 모든 대기 중인 배치 처리
401
- */
402
- processAllBatches(): Promise<WebhookBatch[]>;
403
- /**
404
- * 배치 통계 조회
405
- */
406
- getBatchStats(): {
407
- pendingJobsCount: number;
408
- activeBatchesCount: number;
409
- endpointsWithPendingJobs: number;
410
- averageQueueSize: number;
411
- };
412
- /**
413
- * 특정 엔드포인트의 대기 중인 작업 수 조회
414
- */
415
- getPendingJobCount(endpointId: string): number;
416
- /**
417
- * 배치 처리기 시작
418
- */
419
- private startBatchProcessor;
420
- /**
421
- * 우선순위 기반 작업 삽입
422
- */
423
- private insertJobByPriority;
424
- /**
425
- * 배치 생성
426
- */
427
- private createBatch;
428
- /**
429
- * 배치 실행
430
- */
431
- private executeBatch;
432
- /**
433
- * 개별 작업 실행 (실제로는 WebhookDispatcher 사용)
434
- */
435
- private executeJob;
436
- /**
437
- * 실패한 작업들을 다시 큐에 추가
438
- */
439
- private requeueFailedJobs;
440
- /**
441
- * 배치 처리기 정지
442
- */
443
- shutdown(): Promise<void>;
444
- }
445
-
446
- /**
447
- * Queue Manager
448
- * 웹훅 작업 큐 관리 시스템
449
- */
450
-
451
- declare class QueueManager extends EventEmitter {
452
- private config;
453
- private queues;
454
- private highPriorityQueue;
455
- private mediumPriorityQueue;
456
- private lowPriorityQueue;
457
- private delayedJobs;
458
- private totalJobs;
459
- private defaultConfig;
460
- constructor(config?: Partial<QueueConfig>);
461
- /**
462
- * 작업을 큐에 추가
463
- */
464
- enqueue(job: DispatchJob): Promise<boolean>;
465
- /**
466
- * 우선순위에 따라 작업 추출
467
- */
468
- dequeue(): Promise<DispatchJob | null>;
469
- /**
470
- * 특정 우선순위 큐에서 작업 추출
471
- */
472
- dequeueFromPriority(priority: number): Promise<DispatchJob | null>;
473
- /**
474
- * 작업 상태 확인
475
- */
476
- peek(): DispatchJob | null;
477
- /**
478
- * 특정 작업 제거
479
- */
480
- removeJob(jobId: string): Promise<boolean>;
481
- /**
482
- * 큐 통계 조회
483
- */
484
- getStats(): {
485
- totalJobs: number;
486
- highPriorityJobs: number;
487
- mediumPriorityJobs: number;
488
- lowPriorityJobs: number;
489
- delayedJobs: number;
490
- queueUtilization: number;
491
- };
492
- /**
493
- * 큐 비우기
494
- */
495
- clear(): Promise<void>;
496
- /**
497
- * 만료된 작업 정리
498
- */
499
- cleanupExpiredJobs(): Promise<number>;
500
- /**
501
- * 우선순위 숫자를 큐 이름으로 변환
502
- */
503
- private getQueueName;
504
- /**
505
- * 지연된 작업 스케줄링
506
- */
507
- private scheduleDelayedJob;
508
- /**
509
- * TTL 정리 작업 시작
510
- */
511
- private startTTLCleanup;
512
- /**
513
- * 디스크에 큐 상태 저장
514
- */
515
- private saveToDisk;
516
- /**
517
- * 디스크에서 큐 상태 로드
518
- */
519
- private loadFromDisk;
520
- /**
521
- * 큐 관리자 종료
522
- */
523
- shutdown(): Promise<void>;
524
- }
525
-
526
- /**
527
- * Load Balancer
528
- * 웹훅 엔드포인트 간의 부하 분산 관리
529
- */
530
-
531
- interface EndpointHealth {
532
- endpointId: string;
533
- isHealthy: boolean;
534
- consecutiveFailures: number;
535
- lastHealthCheckAt: Date;
536
- averageResponseTime: number;
537
- activeConnections: number;
538
- }
539
- declare class LoadBalancer extends EventEmitter {
540
- private config;
541
- private endpointHealth;
542
- private circuitBreakers;
543
- private connectionCounts;
544
- private roundRobinIndex;
545
- private healthCheckInterval;
546
- private defaultConfig;
547
- constructor(config?: Partial<LoadBalancerConfig>);
548
- /**
549
- * 엔드포인트 등록
550
- */
551
- registerEndpoint(endpoint: WebhookEndpoint): Promise<void>;
552
- /**
553
- * 엔드포인트 등록 해제
554
- */
555
- unregisterEndpoint(endpointId: string): Promise<void>;
556
- /**
557
- * 로드 밸런싱을 통한 엔드포인트 선택
558
- */
559
- selectEndpoint(endpoints: WebhookEndpoint[]): Promise<WebhookEndpoint | null>;
560
- /**
561
- * 요청 완료 시 호출 (연결 수 감소 및 통계 업데이트)
562
- */
563
- onRequestComplete(endpointId: string, success: boolean, responseTime: number): Promise<void>;
564
- /**
565
- * 엔드포인트 건강 상태 조회
566
- */
567
- getEndpointHealth(endpointId: string): EndpointHealth | null;
568
- /**
569
- * 모든 엔드포인트 건강 상태 조회
570
- */
571
- getAllEndpointHealth(): EndpointHealth[];
572
- /**
573
- * 로드 밸런서 통계 조회
574
- */
575
- getStats(): {
576
- totalEndpoints: number;
577
- healthyEndpoints: number;
578
- activeConnections: number;
579
- circuitBreakersOpen: number;
580
- averageResponseTime: number;
581
- };
582
- /**
583
- * Round Robin 전략
584
- */
585
- private selectRoundRobin;
586
- /**
587
- * Least Connections 전략
588
- */
589
- private selectLeastConnections;
590
- /**
591
- * Weighted 전략
592
- */
593
- private selectWeighted;
594
- /**
595
- * Random 전략
596
- */
597
- private selectRandom;
598
- /**
599
- * Half-open Circuit Breaker 엔드포인트 시도
600
- */
601
- private tryHalfOpenEndpoint;
602
- /**
603
- * Circuit Breaker 상태 업데이트
604
- */
605
- private updateCircuitBreaker;
606
- /**
607
- * 연결 수 증가
608
- */
609
- private incrementConnections;
610
- /**
611
- * 연결 수 감소
612
- */
613
- private decrementConnections;
614
- /**
615
- * 엔드포인트 건강 상태 확인
616
- */
617
- private checkEndpointHealth;
618
- /**
619
- * 건강 상태 확인 시작
620
- */
621
- private startHealthChecks;
622
- /**
623
- * 로드 밸런서 종료
624
- */
625
- shutdown(): Promise<void>;
626
- }
627
-
628
- /**
629
- * Registry Type Definitions
630
- */
631
-
632
- interface EndpointFilter {
633
- status?: 'active' | 'inactive' | 'error' | 'suspended';
634
- events?: WebhookEventType[];
635
- providerId?: string[];
636
- channelId?: string[];
637
- createdAfter?: Date;
638
- createdBefore?: Date;
639
- lastTriggeredAfter?: Date;
640
- lastTriggeredBefore?: Date;
641
- }
642
- interface DeliveryFilter {
643
- endpointId?: string;
644
- eventId?: string;
645
- status?: 'pending' | 'success' | 'failed' | 'exhausted';
646
- createdAfter?: Date;
647
- createdBefore?: Date;
648
- completedAfter?: Date;
649
- completedBefore?: Date;
650
- httpStatusCode?: number[];
651
- hasError?: boolean;
652
- }
653
- interface EventFilter {
654
- type?: WebhookEventType[];
655
- providerId?: string[];
656
- channelId?: string[];
657
- templateId?: string[];
658
- messageId?: string[];
659
- userId?: string[];
660
- organizationId?: string[];
661
- createdAfter?: Date;
662
- createdBefore?: Date;
663
- }
664
- interface StorageConfig {
665
- type: 'memory' | 'file' | 'database';
666
- filePath?: string;
667
- enableCompression?: boolean;
668
- maxFileSize?: number;
669
- connectionString?: string;
670
- tableName?: string;
671
- maxMemoryUsage?: number;
672
- retentionDays?: number;
673
- enableEncryption?: boolean;
674
- encryptionKey?: string;
675
- }
676
- interface PaginationOptions {
677
- page: number;
678
- limit: number;
679
- sortBy?: string;
680
- sortOrder?: 'asc' | 'desc';
681
- }
682
- interface SearchResult<T> {
683
- items: T[];
684
- totalCount: number;
685
- page: number;
686
- totalPages: number;
687
- hasNext: boolean;
688
- hasPrevious: boolean;
689
- }
690
-
691
- /**
692
- * Endpoint Manager
693
- * 웹훅 엔드포인트 관리를 위한 고급 기능 제공
694
- */
695
-
696
- declare class EndpointManager extends EventEmitter {
697
- private config;
698
- private endpoints;
699
- private indexByUrl;
700
- private indexByEvent;
701
- private indexByStatus;
702
- private defaultConfig;
703
- constructor(config?: Partial<StorageConfig>);
704
- /**
705
- * 엔드포인트 추가
706
- */
707
- addEndpoint(endpoint: WebhookEndpoint): Promise<void>;
708
- /**
709
- * 엔드포인트 업데이트
710
- */
711
- updateEndpoint(endpointId: string, updates: Partial<WebhookEndpoint>): Promise<WebhookEndpoint>;
712
- /**
713
- * 엔드포인트 제거
714
- */
715
- removeEndpoint(endpointId: string): Promise<boolean>;
716
- /**
717
- * 엔드포인트 조회
718
- */
719
- getEndpoint(endpointId: string): Promise<WebhookEndpoint | null>;
720
- /**
721
- * URL로 엔드포인트 조회
722
- */
723
- getEndpointByUrl(url: string): Promise<WebhookEndpoint | null>;
724
- /**
725
- * 필터 조건에 맞는 엔드포인트 검색
726
- */
727
- searchEndpoints(filter?: EndpointFilter, pagination?: PaginationOptions): Promise<SearchResult<WebhookEndpoint>>;
728
- /**
729
- * 특정 이벤트 타입을 구독하는 활성 엔드포인트 조회
730
- */
731
- getActiveEndpointsForEvent(eventType: WebhookEventType): Promise<WebhookEndpoint[]>;
732
- /**
733
- * 엔드포인트 통계 조회
734
- */
735
- getStats(): {
736
- totalEndpoints: number;
737
- activeEndpoints: number;
738
- inactiveEndpoints: number;
739
- errorEndpoints: number;
740
- suspendedEndpoints: number;
741
- eventSubscriptions: Record<WebhookEventType, number>;
742
- };
743
- /**
744
- * 만료된 엔드포인트 정리
745
- */
746
- cleanupExpiredEndpoints(): Promise<number>;
747
- /**
748
- * 인덱스 초기화
749
- */
750
- private initializeIndexes;
751
- /**
752
- * 인덱스에 엔드포인트 추가
753
- */
754
- private addToIndexes;
755
- /**
756
- * 인덱스에서 엔드포인트 제거
757
- */
758
- private removeFromIndexes;
759
- /**
760
- * 필터 조건 매칭 확인
761
- */
762
- private matchesFilter;
763
- /**
764
- * 객체 필드 값 가져오기 (정렬용)
765
- */
766
- private getFieldValue;
767
- /**
768
- * 파일에서 데이터 로드
769
- */
770
- private loadFromFile;
771
- /**
772
- * 파일에 데이터 저장
773
- */
774
- private saveToFile;
775
- /**
776
- * 엔드포인트 관리자 종료
777
- */
778
- shutdown(): Promise<void>;
779
- }
780
-
781
- /**
782
- * Delivery Store
783
- * 웹훅 전달 기록 저장 및 관리
784
- */
785
-
786
- declare class DeliveryStore extends EventEmitter {
787
- private config;
788
- private deliveries;
789
- private indexByEndpoint;
790
- private indexByStatus;
791
- private indexByDate;
792
- private cleanupInterval;
793
- private defaultConfig;
794
- constructor(config?: Partial<StorageConfig>);
795
- /**
796
- * 전달 기록 저장
797
- */
798
- saveDelivery(delivery: WebhookDelivery): Promise<void>;
799
- /**
800
- * 전달 기록 조회
801
- */
802
- getDelivery(deliveryId: string): Promise<WebhookDelivery | null>;
803
- /**
804
- * 필터 조건에 맞는 전달 기록 검색
805
- */
806
- searchDeliveries(filter?: DeliveryFilter, pagination?: PaginationOptions): Promise<SearchResult<WebhookDelivery>>;
807
- /**
808
- * 엔드포인트별 전달 기록 조회
809
- */
810
- getDeliveriesByEndpoint(endpointId: string, limit?: number): Promise<WebhookDelivery[]>;
811
- /**
812
- * 실패한 전달 기록 조회
813
- */
814
- getFailedDeliveries(endpointId?: string, limit?: number): Promise<WebhookDelivery[]>;
815
- /**
816
- * 전달 통계 조회
817
- */
818
- getDeliveryStats(endpointId?: string, timeRange?: {
819
- start: Date;
820
- end: Date;
821
- }): Promise<{
822
- totalDeliveries: number;
823
- successfulDeliveries: number;
824
- failedDeliveries: number;
825
- pendingDeliveries: number;
826
- exhaustedDeliveries: number;
827
- averageLatency: number;
828
- successRate: number;
829
- errorBreakdown: Record<string, number>;
830
- }>;
831
- /**
832
- * 오래된 전달 기록 정리
833
- */
834
- cleanupOldDeliveries(): Promise<number>;
835
- /**
836
- * 저장소 통계 조회
837
- */
838
- getStorageStats(): {
839
- totalDeliveries: number;
840
- memoryUsage: number;
841
- indexSizes: {
842
- byEndpoint: number;
843
- byStatus: number;
844
- byDate: number;
845
- };
846
- };
847
- /**
848
- * 인덱스 초기화
849
- */
850
- private initializeIndexes;
851
- /**
852
- * 인덱스에 전달 기록 추가
853
- */
854
- private addToIndexes;
855
- /**
856
- * 인덱스에서 전달 기록 제거
857
- */
858
- private removeFromIndexes;
859
- /**
860
- * 날짜 범위로 전달 기록 ID 조회
861
- */
862
- private getDeliveryIdsByDateRange;
863
- /**
864
- * 필터 조건 매칭 확인
865
- */
866
- private matchesFilter;
867
- /**
868
- * 객체 필드 값 가져오기
869
- */
870
- private getFieldValue;
871
- /**
872
- * 메모리 사용량 추정
873
- */
874
- private estimateMemoryUsage;
875
- /**
876
- * 메모리 사용량 확인 및 정리
877
- */
878
- private checkMemoryUsage;
879
- /**
880
- * 정리 작업 시작
881
- */
882
- private startCleanupTask;
883
- /**
884
- * 파일에 전달 기록 추가
885
- */
886
- private appendToFile;
887
- /**
888
- * 파일에서 데이터 로드
889
- */
890
- private loadFromFile;
891
- /**
892
- * 파일에 데이터 저장
893
- */
894
- private saveToFile;
895
- /**
896
- * 전달 저장소 종료
897
- */
898
- shutdown(): Promise<void>;
899
- }
900
-
901
- /**
902
- * Event Store
903
- * 웹훅 이벤트 저장 및 관리
904
- */
905
-
906
- declare class EventStore extends EventEmitter {
907
- private config;
908
- private events;
909
- private indexByType;
910
- private indexByDate;
911
- private indexByProvider;
912
- private indexByChannel;
913
- private cleanupInterval;
914
- private defaultConfig;
915
- constructor(config?: Partial<StorageConfig>);
916
- /**
917
- * 이벤트 저장
918
- */
919
- saveEvent(event: WebhookEvent): Promise<void>;
920
- /**
921
- * 이벤트 조회
922
- */
923
- getEvent(eventId: string): Promise<WebhookEvent | null>;
924
- /**
925
- * 필터 조건에 맞는 이벤트 검색
926
- */
927
- searchEvents(filter?: EventFilter, pagination?: PaginationOptions): Promise<SearchResult<WebhookEvent>>;
928
- /**
929
- * 이벤트 타입별 조회
930
- */
931
- getEventsByType(eventType: WebhookEventType, limit?: number): Promise<WebhookEvent[]>;
932
- /**
933
- * 이벤트 통계 조회
934
- */
935
- getEventStats(timeRange?: {
936
- start: Date;
937
- end: Date;
938
- }): Promise<{
939
- totalEvents: number;
940
- eventsByType: Record<WebhookEventType, number>;
941
- eventsByProvider: Record<string, number>;
942
- eventsByChannel: Record<string, number>;
943
- eventsPerHour: Record<string, number>;
944
- }>;
945
- /**
946
- * 오래된 이벤트 정리
947
- */
948
- cleanupOldEvents(): Promise<number>;
949
- /**
950
- * 중복 이벤트 정리
951
- */
952
- cleanupDuplicateEvents(): Promise<number>;
953
- /**
954
- * 저장소 통계 조회
955
- */
956
- getStorageStats(): {
957
- totalEvents: number;
958
- memoryUsage: number;
959
- indexSizes: {
960
- byType: number;
961
- byDate: number;
962
- byProvider: number;
963
- byChannel: number;
964
- };
965
- };
966
- /**
967
- * 인덱스 초기화
968
- */
969
- private initializeIndexes;
970
- /**
971
- * 인덱스에 이벤트 추가
972
- */
973
- private addToIndexes;
974
- /**
975
- * 인덱스에서 이벤트 제거
976
- */
977
- private removeFromIndexes;
978
- /**
979
- * 날짜 범위로 이벤트 ID 조회
980
- */
981
- private getEventIdsByDateRange;
982
- /**
983
- * 필터 조건 매칭 확인
984
- */
985
- private matchesFilter;
986
- /**
987
- * 객체 필드 값 가져오기
988
- */
989
- private getFieldValue;
990
- /**
991
- * 메모리 사용량 추정
992
- */
993
- private estimateMemoryUsage;
994
- /**
995
- * 메모리 사용량 확인 및 정리
996
- */
997
- private checkMemoryUsage;
998
- /**
999
- * 이벤트 내용 키 생성 (중복 검사용)
1000
- */
1001
- private generateContentKey;
1002
- /**
1003
- * 정리 작업 시작
1004
- */
1005
- private startCleanupTask;
1006
- /**
1007
- * 파일에 이벤트 추가
1008
- */
1009
- private appendToFile;
1010
- /**
1011
- * 파일에서 데이터 로드
1012
- */
1013
- private loadFromFile;
1014
- /**
1015
- * 파일에 데이터 저장
1016
- */
1017
- private saveToFile;
1018
- /**
1019
- * 이벤트 저장소 종료
1020
- */
1021
- shutdown(): Promise<void>;
1022
- }
1023
-
1024
- interface SecurityConfig {
1025
- algorithm: 'sha256' | 'sha1';
1026
- header: string;
1027
- prefix?: string;
1028
- }
1029
- /**
1030
- * Webhook 보안 관리자
1031
- * 서명 생성 및 검증을 담당
1032
- */
1033
- declare class SecurityManager {
1034
- private config;
1035
- constructor(webhookConfig: WebhookConfig);
1036
- /**
1037
- * Webhook 페이로드에 대한 서명 생성
1038
- */
1039
- generateSignature(payload: string, secret: string): string;
1040
- /**
1041
- * Webhook 서명 검증
1042
- */
1043
- verifySignature(payload: string, signature: string, secret: string): boolean;
1044
- /**
1045
- * HTTP 헤더에서 서명 추출
1046
- */
1047
- extractSignature(headers: Record<string, string>): string | null;
1048
- /**
1049
- * Webhook 전송을 위한 보안 헤더 생성
1050
- */
1051
- createSecurityHeaders(payload: string, secret: string): Record<string, string>;
1052
- /**
1053
- * 타임스탬프 기반 재생 공격 방지 검증
1054
- */
1055
- verifyTimestamp(timestamp: string, toleranceSeconds?: number): boolean;
1056
- /**
1057
- * Webhook ID 생성 (추적용)
1058
- */
1059
- private generateWebhookId;
1060
- /**
1061
- * Constant-time 문자열 비교 (타이밍 공격 방지)
1062
- */
1063
- private constantTimeCompare;
1064
- /**
1065
- * 보안 설정 업데이트
1066
- */
1067
- updateConfig(config: Partial<SecurityConfig>): void;
1068
- /**
1069
- * 현재 보안 설정 반환
1070
- */
1071
- getConfig(): SecurityConfig;
1072
- }
1073
-
1074
- interface RetryConfig {
1075
- maxRetries: number;
1076
- baseDelayMs: number;
1077
- maxDelayMs: number;
1078
- backoffMultiplier: number;
1079
- jitter: boolean;
1080
- }
1081
- interface RetryAttempt {
1082
- attemptNumber: number;
1083
- timestamp: Date;
1084
- success: boolean;
1085
- error?: string;
1086
- nextRetryAt?: Date;
1087
- }
1088
- /**
1089
- * Webhook 재시도 관리자
1090
- * 지수 백오프와 지터를 사용한 스마트 재시도 로직
1091
- */
1092
- declare class RetryManager {
1093
- private config;
1094
- constructor(webhookConfig: WebhookConfig);
1095
- /**
1096
- * 다음 재시도 시간 계산
1097
- */
1098
- calculateNextRetry(attemptNumber: number): Date;
1099
- /**
1100
- * 재시도 가능 여부 확인
1101
- */
1102
- shouldRetry(attemptNumber: number, error?: Error): boolean;
1103
- /**
1104
- * 재시도 가능한 에러인지 판단
1105
- */
1106
- private isRetryableError;
1107
- /**
1108
- * HTTP 상태 코드별 재시도 정책
1109
- */
1110
- shouldRetryStatus(statusCode: number): boolean;
1111
- /**
1112
- * 재시도 통계 계산
1113
- */
1114
- calculateRetryStats(attempts: RetryAttempt[]): {
1115
- totalAttempts: number;
1116
- successfulAttempts: number;
1117
- failedAttempts: number;
1118
- averageDelayMs: number;
1119
- totalTimeMs: number;
1120
- };
1121
- /**
1122
- * 재시도 설정 업데이트
1123
- */
1124
- updateConfig(config: Partial<RetryConfig>): void;
1125
- /**
1126
- * 현재 재시도 설정 반환
1127
- */
1128
- getConfig(): RetryConfig;
1129
- /**
1130
- * 백오프 지연 시간 계산 (테스트용)
1131
- */
1132
- getBackoffDelay(attemptNumber: number): number;
1133
- }
1134
-
1135
- export { type BatchConfig, BatchDispatcher, type CircuitBreakerState, type DeliveryFilter, DeliveryStore, type DispatchConfig, type DispatchJob, type EndpointFilter, EndpointManager, type EventFilter, EventStore, LoadBalancer, type LoadBalancerConfig, type PaginationOptions, type QueueConfig, QueueManager, RetryManager, type SearchResult, SecurityManager, type StorageConfig, type WebhookAttempt, type WebhookBatch, type WebhookConfig, type WebhookDelivery, type WebhookDeliveryData, WebhookDispatcher, type WebhookEndpoint, type WebhookEndpointData, type WebhookEvent, type WebhookEventData, WebhookEventType, WebhookRegistry, type WebhookSecurity, WebhookService, type WebhookStats, type WebhookTestResult };