@maiyunnet/kebab 10.0.0 → 10.1.1
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/abox/ratelimit.d.ts +3 -0
- package/abox/ratelimit.js +84 -0
- package/doc/kebab-rag.md +555 -381
- package/index.d.ts +3 -2
- package/index.js +1 -1
- package/lib/db/conn.d.ts +4 -2
- package/lib/db/pool.d.ts +17 -4
- package/lib/db/pool.js +41 -23
- package/lib/db/tran.d.ts +6 -4
- package/lib/db.d.ts +10 -5
- package/lib/db.js +36 -6
- package/lib/kv.d.ts +1 -1
- package/lib/kv.js +60 -6
- package/lib/ratelimit.d.ts +16 -22
- package/lib/ratelimit.js +14 -76
- package/package.json +1 -1
- package/sys/cmd.js +0 -13
- package/sys/ctr.d.ts +2 -2
- package/sys/ctr.js +2 -2
- package/sys/mod.d.ts +16 -0
- package/sys/mod.js +33 -15
- package/www/example/ctr/test.d.ts +1 -1
- package/www/example/ctr/test.js +26 -7
- package/www/example/mod/test.js +0 -1
package/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import type * as tls from 'node:tls';
|
|
7
7
|
/** --- 当前系统版本号 --- */
|
|
8
|
-
export declare const VER = "10.
|
|
8
|
+
export declare const VER = "10.1.1";
|
|
9
9
|
/** --- 框架根目录,以 / 结尾 --- */
|
|
10
10
|
export declare const ROOT_PATH: string;
|
|
11
11
|
/** --- 框架的 LIB,以 / 结尾 --- */
|
|
@@ -41,7 +41,8 @@ export interface IConfig {
|
|
|
41
41
|
'const': IConfigConst;
|
|
42
42
|
'db': Record<string, {
|
|
43
43
|
'default': IConfigDb;
|
|
44
|
-
|
|
44
|
+
/** --- 可选只读从库配置,支持单节点或节点数组;省略的字段自动继承 default --- */
|
|
45
|
+
'read'?: Partial<IConfigDb> | Array<Partial<IConfigDb>>;
|
|
45
46
|
}> & {
|
|
46
47
|
'default': 'MYSQL' | 'PGSQL';
|
|
47
48
|
};
|
package/index.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* --- 本文件用来定义每个目录实体地址的常量 ---
|
|
5
5
|
*/
|
|
6
6
|
/** --- 当前系统版本号 --- */
|
|
7
|
-
export const VER = '10.
|
|
7
|
+
export const VER = '10.1.1';
|
|
8
8
|
// --- 服务端用的路径 ---
|
|
9
9
|
const imu = decodeURIComponent(import.meta.url).replace('file://', '').replace(/^\/(\w:)/, '$1');
|
|
10
10
|
/** --- /xxx/xxx --- */
|
package/lib/db/conn.d.ts
CHANGED
|
@@ -76,17 +76,19 @@ export declare class Connection {
|
|
|
76
76
|
* --- 执行一条 SQL 并获得返回数据 ---
|
|
77
77
|
* @param sql 执行的 SQL 字符串
|
|
78
78
|
* @param values SQL 占位符绑定的值
|
|
79
|
+
* @param opt 查询选项(单连接模式下忽略)
|
|
79
80
|
* @returns 查询结果,result = -500 表示查询失败
|
|
80
81
|
*/
|
|
81
|
-
query(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData>;
|
|
82
|
+
query(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData>;
|
|
82
83
|
/**
|
|
83
84
|
* --- 执行一条 SQL,按指定类型返回数据行 ---
|
|
84
85
|
* @typeParam TRow SQL 返回的行结构,由调用方根据查询字段指定
|
|
85
86
|
* @param sql 执行的 SQL 字符串
|
|
86
87
|
* @param values SQL 占位符绑定的值
|
|
88
|
+
* @param opt 查询选项(单连接模式下忽略)
|
|
87
89
|
* @returns 查询结果,result = -500 表示查询失败
|
|
88
90
|
*/
|
|
89
|
-
query<TRow extends object>(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData<TRow>>;
|
|
91
|
+
query<TRow extends object>(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData<TRow>>;
|
|
90
92
|
/**
|
|
91
93
|
* --- 执行一条 SQL 并获得影响行数对象 packet ---
|
|
92
94
|
* @param sql 执行的 SQL 字符串
|
package/lib/db/pool.d.ts
CHANGED
|
@@ -25,11 +25,15 @@ export declare class Pool {
|
|
|
25
25
|
private _queries;
|
|
26
26
|
/** --- 当前服务商 --- */
|
|
27
27
|
private readonly _service;
|
|
28
|
-
/** --- 当前 Pool
|
|
28
|
+
/** --- 当前 Pool 对象的主库连接信息 --- */
|
|
29
29
|
private readonly _etc;
|
|
30
|
+
/** --- 当前 Pool 对象的只读从库连接列表 --- */
|
|
31
|
+
private readonly _read;
|
|
30
32
|
constructor(etc: kebab.IConfigDb, opt: {
|
|
31
33
|
/** --- 服务商 --- */
|
|
32
34
|
'service': lDb.ESERVICE;
|
|
35
|
+
/** --- 可选只读从库连接列表 --- */
|
|
36
|
+
'read'?: kebab.IConfigDb[];
|
|
33
37
|
});
|
|
34
38
|
/** --- 获取当前连接的服务商 --- */
|
|
35
39
|
getService(): lDb.ESERVICE;
|
|
@@ -39,17 +43,19 @@ export declare class Pool {
|
|
|
39
43
|
* --- 执行一条 SQL,无视顺序和相同连接,随用随取 ---
|
|
40
44
|
* @param sql 执行的 SQL 字符串
|
|
41
45
|
* @param values SQL 占位符绑定的值
|
|
46
|
+
* @param opt 查询选项,read 为 true 且已配置从库时路由到只读从库
|
|
42
47
|
* @returns 查询结果,result = -500 表示系统错误
|
|
43
48
|
*/
|
|
44
|
-
query(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData>;
|
|
49
|
+
query(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData>;
|
|
45
50
|
/**
|
|
46
51
|
* --- 执行一条 SQL,按指定类型返回数据行 ---
|
|
47
52
|
* @typeParam TRow SQL 返回的行结构,由调用方根据查询字段指定
|
|
48
53
|
* @param sql 执行的 SQL 字符串
|
|
49
54
|
* @param values SQL 占位符绑定的值
|
|
55
|
+
* @param opt 查询选项,read 为 true 且已配置从库时路由到只读从库
|
|
50
56
|
* @returns 查询结果,result = -500 表示系统错误
|
|
51
57
|
*/
|
|
52
|
-
query<TRow extends object>(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData<TRow>>;
|
|
58
|
+
query<TRow extends object>(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData<TRow>>;
|
|
53
59
|
/**
|
|
54
60
|
* --- 执行一条 SQL 并获得影响行数对象 packet,连接失败抛出错误 ---
|
|
55
61
|
* @param sql 执行的 SQL 字符串
|
|
@@ -61,7 +67,14 @@ export declare class Pool {
|
|
|
61
67
|
*/
|
|
62
68
|
beginTransaction(ctr: sCtr.Ctr | null): Promise<Transaction | null>;
|
|
63
69
|
/**
|
|
64
|
-
* ---
|
|
70
|
+
* --- 按读写标志选择本次目标连接配置;未开启 read 或未配置从库时返回主库 ---
|
|
71
|
+
* @param read 是否优先使用只读从库
|
|
72
|
+
* @returns 目标数据库连接配置
|
|
73
|
+
*/
|
|
74
|
+
private _pickEtc;
|
|
75
|
+
/**
|
|
76
|
+
* --- 获取一个连接,自动变为 using 状态;连接失败会返回 null ---
|
|
77
|
+
* @param targetEtc 目标连接配置,默认使用主库
|
|
65
78
|
*/
|
|
66
79
|
private _getConnection;
|
|
67
80
|
/**
|
package/lib/db/pool.js
CHANGED
|
@@ -103,11 +103,14 @@ export class Pool {
|
|
|
103
103
|
_queries = 0;
|
|
104
104
|
/** --- 当前服务商 --- */
|
|
105
105
|
_service;
|
|
106
|
-
/** --- 当前 Pool
|
|
106
|
+
/** --- 当前 Pool 对象的主库连接信息 --- */
|
|
107
107
|
_etc;
|
|
108
|
+
/** --- 当前 Pool 对象的只读从库连接列表 --- */
|
|
109
|
+
_read;
|
|
108
110
|
constructor(etc, opt) {
|
|
109
111
|
this._etc = etc;
|
|
110
112
|
this._service = opt.service;
|
|
113
|
+
this._read = (opt.read ?? []).filter(item => Boolean(item.host));
|
|
111
114
|
}
|
|
112
115
|
/** --- 获取当前连接的服务商 --- */
|
|
113
116
|
getService() {
|
|
@@ -117,10 +120,10 @@ export class Pool {
|
|
|
117
120
|
getName() {
|
|
118
121
|
return this._etc.name ?? '';
|
|
119
122
|
}
|
|
120
|
-
async query(sql, values) {
|
|
123
|
+
async query(sql, values, opt = {}) {
|
|
121
124
|
++this._queries;
|
|
122
125
|
// --- 获取并自动 using ---
|
|
123
|
-
const conn = await this._getConnection();
|
|
126
|
+
const conn = await this._getConnection(this._pickEtc(opt.read));
|
|
124
127
|
if (!conn) {
|
|
125
128
|
return {
|
|
126
129
|
'rows': null,
|
|
@@ -177,17 +180,32 @@ export class Pool {
|
|
|
177
180
|
return null;
|
|
178
181
|
}
|
|
179
182
|
/**
|
|
180
|
-
* ---
|
|
183
|
+
* --- 按读写标志选择本次目标连接配置;未开启 read 或未配置从库时返回主库 ---
|
|
184
|
+
* @param read 是否优先使用只读从库
|
|
185
|
+
* @returns 目标数据库连接配置
|
|
186
|
+
*/
|
|
187
|
+
_pickEtc(read) {
|
|
188
|
+
if (!read || this._read.length === 0) {
|
|
189
|
+
return this._etc;
|
|
190
|
+
}
|
|
191
|
+
if (this._read.length === 1) {
|
|
192
|
+
return this._read[0];
|
|
193
|
+
}
|
|
194
|
+
return this._read[Math.floor(Math.random() * this._read.length)];
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* --- 获取一个连接,自动变为 using 状态;连接失败会返回 null ---
|
|
198
|
+
* @param targetEtc 目标连接配置,默认使用主库
|
|
181
199
|
*/
|
|
182
|
-
async _getConnection() {
|
|
200
|
+
async _getConnection(targetEtc = this._etc) {
|
|
183
201
|
let conn = null;
|
|
184
202
|
for (const connection of connections) {
|
|
185
203
|
const etc = connection.getEtc();
|
|
186
204
|
const service = connection.getService();
|
|
187
|
-
if ((etc.host !==
|
|
188
|
-
(etc.port !==
|
|
189
|
-
(etc.name !==
|
|
190
|
-
(etc.user !==
|
|
205
|
+
if ((etc.host !== targetEtc.host) ||
|
|
206
|
+
(etc.port !== targetEtc.port) ||
|
|
207
|
+
(etc.name !== targetEtc.name) ||
|
|
208
|
+
(etc.user !== targetEtc.user) ||
|
|
191
209
|
(service !== this._service)) {
|
|
192
210
|
// --- 配置项连接项不匹配 ---
|
|
193
211
|
continue;
|
|
@@ -208,12 +226,12 @@ export class Pool {
|
|
|
208
226
|
case lDb.ESERVICE.MYSQL: {
|
|
209
227
|
// --- MYSQL ---
|
|
210
228
|
const link = await mysql2.createConnection({
|
|
211
|
-
'host':
|
|
212
|
-
'port':
|
|
213
|
-
'charset':
|
|
214
|
-
'database':
|
|
215
|
-
'user':
|
|
216
|
-
'password':
|
|
229
|
+
'host': targetEtc.host,
|
|
230
|
+
'port': targetEtc.port,
|
|
231
|
+
'charset': targetEtc.charset,
|
|
232
|
+
'database': targetEtc.name,
|
|
233
|
+
'user': targetEtc.user,
|
|
234
|
+
'password': targetEtc.pwd,
|
|
217
235
|
'connectTimeout': 3_000,
|
|
218
236
|
typeCast: (field, next) => {
|
|
219
237
|
if (field.type !== 'GEOMETRY') {
|
|
@@ -232,7 +250,7 @@ export class Pool {
|
|
|
232
250
|
return geo[0];
|
|
233
251
|
},
|
|
234
252
|
});
|
|
235
|
-
const c = new Connection(
|
|
253
|
+
const c = new Connection(targetEtc, link);
|
|
236
254
|
c.using();
|
|
237
255
|
link.on('error', function (err) {
|
|
238
256
|
c.setLost();
|
|
@@ -253,15 +271,15 @@ export class Pool {
|
|
|
253
271
|
case lDb.ESERVICE.PGSQL: {
|
|
254
272
|
// --- PGSQL ---
|
|
255
273
|
const link = new pg.Client({
|
|
256
|
-
'host':
|
|
257
|
-
'port':
|
|
258
|
-
'database':
|
|
259
|
-
'user':
|
|
260
|
-
'password':
|
|
274
|
+
'host': targetEtc.host,
|
|
275
|
+
'port': targetEtc.port,
|
|
276
|
+
'database': targetEtc.name,
|
|
277
|
+
'user': targetEtc.user,
|
|
278
|
+
'password': targetEtc.pwd,
|
|
261
279
|
'connectionTimeoutMillis': 3_000,
|
|
262
280
|
});
|
|
263
281
|
await link.connect();
|
|
264
|
-
const c = new Connection(
|
|
282
|
+
const c = new Connection(targetEtc, link);
|
|
265
283
|
c.using();
|
|
266
284
|
link.on('error', err => {
|
|
267
285
|
c.setLost();
|
|
@@ -283,7 +301,7 @@ export class Pool {
|
|
|
283
301
|
await lCore.sleep(300);
|
|
284
302
|
continue;
|
|
285
303
|
}
|
|
286
|
-
const msg = `[DB][_getConnection][${lDb.ESERVICE[this._service]}] ${message}(${
|
|
304
|
+
const msg = `[DB][_getConnection][${lDb.ESERVICE[this._service]}] ${message}(${targetEtc.host}:${targetEtc.port})`;
|
|
287
305
|
lCore.debug(msg);
|
|
288
306
|
lCore.log({}, msg, '-error');
|
|
289
307
|
break;
|
package/lib/db/tran.d.ts
CHANGED
|
@@ -17,20 +17,22 @@ export declare class Transaction {
|
|
|
17
17
|
/** --- 获取当前连接的服务商 --- */
|
|
18
18
|
getService(): lDb.ESERVICE | null;
|
|
19
19
|
/**
|
|
20
|
-
* --- 在事务连接中执行一条 SQL ---
|
|
20
|
+
* --- 在事务连接中执行一条 SQL(事务内始终走当前主库连接,忽略 read 选项) ---
|
|
21
21
|
* @param sql 执行的 SQL 字符串
|
|
22
22
|
* @param values SQL 占位符绑定的值
|
|
23
|
+
* @param opt 查询选项(事务内忽略)
|
|
23
24
|
* @returns 查询结果,result = -500 表示事务已关闭或查询失败
|
|
24
25
|
*/
|
|
25
|
-
query(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData>;
|
|
26
|
+
query(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData>;
|
|
26
27
|
/**
|
|
27
|
-
* --- 在事务连接中执行一条 SQL
|
|
28
|
+
* --- 在事务连接中执行一条 SQL,按指定类型返回数据行(事务内始终走当前主库连接,忽略 read 选项) ---
|
|
28
29
|
* @typeParam TRow SQL 返回的行结构,由调用方根据查询字段指定
|
|
29
30
|
* @param sql 执行的 SQL 字符串
|
|
30
31
|
* @param values SQL 占位符绑定的值
|
|
32
|
+
* @param opt 查询选项(事务内忽略)
|
|
31
33
|
* @returns 查询结果,result = -500 表示事务已关闭或查询失败
|
|
32
34
|
*/
|
|
33
|
-
query<TRow extends object>(sql: string, values?: kebab.DbValue[]): Promise<lDb.IData<TRow>>;
|
|
35
|
+
query<TRow extends object>(sql: string, values?: kebab.DbValue[], opt?: lDb.IQueryOptions): Promise<lDb.IData<TRow>>;
|
|
34
36
|
/**
|
|
35
37
|
* --- 执行一条 SQL 并获得影响行数对象 packet,连接失败抛出错误 ---
|
|
36
38
|
* @param sql 执行的 SQL 字符串
|
package/lib/db.d.ts
CHANGED
|
@@ -51,16 +51,21 @@ export interface IPacket {
|
|
|
51
51
|
/** --- 1-正常,-500-服务器错误 --- */
|
|
52
52
|
'result': number;
|
|
53
53
|
}
|
|
54
|
+
/** --- query 查询选项 --- */
|
|
55
|
+
export interface IQueryOptions {
|
|
56
|
+
/** --- 是否优先使用只读从库,默认 false(走主库);未配置从库时自动走主库 --- */
|
|
57
|
+
'read'?: boolean;
|
|
58
|
+
}
|
|
54
59
|
/**
|
|
55
|
-
* --- 获取 Db Pool
|
|
56
|
-
* @param ctrEtc
|
|
60
|
+
* --- 获取 Db Pool 对象(单 Pool 内同时管理主库和可选只读从库) ---
|
|
61
|
+
* @param ctrEtc 控制器对象或主库连接配置
|
|
57
62
|
* @param opt 选项
|
|
58
63
|
* @returns Db Pool 对象
|
|
59
64
|
*/
|
|
60
65
|
export declare function get(ctrEtc: sCtr.Ctr | kebab.IConfigDb, opt?: {
|
|
61
|
-
/** ---
|
|
66
|
+
/** --- 服务商,未传时从控制器配置读取,直接传配置时默认 PGSQL --- */
|
|
62
67
|
'service'?: ESERVICE;
|
|
63
|
-
/** ---
|
|
64
|
-
'read'?:
|
|
68
|
+
/** --- 可选只读从库配置,传入时覆盖控制器配置中的 read --- */
|
|
69
|
+
'read'?: Partial<kebab.IConfigDb> | Array<Partial<kebab.IConfigDb>>;
|
|
65
70
|
}): Pool;
|
|
66
71
|
export { Connection, Pool, IConnectionInfo, getConnectionList, Transaction };
|
package/lib/db.js
CHANGED
|
@@ -14,8 +14,35 @@ export var ESERVICE;
|
|
|
14
14
|
ESERVICE[ESERVICE["PGSQL"] = 1] = "PGSQL";
|
|
15
15
|
})(ESERVICE || (ESERVICE = {}));
|
|
16
16
|
/**
|
|
17
|
-
* ---
|
|
18
|
-
* @param
|
|
17
|
+
* --- 将只读从库配置规范化为完整连接列表,省略字段自动继承主库 ---
|
|
18
|
+
* @param primary 主库连接配置
|
|
19
|
+
* @param read 只读从库配置(单对象或数组)
|
|
20
|
+
* @returns 有效的只读从库连接列表
|
|
21
|
+
*/
|
|
22
|
+
function normalizeReadConfigs(primary, read) {
|
|
23
|
+
if (!read) {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
const items = Array.isArray(read) ? read : [read];
|
|
27
|
+
const list = [];
|
|
28
|
+
for (const item of items) {
|
|
29
|
+
if (!item?.host) {
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
list.push({
|
|
33
|
+
'host': item.host,
|
|
34
|
+
'port': item.port ?? primary.port,
|
|
35
|
+
'charset': item.charset ?? primary.charset,
|
|
36
|
+
'name': item.name ?? primary.name,
|
|
37
|
+
'user': item.user ?? primary.user,
|
|
38
|
+
'pwd': item.pwd ?? primary.pwd,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return list;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* --- 获取 Db Pool 对象(单 Pool 内同时管理主库和可选只读从库) ---
|
|
45
|
+
* @param ctrEtc 控制器对象或主库连接配置
|
|
19
46
|
* @param opt 选项
|
|
20
47
|
* @returns Db Pool 对象
|
|
21
48
|
*/
|
|
@@ -23,15 +50,18 @@ export function get(ctrEtc, opt = {}) {
|
|
|
23
50
|
if (ctrEtc instanceof sCtr.Ctr) {
|
|
24
51
|
// --- 从 ctr 中读取连接信息 ---
|
|
25
52
|
const config = ctrEtc.getPrototype('_config');
|
|
26
|
-
const service = opt.service ? ESERVICE[opt.service] : config.db.default;
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
return new Pool(
|
|
53
|
+
const service = opt.service !== undefined ? ESERVICE[opt.service] : config.db.default;
|
|
54
|
+
const primary = config.db[service].default;
|
|
55
|
+
const read = normalizeReadConfigs(primary, opt.read ?? config.db[service].read);
|
|
56
|
+
return new Pool(primary, {
|
|
30
57
|
'service': service === 'MYSQL' ? ESERVICE.MYSQL : ESERVICE.PGSQL,
|
|
58
|
+
'read': read,
|
|
31
59
|
});
|
|
32
60
|
}
|
|
61
|
+
const read = normalizeReadConfigs(ctrEtc, opt.read);
|
|
33
62
|
return new Pool(ctrEtc, {
|
|
34
63
|
'service': opt.service ?? ESERVICE.PGSQL,
|
|
64
|
+
'read': read,
|
|
35
65
|
});
|
|
36
66
|
}
|
|
37
67
|
export { Connection, Pool, getConnectionList, Transaction };
|
package/lib/kv.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export declare class Kv {
|
|
|
42
42
|
*/
|
|
43
43
|
pipeline(): Promise<TRedisMulti | false>;
|
|
44
44
|
/**
|
|
45
|
-
* --- 在共享连接上执行一个 Redis Lua
|
|
45
|
+
* --- 在共享连接上执行一个 Redis Lua 脚本,首次走 EVAL 加载,后续走 EVALSHA 并在 NOSCRIPT 时自动回退 ---
|
|
46
46
|
* @param script Lua 源码
|
|
47
47
|
* @param keys 传给 KEYS 的完整键名,调用方需自行添加项目前缀
|
|
48
48
|
* @param args 传给 ARGV 的参数
|
package/lib/kv.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Project: Kebab, User: JianSuoQiYue
|
|
3
3
|
* Date: 2019-5-30 19:25:22
|
|
4
4
|
*/
|
|
5
|
+
// --- 原生 ---
|
|
6
|
+
import * as crypto from 'node:crypto';
|
|
5
7
|
// --- 第三方 ---
|
|
6
8
|
import * as redis from 'redis';
|
|
7
9
|
import * as lText from '#kebab/lib/text.js';
|
|
@@ -9,6 +11,37 @@ import * as lCore from '#kebab/lib/core.js';
|
|
|
9
11
|
import * as sCtr from '#kebab/sys/ctr.js';
|
|
10
12
|
/** --- 相同地址、数据库和凭据共用一次连接初始化 --- */
|
|
11
13
|
const connections = [];
|
|
14
|
+
/** --- 缓存已加载的 Lua 源码与其 SHA-1(LRU 上限 256 条),后续直接走 EVALSHA --- */
|
|
15
|
+
const evalShaCache = new Map();
|
|
16
|
+
/**
|
|
17
|
+
* --- 读取并刷新 Lua 源码的缓存 SHA-1(LRU) ---
|
|
18
|
+
* @param script Lua 源码
|
|
19
|
+
* @returns 已缓存的 40 位 SHA-1,未缓存返回 null
|
|
20
|
+
*/
|
|
21
|
+
function getCachedScriptSha(script) {
|
|
22
|
+
const cached = evalShaCache.get(script);
|
|
23
|
+
if (!cached) {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
evalShaCache.delete(script);
|
|
27
|
+
evalShaCache.set(script, cached);
|
|
28
|
+
return cached;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* --- 计算并记录 Lua 源码的 SHA-1 到定长 LRU 缓存 ---
|
|
32
|
+
* @param script Lua 源码
|
|
33
|
+
*/
|
|
34
|
+
function cacheScriptSha(script) {
|
|
35
|
+
const sha = crypto.createHash('sha1').update(script).digest('hex');
|
|
36
|
+
evalShaCache.delete(script);
|
|
37
|
+
if (evalShaCache.size >= 256) {
|
|
38
|
+
const oldest = evalShaCache.keys().next().value;
|
|
39
|
+
if (oldest !== undefined) {
|
|
40
|
+
evalShaCache.delete(oldest);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
evalShaCache.set(script, sha);
|
|
44
|
+
}
|
|
12
45
|
/**
|
|
13
46
|
* --- 生成 TLS 配置的缓存区分键,避免不同证书或 servername 误用同一连接 ---
|
|
14
47
|
* @param tlsOpt TLS 配置
|
|
@@ -154,7 +187,7 @@ export class Kv {
|
|
|
154
187
|
}
|
|
155
188
|
}
|
|
156
189
|
/**
|
|
157
|
-
* --- 在共享连接上执行一个 Redis Lua
|
|
190
|
+
* --- 在共享连接上执行一个 Redis Lua 脚本,首次走 EVAL 加载,后续走 EVALSHA 并在 NOSCRIPT 时自动回退 ---
|
|
158
191
|
* @param script Lua 源码
|
|
159
192
|
* @param keys 传给 KEYS 的完整键名,调用方需自行添加项目前缀
|
|
160
193
|
* @param args 传给 ARGV 的参数
|
|
@@ -165,13 +198,34 @@ export class Kv {
|
|
|
165
198
|
if (!conn) {
|
|
166
199
|
return false;
|
|
167
200
|
}
|
|
201
|
+
const options = {
|
|
202
|
+
'keys': keys,
|
|
203
|
+
'arguments': args,
|
|
204
|
+
};
|
|
205
|
+
const sha = getCachedScriptSha(script);
|
|
206
|
+
if (!sha) {
|
|
207
|
+
try {
|
|
208
|
+
const res = await conn.eval(script, options);
|
|
209
|
+
cacheScriptSha(script);
|
|
210
|
+
return res;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
168
216
|
try {
|
|
169
|
-
return await conn.
|
|
170
|
-
'keys': keys,
|
|
171
|
-
'arguments': args,
|
|
172
|
-
});
|
|
217
|
+
return await conn.evalSha(sha, options);
|
|
173
218
|
}
|
|
174
|
-
catch {
|
|
219
|
+
catch (err) {
|
|
220
|
+
// --- 服务端重启或清理脚本缓存后返回 NOSCRIPT,回退 EVAL 重新加载 ---
|
|
221
|
+
if (err instanceof Error && err.message.startsWith('NOSCRIPT')) {
|
|
222
|
+
try {
|
|
223
|
+
return await conn.eval(script, options);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
175
229
|
return false;
|
|
176
230
|
}
|
|
177
231
|
}
|
package/lib/ratelimit.d.ts
CHANGED
|
@@ -1,47 +1,41 @@
|
|
|
1
|
+
import type * as lKv from '#kebab/lib/kv.js';
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
* Date: 2026-3-22 00:00:00
|
|
4
|
-
* --- Rate Limiting 限速库,支持令牌桶和滑动窗口两种策略 ---
|
|
5
|
-
* --- 基于 KV(Redis)实现,天然支持多进程和多机部署 ---
|
|
6
|
-
*/
|
|
7
|
-
import * as lKv from '#kebab/lib/kv.js';
|
|
8
|
-
/**
|
|
9
|
-
* --- 检查指定 key 是否超速,使用多段近似滑动窗口算法 ---
|
|
3
|
+
* --- 检查指定 key 是否超出近似滑动窗口限额,超限请求同样计入次数 ---
|
|
10
4
|
* @param kv KV 实例
|
|
11
5
|
* @param key 限速标识(如 IP、用户 UID 等)
|
|
12
6
|
* @param opt 限速选项
|
|
13
|
-
* @returns
|
|
7
|
+
* @returns 检查结果;窗口开头最多多计一个时间段,Redis 无法检查时默认放行并标记 unavailable,failClosed 为 true 时拒绝
|
|
14
8
|
*/
|
|
15
|
-
export declare function check(kv: lKv.Kv, key: string, opt?:
|
|
16
|
-
/** --- 窗口时间(秒),默认 60 --- */
|
|
17
|
-
'window'?: number;
|
|
18
|
-
/** --- 窗口内最大请求数,默认 60 --- */
|
|
19
|
-
'max'?: number;
|
|
20
|
-
/** --- key 前缀,默认 rl: --- */
|
|
21
|
-
'pre'?: string;
|
|
22
|
-
}): Promise<ICheckResult>;
|
|
9
|
+
export declare function check(kv: lKv.Kv, key: string, opt?: ICheckOptions): Promise<ICheckResult>;
|
|
23
10
|
/**
|
|
24
|
-
* ---
|
|
11
|
+
* --- 检查指定 key 是否超出固定窗口限额,窗口从首次请求开始且超限请求同样计入次数 ---
|
|
25
12
|
* @param kv KV 实例
|
|
26
13
|
* @param key 限速标识
|
|
27
14
|
* @param opt 限速选项
|
|
15
|
+
* @returns 检查结果;后续请求沿用首次请求设置的过期时间,Redis 无法检查时默认放行并标记 unavailable,failClosed 为 true 时拒绝
|
|
28
16
|
*/
|
|
29
|
-
export declare function checkFixed(kv: lKv.Kv, key: string, opt?:
|
|
17
|
+
export declare function checkFixed(kv: lKv.Kv, key: string, opt?: ICheckOptions): Promise<ICheckResult>;
|
|
18
|
+
/** --- 限速检查选项 --- */
|
|
19
|
+
export interface ICheckOptions {
|
|
30
20
|
/** --- 窗口时间(秒),默认 60 --- */
|
|
31
21
|
'window'?: number;
|
|
32
22
|
/** --- 窗口内最大请求数,默认 60 --- */
|
|
33
23
|
'max'?: number;
|
|
34
24
|
/** --- key 前缀,默认 rl: --- */
|
|
35
25
|
'pre'?: string;
|
|
36
|
-
|
|
26
|
+
/** --- Redis 无法检查时是否拒绝请求,默认 false(放行) --- */
|
|
27
|
+
'failClosed'?: boolean;
|
|
28
|
+
}
|
|
37
29
|
/** --- 限速检查结果 --- */
|
|
38
30
|
export interface ICheckResult {
|
|
39
31
|
/** --- 是否允许通过 --- */
|
|
40
32
|
'allowed': boolean;
|
|
41
|
-
/** ---
|
|
33
|
+
/** --- 当前剩余可用次数 --- */
|
|
42
34
|
'remaining': number;
|
|
43
35
|
/** --- 总限额 --- */
|
|
44
36
|
'limit': number;
|
|
45
|
-
/** ---
|
|
37
|
+
/** --- 预计恢复额度的 Unix 秒,滑动窗口按此后没有新请求估算 --- */
|
|
46
38
|
'reset': number;
|
|
39
|
+
/** --- Redis 无法检查限额时为 true --- */
|
|
40
|
+
'unavailable'?: true;
|
|
47
41
|
}
|
package/lib/ratelimit.js
CHANGED
|
@@ -1,88 +1,26 @@
|
|
|
1
|
-
import * as lTime from '#kebab/lib/time.js';
|
|
2
|
-
import * as lCore from '#kebab/lib/core.js';
|
|
3
1
|
/**
|
|
4
|
-
*
|
|
2
|
+
* Project: Kebab
|
|
3
|
+
* Date: 2026-3-22 00:00:00
|
|
4
|
+
* --- 基于 Redis 的固定窗口和近似滑动窗口限速 ---
|
|
5
|
+
*/
|
|
6
|
+
import { checkRate } from '#kebab/abox/ratelimit.js';
|
|
7
|
+
/**
|
|
8
|
+
* --- 检查指定 key 是否超出近似滑动窗口限额,超限请求同样计入次数 ---
|
|
5
9
|
* @param kv KV 实例
|
|
6
10
|
* @param key 限速标识(如 IP、用户 UID 等)
|
|
7
11
|
* @param opt 限速选项
|
|
8
|
-
* @returns
|
|
12
|
+
* @returns 检查结果;窗口开头最多多计一个时间段,Redis 无法检查时默认放行并标记 unavailable,failClosed 为 true 时拒绝
|
|
9
13
|
*/
|
|
10
|
-
export
|
|
11
|
-
|
|
12
|
-
const max = Math.max(Math.floor(opt.max ?? 60), 1);
|
|
13
|
-
const pre = opt.pre ?? 'rl:';
|
|
14
|
-
const now = lTime.stamp();
|
|
15
|
-
/** --- 将窗口分为 6 个子段 --- */
|
|
16
|
-
const segSize = Math.max(Math.floor(window / 6), 1);
|
|
17
|
-
/** --- 当前段标识 --- */
|
|
18
|
-
const segId = Math.floor(now / segSize);
|
|
19
|
-
/** --- 需要统计的段数 --- */
|
|
20
|
-
const segCount = Math.ceil(window / segSize);
|
|
21
|
-
/** --- 统计各段请求数总和 --- */
|
|
22
|
-
let total = 0;
|
|
23
|
-
for (let i = 1; i < segCount; ++i) {
|
|
24
|
-
const segKey = `${pre}${key}:${segId - i}`;
|
|
25
|
-
const val = await kv.get(segKey);
|
|
26
|
-
if (val) {
|
|
27
|
-
total += parseInt(val) || 0;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
// --- 当前段 +1 ---
|
|
31
|
-
const currentSegKey = `${pre}${key}:${segId}`;
|
|
32
|
-
const count = await kv.incr(currentSegKey);
|
|
33
|
-
if (count === false) {
|
|
34
|
-
// --- KV 连接失败,放行 ---
|
|
35
|
-
lCore.debug('[RATELIMIT] KV incr failed, allow by default');
|
|
36
|
-
return {
|
|
37
|
-
'allowed': true,
|
|
38
|
-
'remaining': max,
|
|
39
|
-
'limit': max,
|
|
40
|
-
'reset': now + window,
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
if (count === 1) {
|
|
44
|
-
await kv.expire(currentSegKey, window + segSize);
|
|
45
|
-
}
|
|
46
|
-
total += count;
|
|
47
|
-
const allowed = total <= max;
|
|
48
|
-
return {
|
|
49
|
-
'allowed': allowed,
|
|
50
|
-
'remaining': allowed ? max - total : 0,
|
|
51
|
-
'limit': max,
|
|
52
|
-
'reset': (segId + 1) * segSize,
|
|
53
|
-
};
|
|
14
|
+
export function check(kv, key, opt = {}) {
|
|
15
|
+
return checkRate(kv, key, opt, 'sliding');
|
|
54
16
|
}
|
|
55
17
|
/**
|
|
56
|
-
* ---
|
|
18
|
+
* --- 检查指定 key 是否超出固定窗口限额,窗口从首次请求开始且超限请求同样计入次数 ---
|
|
57
19
|
* @param kv KV 实例
|
|
58
20
|
* @param key 限速标识
|
|
59
21
|
* @param opt 限速选项
|
|
22
|
+
* @returns 检查结果;后续请求沿用首次请求设置的过期时间,Redis 无法检查时默认放行并标记 unavailable,failClosed 为 true 时拒绝
|
|
60
23
|
*/
|
|
61
|
-
export
|
|
62
|
-
|
|
63
|
-
const max = Math.max(Math.floor(opt.max ?? 60), 1);
|
|
64
|
-
const pre = opt.pre ?? 'rl:';
|
|
65
|
-
const now = lTime.stamp();
|
|
66
|
-
const rkey = pre + key;
|
|
67
|
-
const count = await kv.incr(rkey);
|
|
68
|
-
if (count === false) {
|
|
69
|
-
// --- KV 连接失败,放行 ---
|
|
70
|
-
return {
|
|
71
|
-
'allowed': true,
|
|
72
|
-
'remaining': max,
|
|
73
|
-
'limit': max,
|
|
74
|
-
'reset': now + window,
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
if (count === 1) {
|
|
78
|
-
// --- 首次请求,设置过期时间 ---
|
|
79
|
-
await kv.expire(rkey, window);
|
|
80
|
-
}
|
|
81
|
-
const allowed = count <= max;
|
|
82
|
-
return {
|
|
83
|
-
'allowed': allowed,
|
|
84
|
-
'remaining': allowed ? max - count : 0,
|
|
85
|
-
'limit': max,
|
|
86
|
-
'reset': now + window,
|
|
87
|
-
};
|
|
24
|
+
export function checkFixed(kv, key, opt = {}) {
|
|
25
|
+
return checkRate(kv, key, opt, 'fixed');
|
|
88
26
|
}
|
package/package.json
CHANGED
package/sys/cmd.js
CHANGED
|
@@ -293,13 +293,6 @@ async function run() {
|
|
|
293
293
|
config.db['MYSQL'].default.name ??= 'maiyun';
|
|
294
294
|
config.db['MYSQL'].default.user ??= 'root';
|
|
295
295
|
config.db['MYSQL'].default.pwd ??= 'DashAdmin';
|
|
296
|
-
config.db['MYSQL'].read ??= {};
|
|
297
|
-
config.db['MYSQL'].read.host ??= '127.0.0.1';
|
|
298
|
-
config.db['MYSQL'].read.port ??= 3306;
|
|
299
|
-
config.db['MYSQL'].read.charset ??= 'utf8mb4';
|
|
300
|
-
config.db['MYSQL'].read.name ??= 'maiyun';
|
|
301
|
-
config.db['MYSQL'].read.user ??= 'root';
|
|
302
|
-
config.db['MYSQL'].read.pwd ??= 'DashAdmin';
|
|
303
296
|
config.db['PGSQL'] ??= {};
|
|
304
297
|
config.db['PGSQL'].default ??= {};
|
|
305
298
|
config.db['PGSQL'].default.host ??= '127.0.0.1';
|
|
@@ -307,12 +300,6 @@ async function run() {
|
|
|
307
300
|
config.db['PGSQL'].default.name ??= 'maiyun';
|
|
308
301
|
config.db['PGSQL'].default.user ??= 'root';
|
|
309
302
|
config.db['PGSQL'].default.pwd ??= 'DashAdmin';
|
|
310
|
-
config.db['PGSQL'].read ??= {};
|
|
311
|
-
config.db['PGSQL'].read.host ??= '127.0.0.1';
|
|
312
|
-
config.db['PGSQL'].read.port ??= 5432;
|
|
313
|
-
config.db['PGSQL'].read.name ??= 'maiyun';
|
|
314
|
-
config.db['PGSQL'].read.user ??= 'root';
|
|
315
|
-
config.db['PGSQL'].read.pwd ??= 'DashAdmin';
|
|
316
303
|
// --- config - dns ---
|
|
317
304
|
config.dns ??= {};
|
|
318
305
|
config.dns['DNSPOD'] ??= {};
|