@cydm/pie 4.12.0 → 4.12.2

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.
@@ -0,0 +1,210 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+
3
+ // src/core/node-ownership-lock.ts
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomUUID } from "node:crypto";
9
+ var REBOOT_CLOCK_SKEW_MARGIN_MS = 6e4;
10
+ var PROCESS_IDENTITY_PROBE_TIMEOUT_MS = 500;
11
+ var MUTEX_PROBE_THROTTLE_MS = 250;
12
+ var NODE_OR_PIE_IDENTITY_RE = /(?:^|[\s/\\"'=])(?:node(?:\.exe)?|pie(?:\.exe|\.cmd)?|bun(?:\.exe)?|deno(?:\.exe)?|tsx(?:\.cmd)?|service-launcher(?:\.exe)?|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh(?:\.exe)?|cli\.(?:js|ts|mjs|cjs))(?:$|[\s/\\"'=])/i;
13
+ function pidDefinitelyDead(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return false;
18
+ } catch (error) {
19
+ return error.code === "ESRCH";
20
+ }
21
+ }
22
+ function isPreRebootTimestamp(timestampMs, nowMs = Date.now(), uptimeSec = os.uptime()) {
23
+ if (typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || timestampMs <= 0) return false;
24
+ if (!Number.isFinite(nowMs) || !Number.isFinite(uptimeSec) || uptimeSec < 0) return false;
25
+ const hostBootMs = nowMs - Math.floor(uptimeSec * 1e3);
26
+ return timestampMs < hostBootMs - REBOOT_CLOCK_SKEW_MARGIN_MS;
27
+ }
28
+ function parseWindowsTasklistImageName(stdout, expectedPid) {
29
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
30
+ for (const rawLine of stdout.split(/\r?\n/)) {
31
+ const line = rawLine.trim();
32
+ if (!line) continue;
33
+ const match = /^"([^"]+)"\s*,\s*"(\d+)"\s*,/.exec(line);
34
+ if (!match) return void 0;
35
+ const imageName = match[1].trim();
36
+ const rowPid = Number.parseInt(match[2], 10);
37
+ if (!imageName || rowPid !== expectedPid) return void 0;
38
+ return imageName;
39
+ }
40
+ return void 0;
41
+ }
42
+ function parsePosixPsIdentity(stdout, expectedPid) {
43
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
44
+ for (const rawLine of stdout.split(/\r?\n/)) {
45
+ const line = rawLine.trim();
46
+ if (!line) continue;
47
+ const match = /^(\d+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
48
+ if (!match) return void 0;
49
+ const rowPid = Number.parseInt(match[1], 10);
50
+ const comm = match[2].trim();
51
+ const args = match[3]?.trim() ?? "";
52
+ if (!comm || rowPid !== expectedPid) return void 0;
53
+ return args ? `${comm} ${args}` : comm;
54
+ }
55
+ return void 0;
56
+ }
57
+ function probeProcessIdentity(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
59
+ try {
60
+ if (process.platform === "win32") {
61
+ const out2 = execFileSync(
62
+ "tasklist",
63
+ ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"],
64
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
65
+ );
66
+ return parseWindowsTasklistImageName(out2, pid);
67
+ }
68
+ const out = execFileSync(
69
+ "ps",
70
+ ["-p", String(pid), "-o", "pid=,comm=,args="],
71
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }
72
+ );
73
+ return parsePosixPsIdentity(out, pid);
74
+ } catch {
75
+ return void 0;
76
+ }
77
+ }
78
+ function isPositivelyDeadHolder(pid, timestampMs, options) {
79
+ if (!Number.isInteger(pid) || pid <= 0) return false;
80
+ const checkDead = options?.isDead ?? pidDefinitelyDead;
81
+ if (checkDead(pid)) return true;
82
+ const selfPid = options?.selfPid ?? process.pid;
83
+ if (pid === selfPid) return false;
84
+ if (!isPreRebootTimestamp(timestampMs, options?.nowMs, options?.uptimeSec)) return false;
85
+ const identity = (options?.probeIdentity ?? probeProcessIdentity)(pid);
86
+ if (identity === void 0 || identity.trim().length === 0) return false;
87
+ return !NODE_OR_PIE_IDENTITY_RE.test(identity);
88
+ }
89
+ function withOwnershipMutex(lock, fn) {
90
+ fs.mkdirSync(path.dirname(lock), { recursive: true, mode: 448 });
91
+ const token = randomUUID();
92
+ const candidate = `${lock}.acquire.${token}`;
93
+ fs.mkdirSync(candidate, { mode: 448 });
94
+ try {
95
+ fs.writeFileSync(path.join(candidate, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, at: Date.now() }), { flag: "wx", mode: 384 });
96
+ const deadline = process.hrtime.bigint() + 2000000000n;
97
+ const lastNegativeProbeAt = /* @__PURE__ */ new Map();
98
+ for (; ; ) {
99
+ try {
100
+ fs.renameSync(candidate, lock);
101
+ break;
102
+ } catch (error) {
103
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "ENOTDIR"].includes(error.code ?? "")) throw error;
104
+ if (process.hrtime.bigint() >= deadline) throw new Error(`Ownership mutex contention: ${lock}`);
105
+ try {
106
+ const entries = fs.readdirSync(lock);
107
+ if (entries.every((name) => {
108
+ if (!/^held\.[a-f0-9-]+$/.test(name)) return false;
109
+ const value = JSON.parse(fs.readFileSync(path.join(lock, name), "utf8"));
110
+ if (value?.version !== 1 || !Number.isInteger(value.pid) || value.pid <= 0) return false;
111
+ if (pidDefinitelyDead(value.pid)) return true;
112
+ const heldAt = typeof value.at === "number" ? value.at : void 0;
113
+ const cacheKey = `${name}:${value.pid}`;
114
+ const now = Date.now();
115
+ const lastProbed = lastNegativeProbeAt.get(cacheKey);
116
+ if (lastProbed !== void 0 && now - lastProbed < MUTEX_PROBE_THROTTLE_MS) return false;
117
+ const dead = isPositivelyDeadHolder(value.pid, heldAt);
118
+ if (!dead) lastNegativeProbeAt.set(cacheKey, now);
119
+ return dead;
120
+ })) {
121
+ for (const name of entries) {
122
+ try {
123
+ fs.unlinkSync(path.join(lock, name));
124
+ } catch (e) {
125
+ if (e.code !== "ENOENT") throw e;
126
+ }
127
+ }
128
+ fs.rmdirSync(lock);
129
+ }
130
+ } catch {
131
+ }
132
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3);
133
+ }
134
+ }
135
+ try {
136
+ return fn();
137
+ } finally {
138
+ try {
139
+ fs.unlinkSync(path.join(lock, `held.${token}`));
140
+ } catch {
141
+ }
142
+ try {
143
+ fs.rmdirSync(lock);
144
+ } catch {
145
+ }
146
+ }
147
+ } finally {
148
+ fs.rmSync(candidate, { recursive: true, force: true });
149
+ }
150
+ }
151
+ function readOwnership(target, valid) {
152
+ let raw;
153
+ try {
154
+ raw = fs.readFileSync(target, "utf8");
155
+ } catch (error) {
156
+ if (error.code === "ENOENT") return void 0;
157
+ throw error;
158
+ }
159
+ const value = JSON.parse(raw);
160
+ if (!value || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.holder !== "string" || !Number.isFinite(value.heartbeatAt) || value.generation !== void 0 && typeof value.generation !== "string" || !valid(value)) {
161
+ throw new Error(`Invalid ownership record: ${target}`);
162
+ }
163
+ return value;
164
+ }
165
+ function claimOwnership(target, mine, valid) {
166
+ const mutex = `${target}.mutex`;
167
+ const generation = randomUUID();
168
+ const publish = () => {
169
+ const tmp = `${target}.${randomUUID()}.tmp`;
170
+ try {
171
+ fs.writeFileSync(tmp, `${JSON.stringify({ ...mine, generation, heartbeatAt: Date.now() })}
172
+ `, { flag: "wx", mode: 384 });
173
+ fs.renameSync(tmp, target);
174
+ } finally {
175
+ fs.rmSync(tmp, { force: true });
176
+ }
177
+ };
178
+ const holder = withOwnershipMutex(mutex, () => {
179
+ const current = readOwnership(target, valid);
180
+ if (current && !isPositivelyDeadHolder(current.pid, current.heartbeatAt)) return current;
181
+ publish();
182
+ return void 0;
183
+ });
184
+ if (holder) return { holder };
185
+ let released = false;
186
+ return { handle: {
187
+ heartbeat: () => {
188
+ if (released) return false;
189
+ return withOwnershipMutex(mutex, () => {
190
+ if (readOwnership(target, valid)?.generation !== generation) return false;
191
+ publish();
192
+ return true;
193
+ });
194
+ },
195
+ release: () => {
196
+ if (released) return;
197
+ released = true;
198
+ withOwnershipMutex(mutex, () => {
199
+ if (readOwnership(target, valid)?.generation === generation) fs.unlinkSync(target);
200
+ });
201
+ }
202
+ } };
203
+ }
204
+
205
+ export {
206
+ isPositivelyDeadHolder,
207
+ withOwnershipMutex,
208
+ readOwnership,
209
+ claimOwnership
210
+ };
@@ -1,9 +1,9 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  claimOwnership,
4
- pidDefinitelyDead,
4
+ isPositivelyDeadHolder,
5
5
  readOwnership
6
- } from "./chunk-BSITHT43.js";
6
+ } from "./chunk-Q4NJEPIZ.js";
7
7
  import {
8
8
  getSessionsDir
9
9
  } from "./chunk-CBDQJMUI.js";
@@ -25,7 +25,7 @@ function unavailable(sessionId) {
25
25
  function sessionOwnerAlive(sessionId, _now = Date.now()) {
26
26
  try {
27
27
  const info = readOwnership(lockPath(sessionId), (v) => v.sessionId === sessionId);
28
- return info && !pidDefinitelyDead(info.pid) ? info : void 0;
28
+ return info && !isPositivelyDeadHolder(info.pid, info.heartbeatAt) ? info : void 0;
29
29
  } catch {
30
30
  return unavailable(sessionId);
31
31
  }
@@ -98,8 +98,11 @@ function formatBlockingWindowsPeers(peers) {
98
98
  return `${label} "${p.name}" (pid ${p.pid})`;
99
99
  }).join(", ");
100
100
  }
101
+ function isWindowsTaskNotFoundDetail(detail) {
102
+ return /cannot find|does not exist|not found|找不到指定的文件|系统找不到/i.test(detail);
103
+ }
101
104
  function isWindowsTaskAlreadyStoppedDetail(detail) {
102
- return /not currently running|not running|cannot find|does not exist|not found|当前未运行|尚未运行|没有正在运行|找不到指定的文件|系统找不到/i.test(detail);
105
+ return /not currently running|not running|当前未运行|尚未运行|没有正在运行/i.test(detail) || isWindowsTaskNotFoundDetail(detail);
103
106
  }
104
107
  function parseWindowsTaskNumericState(status, stdout, _stderr = "") {
105
108
  if (status !== 0) return "unknown";
@@ -149,6 +152,30 @@ ${r.stderr ?? ""}`;
149
152
  return "unknown";
150
153
  }
151
154
  }
155
+ function queryWindowsServiceTaskPresence(runQuery) {
156
+ const exec = runQuery ?? ((cmd, args) => spawnSync(cmd, args, {
157
+ encoding: "utf8",
158
+ timeout: 15e3,
159
+ windowsHide: true
160
+ }));
161
+ try {
162
+ const ps = exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TASK_STATE_PS]);
163
+ if (!ps.error) {
164
+ if (ps.status !== 0) return "unknown";
165
+ const m = /^\s*STATE=(NOT_FOUND|[0-4])\s*$/im.exec(ps.stdout ?? "");
166
+ if (!m) return "unknown";
167
+ return m[1].toUpperCase() === "NOT_FOUND" ? "not-found" : "present";
168
+ }
169
+ const r = exec("schtasks", ["/Query", "/TN", "dev.pie.manager"]);
170
+ const combined = `${r.stdout ?? ""}
171
+ ${r.stderr ?? ""}`;
172
+ if (r.error) return "unknown";
173
+ if (r.status === 0) return combined.trim().length > 0 ? "present" : "unknown";
174
+ return isWindowsTaskNotFoundDetail(combined) ? "not-found" : "unknown";
175
+ } catch {
176
+ return "unknown";
177
+ }
178
+ }
152
179
  function runWindowsPreInstallStop(state, deps) {
153
180
  const checkManagerIdle = () => {
154
181
  const liveManager = deps.findManagerResident(state.sessionId);
@@ -570,8 +597,11 @@ export {
570
597
  normalizePreInstallStopOutcome,
571
598
  resolveDefaultTuiUsePidFile,
572
599
  scanBlockingWindowsPeers,
600
+ isWindowsTaskNotFoundDetail,
601
+ isWindowsTaskAlreadyStoppedDetail,
573
602
  parseWindowsTaskNumericState,
574
603
  queryWindowsServiceTaskState,
604
+ queryWindowsServiceTaskPresence,
575
605
  runWindowsPreInstallStop,
576
606
  isWindowsServiceManager,
577
607
  resolveAbsoluteActorEnv,