@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.e83e5bc6ecce
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 -2
- package/dist/bridge/bridge.service.d.ts +5 -1
- package/dist/bridge/bridge.service.js +40 -6
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.service.js +10 -2
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +172 -0
- package/dist/runtime/host-load-governor.js +519 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-sampler.d.ts +126 -0
- package/dist/runtime/host-load-sampler.js +232 -0
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +4 -0
- package/dist/runtime/host-runtime-contract.js +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +17 -3
- package/dist/runtime/host-runtime-lease.js +83 -4
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +98 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +25 -12
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +44 -59
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
- package/dist/session/provider-cli/provider-cli.process.js +122 -30
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
- package/dist/session/provider-cli/provider-cli.service.js +134 -30
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +21 -4
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +14 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
|
+
import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
|
|
3
|
+
import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
4
|
+
import type { HostLoadGovernorSource } from "./host-load-sampler.js";
|
|
5
|
+
import type { HostLoadStepCost } from "./host-load-step-class.js";
|
|
6
|
+
import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
|
|
7
|
+
import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
|
|
8
|
+
export interface HostLoadStepRequest {
|
|
9
|
+
readonly stepClass: string;
|
|
10
|
+
/** What the step is, for diagnostics (for example the validation check id). */
|
|
11
|
+
readonly label: string;
|
|
12
|
+
readonly cost: HostLoadStepCost;
|
|
13
|
+
readonly dispatchAttemptId: string | null;
|
|
14
|
+
readonly priority: HostLoadTokenPriority;
|
|
15
|
+
}
|
|
16
|
+
export interface HostLoadAcquireOptions {
|
|
17
|
+
readonly signal?: AbortSignal;
|
|
18
|
+
/** Called once, when the first admission decision says the step must wait. */
|
|
19
|
+
readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export interface HostLoadAdmission {
|
|
22
|
+
readonly tokenId: string;
|
|
23
|
+
readonly fencingToken: number;
|
|
24
|
+
readonly stepClass: string;
|
|
25
|
+
/** Time spent queued; never counted as step execution time. */
|
|
26
|
+
readonly waitMs: number;
|
|
27
|
+
readonly decision: HostLoadAdmissionDecision;
|
|
28
|
+
/**
|
|
29
|
+
* Aborted when the reservation is lost while the step runs: with
|
|
30
|
+
* host_capacity_token_fenced when the token was fenced (this owner stalled
|
|
31
|
+
* past its lease and another process saw it), or with
|
|
32
|
+
* host_capacity_ledger_unavailable when it could not be renewed for a whole
|
|
33
|
+
* lease. The step must stop; the token keeps its cost until it is released.
|
|
34
|
+
*/
|
|
35
|
+
readonly fenced: AbortSignal;
|
|
36
|
+
/** Records the step's process tree, so a reclaim stops it before reusing its capacity. */
|
|
37
|
+
attachProcess(stepProcess: HostLoadStepProcess): Promise<void>;
|
|
38
|
+
/** Returns the token. Rejects with host_capacity_token_fenced if it was fenced or reclaimed. */
|
|
39
|
+
release(): Promise<void>;
|
|
40
|
+
/**
|
|
41
|
+
* Instead of release: the step ended but part of its process tree could not
|
|
42
|
+
* be proven gone. The token stays held, with its cost, and is returned only
|
|
43
|
+
* once `stillGone` (re-checked on every renewal) resolves true. Without a
|
|
44
|
+
* check, the token's recorded process tree is checked instead; with neither,
|
|
45
|
+
* the token is kept until attempt teardown has stopped the attempt's processes.
|
|
46
|
+
*/
|
|
47
|
+
retainUntilStopped(stillGone: (() => Promise<boolean>) | null, reason: Error): void;
|
|
48
|
+
}
|
|
49
|
+
/** The gate heavy steps call before launching. */
|
|
50
|
+
export interface HostLoadStepGate {
|
|
51
|
+
readonly enabled: boolean;
|
|
52
|
+
/** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
|
|
53
|
+
readonly maxWaitMs?: number;
|
|
54
|
+
acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
|
|
55
|
+
}
|
|
56
|
+
export declare class HostCapacityTimeoutError extends ForgeFailureError {
|
|
57
|
+
readonly stepClass: string;
|
|
58
|
+
readonly label: string;
|
|
59
|
+
readonly waitMs: number;
|
|
60
|
+
readonly code = "host_capacity_timeout";
|
|
61
|
+
constructor(stepClass: string, label: string, waitMs: number, detail: string);
|
|
62
|
+
}
|
|
63
|
+
export interface HostLoadGovernorOptions {
|
|
64
|
+
readonly stateRoot: string;
|
|
65
|
+
readonly load: HostLoadGovernorSource;
|
|
66
|
+
readonly config?: HostLoadGovernorConfig;
|
|
67
|
+
readonly liveness?: HostLoadOwnerLiveness;
|
|
68
|
+
/** Owner recorded on tokens (tests model separate processes); defaults to this process. */
|
|
69
|
+
readonly owner?: HostLoadTokenOwner;
|
|
70
|
+
readonly now?: () => number;
|
|
71
|
+
/** Test seam for the ledger's process-tree reaper. */
|
|
72
|
+
readonly terminateStep?: HostLoadStepTerminator;
|
|
73
|
+
/** Test seam for the host suspend counter. */
|
|
74
|
+
readonly suspendedMs?: () => number;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Host-wide admission for heavy steps (decision 0013). Waiters queue
|
|
78
|
+
* foreground before background and FIFO within a class; a waiter that fits may
|
|
79
|
+
* overtake an unfit head until the head has waited past the anti-starvation
|
|
80
|
+
* window. Running steps are never preempted. Reserved cost comes from the
|
|
81
|
+
* shared token ledger, so other processes' steps count against the same budget.
|
|
82
|
+
*/
|
|
83
|
+
export declare class HostLoadGovernor implements HostLoadStepGate {
|
|
84
|
+
private readonly options;
|
|
85
|
+
readonly enabled: boolean;
|
|
86
|
+
private readonly config;
|
|
87
|
+
private readonly ledger;
|
|
88
|
+
private readonly waiters;
|
|
89
|
+
private readonly held;
|
|
90
|
+
private recheckTimer;
|
|
91
|
+
private renewTimer;
|
|
92
|
+
private draining;
|
|
93
|
+
private drainAgain;
|
|
94
|
+
/** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
|
|
95
|
+
private idleOwnMemoryBytes;
|
|
96
|
+
constructor(options: HostLoadGovernorOptions);
|
|
97
|
+
get maxWaitMs(): number;
|
|
98
|
+
acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
|
|
99
|
+
/** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
|
|
100
|
+
reclaim(): Promise<readonly HostLoadToken[]>;
|
|
101
|
+
/** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
|
|
102
|
+
releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
|
|
103
|
+
/**
|
|
104
|
+
* Attempt teardown: cancels the attempt's queued steps and stops its running
|
|
105
|
+
* ones (their `fenced` signal aborts with dispatch_cancelled). A running step
|
|
106
|
+
* keeps its token, and its cost, until the step itself returns it once its
|
|
107
|
+
* processes are gone, so the capacity is never reused while it still runs.
|
|
108
|
+
*/
|
|
109
|
+
stopAttempt(dispatchAttemptId: string): void;
|
|
110
|
+
/**
|
|
111
|
+
* Cancels the attempt's queued steps and returns every token it holds at
|
|
112
|
+
* once. Only for callers that know the attempt's steps are no longer running;
|
|
113
|
+
* attempt teardown uses stopAttempt.
|
|
114
|
+
*/
|
|
115
|
+
releaseAttempt(dispatchAttemptId: string): Promise<void>;
|
|
116
|
+
private cancelAttemptWaiters;
|
|
117
|
+
/** Waiting and admitted steps of this process, for diagnostics. */
|
|
118
|
+
snapshot(): {
|
|
119
|
+
readonly waiting: number;
|
|
120
|
+
readonly held: readonly HostLoadToken[];
|
|
121
|
+
};
|
|
122
|
+
private drain;
|
|
123
|
+
private drainOnce;
|
|
124
|
+
private readSignals;
|
|
125
|
+
/**
|
|
126
|
+
* Consecutive pressured samples ending with the latest one, read from the
|
|
127
|
+
* sampler's history so samples taken while nothing waited still count. A gap
|
|
128
|
+
* in sampling (sampler stopped, host suspended) breaks the streak.
|
|
129
|
+
*/
|
|
130
|
+
private pressureStreak;
|
|
131
|
+
/**
|
|
132
|
+
* Memory the running steps already use, which MemAvailable already reflects,
|
|
133
|
+
* so the budget does not count it twice. Measured from the dedicated cgroup
|
|
134
|
+
* above its idle baseline; without one, a step admitted longer than the ramp
|
|
135
|
+
* window ago is assumed to hold its reservation. Never above the reservations.
|
|
136
|
+
*/
|
|
137
|
+
private runningStepsMemoryBytes;
|
|
138
|
+
private logicalCpus;
|
|
139
|
+
private settle;
|
|
140
|
+
/** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
|
|
141
|
+
private applyHeldOutcome;
|
|
142
|
+
/** The step must stop: its reservation is no longer guaranteed. */
|
|
143
|
+
private lose;
|
|
144
|
+
/** Ledger failures reach every queued step instead of leaving it to time out. */
|
|
145
|
+
private failWaiters;
|
|
146
|
+
private attachProcess;
|
|
147
|
+
/**
|
|
148
|
+
* Returns a step's token. It stays held (and renewed) until the ledger takes
|
|
149
|
+
* it back, so a ledger outage cannot leave it to lapse into a fenced
|
|
150
|
+
* reservation; the renewal timer retries the release. A fenced token is
|
|
151
|
+
* removed too (its step is over) and the release reports the fence.
|
|
152
|
+
*/
|
|
153
|
+
private releaseHeld;
|
|
154
|
+
private forget;
|
|
155
|
+
private armRecheck;
|
|
156
|
+
private disarmRecheck;
|
|
157
|
+
private armRenewal;
|
|
158
|
+
private disarmRenewal;
|
|
159
|
+
/**
|
|
160
|
+
* The step ended but part of its process tree may still run: its token stays
|
|
161
|
+
* held and renewed, with its cost, and the step's own termination check is
|
|
162
|
+
* retried on every renewal tick until it proves the tree gone.
|
|
163
|
+
*/
|
|
164
|
+
private retainUntilStopped;
|
|
165
|
+
/**
|
|
166
|
+
* Attempt teardown stopped the attempt's processes (its process supervisor
|
|
167
|
+
* proved them gone): tokens kept for a tree nothing else can check are returned.
|
|
168
|
+
*/
|
|
169
|
+
releaseRetainedAfterTeardown(dispatchAttemptId: string): Promise<void>;
|
|
170
|
+
private checkRetained;
|
|
171
|
+
private renewHeld;
|
|
172
|
+
}
|
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
3
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
4
|
+
import { decideHostLoadAdmission, } from "./host-load-admission.js";
|
|
5
|
+
import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
6
|
+
import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
|
|
7
|
+
import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
|
|
8
|
+
import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
|
|
9
|
+
export class HostCapacityTimeoutError extends ForgeFailureError {
|
|
10
|
+
stepClass;
|
|
11
|
+
label;
|
|
12
|
+
waitMs;
|
|
13
|
+
code = "host_capacity_timeout";
|
|
14
|
+
constructor(stepClass, label, waitMs, detail) {
|
|
15
|
+
super("host_capacity_timeout", `host_capacity_timeout: ${label} (${stepClass}) waited ${Math.round(waitMs / 1000)}s for host capacity without being admitted: ${detail} This is a retryable host-load condition, not a test failure.`, "bridge");
|
|
16
|
+
this.stepClass = stepClass;
|
|
17
|
+
this.label = label;
|
|
18
|
+
this.waitMs = waitMs;
|
|
19
|
+
this.name = "HostCapacityTimeoutError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Host-wide admission for heavy steps (decision 0013). Waiters queue
|
|
24
|
+
* foreground before background and FIFO within a class; a waiter that fits may
|
|
25
|
+
* overtake an unfit head until the head has waited past the anti-starvation
|
|
26
|
+
* window. Running steps are never preempted. Reserved cost comes from the
|
|
27
|
+
* shared token ledger, so other processes' steps count against the same budget.
|
|
28
|
+
*/
|
|
29
|
+
export class HostLoadGovernor {
|
|
30
|
+
options;
|
|
31
|
+
enabled;
|
|
32
|
+
config;
|
|
33
|
+
ledger;
|
|
34
|
+
waiters = [];
|
|
35
|
+
held = new Map();
|
|
36
|
+
recheckTimer = null;
|
|
37
|
+
renewTimer = null;
|
|
38
|
+
draining = null;
|
|
39
|
+
drainAgain = false;
|
|
40
|
+
/** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
|
|
41
|
+
idleOwnMemoryBytes = null;
|
|
42
|
+
constructor(options) {
|
|
43
|
+
this.options = options;
|
|
44
|
+
this.config = options.config ?? loadHostLoadGovernorConfig();
|
|
45
|
+
this.enabled = this.config.mode === "on";
|
|
46
|
+
this.ledger = new HostLoadTokenLedger({
|
|
47
|
+
stateRoot: options.stateRoot,
|
|
48
|
+
leaseMs: this.config.leaseMs,
|
|
49
|
+
now: options.now,
|
|
50
|
+
liveness: options.liveness,
|
|
51
|
+
owner: options.owner,
|
|
52
|
+
terminateStep: options.terminateStep,
|
|
53
|
+
suspendedMs: options.suspendedMs,
|
|
54
|
+
// Every ledger transaction renews the steps this governor is running.
|
|
55
|
+
heldTokens: () => [...this.held.values()].map(entry => entry.token),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
get maxWaitMs() {
|
|
59
|
+
return this.config.maxWaitMs;
|
|
60
|
+
}
|
|
61
|
+
async acquire(request, options = {}) {
|
|
62
|
+
if (!this.enabled)
|
|
63
|
+
throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
|
|
64
|
+
const { signal } = options;
|
|
65
|
+
if (signal?.aborted)
|
|
66
|
+
throw abortError(signal);
|
|
67
|
+
await this.options.load.start().catch(() => undefined);
|
|
68
|
+
if (signal?.aborted)
|
|
69
|
+
throw abortError(signal);
|
|
70
|
+
return await new Promise((resolve, reject) => {
|
|
71
|
+
const waiter = {
|
|
72
|
+
request,
|
|
73
|
+
enqueuedAtMs: monotonicNowMs(),
|
|
74
|
+
signal,
|
|
75
|
+
onWaiting: options.onWaiting,
|
|
76
|
+
resolve,
|
|
77
|
+
reject,
|
|
78
|
+
abort: () => this.settle(waiter, () => reject(abortError(signal))),
|
|
79
|
+
deadline: null,
|
|
80
|
+
lastDecision: null,
|
|
81
|
+
settled: false,
|
|
82
|
+
};
|
|
83
|
+
waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
|
|
84
|
+
waiter.deadline.unref?.();
|
|
85
|
+
signal?.addEventListener("abort", waiter.abort, { once: true });
|
|
86
|
+
// Foreground goes ahead of background, except background that has already
|
|
87
|
+
// waited past the anti-starvation window: steady foreground load cannot starve it.
|
|
88
|
+
const backgroundIndex = request.priority === "foreground"
|
|
89
|
+
? this.waiters.findIndex(candidate => candidate.request.priority === "background"
|
|
90
|
+
&& waiter.enqueuedAtMs - candidate.enqueuedAtMs < this.config.antiStarvationMs)
|
|
91
|
+
: -1;
|
|
92
|
+
if (backgroundIndex < 0)
|
|
93
|
+
this.waiters.push(waiter);
|
|
94
|
+
else
|
|
95
|
+
this.waiters.splice(backgroundIndex, 0, waiter);
|
|
96
|
+
this.armRecheck();
|
|
97
|
+
void this.drain();
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
/** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
|
|
101
|
+
async reclaim() {
|
|
102
|
+
if (!this.enabled)
|
|
103
|
+
return [];
|
|
104
|
+
const outcome = await this.ledger.transaction(() => undefined);
|
|
105
|
+
this.applyHeldOutcome(outcome);
|
|
106
|
+
if (outcome.reclaimed.length > 0)
|
|
107
|
+
void this.drain();
|
|
108
|
+
return outcome.reclaimed;
|
|
109
|
+
}
|
|
110
|
+
/** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
|
|
111
|
+
async releaseOrphaned(belongs) {
|
|
112
|
+
if (!this.enabled)
|
|
113
|
+
return [];
|
|
114
|
+
const released = await this.ledger.releaseOrphaned(belongs);
|
|
115
|
+
if (released.length > 0)
|
|
116
|
+
void this.drain();
|
|
117
|
+
return released;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Attempt teardown: cancels the attempt's queued steps and stops its running
|
|
121
|
+
* ones (their `fenced` signal aborts with dispatch_cancelled). A running step
|
|
122
|
+
* keeps its token, and its cost, until the step itself returns it once its
|
|
123
|
+
* processes are gone, so the capacity is never reused while it still runs.
|
|
124
|
+
*/
|
|
125
|
+
stopAttempt(dispatchAttemptId) {
|
|
126
|
+
if (!this.enabled)
|
|
127
|
+
return;
|
|
128
|
+
this.cancelAttemptWaiters(dispatchAttemptId);
|
|
129
|
+
for (const entry of this.held.values()) {
|
|
130
|
+
if (entry.token.dispatchAttemptId !== dispatchAttemptId)
|
|
131
|
+
continue;
|
|
132
|
+
this.lose(entry, new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while this step ran; it was stopped before its host capacity was returned.", "bridge"));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Cancels the attempt's queued steps and returns every token it holds at
|
|
137
|
+
* once. Only for callers that know the attempt's steps are no longer running;
|
|
138
|
+
* attempt teardown uses stopAttempt.
|
|
139
|
+
*/
|
|
140
|
+
async releaseAttempt(dispatchAttemptId) {
|
|
141
|
+
if (!this.enabled)
|
|
142
|
+
return;
|
|
143
|
+
this.cancelAttemptWaiters(dispatchAttemptId);
|
|
144
|
+
const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
|
|
145
|
+
await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
|
|
146
|
+
}
|
|
147
|
+
cancelAttemptWaiters(dispatchAttemptId) {
|
|
148
|
+
for (const waiter of [...this.waiters]) {
|
|
149
|
+
if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
|
|
150
|
+
continue;
|
|
151
|
+
this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** Waiting and admitted steps of this process, for diagnostics. */
|
|
155
|
+
snapshot() {
|
|
156
|
+
return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
|
|
157
|
+
}
|
|
158
|
+
async drain() {
|
|
159
|
+
if (this.draining) {
|
|
160
|
+
this.drainAgain = true;
|
|
161
|
+
return await this.draining;
|
|
162
|
+
}
|
|
163
|
+
this.draining = (async () => {
|
|
164
|
+
do {
|
|
165
|
+
this.drainAgain = false;
|
|
166
|
+
await this.drainOnce().catch(error => this.failWaiters(error));
|
|
167
|
+
} while (this.drainAgain && this.waiters.length > 0);
|
|
168
|
+
})().finally(() => {
|
|
169
|
+
this.draining = null;
|
|
170
|
+
});
|
|
171
|
+
return await this.draining;
|
|
172
|
+
}
|
|
173
|
+
async drainOnce() {
|
|
174
|
+
if (this.waiters.length === 0)
|
|
175
|
+
return;
|
|
176
|
+
const signals = this.readSignals();
|
|
177
|
+
const logicalCpus = this.logicalCpus();
|
|
178
|
+
const nowMs = monotonicNowMs();
|
|
179
|
+
const outcomes = [];
|
|
180
|
+
const outcome = await this.ledger.transaction(transaction => {
|
|
181
|
+
const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
|
|
182
|
+
const head = this.waiters[0];
|
|
183
|
+
const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
|
|
184
|
+
for (const waiter of this.waiters) {
|
|
185
|
+
if (waiter.settled)
|
|
186
|
+
continue;
|
|
187
|
+
const computed = decideHostLoadAdmission({
|
|
188
|
+
request: waiter.request.cost,
|
|
189
|
+
running: transaction.tokens.map(token => token.cost),
|
|
190
|
+
runningMemoryBytes,
|
|
191
|
+
logicalCpus,
|
|
192
|
+
signals,
|
|
193
|
+
config: this.config,
|
|
194
|
+
});
|
|
195
|
+
const decision = transaction.recoveringUntil
|
|
196
|
+
? {
|
|
197
|
+
...computed,
|
|
198
|
+
admitted: false,
|
|
199
|
+
reason: "ledger_recovering",
|
|
200
|
+
detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
|
|
201
|
+
}
|
|
202
|
+
: computed;
|
|
203
|
+
outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
|
|
204
|
+
// A starving head blocks the queue so running steps drain and it can start.
|
|
205
|
+
if (waiter === head && headStarving && !decision.admitted)
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
this.applyHeldOutcome(outcome);
|
|
210
|
+
for (const { waiter, token, decision } of outcomes) {
|
|
211
|
+
if (!token) {
|
|
212
|
+
const first = waiter.lastDecision === null;
|
|
213
|
+
waiter.lastDecision = decision;
|
|
214
|
+
if (first && !waiter.settled)
|
|
215
|
+
void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const entry = {
|
|
219
|
+
token,
|
|
220
|
+
fencedController: new AbortController(),
|
|
221
|
+
fencedError: null,
|
|
222
|
+
renewedAtMs: monotonicNowMs(),
|
|
223
|
+
releasing: false,
|
|
224
|
+
releaseInFlight: null,
|
|
225
|
+
gone: false,
|
|
226
|
+
retainedUntil: null,
|
|
227
|
+
retainCheck: null,
|
|
228
|
+
};
|
|
229
|
+
this.held.set(token.tokenId, entry);
|
|
230
|
+
this.armRenewal();
|
|
231
|
+
if (waiter.settled) {
|
|
232
|
+
// Cancelled or timed out while the decision was being made.
|
|
233
|
+
void this.releaseHeld(entry).catch(() => undefined);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
const waitMs = Math.max(0, monotonicNowMs() - waiter.enqueuedAtMs);
|
|
237
|
+
this.settle(waiter, () => waiter.resolve({
|
|
238
|
+
tokenId: token.tokenId,
|
|
239
|
+
fencingToken: token.fencingToken,
|
|
240
|
+
stepClass: token.stepClass,
|
|
241
|
+
waitMs,
|
|
242
|
+
decision,
|
|
243
|
+
fenced: entry.fencedController.signal,
|
|
244
|
+
attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
|
|
245
|
+
release: () => this.releaseHeld(entry),
|
|
246
|
+
retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
|
|
247
|
+
}));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
readSignals() {
|
|
251
|
+
const snapshot = this.options.load.current();
|
|
252
|
+
const cpu = snapshot?.systemPressure?.cpu?.some;
|
|
253
|
+
const sampledAtMs = snapshot ? Date.parse(snapshot.sampledAt) : Number.NaN;
|
|
254
|
+
const now = this.options.now?.() ?? Date.now();
|
|
255
|
+
if (!snapshot?.psiAvailable || !cpu || !Number.isFinite(sampledAtMs) || now - sampledAtMs > this.config.sampleStaleMs) {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
// Own-cgroup numbers are trusted only for a dedicated cgroup (step 1's ownCgroupDedicated).
|
|
259
|
+
const attribution = snapshot.ownCgroupDedicated ? this.options.load.cpuAttribution?.() ?? null : null;
|
|
260
|
+
return {
|
|
261
|
+
cpuSomeAvg10: cpu.avg10,
|
|
262
|
+
cpuPressuredSamples: this.pressureStreak(sampledAtMs, cpu.avg10),
|
|
263
|
+
memoryFullAvg10: snapshot.systemPressure?.memory?.full?.avg10 ?? null,
|
|
264
|
+
memoryAvailableBytes: tighterMemory(snapshot.memoryAvailableBytes, this.options.load.cgroupMemoryHeadroomBytes?.() ?? null),
|
|
265
|
+
externalCpuCores: attribution?.sampledAt === snapshot.sampledAt ? attribution.externalCoresInUse : null,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Consecutive pressured samples ending with the latest one, read from the
|
|
270
|
+
* sampler's history so samples taken while nothing waited still count. A gap
|
|
271
|
+
* in sampling (sampler stopped, host suspended) breaks the streak.
|
|
272
|
+
*/
|
|
273
|
+
pressureStreak(latestAtMs, latestAvg10) {
|
|
274
|
+
if (latestAvg10 < this.config.cpuPressureThreshold)
|
|
275
|
+
return 0;
|
|
276
|
+
let streak = 1;
|
|
277
|
+
let laterAtMs = latestAtMs;
|
|
278
|
+
const history = this.options.load.recent();
|
|
279
|
+
for (let index = history.length - 1; index >= 0 && streak < this.config.backpressureSamples; index -= 1) {
|
|
280
|
+
const sample = history[index];
|
|
281
|
+
const atMs = Date.parse(sample.sampledAt);
|
|
282
|
+
if (!Number.isFinite(atMs) || atMs >= laterAtMs)
|
|
283
|
+
continue;
|
|
284
|
+
if (laterAtMs - atMs > this.config.sampleIntervalMs * 1.5)
|
|
285
|
+
break;
|
|
286
|
+
const avg10 = sample.psiAvailable ? sample.systemPressure?.cpu?.some?.avg10 : undefined;
|
|
287
|
+
if (avg10 === undefined || avg10 < this.config.cpuPressureThreshold)
|
|
288
|
+
break;
|
|
289
|
+
streak += 1;
|
|
290
|
+
laterAtMs = atMs;
|
|
291
|
+
}
|
|
292
|
+
return streak;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Memory the running steps already use, which MemAvailable already reflects,
|
|
296
|
+
* so the budget does not count it twice. Measured from the dedicated cgroup
|
|
297
|
+
* above its idle baseline; without one, a step admitted longer than the ramp
|
|
298
|
+
* window ago is assumed to hold its reservation. Never above the reservations.
|
|
299
|
+
*/
|
|
300
|
+
runningStepsMemoryBytes(tokens) {
|
|
301
|
+
const snapshot = this.options.load.current();
|
|
302
|
+
const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
|
|
303
|
+
if (tokens.length === 0) {
|
|
304
|
+
if (ownMemory !== null)
|
|
305
|
+
this.idleOwnMemoryBytes = ownMemory;
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
308
|
+
const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
|
|
309
|
+
if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
|
|
310
|
+
return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
|
|
311
|
+
}
|
|
312
|
+
const now = this.options.now?.() ?? Date.now();
|
|
313
|
+
return tokens
|
|
314
|
+
.filter(token => now - Date.parse(token.admittedAt) >= this.config.memoryRampMs)
|
|
315
|
+
.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
|
|
316
|
+
}
|
|
317
|
+
logicalCpus() {
|
|
318
|
+
const reported = this.options.load.facts()?.logicalThreads;
|
|
319
|
+
if (reported && reported > 0)
|
|
320
|
+
return reported;
|
|
321
|
+
return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
|
|
322
|
+
}
|
|
323
|
+
settle(waiter, complete) {
|
|
324
|
+
if (waiter.settled)
|
|
325
|
+
return;
|
|
326
|
+
waiter.settled = true;
|
|
327
|
+
if (waiter.deadline)
|
|
328
|
+
clearTimeout(waiter.deadline);
|
|
329
|
+
waiter.signal?.removeEventListener("abort", waiter.abort);
|
|
330
|
+
const index = this.waiters.indexOf(waiter);
|
|
331
|
+
if (index >= 0)
|
|
332
|
+
this.waiters.splice(index, 1);
|
|
333
|
+
if (this.waiters.length === 0)
|
|
334
|
+
this.disarmRecheck();
|
|
335
|
+
complete();
|
|
336
|
+
}
|
|
337
|
+
/** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
|
|
338
|
+
applyHeldOutcome(outcome) {
|
|
339
|
+
const nowMs = monotonicNowMs();
|
|
340
|
+
for (const token of outcome.renewed) {
|
|
341
|
+
const entry = this.held.get(token.tokenId);
|
|
342
|
+
if (entry?.token.fencingToken === token.fencingToken)
|
|
343
|
+
entry.renewedAtMs = nowMs;
|
|
344
|
+
}
|
|
345
|
+
for (const token of outcome.fenced) {
|
|
346
|
+
const entry = this.held.get(token.tokenId);
|
|
347
|
+
if (!entry || entry.token.fencingToken !== token.fencingToken)
|
|
348
|
+
continue;
|
|
349
|
+
entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
|
|
350
|
+
this.lose(entry, entry.fencedError);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** The step must stop: its reservation is no longer guaranteed. */
|
|
354
|
+
lose(entry, reason) {
|
|
355
|
+
if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
|
|
356
|
+
return;
|
|
357
|
+
entry.fencedController.abort(reason);
|
|
358
|
+
}
|
|
359
|
+
/** Ledger failures reach every queued step instead of leaving it to time out. */
|
|
360
|
+
failWaiters(error) {
|
|
361
|
+
const failure = error instanceof HostCapacityLedgerUnavailableError
|
|
362
|
+
? error
|
|
363
|
+
: new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
364
|
+
for (const waiter of [...this.waiters])
|
|
365
|
+
this.settle(waiter, () => waiter.reject(failure));
|
|
366
|
+
}
|
|
367
|
+
async attachProcess(entry, stepProcess) {
|
|
368
|
+
if (entry.fencedError)
|
|
369
|
+
throw entry.fencedError;
|
|
370
|
+
if (entry.gone || entry.releasing)
|
|
371
|
+
return;
|
|
372
|
+
const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
|
|
373
|
+
this.applyHeldOutcome(outcome);
|
|
374
|
+
if (outcome.result)
|
|
375
|
+
entry.token = outcome.result;
|
|
376
|
+
else
|
|
377
|
+
throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Returns a step's token. It stays held (and renewed) until the ledger takes
|
|
381
|
+
* it back, so a ledger outage cannot leave it to lapse into a fenced
|
|
382
|
+
* reservation; the renewal timer retries the release. A fenced token is
|
|
383
|
+
* removed too (its step is over) and the release reports the fence.
|
|
384
|
+
*/
|
|
385
|
+
async releaseHeld(entry) {
|
|
386
|
+
if (entry.gone)
|
|
387
|
+
return;
|
|
388
|
+
entry.releasing = true;
|
|
389
|
+
entry.releaseInFlight ??= (async () => {
|
|
390
|
+
try {
|
|
391
|
+
await this.ledger.release(entry.token.tokenId, entry.token.fencingToken);
|
|
392
|
+
this.forget(entry);
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
if (error instanceof HostCapacityTokenFencedError)
|
|
396
|
+
this.forget(entry);
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
entry.releaseInFlight = null;
|
|
401
|
+
void this.drain();
|
|
402
|
+
}
|
|
403
|
+
})();
|
|
404
|
+
return await entry.releaseInFlight;
|
|
405
|
+
}
|
|
406
|
+
forget(entry) {
|
|
407
|
+
entry.gone = true;
|
|
408
|
+
this.held.delete(entry.token.tokenId);
|
|
409
|
+
if (this.held.size === 0)
|
|
410
|
+
this.disarmRenewal();
|
|
411
|
+
}
|
|
412
|
+
armRecheck() {
|
|
413
|
+
if (this.recheckTimer)
|
|
414
|
+
return;
|
|
415
|
+
// Capacity can return without a local release: another process's token, a
|
|
416
|
+
// new pressure sample, or external load ending.
|
|
417
|
+
this.recheckTimer = setInterval(() => void this.drain(), this.config.recheckIntervalMs);
|
|
418
|
+
this.recheckTimer.unref?.();
|
|
419
|
+
}
|
|
420
|
+
disarmRecheck() {
|
|
421
|
+
if (this.recheckTimer)
|
|
422
|
+
clearInterval(this.recheckTimer);
|
|
423
|
+
this.recheckTimer = null;
|
|
424
|
+
}
|
|
425
|
+
armRenewal() {
|
|
426
|
+
if (this.renewTimer)
|
|
427
|
+
return;
|
|
428
|
+
this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
|
|
429
|
+
this.renewTimer.unref?.();
|
|
430
|
+
}
|
|
431
|
+
disarmRenewal() {
|
|
432
|
+
if (this.renewTimer)
|
|
433
|
+
clearInterval(this.renewTimer);
|
|
434
|
+
this.renewTimer = null;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* The step ended but part of its process tree may still run: its token stays
|
|
438
|
+
* held and renewed, with its cost, and the step's own termination check is
|
|
439
|
+
* retried on every renewal tick until it proves the tree gone.
|
|
440
|
+
*/
|
|
441
|
+
retainUntilStopped(entry, stillGone, reason) {
|
|
442
|
+
if (entry.gone || entry.releasing)
|
|
443
|
+
return;
|
|
444
|
+
this.lose(entry, reason);
|
|
445
|
+
const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
|
|
446
|
+
entry.retainedUntil = stillGone
|
|
447
|
+
// The tree recorded on the token (supervised builds, installs) is stopped and checked.
|
|
448
|
+
?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
|
|
449
|
+
this.armRenewal();
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Attempt teardown stopped the attempt's processes (its process supervisor
|
|
453
|
+
* proved them gone): tokens kept for a tree nothing else can check are returned.
|
|
454
|
+
*/
|
|
455
|
+
async releaseRetainedAfterTeardown(dispatchAttemptId) {
|
|
456
|
+
if (!this.enabled)
|
|
457
|
+
return;
|
|
458
|
+
const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
|
|
459
|
+
for (const entry of settled)
|
|
460
|
+
entry.retainedUntil = null;
|
|
461
|
+
await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
|
|
462
|
+
}
|
|
463
|
+
checkRetained(entry) {
|
|
464
|
+
if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
|
|
465
|
+
return;
|
|
466
|
+
const stillGone = entry.retainedUntil;
|
|
467
|
+
entry.retainCheck = (async () => {
|
|
468
|
+
try {
|
|
469
|
+
if (await stillGone().catch(() => false)) {
|
|
470
|
+
entry.retainedUntil = null;
|
|
471
|
+
await this.releaseHeld(entry).catch(() => undefined);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
finally {
|
|
475
|
+
entry.retainCheck = null;
|
|
476
|
+
}
|
|
477
|
+
})();
|
|
478
|
+
}
|
|
479
|
+
async renewHeld() {
|
|
480
|
+
if (this.held.size === 0)
|
|
481
|
+
return;
|
|
482
|
+
for (const entry of this.held.values()) {
|
|
483
|
+
// A release the ledger could not take is retried until it lands.
|
|
484
|
+
if (entry.releasing && !entry.releaseInFlight)
|
|
485
|
+
void this.releaseHeld(entry).catch(() => undefined);
|
|
486
|
+
this.checkRetained(entry);
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
// The ledger renews every held token at the start of each transaction and
|
|
490
|
+
// reports the fenced ones.
|
|
491
|
+
this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
// A brief outage is retried on the next tick. Once a whole lease passes
|
|
495
|
+
// without a renewal, another process may already have fenced the token.
|
|
496
|
+
const nowMs = monotonicNowMs();
|
|
497
|
+
for (const entry of this.held.values()) {
|
|
498
|
+
if (nowMs - entry.renewedAtMs < this.config.leaseMs)
|
|
499
|
+
continue;
|
|
500
|
+
this.lose(entry, error instanceof HostCapacityLedgerUnavailableError
|
|
501
|
+
? error
|
|
502
|
+
: new HostCapacityLedgerUnavailableError("the host load token could not be renewed.", { cause: error }));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/** The cgroup limit's headroom when one is set, never above host MemAvailable. */
|
|
508
|
+
function tighterMemory(hostAvailable, cgroupHeadroom) {
|
|
509
|
+
if (cgroupHeadroom === null)
|
|
510
|
+
return hostAvailable;
|
|
511
|
+
return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
|
|
512
|
+
}
|
|
513
|
+
function abortError(signal) {
|
|
514
|
+
if (signal.reason instanceof Error)
|
|
515
|
+
return signal.reason;
|
|
516
|
+
const error = new Error(typeof signal.reason === "string" ? signal.reason : "The host capacity wait was cancelled.");
|
|
517
|
+
error.name = "AbortError";
|
|
518
|
+
return error;
|
|
519
|
+
}
|