@maiyunnet/kebab 9.26.3 → 9.26.5
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.d.ts +9 -0
- package/abox/proxy.js +62 -0
- package/doc/kebab-rag.md +480 -238
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/lib/undici/proxy.d.ts +36 -0
- package/lib/undici/proxy.js +21 -0
- package/lib/undici.d.ts +10 -6
- package/lib/undici.js +11 -41
- package/lib/ws.d.ts +4 -1
- package/lib/ws.js +3 -3
- package/package.json +1 -1
- package/sys/mod.d.ts +16 -7
- package/sys/mod.js +111 -52
- package/www/example/ctr/test.js +2 -2
- package/www/example/mod/test.js +2 -2
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* --- 本文件用来定义每个目录实体地址的常量 ---
|
|
6
6
|
*/
|
|
7
7
|
/** --- 当前系统版本号 --- */
|
|
8
|
-
export const VER = '9.26.
|
|
8
|
+
export const VER = '9.26.5';
|
|
9
9
|
// --- 服务端用的路径 ---
|
|
10
10
|
const imu = decodeURIComponent(import.meta.url).replace('file://', '').replace(/^\/(\w:)/, '$1');
|
|
11
11
|
/** --- /xxx/xxx --- */
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type * as http from 'http';
|
|
2
|
+
import type * as http2 from 'http2';
|
|
3
|
+
import type { THttpHeaders } from '#kebab/lib/undici.js';
|
|
4
|
+
/** --- undici 和 ws 共用请求头模式,mproxy 仅支持 passthrough 和 request --- */
|
|
5
|
+
export interface IProxyHeaderOptions {
|
|
6
|
+
/**
|
|
7
|
+
* --- 默认 passthrough 透传;request 使用目标 Host 并清理代理来源头;reverse 保留外部 Host 并生成来源头 ---
|
|
8
|
+
* passthrough 使用目标 Host,保留通过基础过滤的来路头,不自动生成来源头。
|
|
9
|
+
* request/reverse 均清理传入的 Forwarded、X-Forwarded-*、Via、X-Real-IP 及 CDN 来源头。
|
|
10
|
+
* reverse 的协议和 IP 仅取实际连接,不信任来路代理头;可信代理信息由业务验证后通过 headers 覆盖。
|
|
11
|
+
*/
|
|
12
|
+
'proxyMode'?: 'passthrough' | 'request' | 'reverse';
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* --- 过滤代理请求或响应的基础头部,不处理来源信息 ---
|
|
16
|
+
* @param headers 待过滤的头部
|
|
17
|
+
* @param res 传入时直接设置响应头并返回空对象,响应头已发送时不再写入
|
|
18
|
+
* @param filter 业务过滤,返回 true 则保留
|
|
19
|
+
* @returns 过滤后的头部,不修改输入
|
|
20
|
+
*/
|
|
21
|
+
export declare const filterProxyHeaders: (headers: http.IncomingHttpHeaders | http2.IncomingHttpHeaders | THttpHeaders, res?: http2.Http2ServerResponse | http.ServerResponse, filter?: (h: string) => boolean) => Record<string, string | string[]>;
|
|
22
|
+
/**
|
|
23
|
+
* --- 构造上游请求头,依次执行基础过滤、业务 filter、模式处理及 headers 覆盖 ---
|
|
24
|
+
* 保留 Cookie、Authorization、Origin、Referer 的业务语义,不保证请求无法被识别为代理。
|
|
25
|
+
* 来源头包括 Forwarded、Via、X-Real-IP、X-Forwarded-*、CF-*、EO-*、True-Client-IP、Client-IP、
|
|
26
|
+
* X-Client-IP、Fastly-Client-IP、X-Cluster-Client-IP、X-Envoy-External-Address、X-Original-Forwarded-For、
|
|
27
|
+
* X-Original-Host、X-Original-URL、X-Rewrite-URL;业务可通过 filter 补充过滤,headers 覆盖优先级最高。
|
|
28
|
+
* reverse 输出 Host、X-Forwarded-Host、X-Forwarded-Proto、X-Forwarded-For、X-Real-IP。
|
|
29
|
+
* @param req 原始 HTTP 或 WebSocket 握手请求
|
|
30
|
+
* @param opt 模式、业务过滤及显式覆盖的头部
|
|
31
|
+
* @returns 独立的上游请求头对象,不修改输入
|
|
32
|
+
*/
|
|
33
|
+
export declare const getProxyHeaders: (req: http.IncomingMessage | http2.Http2ServerRequest, opt?: IProxyHeaderOptions & {
|
|
34
|
+
'headers'?: http.IncomingHttpHeaders;
|
|
35
|
+
filter?: (h: string) => boolean;
|
|
36
|
+
}) => http.IncomingHttpHeaders;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { buildProxyHeaders, filterProxyHeaders as filterProxyHeadersImpl } from '#kebab/abox/proxy.js';
|
|
2
|
+
/**
|
|
3
|
+
* --- 过滤代理请求或响应的基础头部,不处理来源信息 ---
|
|
4
|
+
* @param headers 待过滤的头部
|
|
5
|
+
* @param res 传入时直接设置响应头并返回空对象,响应头已发送时不再写入
|
|
6
|
+
* @param filter 业务过滤,返回 true 则保留
|
|
7
|
+
* @returns 过滤后的头部,不修改输入
|
|
8
|
+
*/
|
|
9
|
+
export const filterProxyHeaders = filterProxyHeadersImpl;
|
|
10
|
+
/**
|
|
11
|
+
* --- 构造上游请求头,依次执行基础过滤、业务 filter、模式处理及 headers 覆盖 ---
|
|
12
|
+
* 保留 Cookie、Authorization、Origin、Referer 的业务语义,不保证请求无法被识别为代理。
|
|
13
|
+
* 来源头包括 Forwarded、Via、X-Real-IP、X-Forwarded-*、CF-*、EO-*、True-Client-IP、Client-IP、
|
|
14
|
+
* X-Client-IP、Fastly-Client-IP、X-Cluster-Client-IP、X-Envoy-External-Address、X-Original-Forwarded-For、
|
|
15
|
+
* X-Original-Host、X-Original-URL、X-Rewrite-URL;业务可通过 filter 补充过滤,headers 覆盖优先级最高。
|
|
16
|
+
* reverse 输出 Host、X-Forwarded-Host、X-Forwarded-Proto、X-Forwarded-For、X-Real-IP。
|
|
17
|
+
* @param req 原始 HTTP 或 WebSocket 握手请求
|
|
18
|
+
* @param opt 模式、业务过滤及显式覆盖的头部
|
|
19
|
+
* @returns 独立的上游请求头对象,不修改输入
|
|
20
|
+
*/
|
|
21
|
+
export const getProxyHeaders = buildProxyHeaders;
|
package/lib/undici.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import * as http2 from 'http2';
|
|
|
5
5
|
import * as kebab from '#kebab/index.js';
|
|
6
6
|
import * as lCookie from '#kebab/lib/cookie.js';
|
|
7
7
|
import * as sCtr from '#kebab/sys/ctr.js';
|
|
8
|
+
import * as lProxy from '#kebab/lib/undici/proxy.js';
|
|
8
9
|
import * as lFd from './undici/formdata.js';
|
|
9
10
|
import * as lRequest from './undici/request.js';
|
|
10
11
|
import * as lResponse from './undici/response.js';
|
|
@@ -89,12 +90,13 @@ export declare function request(u: string, data?: Record<string, kebab.Json> | B
|
|
|
89
90
|
*/
|
|
90
91
|
export declare function getFormData(): lFd.FormData;
|
|
91
92
|
/**
|
|
92
|
-
* ---
|
|
93
|
-
* @param headers
|
|
94
|
-
* @param res
|
|
95
|
-
* @param filter
|
|
93
|
+
* --- 过滤代理请求或响应的基础头部,不生成或清理来源信息 ---
|
|
94
|
+
* @param headers 待过滤的头部
|
|
95
|
+
* @param res 传入时直接设置响应头并返回空对象,响应头已发送时不再写入
|
|
96
|
+
* @param filter 业务过滤,返回 true 则保留
|
|
97
|
+
* @returns 过滤后的头部,不修改输入
|
|
96
98
|
*/
|
|
97
|
-
export declare
|
|
99
|
+
export declare const filterProxyHeaders: (headers: http.IncomingHttpHeaders | http2.IncomingHttpHeaders | THttpHeaders, res?: http2.Http2ServerResponse | http.ServerResponse, filter?: (h: string) => boolean) => Record<string, string | string[]>;
|
|
98
100
|
/**
|
|
99
101
|
* --- 正向 mproxy 代理,注意提前处理不要自动处理 post 数据,读取 get 的 url 为实际请求地址 ---
|
|
100
102
|
* --- get: url, auth ---
|
|
@@ -171,6 +173,8 @@ export interface IRequestOptions {
|
|
|
171
173
|
}
|
|
172
174
|
/** --- 正向代理请求的传入参数选项 --- */
|
|
173
175
|
export interface IMproxyOptions {
|
|
176
|
+
/** --- 默认 passthrough 保留已有来源头;request 清理来源头;两者均使用目标 Host --- */
|
|
177
|
+
'proxyMode'?: 'passthrough' | 'request';
|
|
174
178
|
/** --- 秒数,默认 300 秒 --- */
|
|
175
179
|
'timeout'?: number;
|
|
176
180
|
'follow'?: number;
|
|
@@ -188,7 +192,7 @@ export interface IMproxyOptions {
|
|
|
188
192
|
'reuse'?: string | undici.ProxyAgent | undici.Agent;
|
|
189
193
|
}
|
|
190
194
|
/** --- 反向代理请求的传入参数选项 --- */
|
|
191
|
-
export interface IRproxyOptions {
|
|
195
|
+
export interface IRproxyOptions extends lProxy.IProxyHeaderOptions {
|
|
192
196
|
/** --- 秒数,默认 300 秒 --- */
|
|
193
197
|
'timeout'?: number;
|
|
194
198
|
'follow'?: number;
|
package/lib/undici.js
CHANGED
|
@@ -7,6 +7,7 @@ import * as lCrypto from '#kebab/lib/crypto.js';
|
|
|
7
7
|
import * as lCore from '#kebab/lib/core.js';
|
|
8
8
|
import * as lCookie from '#kebab/lib/cookie.js';
|
|
9
9
|
import * as lZlib from '#kebab/lib/zlib.js';
|
|
10
|
+
import * as lProxy from '#kebab/lib/undici/proxy.js';
|
|
10
11
|
// --- 自己 ---
|
|
11
12
|
import * as lFd from './undici/formdata.js';
|
|
12
13
|
import * as lRequest from './undici/request.js';
|
|
@@ -576,45 +577,14 @@ export async function request(u, data, opt = {}) {
|
|
|
576
577
|
export function getFormData() {
|
|
577
578
|
return new lFd.FormData();
|
|
578
579
|
}
|
|
579
|
-
/** --- proxy 要剔除的基础头部 --- */
|
|
580
|
-
const proxyContinueHeaders = [
|
|
581
|
-
'host', 'connection', 'keep-alive', 'http-code', 'http-url',
|
|
582
|
-
'transfer-encoding', 'upgrade', 'proxy-connection'
|
|
583
|
-
];
|
|
584
580
|
/**
|
|
585
|
-
* ---
|
|
586
|
-
* @param headers
|
|
587
|
-
* @param res
|
|
588
|
-
* @param filter
|
|
581
|
+
* --- 过滤代理请求或响应的基础头部,不生成或清理来源信息 ---
|
|
582
|
+
* @param headers 待过滤的头部
|
|
583
|
+
* @param res 传入时直接设置响应头并返回空对象,响应头已发送时不再写入
|
|
584
|
+
* @param filter 业务过滤,返回 true 则保留
|
|
585
|
+
* @returns 过滤后的头部,不修改输入
|
|
589
586
|
*/
|
|
590
|
-
export
|
|
591
|
-
const heads = {};
|
|
592
|
-
// --- HTTP/2 下响应已发送则跳过 setHeader,避免 ERR_HTTP2_HEADERS_SENT ---
|
|
593
|
-
const sent = res ? res.headersSent : false;
|
|
594
|
-
for (const h in headers) {
|
|
595
|
-
if (proxyContinueHeaders.includes(h)) {
|
|
596
|
-
continue;
|
|
597
|
-
}
|
|
598
|
-
if (h.includes(':') || h.includes('(')) {
|
|
599
|
-
continue;
|
|
600
|
-
}
|
|
601
|
-
const v = headers[h];
|
|
602
|
-
if (v === undefined) {
|
|
603
|
-
continue;
|
|
604
|
-
}
|
|
605
|
-
if (filter && !filter(h)) {
|
|
606
|
-
continue;
|
|
607
|
-
}
|
|
608
|
-
if (res) {
|
|
609
|
-
if (!sent) {
|
|
610
|
-
res.setHeader(h, v);
|
|
611
|
-
}
|
|
612
|
-
continue;
|
|
613
|
-
}
|
|
614
|
-
heads[h] = v;
|
|
615
|
-
}
|
|
616
|
-
return heads;
|
|
617
|
-
}
|
|
587
|
+
export const filterProxyHeaders = lProxy.filterProxyHeaders;
|
|
618
588
|
/**
|
|
619
589
|
* --- 正向 mproxy 代理,注意提前处理不要自动处理 post 数据,读取 get 的 url 为实际请求地址 ---
|
|
620
590
|
* --- get: url, auth ---
|
|
@@ -640,7 +610,7 @@ export async function mproxy(ctr, auth, opt = {}) {
|
|
|
640
610
|
opt.headers ??= {};
|
|
641
611
|
/** --- 传来的 hosts --- */
|
|
642
612
|
const hosts = lText.parseJson(get['hosts']);
|
|
643
|
-
const headers =
|
|
613
|
+
const headers = lProxy.getProxyHeaders(req, opt);
|
|
644
614
|
// --- 发起请求 ---
|
|
645
615
|
const rres = await request(get['url'], req, {
|
|
646
616
|
...opt,
|
|
@@ -658,7 +628,7 @@ export async function mproxy(ctr, auth, opt = {}) {
|
|
|
658
628
|
// --- HTTP/2 下响应可能已被客户端取消,跳过头部设置避免崩溃 ---
|
|
659
629
|
if (!res.headersSent) {
|
|
660
630
|
if (rres.headers) {
|
|
661
|
-
|
|
631
|
+
filterProxyHeaders(rres.headers, res, opt.filter);
|
|
662
632
|
}
|
|
663
633
|
lCore.writeHead(res, rres.headers?.['http-code'] ?? 200);
|
|
664
634
|
await new Promise(resolve => {
|
|
@@ -728,7 +698,7 @@ export async function rproxy(ctr, route, opt = {}) {
|
|
|
728
698
|
const lpath = path.slice(key.length);
|
|
729
699
|
opt.method = req.method ?? 'GET';
|
|
730
700
|
opt.headers ??= {};
|
|
731
|
-
const headers =
|
|
701
|
+
const headers = lProxy.getProxyHeaders(req, opt);
|
|
732
702
|
// --- 拼接代理目标 URL ---
|
|
733
703
|
let proxyUrl = route[key] + lpath;
|
|
734
704
|
// --- 自定义 GET 查询参数(直接替换整个 query string) ---
|
|
@@ -755,7 +725,7 @@ export async function rproxy(ctr, route, opt = {}) {
|
|
|
755
725
|
// --- HTTP/2 下响应可能已被客户端取消,跳过头部设置避免崩溃 ---
|
|
756
726
|
if (!res.headersSent) {
|
|
757
727
|
if (rres.headers) {
|
|
758
|
-
|
|
728
|
+
filterProxyHeaders(rres.headers, res, opt.filter);
|
|
759
729
|
}
|
|
760
730
|
/** --- 上游已压缩则不再压缩,避免双重压缩导致乱码 --- */
|
|
761
731
|
const upstreamEncoded = !!(rres.headers?.['content-encoding']);
|
package/lib/ws.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import * as kebab from '#kebab/index.js';
|
|
|
9
9
|
import * as lUndici from '#kebab/lib/undici.js';
|
|
10
10
|
import * as lCookie from '#kebab/lib/cookie.js';
|
|
11
11
|
import * as sCtr from '#kebab/sys/ctr.js';
|
|
12
|
+
import * as lProxy from '#kebab/lib/undici/proxy.js';
|
|
12
13
|
/** --- 一般用 SIMPLE --- */
|
|
13
14
|
export declare enum EFrameReceiveMode {
|
|
14
15
|
STANDARD = 0,
|
|
@@ -65,6 +66,8 @@ export interface ISocketCloseInfo {
|
|
|
65
66
|
}
|
|
66
67
|
/** --- 正向代理请求的传入参数选项 --- */
|
|
67
68
|
export interface IMproxyOptions {
|
|
69
|
+
/** --- 默认 passthrough 保留已有来源头;request 清理来源头;两者均使用目标 Host --- */
|
|
70
|
+
'proxyMode'?: 'passthrough' | 'request';
|
|
68
71
|
/** --- 秒数 --- */
|
|
69
72
|
'timeout'?: number;
|
|
70
73
|
/** --- 自定义 host 映射,如 {'www.maiyun.net': '127.0.0.1'},或全部映射到一个 host --- */
|
|
@@ -79,7 +82,7 @@ export interface IMproxyOptions {
|
|
|
79
82
|
'masking'?: boolean;
|
|
80
83
|
}
|
|
81
84
|
/** --- 反向代理请求的传入参数选项 --- */
|
|
82
|
-
export interface IRproxyOptions {
|
|
85
|
+
export interface IRproxyOptions extends lProxy.IProxyHeaderOptions {
|
|
83
86
|
/** --- 秒数 --- */
|
|
84
87
|
'timeout'?: number;
|
|
85
88
|
/** --- 自定义 host 映射,如 {'www.maiyun.net': '127.0.0.1'},或全部映射到一个 host --- */
|
package/lib/ws.js
CHANGED
|
@@ -3,8 +3,8 @@ import * as net from 'net';
|
|
|
3
3
|
import WebSocket, { WebSocketServer } from 'ws';
|
|
4
4
|
import * as lCore from '#kebab/lib/core.js';
|
|
5
5
|
import * as lText from '#kebab/lib/text.js';
|
|
6
|
-
import * as lUndici from '#kebab/lib/undici.js';
|
|
7
6
|
import * as lCookie from '#kebab/lib/cookie.js';
|
|
7
|
+
import * as lProxy from '#kebab/lib/undici/proxy.js';
|
|
8
8
|
/** --- 一般用 SIMPLE --- */
|
|
9
9
|
export var EFrameReceiveMode;
|
|
10
10
|
(function (EFrameReceiveMode) {
|
|
@@ -778,7 +778,7 @@ export async function mproxy(ctr, auth, opt = {}) {
|
|
|
778
778
|
return -1;
|
|
779
779
|
}
|
|
780
780
|
opt.headers ??= {};
|
|
781
|
-
const headers =
|
|
781
|
+
const headers = lProxy.getProxyHeaders(req, opt);
|
|
782
782
|
// --- 发起请求 ---
|
|
783
783
|
/** --- 远程端的双向 socket --- */
|
|
784
784
|
const rsocket = await connect(get['url'], {
|
|
@@ -802,7 +802,7 @@ export async function rproxy(ctr, url, opt = {}) {
|
|
|
802
802
|
/** --- 请求端产生的双向 socket --- */
|
|
803
803
|
const socket = ctr.getPrototype('_socket');
|
|
804
804
|
opt.headers ??= {};
|
|
805
|
-
const headers =
|
|
805
|
+
const headers = lProxy.getProxyHeaders(req, opt);
|
|
806
806
|
// --- 发起请求 ---
|
|
807
807
|
/** --- 远程端的双向 socket --- */
|
|
808
808
|
/** --- 目标连接的握手错误 --- */
|
package/package.json
CHANGED
package/sys/mod.d.ts
CHANGED
|
@@ -45,8 +45,8 @@ export default class Mod {
|
|
|
45
45
|
protected static _$primary: string;
|
|
46
46
|
/** --- 设置后将由 _keyGenerator 函数生成唯一字段 --- */
|
|
47
47
|
protected static _$key: string;
|
|
48
|
-
/** ---
|
|
49
|
-
protected static _$index: string;
|
|
48
|
+
/** --- 自动 key 冲突目标:MySQL 为索引名;PGSQL 为唯一字段或字段数组,PG 留空使用 _$key,不支持部分或表达式索引 --- */
|
|
49
|
+
protected static _$index: string | string[];
|
|
50
50
|
/** --- 前缀,MySQL 时为表前缀(如 prefix_),PostgreSQL 时为 Schema 名。顺序:选项前缀 -> 本前缀 -> 配置文件前缀 --- */
|
|
51
51
|
protected static _$pre?: string;
|
|
52
52
|
/** --- 要 update 的内容 --- */
|
|
@@ -328,13 +328,21 @@ export default class Mod {
|
|
|
328
328
|
*/
|
|
329
329
|
get(n: string): any;
|
|
330
330
|
/**
|
|
331
|
-
* ---
|
|
332
|
-
* @
|
|
331
|
+
* --- 收集待写字段,保留模型内的原始 JSON 值 ---
|
|
332
|
+
* @returns 独立的 SQL 数据对象
|
|
333
|
+
*/
|
|
334
|
+
private _getUpdates;
|
|
335
|
+
/**
|
|
336
|
+
* --- 创建数据,自动 key 最多尝试 3 次;PGSQL 仅忽略指定字段的唯一冲突 ---
|
|
337
|
+
* @return true-成功,false-错误或重试耗尽,null-其他唯一冲突;PGSQL 的 SQL 错误需要回滚事务
|
|
333
338
|
*/
|
|
334
339
|
create(): Promise<boolean | null>;
|
|
335
340
|
/**
|
|
336
|
-
* ---
|
|
337
|
-
*
|
|
341
|
+
* --- 插入数据,如果业务唯一键已存在则更新,保留已有主键和自动 key ---
|
|
342
|
+
* --- PGSQL 为原子 UPSERT,自动 key 只生成一次,SQL 错误需回滚事务 ---
|
|
343
|
+
* --- MySQL 分步执行;自动 key 有多个唯一索引时须配置 _$index,整笔原子性由调用方事务保证 ---
|
|
344
|
+
* @param conflict 已通过 set 赋非 NULL 值的业务唯一字段,不得包含 _$key 或 _$primary;PGSQL 不支持部分或表达式索引
|
|
345
|
+
* @returns 是否成功;至少需要一个可更新字段,失败保留待写数据
|
|
338
346
|
*/
|
|
339
347
|
upsert(conflict: string | string[]): Promise<boolean>;
|
|
340
348
|
/**
|
|
@@ -344,7 +352,8 @@ export default class Mod {
|
|
|
344
352
|
refresh(lock?: boolean): Promise<boolean | null>;
|
|
345
353
|
/**
|
|
346
354
|
* --- 更新 set 的数据到数据库,有未保存数据时才保存 ---
|
|
347
|
-
* @param where
|
|
355
|
+
* @param where 非空筛选条件,省略时必须有主键
|
|
356
|
+
* @returns 是否成功,失败保留待写数据
|
|
348
357
|
*/
|
|
349
358
|
save(where?: any): Promise<boolean>;
|
|
350
359
|
/**
|
package/sys/mod.js
CHANGED
|
@@ -53,7 +53,7 @@ export default class Mod {
|
|
|
53
53
|
static _$primary = 'id';
|
|
54
54
|
/** --- 设置后将由 _keyGenerator 函数生成唯一字段 --- */
|
|
55
55
|
static _$key = '';
|
|
56
|
-
/** ---
|
|
56
|
+
/** --- 自动 key 冲突目标:MySQL 为索引名;PGSQL 为唯一字段或字段数组,PG 留空使用 _$key,不支持部分或表达式索引 --- */
|
|
57
57
|
static _$index = '';
|
|
58
58
|
/** --- 前缀,MySQL 时为表前缀(如 prefix_),PostgreSQL 时为 Schema 名。顺序:选项前缀 -> 本前缀 -> 配置文件前缀 --- */
|
|
59
59
|
static _$pre;
|
|
@@ -605,17 +605,34 @@ export default class Mod {
|
|
|
605
605
|
return this._data[n];
|
|
606
606
|
}
|
|
607
607
|
/**
|
|
608
|
-
* ---
|
|
609
|
-
* @
|
|
608
|
+
* --- 收集待写字段,保留模型内的原始 JSON 值 ---
|
|
609
|
+
* @returns 独立的 SQL 数据对象
|
|
610
610
|
*/
|
|
611
|
-
|
|
612
|
-
const cstr = this.constructor;
|
|
611
|
+
_getUpdates() {
|
|
613
612
|
const updates = {};
|
|
614
|
-
for (const
|
|
615
|
-
updates[
|
|
613
|
+
for (const field in this._updates) {
|
|
614
|
+
updates[field] = this._jsonUpdates[field] ? lSql.json(this._data[field]) : this._data[field];
|
|
616
615
|
}
|
|
616
|
+
return updates;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* --- 创建数据,自动 key 最多尝试 3 次;PGSQL 仅忽略指定字段的唯一冲突 ---
|
|
620
|
+
* @return true-成功,false-错误或重试耗尽,null-其他唯一冲突;PGSQL 的 SQL 错误需要回滚事务
|
|
621
|
+
*/
|
|
622
|
+
async create() {
|
|
623
|
+
const cstr = this.constructor;
|
|
624
|
+
const updates = this._getUpdates();
|
|
625
|
+
const service = this._db.getService();
|
|
626
|
+
const keyIndex = cstr._$index;
|
|
617
627
|
let r = null;
|
|
618
628
|
if ((cstr._$key !== '') && (updates[cstr._$key] === undefined)) {
|
|
629
|
+
const keyFields = Array.isArray(keyIndex) ? keyIndex : [keyIndex || cstr._$key];
|
|
630
|
+
if (service === lDb.ESERVICE.PGSQL && !keyFields.includes(cstr._$key)) {
|
|
631
|
+
return false;
|
|
632
|
+
}
|
|
633
|
+
if (service === lDb.ESERVICE.MYSQL && Array.isArray(keyIndex)) {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
619
636
|
let count = 0;
|
|
620
637
|
while (true) {
|
|
621
638
|
if (count === 3) {
|
|
@@ -626,38 +643,32 @@ export default class Mod {
|
|
|
626
643
|
this[cstr._$key] = updates[cstr._$key];
|
|
627
644
|
this._sql.insert(cstr._$table + (this._index ? ('_' + this._index[0]) : ''));
|
|
628
645
|
this._sql.values(updates);
|
|
646
|
+
if (service === lDb.ESERVICE.PGSQL) {
|
|
647
|
+
this._sql.append(' ON CONFLICT (' + keyFields.map(field => this._sql.field(field)).join(', ') + ') DO NOTHING');
|
|
648
|
+
}
|
|
629
649
|
r = await this._db.execute(this._sql.getSql(), this._sql.getData());
|
|
630
650
|
++count;
|
|
631
651
|
if (!r.error) {
|
|
652
|
+
// --- PG 的自动 key 冲突不报错,未插入时换一个候选值 ---
|
|
653
|
+
if (service === lDb.ESERVICE.PGSQL && r.packet?.affected === 0) {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
632
656
|
break;
|
|
633
657
|
}
|
|
634
658
|
if (r.error.errno === 1062) {
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
// --- 没设置 index,那就当做是本次生成的 key 重复了 ---
|
|
638
|
-
continue;
|
|
639
|
-
}
|
|
640
|
-
if (this._db.getService() === lDb.ESERVICE.MYSQL) {
|
|
641
|
-
// --- MYSQL ---
|
|
642
|
-
const match = /for key '([\w.]+)'/.exec(r.error.message);
|
|
643
|
-
if (match?.[1].includes(cstr._$index)) {
|
|
644
|
-
// --- key 索引重复,继续生成 key ---
|
|
659
|
+
if (service === lDb.ESERVICE.MYSQL) {
|
|
660
|
+
if (!keyIndex) {
|
|
645
661
|
continue;
|
|
646
662
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
// --- PGSQL ---
|
|
650
|
-
const match = /constraint "([\w.]+)"/.exec(r.error.message);
|
|
651
|
-
if (match?.[1].includes(cstr._$index)) {
|
|
652
|
-
// --- key 索引重复,继续生成 key ---
|
|
663
|
+
const match = /for key '([\w.]+)'/.exec(r.error.message);
|
|
664
|
+
if (typeof keyIndex === 'string' && match?.[1].includes(keyIndex)) {
|
|
653
665
|
continue;
|
|
654
666
|
}
|
|
655
667
|
}
|
|
656
|
-
// ---
|
|
668
|
+
// --- PG 的目标冲突已经被 SQL 处理,剩下的是其他唯一约束冲突 ---
|
|
657
669
|
return null;
|
|
658
670
|
}
|
|
659
671
|
// --- 未处理的错误 ---
|
|
660
|
-
const service = this._db.getService();
|
|
661
672
|
lCore.log(this._ctr ?? {}, '[MOD][create0][' + cstr._$table + '] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
|
|
662
673
|
if (lCore.globalConfig.debug) {
|
|
663
674
|
lCore.debug('[MOD][create0][' + cstr._$table + ']', service !== null ? lDb.ESERVICE[service] : 'NONE', r);
|
|
@@ -694,34 +705,79 @@ export default class Mod {
|
|
|
694
705
|
}
|
|
695
706
|
}
|
|
696
707
|
/**
|
|
697
|
-
* ---
|
|
698
|
-
*
|
|
708
|
+
* --- 插入数据,如果业务唯一键已存在则更新,保留已有主键和自动 key ---
|
|
709
|
+
* --- PGSQL 为原子 UPSERT,自动 key 只生成一次,SQL 错误需回滚事务 ---
|
|
710
|
+
* --- MySQL 分步执行;自动 key 有多个唯一索引时须配置 _$index,整笔原子性由调用方事务保证 ---
|
|
711
|
+
* @param conflict 已通过 set 赋非 NULL 值的业务唯一字段,不得包含 _$key 或 _$primary;PGSQL 不支持部分或表达式索引
|
|
712
|
+
* @returns 是否成功;至少需要一个可更新字段,失败保留待写数据
|
|
699
713
|
*/
|
|
700
714
|
async upsert(conflict) {
|
|
701
|
-
|
|
702
|
-
// --- 因为还要处理 _$key 的自动生成 ---
|
|
703
|
-
const res = await this.create();
|
|
704
|
-
if (res) {
|
|
705
|
-
// --- 创建成功 ---
|
|
706
|
-
return true;
|
|
707
|
-
}
|
|
708
|
-
if (res === false) {
|
|
709
|
-
// --- 系统错误 ---
|
|
710
|
-
return false;
|
|
711
|
-
}
|
|
712
|
-
// --- res === null,唯一键冲突,执行更新 ---
|
|
713
|
-
/** --- 冲突字段列表 --- */
|
|
715
|
+
const cstr = this.constructor;
|
|
714
716
|
const conflicts = typeof conflict === 'string' ? [conflict] : conflict;
|
|
717
|
+
const inserts = this._getUpdates();
|
|
718
|
+
const updates = { ...inserts };
|
|
715
719
|
const where = {};
|
|
720
|
+
if (!conflicts.length) {
|
|
721
|
+
return false;
|
|
722
|
+
}
|
|
716
723
|
for (const field of conflicts) {
|
|
717
|
-
if (!
|
|
724
|
+
if (!field || field === cstr._$key || field === cstr._$primary ||
|
|
725
|
+
!this._updates[field] || inserts[field] === null) {
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
where[field] = inserts[field];
|
|
729
|
+
delete updates[field];
|
|
730
|
+
}
|
|
731
|
+
delete updates[cstr._$primary];
|
|
732
|
+
delete updates[cstr._$key];
|
|
733
|
+
if (!Object.keys(updates).length) {
|
|
734
|
+
return false;
|
|
735
|
+
}
|
|
736
|
+
const mysql = this._db.getService() === lDb.ESERVICE.MYSQL;
|
|
737
|
+
const table = cstr._$table + (this._index ? `_${this._index[0]}` : '');
|
|
738
|
+
const identity = [...new Set([cstr._$primary, cstr._$key].filter(field => field))];
|
|
739
|
+
if (mysql) {
|
|
740
|
+
const created = await this.create();
|
|
741
|
+
if (created !== null) {
|
|
742
|
+
return created;
|
|
743
|
+
}
|
|
744
|
+
// --- 按业务键读取最新目标,事务内锁住该行直到更新完成 ---
|
|
745
|
+
this._sql.select(identity, table).where(where).limit(1).lock();
|
|
746
|
+
}
|
|
747
|
+
else {
|
|
748
|
+
if (cstr._$key && inserts[cstr._$key] === undefined) {
|
|
749
|
+
inserts[cstr._$key] = this._keyGenerator();
|
|
750
|
+
}
|
|
751
|
+
this._sql.insert(table).values(inserts).upsert(updates, conflicts);
|
|
752
|
+
this._sql.append(` RETURNING ${identity.map(field => this._sql.field(field)).join(', ')}`);
|
|
753
|
+
}
|
|
754
|
+
const result = await this._db.query(this._sql.getSql(), this._sql.getData());
|
|
755
|
+
if (result.error) {
|
|
756
|
+
lCore.log(this._ctr ?? {}, `[MOD][upsert][${cstr._$table}] database error: ${result.error.errno}`, '-error');
|
|
757
|
+
return false;
|
|
758
|
+
}
|
|
759
|
+
const row = result.rows?.[0];
|
|
760
|
+
if (!row) {
|
|
761
|
+
return false;
|
|
762
|
+
}
|
|
763
|
+
if (mysql) {
|
|
764
|
+
// --- 同时匹配身份字段和业务键,目标变化时不回填旧身份 ---
|
|
765
|
+
this._sql.update(table, updates).where({ ...where, ...row });
|
|
766
|
+
const saved = await this._db.execute(this._sql.getSql(), this._sql.getData());
|
|
767
|
+
if (saved.error) {
|
|
768
|
+
lCore.log(this._ctr ?? {}, `[MOD][upsert][${cstr._$table}] database error: ${saved.error.errno}`, '-error');
|
|
718
769
|
return false;
|
|
719
770
|
}
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
771
|
+
if (!saved.packet?.affected) {
|
|
772
|
+
return false;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
for (const field of identity) {
|
|
776
|
+
this._setProperty(field, row[field]);
|
|
723
777
|
}
|
|
724
|
-
|
|
778
|
+
this._updates = {};
|
|
779
|
+
this._jsonUpdates = {};
|
|
780
|
+
return true;
|
|
725
781
|
}
|
|
726
782
|
/**
|
|
727
783
|
* --- 刷新当前模型获取最新数据 ---
|
|
@@ -756,24 +812,27 @@ export default class Mod {
|
|
|
756
812
|
}
|
|
757
813
|
/**
|
|
758
814
|
* --- 更新 set 的数据到数据库,有未保存数据时才保存 ---
|
|
759
|
-
* @param where
|
|
815
|
+
* @param where 非空筛选条件,省略时必须有主键
|
|
816
|
+
* @returns 是否成功,失败保留待写数据
|
|
760
817
|
*/
|
|
761
818
|
async save(where) {
|
|
762
819
|
if (Object.keys(this._updates).length === 0) {
|
|
763
820
|
return true;
|
|
764
821
|
}
|
|
765
822
|
const cstr = this.constructor;
|
|
766
|
-
if (!this._data[cstr._$primary]) {
|
|
823
|
+
if (!this._data[cstr._$primary] && (where === undefined || where === null)) {
|
|
767
824
|
lCore.log(this._ctr ?? {}, '[MOD][save] primary key not found', '-error');
|
|
768
825
|
return false;
|
|
769
826
|
}
|
|
770
|
-
const updates =
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
this._sql.update(cstr._$table + (this._index ? ('_' + this._index[0]) : ''), [updates]).where(where ?? {
|
|
827
|
+
const updates = this._getUpdates();
|
|
828
|
+
this._sql.update(cstr._$table + (this._index ? ('_' + this._index[0]) : ''), [updates]);
|
|
829
|
+
const updateSql = this._sql.getSql();
|
|
830
|
+
this._sql.where(where ?? {
|
|
775
831
|
[cstr._$primary]: this._data[cstr._$primary]
|
|
776
832
|
});
|
|
833
|
+
if (this._sql.getSql() === updateSql) {
|
|
834
|
+
return false;
|
|
835
|
+
}
|
|
777
836
|
const r = await this._db.execute(this._sql.getSql(), this._sql.getData());
|
|
778
837
|
if (r.packet === null) {
|
|
779
838
|
lCore.log(this._ctr ?? {}, '[MOD][save] ' + (lText.stringifyJson(r.error?.message ?? '').slice(1, -1) + ' - ' + this._sql.format()).replaceAll('"', '""'), '-error');
|
package/www/example/ctr/test.js
CHANGED
|
@@ -2540,10 +2540,10 @@ error: <pre>${JSON.stringify(res.error, null, 4)}</pre>`);
|
|
|
2540
2540
|
'authorization': ''
|
|
2541
2541
|
};
|
|
2542
2542
|
echo.push(`origin:<pre>${JSON.stringify(headers, null, 4)}</pre>`);
|
|
2543
|
-
const filtered = lUndici.
|
|
2543
|
+
const filtered = lUndici.filterProxyHeaders(headers, undefined, h => {
|
|
2544
2544
|
return !['x-', 'eo-'].some(i => h.startsWith(i));
|
|
2545
2545
|
});
|
|
2546
|
-
echo.push(`const filtered = lUndici.
|
|
2546
|
+
echo.push(`const filtered = lUndici.filterProxyHeaders(headers);<pre>${JSON.stringify(filtered, null, 4)}</pre>`);
|
|
2547
2547
|
return echo.join('') + this._getEnd();
|
|
2548
2548
|
}
|
|
2549
2549
|
async undiciFetch() {
|
package/www/example/mod/test.js
CHANGED
|
@@ -12,7 +12,7 @@ CREATE TABLE `m_test` (
|
|
|
12
12
|
`time_add` bigint NOT NULL,
|
|
13
13
|
PRIMARY KEY (`id`) USING BTREE,
|
|
14
14
|
INDEX `time_add`(`time_add` ASC) USING BTREE,
|
|
15
|
-
UNIQUE INDEX `
|
|
15
|
+
UNIQUE INDEX `token`(`token` ASC) USING BTREE,
|
|
16
16
|
UNIQUE INDEX `uname`(`name` ASC) USING BTREE
|
|
17
17
|
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
|
|
18
18
|
// --- PGSQL ---
|
|
@@ -41,7 +41,7 @@ export default class default_1 extends sMod {
|
|
|
41
41
|
static _$table = 'test';
|
|
42
42
|
static _$primary = 'id';
|
|
43
43
|
static _$key = 'token';
|
|
44
|
-
static _$index = '
|
|
44
|
+
static _$index = 'token';
|
|
45
45
|
/* eslint-enable */
|
|
46
46
|
_keyGenerator() {
|
|
47
47
|
return 'test_' + lCore.rand(0, 3).toString();
|