@maiyunnet/kebab 9.29.6 → 10.1.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/abox/proxy.js +24 -2
- package/abox/response.js +36 -17
- package/abox/session-login.js +1 -13
- package/doc/kebab-rag.md +1687 -1061
- package/index.d.ts +14 -2
- package/index.js +1 -1
- package/lib/ai.d.ts +4 -0
- package/lib/ai.js +32 -16
- package/lib/cookie.d.ts +2 -0
- package/lib/cookie.js +47 -45
- package/lib/core.d.ts +26 -0
- package/lib/core.js +36 -13
- package/lib/cron.js +1 -8
- package/lib/crypto.js +20 -6
- package/lib/db/conn.d.ts +4 -2
- package/lib/db/conn.js +1 -0
- 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/fs.js +78 -31
- package/lib/kv.d.ts +182 -79
- package/lib/kv.js +518 -214
- package/lib/s3.d.ts +2 -0
- package/lib/s3.js +14 -27
- package/lib/session.d.ts +7 -0
- package/lib/session.js +23 -2
- package/lib/socket.d.ts +4 -1
- package/lib/socket.js +1 -0
- package/lib/sql.d.ts +0 -5
- package/lib/sql.js +48 -12
- package/lib/text.d.ts +10 -5
- package/lib/text.js +22 -12
- package/lib/turnstile.d.ts +6 -0
- package/lib/turnstile.js +16 -9
- package/lib/undici/response.d.ts +1 -1
- package/lib/undici.d.ts +7 -1
- package/lib/undici.js +72 -36
- package/lib/ws.d.ts +1 -1
- package/lib/ws.js +85 -128
- package/lib/zip.js +46 -45
- package/package.json +2 -2
- package/sys/child.js +178 -146
- package/sys/cmd.js +196 -210
- package/sys/ctr.d.ts +16 -16
- package/sys/ctr.js +147 -61
- package/sys/master.js +111 -80
- package/sys/mod.d.ts +24 -2
- package/sys/mod.js +56 -26
- package/sys/monitor/files.d.ts +2 -1
- package/sys/monitor/files.js +77 -21
- package/sys/monitor/watchdog.d.ts +7 -0
- package/sys/monitor/watchdog.js +311 -203
- package/sys/monitor.d.ts +59 -54
- package/sys/monitor.js +742 -681
- package/sys/route.d.ts +4 -4
- package/sys/route.js +93 -52
- package/www/example/ctr/test.d.ts +1 -1
- package/www/example/ctr/test.js +34 -15
- package/www/example/mod/test.js +0 -1
package/lib/db/conn.js
CHANGED
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/fs.js
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
* Date: 2019-3-29 23:03:07
|
|
4
4
|
* Last: 2020-3-11 22:21:51, 2022-12-29 01:18:25, 2023-12-13 20:50:09
|
|
5
5
|
*/
|
|
6
|
+
// --- 系统 ---
|
|
6
7
|
import * as fs from 'fs';
|
|
7
8
|
import * as crypto from 'crypto';
|
|
8
9
|
import * as http2 from 'http2';
|
|
9
10
|
import * as stream from 'stream';
|
|
11
|
+
// --- 第三方 ---
|
|
10
12
|
import * as mime from '@litert/mime';
|
|
13
|
+
// --- 库和定义 ---
|
|
11
14
|
import * as lText from './text.js';
|
|
12
15
|
import * as lCore from './core.js';
|
|
13
16
|
import * as lZlib from './zlib.js';
|
|
@@ -21,10 +24,10 @@ export async function getContent(path, options) {
|
|
|
21
24
|
const { encoding, start, end } = typeof options === 'string' ? { 'encoding': options } : options ?? {};
|
|
22
25
|
try {
|
|
23
26
|
if (start === undefined && end === undefined) {
|
|
24
|
-
return await fs.promises.readFile(path, { encoding });
|
|
27
|
+
return await fs.promises.readFile(path, { 'encoding': encoding });
|
|
25
28
|
}
|
|
26
29
|
const data = [];
|
|
27
|
-
for await (const chunk of createReadStream(path, { start, end })) {
|
|
30
|
+
for await (const chunk of createReadStream(path, { 'start': start, 'end': end })) {
|
|
28
31
|
data.push(chunk);
|
|
29
32
|
}
|
|
30
33
|
const content = Buffer.concat(data);
|
|
@@ -236,8 +239,8 @@ export async function readDir(path, encoding) {
|
|
|
236
239
|
*/
|
|
237
240
|
export async function copyFolder(from, to, ignore = []) {
|
|
238
241
|
let num = 0;
|
|
239
|
-
// ---
|
|
240
|
-
if (!await isDir(from)) {
|
|
242
|
+
// --- 如果源目录不存在、不是目录或为符号链接,则直接返回 0 ---
|
|
243
|
+
if (!await isDir(from.replace(/\/+$/, '') || from)) {
|
|
241
244
|
return 0;
|
|
242
245
|
}
|
|
243
246
|
// --- 遍历源目录文件和文件夹,准备复制 ---
|
|
@@ -323,14 +326,15 @@ export function createWriteStream(path, options) {
|
|
|
323
326
|
* @returns 区间列表;false 表示全部越界或区间过多;null 表示忽略请求头
|
|
324
327
|
*/
|
|
325
328
|
function parseFileRanges(value, size) {
|
|
329
|
+
// --- 校验单位与分段上限,防止客户端利用大量小区间放大读取开销 ---
|
|
326
330
|
if (!/^bytes=/i.test(value) || size === 0 || !Number.isSafeInteger(size)) {
|
|
327
331
|
return null;
|
|
328
332
|
}
|
|
329
333
|
const values = value.slice(6).split(',');
|
|
330
|
-
// --- 防止客户端利用大量小区间放大文件读取与响应开销 ---
|
|
331
334
|
if (value.length > 8192 || values.length > 16) {
|
|
332
335
|
return false;
|
|
333
336
|
}
|
|
337
|
+
// --- 逐段解析字节区间(用 BigInt 避免超大偏移被浮点取整) ---
|
|
334
338
|
const total = BigInt(size);
|
|
335
339
|
const ranges = [];
|
|
336
340
|
let count = 0;
|
|
@@ -340,11 +344,10 @@ function parseFileRanges(value, size) {
|
|
|
340
344
|
continue;
|
|
341
345
|
}
|
|
342
346
|
const match = /^(\d*)-(\d*)$/.exec(part);
|
|
343
|
-
if (!match || match[1] === '' && match[2] === '') {
|
|
347
|
+
if (!match || (match[1] === '' && match[2] === '')) {
|
|
344
348
|
return null;
|
|
345
349
|
}
|
|
346
350
|
++count;
|
|
347
|
-
// --- 先以 BigInt 解析,避免超大偏移被浮点取整后读错字节 ---
|
|
348
351
|
const start = match[1] !== '' ? BigInt(match[1]) : total - BigInt(match[2]);
|
|
349
352
|
const end = match[1] !== '' && match[2] !== '' ? BigInt(match[2]) : total - 1n;
|
|
350
353
|
if (match[1] !== '' && match[2] !== '' && end < start) {
|
|
@@ -356,7 +359,7 @@ function parseFileRanges(value, size) {
|
|
|
356
359
|
ranges.push({
|
|
357
360
|
'start': Number(start < 0n ? 0n : start),
|
|
358
361
|
'end': Number(end >= total ? total - 1n : end),
|
|
359
|
-
'order': count
|
|
362
|
+
'order': count,
|
|
360
363
|
});
|
|
361
364
|
}
|
|
362
365
|
if (count === 0) {
|
|
@@ -365,6 +368,7 @@ function parseFileRanges(value, size) {
|
|
|
365
368
|
if (ranges.length === 0) {
|
|
366
369
|
return false;
|
|
367
370
|
}
|
|
371
|
+
// --- 合并重叠或相邻区间,并按客户端请求顺序返回 ---
|
|
368
372
|
ranges.sort((a, b) => a.start - b.start);
|
|
369
373
|
const merged = [];
|
|
370
374
|
for (const range of ranges) {
|
|
@@ -413,7 +417,7 @@ async function* readFileRanges(path, ranges, headers, footer) {
|
|
|
413
417
|
*/
|
|
414
418
|
export async function readToResponse(path, req, res, stat) {
|
|
415
419
|
stat ??= await stats(path);
|
|
416
|
-
if (!stat) {
|
|
420
|
+
if (!stat?.isFile()) {
|
|
417
421
|
const content = '<h1>404 Not found</h1>';
|
|
418
422
|
res.setHeader('content-length', Buffer.byteLength(content));
|
|
419
423
|
lCore.writeHead(res, 404);
|
|
@@ -436,13 +440,14 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
436
440
|
res.setHeader('accept-ranges', 'bytes');
|
|
437
441
|
if (canCompress) {
|
|
438
442
|
const vary = res.getHeader('vary');
|
|
439
|
-
const
|
|
443
|
+
const rawVary = Array.isArray(vary) ? vary.join(',') : String(vary ?? '');
|
|
444
|
+
const values = rawVary.split(',').map((item) => item.trim()).filter(Boolean);
|
|
440
445
|
if (!values.some((item) => item === '*' || item.toLowerCase() === 'accept-encoding')) {
|
|
441
446
|
values.push('Accept-Encoding');
|
|
442
447
|
res.setHeader('vary', values.join(', '));
|
|
443
448
|
}
|
|
444
449
|
}
|
|
445
|
-
// ---
|
|
450
|
+
// --- 设置静态文件缓存策略 ---
|
|
446
451
|
if (['htm', 'html', 'css', 'js', 'mjs', 'xml', 'jpg', 'jpeg', 'svg', 'gif', 'png', 'json'].includes(mimeData.extension)) {
|
|
447
452
|
/** --- 静态文件默认缓存秒数 --- */
|
|
448
453
|
const cacheTTL = 600;
|
|
@@ -452,20 +457,31 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
452
457
|
else {
|
|
453
458
|
res.setHeader('cache-control', 'no-cache, must-revalidate');
|
|
454
459
|
}
|
|
455
|
-
// ---
|
|
460
|
+
// --- 条件请求校验(优先于 Range;弱 ETag 只能用于缓存验证,不能用于 If-Match) ---
|
|
456
461
|
const match = req.headers['if-match'];
|
|
457
462
|
const unmodifiedSince = req.headers['if-unmodified-since'];
|
|
458
|
-
|
|
463
|
+
const failedPrecondition = match !== undefined
|
|
464
|
+
? match.trim() !== '*'
|
|
465
|
+
: (unmodifiedSince !== undefined && modifiedTime > Date.parse(unmodifiedSince));
|
|
466
|
+
if (failedPrecondition) {
|
|
459
467
|
res.setHeader('content-length', 0);
|
|
460
468
|
lCore.writeHead(res, 412);
|
|
461
469
|
res.end();
|
|
462
470
|
return;
|
|
463
471
|
}
|
|
472
|
+
// --- 缓存未变更校验(If-None-Match / If-Modified-Since) ---
|
|
464
473
|
const noneMatch = req.headers['if-none-match'];
|
|
465
474
|
const modifiedSince = req.headers['if-modified-since'];
|
|
466
475
|
const isRead = req.method === 'GET' || req.method === 'HEAD';
|
|
467
|
-
|
|
468
|
-
|
|
476
|
+
let unchanged = false;
|
|
477
|
+
if (noneMatch !== undefined) {
|
|
478
|
+
const tag = hash.slice(2);
|
|
479
|
+
unchanged = noneMatch.trim() === '*' ||
|
|
480
|
+
noneMatch.split(',').some((item) => item.trim().replace(/^W\//, '') === tag);
|
|
481
|
+
}
|
|
482
|
+
else if (isRead && modifiedSince !== undefined) {
|
|
483
|
+
unchanged = modifiedTime <= Date.parse(modifiedSince);
|
|
484
|
+
}
|
|
469
485
|
if (unchanged) {
|
|
470
486
|
if (!isRead) {
|
|
471
487
|
res.setHeader('content-length', 0);
|
|
@@ -474,15 +490,21 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
474
490
|
res.end();
|
|
475
491
|
return;
|
|
476
492
|
}
|
|
493
|
+
// --- 解析 Range 与 If-Range ---
|
|
477
494
|
const contentType = mimeData.mime + charset;
|
|
478
495
|
res.setHeader('content-type', contentType);
|
|
479
496
|
const rangeHeader = req.headers['range'];
|
|
480
497
|
const ifRange = req.headers['if-range'];
|
|
481
498
|
// --- 日期必须精确匹配且至少早一秒;压缩与原始字节共享的日期不能作强校验,避免跨编码续传 ---
|
|
482
|
-
const rangeMatches = ifRange === undefined || typeof ifRange === 'string' &&
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
499
|
+
const rangeMatches = ifRange === undefined || (typeof ifRange === 'string' &&
|
|
500
|
+
!ifRange.includes('"') &&
|
|
501
|
+
Date.parse(ifRange) === modifiedTime &&
|
|
502
|
+
modifiedTime <= Date.now() - 1_000 &&
|
|
503
|
+
!canCompress);
|
|
504
|
+
let ranges = null;
|
|
505
|
+
if (req.method === 'GET' && rangeHeader !== undefined && rangeMatches) {
|
|
506
|
+
ranges = parseFileRanges(rangeHeader, stat.size);
|
|
507
|
+
}
|
|
486
508
|
if (ranges === false) {
|
|
487
509
|
res.setHeader('content-range', `bytes */${stat.size}`);
|
|
488
510
|
res.setHeader('content-length', 0);
|
|
@@ -490,19 +512,41 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
490
512
|
res.end();
|
|
491
513
|
return;
|
|
492
514
|
}
|
|
493
|
-
// ---
|
|
515
|
+
// --- 判断客户端支持的压缩模式(2 MiB 内缓冲压缩保留精确 Content-Length;大文件走流式压缩防 OOM) ---
|
|
494
516
|
const encoding = req.headers['accept-encoding'] ?? '';
|
|
495
517
|
if (ranges === null && canCompress && encoding !== '') {
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
518
|
+
if (stat.size <= 2 * 1024 * 1024) {
|
|
519
|
+
const compress = await lZlib.compress(encoding, await getContent(path));
|
|
520
|
+
if (compress) {
|
|
521
|
+
res.setHeader('content-encoding', compress.type);
|
|
522
|
+
res.setHeader('content-length', Buffer.byteLength(compress.buffer));
|
|
523
|
+
lCore.writeHead(res, 200);
|
|
524
|
+
res.end(req.method === 'HEAD' ? '' : compress.buffer);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
const compress = lZlib.createCompress(encoding);
|
|
530
|
+
if (compress) {
|
|
531
|
+
res.setHeader('content-encoding', compress.type);
|
|
532
|
+
res.removeHeader('content-length');
|
|
533
|
+
lCore.writeHead(res, 200);
|
|
534
|
+
if (req.method === 'HEAD') {
|
|
535
|
+
compress.compress.destroy();
|
|
536
|
+
res.end();
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
await stream.promises.pipeline(createReadStream(path), compress.compress, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
|
|
541
|
+
}
|
|
542
|
+
catch {
|
|
543
|
+
res.destroy();
|
|
544
|
+
}
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
504
547
|
}
|
|
505
548
|
}
|
|
549
|
+
// --- 设置完整响应或 206 部分响应头 ---
|
|
506
550
|
let headers = [];
|
|
507
551
|
let footer = Buffer.alloc(0);
|
|
508
552
|
if (ranges !== null && ranges.length > 1) {
|
|
@@ -510,7 +554,8 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
510
554
|
headers = ranges.map((range) => Buffer.from(`--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${range.start}-${range.end}/${stat.size}\r\n\r\n`));
|
|
511
555
|
footer = Buffer.from(`--${boundary}--\r\n`);
|
|
512
556
|
res.setHeader('content-type', `multipart/byteranges; boundary=${boundary}`);
|
|
513
|
-
|
|
557
|
+
const totalLength = ranges.reduce((length, range, i) => length + headers[i].length + (range.end - range.start + 1) + 2, footer.length);
|
|
558
|
+
res.setHeader('content-length', totalLength);
|
|
514
559
|
}
|
|
515
560
|
else if (ranges !== null) {
|
|
516
561
|
res.setHeader('content-range', `bytes ${ranges[0].start}-${ranges[0].end}/${stat.size}`);
|
|
@@ -524,8 +569,10 @@ export async function readToResponse(path, req, res, stat) {
|
|
|
524
569
|
res.end();
|
|
525
570
|
return;
|
|
526
571
|
}
|
|
527
|
-
|
|
528
|
-
|
|
572
|
+
// --- 流式输出文件内容 ---
|
|
573
|
+
const source = ranges !== null && ranges.length > 1
|
|
574
|
+
? stream.Readable.from(readFileRanges(path, ranges, headers, footer))
|
|
575
|
+
: createReadStream(path, ranges?.[0]);
|
|
529
576
|
try {
|
|
530
577
|
await stream.promises.pipeline(source, res instanceof http2.Http2ServerResponse ? (res.stream ?? res) : res);
|
|
531
578
|
}
|