@k-msg/analytics 0.1.1 → 0.1.3

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.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Aggregators - 데이터 집계 컴포넌트들
3
+ */
4
+ export { type AggregationRule, type AggregatorConfig, MetricAggregator, } from "./metric.aggregator";
5
+ export { type AggregationOptions, TimeSeriesAggregator, type TimeWindow, } from "./time-series.aggregator";
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Metric Aggregator
3
+ * 메트릭별 특화 집계 로직
4
+ */
5
+ import type { AggregatedMetric, MetricData } from "../types/analytics.types";
6
+ import { MetricType } from "../types/analytics.types";
7
+ export interface AggregationRule {
8
+ metricType: MetricType;
9
+ aggregationType: "sum" | "avg" | "min" | "max" | "count" | "rate" | "percentile";
10
+ dimensions: string[];
11
+ conditions?: Array<{
12
+ field: string;
13
+ operator: "equals" | "not_equals" | "gt" | "lt" | "contains";
14
+ value: any;
15
+ }>;
16
+ percentile?: number;
17
+ }
18
+ export interface AggregatorConfig {
19
+ rules: AggregationRule[];
20
+ batchSize: number;
21
+ flushInterval: number;
22
+ }
23
+ export declare class MetricAggregator {
24
+ private config;
25
+ private buffer;
26
+ private aggregationCache;
27
+ constructor(config: AggregatorConfig);
28
+ /**
29
+ * 메트릭 추가 및 실시간 집계
30
+ */
31
+ addMetric(metric: MetricData): Promise<void>;
32
+ /**
33
+ * 배치 메트릭 처리
34
+ */
35
+ addMetrics(metrics: MetricData[]): Promise<void>;
36
+ /**
37
+ * 규칙 기반 집계 실행
38
+ */
39
+ aggregateByRules(metrics: MetricData[]): Promise<AggregatedMetric[]>;
40
+ /**
41
+ * 커스텀 집계 (동적 규칙)
42
+ */
43
+ aggregateCustom(metrics: MetricData[], groupBy: string[], aggregationType: "sum" | "avg" | "min" | "max" | "count" | "rate", filters?: Record<string, any>): Promise<AggregatedMetric[]>;
44
+ /**
45
+ * 비율 계산 (예: 전환율, 오류율)
46
+ */
47
+ calculateRates(numeratorMetrics: MetricData[], denominatorMetrics: MetricData[], groupBy?: string[]): Promise<AggregatedMetric[]>;
48
+ /**
49
+ * 백분위수 계산
50
+ */
51
+ calculatePercentiles(metrics: MetricData[], percentiles: number[], groupBy?: string[]): Promise<AggregatedMetric[]>;
52
+ /**
53
+ * 슬라이딩 윈도우 집계
54
+ */
55
+ aggregateSlidingWindow(metrics: MetricData[], windowSizeMs: number, stepMs: number, aggregationType: "sum" | "avg" | "min" | "max" | "count"): Promise<AggregatedMetric[]>;
56
+ /**
57
+ * 메트릭 정규화
58
+ */
59
+ normalizeMetrics(metrics: AggregatedMetric[], method: "minmax" | "zscore" | "robust"): Promise<AggregatedMetric[]>;
60
+ private getBufferKey;
61
+ private flushBuffer;
62
+ private filterMetricsByRule;
63
+ private applyAggregationRule;
64
+ private groupMetrics;
65
+ private createGroupKey;
66
+ private getFieldValue;
67
+ private evaluateCondition;
68
+ private performAggregation;
69
+ private applyFilters;
70
+ private calculatePercentile;
71
+ private minMaxNormalize;
72
+ private zScoreNormalize;
73
+ private robustNormalize;
74
+ private calculateMAD;
75
+ private startPeriodicFlush;
76
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Time Series Data Aggregator
3
+ * 시계열 데이터 집계 및 다운샘플링
4
+ */
5
+ import type { AggregatedMetric, MetricData } from "../types/analytics.types";
6
+ export interface TimeWindow {
7
+ start: Date;
8
+ end: Date;
9
+ interval: "minute" | "hour" | "day" | "week" | "month";
10
+ }
11
+ export interface AggregationOptions {
12
+ fillGaps: boolean;
13
+ fillValue: number;
14
+ timezone?: string;
15
+ }
16
+ export declare class TimeSeriesAggregator {
17
+ private timezone;
18
+ constructor(timezone?: string);
19
+ /**
20
+ * 시계열 데이터를 지정된 간격으로 집계
21
+ */
22
+ aggregate(metrics: MetricData[], interval: "minute" | "hour" | "day" | "week" | "month", options?: AggregationOptions): Promise<AggregatedMetric[]>;
23
+ /**
24
+ * 롤링 윈도우 집계
25
+ */
26
+ aggregateRolling(metrics: MetricData[], windowSize: number, // 분 단위
27
+ step?: number): Promise<AggregatedMetric[]>;
28
+ /**
29
+ * 계절성 분해 (간단한 이동평균 기반)
30
+ */
31
+ decomposeSeasonality(metrics: AggregatedMetric[], seasonLength?: number): Promise<{
32
+ trend: AggregatedMetric[];
33
+ seasonal: AggregatedMetric[];
34
+ residual: AggregatedMetric[];
35
+ }>;
36
+ /**
37
+ * 다운샘플링 (고해상도 → 저해상도)
38
+ */
39
+ downsample(metrics: AggregatedMetric[], targetInterval: "minute" | "hour" | "day" | "week" | "month"): Promise<AggregatedMetric[]>;
40
+ private groupByType;
41
+ private groupByDimensions;
42
+ private aggregateByInterval;
43
+ private groupByTimeInterval;
44
+ private getTimeIntervalKey;
45
+ private fillTimeGaps;
46
+ private calculateAggregations;
47
+ private aggregateWindow;
48
+ private calculateMovingAverage;
49
+ private calculateSeasonalComponent;
50
+ private calculateResidual;
51
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Event Collector
3
+ * 실시간 이벤트 수집 및 메트릭 변환
4
+ */
5
+ import { EventEmitter } from "events";
6
+ import type { MetricData } from "../types/analytics.types";
7
+ export interface EventData {
8
+ id: string;
9
+ type: string;
10
+ timestamp: Date;
11
+ source: string;
12
+ payload: Record<string, any>;
13
+ context?: {
14
+ userId?: string;
15
+ sessionId?: string;
16
+ requestId?: string;
17
+ userAgent?: string;
18
+ ipAddress?: string;
19
+ };
20
+ }
21
+ export interface EventCollectorConfig {
22
+ bufferSize: number;
23
+ flushInterval: number;
24
+ enableDeduplication: boolean;
25
+ deduplicationWindow: number;
26
+ enableSampling: boolean;
27
+ samplingRate: number;
28
+ }
29
+ export interface EventProcessor {
30
+ canProcess(event: EventData): boolean;
31
+ process(event: EventData): Promise<MetricData[]>;
32
+ }
33
+ export declare class EventCollector extends EventEmitter {
34
+ private config;
35
+ private buffer;
36
+ private processors;
37
+ private recentEvents;
38
+ private metrics;
39
+ private defaultConfig;
40
+ constructor(config?: Partial<EventCollectorConfig>);
41
+ /**
42
+ * 이벤트 수집
43
+ */
44
+ collectEvent(event: EventData): Promise<void>;
45
+ /**
46
+ * 배치 이벤트 수집
47
+ */
48
+ collectEvents(events: EventData[]): Promise<void>;
49
+ /**
50
+ * 커스텀 이벤트 프로세서 등록
51
+ */
52
+ registerProcessor(name: string, processor: EventProcessor): void;
53
+ /**
54
+ * 이벤트 프로세서 제거
55
+ */
56
+ unregisterProcessor(name: string): boolean;
57
+ /**
58
+ * 수집된 메트릭 조회
59
+ */
60
+ getCollectedMetrics(since?: Date): MetricData[];
61
+ /**
62
+ * 실시간 메트릭 스트림
63
+ */
64
+ streamMetrics(): AsyncGenerator<MetricData[]>;
65
+ /**
66
+ * 이벤트 통계
67
+ */
68
+ getEventStats(): {
69
+ totalEvents: number;
70
+ eventsByType: Record<string, number>;
71
+ eventsBySource: Record<string, number>;
72
+ bufferSize: number;
73
+ metricsGenerated: number;
74
+ };
75
+ /**
76
+ * 버퍼 강제 플러시
77
+ */
78
+ flush(): Promise<void>;
79
+ private processEvent;
80
+ private validateEvent;
81
+ private isDuplicate;
82
+ private isHighPriorityEvent;
83
+ private initializeDefaultProcessors;
84
+ private startPeriodicFlush;
85
+ private startCleanup;
86
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Collectors - 데이터 수집 컴포넌트들
3
+ */
4
+ export { EventCollector, type EventCollectorConfig, type EventData, type EventProcessor, } from "./event.collector";
5
+ export { WebhookCollector, type WebhookCollectorConfig, type WebhookData, } from "./webhook.collector";
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Webhook Collector
3
+ * 웹훅을 통한 외부 이벤트 수집
4
+ */
5
+ import { EventEmitter } from "events";
6
+ import type { EventData } from "./event.collector";
7
+ export interface WebhookData {
8
+ id: string;
9
+ source: string;
10
+ timestamp: Date;
11
+ headers: Record<string, string>;
12
+ body: any;
13
+ signature?: string;
14
+ }
15
+ export interface WebhookCollectorConfig {
16
+ enableSignatureValidation: boolean;
17
+ signatureHeader: string;
18
+ secretKey?: string;
19
+ allowedSources: string[];
20
+ maxPayloadSize: number;
21
+ rateLimitPerMinute: number;
22
+ }
23
+ export interface WebhookTransformer {
24
+ canTransform(webhook: WebhookData): boolean;
25
+ transform(webhook: WebhookData): Promise<EventData[]>;
26
+ }
27
+ export declare class WebhookCollector extends EventEmitter {
28
+ private config;
29
+ private transformers;
30
+ private requestCounts;
31
+ private processedWebhooks;
32
+ private defaultConfig;
33
+ constructor(config?: Partial<WebhookCollectorConfig>);
34
+ /**
35
+ * 웹훅 수신 처리
36
+ */
37
+ receiveWebhook(webhook: WebhookData): Promise<EventData[]>;
38
+ /**
39
+ * 웹훅 변환기 등록
40
+ */
41
+ registerTransformer(name: string, transformer: WebhookTransformer): void;
42
+ /**
43
+ * 웹훅 변환기 제거
44
+ */
45
+ unregisterTransformer(name: string): boolean;
46
+ /**
47
+ * 처리된 웹훅 조회
48
+ */
49
+ getProcessedWebhooks(since?: Date): WebhookData[];
50
+ /**
51
+ * 웹훅 통계
52
+ */
53
+ getWebhookStats(): {
54
+ totalProcessed: number;
55
+ bySource: Record<string, number>;
56
+ recentCount: number;
57
+ transformerCount: number;
58
+ };
59
+ private validateWebhook;
60
+ private validateSignature;
61
+ private generateSignature;
62
+ private checkRateLimit;
63
+ private transformWebhook;
64
+ private defaultTransform;
65
+ private initializeDefaultTransformers;
66
+ private startCleanup;
67
+ }