@onebots/core 0.5.0 → 1.0.4

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.
Files changed (66) hide show
  1. package/README.md +3 -3
  2. package/lib/__tests__/config-validator.test.d.ts +4 -0
  3. package/lib/__tests__/config-validator.test.js +152 -0
  4. package/lib/__tests__/di-container.test.d.ts +4 -0
  5. package/lib/__tests__/di-container.test.js +114 -0
  6. package/lib/__tests__/errors.test.d.ts +4 -0
  7. package/lib/__tests__/errors.test.js +111 -0
  8. package/lib/__tests__/integration.test.d.ts +5 -0
  9. package/lib/__tests__/integration.test.js +112 -0
  10. package/lib/__tests__/lifecycle.test.d.ts +4 -0
  11. package/lib/__tests__/lifecycle.test.js +163 -0
  12. package/lib/account.d.ts +4 -1
  13. package/lib/account.js +6 -3
  14. package/lib/adapter.d.ts +67 -1
  15. package/lib/adapter.js +31 -4
  16. package/lib/base-app.d.ts +30 -3
  17. package/lib/base-app.js +295 -142
  18. package/lib/circuit-breaker.d.ts +94 -0
  19. package/lib/circuit-breaker.js +206 -0
  20. package/lib/config-validator.d.ts +51 -0
  21. package/lib/config-validator.js +184 -0
  22. package/lib/connection-pool.d.ts +68 -0
  23. package/lib/connection-pool.js +202 -0
  24. package/lib/db.d.ts +2 -1
  25. package/lib/db.js +11 -2
  26. package/lib/di-container.d.ts +60 -0
  27. package/lib/di-container.js +103 -0
  28. package/lib/errors.d.ts +157 -0
  29. package/lib/errors.js +257 -0
  30. package/lib/index.d.ts +13 -4
  31. package/lib/index.js +17 -3
  32. package/lib/lifecycle.d.ts +75 -0
  33. package/lib/lifecycle.js +175 -0
  34. package/lib/logger.d.ts +76 -0
  35. package/lib/logger.js +156 -0
  36. package/lib/metrics.d.ts +80 -0
  37. package/lib/metrics.js +201 -0
  38. package/lib/middleware/index.d.ts +8 -0
  39. package/lib/middleware/index.js +8 -0
  40. package/lib/middleware/metrics-collector.d.ts +9 -0
  41. package/lib/middleware/metrics-collector.js +64 -0
  42. package/lib/middleware/rate-limit.d.ts +32 -0
  43. package/lib/middleware/rate-limit.js +149 -0
  44. package/lib/middleware/security-audit.d.ts +33 -0
  45. package/lib/middleware/security-audit.js +223 -0
  46. package/lib/middleware/token-manager.d.ts +73 -0
  47. package/lib/middleware/token-manager.js +186 -0
  48. package/lib/middleware/token-validator.d.ts +42 -0
  49. package/lib/middleware/token-validator.js +198 -0
  50. package/lib/protocol.d.ts +2 -3
  51. package/lib/protocol.js +4 -0
  52. package/lib/rate-limiter.d.ts +88 -0
  53. package/lib/rate-limiter.js +196 -0
  54. package/lib/registry.d.ts +27 -0
  55. package/lib/registry.js +40 -5
  56. package/lib/retry.d.ts +87 -0
  57. package/lib/retry.js +205 -0
  58. package/lib/router.d.ts +43 -6
  59. package/lib/router.js +139 -12
  60. package/lib/timestamp.d.ts +42 -0
  61. package/lib/timestamp.js +72 -0
  62. package/lib/types.d.ts +1 -0
  63. package/lib/types.js +2 -1
  64. package/lib/utils.d.ts +2 -1
  65. package/lib/utils.js +11 -19
  66. package/package.json +24 -9
@@ -0,0 +1,75 @@
1
+ /**
2
+ * 生命周期管理
3
+ * 提供资源管理和优雅关闭机制
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ import type { Dispose } from './types.js';
7
+ export interface LifecycleHook {
8
+ /** 初始化钩子 */
9
+ onInit?(): void | Promise<void>;
10
+ /** 启动钩子 */
11
+ onStart?(): void | Promise<void>;
12
+ /** 停止钩子 */
13
+ onStop?(): void | Promise<void>;
14
+ /** 清理钩子 */
15
+ onCleanup?(): void | Promise<void>;
16
+ }
17
+ /**
18
+ * 生命周期管理器
19
+ */
20
+ export declare class LifecycleManager extends EventEmitter {
21
+ private resources;
22
+ private hooks;
23
+ private isShuttingDown;
24
+ private shutdownTimeout;
25
+ /**
26
+ * 注册资源
27
+ */
28
+ register(name: string, dispose: Dispose): void;
29
+ /**
30
+ * 注销资源
31
+ */
32
+ unregister(name: string): boolean;
33
+ /**
34
+ * 注册生命周期钩子
35
+ */
36
+ addHook(hook: LifecycleHook): void;
37
+ /**
38
+ * 移除生命周期钩子
39
+ */
40
+ removeHook(hook: LifecycleHook): void;
41
+ /**
42
+ * 初始化所有钩子
43
+ */
44
+ init(): Promise<void>;
45
+ /**
46
+ * 启动所有钩子
47
+ */
48
+ start(): Promise<void>;
49
+ /**
50
+ * 停止所有钩子
51
+ */
52
+ stop(): Promise<void>;
53
+ /**
54
+ * 清理所有资源
55
+ */
56
+ cleanup(): Promise<void>;
57
+ /**
58
+ * 优雅关闭
59
+ */
60
+ gracefulShutdown(signal?: string, options?: {
61
+ exitOnTimeout?: boolean;
62
+ }): Promise<void>;
63
+ /**
64
+ * 设置关闭超时时间
65
+ */
66
+ setShutdownTimeout(timeout: number): void;
67
+ /**
68
+ * 获取资源数量
69
+ */
70
+ getResourceCount(): number;
71
+ /**
72
+ * 获取所有资源名称
73
+ */
74
+ getResourceNames(): string[];
75
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * 生命周期管理
3
+ * 提供资源管理和优雅关闭机制
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ import { ResourceError } from './errors.js';
7
+ /**
8
+ * 生命周期管理器
9
+ */
10
+ export class LifecycleManager extends EventEmitter {
11
+ resources = new Map();
12
+ hooks = [];
13
+ isShuttingDown = false;
14
+ shutdownTimeout = 30000; // 30秒超时
15
+ /**
16
+ * 注册资源
17
+ */
18
+ register(name, dispose) {
19
+ if (this.resources.has(name)) {
20
+ throw new ResourceError(`Resource ${name} already registered`);
21
+ }
22
+ this.resources.set(name, dispose);
23
+ }
24
+ /**
25
+ * 注销资源
26
+ */
27
+ unregister(name) {
28
+ return this.resources.delete(name);
29
+ }
30
+ /**
31
+ * 注册生命周期钩子
32
+ */
33
+ addHook(hook) {
34
+ this.hooks.push(hook);
35
+ }
36
+ /**
37
+ * 移除生命周期钩子
38
+ */
39
+ removeHook(hook) {
40
+ const index = this.hooks.indexOf(hook);
41
+ if (index !== -1) {
42
+ this.hooks.splice(index, 1);
43
+ }
44
+ }
45
+ /**
46
+ * 初始化所有钩子
47
+ */
48
+ async init() {
49
+ this.emit('beforeInit');
50
+ for (const hook of this.hooks) {
51
+ if (hook.onInit) {
52
+ await hook.onInit();
53
+ }
54
+ }
55
+ this.emit('afterInit');
56
+ }
57
+ /**
58
+ * 启动所有钩子
59
+ */
60
+ async start() {
61
+ this.emit('beforeStart');
62
+ for (const hook of this.hooks) {
63
+ if (hook.onStart) {
64
+ await hook.onStart();
65
+ }
66
+ }
67
+ this.emit('afterStart');
68
+ }
69
+ /**
70
+ * 停止所有钩子
71
+ */
72
+ async stop() {
73
+ this.emit('beforeStop');
74
+ for (const hook of this.hooks) {
75
+ if (hook.onStop) {
76
+ await hook.onStop();
77
+ }
78
+ }
79
+ this.emit('afterStop');
80
+ }
81
+ /**
82
+ * 清理所有资源
83
+ */
84
+ async cleanup() {
85
+ if (this.isShuttingDown) {
86
+ return;
87
+ }
88
+ this.isShuttingDown = true;
89
+ this.emit('beforeCleanup');
90
+ // 执行清理钩子
91
+ for (const hook of this.hooks) {
92
+ if (hook.onCleanup) {
93
+ try {
94
+ await hook.onCleanup();
95
+ }
96
+ catch (error) {
97
+ this.emit('cleanupError', { hook: 'onCleanup', error });
98
+ // 继续执行,不抛出错误
99
+ }
100
+ }
101
+ }
102
+ // 清理所有资源
103
+ const cleanupPromises = [];
104
+ for (const [name, dispose] of this.resources.entries()) {
105
+ cleanupPromises.push((async () => {
106
+ try {
107
+ const result = dispose();
108
+ if (result instanceof Promise) {
109
+ await result;
110
+ }
111
+ }
112
+ catch (error) {
113
+ this.emit('cleanupError', { name, error });
114
+ // 继续执行,不抛出错误
115
+ }
116
+ })());
117
+ }
118
+ await Promise.all(cleanupPromises);
119
+ this.resources.clear();
120
+ this.hooks = [];
121
+ this.emit('afterCleanup');
122
+ }
123
+ /**
124
+ * 优雅关闭
125
+ */
126
+ async gracefulShutdown(signal, options) {
127
+ if (this.isShuttingDown) {
128
+ return;
129
+ }
130
+ this.emit('shutdown', signal);
131
+ // 设置超时
132
+ let timeout = null;
133
+ if (this.shutdownTimeout > 0) {
134
+ timeout = setTimeout(() => {
135
+ this.emit('shutdownTimeout');
136
+ if (options?.exitOnTimeout !== false) {
137
+ process.exit(1);
138
+ }
139
+ }, this.shutdownTimeout);
140
+ }
141
+ try {
142
+ await this.stop();
143
+ await this.cleanup();
144
+ if (timeout) {
145
+ clearTimeout(timeout);
146
+ }
147
+ this.emit('shutdownComplete');
148
+ }
149
+ catch (error) {
150
+ if (timeout) {
151
+ clearTimeout(timeout);
152
+ }
153
+ this.emit('shutdownError', error);
154
+ throw error;
155
+ }
156
+ }
157
+ /**
158
+ * 设置关闭超时时间
159
+ */
160
+ setShutdownTimeout(timeout) {
161
+ this.shutdownTimeout = timeout;
162
+ }
163
+ /**
164
+ * 获取资源数量
165
+ */
166
+ getResourceCount() {
167
+ return this.resources.size;
168
+ }
169
+ /**
170
+ * 获取所有资源名称
171
+ */
172
+ getResourceNames() {
173
+ return Array.from(this.resources.keys());
174
+ }
175
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 增强的日志系统
3
+ * 提供结构化日志、错误追踪和上下文信息
4
+ */
5
+ import { OneBotsError } from './errors.js';
6
+ import type { LogLevel } from './types.js';
7
+ export interface LogContext {
8
+ [key: string]: any;
9
+ }
10
+ export interface LogEntry {
11
+ level: string;
12
+ message: string;
13
+ context?: LogContext;
14
+ error?: OneBotsError;
15
+ timestamp: Date;
16
+ }
17
+ /**
18
+ * 增强的 Logger 类
19
+ */
20
+ export declare class Logger {
21
+ private logger;
22
+ private context;
23
+ constructor(name: string, level?: LogLevel);
24
+ /**
25
+ * 设置日志级别
26
+ */
27
+ setLevel(level: LogLevel): void;
28
+ /**
29
+ * 添加上下文信息
30
+ */
31
+ withContext(context: LogContext): Logger;
32
+ /**
33
+ * Trace 级别日志
34
+ */
35
+ trace(message: string, context?: LogContext): void;
36
+ /**
37
+ * Debug 级别日志
38
+ */
39
+ debug(message: string, context?: LogContext): void;
40
+ /**
41
+ * Info 级别日志
42
+ */
43
+ info(message: string, context?: LogContext): void;
44
+ /**
45
+ * Warn 级别日志
46
+ */
47
+ warn(message: string, context?: LogContext): void;
48
+ /**
49
+ * Error 级别日志
50
+ */
51
+ error(message: string | Error | OneBotsError, context?: LogContext): void;
52
+ /**
53
+ * Fatal 级别日志
54
+ */
55
+ fatal(message: string | Error | OneBotsError, context?: LogContext): void;
56
+ /**
57
+ * Mark 级别日志
58
+ */
59
+ mark(message: string, context?: LogContext): void;
60
+ /**
61
+ * 记录性能指标
62
+ */
63
+ performance(operation: string, duration: number, context?: LogContext): void;
64
+ /**
65
+ * 记录操作开始
66
+ */
67
+ start(operation: string, context?: LogContext): () => void;
68
+ /**
69
+ * 内部日志方法
70
+ */
71
+ private log;
72
+ }
73
+ /**
74
+ * 创建 Logger 实例
75
+ */
76
+ export declare function createLogger(name: string, level?: LogLevel): Logger;
package/lib/logger.js ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * 增强的日志系统
3
+ * 提供结构化日志、错误追踪和上下文信息
4
+ */
5
+ import log4js from 'log4js';
6
+ import { ErrorHandler } from './errors.js';
7
+ const { getLogger } = log4js;
8
+ /**
9
+ * 增强的 Logger 类
10
+ */
11
+ export class Logger {
12
+ logger;
13
+ context = {};
14
+ constructor(name, level) {
15
+ this.logger = getLogger(name);
16
+ if (level) {
17
+ this.logger.level = level;
18
+ }
19
+ }
20
+ /**
21
+ * 设置日志级别
22
+ */
23
+ setLevel(level) {
24
+ this.logger.level = level;
25
+ }
26
+ /**
27
+ * 添加上下文信息
28
+ */
29
+ withContext(context) {
30
+ const newLogger = new Logger(this.logger.category, this.logger.level);
31
+ newLogger.context = { ...this.context, ...context };
32
+ return newLogger;
33
+ }
34
+ /**
35
+ * Trace 级别日志
36
+ */
37
+ trace(message, context) {
38
+ this.log('trace', message, context);
39
+ }
40
+ /**
41
+ * Debug 级别日志
42
+ */
43
+ debug(message, context) {
44
+ this.log('debug', message, context);
45
+ }
46
+ /**
47
+ * Info 级别日志
48
+ */
49
+ info(message, context) {
50
+ this.log('info', message, context);
51
+ }
52
+ /**
53
+ * Warn 级别日志
54
+ */
55
+ warn(message, context) {
56
+ this.log('warn', message, context);
57
+ }
58
+ /**
59
+ * Error 级别日志
60
+ */
61
+ error(message, context) {
62
+ if (typeof message === 'object' && message !== null) {
63
+ if (message instanceof Error || message.category !== undefined) {
64
+ const error = ErrorHandler.wrap(message, context);
65
+ this.log('error', error.message, {
66
+ ...context,
67
+ error: error.toJSON(),
68
+ });
69
+ return;
70
+ }
71
+ }
72
+ this.log('error', message, context);
73
+ }
74
+ /**
75
+ * Fatal 级别日志
76
+ */
77
+ fatal(message, context) {
78
+ if (typeof message === 'object' && message !== null) {
79
+ if (message instanceof Error || message.category !== undefined) {
80
+ const error = ErrorHandler.wrap(message, context);
81
+ this.log('fatal', error.message, {
82
+ ...context,
83
+ error: error.toJSON(),
84
+ });
85
+ return;
86
+ }
87
+ }
88
+ this.log('fatal', message, context);
89
+ }
90
+ /**
91
+ * Mark 级别日志
92
+ */
93
+ mark(message, context) {
94
+ this.log('mark', message, context);
95
+ }
96
+ /**
97
+ * 记录性能指标
98
+ */
99
+ performance(operation, duration, context) {
100
+ this.info(`Performance: ${operation} took ${duration}ms`, {
101
+ ...context,
102
+ operation,
103
+ duration,
104
+ type: 'performance',
105
+ });
106
+ }
107
+ /**
108
+ * 记录操作开始
109
+ */
110
+ start(operation, context) {
111
+ const startTime = Date.now();
112
+ this.debug(`Starting: ${operation}`, context);
113
+ return () => {
114
+ const duration = Date.now() - startTime;
115
+ this.performance(operation, duration, context);
116
+ };
117
+ }
118
+ /**
119
+ * 内部日志方法
120
+ */
121
+ log(level, message, context) {
122
+ const mergedContext = { ...this.context, ...context };
123
+ const logMessage = mergedContext && Object.keys(mergedContext).length > 0
124
+ ? `${message} ${JSON.stringify(mergedContext)}`
125
+ : message;
126
+ switch (level) {
127
+ case 'trace':
128
+ this.logger.trace(logMessage);
129
+ break;
130
+ case 'debug':
131
+ this.logger.debug(logMessage);
132
+ break;
133
+ case 'info':
134
+ this.logger.info(logMessage);
135
+ break;
136
+ case 'warn':
137
+ this.logger.warn(logMessage);
138
+ break;
139
+ case 'error':
140
+ this.logger.error(logMessage);
141
+ break;
142
+ case 'fatal':
143
+ this.logger.fatal(logMessage);
144
+ break;
145
+ case 'mark':
146
+ this.logger.mark(logMessage);
147
+ break;
148
+ }
149
+ }
150
+ }
151
+ /**
152
+ * 创建 Logger 实例
153
+ */
154
+ export function createLogger(name, level) {
155
+ return new Logger(name, level);
156
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 性能指标收集系统
3
+ * 收集请求数、响应时间、错误率等指标
4
+ */
5
+ export interface MetricValue {
6
+ value: number;
7
+ timestamp: number;
8
+ labels?: Record<string, string>;
9
+ }
10
+ export interface Metric {
11
+ name: string;
12
+ type: 'counter' | 'gauge' | 'histogram';
13
+ help: string;
14
+ values: MetricValue[];
15
+ labels?: Record<string, string>;
16
+ }
17
+ /**
18
+ * 指标收集器
19
+ */
20
+ export declare class MetricsCollector {
21
+ private metrics;
22
+ private readonly maxSamples;
23
+ /**
24
+ * 增加计数器
25
+ */
26
+ increment(name: string, value?: number, labels?: Record<string, string>): void;
27
+ /**
28
+ * 设置仪表值
29
+ */
30
+ set(name: string, value: number, labels?: Record<string, string>): void;
31
+ /**
32
+ * 记录直方图值
33
+ */
34
+ observe(name: string, value: number, labels?: Record<string, string>): void;
35
+ /**
36
+ * 获取或创建指标
37
+ */
38
+ private getOrCreateMetric;
39
+ /**
40
+ * 获取指标键
41
+ */
42
+ private getMetricKey;
43
+ /**
44
+ * 修剪样本数量
45
+ */
46
+ private trimSamples;
47
+ /**
48
+ * 获取指标
49
+ */
50
+ getMetric(name: string, labels?: Record<string, string>): Metric | undefined;
51
+ /**
52
+ * 获取所有指标
53
+ */
54
+ getAllMetrics(): Metric[];
55
+ /**
56
+ * 获取最新值
57
+ */
58
+ getLatestValue(name: string, labels?: Record<string, string>): number | undefined;
59
+ /**
60
+ * 计算平均值
61
+ */
62
+ getAverage(name: string, labels?: Record<string, string>, windowMs?: number): number | undefined;
63
+ /**
64
+ * 计算总和
65
+ */
66
+ getSum(name: string, labels?: Record<string, string>, windowMs?: number): number | undefined;
67
+ /**
68
+ * 导出为 Prometheus 格式
69
+ */
70
+ exportPrometheus(): string;
71
+ /**
72
+ * 清理过期数据
73
+ */
74
+ cleanup(maxAge?: number): void;
75
+ /**
76
+ * 重置所有指标
77
+ */
78
+ reset(): void;
79
+ }
80
+ export declare const metrics: MetricsCollector;