stim 1.14.0 → 1.16.0
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/README.md +2 -0
- package/dist/activity-BxwdD81S.mjs +609 -0
- package/dist/agent-device-usage-output-Dpih1Tfa.mjs +411 -0
- package/dist/{android-d6rGq1pA.mjs → android-B_NumVyQ.mjs} +169 -81
- package/dist/{android-LbPFRWVL.mjs → android-Ift4kVvt.mjs} +517 -413
- package/dist/android-cas-8U4DPqeR.mjs +167 -0
- package/dist/android-cas-compiler.mjs +2 -2
- package/dist/{android-XpvCrV7q.mjs → android-r2rBL8kV.mjs} +2 -2
- package/dist/{app-install-BpgSgkJj.mjs → app-install-CKWdbXIX.mjs} +128 -151
- package/dist/attempt-Bk2ouQVL.mjs +39 -0
- package/dist/budget-DjrURfQn.mjs +2700 -0
- package/dist/{build-plan-Dcr-3ie0.mjs → build-plan-DjeSb2Xl.mjs} +192 -653
- package/dist/build-slots-rUk77xqh.mjs +132 -0
- package/dist/{cache-manifest-C68QQ0ua.mjs → cache-manifest-DnUHBJaU.mjs} +2 -2
- package/dist/cache-manifest.mjs +1 -1
- package/dist/{chrome-BPCiC3ZX.mjs → chrome-BrcVWQyD.mjs} +1 -1
- package/dist/cli-BkYZ_6hy.mjs +51 -0
- package/dist/cli.mjs +6 -42
- package/dist/client-BTY686R6.mjs +1368 -0
- package/dist/collector-run.mjs +9 -195
- package/dist/{command-output-DVcpw6eE.mjs → command-output-DnJMdEY-.mjs} +1 -1
- package/dist/{config-lvc7d3C2.mjs → config-D0DbpZtM.mjs} +28 -29
- package/dist/{created-devices-CllH_8eb.mjs → created-devices-D5owjN4C.mjs} +2 -2
- package/dist/{dependency-state-DsT7aKeo.mjs → dependency-state-B6cMXZab.mjs} +2 -2
- package/dist/{deps-D9IcKqXS.mjs → deps-urbmfXig.mjs} +3 -3
- package/dist/{detached-entry-DJHoca49.mjs → detached-entry-CiTEgMR1.mjs} +1 -1
- package/dist/dev-client-CroAIjjj.mjs +43 -0
- package/dist/{device-CjuuAJjQ.mjs → device-DZQjF7H5.mjs} +8 -7
- package/dist/device-capacity-BHwxNBlu.mjs +136 -0
- package/dist/device-host-worker.d.mts +1 -0
- package/dist/device-host-worker.mjs +964 -0
- package/dist/device-ios-BadmeL2V.mjs +381 -0
- package/dist/{device-lease-5c3WrVRm.mjs → device-lease-D-hLqx1b.mjs} +43 -36
- package/dist/{device-pool-BiyDyPP-.mjs → device-lease-run-CqjShqWW.mjs} +6 -126
- package/dist/device-pool-CUaEWMMm.mjs +125 -0
- package/dist/{device-remote-D87zEzaq.mjs → device-remote-D5WVWqOq.mjs} +69 -163
- package/dist/{doctor-x9pnU9fq.mjs → doctor-Cimf-gGB.mjs} +241 -103
- package/dist/{error-diagnostics-C5HzcwCW.mjs → error-diagnostics-B9L4Ae0x.mjs} +15 -18
- package/dist/{exec-DK8KaVHK.mjs → exec-CaErVv7t.mjs} +5 -1
- package/dist/{gc-ko6mUAYD.mjs → gc-Bqy4bjEu.mjs} +599 -108
- package/dist/{android-cas-iZK3DOCr.mjs → gradle-BsO1MdsH.mjs} +8 -294
- package/dist/{guide-6R0VNFqI.mjs → guide-B_uyKTxW.mjs} +2511 -239
- package/dist/{guide-status-BZrFPIA_.mjs → guide-status-CjEZMAD4.mjs} +3 -3
- package/dist/hosted-client-a-WmqE2L.mjs +197 -0
- package/dist/hosted-ios-CIWelIqf.mjs +220 -0
- package/dist/hosted-logs-D5g041Q3.mjs +187 -0
- package/dist/hosted-macos-BSZyIb3y.mjs +135 -0
- package/dist/idle-DYVymG92.mjs +1099 -0
- package/dist/idle-shutdown-CTsDnAde.mjs +122 -0
- package/dist/in-use-DvBw0Kxo.mjs +130 -0
- package/dist/{ios-BwDPrnYQ.mjs → ios-BaInn3sW.mjs} +201 -10
- package/dist/ios-Cr1h5gnO.mjs +189 -0
- package/dist/{ios-P1f5nm2n.mjs → ios-aq3QoGI3.mjs} +1159 -633
- package/dist/{ios-device-BiOsSVzd.mjs → ios-device-Ee7sDXfp.mjs} +1 -1
- package/dist/{ios-device-DGglU3E_.mjs → ios-device-FfCN_C8p.mjs} +12 -7
- package/dist/ios-state-DS5UpYTH.mjs +48 -0
- package/dist/{launch-verify-Deg4tB3Z.mjs → launch-verify-2DBRizjo.mjs} +5 -5
- package/dist/logs-CHEVK8zD.mjs +371 -0
- package/dist/machines-BIBUdhpj.mjs +265 -0
- package/dist/macos-CSYEAFmF.mjs +473 -0
- package/dist/macos-run.d.mts +5 -0
- package/dist/macos-run.mjs +2 -0
- package/dist/maintenance-run.d.mts +4 -0
- package/dist/maintenance-run.mjs +254 -0
- package/dist/{metro-CcEo8Fl8.mjs → metro-BeK1ZPz1.mjs} +20 -120
- package/dist/metro-gateway-BJ-rxQAB.mjs +84 -0
- package/dist/{named-ports-Blg8IxOh.mjs → named-ports-Bk_YXEmE.mjs} +6 -59
- package/dist/native-run-NaBrRFtQ.mjs +147 -0
- package/dist/{native-runtime-DjBHRg5m.mjs → native-runtime-DBzRnEKS.mjs} +9 -5
- package/dist/{ndjson-CDY9IkVC.mjs → ndjson-PclOIwVY.mjs} +2 -2
- package/dist/offload-worker.d.mts +122 -0
- package/dist/offload-worker.mjs +606 -0
- package/dist/{ownership-DyYDF5ww.mjs → ownership-DiA16AsN.mjs} +3 -2
- package/dist/ownership-hCkPzGmr.mjs +571 -0
- package/dist/{page-BHUzTDFt.mjs → page-QF_Ke10s.mjs} +7 -2
- package/dist/{ports-BguS83ex.mjs → ports-R2k4Knz3.mjs} +3 -3
- package/dist/prebuild-D2fsca_Z.mjs +213 -0
- package/dist/preview-DhVbvPAZ.mjs +318 -0
- package/dist/process-identity-BmRm1qV0.mjs +12 -0
- package/dist/{project-CWlvEaeN.mjs → project-Du91Ilvc.mjs} +74 -19
- package/dist/pull-request-pxnDCQzn.mjs +322 -0
- package/dist/pull-requests.d.mts +120 -0
- package/dist/pull-requests.mjs +2 -0
- package/dist/recordings-BIXOzVnr.mjs +37 -0
- package/dist/{reload-BiniwsSZ.mjs → reload-rM9jV1fz.mjs} +109 -24
- package/dist/{remote-cache-CcR6o6lI.mjs → remote-cache-C8-V13XN.mjs} +5 -5
- package/dist/run-f4vI6EnK.mjs +119 -0
- package/dist/{server-bare-DGfgyJ5J.mjs → server-bare-CpPGmnmO.mjs} +33 -15
- package/dist/server-expo-CVqO2c35.mjs +2 -0
- package/dist/{server-expo-BVuwQ65v.mjs → server-expo-MC0rHlOC.mjs} +8 -12
- package/dist/settings-BBpMcDbD.mjs +25 -0
- package/dist/{settings-B-fsC-Om.mjs → settings-ZkDzkzvB.mjs} +22 -10
- package/dist/settings-oTSkkNrM.mjs +1439 -0
- package/dist/settings.schema.json +845 -97
- package/dist/{simslim-DrDN4WuV.mjs → simslim-B8-7AoTI.mjs} +8 -132
- package/dist/{slot-launch-D5t8EiMf.mjs → slot-launch-B8VrHxn1.mjs} +11 -8
- package/dist/{spawn-claims-Drw_o-Fb.mjs → spawn-claims-D0XfSe8u.mjs} +1 -1
- package/dist/spawn-entry-jw19m8Nl.mjs +17 -0
- package/dist/stage-CzaiwFsI.mjs +143 -0
- package/dist/start-CX8Ig-U2.mjs +2 -0
- package/dist/{start-s4RXp1wy.mjs → start-ClDfwXa4.mjs} +116 -65
- package/dist/state-3DwSQIBK.mjs +41 -0
- package/dist/state-B4PQFXMW.d.mts +12 -0
- package/dist/{state-Dk9RVXI7.mjs → state-C1jB7Q8q.mjs} +70 -8
- package/dist/{state-DHqvsbqC.mjs → state-DcW6vOd_.mjs} +7 -4
- package/dist/stats-CEZ_i5je.mjs +77 -0
- package/dist/{status-BgAuxESg.mjs → status-BuvBFeII.mjs} +118 -20
- package/dist/{status-BsPAnfOI.mjs → status-Cs7VLg9D.mjs} +542 -283
- package/dist/status-DlKvVJBE.mjs +49 -0
- package/dist/stdout-reader-C8yjre1x.mjs +23 -0
- package/dist/stim-desktop-Cnz8CPnl.mjs +63 -0
- package/dist/stim-footprint.swift +32 -0
- package/dist/{stim-installations-CINXy_su.mjs → stim-installations-QMEI32v1.mjs} +1 -1
- package/dist/stop-B0Yxtmiy.mjs +48 -0
- package/dist/{stop-BzreOWJp.mjs → stop-Bffozsac.mjs} +83 -16
- package/dist/{stop-BWIF_6BK.mjs → stop-Dt_dM16A.mjs} +2 -2
- package/dist/stop-cause-CidxIqup.mjs +97 -0
- package/dist/supervisor-run.d.mts +43 -11
- package/dist/supervisor-run.mjs +363 -24
- package/dist/support-CAP8qDUF.mjs +316 -0
- package/dist/support-D4aYJniO.mjs +201 -0
- package/dist/teardown-CL6vDs2Y.mjs +727 -0
- package/dist/{xcode-Cp5KvK9x.mjs → toolchain-DkUflduf.mjs} +364 -14
- package/dist/trigger-Bemu8ytw.mjs +65 -0
- package/dist/trigger-CXts6qt1.mjs +2 -0
- package/dist/warm-progress-CpGv3Wb6.mjs +732 -0
- package/dist/{web-BsQs1WlO.mjs → web-DWUaMp8P.mjs} +37 -21
- package/dist/web-run.mjs +310 -13
- package/dist/workspace-process-lock-BL7Q0HCO.mjs +57 -0
- package/dist/workspace-state-B8-aJ1_5.mjs +371 -0
- package/dist/workspaces-BV4pdHFz.mjs +306 -0
- package/dist/{worktree-UrQWXSeb.mjs → worktree-K-xj9Db0.mjs} +625 -256
- package/dist/worktree-jnG8Iph5.mjs +2 -0
- package/package.json +10 -5
- package/shim/bundle-response.cjs +28 -12
- package/dist/activity-CYVDcrt3.mjs +0 -356
- package/dist/budget-CGDkhvv_.mjs +0 -1745
- package/dist/build-progress-DxKpwnaS.mjs +0 -247
- package/dist/idle-DXtx3RbX.mjs +0 -191
- package/dist/in-use-DlqBDKqY.mjs +0 -249
- package/dist/logs-Civ4gbBH.mjs +0 -486
- package/dist/merge-state-ytFQCeh4.mjs +0 -262
- package/dist/server-expo-DIHDhvGg.mjs +0 -2
- package/dist/settings-D61iNOsB.mjs +0 -629
- package/dist/start-Cetfvy8l.mjs +0 -2
- package/dist/stats-CFpFGlJV.mjs +0 -62
- package/dist/stats-CX1Z8Tca.mjs +0 -368
- package/dist/stim-desktop-CXt8-Z3J.mjs +0 -40
- package/dist/stop-cause-hjGBOZTG.mjs +0 -1231
- package/dist/worktree-BVrHsYZG.mjs +0 -752
- package/dist/worktree-CHWWvm5v.mjs +0 -2
- package/dist/{metro-store-DzeWkfqW.mjs → metro-store-CDDZHtPl.mjs} +1 -1
|
@@ -0,0 +1,2700 @@
|
|
|
1
|
+
import { t as getExecutor } from "./exec-CaErVv7t.mjs";
|
|
2
|
+
import { A as directorySize, D as withConfigLock$1, F as volumeRootFor, H as projectDeviceSlots, M as isOnMountedVolume, P as measuredDirectorySize, _ as loadConfig$1, a as clearDevice, d as getConfigDir, j as formatBytes, o as clearSupervisor, p as getProject, z as deviceSlotPlatforms } from "./config-D0DbpZtM.mjs";
|
|
3
|
+
import { t as process_identity_exports } from "./process-identity-BmRm1qV0.mjs";
|
|
4
|
+
import { i as registeredCaches } from "./cache-manifest-DnUHBJaU.mjs";
|
|
5
|
+
import { l as phaseLine, o as formatLongDuration, u as plural } from "./command-output-DnJMdEY-.mjs";
|
|
6
|
+
import { l as resolveProjectMetro, r as killMetroTree } from "./metro-BeK1ZPz1.mjs";
|
|
7
|
+
import { d as sharedBuildCache, r as readWorkspaceState$1, v as workspaceDir } from "./workspace-state-B8-aJ1_5.mjs";
|
|
8
|
+
import { a as capacity, l as environmentState, u as formatSpace } from "./status-BuvBFeII.mjs";
|
|
9
|
+
import { i as recordGcResult, n as withIdleWorkspace, o as canonicalPath } from "./in-use-DvBw0Kxo.mjs";
|
|
10
|
+
import { i as createDeviceProcessTables, p as workspaceActivity } from "./activity-BxwdD81S.mjs";
|
|
11
|
+
import { h as listBuildLocks, i as listLeaseFiles, r as leaseIsExpired } from "./device-lease-D-hLqx1b.mjs";
|
|
12
|
+
import { n as listBuildSlots } from "./build-slots-rUk77xqh.mjs";
|
|
13
|
+
import { l as readPidFile, s as clearWorkspaceSupervisor } from "./state-DcW6vOd_.mjs";
|
|
14
|
+
import { C as parseSubscriberNames, D as parseWatchmanPid, E as parseWatchmanClients, T as parseWatchRoots, i as idleShutdownCandidates, n as collectOwnedDeviceActivity, o as shutDownIdleDevices, s as workspaceBuildInProgress, t as collectIdleDevices, w as parseTriggerCount } from "./idle-DYVymG92.mjs";
|
|
15
|
+
import { A as listAvds, I as ownedAvdDirectory, at as isStimOwnedSim, ct as dropParked, it as isStimOwnedAvd, pt as readParked, z as ownedAvdSerialResolver } from "./android-B_NumVyQ.mjs";
|
|
16
|
+
import { _ as parseRuntimeVersion, f as listIosDeviceTypes, u as listAllIosSims } from "./ios-BaInn3sW.mjs";
|
|
17
|
+
import { c as teardownParkedIosSim, i as teardownOwnedAvd, n as eraseParkedIosSim, o as teardownOwnedIosSim, s as teardownParkedAvd, t as eraseParkedAvd } from "./teardown-CL6vDs2Y.mjs";
|
|
18
|
+
import { n as workspaceProcessLockError, t as withWorkspaceProcessLock } from "./workspace-process-lock-BL7Q0HCO.mjs";
|
|
19
|
+
import { t as resolveSupervisorTarget } from "./ownership-hCkPzGmr.mjs";
|
|
20
|
+
import { a as collectWorkspaceOutputs, r as clearWorkspaceOutputs } from "./workspaces-BV4pdHFz.mjs";
|
|
21
|
+
import { n as supervisorError } from "./errors-B6W7FkxQ.mjs";
|
|
22
|
+
import { l as withdrawDevServerStopRequest, s as requestDevServerStop } from "./stop-cause-CidxIqup.mjs";
|
|
23
|
+
import { existsSync, readFileSync, statSync, statfsSync } from "node:fs";
|
|
24
|
+
import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
25
|
+
import { existsSync as existsSync$1, readdirSync as readdirSync$1, realpathSync as realpathSync$1, rmSync as rmSync$1, statSync as statSync$1 } from "fs";
|
|
26
|
+
import { homedir, tmpdir } from "os";
|
|
27
|
+
import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, join as join$1, relative as relative$1, resolve as resolve$1 } from "path";
|
|
28
|
+
import { METRO_NAMED_CACHE_LAYOUT, compiledHelper, configDir } from "@stim-cli/core";
|
|
29
|
+
import { MACHINE_OWNER_KINDS, buildWorkerRoot, loadConfig, settingDefinition, settingValueError } from "@stim-cli/core/state";
|
|
30
|
+
import { fileURLToPath } from "node:url";
|
|
31
|
+
import { homedir as homedir$1, platform, totalmem as totalmem$1 } from "node:os";
|
|
32
|
+
import chalk from "chalk";
|
|
33
|
+
//#region src/cache/caches.ts
|
|
34
|
+
function xcodeDerivedDataRoot() {
|
|
35
|
+
return join$1(homedir(), "Library", "Developer", "Xcode", "DerivedData");
|
|
36
|
+
}
|
|
37
|
+
function compilationCache() {
|
|
38
|
+
const dir = join$1(xcodeDerivedDataRoot(), "CompilationCache.noindex");
|
|
39
|
+
if (!existsSync$1(dir)) return null;
|
|
40
|
+
return {
|
|
41
|
+
name: "Xcode compilation cache",
|
|
42
|
+
dir,
|
|
43
|
+
prune: "atomic",
|
|
44
|
+
note: "index-backed, so it can only be emptied whole"
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function gradleBuildCache() {
|
|
48
|
+
const gradleHome = process.env.GRADLE_USER_HOME || join$1(homedir(), ".gradle");
|
|
49
|
+
const dir = resolve$1(gradleHome, "caches", "build-cache-1");
|
|
50
|
+
if (!existsSync$1(dir)) return null;
|
|
51
|
+
return {
|
|
52
|
+
name: "Gradle build cache",
|
|
53
|
+
dir,
|
|
54
|
+
prune: "report-only",
|
|
55
|
+
note: "shared with every Gradle build; report only, never pruned or emptied by Stim"
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function metroFileMaps() {
|
|
59
|
+
const root = tmpdir();
|
|
60
|
+
if (!existsSync$1(root)) return null;
|
|
61
|
+
let names;
|
|
62
|
+
try {
|
|
63
|
+
names = readdirSync$1(root).filter((n) => n.startsWith("metro-file-map-"));
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
const uid = process.getuid?.();
|
|
68
|
+
const files = [];
|
|
69
|
+
let bytes = 0;
|
|
70
|
+
for (const n of names) try {
|
|
71
|
+
const st = statSync$1(join$1(root, n));
|
|
72
|
+
if (uid !== void 0 && st.uid !== uid) continue;
|
|
73
|
+
files.push(join$1(root, n));
|
|
74
|
+
bytes += st.size;
|
|
75
|
+
} catch {}
|
|
76
|
+
if (!files.length) return null;
|
|
77
|
+
return {
|
|
78
|
+
name: "Metro file maps",
|
|
79
|
+
dir: root,
|
|
80
|
+
files,
|
|
81
|
+
bytes,
|
|
82
|
+
prune: "entries",
|
|
83
|
+
note: `${files.length} file(s), one per project root Metro has served`
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function discoverCaches() {
|
|
87
|
+
const gradle = gradleBuildCache();
|
|
88
|
+
const gradleDir = gradle ? canonicalCacheDir(gradle.dir) : null;
|
|
89
|
+
const registered = protectNestedMetroAncestors(suppressLegacyMetroAncestors(registeredCaches().map((c) => Object.assign({}, c, {
|
|
90
|
+
name: c.name ?? c.dir,
|
|
91
|
+
note: c.note ?? "registered",
|
|
92
|
+
prune: c.prune,
|
|
93
|
+
source: "registered"
|
|
94
|
+
}))));
|
|
95
|
+
const detected = [
|
|
96
|
+
compilationCache(),
|
|
97
|
+
gradle,
|
|
98
|
+
metroFileMaps()
|
|
99
|
+
].filter((c) => Boolean(c)).map((c) => Object.assign({}, c, { source: "detected" }));
|
|
100
|
+
return distinguishSharedNames(mergeCacheDescriptors([...registered, ...detected], gradleDir));
|
|
101
|
+
}
|
|
102
|
+
function distinguishSharedNames(caches) {
|
|
103
|
+
const counts = /* @__PURE__ */ new Map();
|
|
104
|
+
for (const cache of caches) counts.set(cache.name, (counts.get(cache.name) ?? 0) + 1);
|
|
105
|
+
const labelled = caches.map((cache) => (counts.get(cache.name) ?? 0) < 2 ? cache : Object.assign({}, cache, { name: `${cache.name}: ${basename$1(cache.dir) || cache.dir}` }));
|
|
106
|
+
const labels = /* @__PURE__ */ new Map();
|
|
107
|
+
for (const cache of labelled) labels.set(cache.name, (labels.get(cache.name) ?? 0) + 1);
|
|
108
|
+
return labelled.map((cache, i) => (labels.get(cache.name) ?? 0) < 2 || cache === caches[i] ? cache : Object.assign({}, cache, { name: `${caches[i].name}: ${cache.dir}` }));
|
|
109
|
+
}
|
|
110
|
+
function suppressLegacyMetroAncestors(caches) {
|
|
111
|
+
const current = caches.filter(isCurrentMetroStore);
|
|
112
|
+
return caches.filter((cache) => {
|
|
113
|
+
if (!isLegacyMetroStore(cache)) return true;
|
|
114
|
+
return !current.some((candidate) => isNamedMetroChild(cache.dir, candidate.dir));
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function protectNestedMetroAncestors(caches) {
|
|
118
|
+
const current = caches.filter(isCurrentMetroStore);
|
|
119
|
+
return caches.map((cache) => {
|
|
120
|
+
if (!isCurrentMetroStore(cache)) return cache;
|
|
121
|
+
if (!current.some((candidate) => isNamedMetroChild(cache.dir, candidate.dir))) return cache;
|
|
122
|
+
return Object.assign({}, cache, {
|
|
123
|
+
prune: "report-only",
|
|
124
|
+
note: "named Metro store is also an override parent; report only while its child is registered"
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
function isLegacyMetroStore(cache) {
|
|
129
|
+
return isMetroStore(cache) && cache.layout === void 0;
|
|
130
|
+
}
|
|
131
|
+
function isCurrentMetroStore(cache) {
|
|
132
|
+
return isMetroStore(cache) && cache.layout === METRO_NAMED_CACHE_LAYOUT;
|
|
133
|
+
}
|
|
134
|
+
function isMetroStore(cache) {
|
|
135
|
+
return cache.source === "registered" && cache.name === "Metro transform cache" && cache.prune === "entries" && cache.entriesDepth === 2;
|
|
136
|
+
}
|
|
137
|
+
function isNamedMetroChild(parent, candidate) {
|
|
138
|
+
const dir = canonicalCacheDir(parent);
|
|
139
|
+
const child = canonicalCacheDir(candidate);
|
|
140
|
+
return dirname$1(child) === dir || canonicalCacheDir(dirname$1(candidate)) === dir;
|
|
141
|
+
}
|
|
142
|
+
function mergeCacheDescriptors(caches, gradleDir) {
|
|
143
|
+
const merged = [];
|
|
144
|
+
for (const cache of caches) {
|
|
145
|
+
const descriptor = protectGradleCache(cache, gradleDir);
|
|
146
|
+
const dir = canonicalCacheDir(descriptor.dir);
|
|
147
|
+
const exact = merged.findIndex((candidate) => canonicalCacheDir(candidate.dir) === dir);
|
|
148
|
+
if (exact !== -1) {
|
|
149
|
+
const current = merged[exact];
|
|
150
|
+
if (pruneStrength(descriptor.prune) > pruneStrength(current.prune)) merged[exact] = Object.assign({}, current, {
|
|
151
|
+
prune: descriptor.prune,
|
|
152
|
+
note: descriptor.note
|
|
153
|
+
});
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
if (gradleDir && isGradleProtectedDescriptor(descriptor, gradleDir)) {
|
|
157
|
+
if (merged.some((candidate) => {
|
|
158
|
+
const candidateDir = canonicalCacheDir(candidate.dir);
|
|
159
|
+
return isGradleProtectedDescriptor(candidate, gradleDir) && cachePathContains(candidateDir, dir);
|
|
160
|
+
})) continue;
|
|
161
|
+
for (let i = merged.length - 1; i >= 0; i--) {
|
|
162
|
+
const candidate = merged[i];
|
|
163
|
+
const candidateDir = canonicalCacheDir(candidate.dir);
|
|
164
|
+
if (isGradleProtectedDescriptor(candidate, gradleDir) && cachePathContains(dir, candidateDir)) merged.splice(i, 1);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
merged.push(descriptor);
|
|
168
|
+
}
|
|
169
|
+
return merged;
|
|
170
|
+
}
|
|
171
|
+
function protectGradleCache(cache, gradleDir) {
|
|
172
|
+
if (cache.files) return cache;
|
|
173
|
+
if (!gradleDir || !cachePathsOverlap(canonicalCacheDir(cache.dir), gradleDir)) return cache;
|
|
174
|
+
return Object.assign({}, cache, {
|
|
175
|
+
prune: "report-only",
|
|
176
|
+
note: "shared with every Gradle build; report only, never pruned or emptied by Stim"
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
function isGradleProtectedDescriptor(cache, gradleDir) {
|
|
180
|
+
return cache.prune === "report-only" && cachePathsOverlap(canonicalCacheDir(cache.dir), gradleDir);
|
|
181
|
+
}
|
|
182
|
+
function pruneStrength(prune) {
|
|
183
|
+
if (prune === "report-only") return 3;
|
|
184
|
+
if (prune === "atomic") return 2;
|
|
185
|
+
return 1;
|
|
186
|
+
}
|
|
187
|
+
function cachePathsOverlap(left, right) {
|
|
188
|
+
return cachePathContains(left, right) || cachePathContains(right, left);
|
|
189
|
+
}
|
|
190
|
+
function cachePathContains(parent, child) {
|
|
191
|
+
const rel = relative$1(parent, child);
|
|
192
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute$1(rel);
|
|
193
|
+
}
|
|
194
|
+
function canonicalCacheDir(dir) {
|
|
195
|
+
try {
|
|
196
|
+
return realpathSync$1(dir);
|
|
197
|
+
} catch {
|
|
198
|
+
return resolve$1(dir);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function sizeCaches(caches) {
|
|
202
|
+
return caches.map((c) => Object.assign({}, c, { bytes: c.bytes ?? directorySize(c.dir) }));
|
|
203
|
+
}
|
|
204
|
+
function pruneCache(cache, { olderThanDays, now = Date.now() } = {}) {
|
|
205
|
+
const cutoff = now - olderThanDays * 24 * 60 * 60 * 1e3;
|
|
206
|
+
if (cache.prune === "report-only") return {
|
|
207
|
+
removed: 0,
|
|
208
|
+
bytes: 0,
|
|
209
|
+
skipped: "report-only shared cache; Stim never deletes it"
|
|
210
|
+
};
|
|
211
|
+
if (cache.prune === "atomic") return {
|
|
212
|
+
removed: 0,
|
|
213
|
+
bytes: 0,
|
|
214
|
+
skipped: "index-backed; empty it whole or not at all"
|
|
215
|
+
};
|
|
216
|
+
const entries = cache.files ?? entriesAtDepth(cache.dir, cache.entriesDepth ?? 1);
|
|
217
|
+
let removed = 0;
|
|
218
|
+
let bytes = 0;
|
|
219
|
+
let failed = 0;
|
|
220
|
+
for (const entry of entries) {
|
|
221
|
+
let used;
|
|
222
|
+
let size;
|
|
223
|
+
try {
|
|
224
|
+
const st = statSync$1(entry);
|
|
225
|
+
used = Math.max(st.atimeMs, st.mtimeMs);
|
|
226
|
+
size = st.isDirectory() ? directorySize(entry) : st.size;
|
|
227
|
+
} catch {
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (used >= cutoff) continue;
|
|
231
|
+
try {
|
|
232
|
+
rmSync$1(entry, {
|
|
233
|
+
recursive: true,
|
|
234
|
+
force: true
|
|
235
|
+
});
|
|
236
|
+
removed++;
|
|
237
|
+
bytes += size;
|
|
238
|
+
} catch {
|
|
239
|
+
failed++;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
removed,
|
|
244
|
+
bytes,
|
|
245
|
+
failed,
|
|
246
|
+
skipped: null
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function entriesAtDepth(dir, depth) {
|
|
250
|
+
let level = [dir];
|
|
251
|
+
for (let i = 0; i < depth; i++) {
|
|
252
|
+
const next = [];
|
|
253
|
+
for (const parent of level) {
|
|
254
|
+
let names;
|
|
255
|
+
try {
|
|
256
|
+
names = readdirSync$1(parent);
|
|
257
|
+
} catch {
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
for (const name of names) next.push(join$1(parent, name));
|
|
261
|
+
}
|
|
262
|
+
level = next;
|
|
263
|
+
}
|
|
264
|
+
return level;
|
|
265
|
+
}
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/footprint.ts
|
|
268
|
+
const SOURCE = "stim-footprint.swift";
|
|
269
|
+
const COMPILE_TIMEOUT_MS = 12e4;
|
|
270
|
+
const READ_TIMEOUT_MS = 5e3;
|
|
271
|
+
function helperSource() {
|
|
272
|
+
const here = fileURLToPath(import.meta.url);
|
|
273
|
+
if (basename(dirname(here)) === "src") return fileURLToPath(new URL(`../helper/${SOURCE}`, import.meta.url));
|
|
274
|
+
return join(dirname(here), SOURCE);
|
|
275
|
+
}
|
|
276
|
+
async function buildHelper() {
|
|
277
|
+
const exec = getExecutor();
|
|
278
|
+
if (!exec.runFileQuiet("xcode-select", ["-p"], { timeoutMs: READ_TIMEOUT_MS })) return null;
|
|
279
|
+
const source = helperSource();
|
|
280
|
+
try {
|
|
281
|
+
return await compiledHelper({
|
|
282
|
+
dir: join(configDir(), "helpers"),
|
|
283
|
+
name: "stim-footprint",
|
|
284
|
+
inputs: [source],
|
|
285
|
+
version: "",
|
|
286
|
+
compile: async (output) => {
|
|
287
|
+
await exec.runFileAsync("xcrun", [
|
|
288
|
+
"swiftc",
|
|
289
|
+
"-O",
|
|
290
|
+
"-swift-version",
|
|
291
|
+
"5",
|
|
292
|
+
"-o",
|
|
293
|
+
output,
|
|
294
|
+
source
|
|
295
|
+
], { timeoutMs: COMPILE_TIMEOUT_MS });
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const RETRY_BACKOFF_INITIAL_MS = 1e4;
|
|
303
|
+
const RETRY_BACKOFF_MAX_MS = 6e5;
|
|
304
|
+
let built = null;
|
|
305
|
+
let failure = null;
|
|
306
|
+
/** The `stim-footprint` helper, compiled on first use. A success is kept for the process's life; a failure retries after a doubling backoff instead of being pinned forever. */
|
|
307
|
+
function footprintHelper() {
|
|
308
|
+
const home = configDir();
|
|
309
|
+
if (built?.home === home) return built.promise;
|
|
310
|
+
if (failure?.home === home && Date.now() < failure.nextRetryAt) return Promise.resolve(null);
|
|
311
|
+
const promise = buildHelper().then((helper) => {
|
|
312
|
+
if (helper === null) {
|
|
313
|
+
const backoffMs = failure?.home === home ? Math.min(failure.backoffMs * 2, RETRY_BACKOFF_MAX_MS) : RETRY_BACKOFF_INITIAL_MS;
|
|
314
|
+
failure = {
|
|
315
|
+
home,
|
|
316
|
+
nextRetryAt: Date.now() + backoffMs,
|
|
317
|
+
backoffMs
|
|
318
|
+
};
|
|
319
|
+
if (built?.promise === promise) built = null;
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
return helper;
|
|
323
|
+
});
|
|
324
|
+
built = {
|
|
325
|
+
home,
|
|
326
|
+
promise
|
|
327
|
+
};
|
|
328
|
+
return promise;
|
|
329
|
+
}
|
|
330
|
+
/** Parses the helper's `<pid> <bytes>` lines into footprint bytes by pid. */
|
|
331
|
+
function parseFootprints(output) {
|
|
332
|
+
const footprints = /* @__PURE__ */ new Map();
|
|
333
|
+
for (const line of output.split("\n")) {
|
|
334
|
+
const match = /^(\d+) (\d+)$/.exec(line.trim());
|
|
335
|
+
if (match) footprints.set(Number(match[1]), Number(match[2]));
|
|
336
|
+
}
|
|
337
|
+
return footprints;
|
|
338
|
+
}
|
|
339
|
+
/** Every readable process's physical footprint in bytes, or null when the helper is unavailable or fails. */
|
|
340
|
+
async function readFootprints() {
|
|
341
|
+
const helper = await footprintHelper();
|
|
342
|
+
const output = helper ? getExecutor().runFileQuiet(helper, [], { timeoutMs: READ_TIMEOUT_MS }) : null;
|
|
343
|
+
return output === null ? null : parseFootprints(output);
|
|
344
|
+
}
|
|
345
|
+
//#endregion
|
|
346
|
+
//#region src/machine-usage.ts
|
|
347
|
+
const SHARED = [
|
|
348
|
+
{
|
|
349
|
+
name: "CoreSimulator services",
|
|
350
|
+
pattern: /\/CoreSimulator\.framework\/|\/Simulator\.app\/Contents\/MacOS\//
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
name: "adb server",
|
|
354
|
+
pattern: /(^|\/)adb\s.*\bfork-server\b/
|
|
355
|
+
},
|
|
356
|
+
{
|
|
357
|
+
name: "Android emulator services",
|
|
358
|
+
pattern: /\/emulator\/netsimd(\s|$)/
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: "Gradle daemon",
|
|
362
|
+
pattern: /\borg\.gradle\.launcher\.daemon\.bootstrap\.GradleDaemon\b/
|
|
363
|
+
},
|
|
364
|
+
{
|
|
365
|
+
name: "Kotlin daemon",
|
|
366
|
+
pattern: /\bKotlinCompileDaemon\b/
|
|
367
|
+
},
|
|
368
|
+
{
|
|
369
|
+
name: "Watchman",
|
|
370
|
+
pattern: /(^|\/)watchman(\s|$)/
|
|
371
|
+
}
|
|
372
|
+
];
|
|
373
|
+
const STIM_SERVER_COMMAND = /(^|[\s/])stim-server(\.mjs)?(\s|$)/;
|
|
374
|
+
const LAUNCHD_SIM = /^launchd_sim\s.*\/Devices\/([^/\s]+)\//;
|
|
375
|
+
const MAX_DEPTH = 64;
|
|
376
|
+
const EMULATOR = /(?:^|\/)(?:qemu-system-[^\s/]+|emulator)(?:\s.*)?\s(?:-avd\s+|@)(\S+)/;
|
|
377
|
+
function emulatorAvd(command) {
|
|
378
|
+
return EMULATOR.exec(command)?.[1] ?? null;
|
|
379
|
+
}
|
|
380
|
+
function workspaceOwner(kind, env, name, id) {
|
|
381
|
+
return {
|
|
382
|
+
kind,
|
|
383
|
+
name,
|
|
384
|
+
workspace: env.path,
|
|
385
|
+
id,
|
|
386
|
+
owned: true
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
function rank(owner) {
|
|
390
|
+
return MACHINE_OWNER_KINDS.indexOf(owner.kind);
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Attributes every process in `processes` to at most one owner: the owner of its nearest ancestor (itself included)
|
|
394
|
+
* that is a root. Roots are each booted simulator's `launchd_sim`, each emulator launcher and qemu process, and each
|
|
395
|
+
* workspace's verified supervisor and Metro, running build and Chrome. Only a process under none of those falls back
|
|
396
|
+
* to stim-server or a machine-wide service in `SHARED`, so a `simctl` a workspace's log collector runs stays with the
|
|
397
|
+
* workspace. An emulator counts in the workspace that records its AVD whenever its process runs, including while adb
|
|
398
|
+
* does not list it. A process with no root ancestor is left out. `footprints` holds physical footprint bytes by pid,
|
|
399
|
+
* or is null when they could not be read, and the owners' `memoryMb` then sums resident sizes. A process missing from
|
|
400
|
+
* `footprints`, another user's or one that exited between the two reads, counts its resident size.
|
|
401
|
+
*/
|
|
402
|
+
function attributeMachineUsage({ processes, footprints, environments, roots, simNames }) {
|
|
403
|
+
const owners = /* @__PURE__ */ new Map();
|
|
404
|
+
const rootOf = /* @__PURE__ */ new Map();
|
|
405
|
+
const fallbackOf = /* @__PURE__ */ new Map();
|
|
406
|
+
const claim = (pid, key, owner, into = rootOf) => {
|
|
407
|
+
if (!owners.has(key)) owners.set(key, owner);
|
|
408
|
+
into.set(pid, key);
|
|
409
|
+
};
|
|
410
|
+
const sims = /* @__PURE__ */ new Map();
|
|
411
|
+
const emulators = /* @__PURE__ */ new Map();
|
|
412
|
+
for (const env of environments) for (const device of [{
|
|
413
|
+
slot: "default",
|
|
414
|
+
ios: env.ios,
|
|
415
|
+
android: env.android
|
|
416
|
+
}, ...env.slots ?? []]) {
|
|
417
|
+
const slot = device.slot === "default" ? {} : { slot: device.slot };
|
|
418
|
+
if (device.ios?.state === "Booted") sims.set(device.ios.udid.toUpperCase(), {
|
|
419
|
+
kind: "simulator",
|
|
420
|
+
name: device.ios.name ?? device.ios.udid,
|
|
421
|
+
workspace: env.path,
|
|
422
|
+
...slot,
|
|
423
|
+
id: device.ios.udid,
|
|
424
|
+
owned: device.ios.owned
|
|
425
|
+
});
|
|
426
|
+
if (device.android?.name && !device.android.physical) emulators.set(device.android.name, {
|
|
427
|
+
kind: "emulator",
|
|
428
|
+
name: device.android.name,
|
|
429
|
+
workspace: env.path,
|
|
430
|
+
...slot,
|
|
431
|
+
id: device.android.name,
|
|
432
|
+
owned: device.android.owned
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
for (const p of processes) {
|
|
436
|
+
const shared = SHARED.find(({ pattern }) => pattern.test(p.command));
|
|
437
|
+
if (shared) {
|
|
438
|
+
const owner = {
|
|
439
|
+
kind: "shared",
|
|
440
|
+
name: shared.name,
|
|
441
|
+
workspace: null,
|
|
442
|
+
id: null,
|
|
443
|
+
owned: false
|
|
444
|
+
};
|
|
445
|
+
claim(p.pid, `shared:${shared.name}`, owner, fallbackOf);
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (STIM_SERVER_COMMAND.test(p.command)) {
|
|
449
|
+
claim(p.pid, "server", {
|
|
450
|
+
kind: "server",
|
|
451
|
+
name: "stim-server",
|
|
452
|
+
workspace: null,
|
|
453
|
+
id: null,
|
|
454
|
+
owned: false
|
|
455
|
+
}, fallbackOf);
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
const udid = LAUNCHD_SIM.exec(p.command)?.[1]?.toUpperCase();
|
|
459
|
+
if (udid) {
|
|
460
|
+
const owner = sims.get(udid) ?? {
|
|
461
|
+
kind: "simulator",
|
|
462
|
+
name: simNames[udid] ?? udid,
|
|
463
|
+
workspace: null,
|
|
464
|
+
id: udid,
|
|
465
|
+
owned: false
|
|
466
|
+
};
|
|
467
|
+
claim(p.pid, `simulator:${udid}`, owner);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
const avd = emulatorAvd(p.command);
|
|
471
|
+
if (avd) {
|
|
472
|
+
const owner = emulators.get(avd) ?? {
|
|
473
|
+
kind: "emulator",
|
|
474
|
+
name: avd,
|
|
475
|
+
workspace: null,
|
|
476
|
+
id: avd,
|
|
477
|
+
owned: false
|
|
478
|
+
};
|
|
479
|
+
claim(p.pid, `emulator:${avd}`, owner);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const present = new Set(processes.map((p) => p.pid));
|
|
483
|
+
const byPath = new Map(environments.map((env) => [env.path, env]));
|
|
484
|
+
for (const root of roots) {
|
|
485
|
+
const env = byPath.get(root.path);
|
|
486
|
+
if (!env) continue;
|
|
487
|
+
const metroPids = [root.supervisorPid, env.metro?.running ? env.metro.pid : null];
|
|
488
|
+
for (const pid of metroPids) if (pid && present.has(pid)) {
|
|
489
|
+
const port = env.metro?.port ?? null;
|
|
490
|
+
claim(pid, `metro:${env.path}`, workspaceOwner("metro", env, port ? `Metro :${port}` : "Metro", port ? String(port) : null));
|
|
491
|
+
}
|
|
492
|
+
if (root.build && present.has(root.build.pid)) {
|
|
493
|
+
const label = root.build.platform === "ios" ? "iOS build" : "Android build";
|
|
494
|
+
claim(root.build.pid, `build:${env.path}`, workspaceOwner("build", env, label, root.build.platform));
|
|
495
|
+
}
|
|
496
|
+
for (const pid of root.macosPids ?? []) if (present.has(pid)) claim(pid, `macos:${env.path}`, workspaceOwner("macos", env, env.macos?.product ?? "macOS app", null));
|
|
497
|
+
for (const pid of root.browserPids) if (present.has(pid)) claim(pid, `browser:${env.path}`, workspaceOwner("browser", env, "Chrome", null));
|
|
498
|
+
}
|
|
499
|
+
const parentOf = new Map(processes.map((p) => [p.pid, p.ppid]));
|
|
500
|
+
const totals = /* @__PURE__ */ new Map();
|
|
501
|
+
for (const p of processes) {
|
|
502
|
+
let pid = p.pid;
|
|
503
|
+
let key;
|
|
504
|
+
let fallback;
|
|
505
|
+
for (let depth = 0; pid !== void 0 && pid > 1 && depth < MAX_DEPTH; depth++) {
|
|
506
|
+
key = rootOf.get(pid);
|
|
507
|
+
if (key) break;
|
|
508
|
+
fallback ??= fallbackOf.get(pid);
|
|
509
|
+
pid = parentOf.get(pid);
|
|
510
|
+
}
|
|
511
|
+
key ??= fallback;
|
|
512
|
+
if (!key) continue;
|
|
513
|
+
const total = totals.get(key) ?? {
|
|
514
|
+
rssKb: 0,
|
|
515
|
+
memoryKb: 0,
|
|
516
|
+
cpu: 0,
|
|
517
|
+
processes: 0
|
|
518
|
+
};
|
|
519
|
+
total.rssKb += p.rssKb;
|
|
520
|
+
const footprint = footprints?.get(p.pid);
|
|
521
|
+
total.memoryKb += footprint === void 0 ? p.rssKb : footprint / 1024;
|
|
522
|
+
total.cpu += p.cpuPercent;
|
|
523
|
+
total.processes += 1;
|
|
524
|
+
totals.set(key, total);
|
|
525
|
+
}
|
|
526
|
+
const list = [];
|
|
527
|
+
for (const [key, owner] of owners) {
|
|
528
|
+
const total = totals.get(key);
|
|
529
|
+
if (total) list.push({
|
|
530
|
+
...owner,
|
|
531
|
+
cpuPercent: Math.round(total.cpu),
|
|
532
|
+
residentMb: Math.round(total.rssKb / 1024),
|
|
533
|
+
memoryMb: Math.round(total.memoryKb / 1024),
|
|
534
|
+
processes: total.processes
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
list.sort((x, y) => rank(x) - rank(y) || (x.workspace ?? "~").localeCompare(y.workspace ?? "~") || x.name.localeCompare(y.name));
|
|
538
|
+
return {
|
|
539
|
+
memorySource: footprints ? "footprint" : "rss",
|
|
540
|
+
owners: list
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
//#endregion
|
|
544
|
+
//#region src/commands/gc/progress.ts
|
|
545
|
+
function phase(label, text) {
|
|
546
|
+
console.error(chalk.dim(phaseLine(label, text)));
|
|
547
|
+
}
|
|
548
|
+
//#endregion
|
|
549
|
+
//#region src/commands/gc/memory.ts
|
|
550
|
+
const WATCHMAN_KIND = "watchman";
|
|
551
|
+
const GRADLE_DAEMONS_KIND = "gradle-daemons";
|
|
552
|
+
/** The memory kind `--cache` names, or null for any other name. */
|
|
553
|
+
function memoryCacheKind(cache) {
|
|
554
|
+
const wanted = cache?.trim().toLowerCase();
|
|
555
|
+
return wanted === "watchman" || wanted === "gradle-daemons" ? wanted : null;
|
|
556
|
+
}
|
|
557
|
+
/** Which helpers a gc run inspects: both without --cache, one for its own kind, none for any other --cache. */
|
|
558
|
+
function memoryScope(cache) {
|
|
559
|
+
if (!cache?.trim()) return {
|
|
560
|
+
watchman: true,
|
|
561
|
+
gradle: true
|
|
562
|
+
};
|
|
563
|
+
const kind = memoryCacheKind(cache);
|
|
564
|
+
return kind ? {
|
|
565
|
+
watchman: kind === WATCHMAN_KIND,
|
|
566
|
+
gradle: kind === GRADLE_DAEMONS_KIND
|
|
567
|
+
} : null;
|
|
568
|
+
}
|
|
569
|
+
const WATCHMAN_TIMEOUT_MS = 5e3;
|
|
570
|
+
const WATCHMAN_DOCTOR_BYTES = 2 * 1024 ** 3;
|
|
571
|
+
const GRADLE_STATUS_TIMEOUT_MS = 2e4;
|
|
572
|
+
const GRADLE_STOP_TIMEOUT_MS = 6e4;
|
|
573
|
+
const LSOF_TIMEOUT_MS = 1e4;
|
|
574
|
+
const ROOT_PROBES_AT_ONCE = 4;
|
|
575
|
+
const GRADLE_DAEMON_CLASS = /\borg\.gradle\.launcher\.daemon\.bootstrap\.GradleDaemon\s+(\S+)/;
|
|
576
|
+
const KOTLIN_DAEMON_CLASS = /^\S.*?\/bin\/java\s.*\sorg\.jetbrains\.kotlin\.daemon\.KotlinCompileDaemon(\s|$)/;
|
|
577
|
+
/**
|
|
578
|
+
* The Gradle version, Java home and distribution of a `GradleDaemon` process from its command line. The
|
|
579
|
+
* distribution is the directory whose `lib/` holds the daemon's main jar (`gradle-daemon-main-<v>.jar`, or
|
|
580
|
+
* `gradle-launcher-<v>.jar` before Gradle 8.13), so `<distribution>/bin/gradle` is the daemon's own launcher.
|
|
581
|
+
*/
|
|
582
|
+
function parseGradleDaemonCommand(command) {
|
|
583
|
+
const version = GRADLE_DAEMON_CLASS.exec(command)?.[1];
|
|
584
|
+
const java = /^(\/.*?)\/bin\/java\s/.exec(command)?.[1];
|
|
585
|
+
if (!version || !java) return null;
|
|
586
|
+
const jar = /(?:^|\s)-(?:cp|classpath)\s+(?:[^\s]*:)?(\/.*?\/lib\/gradle-(?:daemon-main|launcher)-[^/\s:]+\.jar)(?=[\s:])/.exec(command)?.[1];
|
|
587
|
+
return {
|
|
588
|
+
version,
|
|
589
|
+
javaHome: java,
|
|
590
|
+
distribution: jar ? dirname(dirname(jar)) : null
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
function isKotlinDaemonCommand(command) {
|
|
594
|
+
return KOTLIN_DAEMON_CLASS.test(command) && !GRADLE_DAEMON_CLASS.test(command);
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* The offload client whose Gradle home under `workerRoot` a daemon uses: named by its classpath, as stim-server
|
|
598
|
+
* matches it, or by the Gradle home it runs in.
|
|
599
|
+
*/
|
|
600
|
+
function offloadClientOf(command, workerRoot, gradleHome) {
|
|
601
|
+
const root = resolve(workerRoot).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
602
|
+
const home = new RegExp(`${root}/([^/\\s]+)/cache/gradle(/|$)`);
|
|
603
|
+
return home.exec(command)?.[1] ?? (gradleHome ? home.exec(gradleHome)?.[1] ?? null : null);
|
|
604
|
+
}
|
|
605
|
+
/** `gradle --status` rows: the state of each daemon pid it lists, lowercased (idle, busy, stopped, ...). */
|
|
606
|
+
function parseGradleStatus(output) {
|
|
607
|
+
const states = /* @__PURE__ */ new Map();
|
|
608
|
+
for (const line of output.split("\n")) {
|
|
609
|
+
const match = /^\s*(\d+)\s+([A-Z][A-Z_]*)\s+\S/.exec(line);
|
|
610
|
+
if (match) states.set(Number(match[1]), match[2].toLowerCase());
|
|
611
|
+
}
|
|
612
|
+
return states;
|
|
613
|
+
}
|
|
614
|
+
/** `lsof -F pnT` output: each pid's open file names and its ESTABLISHED TCP connections. */
|
|
615
|
+
function parseLsof(output) {
|
|
616
|
+
const processes = /* @__PURE__ */ new Map();
|
|
617
|
+
let current = null;
|
|
618
|
+
let name = null;
|
|
619
|
+
for (const line of output.split("\n")) if (line.startsWith("p")) {
|
|
620
|
+
const pid = Number(line.slice(1));
|
|
621
|
+
current = processes.get(pid) ?? {
|
|
622
|
+
files: [],
|
|
623
|
+
connections: []
|
|
624
|
+
};
|
|
625
|
+
processes.set(pid, current);
|
|
626
|
+
} else if (current && line.startsWith("n")) {
|
|
627
|
+
name = line.slice(1);
|
|
628
|
+
current.files.push(name);
|
|
629
|
+
} else if (current && name?.includes("->") && line === "TST=ESTABLISHED") current.connections.push(name);
|
|
630
|
+
return processes;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* The process at the other end of each of `pid`'s connections, found among the other processes lsof listed by the
|
|
634
|
+
* reversed `remote->local` name; null for a peer lsof did not list.
|
|
635
|
+
*/
|
|
636
|
+
function connectionPeers(pid, lsof) {
|
|
637
|
+
return (lsof.get(pid)?.connections ?? []).map((connection) => {
|
|
638
|
+
const [local, remote] = connection.split("->");
|
|
639
|
+
const reversed = `${remote}->${local}`;
|
|
640
|
+
for (const [other, entry] of lsof) if (other !== pid && entry.connections.includes(reversed)) return other;
|
|
641
|
+
return null;
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
/** The Gradle user home a daemon runs in: the one whose `daemon/<version>/daemon-<pid>.out.log` it holds open. */
|
|
645
|
+
function gradleHomeFromFiles(pid, version, files) {
|
|
646
|
+
const suffix = `/daemon/${version}/daemon-${pid}.out.log`;
|
|
647
|
+
const log = files.find((file) => file.endsWith(suffix));
|
|
648
|
+
return log ? log.slice(0, -suffix.length) : null;
|
|
649
|
+
}
|
|
650
|
+
const fsProbe = {
|
|
651
|
+
exists: existsSync,
|
|
652
|
+
isFile(path) {
|
|
653
|
+
try {
|
|
654
|
+
return statSync(path).isFile();
|
|
655
|
+
} catch {
|
|
656
|
+
return false;
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
read(path) {
|
|
660
|
+
try {
|
|
661
|
+
return readFileSync(path, "utf8");
|
|
662
|
+
} catch {
|
|
663
|
+
return null;
|
|
664
|
+
}
|
|
665
|
+
},
|
|
666
|
+
mounted: (path) => isOnMountedVolume(path)
|
|
667
|
+
};
|
|
668
|
+
/**
|
|
669
|
+
* Why a watch root is stale: its directory is gone from a mounted volume, or the nearest `.git` above it is a
|
|
670
|
+
* linked worktree's `.git` file whose gitdir no longer exists (git pruned the worktree and left the directory).
|
|
671
|
+
* Null when it is live or when that cannot be proven, such as a path on a volume that is not mounted.
|
|
672
|
+
*/
|
|
673
|
+
function watchmanRootStaleness(path, probe = fsProbe) {
|
|
674
|
+
if (!probe.exists(path)) return probe.mounted(path) ? "missing" : null;
|
|
675
|
+
for (let dir = path;; dir = dirname(dir)) {
|
|
676
|
+
const git = join(dir, ".git");
|
|
677
|
+
if (probe.exists(git)) {
|
|
678
|
+
if (!probe.isFile(git)) return null;
|
|
679
|
+
const target = /^gitdir:\s*(.+?)\s*$/m.exec(probe.read(git) ?? "")?.[1];
|
|
680
|
+
if (!target) return null;
|
|
681
|
+
const gitdir = isAbsolute(target) ? target : resolve(dir, target);
|
|
682
|
+
return probe.exists(gitdir) || !probe.mounted(gitdir) ? null : "pruned-worktree";
|
|
683
|
+
}
|
|
684
|
+
if (dirname(dir) === dir) return null;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
function staleText(stale) {
|
|
688
|
+
return stale === "missing" ? "its directory is gone" : "its linked worktree was pruned";
|
|
689
|
+
}
|
|
690
|
+
function planWatchmanRoot(root) {
|
|
691
|
+
const subscriptions = root.subscribers?.length ?? null;
|
|
692
|
+
const base = {
|
|
693
|
+
path: root.path,
|
|
694
|
+
stale: root.stale,
|
|
695
|
+
subscriptions,
|
|
696
|
+
triggers: root.triggers
|
|
697
|
+
};
|
|
698
|
+
if (root.stale === null) return {
|
|
699
|
+
...base,
|
|
700
|
+
removable: false,
|
|
701
|
+
detail: null
|
|
702
|
+
};
|
|
703
|
+
const kept = subscriptions === null ? "could not list its subscriptions" : subscriptions > 0 ? `${subscriptions} subscription(s) still use it` : root.triggers === null ? "could not list its triggers" : root.triggers > 0 ? `it has ${root.triggers} trigger(s)` : null;
|
|
704
|
+
return {
|
|
705
|
+
...base,
|
|
706
|
+
removable: kept === null,
|
|
707
|
+
detail: kept ? `${staleText(root.stale)}, but ${kept}` : staleText(root.stale)
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Decides the watchman roots gc removes and whether it may shut the daemon down. A stale root goes only while no
|
|
712
|
+
* subscription or trigger uses it. The daemon goes only when `debug-status` lists no client besides gc's own call and
|
|
713
|
+
* every root's subscriptions and triggers could be read, no kept root has a trigger, and no root has a subscription;
|
|
714
|
+
* `describeClient` names each client that keeps it.
|
|
715
|
+
*/
|
|
716
|
+
function planWatchman(facts, describeClient) {
|
|
717
|
+
const roots = (facts.roots ?? []).map(planWatchmanRoot);
|
|
718
|
+
const unreadRoots = facts.roots === null || roots.some((root) => root.subscriptions === null || root.triggers === null);
|
|
719
|
+
const triggered = roots.filter((root) => !root.removable && (root.triggers ?? 0) > 0);
|
|
720
|
+
let reason = null;
|
|
721
|
+
let detail = null;
|
|
722
|
+
if (facts.clients === null || unreadRoots) {
|
|
723
|
+
reason = "unknown";
|
|
724
|
+
detail = facts.clients === null ? "watchman debug-status did not list its clients" : "could not list the subscriptions and triggers of every root";
|
|
725
|
+
} else if (facts.clients.length > 0) {
|
|
726
|
+
reason = "in-use";
|
|
727
|
+
detail = `used by ${[...new Set(facts.clients.map(describeClient))].join(", ")}; shutting it down would break their file watching`;
|
|
728
|
+
} else if (roots.some((root) => !root.removable && (root.subscriptions ?? 0) > 0)) {
|
|
729
|
+
reason = "in-use";
|
|
730
|
+
detail = "a root still has a subscription";
|
|
731
|
+
} else if (triggered.length > 0) {
|
|
732
|
+
reason = "in-use";
|
|
733
|
+
detail = `${triggered.map((root) => root.path).join(", ")} ha${triggered.length === 1 ? "s" : "ve"} triggers that stop firing while watchman is down`;
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
process: {
|
|
737
|
+
kind: "watchman",
|
|
738
|
+
cacheKind: WATCHMAN_KIND,
|
|
739
|
+
pid: facts.pid,
|
|
740
|
+
startedAt: facts.startedAt,
|
|
741
|
+
bytes: facts.bytes,
|
|
742
|
+
measure: facts.measure,
|
|
743
|
+
version: null,
|
|
744
|
+
gradleHome: null,
|
|
745
|
+
offloadClient: null,
|
|
746
|
+
state: reason === "in-use" ? "busy" : reason === "unknown" ? "unknown" : "idle",
|
|
747
|
+
reclaimable: reason === null,
|
|
748
|
+
reason,
|
|
749
|
+
detail
|
|
750
|
+
},
|
|
751
|
+
roots
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Decides which Gradle and Kotlin daemons gc may stop. A running Stim build (`buildRunning`) keeps every one. An
|
|
756
|
+
* offload worker's daemon is left to stim-server while it runs. A Gradle daemon goes only when its own `gradle
|
|
757
|
+
* --status` says IDLE. A Kotlin daemon goes only when every Gradle daemon is idle and each of its connections comes from
|
|
758
|
+
* a Gradle daemon gc stops in the same run.
|
|
759
|
+
*/
|
|
760
|
+
function planDaemons({ gradle, kotlin, buildRunning, stimServerRunning }) {
|
|
761
|
+
const plans = [];
|
|
762
|
+
const gradleBusy = gradle.some((daemon) => !("state" in daemon.status) || daemon.status.state !== "idle");
|
|
763
|
+
for (const daemon of gradle) {
|
|
764
|
+
const state = "state" in daemon.status ? daemon.status.state : null;
|
|
765
|
+
const idle = state === "idle";
|
|
766
|
+
let reason = null;
|
|
767
|
+
let detail = null;
|
|
768
|
+
if (daemon.offloadClient !== null && stimServerRunning) {
|
|
769
|
+
reason = "stim-server";
|
|
770
|
+
detail = `stim-server stops the daemons of offload client ${daemon.offloadClient} when that client loses build or memory runs low`;
|
|
771
|
+
} else if (buildRunning) {
|
|
772
|
+
reason = "build-running";
|
|
773
|
+
detail = buildRunning;
|
|
774
|
+
} else if (state === "busy") {
|
|
775
|
+
reason = "busy";
|
|
776
|
+
detail = "a build is using it";
|
|
777
|
+
} else if (!idle) {
|
|
778
|
+
reason = "unknown";
|
|
779
|
+
detail = "unknown" in daemon.status ? daemon.status.unknown : `gradle --status reports it ${state}`;
|
|
780
|
+
}
|
|
781
|
+
plans.push({
|
|
782
|
+
kind: "gradleDaemon",
|
|
783
|
+
cacheKind: GRADLE_DAEMONS_KIND,
|
|
784
|
+
pid: daemon.pid,
|
|
785
|
+
startedAt: daemon.startedAt,
|
|
786
|
+
bytes: daemon.bytes,
|
|
787
|
+
measure: daemon.measure,
|
|
788
|
+
version: daemon.command.version,
|
|
789
|
+
gradleHome: daemon.gradleHome,
|
|
790
|
+
offloadClient: daemon.offloadClient,
|
|
791
|
+
state: idle ? "idle" : state === "busy" ? "busy" : "unknown",
|
|
792
|
+
reclaimable: reason === null,
|
|
793
|
+
reason,
|
|
794
|
+
detail
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
const stopping = new Set(plans.filter((plan) => plan.reclaimable).map((plan) => plan.pid));
|
|
798
|
+
for (const daemon of kotlin) {
|
|
799
|
+
const clients = daemon.peers?.filter((peer) => peer === null || !stopping.has(peer)) ?? [];
|
|
800
|
+
let reason = null;
|
|
801
|
+
let detail = null;
|
|
802
|
+
if (buildRunning) {
|
|
803
|
+
reason = "build-running";
|
|
804
|
+
detail = buildRunning;
|
|
805
|
+
} else if (daemon.peers === null) {
|
|
806
|
+
reason = "unknown";
|
|
807
|
+
detail = "lsof could not list its connections";
|
|
808
|
+
} else if (gradleBusy) {
|
|
809
|
+
reason = "busy";
|
|
810
|
+
detail = "a Gradle daemon is busy or its state is unknown, and it may be compiling through this one";
|
|
811
|
+
} else if (clients.length > 0) {
|
|
812
|
+
reason = "busy";
|
|
813
|
+
detail = `${clients.length} connection(s) from a process gc does not stop are open`;
|
|
814
|
+
}
|
|
815
|
+
plans.push({
|
|
816
|
+
kind: "kotlinDaemon",
|
|
817
|
+
cacheKind: GRADLE_DAEMONS_KIND,
|
|
818
|
+
pid: daemon.pid,
|
|
819
|
+
startedAt: daemon.startedAt,
|
|
820
|
+
bytes: daemon.bytes,
|
|
821
|
+
measure: daemon.measure,
|
|
822
|
+
version: null,
|
|
823
|
+
gradleHome: null,
|
|
824
|
+
offloadClient: null,
|
|
825
|
+
state: reason === null ? "idle" : reason === "unknown" ? "unknown" : "busy",
|
|
826
|
+
reclaimable: reason === null,
|
|
827
|
+
reason,
|
|
828
|
+
detail
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
return plans;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Why no Gradle or Kotlin daemon may be stopped now, or null. An Android build lock, or a build slot that no live iOS
|
|
835
|
+
* build lock of the same process holds, counts as a running build; one whose holder is unresolved counts too.
|
|
836
|
+
*/
|
|
837
|
+
function runningBuild(locks, slots) {
|
|
838
|
+
const android = locks.find((lock) => lock.platform === "android" && (lock.alive || lock.unresolved));
|
|
839
|
+
if (android) return `${android.unresolved ? "an unresolved" : "a running"} Android build holds ${android.path} (pid ${android.pid ?? "?"}, ${android.projectRoot || "unrecorded workspace"})`;
|
|
840
|
+
const ios = new Set(locks.filter((lock) => lock.platform === "ios" && lock.alive).map((lock) => lock.pid));
|
|
841
|
+
const slot = slots.find((s) => (s.alive || s.unresolved) && !(s.alive && s.pid !== null && ios.has(s.pid)));
|
|
842
|
+
if (slot) return `${slot.unresolved ? "an unresolved" : "a running"} build holds build slot ${slot.index ?? "?"} (pid ${slot.pid ?? "?"}, ${slot.projectRoot || "unrecorded workspace"})`;
|
|
843
|
+
return null;
|
|
844
|
+
}
|
|
845
|
+
/** A watchman client's pid resolved to the Stim workspace whose supervisor it is or descends from. */
|
|
846
|
+
function stimWorkspaceOf(pid, parentOf, supervisors) {
|
|
847
|
+
let current = pid;
|
|
848
|
+
for (let depth = 0; current !== void 0 && current > 1 && depth < 64; depth++) {
|
|
849
|
+
const workspace = supervisors.get(current);
|
|
850
|
+
if (workspace) return workspace;
|
|
851
|
+
current = parentOf.get(current);
|
|
852
|
+
}
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
function reclaimableBytes(report, kind) {
|
|
856
|
+
return report.processes.filter((entry) => entry.reclaimable && (kind === void 0 || entry.cacheKind === kind)).reduce((sum, entry) => sum + entry.bytes, 0);
|
|
857
|
+
}
|
|
858
|
+
const boundWatchman = async (args) => {
|
|
859
|
+
const answer = JSON.parse(await getExecutor().runFileAsync("watchman", ["--no-spawn", ...args], { timeoutMs: WATCHMAN_TIMEOUT_MS }));
|
|
860
|
+
const error = answer?.error;
|
|
861
|
+
if (error !== void 0) throw new Error(String(error));
|
|
862
|
+
return answer;
|
|
863
|
+
};
|
|
864
|
+
async function quietly(fn) {
|
|
865
|
+
try {
|
|
866
|
+
return await fn();
|
|
867
|
+
} catch {
|
|
868
|
+
return null;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* `watchman debug-status` with gc's own call left out of its clients. The call is spawned directly so its pid is
|
|
873
|
+
* known: debug-status lists the asking CLI as a client too.
|
|
874
|
+
*/
|
|
875
|
+
function watchmanClients() {
|
|
876
|
+
return new Promise((done) => {
|
|
877
|
+
let child;
|
|
878
|
+
try {
|
|
879
|
+
child = getExecutor().spawn("watchman", ["--no-spawn", "debug-status"], { stdio: [
|
|
880
|
+
"ignore",
|
|
881
|
+
"pipe",
|
|
882
|
+
"ignore"
|
|
883
|
+
] });
|
|
884
|
+
} catch {
|
|
885
|
+
done(null);
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
const self = child.pid;
|
|
889
|
+
const chunks = [];
|
|
890
|
+
const timer = setTimeout(() => child.kill("SIGTERM"), WATCHMAN_TIMEOUT_MS);
|
|
891
|
+
child.stdout?.on("data", (chunk) => chunks.push(chunk));
|
|
892
|
+
child.on("error", () => {
|
|
893
|
+
clearTimeout(timer);
|
|
894
|
+
done(null);
|
|
895
|
+
});
|
|
896
|
+
child.on("close", (status) => {
|
|
897
|
+
clearTimeout(timer);
|
|
898
|
+
let clients = null;
|
|
899
|
+
try {
|
|
900
|
+
if (status === 0 && self !== void 0) clients = parseWatchmanClients(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
901
|
+
} catch {}
|
|
902
|
+
done(clients ? clients.filter((client) => client.pid !== self) : null);
|
|
903
|
+
});
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
async function collectWatchmanRoots(pid, progress) {
|
|
907
|
+
const watchman = boundWatchman;
|
|
908
|
+
const paths = parseWatchRoots(await quietly(() => watchman(["watch-list"])));
|
|
909
|
+
if (!paths) return null;
|
|
910
|
+
if (progress) phase("daemons", `watchman pid ${pid}: checking ${plural(paths.length, "root")}`);
|
|
911
|
+
const roots = [];
|
|
912
|
+
let next = 0;
|
|
913
|
+
const probe = async () => {
|
|
914
|
+
while (next < paths.length) {
|
|
915
|
+
const index = next++;
|
|
916
|
+
const path = paths[index];
|
|
917
|
+
const [subscriptions, triggers] = await Promise.all([quietly(() => watchman(["debug-get-subscriptions", path])), quietly(() => watchman(["trigger-list", path]))]);
|
|
918
|
+
roots[index] = {
|
|
919
|
+
path,
|
|
920
|
+
stale: watchmanRootStaleness(path),
|
|
921
|
+
subscribers: parseSubscriberNames(subscriptions),
|
|
922
|
+
triggers: parseTriggerCount(triggers)
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
await Promise.all(Array.from({ length: Math.min(ROOT_PROBES_AT_ONCE, paths.length) }, probe));
|
|
927
|
+
return roots;
|
|
928
|
+
}
|
|
929
|
+
function measureOf(pid, rows, footprints) {
|
|
930
|
+
const footprint = footprints?.get(pid);
|
|
931
|
+
if (footprint !== void 0) return {
|
|
932
|
+
bytes: footprint,
|
|
933
|
+
measure: "footprint"
|
|
934
|
+
};
|
|
935
|
+
return {
|
|
936
|
+
bytes: (rows.get(pid)?.rssKb ?? 0) * 1024,
|
|
937
|
+
measure: "rss"
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
function supervisorPids() {
|
|
941
|
+
const supervisors = /* @__PURE__ */ new Map();
|
|
942
|
+
for (const root of Object.keys(loadConfig()?.projects ?? {})) {
|
|
943
|
+
const pid = readPidFile(root);
|
|
944
|
+
if (pid) supervisors.set(pid, root);
|
|
945
|
+
}
|
|
946
|
+
return supervisors;
|
|
947
|
+
}
|
|
948
|
+
async function readLsof(pids) {
|
|
949
|
+
if (pids.length === 0) return /* @__PURE__ */ new Map();
|
|
950
|
+
try {
|
|
951
|
+
return parseLsof(await getExecutor().runFileAsync("lsof", [
|
|
952
|
+
"-n",
|
|
953
|
+
"-P",
|
|
954
|
+
"-F",
|
|
955
|
+
"pnT",
|
|
956
|
+
"-p",
|
|
957
|
+
pids.join(",")
|
|
958
|
+
], { timeoutMs: LSOF_TIMEOUT_MS }));
|
|
959
|
+
} catch (error) {
|
|
960
|
+
const { status, signal: killed, stdout } = error;
|
|
961
|
+
return status === 1 && !killed && typeof stdout === "string" && stdout ? parseLsof(stdout) : null;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
async function gradleStatus(command, home) {
|
|
965
|
+
if (!command.distribution) return { unknown: "could not find its Gradle distribution on its classpath" };
|
|
966
|
+
const launcher = join(command.distribution, "bin", "gradle");
|
|
967
|
+
if (!existsSync(launcher)) return { unknown: `its distribution has no ${launcher}` };
|
|
968
|
+
try {
|
|
969
|
+
return parseGradleStatus(await getExecutor().runFileAsync(launcher, [
|
|
970
|
+
"--status",
|
|
971
|
+
"-q",
|
|
972
|
+
"-g",
|
|
973
|
+
home
|
|
974
|
+
], {
|
|
975
|
+
cwd: home,
|
|
976
|
+
env: { JAVA_HOME: command.javaHome },
|
|
977
|
+
omitEnv: ["GRADLE_OPTS", "JAVA_OPTS"],
|
|
978
|
+
timeoutMs: GRADLE_STATUS_TIMEOUT_MS
|
|
979
|
+
}));
|
|
980
|
+
} catch (error) {
|
|
981
|
+
return { unknown: `gradle --status failed: ${error.message.split("\n")[0]}` };
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
function groupKey(command, home) {
|
|
985
|
+
return JSON.stringify([
|
|
986
|
+
home,
|
|
987
|
+
command.version,
|
|
988
|
+
command.distribution,
|
|
989
|
+
command.javaHome
|
|
990
|
+
]);
|
|
991
|
+
}
|
|
992
|
+
async function collectGradleFacts(rows, byPid, footprints, stimServerRunning, progress) {
|
|
993
|
+
const gradleRows = rows.flatMap((row) => {
|
|
994
|
+
const command = parseGradleDaemonCommand(row.command);
|
|
995
|
+
return command ? [{
|
|
996
|
+
row,
|
|
997
|
+
command
|
|
998
|
+
}] : [];
|
|
999
|
+
});
|
|
1000
|
+
const kotlinRows = rows.filter((row) => isKotlinDaemonCommand(row.command));
|
|
1001
|
+
if (gradleRows.length === 0 && kotlinRows.length === 0) return {
|
|
1002
|
+
gradle: [],
|
|
1003
|
+
kotlin: []
|
|
1004
|
+
};
|
|
1005
|
+
if (progress) phase("daemons", `checking ${plural(gradleRows.length, "Gradle daemon")} and ${plural(kotlinRows.length, "Kotlin daemon")}`);
|
|
1006
|
+
const lsof = await readLsof([...gradleRows.map(({ row }) => row.pid), ...kotlinRows.map((row) => row.pid)]);
|
|
1007
|
+
const workerRoot = buildWorkerRoot();
|
|
1008
|
+
const homes = gradleRows.map(({ row, command }) => {
|
|
1009
|
+
const files = lsof?.get(row.pid)?.files;
|
|
1010
|
+
return files ? gradleHomeFromFiles(row.pid, command.version, files) : null;
|
|
1011
|
+
});
|
|
1012
|
+
const offload = gradleRows.map(({ row }, index) => offloadClientOf(row.command, workerRoot, homes[index] ?? null));
|
|
1013
|
+
const statuses = /* @__PURE__ */ new Map();
|
|
1014
|
+
gradleRows.forEach(({ command }, index) => {
|
|
1015
|
+
const home = homes[index];
|
|
1016
|
+
if (offload[index] !== null && stimServerRunning) return;
|
|
1017
|
+
if (home && !statuses.has(groupKey(command, home))) {
|
|
1018
|
+
if (progress) phase("daemons", `gradle --status for Gradle ${command.version} in ${home}`);
|
|
1019
|
+
statuses.set(groupKey(command, home), gradleStatus(command, home));
|
|
1020
|
+
}
|
|
1021
|
+
});
|
|
1022
|
+
const gradle = [];
|
|
1023
|
+
for (const [index, { row, command }] of gradleRows.entries()) {
|
|
1024
|
+
const home = homes[index] ?? null;
|
|
1025
|
+
let status;
|
|
1026
|
+
if (offload[index] !== null && stimServerRunning) status = { unknown: "stim-server manages it" };
|
|
1027
|
+
else if (!home) status = { unknown: lsof ? "could not find its Gradle user home among its open files" : "lsof failed" };
|
|
1028
|
+
else {
|
|
1029
|
+
const states = await statuses.get(groupKey(command, home));
|
|
1030
|
+
if (states instanceof Map) {
|
|
1031
|
+
const state = states.get(row.pid);
|
|
1032
|
+
status = state ? { state } : { unknown: "gradle --status did not list it" };
|
|
1033
|
+
} else status = states;
|
|
1034
|
+
}
|
|
1035
|
+
gradle.push({
|
|
1036
|
+
pid: row.pid,
|
|
1037
|
+
startedAt: row.startedAt,
|
|
1038
|
+
...measureOf(row.pid, byPid, footprints),
|
|
1039
|
+
command,
|
|
1040
|
+
gradleHome: home,
|
|
1041
|
+
offloadClient: offload[index] ?? null,
|
|
1042
|
+
status
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
return {
|
|
1046
|
+
gradle,
|
|
1047
|
+
kotlin: kotlinRows.map((row) => Object.assign(measureOf(row.pid, byPid, footprints), {
|
|
1048
|
+
pid: row.pid,
|
|
1049
|
+
startedAt: row.startedAt,
|
|
1050
|
+
peers: lsof?.get(row.pid) ? connectionPeers(row.pid, lsof) : null
|
|
1051
|
+
}))
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
async function collectWatchmanFacts(byPid, footprints, progress) {
|
|
1055
|
+
const pid = parseWatchmanPid(await quietly(() => boundWatchman(["get-pid"])));
|
|
1056
|
+
if (pid === null) return null;
|
|
1057
|
+
const roots = await collectWatchmanRoots(pid, progress);
|
|
1058
|
+
const clients = (await watchmanClients())?.filter((client) => client.pid !== pid) ?? null;
|
|
1059
|
+
return {
|
|
1060
|
+
pid,
|
|
1061
|
+
startedAt: byPid.get(pid)?.startedAt ?? null,
|
|
1062
|
+
...measureOf(pid, byPid, footprints),
|
|
1063
|
+
roots,
|
|
1064
|
+
clients
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
function watchmanClientDescriber(rows) {
|
|
1068
|
+
const parentOf = new Map(rows.map((row) => [row.pid, row.ppid]));
|
|
1069
|
+
const supervisors = supervisorPids();
|
|
1070
|
+
return (client) => {
|
|
1071
|
+
const workspace = stimWorkspaceOf(client.pid, parentOf, supervisors);
|
|
1072
|
+
return workspace ? `the Stim workspace ${workspace}` : `${client.name ?? "a client"} (pid ${client.pid})`;
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
function memorySweepIsScoped() {
|
|
1076
|
+
return Boolean(process.env.STIM_HOME);
|
|
1077
|
+
}
|
|
1078
|
+
/** The report of a run whose STIM_HOME is set: the helpers are machine-global, so none is inspected or stopped. */
|
|
1079
|
+
function scopedMemoryReport() {
|
|
1080
|
+
return {
|
|
1081
|
+
processes: [],
|
|
1082
|
+
watchmanRoots: [],
|
|
1083
|
+
notices: ["memory sweep skipped: STIM_HOME scopes this config, but watchman and the Gradle and Kotlin daemons are machine-global"]
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
async function collectMemoryReport(scope, progress = false) {
|
|
1087
|
+
const report = {
|
|
1088
|
+
processes: [],
|
|
1089
|
+
watchmanRoots: [],
|
|
1090
|
+
notices: []
|
|
1091
|
+
};
|
|
1092
|
+
if (process.platform === "win32") return report;
|
|
1093
|
+
const rows = createDeviceProcessTables().host();
|
|
1094
|
+
if (rows === null) {
|
|
1095
|
+
report.notices.push("memory sweep skipped: ps did not answer");
|
|
1096
|
+
return report;
|
|
1097
|
+
}
|
|
1098
|
+
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
1099
|
+
const footprints = await readFootprints();
|
|
1100
|
+
if (scope.watchman) {
|
|
1101
|
+
const facts = await collectWatchmanFacts(byPid, footprints, progress);
|
|
1102
|
+
if (facts) {
|
|
1103
|
+
const plan = planWatchman(facts, watchmanClientDescriber(rows));
|
|
1104
|
+
report.processes.push(plan.process);
|
|
1105
|
+
report.watchmanRoots = plan.roots;
|
|
1106
|
+
} else if (!scope.gradle) report.notices.push("no watchman daemon answered");
|
|
1107
|
+
}
|
|
1108
|
+
if (scope.gradle) {
|
|
1109
|
+
const stimServerRunning = rows.some((row) => STIM_SERVER_COMMAND.test(row.command));
|
|
1110
|
+
const facts = await collectGradleFacts(rows, byPid, footprints, stimServerRunning, progress);
|
|
1111
|
+
report.processes.push(...planDaemons({
|
|
1112
|
+
...facts,
|
|
1113
|
+
buildRunning: facts.gradle.length || facts.kotlin.length ? runningBuild(listBuildLocks(), listBuildSlots()) : null,
|
|
1114
|
+
stimServerRunning
|
|
1115
|
+
}));
|
|
1116
|
+
if (!scope.watchman && report.processes.length === 0) report.notices.push("no Gradle or Kotlin daemon is running");
|
|
1117
|
+
}
|
|
1118
|
+
return report;
|
|
1119
|
+
}
|
|
1120
|
+
function processLabel(entry) {
|
|
1121
|
+
if (entry.kind === "watchman") return `watchman pid ${entry.pid}`;
|
|
1122
|
+
if (entry.kind === "kotlinDaemon") return `Kotlin compile daemon pid ${entry.pid}`;
|
|
1123
|
+
const where = entry.offloadClient ? `offload client ${entry.offloadClient}` : entry.gradleHome ?? "unknown Gradle home";
|
|
1124
|
+
return `Gradle ${entry.version ?? "?"} daemon pid ${entry.pid} (${where})`;
|
|
1125
|
+
}
|
|
1126
|
+
function uptime(startedAt, now) {
|
|
1127
|
+
const at = startedAt ? Date.parse(startedAt) : NaN;
|
|
1128
|
+
return Number.isFinite(at) ? `up ${formatLongDuration(Math.max(0, now - at))}` : "uptime unknown";
|
|
1129
|
+
}
|
|
1130
|
+
function memoryLines(report, scoped, now = Date.now()) {
|
|
1131
|
+
if (!report || report.processes.length === 0 && report.notices.length === 0) return [];
|
|
1132
|
+
const lines = [`Memory (${report.processes.some((entry) => entry.measure === "rss") ? "footprint, resident size where unreadable" : "physical footprint"}) - shared helpers that grow while they run; only --cache watchman or gradle-daemons stops them:`];
|
|
1133
|
+
for (const entry of report.processes) {
|
|
1134
|
+
const state = entry.reclaimable ? "idle" : entry.kind === "watchman" && entry.state === "busy" ? "in use" : entry.state;
|
|
1135
|
+
lines.push(` ${processLabel(entry)} ${formatBytes(entry.bytes)}, ${uptime(entry.startedAt, now)}, ${state}`);
|
|
1136
|
+
if (entry.kind === "watchman") {
|
|
1137
|
+
const stale = report.watchmanRoots.filter((root) => root.stale !== null).length;
|
|
1138
|
+
lines.push(` ${report.watchmanRoots.length} root(s), ${stale} stale`);
|
|
1139
|
+
for (const root of report.watchmanRoots.filter((r) => r.stale !== null)) lines.push(` stale root ${root.path}: ${root.detail}${root.removable ? "" : "; kept"}`);
|
|
1140
|
+
}
|
|
1141
|
+
if (entry.detail) lines.push(` ${entry.reclaimable ? "" : "kept: "}${entry.detail}`);
|
|
1142
|
+
}
|
|
1143
|
+
for (const notice of report.notices) lines.push(` ${notice}`);
|
|
1144
|
+
const kinds = scoped ? [scoped] : [WATCHMAN_KIND, GRADLE_DAEMONS_KIND];
|
|
1145
|
+
const parts = [];
|
|
1146
|
+
for (const kind of kinds) {
|
|
1147
|
+
if (!report.processes.some((entry) => entry.cacheKind === kind)) continue;
|
|
1148
|
+
const roots = kind === "watchman" ? report.watchmanRoots.filter((root) => root.removable).length : 0;
|
|
1149
|
+
const note = roots ? ` (and ${roots} stale root(s) removed)` : "";
|
|
1150
|
+
parts.push(`${formatBytes(reclaimableBytes(report, kind))} with stim gc --delete --cache ${kind}${note}`);
|
|
1151
|
+
}
|
|
1152
|
+
if (parts.length) lines.push(` reclaimable ${formatBytes(reclaimableBytes(report))}: ${parts.join("; ")}`);
|
|
1153
|
+
return lines;
|
|
1154
|
+
}
|
|
1155
|
+
function sameProcess(entry, rows) {
|
|
1156
|
+
const row = rows?.get(entry.pid);
|
|
1157
|
+
return Boolean(row && entry.startedAt !== null && row.startedAt === entry.startedAt);
|
|
1158
|
+
}
|
|
1159
|
+
function signal(pid) {
|
|
1160
|
+
try {
|
|
1161
|
+
process.kill(pid, "SIGTERM");
|
|
1162
|
+
return null;
|
|
1163
|
+
} catch (error) {
|
|
1164
|
+
return error.code === "ESRCH" ? null : error.message;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
function keep(entry, kind, detail) {
|
|
1168
|
+
console.log(chalk.yellow(`Kept ${processLabel(entry)}: ${detail}`));
|
|
1169
|
+
recordGcResult(kind, "kept", processLabel(entry), {
|
|
1170
|
+
id: String(entry.pid),
|
|
1171
|
+
bytes: entry.bytes,
|
|
1172
|
+
detail
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
async function reclaimWatchman(before) {
|
|
1176
|
+
let failures = 0;
|
|
1177
|
+
const fresh = await collectMemoryReport({
|
|
1178
|
+
watchman: true,
|
|
1179
|
+
gradle: false
|
|
1180
|
+
}, true);
|
|
1181
|
+
const daemon = fresh.processes.find((entry) => entry.kind === "watchman");
|
|
1182
|
+
const planned = before.processes.find((entry) => entry.kind === "watchman");
|
|
1183
|
+
if (!daemon || !planned || daemon.pid !== planned.pid) {
|
|
1184
|
+
if (planned) keep(planned, "watchman", "the daemon changed or stopped since the report");
|
|
1185
|
+
return 0;
|
|
1186
|
+
}
|
|
1187
|
+
for (const root of fresh.watchmanRoots.filter((r) => r.stale !== null)) {
|
|
1188
|
+
if (!root.removable) {
|
|
1189
|
+
console.log(chalk.yellow(`Kept the watchman root ${root.path}: ${root.detail}`));
|
|
1190
|
+
recordGcResult("watchmanRoot", "kept", root.path, { detail: root.detail });
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
try {
|
|
1194
|
+
phase("daemons", `removing stale watchman root ${root.path}`);
|
|
1195
|
+
await boundWatchman(["watch-del", root.path]);
|
|
1196
|
+
console.log(chalk.green(`Removed the stale watchman root ${root.path} (${root.detail})`));
|
|
1197
|
+
recordGcResult("watchmanRoot", "done", root.path, { detail: root.detail });
|
|
1198
|
+
} catch (error) {
|
|
1199
|
+
failures++;
|
|
1200
|
+
console.log(chalk.red(`Could not remove the watchman root ${root.path}: ${error.message}`));
|
|
1201
|
+
recordGcResult("watchmanRoot", "failed", root.path, { detail: error.message });
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
const current = (await collectMemoryReport({
|
|
1205
|
+
watchman: true,
|
|
1206
|
+
gradle: false
|
|
1207
|
+
}, true)).processes.find((entry) => entry.kind === "watchman");
|
|
1208
|
+
if (!current || current.pid !== daemon.pid) return failures;
|
|
1209
|
+
if (!current.reclaimable) {
|
|
1210
|
+
keep(current, "watchman", current.detail ?? "it could not be proven unused");
|
|
1211
|
+
return failures;
|
|
1212
|
+
}
|
|
1213
|
+
try {
|
|
1214
|
+
phase("daemons", `shutting down watchman pid ${current.pid}: no client uses it`);
|
|
1215
|
+
await boundWatchman(["shutdown-server"]);
|
|
1216
|
+
console.log(chalk.green(`Shut down watchman pid ${current.pid}, freeing ${formatBytes(current.bytes)}; the next client that needs it starts it again`));
|
|
1217
|
+
recordGcResult("watchman", "done", processLabel(current), {
|
|
1218
|
+
id: String(current.pid),
|
|
1219
|
+
bytes: current.bytes
|
|
1220
|
+
});
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
failures++;
|
|
1223
|
+
console.log(chalk.red(`Could not shut down watchman pid ${current.pid}: ${error.message}`));
|
|
1224
|
+
recordGcResult("watchman", "failed", processLabel(current), {
|
|
1225
|
+
id: String(current.pid),
|
|
1226
|
+
bytes: current.bytes,
|
|
1227
|
+
detail: error.message
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
return failures;
|
|
1231
|
+
}
|
|
1232
|
+
function stopKotlin(entry, rows) {
|
|
1233
|
+
if (!sameProcess(entry, rows)) {
|
|
1234
|
+
keep(entry, "kotlinDaemon", "the process changed or exited since the check");
|
|
1235
|
+
return 0;
|
|
1236
|
+
}
|
|
1237
|
+
const error = signal(entry.pid);
|
|
1238
|
+
if (error) {
|
|
1239
|
+
console.log(chalk.red(`Could not stop ${processLabel(entry)}: ${error}`));
|
|
1240
|
+
recordGcResult("kotlinDaemon", "failed", processLabel(entry), {
|
|
1241
|
+
id: String(entry.pid),
|
|
1242
|
+
bytes: entry.bytes,
|
|
1243
|
+
detail: error
|
|
1244
|
+
});
|
|
1245
|
+
return 1;
|
|
1246
|
+
}
|
|
1247
|
+
console.log(chalk.green(`Stopped ${processLabel(entry)}, freeing ${formatBytes(entry.bytes)}`));
|
|
1248
|
+
recordGcResult("kotlinDaemon", "done", processLabel(entry), {
|
|
1249
|
+
id: String(entry.pid),
|
|
1250
|
+
bytes: entry.bytes
|
|
1251
|
+
});
|
|
1252
|
+
return 0;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Stops the Gradle daemons a fresh check still finds idle. When every daemon `gradle --status` lists for a home and
|
|
1256
|
+
* version is one of them, the daemon's own `gradle --stop` runs for that home; otherwise each idle one gets SIGTERM,
|
|
1257
|
+
* because `--stop` also stops the busy daemons of that home and version.
|
|
1258
|
+
*/
|
|
1259
|
+
async function stopGradle(idle, rows) {
|
|
1260
|
+
let failures = 0;
|
|
1261
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1262
|
+
for (const entry of idle) {
|
|
1263
|
+
const command = parseGradleDaemonCommand(rows?.get(entry.pid)?.command ?? "");
|
|
1264
|
+
if (!command || !entry.gradleHome || !sameProcess(entry, rows)) {
|
|
1265
|
+
keep(entry, "gradleDaemon", "the process changed or exited since the check");
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
const key = groupKey(command, entry.gradleHome);
|
|
1269
|
+
groups.set(key, [...groups.get(key) ?? [], entry]);
|
|
1270
|
+
}
|
|
1271
|
+
for (const [key, entries] of groups) {
|
|
1272
|
+
const [home, , distribution, javaHome] = JSON.parse(key);
|
|
1273
|
+
const command = parseGradleDaemonCommand(rows.get(entries[0].pid).command);
|
|
1274
|
+
const building = runningBuild(listBuildLocks(), listBuildSlots());
|
|
1275
|
+
if (building) {
|
|
1276
|
+
for (const entry of entries) keep(entry, "gradleDaemon", building);
|
|
1277
|
+
continue;
|
|
1278
|
+
}
|
|
1279
|
+
phase("daemons", `gradle --status for Gradle ${command.version} in ${home}`);
|
|
1280
|
+
let states = await gradleStatus(command, home);
|
|
1281
|
+
let current = hostRows();
|
|
1282
|
+
const listed = states instanceof Map ? [...states].filter(([, state]) => state !== "stopped") : [];
|
|
1283
|
+
if (distribution !== null && listed.length > 0 && listed.every(([pid, state]) => state === "idle" && entries.some((entry) => entry.pid === pid))) try {
|
|
1284
|
+
phase("daemons", `gradle --stop for Gradle ${command.version} in ${home}`);
|
|
1285
|
+
await getExecutor().runFileAsync(join(distribution, "bin", "gradle"), [
|
|
1286
|
+
"--stop",
|
|
1287
|
+
"-q",
|
|
1288
|
+
"-g",
|
|
1289
|
+
home
|
|
1290
|
+
], {
|
|
1291
|
+
cwd: home,
|
|
1292
|
+
env: { JAVA_HOME: javaHome },
|
|
1293
|
+
omitEnv: ["GRADLE_OPTS", "JAVA_OPTS"],
|
|
1294
|
+
timeoutMs: GRADLE_STOP_TIMEOUT_MS
|
|
1295
|
+
});
|
|
1296
|
+
for (const entry of entries) {
|
|
1297
|
+
console.log(chalk.green(`Stopped ${processLabel(entry)} with gradle --stop, freeing ${formatBytes(entry.bytes)}`));
|
|
1298
|
+
recordGcResult("gradleDaemon", "done", processLabel(entry), {
|
|
1299
|
+
id: String(entry.pid),
|
|
1300
|
+
bytes: entry.bytes
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
continue;
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
console.log(chalk.dim(`gradle --stop failed for ${home}; signalling each idle daemon: ${error.message.split("\n")[0]}`));
|
|
1306
|
+
states = await gradleStatus(command, home);
|
|
1307
|
+
current = hostRows();
|
|
1308
|
+
}
|
|
1309
|
+
for (const entry of entries) {
|
|
1310
|
+
const state = states instanceof Map ? states.get(entry.pid) : void 0;
|
|
1311
|
+
if (!sameProcess(entry, current)) {
|
|
1312
|
+
keep(entry, "gradleDaemon", "the process changed or exited since the check");
|
|
1313
|
+
continue;
|
|
1314
|
+
}
|
|
1315
|
+
if (state !== "idle") {
|
|
1316
|
+
keep(entry, "gradleDaemon", state ? `gradle --status now reports it ${state}` : "gradle --status no longer lists it idle");
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
const error = signal(entry.pid);
|
|
1320
|
+
if (error) {
|
|
1321
|
+
failures++;
|
|
1322
|
+
console.log(chalk.red(`Could not stop ${processLabel(entry)}: ${error}`));
|
|
1323
|
+
recordGcResult("gradleDaemon", "failed", processLabel(entry), {
|
|
1324
|
+
id: String(entry.pid),
|
|
1325
|
+
bytes: entry.bytes,
|
|
1326
|
+
detail: error
|
|
1327
|
+
});
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
console.log(chalk.green(`Stopped ${processLabel(entry)}, freeing ${formatBytes(entry.bytes)}`));
|
|
1331
|
+
recordGcResult("gradleDaemon", "done", processLabel(entry), {
|
|
1332
|
+
id: String(entry.pid),
|
|
1333
|
+
bytes: entry.bytes
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
return failures;
|
|
1338
|
+
}
|
|
1339
|
+
function stillPlanned(fresh, before, kind) {
|
|
1340
|
+
const planned = new Map(before.processes.filter((entry) => entry.kind === kind).map((entry) => [entry.pid, entry]));
|
|
1341
|
+
return fresh.processes.filter((entry) => entry.kind === kind && planned.get(entry.pid)?.startedAt === entry.startedAt);
|
|
1342
|
+
}
|
|
1343
|
+
function hostRows() {
|
|
1344
|
+
const rows = createDeviceProcessTables().host();
|
|
1345
|
+
return rows ? new Map(rows.map((row) => [row.pid, row])) : null;
|
|
1346
|
+
}
|
|
1347
|
+
const EXIT_WAIT_MS = 1e4;
|
|
1348
|
+
function alive(pid) {
|
|
1349
|
+
try {
|
|
1350
|
+
process.kill(pid, 0);
|
|
1351
|
+
return true;
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
return error.code !== "ESRCH";
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
async function waitForExit(pids) {
|
|
1357
|
+
const running = pids.filter(alive);
|
|
1358
|
+
if (running.length === 0) return;
|
|
1359
|
+
phase("daemons", `waiting up to ${EXIT_WAIT_MS / 1e3}s for ${plural(running.length, "Gradle daemon")} to exit: pid ${running.join(", ")}`);
|
|
1360
|
+
const deadline = Date.now() + EXIT_WAIT_MS;
|
|
1361
|
+
while (running.some(alive) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 200));
|
|
1362
|
+
}
|
|
1363
|
+
/** Stops the Gradle daemons first, then re-checks the Kotlin daemons, whose clients those Gradle daemons were. */
|
|
1364
|
+
async function reclaimDaemons(before) {
|
|
1365
|
+
const scope = {
|
|
1366
|
+
watchman: false,
|
|
1367
|
+
gradle: true
|
|
1368
|
+
};
|
|
1369
|
+
const gradle = stillPlanned(await collectMemoryReport(scope, true), before, "gradleDaemon");
|
|
1370
|
+
for (const entry of gradle.filter((e) => !e.reclaimable)) keep(entry, "gradleDaemon", entry.detail ?? "it could not be proven idle");
|
|
1371
|
+
const stopping = gradle.filter((entry) => entry.reclaimable);
|
|
1372
|
+
let failures = await stopGradle(stopping, hostRows());
|
|
1373
|
+
if (!before.processes.some((entry) => entry.kind === "kotlinDaemon")) return failures;
|
|
1374
|
+
await waitForExit(stopping.map((entry) => entry.pid));
|
|
1375
|
+
const kotlin = stillPlanned(await collectMemoryReport(scope, true), before, "kotlinDaemon");
|
|
1376
|
+
for (const entry of before.processes.filter((e) => e.kind === "kotlinDaemon" && e.reclaimable)) {
|
|
1377
|
+
if (kotlin.some((current) => current.pid === entry.pid) || alive(entry.pid)) continue;
|
|
1378
|
+
console.log(chalk.green(`${processLabel(entry)} exited with its Gradle daemon, freeing ${formatBytes(entry.bytes)}`));
|
|
1379
|
+
recordGcResult("kotlinDaemon", "done", processLabel(entry), {
|
|
1380
|
+
id: String(entry.pid),
|
|
1381
|
+
bytes: entry.bytes
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
const rows = hostRows();
|
|
1385
|
+
for (const entry of kotlin) if (entry.reclaimable) failures += stopKotlin(entry, rows);
|
|
1386
|
+
else keep(entry, "kotlinDaemon", entry.detail ?? "it could not be proven idle");
|
|
1387
|
+
return failures;
|
|
1388
|
+
}
|
|
1389
|
+
/** Whether `gc --delete --cache <cache>` would act on a memory kind: stop a process or remove a watchman root. */
|
|
1390
|
+
function memoryWorkPending(cache, report) {
|
|
1391
|
+
if (!memoryCacheKind(cache) || !report) return false;
|
|
1392
|
+
return reclaimableBytes(report) > 0 || report.watchmanRoots.some((root) => root.removable);
|
|
1393
|
+
}
|
|
1394
|
+
/** Acts on the one memory kind `--cache` names: never on an unscoped run or `--cache all`. */
|
|
1395
|
+
async function reclaimMemory(cache, report) {
|
|
1396
|
+
const kind = memoryCacheKind(cache);
|
|
1397
|
+
if (!kind || !report || report.processes.length === 0) return 0;
|
|
1398
|
+
return kind === "watchman" ? reclaimWatchman(report) : reclaimDaemons(report);
|
|
1399
|
+
}
|
|
1400
|
+
/** A doctor note when watchman's footprint is over 2 GiB: only a restart shrinks it, and gc says when one is safe. */
|
|
1401
|
+
function watchmanFinding(report) {
|
|
1402
|
+
const daemon = report.processes.find((entry) => entry.kind === "watchman");
|
|
1403
|
+
if (!daemon || daemon.bytes < WATCHMAN_DOCTOR_BYTES) return null;
|
|
1404
|
+
const stale = report.watchmanRoots.filter((root) => root.stale !== null).length;
|
|
1405
|
+
const state = daemon.reclaimable ? "no client uses it now" : `it is kept: ${daemon.detail}`;
|
|
1406
|
+
return {
|
|
1407
|
+
level: "note",
|
|
1408
|
+
title: `watchman uses ${formatBytes(daemon.bytes)}`,
|
|
1409
|
+
detail: `The shared watchman daemon (pid ${daemon.pid}) has a ${formatBytes(daemon.bytes)} ${daemon.measure} with ${report.watchmanRoots.length} watched root(s), ${stale} of them stale; ${state}. Removing roots stops their recrawls, but only a restart returns the memory.`,
|
|
1410
|
+
fix: "Run `stim gc --cache watchman` to see its roots and clients, then `stim gc --delete --cache watchman` once no workspace uses it."
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
async function inspectWatchmanMemory() {
|
|
1414
|
+
if (process.platform === "win32" || memorySweepIsScoped()) return null;
|
|
1415
|
+
return watchmanFinding(await collectMemoryReport({
|
|
1416
|
+
watchman: true,
|
|
1417
|
+
gradle: false
|
|
1418
|
+
}));
|
|
1419
|
+
}
|
|
1420
|
+
//#endregion
|
|
1421
|
+
//#region src/commands/gc/caches.ts
|
|
1422
|
+
const DAY_MS$1 = 864e5;
|
|
1423
|
+
function cacheSweepIsScoped() {
|
|
1424
|
+
return Boolean(process.env.STIM_HOME);
|
|
1425
|
+
}
|
|
1426
|
+
function isInsideConfigDir(dir) {
|
|
1427
|
+
const root = canonicalPath(getConfigDir());
|
|
1428
|
+
const target = canonicalPath(dir);
|
|
1429
|
+
const rel = relative$1(root, target);
|
|
1430
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute$1(rel);
|
|
1431
|
+
}
|
|
1432
|
+
function machineGlobalReason(cache) {
|
|
1433
|
+
if (!cacheSweepIsScoped()) return null;
|
|
1434
|
+
if (cache.source === "registered") return null;
|
|
1435
|
+
if (isInsideConfigDir(cache.dir)) return null;
|
|
1436
|
+
return `STIM_HOME scopes this config, but ${cache.dir} is outside it and therefore machine-global`;
|
|
1437
|
+
}
|
|
1438
|
+
const EVERY_CACHE = "all";
|
|
1439
|
+
const WORKSPACE_OUTPUTS = "workspaces";
|
|
1440
|
+
const RECORDINGS = "recordings";
|
|
1441
|
+
const PARKED_DEVICES = "parked";
|
|
1442
|
+
function includesArchives(name) {
|
|
1443
|
+
const wanted = name?.trim().toLowerCase();
|
|
1444
|
+
return Boolean(wanted && (wanted === "archived" || wanted.startsWith("archived:") || [
|
|
1445
|
+
"archived-logs",
|
|
1446
|
+
"archived-recordings",
|
|
1447
|
+
"archived-agent"
|
|
1448
|
+
].includes(wanted)));
|
|
1449
|
+
}
|
|
1450
|
+
function includesParkedDevices(name) {
|
|
1451
|
+
return name?.trim().toLowerCase() === PARKED_DEVICES;
|
|
1452
|
+
}
|
|
1453
|
+
function includesRecordings(name) {
|
|
1454
|
+
const wanted = name?.trim().toLowerCase();
|
|
1455
|
+
return !wanted || wanted === EVERY_CACHE || wanted === RECORDINGS;
|
|
1456
|
+
}
|
|
1457
|
+
function isWorkspacesScope(name) {
|
|
1458
|
+
return name?.trim().toLowerCase() === WORKSPACE_OUTPUTS;
|
|
1459
|
+
}
|
|
1460
|
+
function includesWorkspaceOutputs(name) {
|
|
1461
|
+
const wanted = name?.trim().toLowerCase();
|
|
1462
|
+
return !wanted || wanted === EVERY_CACHE || wanted === WORKSPACE_OUTPUTS;
|
|
1463
|
+
}
|
|
1464
|
+
/** Whether a --cache name selects something besides shared caches: recordings, parked devices or a memory kind. */
|
|
1465
|
+
function selectsBeyondCaches(name) {
|
|
1466
|
+
return includesArchives(name) || includesRecordings(name) || includesParkedDevices(name) || memoryCacheKind(name) !== null;
|
|
1467
|
+
}
|
|
1468
|
+
function selectCaches(caches, name) {
|
|
1469
|
+
if (!name) return caches;
|
|
1470
|
+
const wanted = name.trim().toLowerCase();
|
|
1471
|
+
if (wanted === EVERY_CACHE) return caches;
|
|
1472
|
+
if (includesArchives(wanted) || wanted === WORKSPACE_OUTPUTS || wanted === RECORDINGS || wanted === PARKED_DEVICES || memoryCacheKind(wanted)) return [];
|
|
1473
|
+
return caches.filter((c) => c.name.toLowerCase().includes(wanted) || c.dir.toLowerCase().includes(wanted));
|
|
1474
|
+
}
|
|
1475
|
+
function emptyVerdict(c) {
|
|
1476
|
+
if (c.prune === "report-only") return {
|
|
1477
|
+
willEmpty: false,
|
|
1478
|
+
emptySkipped: "report-only shared cache; Stim never deletes it"
|
|
1479
|
+
};
|
|
1480
|
+
if (c.machineGlobal) return {
|
|
1481
|
+
willEmpty: false,
|
|
1482
|
+
emptySkipped: c.machineGlobal
|
|
1483
|
+
};
|
|
1484
|
+
if (!ownsItsDirectory(c)) return {
|
|
1485
|
+
willEmpty: false,
|
|
1486
|
+
emptySkipped: `${c.dir} is not a directory this cache owns`
|
|
1487
|
+
};
|
|
1488
|
+
return {
|
|
1489
|
+
willEmpty: true,
|
|
1490
|
+
emptySkipped: null
|
|
1491
|
+
};
|
|
1492
|
+
}
|
|
1493
|
+
function planCacheEmptying(caches, all) {
|
|
1494
|
+
const annotated = caches.map((c) => Object.assign({}, c, { machineGlobal: machineGlobalReason(c) }));
|
|
1495
|
+
return all ? annotated.map((c) => Object.assign({}, c, emptyVerdict(c))) : annotated;
|
|
1496
|
+
}
|
|
1497
|
+
/** What `gc --delete --cache <name>` would do to each cache, for a report that does not run that scope. */
|
|
1498
|
+
function previewScopedEmptying(caches) {
|
|
1499
|
+
return planCacheEmptying(caches, false).map((c) => Object.assign({}, c, { scopedEmpty: emptyVerdict(c) }));
|
|
1500
|
+
}
|
|
1501
|
+
function ownsItsDirectory(cache) {
|
|
1502
|
+
if (Array.isArray(cache.files)) return false;
|
|
1503
|
+
const dir = canonicalPath(cache.dir);
|
|
1504
|
+
if (dirname$1(dir) === dir) return false;
|
|
1505
|
+
return ![
|
|
1506
|
+
homedir(),
|
|
1507
|
+
tmpdir(),
|
|
1508
|
+
getConfigDir()
|
|
1509
|
+
].map(canonicalPath).includes(dir);
|
|
1510
|
+
}
|
|
1511
|
+
function emptyCache(cache) {
|
|
1512
|
+
if (cache.prune === "report-only") return {
|
|
1513
|
+
removed: 0,
|
|
1514
|
+
bytes: 0,
|
|
1515
|
+
skipped: "report-only shared cache; Stim never deletes it"
|
|
1516
|
+
};
|
|
1517
|
+
if (cache.prune !== "atomic") return pruneCache(cache, {
|
|
1518
|
+
olderThanDays: 0,
|
|
1519
|
+
now: Date.now() + DAY_MS$1
|
|
1520
|
+
});
|
|
1521
|
+
let names;
|
|
1522
|
+
try {
|
|
1523
|
+
names = readdirSync$1(cache.dir);
|
|
1524
|
+
} catch (e) {
|
|
1525
|
+
return {
|
|
1526
|
+
removed: 0,
|
|
1527
|
+
bytes: 0,
|
|
1528
|
+
skipped: `could not read ${cache.dir}: ${e.message}`
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
let removed = 0;
|
|
1532
|
+
let failed = 0;
|
|
1533
|
+
for (const name of names) try {
|
|
1534
|
+
rmSync$1(join$1(cache.dir, name), {
|
|
1535
|
+
recursive: true,
|
|
1536
|
+
force: true
|
|
1537
|
+
});
|
|
1538
|
+
removed++;
|
|
1539
|
+
} catch {
|
|
1540
|
+
failed++;
|
|
1541
|
+
}
|
|
1542
|
+
return {
|
|
1543
|
+
removed,
|
|
1544
|
+
bytes: failed ? 0 : cache.bytes ?? 0,
|
|
1545
|
+
failed,
|
|
1546
|
+
skipped: null
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
function reportFailures(cache, failed) {
|
|
1550
|
+
if (!failed) return;
|
|
1551
|
+
const message = `${failed} entr${failed === 1 ? "y" : "ies"} in ${cache.dir} could not be removed`;
|
|
1552
|
+
console.log(chalk.red(`${cache.name}: ${message}`));
|
|
1553
|
+
recordGcResult("cache", "failed", cache.name, {
|
|
1554
|
+
id: cache.dir,
|
|
1555
|
+
detail: message
|
|
1556
|
+
});
|
|
1557
|
+
process.exitCode = 1;
|
|
1558
|
+
}
|
|
1559
|
+
function trimCaches(caches, olderThan) {
|
|
1560
|
+
let cacheBytes = 0;
|
|
1561
|
+
const trimmed = [];
|
|
1562
|
+
for (const c of caches) {
|
|
1563
|
+
if (c.machineGlobal) {
|
|
1564
|
+
console.log(chalk.yellow(`Left ${c.name} alone: ${c.machineGlobal}`));
|
|
1565
|
+
recordGcResult("cache", "kept", c.name, {
|
|
1566
|
+
id: c.dir,
|
|
1567
|
+
detail: c.machineGlobal
|
|
1568
|
+
});
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1571
|
+
const r = pruneCache(c, { olderThanDays: olderThan });
|
|
1572
|
+
if (r.skipped) {
|
|
1573
|
+
console.log(chalk.yellow(`Left ${c.name} alone: ${r.skipped}`));
|
|
1574
|
+
recordGcResult("cache", "kept", c.name, {
|
|
1575
|
+
id: c.dir,
|
|
1576
|
+
detail: r.skipped
|
|
1577
|
+
});
|
|
1578
|
+
} else if (r.removed) {
|
|
1579
|
+
cacheBytes += r.bytes;
|
|
1580
|
+
trimmed.push(c);
|
|
1581
|
+
recordGcResult("cache", "done", c.name, {
|
|
1582
|
+
id: c.dir,
|
|
1583
|
+
bytes: r.bytes
|
|
1584
|
+
});
|
|
1585
|
+
console.log(chalk.green(`Trimmed ${c.name}: ${r.removed} entr${r.removed === 1 ? "y" : "ies"} (${formatBytes(r.bytes)})`));
|
|
1586
|
+
} else if (!r.failed) console.log(chalk.dim(`${c.name}: nothing older than ${olderThan}d`));
|
|
1587
|
+
reportFailures(c, r.failed);
|
|
1588
|
+
}
|
|
1589
|
+
if (cacheBytes) console.log(chalk.dim(`Trimmed ${formatBytes(cacheBytes)} of shared cache. The next build that wanted those entries pays to rebuild them.`));
|
|
1590
|
+
return trimmed;
|
|
1591
|
+
}
|
|
1592
|
+
function emptyCaches(caches) {
|
|
1593
|
+
let cacheBytes = 0;
|
|
1594
|
+
for (const c of caches) {
|
|
1595
|
+
if (!c.willEmpty) {
|
|
1596
|
+
console.log(chalk.yellow(`Left ${c.name} alone: ${c.emptySkipped}`));
|
|
1597
|
+
recordGcResult("cache", "kept", c.name, {
|
|
1598
|
+
id: c.dir,
|
|
1599
|
+
detail: c.emptySkipped ?? null
|
|
1600
|
+
});
|
|
1601
|
+
continue;
|
|
1602
|
+
}
|
|
1603
|
+
const r = emptyCache(c);
|
|
1604
|
+
if (r.skipped) {
|
|
1605
|
+
console.log(chalk.yellow(`Left ${c.name} alone: ${r.skipped}`));
|
|
1606
|
+
recordGcResult("cache", "kept", c.name, {
|
|
1607
|
+
id: c.dir,
|
|
1608
|
+
detail: r.skipped
|
|
1609
|
+
});
|
|
1610
|
+
} else if (r.removed) {
|
|
1611
|
+
cacheBytes += r.bytes;
|
|
1612
|
+
recordGcResult("cache", "done", c.name, {
|
|
1613
|
+
id: c.dir,
|
|
1614
|
+
bytes: r.bytes
|
|
1615
|
+
});
|
|
1616
|
+
console.log(chalk.green(`Emptied ${c.name}: ${r.removed} entr${r.removed === 1 ? "y" : "ies"} (${formatBytes(r.bytes)})`));
|
|
1617
|
+
} else if (!r.failed) console.log(chalk.dim(`${c.name}: already empty`));
|
|
1618
|
+
reportFailures(c, r.failed);
|
|
1619
|
+
}
|
|
1620
|
+
if (cacheBytes) console.log(chalk.dim(`Emptied ${formatBytes(cacheBytes)} of shared cache. Every build that wanted any of it now pays to rebuild it.`));
|
|
1621
|
+
}
|
|
1622
|
+
//#endregion
|
|
1623
|
+
//#region src/commands/gc/devices.ts
|
|
1624
|
+
const DEVICE_LIST_TIMEOUT_MS$1 = 3e4;
|
|
1625
|
+
const AVD_SIZE_TIMEOUT_MS = 5e3;
|
|
1626
|
+
const DAY_MS = 864e5;
|
|
1627
|
+
function describeKept(ref) {
|
|
1628
|
+
return ref.mounted ? `referenced by ${ref.path}` : `referenced by ${ref.path} (volume not mounted; kept just in case)`;
|
|
1629
|
+
}
|
|
1630
|
+
function findOrphanedDevices({ sims = [], avds = [], config, isMounted, deadProjects = [] }) {
|
|
1631
|
+
const dead = new Set(deadProjects);
|
|
1632
|
+
const referenced = /* @__PURE__ */ new Map();
|
|
1633
|
+
for (const [path, proj] of Object.entries(config?.projects || {})) {
|
|
1634
|
+
if (dead.has(path)) continue;
|
|
1635
|
+
const mounted = isMounted ? isMounted(path) : true;
|
|
1636
|
+
for (const { platforms } of projectDeviceSlots(proj)) {
|
|
1637
|
+
const ios = platforms.ios;
|
|
1638
|
+
if (ios?.deviceUdid) referenced.set(ios.deviceUdid, {
|
|
1639
|
+
path,
|
|
1640
|
+
mounted
|
|
1641
|
+
});
|
|
1642
|
+
const android = platforms.android;
|
|
1643
|
+
if (android?.avdName) referenced.set(android.avdName, {
|
|
1644
|
+
path,
|
|
1645
|
+
mounted
|
|
1646
|
+
});
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
for (const sim of readParked("ios", { config })) referenced.set(sim.udid, {
|
|
1650
|
+
path: "the simulator pool",
|
|
1651
|
+
mounted: true
|
|
1652
|
+
});
|
|
1653
|
+
for (const avd of readParked("android", { config })) referenced.set(avd.name, {
|
|
1654
|
+
path: "the emulator pool",
|
|
1655
|
+
mounted: true
|
|
1656
|
+
});
|
|
1657
|
+
const orphaned = [];
|
|
1658
|
+
const kept = [];
|
|
1659
|
+
const unverified = [];
|
|
1660
|
+
for (const sim of sims) {
|
|
1661
|
+
if (!sim?.name?.startsWith("stim-")) continue;
|
|
1662
|
+
const ref = referenced.get(sim.udid);
|
|
1663
|
+
const device = {
|
|
1664
|
+
kind: "ios",
|
|
1665
|
+
id: sim.udid,
|
|
1666
|
+
name: sim.name
|
|
1667
|
+
};
|
|
1668
|
+
if (!ref && !isStimCreated(device)) unverified.push(device);
|
|
1669
|
+
else if (!ref) orphaned.push({
|
|
1670
|
+
...device,
|
|
1671
|
+
...simBytes(sim)
|
|
1672
|
+
});
|
|
1673
|
+
else kept.push({
|
|
1674
|
+
kind: "ios",
|
|
1675
|
+
id: sim.udid,
|
|
1676
|
+
name: sim.name,
|
|
1677
|
+
reason: describeKept(ref)
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
for (const avdName of avds) {
|
|
1681
|
+
if (!avdName?.startsWith("stim-")) continue;
|
|
1682
|
+
const ref = referenced.get(avdName);
|
|
1683
|
+
const device = {
|
|
1684
|
+
kind: "android",
|
|
1685
|
+
id: avdName,
|
|
1686
|
+
name: avdName
|
|
1687
|
+
};
|
|
1688
|
+
if (!ref && !isStimCreated(device)) unverified.push(device);
|
|
1689
|
+
else if (!ref) orphaned.push(device);
|
|
1690
|
+
else kept.push({
|
|
1691
|
+
kind: "android",
|
|
1692
|
+
id: avdName,
|
|
1693
|
+
name: avdName,
|
|
1694
|
+
reason: describeKept(ref)
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
return {
|
|
1698
|
+
orphaned,
|
|
1699
|
+
kept,
|
|
1700
|
+
unverified
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
function simBytes(sim) {
|
|
1704
|
+
return typeof sim.dataPathSize === "number" ? { bytes: sim.dataPathSize } : {};
|
|
1705
|
+
}
|
|
1706
|
+
function isStimCreated(device) {
|
|
1707
|
+
return device.kind === "ios" ? isStimOwnedSim({
|
|
1708
|
+
udid: device.id,
|
|
1709
|
+
name: device.name
|
|
1710
|
+
}) : isStimOwnedAvd(device.id);
|
|
1711
|
+
}
|
|
1712
|
+
function unverifiedDeviceCommand(device) {
|
|
1713
|
+
if (device.kind === "ios") return `xcrun simctl delete ${device.id}`;
|
|
1714
|
+
return device.directory ? `rm -rf ${JSON.stringify(device.directory)}` : `avdmanager delete avd -n ${JSON.stringify(device.id)}`;
|
|
1715
|
+
}
|
|
1716
|
+
function findStaleProjectDevices({ config, sims = [], avds = [], olderThanDays, now = Date.now(), lastTouched, deadProjects = [] }) {
|
|
1717
|
+
if (!Number.isFinite(olderThanDays) || typeof lastTouched !== "function") return [];
|
|
1718
|
+
const cutoff = now - olderThanDays * DAY_MS;
|
|
1719
|
+
const dead = new Set(deadProjects);
|
|
1720
|
+
const liveSims = new Map(sims.filter((s) => s?.name?.startsWith("stim-")).map((s) => [s.udid, s]));
|
|
1721
|
+
const liveAvds = new Set(avds.filter((a) => typeof a === "string" && a.startsWith("stim-")));
|
|
1722
|
+
const stale = [];
|
|
1723
|
+
for (const [path, proj] of Object.entries(config?.projects || {})) {
|
|
1724
|
+
if (dead.has(path) || !isAbsolute$1(path)) continue;
|
|
1725
|
+
const touched = lastTouched(path);
|
|
1726
|
+
if (!Number.isFinite(touched) || touched >= cutoff) continue;
|
|
1727
|
+
const idleDays = Math.floor((now - touched) / DAY_MS);
|
|
1728
|
+
for (const { slot, platforms } of projectDeviceSlots(proj)) {
|
|
1729
|
+
const ios = platforms.ios;
|
|
1730
|
+
const sim = ios?.owned && ios.deviceUdid ? liveSims.get(ios.deviceUdid) : void 0;
|
|
1731
|
+
if (sim) stale.push({
|
|
1732
|
+
kind: "ios",
|
|
1733
|
+
id: sim.udid,
|
|
1734
|
+
name: sim.name,
|
|
1735
|
+
project: path,
|
|
1736
|
+
...slot === "default" ? {} : { slot },
|
|
1737
|
+
idleDays,
|
|
1738
|
+
...simBytes(sim)
|
|
1739
|
+
});
|
|
1740
|
+
const android = platforms.android;
|
|
1741
|
+
if (android?.owned && android.avdName && liveAvds.has(android.avdName)) stale.push({
|
|
1742
|
+
kind: "android",
|
|
1743
|
+
id: android.avdName,
|
|
1744
|
+
name: android.avdName,
|
|
1745
|
+
project: path,
|
|
1746
|
+
idleDays,
|
|
1747
|
+
...slot === "default" ? {} : { slot }
|
|
1748
|
+
});
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
return stale;
|
|
1752
|
+
}
|
|
1753
|
+
function findStaleDeviceRecords({ config, sims = [], avds = [], deadProjects = [], simsChecked = true, avdsChecked = true }) {
|
|
1754
|
+
const dead = new Set(deadProjects);
|
|
1755
|
+
const liveSims = new Set(sims.map((s) => s?.udid).filter(Boolean));
|
|
1756
|
+
const liveAvds = new Set(avds.filter((a) => typeof a === "string"));
|
|
1757
|
+
const stale = [];
|
|
1758
|
+
for (const [path, proj] of Object.entries(config?.projects || {})) {
|
|
1759
|
+
if (dead.has(path)) continue;
|
|
1760
|
+
for (const { slot, platforms } of projectDeviceSlots(proj)) {
|
|
1761
|
+
const ios = platforms.ios;
|
|
1762
|
+
if (simsChecked && ios?.deviceUdid && !liveSims.has(ios.deviceUdid)) stale.push({
|
|
1763
|
+
kind: "ios",
|
|
1764
|
+
id: ios.deviceUdid,
|
|
1765
|
+
project: path,
|
|
1766
|
+
...slot === "default" ? {} : { slot },
|
|
1767
|
+
owned: Boolean(ios.owned)
|
|
1768
|
+
});
|
|
1769
|
+
const android = platforms.android;
|
|
1770
|
+
if (avdsChecked && android?.avdName && !liveAvds.has(android.avdName)) stale.push({
|
|
1771
|
+
kind: "android",
|
|
1772
|
+
id: android.avdName,
|
|
1773
|
+
project: path,
|
|
1774
|
+
...slot === "default" ? {} : { slot },
|
|
1775
|
+
owned: Boolean(android.owned)
|
|
1776
|
+
});
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
return stale;
|
|
1780
|
+
}
|
|
1781
|
+
function describeUnverifiableDevices(simNames = [], avdNames = [], { reason = "no Stim config found" } = {}) {
|
|
1782
|
+
const ours = [...simNames, ...avdNames].filter((n) => typeof n === "string" && n.startsWith("stim-"));
|
|
1783
|
+
if (ours.length === 0) return [`${reason}; device sweep skipped`];
|
|
1784
|
+
return [`${reason}, so ${ours.length} stim-created device(s) cannot be verified as orphaned: ${ours.join(", ")}`, "they were NOT touched. If they are stale, delete them with `xcrun simctl delete <udid>` or `avdmanager delete avd -n <name>`"];
|
|
1785
|
+
}
|
|
1786
|
+
function withAndroidAvdSizes(devices, { avdDirectory = ownedAvdDirectory, size = directorySize } = {}) {
|
|
1787
|
+
return devices.map((device) => {
|
|
1788
|
+
if (device.kind !== "android") return device;
|
|
1789
|
+
const dir = device.orphanedDirectory?.directory ?? avdDirectory(device.id);
|
|
1790
|
+
if (!dir) return device;
|
|
1791
|
+
try {
|
|
1792
|
+
const bytes = size(dir, { timeoutMs: AVD_SIZE_TIMEOUT_MS });
|
|
1793
|
+
return bytes > 0 ? {
|
|
1794
|
+
...device,
|
|
1795
|
+
bytes
|
|
1796
|
+
} : device;
|
|
1797
|
+
} catch {
|
|
1798
|
+
return device;
|
|
1799
|
+
}
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1802
|
+
function describeParkedSims(records, sims, deviceTypes, { simsChecked = true } = {}) {
|
|
1803
|
+
const listed = new Map(sims.map((sim) => [sim.udid, sim]));
|
|
1804
|
+
return records.map((record) => {
|
|
1805
|
+
const sim = listed.get(record.udid);
|
|
1806
|
+
return {
|
|
1807
|
+
udid: record.udid,
|
|
1808
|
+
name: sim?.name ?? record.name,
|
|
1809
|
+
model: deviceTypes.find((d) => d.identifier === record.deviceTypeIdentifier)?.name ?? null,
|
|
1810
|
+
runtime: sim ? parseRuntimeVersion(sim.runtime) : parseRuntimeVersion(record.runtimeIdentifier),
|
|
1811
|
+
parkedAt: record.parkedAt,
|
|
1812
|
+
app: record.bundleId ?? null,
|
|
1813
|
+
bytes: typeof sim?.dataPathSize === "number" ? sim.dataPathSize : null,
|
|
1814
|
+
listed: simsChecked ? Boolean(sim) : null
|
|
1815
|
+
};
|
|
1816
|
+
});
|
|
1817
|
+
}
|
|
1818
|
+
function parkedAtLeast(records, { olderThanDays = null, now = Date.now() }) {
|
|
1819
|
+
if (olderThanDays === null) return [...records];
|
|
1820
|
+
const cutoff = now - olderThanDays * DAY_MS;
|
|
1821
|
+
return records.filter((record) => Date.parse(record.parkedAt) <= cutoff);
|
|
1822
|
+
}
|
|
1823
|
+
function collectParkedSims(deps, age = {}) {
|
|
1824
|
+
const records = parkedAtLeast(readParked("ios"), age);
|
|
1825
|
+
if (records.length === 0) return [];
|
|
1826
|
+
let sims;
|
|
1827
|
+
let deviceTypes = [];
|
|
1828
|
+
try {
|
|
1829
|
+
sims = (deps.listAllIosSims ?? listAllIosSims)({
|
|
1830
|
+
timeoutMs: DEVICE_LIST_TIMEOUT_MS$1,
|
|
1831
|
+
includeUnavailable: true
|
|
1832
|
+
});
|
|
1833
|
+
} catch {
|
|
1834
|
+
return describeParkedSims(records, [], [], { simsChecked: false });
|
|
1835
|
+
}
|
|
1836
|
+
try {
|
|
1837
|
+
deviceTypes = (deps.listIosDeviceTypes ?? listIosDeviceTypes)();
|
|
1838
|
+
} catch {}
|
|
1839
|
+
return describeParkedSims(records, sims, deviceTypes);
|
|
1840
|
+
}
|
|
1841
|
+
function poolConfigurationDeviceProfile(configuration) {
|
|
1842
|
+
try {
|
|
1843
|
+
const entries = JSON.parse(configuration);
|
|
1844
|
+
const entry = Array.isArray(entries) ? entries.find((pair) => Array.isArray(pair) && pair[0] === "hw.device.name") : void 0;
|
|
1845
|
+
return typeof entry?.[1] === "string" ? entry[1] : null;
|
|
1846
|
+
} catch {
|
|
1847
|
+
return null;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
function collectParkedAvds(deps, age = {}) {
|
|
1851
|
+
const records = parkedAtLeast(readParked("android"), age);
|
|
1852
|
+
if (!records.length) return [];
|
|
1853
|
+
let avds = null;
|
|
1854
|
+
try {
|
|
1855
|
+
avds = (deps.listAvds ?? listAvds)();
|
|
1856
|
+
} catch {}
|
|
1857
|
+
return records.map((record) => {
|
|
1858
|
+
let bytes = null;
|
|
1859
|
+
try {
|
|
1860
|
+
const directory = (deps.avdDirectory ?? ownedAvdDirectory)(record.name);
|
|
1861
|
+
if (directory) bytes = (deps.directorySize ?? directorySize)(directory, { timeoutMs: AVD_SIZE_TIMEOUT_MS });
|
|
1862
|
+
} catch {}
|
|
1863
|
+
return {
|
|
1864
|
+
name: record.name,
|
|
1865
|
+
systemImage: record.systemImage,
|
|
1866
|
+
deviceProfile: poolConfigurationDeviceProfile(record.configuration),
|
|
1867
|
+
parkedAt: record.parkedAt,
|
|
1868
|
+
app: record.packageName ?? null,
|
|
1869
|
+
bytes,
|
|
1870
|
+
listed: avds === null ? null : avds.includes(record.name)
|
|
1871
|
+
};
|
|
1872
|
+
});
|
|
1873
|
+
}
|
|
1874
|
+
function eraseParkedDevices(sims, avds) {
|
|
1875
|
+
let failures = 0;
|
|
1876
|
+
const devices = [...sims.map((sim) => ({
|
|
1877
|
+
platform: "ios",
|
|
1878
|
+
id: sim.udid,
|
|
1879
|
+
name: sim.name,
|
|
1880
|
+
listed: sim.listed,
|
|
1881
|
+
bytes: sim.bytes
|
|
1882
|
+
})), ...avds.map((avd) => ({
|
|
1883
|
+
platform: "android",
|
|
1884
|
+
id: avd.name,
|
|
1885
|
+
name: avd.name,
|
|
1886
|
+
listed: avd.listed,
|
|
1887
|
+
bytes: avd.bytes
|
|
1888
|
+
}))];
|
|
1889
|
+
for (const device of devices) {
|
|
1890
|
+
const what = `parked ${device.platform === "ios" ? "ios sim" : "android emulator"} ${device.name}`;
|
|
1891
|
+
if (device.listed !== true) {
|
|
1892
|
+
const unverified = device.listed === null;
|
|
1893
|
+
const detail = unverified ? "Stim could not list devices to verify it; it was kept. Retry stim gc --cache parked --delete." : "it is not on this machine; stim gc --delete drops its pool record.";
|
|
1894
|
+
if (unverified) failures++;
|
|
1895
|
+
console.log((unverified ? chalk.red : chalk.dim)(`Did not erase ${what}: ${detail}`));
|
|
1896
|
+
recordGcResult("parkedDevice", unverified ? "failed" : "kept", device.name, {
|
|
1897
|
+
id: device.id,
|
|
1898
|
+
detail
|
|
1899
|
+
});
|
|
1900
|
+
continue;
|
|
1901
|
+
}
|
|
1902
|
+
const result = device.platform === "ios" ? eraseParkedIosSim(device.id, { label: device.name }) : eraseParkedAvd(device.id);
|
|
1903
|
+
if (result.status === "torn-down") {
|
|
1904
|
+
console.log(chalk.green(`Erased ${what}; it stays parked`));
|
|
1905
|
+
recordGcResult("parkedDevice", "done", device.name, {
|
|
1906
|
+
id: device.id,
|
|
1907
|
+
bytes: device.bytes
|
|
1908
|
+
});
|
|
1909
|
+
} else if (result.status === "failed") {
|
|
1910
|
+
failures++;
|
|
1911
|
+
console.log(chalk.red(`Failed to erase ${what}: ${result.reason}`));
|
|
1912
|
+
recordGcResult("parkedDevice", "failed", device.name, {
|
|
1913
|
+
id: device.id,
|
|
1914
|
+
detail: result.reason
|
|
1915
|
+
});
|
|
1916
|
+
} else console.log(chalk.dim(`Skipped ${device.name}; it is no longer parked.`));
|
|
1917
|
+
}
|
|
1918
|
+
return failures;
|
|
1919
|
+
}
|
|
1920
|
+
function deleteParkedAvds(avds) {
|
|
1921
|
+
let failures = 0;
|
|
1922
|
+
for (const avd of avds) {
|
|
1923
|
+
if (avd.listed === null) {
|
|
1924
|
+
failures++;
|
|
1925
|
+
console.log(chalk.red(`Could not verify parked android emulator ${avd.name}; its pool record was kept.`));
|
|
1926
|
+
recordGcResult("parkedDevice", "failed", avd.name, {
|
|
1927
|
+
id: avd.name,
|
|
1928
|
+
detail: "Stim could not list emulators to verify it; its pool record was kept. Retry stim gc --delete."
|
|
1929
|
+
});
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
const result = teardownParkedAvd(avd.name);
|
|
1933
|
+
if (result.status === "failed") {
|
|
1934
|
+
failures++;
|
|
1935
|
+
console.log(chalk.red(`Failed to delete parked android emulator ${avd.name}: ${result.reason}`));
|
|
1936
|
+
recordGcResult("parkedDevice", "failed", avd.name, {
|
|
1937
|
+
id: avd.name,
|
|
1938
|
+
detail: result.reason
|
|
1939
|
+
});
|
|
1940
|
+
} else if (result.status === "torn-down") {
|
|
1941
|
+
console.log(chalk.green(`Deleted parked android emulator ${avd.name}`));
|
|
1942
|
+
recordGcResult("parkedDevice", "done", avd.name, {
|
|
1943
|
+
id: avd.name,
|
|
1944
|
+
bytes: avd.bytes
|
|
1945
|
+
});
|
|
1946
|
+
} else console.log(chalk.dim(`Skipped ${avd.name}; it is no longer parked.`));
|
|
1947
|
+
}
|
|
1948
|
+
return failures;
|
|
1949
|
+
}
|
|
1950
|
+
function deleteParkedSims(parkedSims, deps = {}) {
|
|
1951
|
+
let failures = 0;
|
|
1952
|
+
let emptied = 0;
|
|
1953
|
+
for (const sim of parkedSims) {
|
|
1954
|
+
if (sim.listed === null) {
|
|
1955
|
+
failures++;
|
|
1956
|
+
console.log(chalk.red(`Could not verify parked ios sim ${sim.name} (${sim.udid}); its pool record was kept.`));
|
|
1957
|
+
recordGcResult("parkedDevice", "failed", sim.name, {
|
|
1958
|
+
id: sim.udid,
|
|
1959
|
+
detail: "Stim could not list simulators to verify it; its pool record was kept. Retry stim gc --delete."
|
|
1960
|
+
});
|
|
1961
|
+
continue;
|
|
1962
|
+
}
|
|
1963
|
+
try {
|
|
1964
|
+
const teardown = sim.listed ? teardownParkedIosSim(sim.udid, {
|
|
1965
|
+
label: sim.name,
|
|
1966
|
+
deleteSim: deps.deleteParkedIosSim
|
|
1967
|
+
}) : null;
|
|
1968
|
+
if (!(sim.listed ? teardown?.status === "torn-down" : dropParked("ios", sim.udid))) {
|
|
1969
|
+
if (teardown?.status === "failed") {
|
|
1970
|
+
failures++;
|
|
1971
|
+
console.log(chalk.red(`Failed to delete parked ios sim ${sim.name}: ${teardown.reason}`));
|
|
1972
|
+
recordGcResult("parkedDevice", "failed", sim.name, {
|
|
1973
|
+
id: sim.udid,
|
|
1974
|
+
detail: teardown.reason
|
|
1975
|
+
});
|
|
1976
|
+
} else console.log(chalk.dim(`Skipped ${sim.name} (${sim.udid}); it is no longer parked.`));
|
|
1977
|
+
continue;
|
|
1978
|
+
}
|
|
1979
|
+
emptied++;
|
|
1980
|
+
recordGcResult("parkedDevice", "done", sim.name, {
|
|
1981
|
+
id: sim.udid,
|
|
1982
|
+
bytes: sim.listed ? sim.bytes : null
|
|
1983
|
+
});
|
|
1984
|
+
console.log(chalk.green(sim.listed ? `Deleted parked ios sim ${sim.name} (${sim.udid})` : `Dropped the parked record for ${sim.name} (${sim.udid}); it is not on this machine.`));
|
|
1985
|
+
} catch (err) {
|
|
1986
|
+
failures++;
|
|
1987
|
+
console.log(chalk.red(`Failed to delete parked ios sim ${sim.name}: ${err?.message || err}`));
|
|
1988
|
+
recordGcResult("parkedDevice", "failed", sim.name, {
|
|
1989
|
+
id: sim.udid,
|
|
1990
|
+
detail: err?.message || String(err)
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
if (emptied) console.log(chalk.dim(` emptied ${plural(emptied, "parked simulator")} from the pool`));
|
|
1995
|
+
return failures;
|
|
1996
|
+
}
|
|
1997
|
+
function deviceSweepIsScoped() {
|
|
1998
|
+
return Boolean(process.env.STIM_HOME);
|
|
1999
|
+
}
|
|
2000
|
+
function collectDeviceLeases(now) {
|
|
2001
|
+
const expired = [];
|
|
2002
|
+
const kept = [];
|
|
2003
|
+
for (const entry of listLeaseFiles()) {
|
|
2004
|
+
const lease = entry.lease;
|
|
2005
|
+
if (!lease) {
|
|
2006
|
+
kept.push({
|
|
2007
|
+
name: entry.name,
|
|
2008
|
+
path: entry.path,
|
|
2009
|
+
reason: "it does not parse as a lease, so no run may take that device"
|
|
2010
|
+
});
|
|
2011
|
+
continue;
|
|
2012
|
+
}
|
|
2013
|
+
if (leaseIsExpired(lease, now)) {
|
|
2014
|
+
expired.push(entry);
|
|
2015
|
+
continue;
|
|
2016
|
+
}
|
|
2017
|
+
if (!existsSync$1(lease.holder)) kept.push({
|
|
2018
|
+
name: entry.name,
|
|
2019
|
+
path: entry.path,
|
|
2020
|
+
reason: `${lease.holder} is not on this machine, but the lease runs until ${lease.expiresAt}`
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
return {
|
|
2024
|
+
expired,
|
|
2025
|
+
kept
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
function deleteProjectDevices(orphanedDevices, staleDevices, staleDeviceRecords) {
|
|
2029
|
+
let deleteFailures = 0;
|
|
2030
|
+
function reap(d, onlyIfMissing = false) {
|
|
2031
|
+
const r = d.kind === "ios" ? teardownOwnedIosSim(d.id, {
|
|
2032
|
+
del: true,
|
|
2033
|
+
label: d.name
|
|
2034
|
+
}) : teardownOwnedAvd(d.name, {
|
|
2035
|
+
del: true,
|
|
2036
|
+
onlyIfMissing,
|
|
2037
|
+
..."project" in d ? { owner: {
|
|
2038
|
+
projectPath: d.project,
|
|
2039
|
+
slot: d.slot
|
|
2040
|
+
} } : {},
|
|
2041
|
+
..."project" in d ? { onRemoved: () => {
|
|
2042
|
+
if (clearDevice(d.project, d.kind, d.slot, d.id)) console.log(chalk.dim(` cleared the ${d.kind} record for ${d.project}`));
|
|
2043
|
+
} } : {},
|
|
2044
|
+
..."orphanedDirectory" in d ? { orphanedDirectory: d.orphanedDirectory } : {}
|
|
2045
|
+
});
|
|
2046
|
+
const what = d.kind === "ios" ? `ios sim ${d.name} (${d.id})` : `android avd ${d.name}`;
|
|
2047
|
+
const result = {
|
|
2048
|
+
id: d.id,
|
|
2049
|
+
bytes: d.bytes ?? null
|
|
2050
|
+
};
|
|
2051
|
+
if (r.status === "torn-down") {
|
|
2052
|
+
console.log(chalk.green(`Deleted ${what}`));
|
|
2053
|
+
recordGcResult("device", "done", d.name, result);
|
|
2054
|
+
} else if (r.status === "missing") console.log(chalk.dim(`${what} is already gone; nothing to delete.`));
|
|
2055
|
+
else if (r.status === "skipped") {
|
|
2056
|
+
console.log(chalk.yellow(`Skipped ${what}: ${r.reason} -- left for a later gc`));
|
|
2057
|
+
recordGcResult("device", "kept", d.name, {
|
|
2058
|
+
...result,
|
|
2059
|
+
detail: `${r.reason}; left for a later gc`
|
|
2060
|
+
});
|
|
2061
|
+
} else {
|
|
2062
|
+
deleteFailures++;
|
|
2063
|
+
console.log(chalk.red(`Failed to delete ${d.kind} device ${d.name}: ${r.reason}`));
|
|
2064
|
+
recordGcResult("device", "failed", d.name, {
|
|
2065
|
+
...result,
|
|
2066
|
+
detail: r.reason
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
return r.status;
|
|
2070
|
+
}
|
|
2071
|
+
for (const d of orphanedDevices) reap(d);
|
|
2072
|
+
for (const d of staleDevices) {
|
|
2073
|
+
const status = reap(d);
|
|
2074
|
+
if (d.kind === "ios" && (status === "torn-down" || status === "missing")) {
|
|
2075
|
+
clearDevice(d.project, d.kind, d.slot, d.id);
|
|
2076
|
+
console.log(chalk.dim(` cleared the ${d.kind} record for ${d.project}`));
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
for (const r of staleDeviceRecords) if (r.kind === "android" && r.owned) reap({
|
|
2080
|
+
...r,
|
|
2081
|
+
name: r.id,
|
|
2082
|
+
idleDays: 0
|
|
2083
|
+
}, true);
|
|
2084
|
+
else if (withConfigLock$1(() => {
|
|
2085
|
+
if (r.kind === "android" && deviceSlotPlatforms(getProject(r.project), r.slot)?.android?.owned) return false;
|
|
2086
|
+
return clearDevice(r.project, r.kind, r.slot, r.id);
|
|
2087
|
+
})) {
|
|
2088
|
+
console.log(chalk.green(`Cleared the ${r.kind} record for ${r.project} (${r.id} is not on this machine)`));
|
|
2089
|
+
recordGcResult("deviceRecord", "done", r.project, { id: r.id });
|
|
2090
|
+
}
|
|
2091
|
+
return deleteFailures;
|
|
2092
|
+
}
|
|
2093
|
+
//#endregion
|
|
2094
|
+
//#region src/supervisor/cache-reset.ts
|
|
2095
|
+
async function stopOwnedMetro(root, requester) {
|
|
2096
|
+
const project = getProject(root);
|
|
2097
|
+
const port = project?.metroPort;
|
|
2098
|
+
const target = resolveSupervisorTarget({
|
|
2099
|
+
state: readWorkspaceState$1(root)?.supervisor,
|
|
2100
|
+
record: project?.supervisor,
|
|
2101
|
+
reservedPort: port
|
|
2102
|
+
});
|
|
2103
|
+
if (target.status === "unverified") return {
|
|
2104
|
+
status: "unverified",
|
|
2105
|
+
reason: target.reason ?? "unknown identity"
|
|
2106
|
+
};
|
|
2107
|
+
if (port && target.status !== "ours" && !(await resolveProjectMetro(port, root)).missing) return {
|
|
2108
|
+
status: "external",
|
|
2109
|
+
reason: `a dev server Stim did not start answers on port ${port}`
|
|
2110
|
+
};
|
|
2111
|
+
if (target.status !== "ours") return { status: "not-running" };
|
|
2112
|
+
const expected = {
|
|
2113
|
+
pid: target.pid,
|
|
2114
|
+
processToken: target.processToken
|
|
2115
|
+
};
|
|
2116
|
+
requestDevServerStop(root, target.processToken, requester);
|
|
2117
|
+
const signalled = killMetroTree(target.pid, target.processToken);
|
|
2118
|
+
if (!signalled) withdrawDevServerStopRequest(root, target.processToken);
|
|
2119
|
+
if (!signalled || !await (0, process_identity_exports.waitForProcessExit)(expected, 1e4)) return {
|
|
2120
|
+
status: "stuck",
|
|
2121
|
+
reason: `supervisor pid ${target.pid} did not exit`
|
|
2122
|
+
};
|
|
2123
|
+
if (port && !(await resolveProjectMetro(port, root)).missing) return {
|
|
2124
|
+
status: "port-occupied",
|
|
2125
|
+
reason: `port ${port} is still occupied after stopping Metro`
|
|
2126
|
+
};
|
|
2127
|
+
clearWorkspaceSupervisor(root, expected);
|
|
2128
|
+
clearSupervisor(root, expected);
|
|
2129
|
+
return { status: "stopped" };
|
|
2130
|
+
}
|
|
2131
|
+
async function stopOwnedMetroForReset(root) {
|
|
2132
|
+
const stopped = await stopOwnedMetro(root, { by: "stim start --reset-cache" });
|
|
2133
|
+
switch (stopped.status) {
|
|
2134
|
+
case "unverified": throw supervisorError("STIM_SUPERVISOR_EXITED", `Cannot reset Metro: ${stopped.reason}.`, "Stop it with the tool that started it, then retry. Stim leaves unverified processes alone.");
|
|
2135
|
+
case "external": throw supervisorError("STIM_SUPERVISOR_EXITED", "Cannot reset an externally started dev server.", "Stop it with the tool that started it, then retry `stim start --reset-cache`.");
|
|
2136
|
+
case "stuck": throw supervisorError("STIM_SUPERVISOR_EXITED", "The owned Metro supervisor could not be stopped for a cache reset.", "Inspect `stim status` and `stim logs`, then retry. No cache reset was recorded.");
|
|
2137
|
+
case "port-occupied": throw supervisorError("STIM_SUPERVISOR_EXITED", `Port ${getProject(root)?.metroPort} is still occupied after stopping Metro.`, "Inspect the listener before retrying. Stim does not terminate unrecorded processes.");
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
//#endregion
|
|
2141
|
+
//#region src/budget.ts
|
|
2142
|
+
const MB = 1048576;
|
|
2143
|
+
const GB_IN_MB = 1024;
|
|
2144
|
+
const COMMITTED_MEMORY_SHARE = .6;
|
|
2145
|
+
const STALE_CACHE_DAYS = 14;
|
|
2146
|
+
const DEVICE_LIST_TIMEOUT_MS = 1e4;
|
|
2147
|
+
const USAGE_TIMEOUT_MS = 1e4;
|
|
2148
|
+
const BUDGET_SETTING_REMEDY = "Fix the value with `stim settings set <key> <value>`, or unset the environment variable. Run `stim guide settings` for the budget keys.";
|
|
2149
|
+
function valueAt(source, key) {
|
|
2150
|
+
let node = source;
|
|
2151
|
+
for (const part of key.split(".")) {
|
|
2152
|
+
if (node === null || typeof node !== "object" || Array.isArray(node)) return void 0;
|
|
2153
|
+
node = node[part];
|
|
2154
|
+
}
|
|
2155
|
+
return node;
|
|
2156
|
+
}
|
|
2157
|
+
function machineNumber(key, config, env) {
|
|
2158
|
+
const setting = settingDefinition(key);
|
|
2159
|
+
const fromEnv = setting.env ? env[setting.env] : void 0;
|
|
2160
|
+
if (fromEnv !== void 0 && fromEnv !== "") {
|
|
2161
|
+
const value = fromEnv.trim() === "" ? NaN : Number(fromEnv);
|
|
2162
|
+
const problem = settingValueError(setting, value);
|
|
2163
|
+
return problem ? {
|
|
2164
|
+
value: void 0,
|
|
2165
|
+
error: `Invalid ${setting.env} value ${JSON.stringify(fromEnv)}. Expected ${problem}.`
|
|
2166
|
+
} : {
|
|
2167
|
+
value,
|
|
2168
|
+
error: null
|
|
2169
|
+
};
|
|
2170
|
+
}
|
|
2171
|
+
if (env.STIM_HOME && typeof setting.scopedHomeValue === "number") return {
|
|
2172
|
+
value: setting.scopedHomeValue,
|
|
2173
|
+
error: null
|
|
2174
|
+
};
|
|
2175
|
+
const raw = valueAt(config, key);
|
|
2176
|
+
if (raw === void 0) return {
|
|
2177
|
+
value: typeof setting.default === "number" ? setting.default : void 0,
|
|
2178
|
+
error: null
|
|
2179
|
+
};
|
|
2180
|
+
const problem = settingValueError(setting, raw);
|
|
2181
|
+
return problem ? {
|
|
2182
|
+
value: void 0,
|
|
2183
|
+
error: `Invalid ${key} value ${JSON.stringify(raw)}. Expected ${problem}.`
|
|
2184
|
+
} : {
|
|
2185
|
+
value: raw,
|
|
2186
|
+
error: null
|
|
2187
|
+
};
|
|
2188
|
+
}
|
|
2189
|
+
function resolveBudget({ config = loadConfig$1(), env = process.env, totalMemoryMb = totalmem$1() / MB } = {}) {
|
|
2190
|
+
const minFree = machineNumber("budget.minFreeDiskGb", config, env);
|
|
2191
|
+
const hardFloor = machineNumber("budget.hardFloorDiskGb", config, env);
|
|
2192
|
+
const memory = machineNumber("budget.maxCommittedMemoryGb", config, env);
|
|
2193
|
+
const live = machineNumber("budget.maxLiveWorkspaces", config, env);
|
|
2194
|
+
return {
|
|
2195
|
+
budget: {
|
|
2196
|
+
minFreeDiskMb: (minFree.value ?? 0) * GB_IN_MB,
|
|
2197
|
+
hardFloorDiskMb: (hardFloor.value ?? 0) * GB_IN_MB,
|
|
2198
|
+
maxCommittedMemoryMb: memory.value === void 0 ? Math.round(totalMemoryMb * COMMITTED_MEMORY_SHARE) : memory.value * GB_IN_MB,
|
|
2199
|
+
maxLiveWorkspaces: live.value ?? 0
|
|
2200
|
+
},
|
|
2201
|
+
error: minFree.error ?? hardFloor.error ?? memory.error ?? live.error
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
function existingAncestor(path) {
|
|
2205
|
+
let current = path;
|
|
2206
|
+
while (!existsSync(current) && dirname(current) !== current) current = dirname(current);
|
|
2207
|
+
return current;
|
|
2208
|
+
}
|
|
2209
|
+
function readVolumeSpace(paths) {
|
|
2210
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2211
|
+
const volumes = [];
|
|
2212
|
+
for (const path of paths) try {
|
|
2213
|
+
const existing = existingAncestor(path);
|
|
2214
|
+
const device = statSync(existing).dev;
|
|
2215
|
+
if (seen.has(device)) continue;
|
|
2216
|
+
seen.add(device);
|
|
2217
|
+
const fs = statfsSync(existing);
|
|
2218
|
+
volumes.push({
|
|
2219
|
+
volume: volumeRootFor(path),
|
|
2220
|
+
freeMb: fs.bavail * fs.bsize / MB
|
|
2221
|
+
});
|
|
2222
|
+
} catch {}
|
|
2223
|
+
return volumes;
|
|
2224
|
+
}
|
|
2225
|
+
function estimateMemoryUse({ config, sims, androidSerial, supervisorRunning }) {
|
|
2226
|
+
const simsByUdid = Object.fromEntries((sims ?? []).map((sim) => [sim.udid, sim]));
|
|
2227
|
+
const runtime = (avdName) => {
|
|
2228
|
+
if (!avdName) return null;
|
|
2229
|
+
const serial = androidSerial(avdName);
|
|
2230
|
+
return {
|
|
2231
|
+
serial,
|
|
2232
|
+
state: serial ? "detected" : "not-detected"
|
|
2233
|
+
};
|
|
2234
|
+
};
|
|
2235
|
+
const states = Object.entries(config?.projects ?? {}).map(([path, project]) => {
|
|
2236
|
+
const pid = supervisorRunning(path, project);
|
|
2237
|
+
const slots = projectDeviceSlots(project);
|
|
2238
|
+
return environmentState({
|
|
2239
|
+
...project,
|
|
2240
|
+
__path: path
|
|
2241
|
+
}, {
|
|
2242
|
+
simsByUdid,
|
|
2243
|
+
simsAvailable: sims !== null,
|
|
2244
|
+
metro: pid === null ? { missing: true } : { metro: { pid } },
|
|
2245
|
+
androidRuntime: project.platforms?.android?.owned ? runtime(project.platforms.android.avdName) : null,
|
|
2246
|
+
androidRuntimes: Object.fromEntries(slots.slice(1).map(({ slot, platforms }) => [slot, platforms.android?.owned ? runtime(platforms.android.avdName) : null]))
|
|
2247
|
+
});
|
|
2248
|
+
});
|
|
2249
|
+
const { committedMb, liveCount } = capacity(states, 0);
|
|
2250
|
+
return {
|
|
2251
|
+
committedMb,
|
|
2252
|
+
liveWorkspaces: liveCount
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
function listSims() {
|
|
2256
|
+
try {
|
|
2257
|
+
return listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS });
|
|
2258
|
+
} catch {
|
|
2259
|
+
return null;
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
function runningSupervisorPid(path, project) {
|
|
2263
|
+
const target = resolveSupervisorTarget({
|
|
2264
|
+
state: readWorkspaceState$1(path)?.supervisor,
|
|
2265
|
+
record: project.supervisor,
|
|
2266
|
+
reservedPort: project.metroPort
|
|
2267
|
+
});
|
|
2268
|
+
return target.status === "ours" ? target.pid ?? null : null;
|
|
2269
|
+
}
|
|
2270
|
+
function readMemoryUse() {
|
|
2271
|
+
const resolve = ownedAvdSerialResolver({ timeoutMs: 5e3 });
|
|
2272
|
+
return estimateMemoryUse({
|
|
2273
|
+
config: loadConfig$1(),
|
|
2274
|
+
sims: listSims(),
|
|
2275
|
+
androidSerial: (avdName) => {
|
|
2276
|
+
try {
|
|
2277
|
+
return resolve(avdName).serial ?? null;
|
|
2278
|
+
} catch {
|
|
2279
|
+
return null;
|
|
2280
|
+
}
|
|
2281
|
+
},
|
|
2282
|
+
supervisorRunning: runningSupervisorPid
|
|
2283
|
+
});
|
|
2284
|
+
}
|
|
2285
|
+
function budgetShortfalls(budget, measure) {
|
|
2286
|
+
const floor = Math.max(budget.minFreeDiskMb, budget.hardFloorDiskMb);
|
|
2287
|
+
return {
|
|
2288
|
+
disk: floor > 0 ? measure.volumes.filter((v) => v.freeMb < floor) : [],
|
|
2289
|
+
hardFloor: budget.hardFloorDiskMb > 0 ? measure.volumes.filter((v) => v.freeMb < budget.hardFloorDiskMb) : [],
|
|
2290
|
+
memory: Boolean(budget.maxCommittedMemoryMb > 0 && measure.memory && measure.memory.committedMb > budget.maxCommittedMemoryMb),
|
|
2291
|
+
workspaces: Boolean(budget.maxLiveWorkspaces > 0 && measure.memory && measure.memory.liveWorkspaces > budget.maxLiveWorkspaces)
|
|
2292
|
+
};
|
|
2293
|
+
}
|
|
2294
|
+
const DISK_ONLY = ["workspace-outputs", "stale-cache-entries"];
|
|
2295
|
+
function reclaimPlan(short) {
|
|
2296
|
+
const disk = short.disk.length > 0;
|
|
2297
|
+
return [...disk || short.memory || short.workspaces ? ["idle-devices", "idle-dev-servers"] : [], ...disk ? DISK_ONLY : []];
|
|
2298
|
+
}
|
|
2299
|
+
function overBudget(short) {
|
|
2300
|
+
return short.disk.length > 0 || short.memory || short.workspaces;
|
|
2301
|
+
}
|
|
2302
|
+
function isOtherWorkspace(root) {
|
|
2303
|
+
const self = canonicalPath(root);
|
|
2304
|
+
return (path) => canonicalPath(path) !== self;
|
|
2305
|
+
}
|
|
2306
|
+
function deviceLabel(device) {
|
|
2307
|
+
return `${device.kind} ${device.name} in ${device.project}`;
|
|
2308
|
+
}
|
|
2309
|
+
function reclaimIdleDevices({ root, dryRun, note, now }) {
|
|
2310
|
+
if (deviceSweepIsScoped()) {
|
|
2311
|
+
note(chalk.dim(phaseLine("budget", "idle devices left alone: STIM_HOME scopes this config, devices are global")));
|
|
2312
|
+
return {
|
|
2313
|
+
targets: [],
|
|
2314
|
+
failures: 0
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
const other = isOtherWorkspace(root);
|
|
2318
|
+
const collect = (at) => idleShutdownCandidates(collectIdleDevices(loadConfig$1(), listSims() ?? [], [], at).filter((device) => other(device.project)), 0);
|
|
2319
|
+
const idle = collect(now);
|
|
2320
|
+
if (dryRun || idle.length === 0) return {
|
|
2321
|
+
targets: idle.map(deviceLabel),
|
|
2322
|
+
failures: 0
|
|
2323
|
+
};
|
|
2324
|
+
const { failures, shutDown } = shutDownIdleDevices(idle, 0, () => collect(Date.now()));
|
|
2325
|
+
return {
|
|
2326
|
+
targets: shutDown.map(deviceLabel),
|
|
2327
|
+
failures
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
function idleSince(path, now) {
|
|
2331
|
+
const activity = workspaceActivity(path, now);
|
|
2332
|
+
const at = Date.parse(activity.lastActivityAt ?? "");
|
|
2333
|
+
return activity.state === "idle" && Number.isFinite(at) ? at : null;
|
|
2334
|
+
}
|
|
2335
|
+
async function reclaimIdleDevServers({ root, dryRun, note, now }) {
|
|
2336
|
+
const config = loadConfig$1();
|
|
2337
|
+
const other = isOtherWorkspace(root);
|
|
2338
|
+
const serving = Object.entries(config?.projects ?? {}).flatMap(([path, project]) => {
|
|
2339
|
+
const pid = other(path) ? runningSupervisorPid(path, project) : null;
|
|
2340
|
+
return pid !== null && !workspaceBuildInProgress(path) && idleSince(path, now) !== null ? [{
|
|
2341
|
+
path,
|
|
2342
|
+
pid
|
|
2343
|
+
}] : [];
|
|
2344
|
+
});
|
|
2345
|
+
if (serving.length === 0) return {
|
|
2346
|
+
targets: [],
|
|
2347
|
+
failures: 0
|
|
2348
|
+
};
|
|
2349
|
+
const sims = listSims();
|
|
2350
|
+
if (sims === null) {
|
|
2351
|
+
note(chalk.dim(phaseLine("budget", "dev servers left alone: simulators could not be listed to prove them idle")));
|
|
2352
|
+
return {
|
|
2353
|
+
targets: [],
|
|
2354
|
+
failures: 0
|
|
2355
|
+
};
|
|
2356
|
+
}
|
|
2357
|
+
const busy = new Set(collectOwnedDeviceActivity(config, sims, now).filter((device) => device.activity.state !== "idle").map((device) => device.project));
|
|
2358
|
+
const idle = serving.filter(({ path }) => !busy.has(path));
|
|
2359
|
+
if (dryRun) return {
|
|
2360
|
+
targets: idle.map(({ path }) => path),
|
|
2361
|
+
failures: 0
|
|
2362
|
+
};
|
|
2363
|
+
const targets = [];
|
|
2364
|
+
let failures = 0;
|
|
2365
|
+
const stillIdle = (path, pid) => {
|
|
2366
|
+
const project = loadConfig$1()?.projects?.[path];
|
|
2367
|
+
return Boolean(project && runningSupervisorPid(path, project) === pid && !workspaceBuildInProgress(path) && idleSince(path, Date.now()) !== null);
|
|
2368
|
+
};
|
|
2369
|
+
for (const { path, pid } of idle) {
|
|
2370
|
+
let run;
|
|
2371
|
+
try {
|
|
2372
|
+
run = await withIdleWorkspace(path, async () => {
|
|
2373
|
+
try {
|
|
2374
|
+
return await withWorkspaceProcessLock(workspaceDir(path), "metro-start", async () => stillIdle(path, pid) ? stopOwnedMetro(path, {
|
|
2375
|
+
by: "budget reclaim",
|
|
2376
|
+
workspace: root
|
|
2377
|
+
}) : "busy", {
|
|
2378
|
+
external: true,
|
|
2379
|
+
waitMs: 0,
|
|
2380
|
+
ownerPurpose: "budget reclaim"
|
|
2381
|
+
});
|
|
2382
|
+
} catch (error) {
|
|
2383
|
+
if (workspaceProcessLockError(error)) return "starting";
|
|
2384
|
+
throw error;
|
|
2385
|
+
}
|
|
2386
|
+
}, {
|
|
2387
|
+
purpose: "budget reclaim",
|
|
2388
|
+
supervisor: false
|
|
2389
|
+
});
|
|
2390
|
+
} catch (error) {
|
|
2391
|
+
failures++;
|
|
2392
|
+
note(chalk.red(`Could not stop the dev server of ${path}: ${error?.message || error}`));
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
if (!run.ran) {
|
|
2396
|
+
note(chalk.yellow(`Kept the dev server of ${path}: ${run.reasons.join("; ")}`));
|
|
2397
|
+
continue;
|
|
2398
|
+
}
|
|
2399
|
+
const stopped = run.value;
|
|
2400
|
+
if (stopped === "busy" || stopped === "starting") {
|
|
2401
|
+
const why = stopped === "busy" ? "it is no longer idle" : "a stim start holds its metro-start lock";
|
|
2402
|
+
note(chalk.dim(`Kept the dev server of ${path}: ${why}`));
|
|
2403
|
+
} else if (stopped.status === "stopped") {
|
|
2404
|
+
targets.push(path);
|
|
2405
|
+
note(chalk.green(`Stopped the idle dev server of ${path}`));
|
|
2406
|
+
} else if ("reason" in stopped) {
|
|
2407
|
+
if (stopped.status === "stuck") failures++;
|
|
2408
|
+
note(chalk.yellow(`Kept the dev server of ${path}: ${stopped.reason}`));
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
return {
|
|
2412
|
+
targets,
|
|
2413
|
+
failures
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2416
|
+
async function reclaimWorkspaceOutputs({ root, dryRun, now, diskRecovered }) {
|
|
2417
|
+
const other = isOtherWorkspace(root);
|
|
2418
|
+
const report = collectWorkspaceOutputs({
|
|
2419
|
+
olderThan: null,
|
|
2420
|
+
now,
|
|
2421
|
+
measure: false
|
|
2422
|
+
});
|
|
2423
|
+
const clearable = report.workspaces.flatMap((entry) => {
|
|
2424
|
+
const project = entry.projectRoot;
|
|
2425
|
+
const since = project !== null && entry.willClear && other(project) ? idleSince(project, now) : null;
|
|
2426
|
+
return since === null ? [] : [{
|
|
2427
|
+
entry,
|
|
2428
|
+
since
|
|
2429
|
+
}];
|
|
2430
|
+
}).toSorted((a, b) => a.since - b.since).map(({ entry }) => entry);
|
|
2431
|
+
if (dryRun) return {
|
|
2432
|
+
targets: clearable.map((entry) => entry.projectRoot),
|
|
2433
|
+
failures: 0
|
|
2434
|
+
};
|
|
2435
|
+
const targets = [];
|
|
2436
|
+
let failures = 0;
|
|
2437
|
+
for (const entry of clearable) {
|
|
2438
|
+
const result = await clearWorkspaceOutputs({
|
|
2439
|
+
...report,
|
|
2440
|
+
workspaces: [entry]
|
|
2441
|
+
}, {
|
|
2442
|
+
olderThan: null,
|
|
2443
|
+
now
|
|
2444
|
+
});
|
|
2445
|
+
failures += result.failures;
|
|
2446
|
+
targets.push(...result.cleared);
|
|
2447
|
+
if (diskRecovered()) break;
|
|
2448
|
+
}
|
|
2449
|
+
return {
|
|
2450
|
+
targets,
|
|
2451
|
+
failures
|
|
2452
|
+
};
|
|
2453
|
+
}
|
|
2454
|
+
function cacheLabel(cache) {
|
|
2455
|
+
return `${cache.name} ${cache.dir}`;
|
|
2456
|
+
}
|
|
2457
|
+
function reclaimStaleCacheEntries({ dryRun }) {
|
|
2458
|
+
const caches = planCacheEmptying(discoverCaches(), false).filter((cache) => cache.prune !== "report-only" && cache.prune !== "atomic" && !cache.machineGlobal);
|
|
2459
|
+
if (dryRun) return {
|
|
2460
|
+
targets: caches.map(cacheLabel),
|
|
2461
|
+
failures: 0
|
|
2462
|
+
};
|
|
2463
|
+
return {
|
|
2464
|
+
targets: trimCaches(caches, STALE_CACHE_DAYS).map(cacheLabel),
|
|
2465
|
+
failures: 0
|
|
2466
|
+
};
|
|
2467
|
+
}
|
|
2468
|
+
const STEPS = {
|
|
2469
|
+
"idle-devices": reclaimIdleDevices,
|
|
2470
|
+
"idle-dev-servers": reclaimIdleDevServers,
|
|
2471
|
+
"workspace-outputs": reclaimWorkspaceOutputs,
|
|
2472
|
+
"stale-cache-entries": reclaimStaleCacheEntries
|
|
2473
|
+
};
|
|
2474
|
+
const STEP_ACTIONS = {
|
|
2475
|
+
"idle-devices": "shut down idle owned devices",
|
|
2476
|
+
"idle-dev-servers": "stop idle dev servers",
|
|
2477
|
+
"workspace-outputs": "clear build outputs of idle workspaces",
|
|
2478
|
+
"stale-cache-entries": `trim cache entries unused for ${STALE_CACHE_DAYS} days`
|
|
2479
|
+
};
|
|
2480
|
+
async function runStep(step, context) {
|
|
2481
|
+
const log = console.log;
|
|
2482
|
+
const exitCode = process.exitCode;
|
|
2483
|
+
console.log = console.error;
|
|
2484
|
+
try {
|
|
2485
|
+
const result = await STEPS[step](context);
|
|
2486
|
+
return process.exitCode === exitCode ? result : {
|
|
2487
|
+
...result,
|
|
2488
|
+
failures: result.failures + 1
|
|
2489
|
+
};
|
|
2490
|
+
} catch (error) {
|
|
2491
|
+
context.note(chalk.red(phaseLine("budget", `${STEP_ACTIONS[step]} failed: ${error?.message || error}`)));
|
|
2492
|
+
return {
|
|
2493
|
+
targets: [],
|
|
2494
|
+
failures: 1
|
|
2495
|
+
};
|
|
2496
|
+
} finally {
|
|
2497
|
+
console.log = log;
|
|
2498
|
+
process.exitCode = exitCode;
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
function spaceUsers() {
|
|
2502
|
+
const home = homedir$1();
|
|
2503
|
+
const candidates = [
|
|
2504
|
+
["Stim state", getConfigDir()],
|
|
2505
|
+
["shared build cache", sharedBuildCache()],
|
|
2506
|
+
...platform() === "darwin" ? [["simulators", join(home, "Library", "Developer", "CoreSimulator", "Devices")], ["Xcode DerivedData", join(home, "Library", "Developer", "Xcode", "DerivedData")]] : [],
|
|
2507
|
+
["Android emulators", join(home, ".android", "avd")]
|
|
2508
|
+
];
|
|
2509
|
+
const measured = /* @__PURE__ */ new Set();
|
|
2510
|
+
const users = [];
|
|
2511
|
+
for (const [label, path] of candidates) {
|
|
2512
|
+
const canonical = canonicalPath(path);
|
|
2513
|
+
if (measured.has(canonical) || [...measured].some((dir) => canonical.startsWith(`${dir}${sep}`))) continue;
|
|
2514
|
+
measured.add(canonical);
|
|
2515
|
+
if (!existsSync(path)) continue;
|
|
2516
|
+
const bytes = measuredDirectorySize(path, { timeoutMs: USAGE_TIMEOUT_MS });
|
|
2517
|
+
if (bytes) users.push({
|
|
2518
|
+
label: `${label} ${path}`,
|
|
2519
|
+
bytes
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
return users.toSorted((a, b) => b.bytes - a.bytes).map(({ label, bytes }) => `${label}: ${formatBytes(bytes)}`);
|
|
2523
|
+
}
|
|
2524
|
+
const DEFAULT_DEPS = {
|
|
2525
|
+
volumes: readVolumeSpace,
|
|
2526
|
+
memory: readMemoryUse,
|
|
2527
|
+
step: runStep,
|
|
2528
|
+
usage: spaceUsers,
|
|
2529
|
+
now: Date.now
|
|
2530
|
+
};
|
|
2531
|
+
const LOW_DISK_REMEDY = "Run `stim gc` to see what else Stim can reclaim, then `stim gc --delete` (add `--cache all` to empty the shared caches, or `--worktrees` to remove finished worktrees). Free space outside Stim from the largest uses listed, or lower budget.hardFloorDiskGb.";
|
|
2532
|
+
function describeShortfall(budget, measure, short) {
|
|
2533
|
+
const floor = Math.max(budget.minFreeDiskMb, budget.hardFloorDiskMb);
|
|
2534
|
+
return [
|
|
2535
|
+
...short.disk.map((v) => `${formatSpace(v.freeMb)} free on ${v.volume}, below the ${formatSpace(floor)} floor`),
|
|
2536
|
+
...short.memory && measure.memory ? [`roughly ${formatSpace(measure.memory.committedMb)} of memory committed, over the ${formatSpace(budget.maxCommittedMemoryMb)} budget`] : [],
|
|
2537
|
+
...short.workspaces && measure.memory ? [`${measure.memory.liveWorkspaces} live workspaces, over the limit of ${budget.maxLiveWorkspaces}`] : []
|
|
2538
|
+
];
|
|
2539
|
+
}
|
|
2540
|
+
async function enforceBudget({ root, note, dryRun = false, budget: resolved }, overrides = {}) {
|
|
2541
|
+
const deps = {
|
|
2542
|
+
...DEFAULT_DEPS,
|
|
2543
|
+
...overrides
|
|
2544
|
+
};
|
|
2545
|
+
let budget = resolved;
|
|
2546
|
+
if (!budget) {
|
|
2547
|
+
const read = resolveBudget();
|
|
2548
|
+
if (read.error) return {
|
|
2549
|
+
status: "invalid",
|
|
2550
|
+
refusal: {
|
|
2551
|
+
code: "STIM_BAD_ARG",
|
|
2552
|
+
message: read.error,
|
|
2553
|
+
remedy: BUDGET_SETTING_REMEDY
|
|
2554
|
+
}
|
|
2555
|
+
};
|
|
2556
|
+
budget = read.budget;
|
|
2557
|
+
}
|
|
2558
|
+
const paths = [root, getConfigDir()];
|
|
2559
|
+
const measureNow = () => ({
|
|
2560
|
+
volumes: budget.minFreeDiskMb > 0 || budget.hardFloorDiskMb > 0 ? deps.volumes(paths) : [],
|
|
2561
|
+
memory: budget.maxCommittedMemoryMb > 0 || budget.maxLiveWorkspaces > 0 ? deps.memory() : null
|
|
2562
|
+
});
|
|
2563
|
+
let measure = measureNow();
|
|
2564
|
+
let short = budgetShortfalls(budget, measure);
|
|
2565
|
+
const reclaimed = [];
|
|
2566
|
+
const plan = reclaimPlan(short);
|
|
2567
|
+
if (plan.length) note(chalk.yellow(phaseLine("budget", `${describeShortfall(budget, measure, short).join("; ")}; ${dryRun ? "would reclaim" : "reclaiming"}`)));
|
|
2568
|
+
for (const step of plan) {
|
|
2569
|
+
if (!dryRun && (!overBudget(short) || DISK_ONLY.includes(step) && short.disk.length === 0)) break;
|
|
2570
|
+
const freeBefore = measure.volumes.reduce((sum, v) => sum + v.freeMb, 0);
|
|
2571
|
+
const result = await deps.step(step, {
|
|
2572
|
+
root,
|
|
2573
|
+
dryRun,
|
|
2574
|
+
note,
|
|
2575
|
+
now: deps.now(),
|
|
2576
|
+
diskRecovered: () => budgetShortfalls(budget, {
|
|
2577
|
+
volumes: deps.volumes(paths),
|
|
2578
|
+
memory: null
|
|
2579
|
+
}).disk.length === 0
|
|
2580
|
+
});
|
|
2581
|
+
if (!dryRun) {
|
|
2582
|
+
measure = measureNow();
|
|
2583
|
+
short = budgetShortfalls(budget, measure);
|
|
2584
|
+
}
|
|
2585
|
+
if (result.targets.length === 0 && result.failures === 0) continue;
|
|
2586
|
+
const freedMb = Math.max(0, Math.round(measure.volumes.reduce((sum, v) => sum + v.freeMb, 0) - freeBefore));
|
|
2587
|
+
reclaimed.push({
|
|
2588
|
+
step,
|
|
2589
|
+
...result,
|
|
2590
|
+
...dryRun ? {} : { freedMb }
|
|
2591
|
+
});
|
|
2592
|
+
const outcome = dryRun ? result.targets.join(", ") : `${result.targets.length}${result.failures ? `, ${result.failures} failed` : ""} (${formatSpace(freedMb)} freed)`;
|
|
2593
|
+
note(chalk.dim(phaseLine("budget", `${STEP_ACTIONS[step]}: ${outcome}`)));
|
|
2594
|
+
}
|
|
2595
|
+
if (!dryRun && short.hardFloor.length) {
|
|
2596
|
+
const tight = short.hardFloor.map((v) => `${formatSpace(v.freeMb)} on ${v.volume}`).join(" and ");
|
|
2597
|
+
const users = deps.usage();
|
|
2598
|
+
return {
|
|
2599
|
+
status: "refused",
|
|
2600
|
+
reclaimed,
|
|
2601
|
+
refusal: {
|
|
2602
|
+
code: "STIM_LOW_DISK",
|
|
2603
|
+
message: `Only ${tight} is free, below the ${formatSpace(budget.hardFloorDiskMb)} hard floor (budget.hardFloorDiskGb)${reclaimed.length ? " after reclaiming what Stim safely could" : ""}, so this run could fill the disk.` + (users.length ? ` Largest uses: ${users.join("; ")}.` : ""),
|
|
2604
|
+
remedy: LOW_DISK_REMEDY
|
|
2605
|
+
}
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
if (!dryRun && overBudget(short)) note(chalk.yellow(phaseLine("budget", `still over budget: ${describeShortfall(budget, measure, short).join("; ")}`)));
|
|
2609
|
+
return {
|
|
2610
|
+
status: "ok",
|
|
2611
|
+
reclaimed,
|
|
2612
|
+
budget,
|
|
2613
|
+
measure,
|
|
2614
|
+
short
|
|
2615
|
+
};
|
|
2616
|
+
}
|
|
2617
|
+
async function budgetGate(args, overrides = {}) {
|
|
2618
|
+
const outcome = await enforceBudget(args, overrides);
|
|
2619
|
+
return {
|
|
2620
|
+
reclaimed: "reclaimed" in outcome ? outcome.reclaimed : [],
|
|
2621
|
+
refusal: outcome.status === "ok" ? null : outcome.refusal
|
|
2622
|
+
};
|
|
2623
|
+
}
|
|
2624
|
+
const gb = (mb) => Math.round(mb / GB_IN_MB * 10) / 10;
|
|
2625
|
+
function budgetFindings(budget, measure, short, plan) {
|
|
2626
|
+
const findings = [];
|
|
2627
|
+
const steps = plan.length ? plan.map((entry) => `${STEP_ACTIONS[entry.step]} (${entry.targets.join(", ")})`).join("; then ") : "nothing Stim can reclaim on its own right now";
|
|
2628
|
+
if (short.disk.length) {
|
|
2629
|
+
const refuses = short.hardFloor.length ? ` Below ${formatSpace(budget.hardFloorDiskMb)} it refuses with STIM_LOW_DISK when reclaiming does not free enough.` : "";
|
|
2630
|
+
findings.push({
|
|
2631
|
+
level: "cost",
|
|
2632
|
+
title: "Free disk is below the Stim budget",
|
|
2633
|
+
detail: `${describeShortfall(budget, measure, {
|
|
2634
|
+
...short,
|
|
2635
|
+
memory: false,
|
|
2636
|
+
workspaces: false
|
|
2637
|
+
}).join("; ")}. The next ios, android or start will first ${steps}.${refuses}`,
|
|
2638
|
+
fix: "Run `stim gc` to see what Stim can reclaim, then `stim gc --delete`. Free space outside Stim, or lower budget.minFreeDiskGb."
|
|
2639
|
+
});
|
|
2640
|
+
}
|
|
2641
|
+
if (short.memory || short.workspaces) findings.push({
|
|
2642
|
+
level: "note",
|
|
2643
|
+
title: "Live environments are over the memory budget",
|
|
2644
|
+
detail: `${describeShortfall(budget, measure, {
|
|
2645
|
+
...short,
|
|
2646
|
+
disk: []
|
|
2647
|
+
}).join("; ")}. The next ios, android or start shuts down idle owned devices and stops idle dev servers in other workspaces first.`,
|
|
2648
|
+
fix: "Run `stim status` to see what is live, and `stim stop` in workspaces you own that you no longer need."
|
|
2649
|
+
});
|
|
2650
|
+
return findings;
|
|
2651
|
+
}
|
|
2652
|
+
async function inspectBudget(root, deps = {}) {
|
|
2653
|
+
const read = resolveBudget();
|
|
2654
|
+
if (read.error) return {
|
|
2655
|
+
report: null,
|
|
2656
|
+
findings: [{
|
|
2657
|
+
level: "cost",
|
|
2658
|
+
title: "A budget setting is invalid",
|
|
2659
|
+
detail: read.error,
|
|
2660
|
+
fix: BUDGET_SETTING_REMEDY
|
|
2661
|
+
}]
|
|
2662
|
+
};
|
|
2663
|
+
const outcome = await enforceBudget({
|
|
2664
|
+
root,
|
|
2665
|
+
note: () => {},
|
|
2666
|
+
dryRun: true,
|
|
2667
|
+
budget: read.budget
|
|
2668
|
+
}, deps);
|
|
2669
|
+
if (outcome.status !== "ok") return {
|
|
2670
|
+
report: null,
|
|
2671
|
+
findings: []
|
|
2672
|
+
};
|
|
2673
|
+
const { budget, measure, short, reclaimed } = outcome;
|
|
2674
|
+
return {
|
|
2675
|
+
report: {
|
|
2676
|
+
budget: {
|
|
2677
|
+
minFreeDiskGb: gb(budget.minFreeDiskMb),
|
|
2678
|
+
hardFloorDiskGb: gb(budget.hardFloorDiskMb),
|
|
2679
|
+
maxCommittedMemoryGb: gb(budget.maxCommittedMemoryMb),
|
|
2680
|
+
maxLiveWorkspaces: budget.maxLiveWorkspaces
|
|
2681
|
+
},
|
|
2682
|
+
volumes: measure.volumes.map((v) => ({
|
|
2683
|
+
volume: v.volume,
|
|
2684
|
+
freeGb: gb(v.freeMb)
|
|
2685
|
+
})),
|
|
2686
|
+
memory: measure.memory ? {
|
|
2687
|
+
committedGb: gb(measure.memory.committedMb),
|
|
2688
|
+
liveWorkspaces: measure.memory.liveWorkspaces
|
|
2689
|
+
} : null,
|
|
2690
|
+
plan: reclaimed
|
|
2691
|
+
},
|
|
2692
|
+
findings: budgetFindings(budget, measure, short, reclaimed)
|
|
2693
|
+
};
|
|
2694
|
+
}
|
|
2695
|
+
function budgetLine(report) {
|
|
2696
|
+
const { budget } = report;
|
|
2697
|
+
return `${report.volumes.length ? `${report.volumes.map((v) => `${v.freeGb} GB free on ${v.volume}`).join(", ")} (reclaims below ${Math.max(budget.minFreeDiskGb, budget.hardFloorDiskGb)} GB, ${budget.hardFloorDiskGb ? `refuses below ${budget.hardFloorDiskGb} GB` : "never refuses"})` : "disk budget off"}; ${report.memory ? `roughly ${report.memory.committedGb} GB of a ${budget.maxCommittedMemoryGb} GB memory budget committed` : "memory budget off"}`;
|
|
2698
|
+
}
|
|
2699
|
+
//#endregion
|
|
2700
|
+
export { isWorkspacesScope as A, memoryCacheKind as B, unverifiedDeviceCommand as C, includesParkedDevices as D, includesArchives as E, trimCaches as F, reclaimMemory as G, memoryScope as H, GRADLE_DAEMONS_KIND as I, attributeMachineUsage as J, scopedMemoryReport as K, WATCHMAN_KIND as L, previewScopedEmptying as M, selectCaches as N, includesRecordings as O, selectsBeyondCaches as P, collectMemoryReport as R, findStaleProjectDevices as S, emptyCaches as T, memorySweepIsScoped as U, memoryLines as V, memoryWorkPending as W, discoverCaches as X, readFootprints as Y, sizeCaches as Z, describeUnverifiableDevices as _, machineNumber as a, findOrphanedDevices as b, stopOwnedMetroForReset as c, collectParkedAvds as d, collectParkedSims as f, describeParkedSims as g, deleteProjectDevices as h, inspectBudget as i, planCacheEmptying as j, includesWorkspaceOutputs as k, DEVICE_LIST_TIMEOUT_MS$1 as l, deleteParkedSims as m, budgetLine as n, readVolumeSpace as o, deleteParkedAvds as p, phase as q, enforceBudget as r, resolveBudget as s, budgetGate as t, collectDeviceLeases as u, deviceSweepIsScoped as v, withAndroidAvdSizes as w, findStaleDeviceRecords as x, eraseParkedDevices as y, inspectWatchmanMemory as z };
|