@ultimat3/cli 31.47.1 → 31.49.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/CLAUDE.md +30 -23
- package/README.md +96 -4
- package/package.json +29 -29
- package/src/api-registration.ts +28 -14
- package/src/app-load.ts +6 -1
- package/src/app-root.ts +7 -1
- package/src/clean-services.ts +142 -0
- package/src/cmd-auth.ts +3 -0
- package/src/cmd-clean-spec.ts +10 -3
- package/src/cmd-clean.ts +23 -9
- package/src/cmd-db-backfill.ts +6 -0
- package/src/cmd-db-branch.ts +10 -4
- package/src/cmd-db-recount.ts +5 -12
- package/src/cmd-db-rollback.ts +77 -0
- package/src/cmd-db-spec.ts +18 -2
- package/src/cmd-db-status.ts +5 -10
- package/src/cmd-db.ts +105 -33
- package/src/cmd-deploy-verify.ts +14 -6
- package/src/cmd-docs-topic.ts +94 -0
- package/src/cmd-docs.ts +15 -1
- package/src/cmd-doctor.ts +109 -41
- package/src/cmd-drill.ts +100 -19
- package/src/cmd-env.ts +30 -8
- package/src/cmd-errors-app.ts +63 -0
- package/src/cmd-errors.ts +50 -14
- package/src/cmd-generate.ts +17 -4
- package/src/cmd-heavy-spec.ts +36 -0
- package/src/cmd-heavy.ts +244 -0
- package/src/cmd-jobs.ts +27 -1
- package/src/cmd-merge-driver-spec.ts +12 -0
- package/src/cmd-merge-driver.ts +95 -0
- package/src/cmd-new.ts +23 -3
- package/src/cmd-policy-spec.ts +9 -1
- package/src/cmd-policy.ts +72 -17
- package/src/cmd-stop.ts +18 -4
- package/src/cmd-tasks-run.ts +87 -0
- package/src/cmd-tasks-spec.ts +10 -3
- package/src/cmd-tasks.ts +8 -5
- package/src/cmd-test.ts +15 -4
- package/src/cmd-upgrade-spec.ts +8 -1
- package/src/cmd-upgrade.ts +32 -5
- package/src/cmd-verify.ts +9 -41
- package/src/codemods/agents-doc-row.ts +73 -0
- package/src/codemods/define-error-leaf.ts +37 -12
- package/src/codemods/docs-many-agents.ts +26 -0
- package/src/codemods/docs-worker-commands.ts +26 -0
- package/src/codemods/index.ts +6 -0
- package/src/codemods/merge-drivers.ts +66 -0
- package/src/command.ts +3 -0
- package/src/db-applied-edits.ts +117 -0
- package/src/db-dev-wire.ts +18 -0
- package/src/db-diagnostics.ts +5 -10
- package/src/db-generate.ts +82 -7
- package/src/db-migrate-pass.ts +51 -0
- package/src/db-migrate-through-dev.ts +209 -0
- package/src/db-rollback-consent.ts +128 -0
- package/src/db-rollback-pass.ts +76 -0
- package/src/db-seed-generate.ts +5 -1
- package/src/db-seed.ts +7 -1
- package/src/deploy-verify-findings.ts +3 -0
- package/src/deploy-verify-grade.ts +3 -0
- package/src/deploy-verify-processes.ts +32 -0
- package/src/dev-boot.ts +3 -0
- package/src/dev-db-migrate.ts +155 -0
- package/src/dev-db-rollback.ts +33 -0
- package/src/dev-db-settled.ts +22 -0
- package/src/dev-lock-errors.ts +78 -0
- package/src/dev-lock-holder-dir.ts +64 -0
- package/src/dev-lock-live.ts +44 -0
- package/src/dev-lock.ts +59 -84
- package/src/dev-policy.ts +11 -8
- package/src/dev-rebuild-schema.ts +116 -13
- package/src/dev-rebuild.ts +13 -4
- package/src/dev-route-table.ts +7 -0
- package/src/dispatch.ts +21 -1
- package/src/doctor-advisory-floors.ts +30 -8
- package/src/doctor-api-listing.ts +114 -0
- package/src/doctor-guarded.ts +41 -0
- package/src/doctor-port.ts +90 -17
- package/src/doctor-probe.ts +36 -5
- package/src/doctor-processes-probe.ts +127 -0
- package/src/doctor-processes.ts +136 -0
- package/src/doctor-warnings.ts +17 -0
- package/src/error-codes-agents.ts +35 -0
- package/src/error-codes-processes.ts +30 -0
- package/src/error-codes-tooling.ts +11 -3
- package/src/error-codes.ts +12 -13
- package/src/errors-suite.ts +27 -0
- package/src/errors.ts +18 -22
- package/src/exec.ts +11 -3
- package/src/exercise-registration.ts +4 -3
- package/src/framework-env.ts +7 -3
- package/src/generate-files.ts +1 -0
- package/src/generate-grant-findings.ts +7 -5
- package/src/generate-grants.ts +9 -8
- package/src/generate-kinds.ts +30 -6
- package/src/generate-roles-file.ts +30 -0
- package/src/generate-slice-policy.ts +3 -3
- package/src/guards.ts +2 -2
- package/src/heavy-cores.ts +51 -0
- package/src/heavy-env.ts +21 -0
- package/src/heavy-errors.ts +54 -0
- package/src/heavy-flock.ts +73 -0
- package/src/heavy-holders.ts +78 -0
- package/src/heavy-ledger.ts +400 -0
- package/src/heavy-memory.ts +67 -0
- package/src/heavy-pressure.ts +104 -0
- package/src/heavy-weights.ts +47 -0
- package/src/heavy.ts +308 -0
- package/src/i18n-registration.ts +22 -2
- package/src/island-harness.ts +2 -2
- package/src/job-budget.ts +4 -2
- package/src/job-registration.ts +64 -8
- package/src/jobs-queue-known.ts +43 -0
- package/src/local-cli.ts +6 -5
- package/src/mcp-errors-agents.ts +20 -0
- package/src/mcp-errors-doctor.ts +27 -0
- package/src/mcp-errors-processes.ts +23 -0
- package/src/mcp-errors.ts +18 -29
- package/src/mcp-host.ts +2 -2
- package/src/merge-driver-catalog.ts +58 -0
- package/src/merge-driver-config.ts +43 -0
- package/src/merge-driver-lines.ts +140 -0
- package/src/merge-state.ts +105 -0
- package/src/messages-db.ts +22 -1
- package/src/messages-processes.ts +13 -0
- package/src/messages-upgrade.ts +6 -0
- package/src/messages.ts +62 -1
- package/src/output-findings.ts +48 -21
- package/src/parse.ts +37 -6
- package/src/policy-facts.ts +38 -21
- package/src/policy-row.ts +99 -0
- package/src/port-pair-free.ts +28 -0
- package/src/registry-lines.ts +110 -0
- package/src/registry.ts +4 -0
- package/src/retain-sweep.ts +1 -1
- package/src/role-replicator.ts +9 -4
- package/src/role-select.ts +86 -0
- package/src/role-start.ts +13 -55
- package/src/role-sync.ts +10 -5
- package/src/runtime-cache-frame.ts +46 -0
- package/src/runtime-cache-ttl.ts +23 -0
- package/src/runtime-cache.ts +56 -18
- package/src/runtime-database-ssl.ts +84 -0
- package/src/runtime-idempotency-scope.ts +16 -2
- package/src/runtime-jobs-share.ts +52 -0
- package/src/runtime-jobs.ts +43 -12
- package/src/runtime-overrides.ts +4 -2
- package/src/runtime-queue.ts +18 -3
- package/src/runtime-services.ts +8 -1
- package/src/schema-drift.ts +19 -2
- package/src/schema-dump-drift.ts +4 -1
- package/src/serve-boot-probe.ts +30 -2
- package/src/serve-boot.ts +11 -1
- package/src/serve-env.ts +39 -3
- package/src/serve.ts +61 -10
- package/src/stop-run-start.ts +12 -0
- package/src/supervise-boot.ts +61 -0
- package/src/supervise-cgroup.ts +84 -0
- package/src/supervise-child.ts +206 -0
- package/src/supervise-count.ts +244 -0
- package/src/supervise-errors.ts +83 -0
- package/src/supervise-facts.ts +40 -0
- package/src/supervise-messages.ts +84 -0
- package/src/supervise-policy.ts +46 -0
- package/src/supervise-pool.ts +10 -0
- package/src/supervise-probe.ts +158 -0
- package/src/supervise-run.ts +54 -0
- package/src/supervise.ts +383 -0
- package/src/templates/generate-purge.ts +6 -6
- package/src/templates/guard-animated-layout-property.ts +2 -2
- package/src/templates/guard-bare-error.ts +1 -1
- package/src/templates/guard-error-declared.ts +2 -2
- package/src/templates/guard-focus-visible.ts +1 -1
- package/src/templates/guard-image-dimensions.ts +2 -2
- package/src/templates/guard-island-mount-clears.ts +1 -1
- package/src/templates/guard-native-confirm.ts +1 -1
- package/src/templates/guard-raw-breakpoint.ts +2 -2
- package/src/templates/guard-raw-colour.ts +2 -2
- package/src/templates/guard-raw-fetch.ts +1 -1
- package/src/templates/guard-raw-interval.ts +1 -1
- package/src/templates/guard-raw-length.ts +3 -3
- package/src/templates/guard-raw-motion.ts +1 -1
- package/src/templates/guard-raw-shadow.ts +1 -1
- package/src/templates/guard-raw-z-index.ts +1 -1
- package/src/templates/guard-released-forms.ts +59 -13
- package/src/templates/guard-repo-await-in-loop.ts +1 -1
- package/src/templates/guard-repo-raw-sql.ts +4 -4
- package/src/templates/guard-repo-unbounded.ts +1 -1
- package/src/templates/guard-runtime-pin.ts +1 -1
- package/src/templates/guard-semantic-interactive.ts +2 -2
- package/src/templates/guard-unbounded-fanout.ts +1 -1
- package/src/templates/guard-undeclared-custom-property.ts +3 -3
- package/src/templates/guard-undefined-style-class.ts +3 -3
- package/src/templates/guard-unzoned-date.ts +3 -3
- package/src/templates/query-slice.ts +82 -0
- package/src/templates/query.ts +76 -30
- package/src/templates/resource-page.ts +3 -2
- package/src/templates/scaffold-bin.ts +2 -0
- package/src/templates/scaffold-claude-agents.ts +9 -6
- package/src/templates/scaffold-claude-commands.ts +7 -1
- package/src/templates/scaffold-claude.ts +4 -4
- package/src/templates/scaffold-container-compose.ts +47 -7
- package/src/templates/scaffold-docs.ts +11 -6
- package/src/templates/scaffold-gitattributes.ts +18 -1
- package/src/templates/scaffold-helm-templates.ts +9 -0
- package/src/templates/scaffold-repo.ts +4 -1
- package/src/templates/scaffold-test-services.ts +33 -11
- package/src/templates/shapes/offline.ts +0 -7
- package/src/templates/shapes/realtime.ts +2 -6
- package/src/templates/sign-in-action-tests.ts +6 -4
- package/src/templates/sign-in-challenge.ts +62 -0
- package/src/templates/sign-in-oidc-mfa.ts +31 -0
- package/src/templates/sign-in-oidc.ts +11 -3
- package/src/templates/sign-in-password.ts +18 -56
- package/src/test-batches.ts +9 -3
- package/src/test-shards.ts +117 -37
- package/src/test-slots.ts +35 -161
- package/src/test-verdict.ts +79 -0
- package/src/test-workers.ts +15 -0
- package/src/upgrade-gate-codemods.ts +5 -3
- package/src/upgrade-gate.ts +19 -1
- package/src/upgrade-merge-drivers.ts +25 -0
- package/src/upgrade-report.ts +18 -4
- package/src/upgrade-scope.ts +62 -0
- package/src/verify-checks.ts +6 -11
- package/src/verify-coverage-run.ts +9 -5
- package/src/verify-deadline.ts +18 -2
- package/src/verify-heavy-steps.ts +26 -0
- package/src/verify-live.ts +38 -14
- package/src/verify-only.ts +67 -0
- package/src/verify-progress.ts +7 -3
- package/src/verify-run.ts +20 -2
- package/src/verify-services-stack.ts +165 -0
- package/src/verify-services.ts +84 -2
- package/src/verify-test-run.ts +9 -9
- package/src/verify-tests.ts +35 -22
- package/src/verify-typecheck.ts +25 -2
- package/wiki/Actions.md +2 -1
- package/wiki/Admin-Dashboard.md +2 -2
- package/wiki/Agents.md +5 -5
- package/wiki/Auth.md +15 -5
- package/wiki/Bare-VM.md +1 -1
- package/wiki/Building-Your-Own-Base.md +15 -2
- package/wiki/CI-Parallel-Gate.md +4 -4
- package/wiki/CLI-Reference.md +127 -48
- package/wiki/Caching-And-Invalidation.md +2 -2
- package/wiki/Client-Navigation.md +1 -1
- package/wiki/Configuration.md +32 -13
- package/wiki/Deployment.md +44 -4
- package/wiki/Entities-And-Migrations.md +5 -1
- package/wiki/FAQ.md +1 -1
- package/wiki/Getting-Started.md +2 -2
- package/wiki/Home.md +2 -1
- package/wiki/I18n.md +5 -3
- package/wiki/Installation.md +12 -11
- package/wiki/Interface-Rules.md +1 -1
- package/wiki/Jobs-And-Workflows.md +24 -4
- package/wiki/Known-Gaps.md +2 -2
- package/wiki/MCP-And-AI.md +8 -5
- package/wiki/Mail.md +1 -1
- package/wiki/Many-Agents.md +127 -0
- package/wiki/Migrations-And-Backfills.md +18 -0
- package/wiki/Notify.md +1 -1
- package/wiki/Observability.md +13 -0
- package/wiki/Queries-And-Live-Queries.md +2 -2
- package/wiki/Realtime.md +10 -1
- package/wiki/Routes-And-Render-Modes.md +1 -1
- package/wiki/Scheduled-Tasks.md +4 -1
- package/wiki/Testing.md +12 -9
- package/wiki/Timezones-And-Dates.md +5 -1
- package/wiki/Troubleshooting.md +1 -0
- package/wiki/Tutorial-01-First-App.md +5 -5
- package/wiki/Tutorial-02-First-Feature.md +1 -1
- package/wiki/Tutorial-03-Auth-And-Admin.md +7 -6
- package/wiki/Upgrading.md +37 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// flock(2) through `bun:ffi`: the one primitive the ledger stands on. The kernel drops the lock when
|
|
2
|
+
// the last descriptor closes, which includes the holder dying by any signal, so "the holder died"
|
|
3
|
+
// and "the lock is free" are one event and nothing has to detect a stale file.
|
|
4
|
+
//
|
|
5
|
+
// WINDOWS has no flock, and a Node descriptor there is not the HANDLE `LockFileEx` wants, so the
|
|
6
|
+
// ledger is OFF on Windows: `x heavy status` says so and the core cap still applies. An honest gap
|
|
7
|
+
// beats a pid file that reintroduces the stale-lock race this module exists to remove.
|
|
8
|
+
|
|
9
|
+
import { HeavyLedgerUnavailableError } from './heavy-errors';
|
|
10
|
+
|
|
11
|
+
const LOCK_EX = 2;
|
|
12
|
+
const LOCK_NB = 4;
|
|
13
|
+
const EINTR = 4;
|
|
14
|
+
|
|
15
|
+
const LIBC: Readonly<Record<string, { libs: readonly string[]; errno: string; busy: number }>> = {
|
|
16
|
+
// glibc first; the two musl names are Alpine's, the base of many app images.
|
|
17
|
+
linux: {
|
|
18
|
+
libs: ['libc.so.6', 'libc.musl-x86_64.so.1', 'libc.musl-aarch64.so.1'],
|
|
19
|
+
errno: '__errno_location',
|
|
20
|
+
busy: 11,
|
|
21
|
+
},
|
|
22
|
+
darwin: { libs: ['libSystem.B.dylib'], errno: '__error', busy: 35 },
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** True when this descriptor now holds the lock, false when another one does. */
|
|
26
|
+
export type TryLock = (fd: number) => boolean;
|
|
27
|
+
|
|
28
|
+
export type FlockBinding =
|
|
29
|
+
| { readonly ok: true; readonly tryLock: TryLock }
|
|
30
|
+
| { readonly ok: false; readonly reason: string };
|
|
31
|
+
|
|
32
|
+
const bound = new Map<string, Promise<FlockBinding>>();
|
|
33
|
+
|
|
34
|
+
async function bind(platform: string): Promise<FlockBinding> {
|
|
35
|
+
const spec = Object.hasOwn(LIBC, platform) ? LIBC[platform] : undefined;
|
|
36
|
+
if (spec === undefined) return { ok: false, reason: `flock(2) does not exist on ${platform}` };
|
|
37
|
+
// Imported here so a command that never reaches the ledger never loads FFI.
|
|
38
|
+
const { dlopen, FFIType, read } = await import('bun:ffi');
|
|
39
|
+
for (const lib of spec.libs) {
|
|
40
|
+
try {
|
|
41
|
+
const { symbols } = dlopen(lib, {
|
|
42
|
+
flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
|
|
43
|
+
[spec.errno]: { args: [], returns: FFIType.ptr },
|
|
44
|
+
});
|
|
45
|
+
const errnoAt = symbols[spec.errno] as unknown as () => Parameters<typeof read.i32>[0];
|
|
46
|
+
const flock = symbols.flock as unknown as (fd: number, operation: number) => number;
|
|
47
|
+
return {
|
|
48
|
+
ok: true,
|
|
49
|
+
tryLock: (fd) => {
|
|
50
|
+
if (flock(fd, LOCK_EX | LOCK_NB) === 0) return true;
|
|
51
|
+
const errno = read.i32(errnoAt(), 0);
|
|
52
|
+
if (errno === spec.busy || errno === EINTR) return false;
|
|
53
|
+
// Reading this as "busy" would wait forever on a filesystem that cannot lock at all.
|
|
54
|
+
throw new HeavyLedgerUnavailableError(
|
|
55
|
+
`flock(2) failed with errno ${String(errno)}, which is not contention`,
|
|
56
|
+
);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
} catch {
|
|
60
|
+
// Not this libc: the next name, and "no libc" below when none loads.
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { ok: false, reason: `no libc with flock(2) loaded (${spec.libs.join(', ')})` };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The process's one binding, loaded on first use. */
|
|
67
|
+
export const flockBinding = (platform: string = process.platform): Promise<FlockBinding> => {
|
|
68
|
+
const known = bound.get(platform);
|
|
69
|
+
if (known !== undefined) return known;
|
|
70
|
+
const binding = bind(platform);
|
|
71
|
+
bound.set(platform, binding);
|
|
72
|
+
return binding;
|
|
73
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Which processes keep a reservation alive: every process with its lock file open, as the OS sees
|
|
2
|
+
// it. The ledger records only the wrapper's pid, and after `kill -9` of the wrapper the memory is
|
|
3
|
+
// held by the command it started, so a recorded pid cannot say what would free it.
|
|
4
|
+
|
|
5
|
+
// why: Bun ships no directory listing, readlink or realpath primitive.
|
|
6
|
+
import { existsSync, readdirSync, readlinkSync, realpathSync } from 'node:fs';
|
|
7
|
+
// why: Bun ships no path-join primitive.
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import type { Runner } from './exec';
|
|
10
|
+
|
|
11
|
+
const PROC = '/proc';
|
|
12
|
+
|
|
13
|
+
function realOrSame(path: string): string {
|
|
14
|
+
try {
|
|
15
|
+
return realpathSync(path);
|
|
16
|
+
} catch {
|
|
17
|
+
return path; // Released while being asked about: nothing will match it, which is the answer.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function hasOpen(procRoot: string, pid: string, target: string): boolean {
|
|
22
|
+
const fds = join(procRoot, pid, 'fd');
|
|
23
|
+
try {
|
|
24
|
+
return readdirSync(fds).some((fd) => {
|
|
25
|
+
try {
|
|
26
|
+
return readlinkSync(join(fds, fd)) === target;
|
|
27
|
+
} catch {
|
|
28
|
+
return false; // The descriptor closed between the listing and the read.
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
} catch {
|
|
32
|
+
return false; // The process exited, or belongs to another user.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const parsePids = (text: string): readonly number[] =>
|
|
37
|
+
text
|
|
38
|
+
.split('\n')
|
|
39
|
+
.map((line) => line.trim())
|
|
40
|
+
.filter((line) => /^\d+$/.test(line))
|
|
41
|
+
.map(Number);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The pids with `file` open, this process excepted, or `undefined` when the OS will not say: `/proc`
|
|
45
|
+
* where it exists, `lsof` elsewhere (macOS; Windows has no ledger).
|
|
46
|
+
*/
|
|
47
|
+
export async function holderPids(
|
|
48
|
+
file: string,
|
|
49
|
+
runner: Runner,
|
|
50
|
+
cwd: string,
|
|
51
|
+
procRoot: string = PROC,
|
|
52
|
+
): Promise<readonly number[] | undefined> {
|
|
53
|
+
if (existsSync(join(procRoot, 'self', 'fd'))) {
|
|
54
|
+
const target = realOrSame(file);
|
|
55
|
+
return readdirSync(procRoot)
|
|
56
|
+
.filter((name) => /^\d+$/.test(name) && Number(name) !== process.pid)
|
|
57
|
+
.filter((pid) => hasOpen(procRoot, pid, target))
|
|
58
|
+
.map(Number)
|
|
59
|
+
.sort((a, b) => a - b);
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
// `lsof` exits 1 for "nobody has it open", so its stdout is read whatever the status.
|
|
63
|
+
const result = await runner(['lsof', '-t', file], { cwd });
|
|
64
|
+
return parsePids(result.stdout).filter((pid) => pid !== process.pid);
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined; // No `lsof` on this machine.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The fallback when no holder list exists. Signal 0 delivers nothing; it only asks. */
|
|
71
|
+
export function isProcessRunning(pid: number): boolean {
|
|
72
|
+
try {
|
|
73
|
+
process.kill(pid, 0);
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
// The machine's memory ledger: reservations weighted in MB, admitted first come, first served, every
|
|
2
|
+
// one a file its owner holds an flock on. A file nobody holds is dead by definition, so a holder or
|
|
3
|
+
// waiter killed by any signal stops counting at that instant and no take-over exists to race.
|
|
4
|
+
//
|
|
5
|
+
// queue/<time>-<pid>-<id> a waiter holds/<pid>-<id> an admitted reservation
|
|
6
|
+
// gate the admission critical section; only the queue's head takes it
|
|
7
|
+
//
|
|
8
|
+
// A holder hands its locked descriptor to the workload, so the kernel frees a reservation only when
|
|
9
|
+
// the holder AND the workload are gone: killing a wrapper never frees memory its child still uses.
|
|
10
|
+
// Holders never wait while holding and children inherit the hold, so the ledger cannot deadlock.
|
|
11
|
+
|
|
12
|
+
// why: flock needs real descriptors, and Bun ships no descriptor-level file API.
|
|
13
|
+
import {
|
|
14
|
+
closeSync,
|
|
15
|
+
ftruncateSync,
|
|
16
|
+
mkdirSync,
|
|
17
|
+
openSync,
|
|
18
|
+
readdirSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
renameSync,
|
|
21
|
+
statSync,
|
|
22
|
+
unlinkSync,
|
|
23
|
+
writeSync,
|
|
24
|
+
} from 'node:fs';
|
|
25
|
+
// why: Bun ships no path-join primitive.
|
|
26
|
+
import { join } from 'node:path';
|
|
27
|
+
import { HeavyLedgerUnavailableError, HeavyWaitExpiredError } from './heavy-errors';
|
|
28
|
+
import type { TryLock } from './heavy-flock';
|
|
29
|
+
import type { CpuReading } from './heavy-pressure';
|
|
30
|
+
import { cpuAdmission } from './heavy-pressure';
|
|
31
|
+
|
|
32
|
+
export const LEDGER_POLL_MS = 100;
|
|
33
|
+
/** A temp file this old lost its creator: creating one takes microseconds. */
|
|
34
|
+
const STALE_TEMP_MS = 60_000;
|
|
35
|
+
|
|
36
|
+
export interface LedgerEntry {
|
|
37
|
+
readonly pid: number;
|
|
38
|
+
readonly mb: number;
|
|
39
|
+
readonly label: string;
|
|
40
|
+
readonly cwd: string;
|
|
41
|
+
readonly at: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An admitted reservation, and the file whose lock it is. */
|
|
45
|
+
export interface LedgerHold extends LedgerEntry {
|
|
46
|
+
readonly file: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface LedgerView {
|
|
50
|
+
readonly holds: readonly LedgerHold[];
|
|
51
|
+
/** Oldest first: index 0 is the next admission. */
|
|
52
|
+
readonly queue: readonly LedgerEntry[];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface Held {
|
|
56
|
+
readonly path: string;
|
|
57
|
+
/** The locked descriptor. Handed to a child, it keeps the lock for as long as the child lives. */
|
|
58
|
+
readonly fd: number;
|
|
59
|
+
release(): void;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface Reservation extends Held {
|
|
63
|
+
readonly units: number;
|
|
64
|
+
readonly mb: number;
|
|
65
|
+
readonly waitedMs: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface ReserveInput {
|
|
69
|
+
readonly dir: string;
|
|
70
|
+
readonly capacityMb: number;
|
|
71
|
+
/** MB one unit costs: a measured peak (`heavy-weights.ts`). */
|
|
72
|
+
readonly unitMb: number;
|
|
73
|
+
readonly units: number;
|
|
74
|
+
/** MB the run costs however wide it is: the parent and whatever its workers share. */
|
|
75
|
+
readonly baseMb?: number;
|
|
76
|
+
/** Fewest units worth starting with. A run of workers narrows to what fits, down to this. */
|
|
77
|
+
readonly minUnits?: number;
|
|
78
|
+
readonly label: string;
|
|
79
|
+
readonly cwd: string;
|
|
80
|
+
readonly tryLock: TryLock;
|
|
81
|
+
readonly pollMs?: number;
|
|
82
|
+
/** Give up after this long in the queue. `0` is one attempt; unset waits for as long as it takes. */
|
|
83
|
+
readonly maxWaitMs?: number;
|
|
84
|
+
/** The CPU reading the head is judged by (`heavy-pressure.ts`); absent, CPU never holds it. */
|
|
85
|
+
readonly cpu?: () => CpuReading;
|
|
86
|
+
readonly onWait?: (wait: LedgerWait) => void;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface LedgerWait {
|
|
90
|
+
readonly needMb: number;
|
|
91
|
+
readonly usedMb: number;
|
|
92
|
+
readonly capacityMb: number;
|
|
93
|
+
readonly position: number;
|
|
94
|
+
readonly queued: number;
|
|
95
|
+
readonly holds: readonly LedgerEntry[];
|
|
96
|
+
/** Set when memory fits and the CPU is what holds the head back. */
|
|
97
|
+
readonly cpu?: CpuReading;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const codeOf = (error: unknown): unknown =>
|
|
101
|
+
typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined;
|
|
102
|
+
|
|
103
|
+
function unlinkQuiet(path: string): void {
|
|
104
|
+
try {
|
|
105
|
+
unlinkSync(path);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (codeOf(error) !== 'ENOENT') throw error;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function once(run: () => void): () => void {
|
|
112
|
+
let spent = false;
|
|
113
|
+
return () => {
|
|
114
|
+
if (spent) return;
|
|
115
|
+
spent = true;
|
|
116
|
+
run();
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function prepareLedger(dir: string): void {
|
|
121
|
+
for (const sub of ['queue', 'holds', 'locks']) {
|
|
122
|
+
mkdirSync(join(dir, sub), { recursive: true, mode: 0o700 });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const parseEntry = (text: string): LedgerEntry | undefined => {
|
|
127
|
+
try {
|
|
128
|
+
const value: unknown = JSON.parse(text);
|
|
129
|
+
if (typeof value !== 'object' || value === null) return undefined;
|
|
130
|
+
const field = (name: string): unknown => Reflect.get(value, name);
|
|
131
|
+
const [pid, mb, at] = [field('pid'), field('mb'), field('at')];
|
|
132
|
+
if (typeof pid !== 'number' || typeof mb !== 'number' || typeof at !== 'number') {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
return { pid, mb, at, label: String(field('label')), cwd: String(field('cwd')) };
|
|
136
|
+
} catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
interface Live {
|
|
142
|
+
readonly name: string;
|
|
143
|
+
readonly entry: LedgerEntry;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The entries whose owner still holds their lock, in name order. A dead one is dropped. */
|
|
147
|
+
function liveEntries(dir: string, tryLock: TryLock, sweep: boolean): Live[] {
|
|
148
|
+
let names: string[];
|
|
149
|
+
try {
|
|
150
|
+
names = readdirSync(dir).sort();
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (codeOf(error) === 'ENOENT') return [];
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
const live: Live[] = [];
|
|
156
|
+
for (const name of names) {
|
|
157
|
+
const path = join(dir, name);
|
|
158
|
+
let fd: number;
|
|
159
|
+
try {
|
|
160
|
+
fd = openSync(path, 'r');
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (codeOf(error) === 'ENOENT') continue;
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
if (tryLock(fd)) {
|
|
167
|
+
if (sweep) unlinkQuiet(path);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const entry = parseEntry(readFileSync(fd, 'utf8'));
|
|
171
|
+
if (entry !== undefined) live.push({ name, entry });
|
|
172
|
+
} finally {
|
|
173
|
+
closeSync(fd);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return live;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export const readLedger = (dir: string, tryLock: TryLock): LedgerView => ({
|
|
180
|
+
holds: liveEntries(join(dir, 'holds'), tryLock, false).map((one) => ({
|
|
181
|
+
...one.entry,
|
|
182
|
+
file: join(dir, 'holds', one.name),
|
|
183
|
+
})),
|
|
184
|
+
queue: liveEntries(join(dir, 'queue'), tryLock, false).map((one) => one.entry),
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
/** Whether the file at `path` is a reservation some live process still holds. */
|
|
188
|
+
export function isHeld(path: string, tryLock: TryLock): boolean {
|
|
189
|
+
let fd: number;
|
|
190
|
+
try {
|
|
191
|
+
fd = openSync(path, 'r');
|
|
192
|
+
} catch {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
return !tryLock(fd);
|
|
197
|
+
} finally {
|
|
198
|
+
closeSync(fd);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Created under a temp name, locked, THEN renamed in: no live entry is ever visible unlocked. */
|
|
203
|
+
function createEntry(root: string, sub: string, name: string, entry: LedgerEntry, lock: TryLock) {
|
|
204
|
+
const temp = join(root, `tmp-${name}`);
|
|
205
|
+
const fd = openSync(temp, 'wx');
|
|
206
|
+
if (!lock(fd)) {
|
|
207
|
+
closeSync(fd);
|
|
208
|
+
unlinkQuiet(temp);
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
writeSync(fd, JSON.stringify(entry));
|
|
212
|
+
const path = join(root, sub, name);
|
|
213
|
+
renameSync(temp, path);
|
|
214
|
+
// Unlink before close: the lock must outlast the file, or a sweeper could judge it dead.
|
|
215
|
+
return {
|
|
216
|
+
path,
|
|
217
|
+
fd,
|
|
218
|
+
release: once(() => {
|
|
219
|
+
unlinkQuiet(path);
|
|
220
|
+
closeSync(fd);
|
|
221
|
+
}),
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function sweepTemps(root: string, now: number): void {
|
|
226
|
+
for (const name of readdirSync(root)) {
|
|
227
|
+
if (!name.startsWith('tmp-')) continue;
|
|
228
|
+
const path = join(root, name);
|
|
229
|
+
try {
|
|
230
|
+
if (now - statSync(path).mtimeMs > STALE_TEMP_MS) unlinkQuiet(path);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (codeOf(error) !== 'ENOENT') throw error;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** A short exclusive lock on `path`, or nothing when another descriptor has it. */
|
|
238
|
+
export function tryLockPath(path: string, label: string, tryLock: TryLock): Held | undefined {
|
|
239
|
+
const fd = openSync(path, 'a');
|
|
240
|
+
let held = false;
|
|
241
|
+
try {
|
|
242
|
+
held = tryLock(fd);
|
|
243
|
+
} finally {
|
|
244
|
+
if (!held) closeSync(fd);
|
|
245
|
+
}
|
|
246
|
+
if (!held) return undefined;
|
|
247
|
+
ftruncateSync(fd, 0);
|
|
248
|
+
writeSync(fd, `pid ${String(process.pid)}: ${label}\n`);
|
|
249
|
+
return { path, fd, release: once(() => closeSync(fd)) };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Wait for `path`. `onWait` is told once, with whoever the file names as its holder. */
|
|
253
|
+
export async function lockPath(
|
|
254
|
+
path: string,
|
|
255
|
+
label: string,
|
|
256
|
+
tryLock: TryLock,
|
|
257
|
+
onWait?: (holder: string) => void,
|
|
258
|
+
pollMs: number = LEDGER_POLL_MS,
|
|
259
|
+
): Promise<Held> {
|
|
260
|
+
let told = false;
|
|
261
|
+
for (;;) {
|
|
262
|
+
const held = tryLockPath(path, label, tryLock);
|
|
263
|
+
if (held !== undefined) return held;
|
|
264
|
+
if (!told) {
|
|
265
|
+
told = true;
|
|
266
|
+
onWait?.(readFileSync(path, 'utf8').trim() || 'an unnamed holder');
|
|
267
|
+
}
|
|
268
|
+
await Bun.sleep(pollMs);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const unique = (): string => `${String(process.pid)}-${crypto.randomUUID()}`;
|
|
273
|
+
|
|
274
|
+
/** How many units fit now, or 0 when even `min` does not. Too big for the ledger runs alone. */
|
|
275
|
+
export function unitsThatFit(input: {
|
|
276
|
+
readonly capacityMb: number;
|
|
277
|
+
readonly usedMb: number;
|
|
278
|
+
readonly unitMb: number;
|
|
279
|
+
readonly units: number;
|
|
280
|
+
readonly minUnits: number;
|
|
281
|
+
readonly baseMb?: number;
|
|
282
|
+
}): number {
|
|
283
|
+
const { usedMb, unitMb, units } = input;
|
|
284
|
+
const capacityMb = input.capacityMb - (input.baseMb ?? 0);
|
|
285
|
+
const most = Math.max(1, Math.floor(capacityMb / unitMb));
|
|
286
|
+
const want = Math.min(units, most);
|
|
287
|
+
const min = Math.min(input.minUnits, want);
|
|
288
|
+
if (usedMb === 0) return want;
|
|
289
|
+
const fit = Math.min(want, Math.floor((capacityMb - usedMb) / unitMb));
|
|
290
|
+
return fit >= min ? fit : 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Join the queue and return once admitted. First come, first served: only the head may admit, so a
|
|
295
|
+
* big request is never starved by small ones slipping past it. The gate is held for one check at a
|
|
296
|
+
* time and never across a wait, so a head that dies leaves nothing behind.
|
|
297
|
+
*/
|
|
298
|
+
export async function reserve(input: ReserveInput): Promise<Reservation> {
|
|
299
|
+
const { dir, tryLock, capacityMb, unitMb, units } = input;
|
|
300
|
+
const baseMb = input.baseMb ?? 0;
|
|
301
|
+
// A NaN passes `??` and would turn the wait into a spin on the ledger directory.
|
|
302
|
+
const pollMs = Number.isFinite(input.pollMs) ? (input.pollMs as number) : LEDGER_POLL_MS;
|
|
303
|
+
prepareLedger(dir);
|
|
304
|
+
const started = performance.now();
|
|
305
|
+
const base = { pid: process.pid, label: input.label, cwd: input.cwd };
|
|
306
|
+
const name = `${String(Date.now()).padStart(15, '0')}-${unique()}`;
|
|
307
|
+
const ticket = createEntry(
|
|
308
|
+
dir,
|
|
309
|
+
'queue',
|
|
310
|
+
name,
|
|
311
|
+
{ ...base, mb: baseMb + units * unitMb, at: Date.now() },
|
|
312
|
+
tryLock,
|
|
313
|
+
);
|
|
314
|
+
if (ticket === undefined) throw new HeavyLedgerUnavailableError('a new queue file was locked');
|
|
315
|
+
const minUnits = input.minUnits ?? 1;
|
|
316
|
+
let said = '';
|
|
317
|
+
/** When the head started waiting on CPU alone: `CPU_WAIT_LIMIT_MS` is counted from here. */
|
|
318
|
+
let cpuBlockedAt: number | undefined;
|
|
319
|
+
try {
|
|
320
|
+
for (;;) {
|
|
321
|
+
let cpu: CpuReading | undefined;
|
|
322
|
+
const queue = liveEntries(join(dir, 'queue'), tryLock, true);
|
|
323
|
+
const position = queue.findIndex((one) => one.name === name);
|
|
324
|
+
if (position === -1) throw new HeavyLedgerUnavailableError(`${dir} was removed mid-wait`);
|
|
325
|
+
let holds = liveEntries(join(dir, 'holds'), tryLock, position === 0);
|
|
326
|
+
if (position === 0) {
|
|
327
|
+
const gate = tryLockPath(join(dir, 'gate'), input.label, tryLock);
|
|
328
|
+
if (gate !== undefined) {
|
|
329
|
+
try {
|
|
330
|
+
sweepTemps(dir, Date.now());
|
|
331
|
+
// Re-read under the gate: an admission may have landed since the read above.
|
|
332
|
+
holds = liveEntries(join(dir, 'holds'), tryLock, true);
|
|
333
|
+
const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
|
|
334
|
+
const granted = unitsThatFit({ capacityMb, usedMb, unitMb, units, minUnits, baseMb });
|
|
335
|
+
const reading = granted > 0 ? input.cpu?.() : undefined;
|
|
336
|
+
const now = performance.now();
|
|
337
|
+
const verdict = cpuAdmission({
|
|
338
|
+
reading,
|
|
339
|
+
running: holds.length,
|
|
340
|
+
blockedMs: cpuBlockedAt === undefined ? 0 : now - cpuBlockedAt,
|
|
341
|
+
});
|
|
342
|
+
if (granted > 0 && verdict === 'wait') {
|
|
343
|
+
cpuBlockedAt ??= now;
|
|
344
|
+
cpu = reading;
|
|
345
|
+
} else cpuBlockedAt = undefined;
|
|
346
|
+
if (granted > 0 && verdict === 'admit') {
|
|
347
|
+
const mb = baseMb + granted * unitMb;
|
|
348
|
+
const hold = createEntry(
|
|
349
|
+
dir,
|
|
350
|
+
'holds',
|
|
351
|
+
unique(),
|
|
352
|
+
{ ...base, mb, at: Date.now() },
|
|
353
|
+
tryLock,
|
|
354
|
+
);
|
|
355
|
+
if (hold === undefined) {
|
|
356
|
+
throw new HeavyLedgerUnavailableError('a new reservation file was locked');
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
...hold,
|
|
360
|
+
units: granted,
|
|
361
|
+
mb,
|
|
362
|
+
waitedMs: Math.round(performance.now() - started),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
} finally {
|
|
366
|
+
gate.release();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
|
|
371
|
+
// Behind the head, the queue is held by whatever holds the head: say CPU when that is it.
|
|
372
|
+
if (cpu === undefined && position > 0 && holds.length > 0) {
|
|
373
|
+
const reading = input.cpu?.();
|
|
374
|
+
if (reading?.busy === true) cpu = reading;
|
|
375
|
+
}
|
|
376
|
+
const wait: LedgerWait = {
|
|
377
|
+
needMb: Math.min(baseMb + units * unitMb, capacityMb),
|
|
378
|
+
usedMb,
|
|
379
|
+
capacityMb,
|
|
380
|
+
position: position + 1,
|
|
381
|
+
queued: queue.length,
|
|
382
|
+
holds: holds.map((one) => one.entry),
|
|
383
|
+
...(cpu === undefined ? {} : { cpu }),
|
|
384
|
+
};
|
|
385
|
+
const key = `${String(position)}|${cpu === undefined ? '' : 'cpu'}|${holds.map((one) => one.name).join(',')}`;
|
|
386
|
+
if (key !== said) {
|
|
387
|
+
said = key;
|
|
388
|
+
input.onWait?.(wait);
|
|
389
|
+
}
|
|
390
|
+
const { maxWaitMs } = input;
|
|
391
|
+
const left = (maxWaitMs ?? Number.POSITIVE_INFINITY) - (performance.now() - started);
|
|
392
|
+
if (maxWaitMs !== undefined && left <= 0) {
|
|
393
|
+
throw new HeavyWaitExpiredError({ label: input.label, maxWaitMs, wait });
|
|
394
|
+
}
|
|
395
|
+
await Bun.sleep(Math.min(pollMs, left));
|
|
396
|
+
}
|
|
397
|
+
} finally {
|
|
398
|
+
ticket.release();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// What the ledger may admit: half of the memory this process can really use. `totalmem()` is the
|
|
2
|
+
// host's figure, so inside a capped cgroup it plans for memory the kernel will never grant; the
|
|
3
|
+
// binding limit is the smallest `memory.max` along this process's own cgroup-v2 ancestry.
|
|
4
|
+
|
|
5
|
+
// why: Bun ships no synchronous file read, and `/proc` and `/sys` must be read at their real size.
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
// why: Bun exposes no total-memory or free-memory primitive.
|
|
8
|
+
import { freemem, totalmem } from 'node:os';
|
|
9
|
+
import type { HeavyEnv } from './heavy-env';
|
|
10
|
+
import { HEAVY_MEMORY_ENV } from './heavy-env';
|
|
11
|
+
import { HeavyMemoryInvalidError } from './heavy-errors';
|
|
12
|
+
import { parseBytes } from './test-workers';
|
|
13
|
+
|
|
14
|
+
/** RAM's other half stays for the agent sessions, editors and servers no ledger can see. */
|
|
15
|
+
export const LEDGER_SHARE = 0.5;
|
|
16
|
+
|
|
17
|
+
const CGROUP_ROOT = '/sys/fs/cgroup';
|
|
18
|
+
const MIB = 2 ** 20;
|
|
19
|
+
|
|
20
|
+
export type ReadFile = (path: string) => string | undefined;
|
|
21
|
+
|
|
22
|
+
const readOrNothing: ReadFile = (path) => {
|
|
23
|
+
try {
|
|
24
|
+
return readFileSync(path, 'utf8');
|
|
25
|
+
} catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** The smallest numeric `memory.max` from the mount root down to this process's cgroup. */
|
|
31
|
+
export function cgroupLimitBytes(read: ReadFile = readOrNothing): number | undefined {
|
|
32
|
+
const line = read('/proc/self/cgroup')
|
|
33
|
+
?.split('\n')
|
|
34
|
+
.find((candidate) => candidate.startsWith('0::'));
|
|
35
|
+
if (line === undefined) return undefined;
|
|
36
|
+
const limits: number[] = [];
|
|
37
|
+
let dir = CGROUP_ROOT;
|
|
38
|
+
// The root counts: inside a container the namespace shows `/` and the limit sits on the mount.
|
|
39
|
+
for (const part of ['', ...line.slice(3).trim().split('/').filter(Boolean)]) {
|
|
40
|
+
if (part !== '') dir = `${dir}/${part}`;
|
|
41
|
+
const raw = read(`${dir}/memory.max`)?.trim();
|
|
42
|
+
if (raw !== undefined && /^\d+$/.test(raw)) limits.push(Number(raw));
|
|
43
|
+
}
|
|
44
|
+
return limits.length === 0 ? undefined : Math.min(...limits);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The machine as this process may use it, bytes. */
|
|
48
|
+
export const usableMemoryBytes = (
|
|
49
|
+
host: number = totalmem(),
|
|
50
|
+
limit: number | undefined = cgroupLimitBytes(),
|
|
51
|
+
): number => (limit === undefined ? host : Math.min(host, limit));
|
|
52
|
+
|
|
53
|
+
/** MB the ledger admits; 0 means it is off. Throws `X_HEAVY_MEMORY_INVALID` on a bad override. */
|
|
54
|
+
export function ledgerCapacityMb(env: HeavyEnv, usable: number = usableMemoryBytes()): number {
|
|
55
|
+
const raw = env[HEAVY_MEMORY_ENV]?.trim();
|
|
56
|
+
if (raw === undefined || raw === '') return Math.floor((usable * LEDGER_SHARE) / MIB);
|
|
57
|
+
if (raw === '0') return 0;
|
|
58
|
+
const bytes = parseBytes(raw);
|
|
59
|
+
if (bytes === undefined) throw new HeavyMemoryInvalidError(raw);
|
|
60
|
+
return Math.max(1, Math.floor(bytes / MIB));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Memory a new process could get now: `MemAvailable` where Linux reports it. */
|
|
64
|
+
export function availableMemoryBytes(read: ReadFile = readOrNothing): number {
|
|
65
|
+
const match = /^MemAvailable:\s+(\d+) kB/m.exec(read('/proc/meminfo') ?? '');
|
|
66
|
+
return match === null ? freemem() : Number(match[1]) * 1024;
|
|
67
|
+
}
|