@marktrue/dsh-mobile-remote 3.2.4-alpha.2 → 3.2.4-alpha.20
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/CHANGELOG.md +527 -0
- package/README.md +2 -0
- package/docs/03-api.md +328 -26
- package/docs/04-security.md +14 -0
- package/docs/09-compatibility.md +25 -4
- package/docs/10-release.md +33 -60
- package/docs/11-notification-reliability.md +45 -0
- package/docs/12-implementation-status.md +41 -0
- package/docs/13-device-acceptance-2026-11-03.md +37 -0
- package/docs/16-next-window-handoff-2026-11-04.md +44 -0
- package/docs/17-remaining-work-review-2026-11-04.md +53 -0
- package/docs/18-device-reliability-acceptance-2026-11-04.md +63 -0
- package/docs/19-issue-followup-2026-11-04.md +39 -0
- package/docs/20-dsh-022-compatibility-2026-11-05.md +32 -0
- package/lib/client.js +23 -1
- package/lib/endpoint-registry.js +32 -12
- package/lib/git-read-bundled-provider.js +27 -13
- package/lib/git-read-service.js +309 -38
- package/lib/host-manager-update.js +178 -0
- package/lib/host-update-capabilities.js +209 -0
- package/lib/index.js +3019 -145
- package/lib/npm-update-source.js +16 -16
- package/lib/plugin-self-update.js +127 -12
- package/lib/plugin-update-check.js +268 -0
- package/lib/plugin-update-controller.js +129 -7
- package/lib/plugin-update-transaction.js +38 -2
- package/lib/update-lock-arbiter.js +46 -6
- package/lib/update-supervisor.js +38 -5
- package/package.json +9 -6
package/lib/npm-update-source.js
CHANGED
|
@@ -89,14 +89,22 @@ export async function resolveNpmUpdateCandidate({ packageName, localVersion, pac
|
|
|
89
89
|
}
|
|
90
90
|
record(`→ ${channel.channel}=${candidateVersion}`);
|
|
91
91
|
|
|
92
|
-
|
|
92
|
+
// issue #96:dist-tags 只取一次;插件与 carrier 元数据**并行**取(两者版本都可从
|
|
93
|
+
// dist-tag 候选版本推出),把总检查耗时压到一次 npm view 的量级。
|
|
94
|
+
const carrierVersion = appCarrierVersion(candidateVersion);
|
|
95
|
+
const alias = appCarrierAlias(packageName);
|
|
96
|
+
const expectedAliasSpec = `npm:${packageName}@${carrierVersion}`;
|
|
93
97
|
record(`$ npm view ${packageName}@${candidateVersion} --json`);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
+
record(`$ npm view ${packageName}@${carrierVersion} --json`);
|
|
99
|
+
const [pluginOutcome, carrierOutcome] = await Promise.all([
|
|
100
|
+
packageView(`${packageName}@${candidateVersion}`).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error })),
|
|
101
|
+
packageView(`${packageName}@${carrierVersion}`).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error })),
|
|
102
|
+
]);
|
|
103
|
+
if (!pluginOutcome.ok) {
|
|
104
|
+
record(`→ 失败:${viewFailureReason(pluginOutcome.error)}`);
|
|
98
105
|
return { ok: false, reason: "npm-plugin-metadata-unavailable" };
|
|
99
106
|
}
|
|
107
|
+
const plugin = pluginOutcome.value;
|
|
100
108
|
if (!plugin || plugin.version !== candidateVersion) {
|
|
101
109
|
record(`→ 版本不符:${String(plugin?.version ?? "缺失")} ≠ ${candidateVersion}`);
|
|
102
110
|
return { ok: false, reason: "npm-plugin-version-mismatch" };
|
|
@@ -107,23 +115,15 @@ export async function resolveNpmUpdateCandidate({ packageName, localVersion, pac
|
|
|
107
115
|
return { ok: false, reason: "npm-plugin-integrity-missing" };
|
|
108
116
|
}
|
|
109
117
|
record(`→ 插件 v${candidateVersion}`);
|
|
110
|
-
|
|
111
|
-
const carrierVersion = appCarrierVersion(candidateVersion);
|
|
112
|
-
const alias = appCarrierAlias(packageName);
|
|
113
|
-
const expectedAliasSpec = `npm:${packageName}@${carrierVersion}`;
|
|
114
118
|
if (plugin.optionalDependencies?.[alias] !== expectedAliasSpec) {
|
|
115
119
|
record(`→ 载体别名不匹配:${String(plugin.optionalDependencies?.[alias] ?? "缺失")}(期望 ${expectedAliasSpec})`);
|
|
116
120
|
return { ok: false, reason: "npm-carrier-alias-mismatch" };
|
|
117
121
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
record(`$ npm view ${packageName}@${carrierVersion} --json`);
|
|
121
|
-
try {
|
|
122
|
-
carrier = await packageView(`${packageName}@${carrierVersion}`);
|
|
123
|
-
} catch (error) {
|
|
124
|
-
record(`→ 失败:${viewFailureReason(error)}`);
|
|
122
|
+
if (!carrierOutcome.ok) {
|
|
123
|
+
record(`→ 失败:${viewFailureReason(carrierOutcome.error)}`);
|
|
125
124
|
return { ok: false, reason: "npm-carrier-metadata-unavailable" };
|
|
126
125
|
}
|
|
126
|
+
const carrier = carrierOutcome.value;
|
|
127
127
|
if (!carrier || carrier.version !== carrierVersion) {
|
|
128
128
|
record(`→ 版本不符:${String(carrier?.version ?? "缺失")} ≠ ${carrierVersion}`);
|
|
129
129
|
return { ok: false, reason: "npm-carrier-version-mismatch" };
|
|
@@ -288,7 +288,7 @@ export function isAllowedDownloadUrl(url) {
|
|
|
288
288
|
* 该形态下如何更新;不能自更新时给出**与实际安装方式对应的那一条**降级指引(R11)。
|
|
289
289
|
* `canSelfUpdate` 由调用方按宿主运行形态判定后传入。
|
|
290
290
|
*/
|
|
291
|
-
export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "" } = {}) {
|
|
291
|
+
export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdate = true, reason = "", channel = "" } = {}) {
|
|
292
292
|
const installCmd = "pnpm install";
|
|
293
293
|
const base = (() => {
|
|
294
294
|
switch (shape) {
|
|
@@ -330,7 +330,20 @@ export function planForShape(shape, { specifier = "", dirPath = "", canSelfUpdat
|
|
|
330
330
|
};
|
|
331
331
|
}
|
|
332
332
|
})();
|
|
333
|
-
|
|
333
|
+
// 通道优先:能走宿主原生管理器时,指引要描述**实际会发生什么**,而不是让用户去跑
|
|
334
|
+
// pnpm install(旧实现只按「能不能重启」决定 auto/guidance,容器里就永远给手工指引)。
|
|
335
|
+
if (channel === "host-manager") {
|
|
336
|
+
return {
|
|
337
|
+
summary: "由 DSH 插件管理器在进程内更新,无需重启宿主",
|
|
338
|
+
steps: ["确认目标版本", "宿主移除旧版本并安装新版本", "插件在进程内重新加载(连接不中断)"],
|
|
339
|
+
commands: [],
|
|
340
|
+
shape,
|
|
341
|
+
mode: "auto",
|
|
342
|
+
reason,
|
|
343
|
+
channel,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
return { ...base, shape, mode: canSelfUpdate ? "auto" : "guidance", reason, channel };
|
|
334
347
|
}
|
|
335
348
|
|
|
336
349
|
/** 检查是否有新版(**不下载、不改动任何东西**)。 */
|
|
@@ -639,7 +652,7 @@ function writeJsonFile(file, doc) {
|
|
|
639
652
|
|
|
640
653
|
// ── 重启 ──────────────────────────────────────────────────────────────────
|
|
641
654
|
|
|
642
|
-
export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh" } = {}) {
|
|
655
|
+
export function restartPlan({ form, pid = null, profile = "web", dshCommand = "dsh", respawnCommand = "" } = {}) {
|
|
643
656
|
switch (form) {
|
|
644
657
|
case "web-systemd":
|
|
645
658
|
return {
|
|
@@ -648,11 +661,16 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
|
|
|
648
661
|
commands: pid ? [`kill -TERM ${pid}`] : ["systemctl --user restart dsh-web.service"],
|
|
649
662
|
};
|
|
650
663
|
case "web-foreground":
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
664
|
+
// 优先复用**本进程原样的命令行**(含 --port / --no-open 等参数):容器与自定义启动
|
|
665
|
+
// 方式下拼一个 `dsh web --profile x` 会丢掉这些参数,重启后端口就变了。
|
|
666
|
+
{
|
|
667
|
+
const respawn = respawnCommand !== "" ? respawnCommand : `${dshCommand} web --profile ${profile}`;
|
|
668
|
+
return {
|
|
669
|
+
mode: "respawn",
|
|
670
|
+
steps: ["终止当前宿主进程", "由分离脚本用原命令行重新拉起 dsh web"],
|
|
671
|
+
commands: pid ? [`kill -TERM ${pid}`, respawn] : [respawn],
|
|
672
|
+
};
|
|
673
|
+
}
|
|
656
674
|
default:
|
|
657
675
|
return {
|
|
658
676
|
mode: "unsupported",
|
|
@@ -666,13 +684,96 @@ export function restartPlan({ form, pid = null, profile = "web", dshCommand = "d
|
|
|
666
684
|
* 识别本机可自动重启的形态。
|
|
667
685
|
* **默认读真实 `process.env`**——生产调用漏传 env 会让前台 web 永远探测不到(评审 R12)。
|
|
668
686
|
*/
|
|
669
|
-
export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false } = {}) {
|
|
687
|
+
export function detectRestartForm({ env = process.env, platform = process.platform, hasSystemdUnit = () => false, commandLine = null } = {}) {
|
|
670
688
|
if (platform === "win32" || platform === "darwin") return "unsupported";
|
|
671
689
|
if (hasSystemdUnit()) return "web-systemd";
|
|
690
|
+
// 显式标记:启动脚本/服务单元自己声明了这是可重启的前台 web。
|
|
672
691
|
if (env?.DSH_PROFILE || env?.DSH_WEB_FOREGROUND === "1") return "web-foreground";
|
|
692
|
+
// 退一步看**实际命令行**:`dsh web ...` 本身就是前台 web 形态,与原命令行重启就能生效。
|
|
693
|
+
// 旧实现只看两个环境变量,于是容器/自定义启动(`dsh web --port 3082`,无 DSH_PROFILE)
|
|
694
|
+
// 被误判成 unsupported,整条自更新降级成「请到电脑上运行 pnpm install」。
|
|
695
|
+
// 命令行证据是**本进程自己的**,不依赖外部约定,因此可以作为该判定的依据。
|
|
696
|
+
if (Array.isArray(commandLine) && isDshWebCommandLine(commandLine)) return "web-foreground";
|
|
673
697
|
return "unsupported";
|
|
674
698
|
}
|
|
675
699
|
|
|
700
|
+
/**
|
|
701
|
+
* 判断命令行是否是前台 `dsh web` 调用。
|
|
702
|
+
*
|
|
703
|
+
* 只认「结尾是 dsh 入口 + `web` 子命令」的形状(兼容 `node <path>/dsh web ...`),
|
|
704
|
+
* 不猜其它形状——误判会让重启脚本执行错误的命令。
|
|
705
|
+
*
|
|
706
|
+
* @param {string[]} commandLine - 完整命令行(`process.argv` 形状)。
|
|
707
|
+
* @returns {boolean}
|
|
708
|
+
*/
|
|
709
|
+
export function isDshWebCommandLine(commandLine) {
|
|
710
|
+
if (!Array.isArray(commandLine) || commandLine.length < 2) return false;
|
|
711
|
+
// 第一个参数是 node(或执行器),从第二个开始找 dsh 入口;允许前面有 `--flag`。
|
|
712
|
+
const rest = commandLine.slice(1);
|
|
713
|
+
const dshIndex = rest.findIndex((arg) => typeof arg === "string" && /(^|\/)dsh$/i.test(arg));
|
|
714
|
+
if (dshIndex === -1) return false;
|
|
715
|
+
// dsh 之后第一个**位置参数**必须是 `web`。
|
|
716
|
+
// 注意不能简单地「跳过所有 - 开头的参数再取第一个」:`--profile web` 的取值
|
|
717
|
+
// `web` 会被误当成子命令,而 `--profile web` 实际是「启动名为 web 的 profile」。
|
|
718
|
+
// 因此这里按 dsh 自己的 CLI 选项表跳过取值。
|
|
719
|
+
return firstDshPositional(rest.slice(dshIndex + 1)) === "web";
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** dsh 顶层会吃掉一个取值的选项(见 `dsh --help`)。 */
|
|
723
|
+
const DSH_VALUE_OPTIONS = new Set([
|
|
724
|
+
"--profile",
|
|
725
|
+
"--from-default-profile",
|
|
726
|
+
"--patch",
|
|
727
|
+
]);
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* 取 dsh 参数里第一个位置参数,跳过选项及其取值。
|
|
731
|
+
*
|
|
732
|
+
* `--profile web` 与 `--patch a.yml` 的取值不算位置参数;`--flag=value` 形式不占额外参数。
|
|
733
|
+
*
|
|
734
|
+
* @param {string[]} args - dsh 之后的参数。
|
|
735
|
+
* @returns {string} 第一个位置参数,没有则空串。
|
|
736
|
+
*/
|
|
737
|
+
export function firstDshPositional(args) {
|
|
738
|
+
for (let i = 0; i < args.length; i++) {
|
|
739
|
+
const arg = args[i];
|
|
740
|
+
if (typeof arg !== "string" || arg === "") continue;
|
|
741
|
+
if (arg.startsWith("-")) {
|
|
742
|
+
// 已带 `=` 的形式(`--profile=web`)不再吃下一个参数。
|
|
743
|
+
if (arg.includes("=")) continue;
|
|
744
|
+
if (DSH_VALUE_OPTIONS.has(arg)) i++;
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
return arg;
|
|
748
|
+
}
|
|
749
|
+
return "";
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* 用本进程原命令行重建一条可执行的 respawn 命令(用于前台 web 形态的重启)。
|
|
754
|
+
*
|
|
755
|
+
* 重新执行的必须是**同一入口、同一参数**;拿不到可靠命令行时返回空串,
|
|
756
|
+
* 由调用方退回 `dsh web --profile <name>` 的保守写法。
|
|
757
|
+
*
|
|
758
|
+
* @param {string[]} commandLine - `process.argv`。
|
|
759
|
+
* @returns {string} 可直接交给 shell 的命令行,或空串。
|
|
760
|
+
*/
|
|
761
|
+
export function respawnCommandOf(commandLine) {
|
|
762
|
+
if (!isDshWebCommandLine(commandLine)) return "";
|
|
763
|
+
const parts = commandLine.map((arg) => String(arg));
|
|
764
|
+
// `process.argv[0]` 是 node 可执行文件;用 process.execPath 更稳(argv[0] 可能是别名)。
|
|
765
|
+
if (parts.length > 0) parts[0] = process.execPath;
|
|
766
|
+
return parts.map(shellQuote).join(" ");
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** 最小 shell 引用:只给含空白/特殊字符的参数加引号,避免破坏正常路径。 */
|
|
770
|
+
function shellQuote(value) {
|
|
771
|
+
const text = String(value);
|
|
772
|
+
if (text === "") return "''";
|
|
773
|
+
if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(text)) return text;
|
|
774
|
+
return `'${text.replace(/'/g, `'\\''`)}'`;
|
|
775
|
+
}
|
|
776
|
+
|
|
676
777
|
export function buildRestartScript({ plan, pid = null, delayMs = 3000 } = {}) {
|
|
677
778
|
const seconds = Math.max(0, Math.round(delayMs / 1000));
|
|
678
779
|
if (plan?.mode === "supervised") {
|
|
@@ -962,20 +1063,34 @@ export async function runSelfUpdate({
|
|
|
962
1063
|
* 但**任何非终态**(staging / installing / restart-pending)在持有者已死且超时后
|
|
963
1064
|
* 都必须收敛为 FAILED,否则后续更新会永久 busy。
|
|
964
1065
|
*/
|
|
965
|
-
export function reportPendingUpdate({ stateFile, lockPath = "", localContentSha256 = "", supervisorAlive = false, timeoutMs = 10 * 60 * 1000, now = () => Date.now() } = {}) {
|
|
1066
|
+
export function reportPendingUpdate({ stateFile, lockPath = "", localContentSha256 = "", holderAlive = false, supervisorAlive = false, timeoutMs = 10 * 60 * 1000, now = () => Date.now() } = {}) {
|
|
966
1067
|
const tx = readTransaction(stateFile);
|
|
967
1068
|
if (!tx) return { action: "none", reason: "no-transaction", transaction: null };
|
|
968
1069
|
if (isTerminalPhase(tx.phase)) return { action: "none", reason: `phase-${tx.phase}`, transaction: tx };
|
|
969
1070
|
if (tx.phase === TRANSACTION_PHASE.RESTART_PENDING) {
|
|
970
1071
|
const target = String(tx.targetContentSha256 ?? "").toLowerCase();
|
|
971
1072
|
if (target !== "" && String(localContentSha256 ?? "").toLowerCase() === target) {
|
|
1073
|
+
// issue #110 P1-B:内容已生效且 holder 已死 → 启动方可认领并结算;
|
|
1074
|
+
// holder 仍活着时插件只报告,不抢监督器。
|
|
1075
|
+
if (!holderAlive) {
|
|
1076
|
+
return { action: "adoptable", reason: "loaded-target-content-adopted", transaction: tx };
|
|
1077
|
+
}
|
|
972
1078
|
return { action: "matched", reason: "loaded-target-content", transaction: tx };
|
|
973
1079
|
}
|
|
974
1080
|
}
|
|
975
1081
|
if (!lockPath) return { action: "waiting", reason: "no-lock-path", transaction: tx };
|
|
976
|
-
const converged = convergeStaleTransaction({
|
|
1082
|
+
const converged = convergeStaleTransaction({
|
|
1083
|
+
stateFile,
|
|
1084
|
+
lockPath,
|
|
1085
|
+
localContentSha256,
|
|
1086
|
+
now,
|
|
1087
|
+
staleMs: timeoutMs,
|
|
1088
|
+
});
|
|
1089
|
+
if (converged.action === "settled") {
|
|
1090
|
+
return { action: "matched", reason: "loaded-target-content-adopted", transaction: converged.transaction };
|
|
1091
|
+
}
|
|
977
1092
|
if (converged.action === "converged") {
|
|
978
|
-
return { action: "expired", reason: "holder-gone", transaction: converged.transaction };
|
|
1093
|
+
return { action: "expired", reason: "converged-after-holder-gone", transaction: converged.transaction };
|
|
979
1094
|
}
|
|
980
1095
|
if (converged.action === "active") {
|
|
981
1096
|
return { action: "waiting", reason: supervisorAlive ? "supervisor-running" : "update-in-progress", transaction: tx };
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// issue #96:插件更新检查快照 + 有界异步检查任务。
|
|
2
|
+
//
|
|
3
|
+
// - 一次检查总 deadline(默认 12s)严格小于旧 App 的 15s 兼容窗口;
|
|
4
|
+
// 单次 npm view 仍可 20s,但整次检查 race 到 deadline 时返回明确 check-timeout,
|
|
5
|
+
// 绝不返回半结果。
|
|
6
|
+
// - 成功快照 5min、失败/unavailable 30s;force 绕过读缓存;cache key 含更新源/本地版本,
|
|
7
|
+
// 源配置或本地版本变化自然失效;宿主更新成功后调用 invalidate()。
|
|
8
|
+
// - 异步任务只存内存 map + TTL;同 key in-flight 去重;不持久化、不复用更新事务。
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
|
|
11
|
+
export const UPDATE_CHECK_STATE = Object.freeze({
|
|
12
|
+
CHECKING: "checking",
|
|
13
|
+
DONE: "done",
|
|
14
|
+
ERROR: "error",
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const TIMEOUT_RESULT = {
|
|
18
|
+
state: "unavailable",
|
|
19
|
+
reason: "check-timeout",
|
|
20
|
+
source: "npm",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function isFailureResult(result) {
|
|
24
|
+
return result?.state !== "update-available" && result?.state !== "up-to-date" && result?.state !== "local-ahead";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} options
|
|
29
|
+
* @param {() => Promise<object>} options.checkFn 真正的 update check(不得自行吞掉总超时)
|
|
30
|
+
* @param {() => string} [options.cacheKey] 更新源/本地版本指纹
|
|
31
|
+
* @param {number} [options.checkTimeoutMs] 整次检查 deadline;必须 < 15000
|
|
32
|
+
* @param {number} [options.successTtlMs]
|
|
33
|
+
* @param {number} [options.failureTtlMs]
|
|
34
|
+
* @param {number} [options.taskTtlMs] checkId 结果保留时长
|
|
35
|
+
*/
|
|
36
|
+
export function createUpdateCheckService({
|
|
37
|
+
checkFn,
|
|
38
|
+
cacheKey = () => "",
|
|
39
|
+
checkTimeoutMs = 12_000,
|
|
40
|
+
successTtlMs = 5 * 60 * 1000,
|
|
41
|
+
failureTtlMs = 30 * 1000,
|
|
42
|
+
taskTtlMs = 10 * 60 * 1000,
|
|
43
|
+
now = () => Date.now(),
|
|
44
|
+
newCheckId = () => randomUUID(),
|
|
45
|
+
} = {}) {
|
|
46
|
+
if (typeof checkFn !== "function") throw new TypeError("checkFn is required");
|
|
47
|
+
// 成功快照与失败短缓存分开:失败结果不进入“更新检查快照”(CONTEXT 契约),
|
|
48
|
+
// 只有成功结果可供展示/提交复用;失败/unavailable 单独 30s 短缓存防止风暴。
|
|
49
|
+
const snapshot = { key: "", result: null, at: 0 };
|
|
50
|
+
const failureCache = { key: "", result: null, at: 0 };
|
|
51
|
+
const tasks = new Map();
|
|
52
|
+
let activeTask = null;
|
|
53
|
+
let inFlight = null; // { key, promise }
|
|
54
|
+
// 代际:invalidate/强制重查后旧 runCheck 的迟到写回必须被丢弃。
|
|
55
|
+
let generation = 0;
|
|
56
|
+
|
|
57
|
+
function freshResult(key) {
|
|
58
|
+
if (snapshot.result !== null &&
|
|
59
|
+
snapshot.key === key &&
|
|
60
|
+
now() - snapshot.at < successTtlMs) return snapshot.result;
|
|
61
|
+
if (failureCache.result !== null &&
|
|
62
|
+
failureCache.key === key &&
|
|
63
|
+
now() - failureCache.at < failureTtlMs) return failureCache.result;
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function staleResult() {
|
|
68
|
+
return {
|
|
69
|
+
state: "unavailable",
|
|
70
|
+
reason: "check-stale",
|
|
71
|
+
source: "npm",
|
|
72
|
+
checkedAt: new Date().toISOString(),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function rememberFailure(key, result) {
|
|
76
|
+
failureCache.key = key;
|
|
77
|
+
failureCache.result = result;
|
|
78
|
+
failureCache.at = now();
|
|
79
|
+
// 更新检查失败后,旧成功快照不再代表当前检查结果,必须失效。
|
|
80
|
+
snapshot.result = null;
|
|
81
|
+
snapshot.key = "";
|
|
82
|
+
snapshot.at = 0;
|
|
83
|
+
}
|
|
84
|
+
function rememberSuccess(key, result) {
|
|
85
|
+
snapshot.key = key;
|
|
86
|
+
snapshot.result = result;
|
|
87
|
+
snapshot.at = now();
|
|
88
|
+
failureCache.result = null;
|
|
89
|
+
failureCache.key = "";
|
|
90
|
+
failureCache.at = 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function timeoutError() {
|
|
94
|
+
return Object.assign(new Error("check-timeout"), { code: "check-timeout" });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function runWithDeadline() {
|
|
98
|
+
let timer = null;
|
|
99
|
+
const deadline = new Promise((_, reject) => {
|
|
100
|
+
timer = setTimeout(() => reject(timeoutError()), checkTimeoutMs);
|
|
101
|
+
timer.unref?.();
|
|
102
|
+
});
|
|
103
|
+
return Promise.race([Promise.resolve().then(checkFn), deadline]).finally(() => {
|
|
104
|
+
if (timer) clearTimeout(timer);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function runCheck(key, runGeneration) {
|
|
109
|
+
let result;
|
|
110
|
+
try {
|
|
111
|
+
result = await runWithDeadline();
|
|
112
|
+
if (result?.state === "checking") return result;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (error?.code === "check-timeout") {
|
|
115
|
+
result = { ...TIMEOUT_RESULT, checkedAt: new Date().toISOString() };
|
|
116
|
+
} else {
|
|
117
|
+
// review P2:checkFn 任意异常都脱敏成稳定失败结果并进入失败短缓存,
|
|
118
|
+
// 不原样返回 message,也避免连续两次 throw 都打 npm。
|
|
119
|
+
result = {
|
|
120
|
+
state: "unavailable",
|
|
121
|
+
reason: "check-failed",
|
|
122
|
+
source: "npm",
|
|
123
|
+
checkedAt: new Date().toISOString(),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (!result || typeof result !== "object") {
|
|
128
|
+
result = {
|
|
129
|
+
state: "unavailable",
|
|
130
|
+
reason: "check-failed",
|
|
131
|
+
source: "npm",
|
|
132
|
+
checkedAt: new Date().toISOString(),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const stamped = typeof result.checkedAt === "string" ? result : { ...result, checkedAt: new Date().toISOString() };
|
|
136
|
+
// 旧代结果不写缓存,但调用方必须拿到明确的非 null stale 结果(可重试)。
|
|
137
|
+
if (runGeneration !== generation) return staleResult();
|
|
138
|
+
if (isFailureResult(stamped)) rememberFailure(key, stamped);
|
|
139
|
+
else rememberSuccess(key, stamped);
|
|
140
|
+
return stamped;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function check({ force = false } = {}) {
|
|
144
|
+
const key = String(cacheKey() ?? "");
|
|
145
|
+
if (!force) {
|
|
146
|
+
const cached = freshResult(key);
|
|
147
|
+
if (cached) return cached;
|
|
148
|
+
}
|
|
149
|
+
// bootstrap + 立即 force:仍复用同一个 in-flight(不重复出网)。
|
|
150
|
+
if (inFlight && inFlight.key === key) return inFlight.promise;
|
|
151
|
+
// force 且没有可复用 in-flight:换代,旧在途结果不得回填。
|
|
152
|
+
if (force) generation += 1;
|
|
153
|
+
const runGeneration = generation;
|
|
154
|
+
const promise = (async () => {
|
|
155
|
+
try {
|
|
156
|
+
return await runCheck(key, runGeneration);
|
|
157
|
+
} finally {
|
|
158
|
+
if (inFlight?.promise === promise) inFlight = null;
|
|
159
|
+
}
|
|
160
|
+
})();
|
|
161
|
+
inFlight = { key, promise };
|
|
162
|
+
return promise;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function scheduleTaskExpiry(task) {
|
|
166
|
+
const timer = setTimeout(() => {
|
|
167
|
+
if (tasks.get(task.checkId) === task) tasks.delete(task.checkId);
|
|
168
|
+
}, taskTtlMs);
|
|
169
|
+
timer.unref?.();
|
|
170
|
+
task.expiryTimer = timer;
|
|
171
|
+
if (activeTask === task) activeTask = null;
|
|
172
|
+
return () => clearTimeout(timer);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function startAsync({ force = false } = {}) {
|
|
176
|
+
const key = String(cacheKey() ?? "");
|
|
177
|
+
if (activeTask && activeTask.state === UPDATE_CHECK_STATE.CHECKING && activeTask.key === key) {
|
|
178
|
+
return { state: UPDATE_CHECK_STATE.CHECKING, checkId: activeTask.checkId };
|
|
179
|
+
}
|
|
180
|
+
const checkId = newCheckId();
|
|
181
|
+
const task = {
|
|
182
|
+
checkId,
|
|
183
|
+
key,
|
|
184
|
+
state: UPDATE_CHECK_STATE.CHECKING,
|
|
185
|
+
startedAt: now(),
|
|
186
|
+
result: null,
|
|
187
|
+
error: null,
|
|
188
|
+
promise: null,
|
|
189
|
+
expiryTimer: null,
|
|
190
|
+
};
|
|
191
|
+
tasks.set(checkId, task);
|
|
192
|
+
activeTask = task;
|
|
193
|
+
// 异步任务与同步 GET 共享同一个 check promise(含 deadline、缓存、in-flight 去重)。
|
|
194
|
+
task.promise = check({ force }).then(
|
|
195
|
+
(result) => {
|
|
196
|
+
task.result = result;
|
|
197
|
+
task.state = UPDATE_CHECK_STATE.DONE;
|
|
198
|
+
task.finishedAt = now();
|
|
199
|
+
scheduleTaskExpiry(task);
|
|
200
|
+
return result;
|
|
201
|
+
},
|
|
202
|
+
(error) => {
|
|
203
|
+
task.state = UPDATE_CHECK_STATE.ERROR;
|
|
204
|
+
// issue #96 review P2:HTTP 只回稳定 code,绝不返回 error.message(可能含路径)。
|
|
205
|
+
task.error = error?.code === "check-timeout" ? "check-timeout" : "check-failed";
|
|
206
|
+
task.finishedAt = now();
|
|
207
|
+
scheduleTaskExpiry(task);
|
|
208
|
+
return null;
|
|
209
|
+
},
|
|
210
|
+
);
|
|
211
|
+
return { state: UPDATE_CHECK_STATE.CHECKING, checkId };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function getAsync(checkId) {
|
|
215
|
+
const task = tasks.get(String(checkId ?? ""));
|
|
216
|
+
if (!task) return { status: 404, body: { state: "error", error: "check-not-found" } };
|
|
217
|
+
if (task.state === UPDATE_CHECK_STATE.CHECKING) {
|
|
218
|
+
const age = now() - (task.startedAt ?? now());
|
|
219
|
+
if (age > taskTtlMs) {
|
|
220
|
+
tasks.delete(task.checkId);
|
|
221
|
+
return { status: 410, body: { state: "error", error: "check-expired" } };
|
|
222
|
+
}
|
|
223
|
+
return { status: 200, body: { state: "checking", checkId: task.checkId } };
|
|
224
|
+
}
|
|
225
|
+
if (task.state === UPDATE_CHECK_STATE.ERROR) {
|
|
226
|
+
return { status: 200, body: { state: "error", checkId: task.checkId, error: task.error } };
|
|
227
|
+
}
|
|
228
|
+
return { status: 200, body: { state: "done", checkId: task.checkId, result: task.result } };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function checkSync() {
|
|
232
|
+
return check({ force: false });
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function checkForSubmit() {
|
|
236
|
+
// 优先 5min 成功快照;过期时等待当前 async 任务(同一 in-flight)或启动有 deadline 检查。
|
|
237
|
+
return check({ force: false });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function invalidate() {
|
|
241
|
+
generation += 1;
|
|
242
|
+
snapshot.result = null;
|
|
243
|
+
snapshot.key = "";
|
|
244
|
+
snapshot.at = 0;
|
|
245
|
+
failureCache.result = null;
|
|
246
|
+
failureCache.key = "";
|
|
247
|
+
failureCache.at = 0;
|
|
248
|
+
// issue #96 review P2:同时清掉 checkId 结果与 in-flight 去重;旧 checkId 不再 done。
|
|
249
|
+
for (const task of tasks.values()) {
|
|
250
|
+
if (task.expiryTimer) clearTimeout(task.expiryTimer);
|
|
251
|
+
}
|
|
252
|
+
tasks.clear();
|
|
253
|
+
activeTask = null;
|
|
254
|
+
inFlight = null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
check,
|
|
259
|
+
checkSync,
|
|
260
|
+
checkForSubmit,
|
|
261
|
+
startAsync,
|
|
262
|
+
getAsync,
|
|
263
|
+
invalidate,
|
|
264
|
+
snapshot: () => snapshot.result,
|
|
265
|
+
failureSnapshot: () => failureCache.result,
|
|
266
|
+
_checkTimeoutMs: checkTimeoutMs,
|
|
267
|
+
};
|
|
268
|
+
}
|