@maiyunnet/kebab 9.26.5 → 9.27.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/sys/mod.d.ts CHANGED
@@ -43,6 +43,12 @@ export default class Mod {
43
43
  protected static _$table: string;
44
44
  /** --- 主键字段名 --- */
45
45
  protected static _$primary: string;
46
+ /**
47
+ * --- 表的分区字段名,如 ['time_push'] ---
48
+ * save、remove、refresh 默认会把这些字段加入 WHERE 条件,与主键一起查找记录。
49
+ * 读取记录后不要修改主键或分区字段;留空时只使用主键。
50
+ */
51
+ protected static _$partition: string[];
46
52
  /** --- 设置后将由 _keyGenerator 函数生成唯一字段 --- */
47
53
  protected static _$key: string;
48
54
  /** --- 自动 key 冲突目标:MySQL 为索引名;PGSQL 为唯一字段或字段数组,PG 留空使用 _$key,不支持部分或表达式索引 --- */
@@ -314,6 +320,11 @@ export default class Mod {
314
320
  * @param obj 要转换的 kv 数据列表
315
321
  */
316
322
  static toArrayByRecord<T extends Mod>(obj: Record<string, T>): Record<string, Record<string, any>>;
323
+ /**
324
+ * --- 构造包含主键和分区字段的 WHERE 条件 ---
325
+ * @returns 主键及分区字段条件,缺少字段时返回 false
326
+ */
327
+ private _getIdentityWhere;
317
328
  /**
318
329
  * --- 设置单个模型属性,并记录是否需要在数据库边界序列化 ---
319
330
  * @param key 字段名
@@ -348,16 +359,18 @@ export default class Mod {
348
359
  /**
349
360
  * --- 刷新当前模型获取最新数据 ---
350
361
  * @param lock 是否加锁
362
+ * @returns true 成功,null 记录不存在,false 缺少定位字段或查询失败
351
363
  */
352
364
  refresh(lock?: boolean): Promise<boolean | null>;
353
365
  /**
354
366
  * --- 更新 set 的数据到数据库,有未保存数据时才保存 ---
355
- * @param where 非空筛选条件,省略时必须有主键
356
- * @returns 是否成功,失败保留待写数据
367
+ * @param where 显式非空筛选条件;省略时使用主键和分区字段值
368
+ * @returns 是否成功,缺少默认定位字段或写入失败返回 false 并保留待写数据
357
369
  */
358
370
  save(where?: any): Promise<boolean>;
359
371
  /**
360
- * --- 移除本条目 ---
372
+ * --- 按主键和分区字段删除当前记录 ---
373
+ * @returns 是否成功,缺少定位字段、记录不存在或删除失败返回 false
361
374
  */
362
375
  remove(): Promise<boolean>;
363
376
  first(lock: boolean, array: true): Promise<false | null | Record<string, any>>;
package/sys/mod.js CHANGED
@@ -51,6 +51,12 @@ export default class Mod {
51
51
  static _$table = '';
52
52
  /** --- 主键字段名 --- */
53
53
  static _$primary = 'id';
54
+ /**
55
+ * --- 表的分区字段名,如 ['time_push'] ---
56
+ * save、remove、refresh 默认会把这些字段加入 WHERE 条件,与主键一起查找记录。
57
+ * 读取记录后不要修改主键或分区字段;留空时只使用主键。
58
+ */
59
+ static _$partition = [];
54
60
  /** --- 设置后将由 _keyGenerator 函数生成唯一字段 --- */
55
61
  static _$key = '';
56
62
  /** --- 自动 key 冲突目标:MySQL 为索引名;PGSQL 为唯一字段或字段数组,PG 留空使用 _$key,不支持部分或表达式索引 --- */
@@ -551,6 +557,25 @@ export default class Mod {
551
557
  return rtn;
552
558
  }
553
559
  // --- 动态方法 ---
560
+ /**
561
+ * --- 构造包含主键和分区字段的 WHERE 条件 ---
562
+ * @returns 主键及分区字段条件,缺少字段时返回 false
563
+ */
564
+ _getIdentityWhere() {
565
+ const cstr = this.constructor;
566
+ if (!cstr._$partition.length) {
567
+ return this._data[cstr._$primary] ? { [cstr._$primary]: this._data[cstr._$primary] } : false;
568
+ }
569
+ const where = {};
570
+ for (const field of new Set([cstr._$primary, ...cstr._$partition])) {
571
+ const value = this._data[field];
572
+ if (value === undefined || (field === cstr._$primary && value === null)) {
573
+ return false;
574
+ }
575
+ where[field] = value;
576
+ }
577
+ return where;
578
+ }
554
579
  /**
555
580
  * --- 设置单个模型属性,并记录是否需要在数据库边界序列化 ---
556
581
  * @param key 字段名
@@ -735,7 +760,7 @@ export default class Mod {
735
760
  }
736
761
  const mysql = this._db.getService() === lDb.ESERVICE.MYSQL;
737
762
  const table = cstr._$table + (this._index ? `_${this._index[0]}` : '');
738
- const identity = [...new Set([cstr._$primary, cstr._$key].filter(field => field))];
763
+ const identity = [...new Set([cstr._$primary, cstr._$key, ...cstr._$partition].filter(field => field))];
739
764
  if (mysql) {
740
765
  const created = await this.create();
741
766
  if (created !== null) {
@@ -782,16 +807,16 @@ export default class Mod {
782
807
  /**
783
808
  * --- 刷新当前模型获取最新数据 ---
784
809
  * @param lock 是否加锁
810
+ * @returns true 成功,null 记录不存在,false 缺少定位字段或查询失败
785
811
  */
786
812
  async refresh(lock = false) {
787
813
  const cstr = this.constructor;
788
- if (!this._data[cstr._$primary]) {
789
- lCore.log(this._ctr ?? {}, '[MOD][refresh] primary key not found', '-error');
814
+ const where = this._getIdentityWhere();
815
+ if (where === false) {
816
+ lCore.log(this._ctr ?? {}, '[MOD][refresh] primary or partition field not loaded', '-error');
790
817
  return false;
791
818
  }
792
- this._sql.select('*', cstr._$table + (this._index ? ('_' + this._index[0]) : '')).where([{
793
- [cstr._$primary]: this._data[cstr._$primary]
794
- }]);
819
+ this._sql.select('*', cstr._$table + (this._index ? ('_' + this._index[0]) : '')).where(where);
795
820
  if (lock) {
796
821
  this._sql.lock();
797
822
  }
@@ -812,24 +837,23 @@ export default class Mod {
812
837
  }
813
838
  /**
814
839
  * --- 更新 set 的数据到数据库,有未保存数据时才保存 ---
815
- * @param where 非空筛选条件,省略时必须有主键
816
- * @returns 是否成功,失败保留待写数据
840
+ * @param where 显式非空筛选条件;省略时使用主键和分区字段值
841
+ * @returns 是否成功,缺少默认定位字段或写入失败返回 false 并保留待写数据
817
842
  */
818
843
  async save(where) {
819
844
  if (Object.keys(this._updates).length === 0) {
820
845
  return true;
821
846
  }
822
847
  const cstr = this.constructor;
823
- if (!this._data[cstr._$primary] && (where === undefined || where === null)) {
824
- lCore.log(this._ctr ?? {}, '[MOD][save] primary key not found', '-error');
848
+ const filter = where ?? this._getIdentityWhere();
849
+ if (filter === false) {
850
+ lCore.log(this._ctr ?? {}, '[MOD][save] primary or partition field not loaded', '-error');
825
851
  return false;
826
852
  }
827
853
  const updates = this._getUpdates();
828
854
  this._sql.update(cstr._$table + (this._index ? ('_' + this._index[0]) : ''), [updates]);
829
855
  const updateSql = this._sql.getSql();
830
- this._sql.where(where ?? {
831
- [cstr._$primary]: this._data[cstr._$primary]
832
- });
856
+ this._sql.where(filter);
833
857
  if (this._sql.getSql() === updateSql) {
834
858
  return false;
835
859
  }
@@ -848,17 +872,17 @@ export default class Mod {
848
872
  }
849
873
  }
850
874
  /**
851
- * --- 移除本条目 ---
875
+ * --- 按主键和分区字段删除当前记录 ---
876
+ * @returns 是否成功,缺少定位字段、记录不存在或删除失败返回 false
852
877
  */
853
878
  async remove() {
854
879
  const cstr = this.constructor;
855
- if (!this._data[cstr._$primary]) {
856
- lCore.log(this._ctr ?? {}, '[MOD][remove] primary key not found', '-error');
880
+ const where = this._getIdentityWhere();
881
+ if (where === false) {
882
+ lCore.log(this._ctr ?? {}, '[MOD][remove] primary or partition field not loaded', '-error');
857
883
  return false;
858
884
  }
859
- this._sql.delete(cstr._$table + (this._index ? ('_' + this._index[0]) : '')).where([{
860
- [cstr._$primary]: this._data[cstr._$primary]
861
- }]);
885
+ this._sql.delete(cstr._$table + (this._index ? ('_' + this._index[0]) : '')).where(where);
862
886
  const r = await this._db.execute(this._sql.getSql(), this._sql.getData());
863
887
  if (r.packet === null) {
864
888
  lCore.log(this._ctr ?? {}, '[MOD][remove] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
@@ -71,7 +71,7 @@ function writeLog(msg) {
71
71
  const entry = {
72
72
  'time': `${ts.slice(8, 10)}:${ts.slice(10, 12)}:${ts.slice(12, 14)}`,
73
73
  'unix': Math.floor(now.getTime() / 1000),
74
- 'url': '', 'cookie': {}, 'session': {}, 'userAgent': '',
74
+ 'url': '', 'userAgent': '',
75
75
  'realIp': '', 'cfIp': '', 'xIp': '',
76
76
  'osMem': `${Math.round((os.totalmem() - os.freemem()) / 1024 / 1024 * 100) / 100}MB`,
77
77
  'procMem': `${Math.round(process.memoryUsage.rss() / 1024 / 1024 * 100) / 100}MB`,
@@ -83,10 +83,10 @@ function writeLog(msg) {
83
83
  }
84
84
  else {
85
85
  if (!fs.existsSync(file)) {
86
- fs.writeFileSync(file, 'TIME,UNIX,URL,COOKIE,SESSION,USER_AGENT,REALIP,CFIP,XIP,OS,PROCESS,MESSAGE\n', { 'mode': 0o600 });
86
+ fs.writeFileSync(file, 'TIME,UNIX,URL,USER_AGENT,REALIP,CFIP,XIP,OS,PROCESS,MESSAGE\n', { 'mode': 0o600 });
87
87
  }
88
88
  const fields = [
89
- entry.time, String(entry.unix), entry.url, '', '{}', 'No HTTP_USER_AGENT',
89
+ entry.time, String(entry.unix), entry.url, 'No HTTP_USER_AGENT',
90
90
  entry.realIp, entry.cfIp, entry.xIp, entry.osMem, entry.procMem, entry.message,
91
91
  ];
92
92
  content = fields.map(field => `"${field.replace(/"/g, '""')}"`).join(',') + '\n';
package/sys/route.js CHANGED
@@ -17,6 +17,9 @@ import * as lLang from '#kebab/lib/lang.js';
17
17
  import * as sCtr from './ctr.js';
18
18
  import * as kebab from '#kebab/index.js';
19
19
  import { getPublicProtocol as getPublicProtocolImpl } from '#kebab/abox/request.js';
20
+ import { pipeResponse as pipeResponseImpl } from '#kebab/abox/response.js';
21
+ /** --- 将片段依次输出;出错或断连时关闭所有源,回调在输入结束或失败时执行 --- */
22
+ const pipeResponse = pipeResponseImpl;
20
23
  /**
21
24
  * --- 只用于推导公开 URL;不改变真实 TLS 状态,也不验证转发头来源 ---
22
25
  * @param req HTTP 或 HTTP/2 请求
@@ -329,7 +332,6 @@ export async function run(data) {
329
332
  cctr.setPrototype('_headers', headers);
330
333
  cctr.setPrototype('_get', get);
331
334
  cctr.setPrototype('_cookie', cookies);
332
- lCore.log(cctr, '', '-visit');
333
335
  try {
334
336
  rtn = await cctr.onLoad();
335
337
  }
@@ -539,7 +541,6 @@ export async function run(data) {
539
541
  cctr.setPrototype('_cacheTTL', middle.getPrototype('_cacheTTL'));
540
542
  cctr.setPrototype('_xsrf', middle.getPrototype('_xsrf'));
541
543
  cctr.setPrototype('_httpCode', middle.getPrototype('_httpCode'));
542
- lCore.log(cctr, '', '-visit');
543
544
  // --- 强制 HTTPS ---
544
545
  if (config.set.mustHttps && !config.const.https) {
545
546
  data.res.setHeader('location', data.req.url ?? '');
@@ -640,9 +641,7 @@ export async function run(data) {
640
641
  }
641
642
  if (!data.res.writableEnded) {
642
643
  if (compress) {
643
- compress.compress.write(rtn);
644
- compress.compress.pipe(data.res);
645
- compress.compress.end();
644
+ pipeResponse([rtn], data.res, compress.compress);
646
645
  }
647
646
  else {
648
647
  data.res.end(rtn);
@@ -676,10 +675,10 @@ export async function run(data) {
676
675
  }
677
676
  if (!data.res.writableEnded) {
678
677
  if (compress) {
679
- stm.pipe(compress.compress).pipe(data.res);
678
+ pipeResponse([stm], data.res, compress.compress);
680
679
  }
681
680
  else {
682
- stm.pipe(data.res);
681
+ pipeResponse([stm], data.res);
683
682
  }
684
683
  }
685
684
  }
@@ -730,9 +729,7 @@ export async function run(data) {
730
729
  }
731
730
  if (!data.res.writableEnded) {
732
731
  if (compress) {
733
- compress.compress.write(writeData);
734
- compress.compress.pipe(data.res);
735
- compress.compress.end();
732
+ pipeResponse([writeData], data.res, compress.compress);
736
733
  }
737
734
  else {
738
735
  data.res.end(writeData);
@@ -754,15 +751,19 @@ export async function run(data) {
754
751
  lCore.writeHead(data.res, httpCode);
755
752
  }
756
753
  if (!data.res.writableEnded) {
757
- const passThrough = new stream.PassThrough();
758
- // --- 先进行 pipe 绑定,之后 write 或 pipe 进 pass 的数据,直接就可以消费 ---
759
- if (compress) {
760
- passThrough.pipe(compress.compress).pipe(data.res);
761
- }
762
- else {
763
- passThrough.pipe(data.res);
764
- }
765
- await lCore.passThroughAppend(passThrough, rtn);
754
+ const parts = rtn.flatMap((item) => {
755
+ if (item instanceof stream.Readable || typeof item === 'string' || item instanceof Buffer) {
756
+ return [item];
757
+ }
758
+ if (item instanceof lNetResponse.Response || item instanceof lUndiciResponse.Response) {
759
+ const itemStream = item.getStream();
760
+ return itemStream ? [itemStream] : [];
761
+ }
762
+ return [];
763
+ });
764
+ await new Promise((resolve) => {
765
+ pipeResponse(parts, data.res, compress?.compress, resolve);
766
+ });
766
767
  }
767
768
  }
768
769
  }
@@ -784,9 +785,7 @@ export async function run(data) {
784
785
  }
785
786
  if (!data.res.writableEnded) {
786
787
  if (compress) {
787
- compress.compress.write(writeData);
788
- compress.compress.pipe(data.res);
789
- compress.compress.end();
788
+ pipeResponse([writeData], data.res, compress.compress);
790
789
  }
791
790
  else {
792
791
  data.res.end(writeData);
@@ -0,0 +1,2 @@
1
+ export declare function prepare(root: string): Promise<string | false>;
2
+ export declare function clear(root: string): Promise<boolean>;
@@ -0,0 +1,43 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ const prefix = 'core-updatecode-';
4
+ const directoryPattern = /^core-updatecode-[a-zA-Z0-9]{6}$/;
5
+ export async function prepare(root) {
6
+ let directory;
7
+ try {
8
+ const temporary = path.join(root, 'ftmp');
9
+ await fs.mkdir(temporary, { recursive: true });
10
+ directory = await fs.mkdtemp(path.join(temporary, prefix));
11
+ await fs.mkdir(path.join(directory, 'www'));
12
+ await fs.writeFile(path.join(directory, 'www/lock.txt'), 'Before updateCode test\n', { flag: 'wx' });
13
+ return path.relative(root, directory).split(path.sep).join('/') + '/';
14
+ }
15
+ catch {
16
+ if (directory)
17
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => { });
18
+ return false;
19
+ }
20
+ }
21
+ export async function clear(root) {
22
+ try {
23
+ const temporary = path.join(root, 'ftmp');
24
+ let entries;
25
+ try {
26
+ entries = await fs.readdir(temporary, { withFileTypes: true });
27
+ }
28
+ catch (error) {
29
+ if (error.code === 'ENOENT')
30
+ return true;
31
+ throw error;
32
+ }
33
+ for (const entry of entries) {
34
+ if (!entry.isDirectory() || !directoryPattern.test(entry.name))
35
+ continue;
36
+ await fs.rm(path.join(temporary, entry.name), { recursive: true, force: true });
37
+ }
38
+ return true;
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
@@ -56,6 +56,10 @@ export default class extends sCtr.Ctr {
56
56
  coreRealiplimit(): string;
57
57
  coreGetlog(): Promise<string>;
58
58
  coreLs(): Promise<string>;
59
+ /**
60
+ * --- 在独立临时目录测试文件覆盖,或清理本示例的测试结果 ---
61
+ * @returns 测试或清理结果页面
62
+ */
59
63
  coreUpdatecode(): Promise<string>;
60
64
  coreReload(): Promise<string>;
61
65
  coreRestart(): Promise<string>;
@@ -29,6 +29,19 @@ import * as sCtr from '#kebab/sys/ctr.js';
29
29
  // --- mod ---
30
30
  import mTest from '../mod/test.js';
31
31
  import mTestData from '../mod/testdata.js';
32
+ import * as coreUpdatecodeTest from '../abox/core-updatecode.js';
33
+ /**
34
+ * --- 创建独立测试目录并预置待覆盖文件 ---
35
+ * @param root 运行根目录
36
+ * @returns 相对运行根目录的测试路径;准备失败返回 false
37
+ */
38
+ const prepareUpdatecodeTest = coreUpdatecodeTest.prepare;
39
+ /**
40
+ * --- 清除 ftmp 下本示例创建的测试目录,保留其他文件及软链接 ---
41
+ * @param root 运行根目录
42
+ * @returns 是否全部清理成功,无测试目录时也返回 true
43
+ */
44
+ const clearUpdatecodeTest = coreUpdatecodeTest.clear;
32
45
  /** --- Kebab 核心库提供的 Valibot 对象 --- */
33
46
  const v = lCore.v;
34
47
  /** --- Valibot 示例支持的语言 --- */
@@ -177,7 +190,7 @@ export default class extends sCtr.Ctr {
177
190
  `<br><a href="${this._config.const.urlBase}test/core-pm2?name=cron&action=restart">View "test/core-pm2"</a>`,
178
191
  `<br><a href="${this._config.const.urlBase}test/core-npm">View "test/core-npm"</a>`,
179
192
  `<br><a href="${this._config.const.urlBase}test/core-global">View "test/core-global"</a>`,
180
- `<br><a href="${this._config.const.urlBase}test/core-updatecode">View "test/core-updatecode"</a>`,
193
+ `<br><a href="${this._config.const.urlBase}test/core-updatecode">View "test/core-updatecode"</a> <a href="${this._config.const.urlBase}test/core-updatecode?action=clear">clear</a>`,
181
194
  `<br><a href="${this._config.const.urlBase}test/core-env">View "test/core-env"</a>`,
182
195
  '<br><br><b>Crypto:</b>',
183
196
  `<br><br><a href="${this._config.const.urlBase}test/crypto">View "test/crypto"</a>`,
@@ -1648,15 +1661,27 @@ for (let i = 0; i < 30000; ++i) {
1648
1661
  echo.push('</table>');
1649
1662
  return echo.join('') + '<br>' + this._getEnd();
1650
1663
  }
1664
+ /**
1665
+ * --- 在独立临时目录测试文件覆盖,或清理本示例的测试结果 ---
1666
+ * @returns 测试或清理结果页面
1667
+ */
1651
1668
  async coreUpdatecode() {
1669
+ if (this._get['action'] === 'clear') {
1670
+ const cleared = await clearUpdatecodeTest(kebab.ROOT_CWD);
1671
+ return (cleared ? 'Test files cleared.' : 'Failed to clear test files.') + '<br><br>' + this._getEnd();
1672
+ }
1652
1673
  const zip = `${this._config.const.dataPath}test.zip`;
1653
- const to = '';
1674
+ const to = await prepareUpdatecodeTest(kebab.ROOT_CWD);
1675
+ if (to === false) {
1676
+ return 'Failed to prepare test files.<br><br>' + this._getEnd();
1677
+ }
1654
1678
  const echo = [
1655
1679
  `zip: ${zip}<br>
1656
1680
  to: ${to}`
1657
1681
  ];
1658
- const list = await lCore.updateCode(zip, to);
1659
- echo.push(`<pre>const list = lCore.updateCode(zip, to);</pre>${JSON.stringify(list)}`);
1682
+ const list = await lCore.updateCode(zip, to, undefined, false, true);
1683
+ echo.push(`<pre>const list = await lCore.updateCode(zip, to, undefined, false, true);</pre>${lText.htmlescape(lText.stringifyJson(list))}`);
1684
+ echo.push(`<br><a href="${this._config.const.urlBase}test/core-updatecode?action=clear">clear</a>`);
1660
1685
  return echo.join('') + '<br><br>' + this._getEnd();
1661
1686
  }
1662
1687
  async coreReload() {