dsh-git-push 2.13.3 → 2.13.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/core/endpoints.js +14 -4
- package/lib/core/mirror-candidates.json +18 -0
- package/lib/core/mirror-store.js +243 -0
- package/lib/git/clone-download.js +54 -4
- package/lib/self/index.js +1 -1
- package/package.json +1 -1
package/lib/core/endpoints.js
CHANGED
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
/** 默认镜像前缀:克隆等**只读**访问默认走 gh-proxy.com(可用环境变量覆盖或关闭)。 */
|
|
20
|
+
import { pickMirror, readSeed } from './mirror-store.js';
|
|
21
|
+
|
|
20
22
|
export const DEFAULT_MIRROR_PREFIX = 'https://gh-proxy.com/';
|
|
21
23
|
/** 显式关闭镜像的取值(环境变量设为其中之一即走直连)。 */
|
|
22
24
|
const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
|
|
@@ -28,10 +30,18 @@ const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
|
|
|
28
30
|
* 注意:默认开启**只影响只读请求** —— 写操作与带 token 的请求由 withMirror 的双闸门拦住。
|
|
29
31
|
*/
|
|
30
32
|
export function mirrorPrefix() {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
// 选择逻辑收敛到 mirror-store(候选清单 + 健康度学习):
|
|
34
|
+
// ① DSH_GIT_MIRROR_PREFIX 显式给值 → 钉死该镜像;设为 off/none/... → 关闭;
|
|
35
|
+
// ② 否则取候选清单里第一个未停用的(出厂顺序 ghfast → ghproxy.net → gh-proxy);
|
|
36
|
+
// ③ 全部停用 → 直连。
|
|
37
|
+
// 旧实现硬编码 DEFAULT_MIRROR_PREFIX:单点坏掉(实测对某文件返回截断缓存)就无退路。
|
|
38
|
+
const picked = pickMirror();
|
|
39
|
+
if (picked) return picked;
|
|
40
|
+
// 空返回有两种含义:显式关闭 / 候选全部停用 —— 两者都走直连。
|
|
41
|
+
// 仅当出厂清单读不到(部署异常)时退回历史默认,避免「清单丢了就静默不加速」。
|
|
42
|
+
if (MIRROR_OFF.has(String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim().toLowerCase())) return '';
|
|
43
|
+
if (!readSeed().length) return DEFAULT_MIRROR_PREFIX;
|
|
44
|
+
return '';
|
|
35
45
|
}
|
|
36
46
|
|
|
37
47
|
const MIRRORABLE = ['https://github.com/', 'https://raw.githubusercontent.com/', 'https://codeload.github.com/'];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 1,
|
|
3
|
+
"note": "GitHub 只读镜像候选清单。mirror 必须以 / 结尾(withMirror 做纯前缀拼接)。顺序即优先级:靠前的先用。运行期会把 failures/disabled/lastOkAt/lastError 学习结果写到配置目录的 mirror-state.json,本文件保持为「出厂清单」不被回写污染。降权是自动的:某镜像连续 3 次数据校验失败(声明总长不符 / blob sha 不符)即停用,一次成功清零。",
|
|
4
|
+
"candidates": [
|
|
5
|
+
{
|
|
6
|
+
"mirror": "https://gh-proxy.com/",
|
|
7
|
+
"note": "历史默认镜像,实测吞吐最好(2026-10-03:codeload 21KB/s → 12MB/s)。2026-10-30 观测到它对个别大文件返回截断缓存(total=590454 而真实 8059635)——属**单文件缓存**问题而非镜像整体失效,故保持首选;真出问题时由下载器的 total/sha 校验自动累计失败并降权到后续候选。"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"mirror": "https://ghfast.top/",
|
|
11
|
+
"note": "备用。实测对同一文件返回正确总长(content-range /8059635)且支持 Range 续传"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"mirror": "https://ghproxy.net/",
|
|
15
|
+
"note": "备用。实测同样返回正确总长、支持 Range"
|
|
16
|
+
}
|
|
17
|
+
]
|
|
18
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 镜像候选清单与「按健康度选镜像」(模仿 dsh-useful-tools 的 github-mirror 设计)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要候选清单:单一镜像被写死(旧实现硬编码 gh-proxy.com)时,一旦该镜像
|
|
5
|
+
* **返回坏数据**——实测它对一个 8MB 文件给过 total=590454 的截断缓存——整条克隆链路
|
|
6
|
+
* 都会卡在同一处。写死单点没有退路,而「换一个镜像」是唯一能立刻绕开的手段。
|
|
7
|
+
*
|
|
8
|
+
* 与 useful-tools 那套的分工(避免重复建设):
|
|
9
|
+
* · useful-tools 的候选清单作用于 **git 层**(`url.<镜像>.insteadOf` 重写);
|
|
10
|
+
* · 本模块作用于**插件自己的 HTTP 只读通道**(raw / codeload / api 的 GET),
|
|
11
|
+
* 由 lib/core/endpoints.js 的 withMirror() 拼接前缀。两者各自收口、互不干扰。
|
|
12
|
+
*
|
|
13
|
+
* 清单分两层,刻意分开:
|
|
14
|
+
* · **出厂清单** `mirror-candidates.json`(随仓库入库):只写「有哪些镜像、优先级」,
|
|
15
|
+
* 运行期的失败计数不回写它 —— 否则部署副本被 sync 覆盖、仓库被学习结果弄脏;
|
|
16
|
+
* · **学习状态** `<配置目录>/mirror-state.json`:每个镜像的 failures / disabled /
|
|
17
|
+
* lastOkAt / lastError。运行期只写这份。
|
|
18
|
+
*
|
|
19
|
+
* 选择策略(mirrorPrefix 每次调用都走这里):
|
|
20
|
+
* 1. 环境变量 `DSH_GIT_MIRROR_PREFIX` 显式给值 → 用它(人工钉死,最高优先);
|
|
21
|
+
* 设为 off/none/no/false/0/- → 关闭镜像;
|
|
22
|
+
* 2. 否则取**未停用**且按清单顺序的第一个镜像;
|
|
23
|
+
* 3. 全部停用 → 返回空串(走直连)——宁可不加速,也不用一个已知会返回坏数据的源。
|
|
24
|
+
*
|
|
25
|
+
* 失败累计:连续失败达 MAX_FAILURES(3) 次置 disabled;一次成功清零。
|
|
26
|
+
* 停用不是永久的:`probe` 成功即恢复(见 probeAll)。
|
|
27
|
+
*/
|
|
28
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
29
|
+
import { dirname, join } from 'node:path';
|
|
30
|
+
import { fileURLToPath } from 'node:url';
|
|
31
|
+
|
|
32
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
33
|
+
/** raw 基址(用于探测;与 endpoints.js 的 GH_RAW 同值,此处内联以保持单向依赖、避免循环 import)。 */
|
|
34
|
+
const PROBE_RAW_BASE = 'https://raw.githubusercontent.com';
|
|
35
|
+
/**
|
|
36
|
+
* 进程内缓存:下载是热路径(7374 个文件 ⇒ 每文件都问一次「用哪个镜像」),
|
|
37
|
+
* 每次读两个 JSON 在 CIFS 上会显著拖慢。缓存选择结果与学习状态,写状态时同步刷新。
|
|
38
|
+
* TTL 只影响「别的进程改了状态本进程多久能看到」,5s 足够(本进程的写入立即生效)。
|
|
39
|
+
*/
|
|
40
|
+
const CACHE_TTL_MS = 5000;
|
|
41
|
+
let pickCache = { key: '', value: '', at: 0 };
|
|
42
|
+
let stateCache = { key: '', value: null, at: 0 };
|
|
43
|
+
/** 出厂清单位置(随仓库入库,只读种子)。 */
|
|
44
|
+
export const SEED_PATH = join(HERE, 'mirror-candidates.json');
|
|
45
|
+
/** 连续失败多少次停用(可在状态文件里手改单条 disabled 覆盖)。 */
|
|
46
|
+
export const MAX_FAILURES = 3;
|
|
47
|
+
/** 显式关闭镜像的取值。 */
|
|
48
|
+
const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
|
|
49
|
+
|
|
50
|
+
/** 归一化前缀:去空白、强制以 / 结尾(withMirror 是纯字符串拼接,缺斜杠会拼出坏 URL)。 */
|
|
51
|
+
export function normalizeMirror(raw) {
|
|
52
|
+
const text = String(raw ?? '').trim();
|
|
53
|
+
if (!text) return '';
|
|
54
|
+
return text.endsWith('/') ? text : `${text}/`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 学习状态文件位置。默认在配置目录(与凭据同处),可被
|
|
59
|
+
* `DSH_GIT_MIRROR_STATE` 覆盖——测试据此指向临时文件,不污染真实状态。
|
|
60
|
+
*/
|
|
61
|
+
export function statePath({ configDir = '' } = {}) {
|
|
62
|
+
const override = String(process.env.DSH_GIT_MIRROR_STATE || '').trim();
|
|
63
|
+
if (override) return override;
|
|
64
|
+
const dir = configDir || (process.env.DSH_HOME ? join(process.env.DSH_HOME, 'git-push') : '');
|
|
65
|
+
return dir ? join(dir, 'mirror-state.json') : '';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 读出出厂清单。文件缺失/损坏 → 空清单(调用方回退直连,不崩)。 */
|
|
69
|
+
export function readSeed(path = SEED_PATH) {
|
|
70
|
+
try {
|
|
71
|
+
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
72
|
+
const list = Array.isArray(raw?.candidates) ? raw.candidates : [];
|
|
73
|
+
return list
|
|
74
|
+
.map((it) => ({ mirror: normalizeMirror(it?.mirror), note: it?.note || '' }))
|
|
75
|
+
.filter((it) => it.mirror);
|
|
76
|
+
} catch { return []; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 读学习状态(mirror → {failures, disabled, lastOkAt, lastError})。缺失/损坏 → 空表。 */
|
|
80
|
+
export function readState(path = statePath()) {
|
|
81
|
+
if (!path) return {};
|
|
82
|
+
try {
|
|
83
|
+
if (!existsSync(path)) return {};
|
|
84
|
+
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
85
|
+
const mirrors = raw && typeof raw.mirrors === 'object' && raw.mirrors ? raw.mirrors : {};
|
|
86
|
+
const out = {};
|
|
87
|
+
for (const [k, v] of Object.entries(mirrors)) {
|
|
88
|
+
const key = normalizeMirror(k);
|
|
89
|
+
if (!key) continue;
|
|
90
|
+
out[key] = {
|
|
91
|
+
failures: Math.max(0, Math.trunc(Number(v?.failures) || 0)),
|
|
92
|
+
disabled: v?.disabled === true,
|
|
93
|
+
lastOkAt: v?.lastOkAt ?? null,
|
|
94
|
+
lastError: v?.lastError ?? null,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
} catch { return {}; }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 原子写学习状态(失败静默:状态是加速用的元数据,写不进去不影响下载主流程)。 */
|
|
102
|
+
export function writeState(state, path = statePath()) {
|
|
103
|
+
if (!path) return { ok: false, error: '状态路径不可用' };
|
|
104
|
+
try {
|
|
105
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
106
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
107
|
+
writeFileSync(tmp, `${JSON.stringify({ version: 1, note: '镜像健康度学习结果(运行期自动维护,可手改 disabled 立即生效)', mirrors: state }, null, 2)}\n`, 'utf8');
|
|
108
|
+
renameSync(tmp, path);
|
|
109
|
+
return { ok: true, path };
|
|
110
|
+
} catch (e) { return { ok: false, error: String((e?.message) || e) }; }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 合并出厂清单与学习状态,产出按优先级排序的候选视图。
|
|
115
|
+
* @returns {Array<{mirror:string, note:string, failures:number, disabled:boolean, lastOkAt:string|null, lastError:string|null}>}
|
|
116
|
+
*/
|
|
117
|
+
export function listCandidates({ seedPath = SEED_PATH, stateFile = statePath() } = {}) {
|
|
118
|
+
const state = readState(stateFile);
|
|
119
|
+
return readSeed(seedPath).map((it) => {
|
|
120
|
+
const st = state[it.mirror] || {};
|
|
121
|
+
return {
|
|
122
|
+
mirror: it.mirror,
|
|
123
|
+
note: it.note,
|
|
124
|
+
failures: st.failures || 0,
|
|
125
|
+
// 状态里的 disabled 可以与清单叠加:手工把状态文件改成 disabled:true 也能立刻停用
|
|
126
|
+
disabled: st.disabled === true,
|
|
127
|
+
lastOkAt: st.lastOkAt ?? null,
|
|
128
|
+
lastError: st.lastError ?? null,
|
|
129
|
+
};
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 当前应使用的镜像前缀(含环境变量优先级与关闭语义)。空串 = 直连。 */
|
|
134
|
+
export function pickMirror({ seedPath, stateFile } = {}) {
|
|
135
|
+
const raw = String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim();
|
|
136
|
+
if (raw && MIRROR_OFF.has(raw.toLowerCase())) return ''; // 显式关闭
|
|
137
|
+
if (raw) return normalizeMirror(raw); // 显式钉死
|
|
138
|
+
const key = `${seedPath || SEED_PATH}|${stateFile || statePath()}`;
|
|
139
|
+
const now = Date.now();
|
|
140
|
+
if (pickCache.key === key && now - pickCache.at < CACHE_TTL_MS) return pickCache.value;
|
|
141
|
+
const usable = listCandidates({ seedPath, stateFile }).find((it) => !it.disabled);
|
|
142
|
+
const value = usable ? usable.mirror : '';
|
|
143
|
+
pickCache = { key, value, at: now };
|
|
144
|
+
return value;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 清空进程内缓存(测试与状态变更后强制重读)。 */
|
|
148
|
+
export function invalidateMirrorCache() {
|
|
149
|
+
pickCache = { key: '', value: '', at: 0 };
|
|
150
|
+
stateCache = { key: '', value: null, at: 0 };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 记录一次实际使用的成败(由下载器在「数据校验通过/失败」后调用)。
|
|
155
|
+
*
|
|
156
|
+
* 为什么以**数据校验**而不是 HTTP 状态为判据:坏镜像的表现是 HTTP 200/206 一切正常、
|
|
157
|
+
* 但内容被截断或陈旧 —— 只有 total/sha 校验才能识别。故调用点放在 clone-download。
|
|
158
|
+
* @param {string} mirror 实际使用的镜像前缀
|
|
159
|
+
* @param {{ok:boolean, error?:string, stateFile?:string}} o
|
|
160
|
+
* @returns {{ok:boolean, state?:object, disabled?:boolean}}
|
|
161
|
+
*/
|
|
162
|
+
export function recordOutcome(mirror, { ok, error = '', stateFile = statePath() } = {}) {
|
|
163
|
+
const key = normalizeMirror(mirror);
|
|
164
|
+
if (!key) return { ok: false };
|
|
165
|
+
const cacheKey = stateFile || statePath();
|
|
166
|
+
const now = Date.now();
|
|
167
|
+
const state = (stateCache.key === cacheKey && stateCache.value && now - stateCache.at < CACHE_TTL_MS)
|
|
168
|
+
? stateCache.value
|
|
169
|
+
: readState(stateFile);
|
|
170
|
+
const cur = state[key] || { failures: 0, disabled: false, lastOkAt: null, lastError: null };
|
|
171
|
+
const at = new Date().toISOString();
|
|
172
|
+
const next = ok
|
|
173
|
+
? { failures: 0, disabled: false, lastOkAt: at, lastError: null }
|
|
174
|
+
: {
|
|
175
|
+
failures: cur.failures + 1,
|
|
176
|
+
disabled: cur.failures + 1 >= MAX_FAILURES,
|
|
177
|
+
lastOkAt: cur.lastOkAt ?? null,
|
|
178
|
+
lastError: String(error || '数据校验失败').slice(0, 300),
|
|
179
|
+
};
|
|
180
|
+
state[key] = next;
|
|
181
|
+
// 无变化不写盘:成功且此前无失败记录(下载主流程的常见情形)时直接返回,
|
|
182
|
+
// 否则 7374 个文件会触发 7374 次状态写盘,在 CIFS 上是纯浪费。
|
|
183
|
+
if (ok && cur.failures === 0 && cur.disabled !== true) {
|
|
184
|
+
// 状态无实质变化(累计失败仍是 0、未停用)⇒ 不写盘、也不清选择缓存:
|
|
185
|
+
// 下载主流程每个文件都会走到这里,清缓存会让「选镜像」重新读两份 JSON。
|
|
186
|
+
stateCache = { key: cacheKey, value: state, at: now };
|
|
187
|
+
return { ok: true, state: next, disabled: false };
|
|
188
|
+
}
|
|
189
|
+
const written = writeState(state, stateFile);
|
|
190
|
+
stateCache = { key: cacheKey, value: state, at: now };
|
|
191
|
+
pickCache = { key: '', value: '', at: 0 }; // 状态变了,下一次选择重新计算
|
|
192
|
+
return { ok: written.ok, state: next, disabled: next.disabled === true };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 主动探测候选(HTTP HEAD 一个必存在的公开文件;带 Range 校验返回的总长是否与声明一致)。
|
|
197
|
+
*
|
|
198
|
+
* 为什么不只判 HTTP 状态:坏镜像恰恰是「状态正常、内容不对」。这里用 Range 请求读回
|
|
199
|
+
* `content-range` 的 total 与 `content-length` 交叉验证,能识别出「声明长度异常」的缓存。
|
|
200
|
+
* @param {{mirror?:string, stateFile?:string, fetchImpl?:Function, timeoutMs?:number,
|
|
201
|
+
* probeUrl?:string, expectedBytes?:number}} o
|
|
202
|
+
* expectedBytes:已知文件字节数;给了就严格校验,不给只判「有响应且非 0 长」。
|
|
203
|
+
*/
|
|
204
|
+
export async function probeMirror({
|
|
205
|
+
mirror, stateFile = statePath(), fetchImpl = globalThis.fetch, timeoutMs = 8000,
|
|
206
|
+
probeUrl = `${PROBE_RAW_BASE}/octocat/Hello-World/main/README`, expectedBytes = 0,
|
|
207
|
+
} = {}) {
|
|
208
|
+
const prefix = normalizeMirror(mirror);
|
|
209
|
+
if (!prefix) return { ok: false, error: '镜像前缀为空', mirror: '' };
|
|
210
|
+
const url = prefix + probeUrl;
|
|
211
|
+
const ctrl = new AbortController();
|
|
212
|
+
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
213
|
+
try {
|
|
214
|
+
const r = await fetchImpl(url, { method: 'GET', headers: { 'User-Agent': 'dsh-git-push', Range: 'bytes=0-1023' }, signal: ctrl.signal });
|
|
215
|
+
if (!r.ok && r.status !== 206) return { ok: false, mirror: prefix, error: `HTTP ${r.status}` };
|
|
216
|
+
const len = Number(r.headers?.get?.('content-length')) || 0;
|
|
217
|
+
const cr = String(r.headers?.get?.('content-range') || '');
|
|
218
|
+
const total = Number(/\/(\d+)\s*$/.exec(cr)?.[1]) || 0;
|
|
219
|
+
// 声明总长与已知字节数不符 = 该源缓存坏了(这次事故的典型形态),直接判不健康
|
|
220
|
+
if (expectedBytes > 0 && total > 0 && total !== expectedBytes) {
|
|
221
|
+
return { ok: false, mirror: prefix, error: `声明总长 ${total} ≠ 期望 ${expectedBytes}`, total };
|
|
222
|
+
}
|
|
223
|
+
if (!len && !total) return { ok: false, mirror: prefix, error: '响应无长度信息' };
|
|
224
|
+
return { ok: true, mirror: prefix, total: total || null, len };
|
|
225
|
+
} catch (e) {
|
|
226
|
+
return { ok: false, mirror: prefix, error: String((e?.message) || e) };
|
|
227
|
+
} finally { clearTimeout(timer); }
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* 探测全部候选并把结果写回学习状态(成功清零并恢复,失败累计)。
|
|
232
|
+
* @returns {Promise<Array<{mirror:string, ok:boolean, error?:string}>>}
|
|
233
|
+
*/
|
|
234
|
+
export async function probeAll({ seedPath, stateFile = statePath(), fetchImpl, timeoutMs, expectedBytes } = {}) {
|
|
235
|
+
const list = listCandidates({ seedPath, stateFile });
|
|
236
|
+
const results = [];
|
|
237
|
+
for (const c of list) {
|
|
238
|
+
const r = await probeMirror({ mirror: c.mirror, stateFile, fetchImpl, timeoutMs, expectedBytes });
|
|
239
|
+
recordOutcome(c.mirror, { ok: r.ok, error: r.error, stateFile });
|
|
240
|
+
results.push({ mirror: c.mirror, ok: r.ok, error: r.error });
|
|
241
|
+
}
|
|
242
|
+
return results;
|
|
243
|
+
}
|
|
@@ -27,7 +27,8 @@ import { mkdir, rename, unlink, chmod, symlink, rm, readdir, rmdir, access } fro
|
|
|
27
27
|
import { dirname, join } from 'node:path';
|
|
28
28
|
import { pipeline } from 'node:stream/promises';
|
|
29
29
|
import { Readable } from 'node:stream';
|
|
30
|
-
import { blobApiUrl, contentsApiUrl, rawFileUrl } from './endpoints.js';
|
|
30
|
+
import { blobApiUrl, contentsApiUrl, rawFileUrl, mirrorPrefix, GH_RAW } from './endpoints.js';
|
|
31
|
+
import { listCandidates, normalizeMirror, recordOutcome } from '../core/mirror-store.js';
|
|
31
32
|
|
|
32
33
|
/* ───────── clone 下载器常量 ───────── */
|
|
33
34
|
const RETRY_BASE_DELAY_MS = 120; // 失败重试基础延迟(第 i 次重试等待 120×(i+1)ms,线性退避)
|
|
@@ -312,6 +313,30 @@ export async function removeDirForce(dir, attempts = 3) {
|
|
|
312
313
|
try { await access(dir); return false; } catch { return true; } // 不存在即视为成功
|
|
313
314
|
}
|
|
314
315
|
|
|
316
|
+
/**
|
|
317
|
+
* 本次请求走的是哪个镜像(未走镜像返回空串)。
|
|
318
|
+
*
|
|
319
|
+
* 用途:只有**真正经镜像**的请求才该影响镜像健康度;api.github.com 直连通道
|
|
320
|
+
* (不走镜像)成功或失败都与镜像无关,不能记到它头上。
|
|
321
|
+
*/
|
|
322
|
+
function mirrorOf(url) {
|
|
323
|
+
try {
|
|
324
|
+
const mp = mirrorPrefix();
|
|
325
|
+
return mp && String(url).startsWith(mp) ? mp : '';
|
|
326
|
+
} catch { return ''; }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 把一次实际使用的成败记到镜像健康度上(数据校验才是判据:坏镜像表现为
|
|
331
|
+
* HTTP 正常但内容截断/陈旧,只有 total/sha 校验能识别)。
|
|
332
|
+
* 记录失败不影响本次下载结果——它只影响「下次优先选谁」。
|
|
333
|
+
*/
|
|
334
|
+
function noteMirror(url, ok, error) {
|
|
335
|
+
const mp = mirrorOf(url);
|
|
336
|
+
if (!mp) return;
|
|
337
|
+
try { recordOutcome(mp, { ok, error }); } catch { /* 健康度是加速用的元数据,失败不打断下载 */ }
|
|
338
|
+
}
|
|
339
|
+
|
|
315
340
|
/** 从响应头提取「该源声明的文件总长」:206 用 content-range 的 /total,200 用 content-length。0=无从判断。 */
|
|
316
341
|
function totalFromResponse(resp) {
|
|
317
342
|
try {
|
|
@@ -357,7 +382,22 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
|
|
|
357
382
|
// 需要续传(have > 0)或 api 失败时退 raw(能断点续,接受其并发不稳)。
|
|
358
383
|
const useRawFirst = have > 0;
|
|
359
384
|
const apiUrl = contentsApiUrl(owner, repo, encoded, encodedBranch);
|
|
360
|
-
const rawUrl = rawFileUrl(owner, repo, encodedBranch, encoded); // raw
|
|
385
|
+
const rawUrl = rawFileUrl(owner, repo, encodedBranch, encoded); // raw 走当前选中的镜像
|
|
386
|
+
// 直连 raw(不经镜像):镜像全部不可用时仍是可用通道
|
|
387
|
+
const rawDirect = `${GH_RAW}/${owner}/${repo}/${encodedBranch}/${encoded}`;
|
|
388
|
+
// **同一文件的救援链**:当前镜像之外的其它候选镜像也要试。
|
|
389
|
+
// 为什么必须这样:候选清单原先只影响「选谁」,而单个文件一旦撞上某个镜像的坏缓存
|
|
390
|
+
// (实测某镜像对该文件只有 590454 字节的截断版本),链里只剩 api 全量重下——
|
|
391
|
+
// 续传能力就白费了。把全部可用镜像都放进链里,才能真的「换一个镜像接着续」。
|
|
392
|
+
const altMirrors = (() => {
|
|
393
|
+
try {
|
|
394
|
+
return listCandidates()
|
|
395
|
+
.filter((it) => !it.disabled)
|
|
396
|
+
.map((it) => normalizeMirror(it.mirror))
|
|
397
|
+
.filter((m) => m && rawUrl !== m && !String(rawUrl).startsWith(m))
|
|
398
|
+
.map((m) => `${m}${rawDirect}`);
|
|
399
|
+
} catch { return []; }
|
|
400
|
+
})();
|
|
361
401
|
const mkHeaders = (raw, withRange) => {
|
|
362
402
|
const headers = { 'User-Agent': 'dsh-git-push' };
|
|
363
403
|
if (token) headers.Authorization = `Bearer ${token}`;
|
|
@@ -366,7 +406,13 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
|
|
|
366
406
|
if (withRange && have > 0) headers.Range = `bytes=${have}-`;
|
|
367
407
|
return headers;
|
|
368
408
|
};
|
|
369
|
-
const
|
|
409
|
+
const mirrorChain = [rawUrl, ...altMirrors].filter((u, i, a) => u && a.indexOf(u) === i).map((u) => [u, true]);
|
|
410
|
+
// 续传优先(have>0):镜像链在前(唯一支持 Range),api 全量兜底;
|
|
411
|
+
// 起步(have=0):api 稳、优先,镜像链随后。直连 raw 仅在**没有任何镜像**时补位。
|
|
412
|
+
const urls = useRawFirst
|
|
413
|
+
? [...mirrorChain, [apiUrl, false]]
|
|
414
|
+
: [[apiUrl, false], ...mirrorChain];
|
|
415
|
+
if (!mirrorChain.length) urls.push([rawDirect, true]);
|
|
370
416
|
|
|
371
417
|
// 依次尝试候选通道,首个成功即用;全失败则回报最后一条的成因
|
|
372
418
|
let resp = null;
|
|
@@ -397,6 +443,7 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
|
|
|
397
443
|
const declaredTotal = totalFromResponse(resp);
|
|
398
444
|
if (declaredTotal > 0 && declaredTotal !== size) {
|
|
399
445
|
try { await resp.body?.cancel?.(); } catch { /* 无所谓 */ }
|
|
446
|
+
noteMirror(urls[respIdx]?.[0], false, `声明总长 ${declaredTotal} ≠ 仓库记录 ${size}(疑似截断缓存)`);
|
|
400
447
|
lastErr = { status: resp.status, reason: `通道数据异常(声明总长 ${declaredTotal} ≠ 仓库记录 ${size},疑似代理截断缓存),弃用该源` };
|
|
401
448
|
let rescued = false;
|
|
402
449
|
for (let ci = 0; ci < urls.length; ci++) {
|
|
@@ -440,7 +487,7 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
|
|
|
440
487
|
if (expectSha && size > 0) {
|
|
441
488
|
const { createHash } = await import('node:crypto');
|
|
442
489
|
hasher = createHash('sha1');
|
|
443
|
-
hasher.update(`blob ${size}\u0000`, 'latin1'); // git object header
|
|
490
|
+
hasher.update(`blob ${size}\u0000`, 'latin1'); // git object header(\u0000 按 latin1 保持单字节)
|
|
444
491
|
if (appending && have > 0) {
|
|
445
492
|
try { hasher.update(readFileSync(partPath)); } catch { hasher = null; }
|
|
446
493
|
}
|
|
@@ -462,10 +509,13 @@ async function fetchToFile({ owner, repo, branch, relPath, token, out, partPath,
|
|
|
462
509
|
const got = hasher.digest('hex');
|
|
463
510
|
if (got !== String(expectSha)) {
|
|
464
511
|
try { await unlink(partPath); } catch { /* 忽略 */ }
|
|
512
|
+
// 内容与 tree 记录的 sha 不符:坏镜像 / 脏前缀都会这样。同样计入镜像健康度。
|
|
513
|
+
noteMirror(urls[respIdx]?.[0], false, `blob sha 不符(实得 ${got.slice(0, 10)}…)`);
|
|
465
514
|
return { ok: false, status: resp.status, reason: `内容校验不符(blob sha 期望 ${String(expectSha).slice(0, 10)}…,实得 ${got.slice(0, 10)}…),已废弃分片以便下轮干净重下` };
|
|
466
515
|
}
|
|
467
516
|
}
|
|
468
517
|
await rename(partPath, out);
|
|
518
|
+
noteMirror(urls[respIdx]?.[0], true); // 校验全过 ⇒ 该镜像这次是健康的
|
|
469
519
|
return { ok: true };
|
|
470
520
|
} catch (e) {
|
|
471
521
|
return { ok: false, status: 0, reason: `写入失败: ${e?.message || e}` };
|
package/lib/self/index.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
export const VERSION = '2.13.
|
|
12
|
+
export const VERSION = '2.13.4'; // 2.13.4:镜像改**候选清单 + 健康度学习**(旧实现硬编码单一 gh-proxy.com,单点坏掉无退路——实测它对某 8MB 文件返回 total=590454 的截断缓存)。出厂清单 lib/core/mirror-candidates.json 只写优先级;运行期学习结果(failures/disabled/lastOkAt/lastError)落 <配置目录>/mirror-state.json,不污染入库文件。选择:DSH_GIT_MIRROR_PREFIX 显式值 > 清单首个未停用 > 全部停用则直连。停用判据以**数据校验**为准(声明总长不符 / blob sha 不符),连续 3 次停用、一次成功清零;clone-download 三处埋点(total/sha/成功),热路径加进程内缓存与「无变化不写盘」。另:test/run-tests.mjs 改**分批执行**(默认 40 文件/批,每批独立进程 + 1GB 堆上限),解决全量回归单进程堆只涨不还在 8GB 机器上挤爆内存的问题;新增 --only=<子串> 便于单组调试。历史:2.13.3 克隆死循环修复。2.13.2 动态权重维度分母。
|
|
13
13
|
// 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
|
|
14
14
|
// 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
|
|
15
15
|
// 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
|