@johnhenry/browsermesh-apps 0.16.0 → 0.17.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 +268 -17
- package/package.json +13 -9
- package/src/apps.mjs +4 -4
- package/src/audit.mjs +2 -2
- package/src/chat.mjs +3 -3
- package/src/cloud-storage-backend.mjs +5 -7
- package/src/cloud-storage.mjs +5 -4
- package/src/compat.mjs +2 -2
- package/src/consensus.mjs +7 -7
- package/src/devtools.mjs +3 -3
- package/src/gpu.mjs +2 -2
- package/src/index.mjs +12 -0
- package/src/internal/channel-codec.mjs +179 -0
- package/src/internal/json-message.mjs +49 -0
- package/src/internal/relay-flow.mjs +178 -0
- package/src/internal/request-target.mjs +280 -0
- package/src/marketplace-ui.mjs +1 -1
- package/src/mesh-agent-swarm.mjs +1 -1
- package/src/mesh-bootstrap.mjs +47 -1
- package/src/mesh-channel.mjs +716 -0
- package/src/mesh-hardening.mjs +8 -1
- package/src/mesh-relay-backend.mjs +116 -22
- package/src/mesh-relay-host.mjs +296 -55
- package/src/mesh-rpc.mjs +3 -1
- package/src/mesh-sync.mjs +1 -1
- package/src/orchestrator.mjs +54 -29
- package/src/payments.mjs +56 -14
- package/src/peer-agent-swarm.mjs +2 -2
- package/src/peer-agent.mjs +7 -7
- package/src/peer-compute.mjs +2 -2
- package/src/peer-encrypted-store.mjs +3 -3
- package/src/peer-escrow.mjs +2 -2
- package/src/peer-health.mjs +3 -3
- package/src/peer-node.mjs +8 -5
- package/src/peer-payments.mjs +2 -2
- package/src/peer-registry.mjs +45 -3
- package/src/peer-routing.mjs +158 -21
- package/src/peer-services.mjs +3 -3
- package/src/peer-timestamp.mjs +3 -3
- package/src/peer-torrent.mjs +112 -47
- package/src/peer-verification.mjs +3 -3
- package/src/pod-host-service.mjs +48 -7
- package/src/pod-placement.mjs +582 -0
- package/src/pod-supervisor.mjs +9 -30
- package/src/protocol-channel.mjs +327 -0
- package/src/resources.mjs +2 -2
- package/src/restart-policy.mjs +67 -0
- package/src/scheduler.mjs +3 -3
- package/src/serverless-proxy.mjs +58 -7
- package/src/silent-catch.mjs +22 -9
- package/src/tools.mjs +3 -3
- package/src/visualizations.mjs +2 -2
- package/src/wsh-negotiator.mjs +97 -0
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pod-placement.mjs -- which host a hosted pod goes to (issue #185 §6), as
|
|
3
|
+
* pure, deterministic logic plus a small pool that applies it to lane
|
|
4
|
+
* drivers.
|
|
5
|
+
*
|
|
6
|
+
* Nothing in here reads a clock or starts a timer: time is a number the
|
|
7
|
+
* caller passes (`now`), and "wait this long before restarting" is a number
|
|
8
|
+
* the caller schedules. That is what makes every rule below unit-testable
|
|
9
|
+
* with fake lane drivers (`InMemoryPodHostDriver`) and no sleeps.
|
|
10
|
+
*
|
|
11
|
+
* Layers:
|
|
12
|
+
*
|
|
13
|
+
* - `planPlacement()` the hard rules (lane, verb, health, boundary,
|
|
14
|
+
* capability, admission limits, quota) and the
|
|
15
|
+
* ranking among the hosts that pass. Pure function.
|
|
16
|
+
* - `HostHealth` a circuit breaker per host: healthy, degraded,
|
|
17
|
+
* unhealthy (cooling down), probing (one try).
|
|
18
|
+
* - `PlacementLedger` what is reserved on each host and per requester.
|
|
19
|
+
* - `createHostPool()` planner + ledger + health + `PodHostDriver`s:
|
|
20
|
+
* `spawn`, `drain`, `drainHost`, `handleExit`.
|
|
21
|
+
*
|
|
22
|
+
* The rule from `pod-host-service.mjs` still holds: the orchestrator
|
|
23
|
+
* PROPOSES, the host ACCEPTS. A host's refusal (`EACCES`, `EBUSY`, ...) is
|
|
24
|
+
* final for that spawn; only a transport-level failure (`ETIMEDOUT`) can
|
|
25
|
+
* move a spawn to the next host, and only when `maxAttempts` > 1 (default 1).
|
|
26
|
+
*
|
|
27
|
+
* ISOLATION BOUNDARY. A host states how strongly it separates a pod from
|
|
28
|
+
* itself (`BOUNDARY`): a `worker_threads` pod is `none` (same process, no
|
|
29
|
+
* boundary), a permission-restricted child process is `process`, a V8
|
|
30
|
+
* isolate in its own process is `language`, a microVM is `hardware`. An
|
|
31
|
+
* untrusted requester (the default) is only placed behind `language` or
|
|
32
|
+
* `hardware`. Nothing here establishes a boundary; it only refuses to place
|
|
33
|
+
* untrusted work where a host says there is none.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import {
|
|
37
|
+
POD_HOST_ERROR,
|
|
38
|
+
POD_HOST_VERB,
|
|
39
|
+
POD_LANE_VERBS,
|
|
40
|
+
PodHostDriverError,
|
|
41
|
+
validatePodSpec,
|
|
42
|
+
} from '@johnhenry/browsermesh-pod'
|
|
43
|
+
import { decideRestart } from './restart-policy.mjs'
|
|
44
|
+
|
|
45
|
+
/** How strongly a host separates a hosted pod from the host. Ordered weakest to strongest. */
|
|
46
|
+
export const BOUNDARY = Object.freeze({
|
|
47
|
+
NONE: 'none',
|
|
48
|
+
PROCESS: 'process',
|
|
49
|
+
LANGUAGE: 'language',
|
|
50
|
+
HARDWARE: 'hardware',
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
const BOUNDARY_RANK = Object.freeze({ none: 0, process: 1, language: 2, hardware: 3 })
|
|
54
|
+
|
|
55
|
+
/** Whether the requester's code is trusted by the host operator. */
|
|
56
|
+
export const TRUST = Object.freeze({
|
|
57
|
+
TRUSTED: 'trusted',
|
|
58
|
+
UNTRUSTED: 'untrusted',
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
/** Charged to a pod that states no limits. */
|
|
62
|
+
const DEFAULT_LIMITS = Object.freeze({ vcpus: 1, memMib: 128 })
|
|
63
|
+
|
|
64
|
+
/** @param {*} value @returns {number} */
|
|
65
|
+
function boundaryRank(value) {
|
|
66
|
+
return BOUNDARY_RANK[value] ?? 0
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @typedef {object} PlacementHost
|
|
71
|
+
* @property {string} id
|
|
72
|
+
* @property {string} lane - A `POD_LANE` value.
|
|
73
|
+
* @property {string} [boundary] - A `BOUNDARY` value; absent means `none`.
|
|
74
|
+
* @property {string[]} [verbs] - Verbs served; defaults to the lane's.
|
|
75
|
+
* @property {string[]} [caps] - Kernel capabilities the host can grant (podspec `caps`).
|
|
76
|
+
* @property {{pods?: number, vcpus?: number, memMib?: number}} [capacity] - Absent dimension = unlimited.
|
|
77
|
+
* @property {'healthy'|'degraded'|'probing'|'unhealthy'|'draining'} [health]
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @typedef {object} PlacementPolicy
|
|
82
|
+
* @property {string} [minBoundary] - Floor for every requester.
|
|
83
|
+
* @property {{vcpus?: number, memMib?: number}} [defaultLimits]
|
|
84
|
+
* @property {number} [perRequesterMaxPods]
|
|
85
|
+
* @property {string[]} [avoidHosts]
|
|
86
|
+
* @property {string} [preferHost]
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Decide where a podspec may go and in what order of preference.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} input
|
|
93
|
+
* @param {object} input.spec - A podspec (validated here).
|
|
94
|
+
* @param {PlacementHost[]} input.hosts
|
|
95
|
+
* @param {{id?: string, trust?: string}} [input.requester] - Default: untrusted.
|
|
96
|
+
* @param {Map<string, {pods: number, vcpus: number, memMib: number}>} [input.usage] - Reserved per host.
|
|
97
|
+
* @param {Map<string, {pods: number}>} [input.requesterUsage]
|
|
98
|
+
* @param {PlacementPolicy} [input.policy]
|
|
99
|
+
* @returns {{ok: true, host: PlacementHost, ranked: Array<{id: string, score: number, host: PlacementHost}>, rejected: Array<{id: string, code: string, reason: string}>}
|
|
100
|
+
* | {ok: false, code: string, ranked: [], rejected: Array<{id: string, code: string, reason: string}>}}
|
|
101
|
+
*/
|
|
102
|
+
export function planPlacement({
|
|
103
|
+
spec, hosts = [], requester = {}, usage = new Map(), requesterUsage = new Map(), policy = {},
|
|
104
|
+
} = {}) {
|
|
105
|
+
const validated = validatePodSpec(spec)
|
|
106
|
+
if (!validated.ok) {
|
|
107
|
+
return { ok: false, code: 'invalid-spec', ranked: [], rejected: [], errors: validated.errors }
|
|
108
|
+
}
|
|
109
|
+
const pod = validated.value
|
|
110
|
+
|
|
111
|
+
if (!Array.isArray(hosts) || hosts.length === 0) {
|
|
112
|
+
return { ok: false, code: 'no-hosts', ranked: [], rejected: [] }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const requesterId = requester.id ?? null
|
|
116
|
+
if (policy.perRequesterMaxPods !== undefined && requesterId !== null) {
|
|
117
|
+
const held = requesterUsage.get(requesterId)?.pods ?? 0
|
|
118
|
+
if (held >= policy.perRequesterMaxPods) {
|
|
119
|
+
return { ok: false, code: 'quota', ranked: [], rejected: [] }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const trusted = requester.trust === TRUST.TRUSTED
|
|
124
|
+
const floor = Math.max(
|
|
125
|
+
boundaryRank(policy.minBoundary),
|
|
126
|
+
trusted ? BOUNDARY_RANK.none : BOUNDARY_RANK.language,
|
|
127
|
+
)
|
|
128
|
+
const charge = {
|
|
129
|
+
vcpus: pod.limits?.vcpus ?? policy.defaultLimits?.vcpus ?? DEFAULT_LIMITS.vcpus,
|
|
130
|
+
memMib: pod.limits?.memMib ?? policy.defaultLimits?.memMib ?? DEFAULT_LIMITS.memMib,
|
|
131
|
+
}
|
|
132
|
+
const avoid = new Set(policy.avoidHosts ?? [])
|
|
133
|
+
|
|
134
|
+
/** @type {Array<{id: string, code: string, reason: string}>} */
|
|
135
|
+
const rejected = []
|
|
136
|
+
/** @type {Array<{id: string, score: number, host: PlacementHost}>} */
|
|
137
|
+
const ranked = []
|
|
138
|
+
|
|
139
|
+
for (const host of hosts) {
|
|
140
|
+
/** @param {string} code @param {string} reason */
|
|
141
|
+
const reject = (code, reason) => { rejected.push({ id: host.id, code, reason }) }
|
|
142
|
+
|
|
143
|
+
if (host.lane !== pod.lane) {
|
|
144
|
+
reject('lane', `host runs lane '${host.lane}', pod needs '${pod.lane}'`)
|
|
145
|
+
continue
|
|
146
|
+
}
|
|
147
|
+
const verbs = host.verbs ?? POD_LANE_VERBS[host.lane] ?? []
|
|
148
|
+
if (!verbs.includes(POD_HOST_VERB.SPAWN)) {
|
|
149
|
+
reject('verb', "host does not serve 'spawn'")
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
if (host.health === 'draining') {
|
|
153
|
+
reject('draining', 'host is draining')
|
|
154
|
+
continue
|
|
155
|
+
}
|
|
156
|
+
if (host.health === 'unhealthy') {
|
|
157
|
+
reject('health', 'host is unhealthy')
|
|
158
|
+
continue
|
|
159
|
+
}
|
|
160
|
+
if (avoid.has(host.id)) {
|
|
161
|
+
reject('avoided', 'host is excluded for this placement')
|
|
162
|
+
continue
|
|
163
|
+
}
|
|
164
|
+
if (boundaryRank(host.boundary) < floor) {
|
|
165
|
+
reject('boundary', `host boundary '${host.boundary ?? BOUNDARY.NONE}' is below the required '${Object.keys(BOUNDARY_RANK).find((k) => BOUNDARY_RANK[k] === floor)}'`)
|
|
166
|
+
continue
|
|
167
|
+
}
|
|
168
|
+
const missing = (pod.caps ?? []).filter((cap) => !(host.caps ?? []).includes(cap))
|
|
169
|
+
if (missing.length > 0) {
|
|
170
|
+
reject('caps', `host cannot grant: ${missing.join(', ')}`)
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const used = usage.get(host.id) ?? { pods: 0, vcpus: 0, memMib: 0 }
|
|
175
|
+
const cap = host.capacity ?? {}
|
|
176
|
+
if (cap.pods !== undefined && used.pods + 1 > cap.pods) {
|
|
177
|
+
reject('capacity', `host is at its limit of ${cap.pods} pods`)
|
|
178
|
+
continue
|
|
179
|
+
}
|
|
180
|
+
if (cap.vcpus !== undefined && used.vcpus + charge.vcpus > cap.vcpus) {
|
|
181
|
+
reject('capacity', `host has ${Math.max(0, cap.vcpus - used.vcpus)} vcpus free, pod needs ${charge.vcpus}`)
|
|
182
|
+
continue
|
|
183
|
+
}
|
|
184
|
+
if (cap.memMib !== undefined && used.memMib + charge.memMib > cap.memMib) {
|
|
185
|
+
reject('capacity', `host has ${Math.max(0, cap.memMib - used.memMib)} MiB free, pod needs ${charge.memMib}`)
|
|
186
|
+
continue
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// -- score -------------------------------------------------------------
|
|
190
|
+
let score = 100
|
|
191
|
+
if (host.health === 'degraded') score -= 30
|
|
192
|
+
else if (host.health === 'probing') score -= 60
|
|
193
|
+
|
|
194
|
+
/** @type {number[]} */
|
|
195
|
+
const freeFractions = []
|
|
196
|
+
if (cap.pods !== undefined && cap.pods > 0) freeFractions.push(1 - (used.pods + 1) / cap.pods)
|
|
197
|
+
if (cap.vcpus !== undefined && cap.vcpus > 0) freeFractions.push(1 - (used.vcpus + charge.vcpus) / cap.vcpus)
|
|
198
|
+
if (cap.memMib !== undefined && cap.memMib > 0) freeFractions.push(1 - (used.memMib + charge.memMib) / cap.memMib)
|
|
199
|
+
const free = freeFractions.length === 0 ? 1 : freeFractions.reduce((a, b) => a + b, 0) / freeFractions.length
|
|
200
|
+
score += 40 * free
|
|
201
|
+
if (policy.preferHost === host.id) score += 15
|
|
202
|
+
|
|
203
|
+
ranked.push({ id: host.id, score, host })
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
ranked.sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
207
|
+
if (ranked.length === 0) return { ok: false, code: 'no-eligible-host', ranked: [], rejected }
|
|
208
|
+
return { ok: true, host: ranked[0].host, ranked, rejected }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
// HostHealth
|
|
213
|
+
// ---------------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A circuit breaker per host. `now` is always passed in.
|
|
217
|
+
*
|
|
218
|
+
* healthy no failures since the last success
|
|
219
|
+
* degraded some failures, below the threshold: still eligible, ranks lower
|
|
220
|
+
* unhealthy threshold reached: not eligible until the cooldown passes
|
|
221
|
+
* probing cooldown passed: eligible (ranks last) for one try; a success
|
|
222
|
+
* restores it, a failure doubles the cooldown (up to the cap)
|
|
223
|
+
*/
|
|
224
|
+
export class HostHealth {
|
|
225
|
+
#failureThreshold
|
|
226
|
+
#cooldownMs
|
|
227
|
+
#maxCooldownMs
|
|
228
|
+
/** @type {Map<string, {failures: number, trips: number, openedAt: number|null}>} */
|
|
229
|
+
#records = new Map()
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* @param {object} [opts]
|
|
233
|
+
* @param {number} [opts.failureThreshold=3]
|
|
234
|
+
* @param {number} [opts.cooldownMs=30000]
|
|
235
|
+
* @param {number} [opts.maxCooldownMs=300000]
|
|
236
|
+
*/
|
|
237
|
+
constructor({ failureThreshold = 3, cooldownMs = 30_000, maxCooldownMs = 300_000 } = {}) {
|
|
238
|
+
this.#failureThreshold = failureThreshold
|
|
239
|
+
this.#cooldownMs = cooldownMs
|
|
240
|
+
this.#maxCooldownMs = maxCooldownMs
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** @param {{trips: number}} record @returns {number} */
|
|
244
|
+
#cooldown(record) {
|
|
245
|
+
return Math.min(this.#cooldownMs * (2 ** record.trips), this.#maxCooldownMs)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** @param {string} id @param {number} now */
|
|
249
|
+
recordFailure(id, now) {
|
|
250
|
+
const record = this.#records.get(id) ?? { failures: 0, trips: 0, openedAt: null }
|
|
251
|
+
record.failures += 1
|
|
252
|
+
if (record.failures >= this.#failureThreshold) {
|
|
253
|
+
if (record.openedAt === null) {
|
|
254
|
+
record.openedAt = now
|
|
255
|
+
} else if (now >= record.openedAt + this.#cooldown(record)) {
|
|
256
|
+
// A failure after the cooldown is a failed probe.
|
|
257
|
+
record.trips += 1
|
|
258
|
+
record.openedAt = now
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
this.#records.set(id, record)
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** @param {string} id @param {number} _now */
|
|
265
|
+
recordSuccess(id, _now) {
|
|
266
|
+
this.#records.delete(id)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* @param {string} id
|
|
271
|
+
* @param {number} now
|
|
272
|
+
* @returns {'healthy'|'degraded'|'unhealthy'|'probing'}
|
|
273
|
+
*/
|
|
274
|
+
state(id, now) {
|
|
275
|
+
const record = this.#records.get(id)
|
|
276
|
+
if (!record || record.failures === 0) return 'healthy'
|
|
277
|
+
if (record.openedAt === null) return 'degraded'
|
|
278
|
+
return now >= record.openedAt + this.#cooldown(record) ? 'probing' : 'unhealthy'
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** @param {number} now @returns {Record<string, string>} Every host that is not healthy. */
|
|
282
|
+
snapshot(now) {
|
|
283
|
+
/** @type {Record<string, string>} */
|
|
284
|
+
const out = {}
|
|
285
|
+
for (const id of this.#records.keys()) {
|
|
286
|
+
const state = this.state(id, now)
|
|
287
|
+
if (state !== 'healthy') out[id] = state
|
|
288
|
+
}
|
|
289
|
+
return out
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---------------------------------------------------------------------------
|
|
294
|
+
// PlacementLedger
|
|
295
|
+
// ---------------------------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
/** What is reserved on each host and by each requester. */
|
|
298
|
+
export class PlacementLedger {
|
|
299
|
+
/** @type {Map<string, {hostId: string, name: string, requesterId: string|null, vcpus: number, memMib: number}>} */
|
|
300
|
+
#entries = new Map()
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* @param {{hostId: string, name: string, requesterId?: string|null, limits: {vcpus: number, memMib: number}}} entry
|
|
304
|
+
*/
|
|
305
|
+
reserve({ hostId, name, requesterId = null, limits }) {
|
|
306
|
+
const key = `${hostId}\0${name}`
|
|
307
|
+
if (this.#entries.has(key)) throw new Error(`'${name}' is already reserved on host '${hostId}'`)
|
|
308
|
+
this.#entries.set(key, { hostId, name, requesterId, vcpus: limits.vcpus, memMib: limits.memMib })
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** @param {string} hostId @param {string} name */
|
|
312
|
+
release(hostId, name) {
|
|
313
|
+
this.#entries.delete(`${hostId}\0${name}`)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** @returns {Map<string, {pods: number, vcpus: number, memMib: number}>} */
|
|
317
|
+
usage() {
|
|
318
|
+
/** @type {Map<string, {pods: number, vcpus: number, memMib: number}>} */
|
|
319
|
+
const out = new Map()
|
|
320
|
+
for (const entry of this.#entries.values()) {
|
|
321
|
+
const used = out.get(entry.hostId) ?? { pods: 0, vcpus: 0, memMib: 0 }
|
|
322
|
+
used.pods += 1
|
|
323
|
+
used.vcpus += entry.vcpus
|
|
324
|
+
used.memMib += entry.memMib
|
|
325
|
+
out.set(entry.hostId, used)
|
|
326
|
+
}
|
|
327
|
+
return out
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** @returns {Map<string, {pods: number}>} */
|
|
331
|
+
requesterUsage() {
|
|
332
|
+
/** @type {Map<string, {pods: number}>} */
|
|
333
|
+
const out = new Map()
|
|
334
|
+
for (const entry of this.#entries.values()) {
|
|
335
|
+
if (entry.requesterId === null) continue
|
|
336
|
+
const used = out.get(entry.requesterId) ?? { pods: 0 }
|
|
337
|
+
used.pods += 1
|
|
338
|
+
out.set(entry.requesterId, used)
|
|
339
|
+
}
|
|
340
|
+
return out
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// ---------------------------------------------------------------------------
|
|
345
|
+
// createHostPool
|
|
346
|
+
// ---------------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
/** Rejection codes that mean "not now" rather than "never". */
|
|
349
|
+
const TRANSIENT = new Set(['capacity', 'health', 'draining', 'avoided'])
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* The `PodHostDriverError` a failed plan becomes.
|
|
353
|
+
* @param {ReturnType<typeof planPlacement>} plan
|
|
354
|
+
* @returns {PodHostDriverError}
|
|
355
|
+
*/
|
|
356
|
+
function planError(plan) {
|
|
357
|
+
const details = { rejected: plan.rejected, plan: plan.code }
|
|
358
|
+
switch (plan.code) {
|
|
359
|
+
case 'invalid-spec':
|
|
360
|
+
return new PodHostDriverError(POD_HOST_ERROR.EINVAL, (plan.errors ?? []).join('; ') || 'invalid podspec', details)
|
|
361
|
+
case 'quota':
|
|
362
|
+
return new PodHostDriverError(POD_HOST_ERROR.EACCES, 'requester is at its pod quota', details)
|
|
363
|
+
case 'no-hosts':
|
|
364
|
+
return new PodHostDriverError(POD_HOST_ERROR.ENOENT, 'no pod hosts are configured', details)
|
|
365
|
+
default: {
|
|
366
|
+
const codes = plan.rejected.map((r) => r.code)
|
|
367
|
+
if (codes.every((c) => c === 'lane' || c === 'verb')) {
|
|
368
|
+
return new PodHostDriverError(POD_HOST_ERROR.ELANE, 'no host serves this pod\'s lane', details)
|
|
369
|
+
}
|
|
370
|
+
if (codes.some((c) => TRANSIENT.has(c))) {
|
|
371
|
+
return new PodHostDriverError(POD_HOST_ERROR.EBUSY, 'no eligible host has room right now', details)
|
|
372
|
+
}
|
|
373
|
+
return new PodHostDriverError(POD_HOST_ERROR.EACCES, 'no host may take this pod', details)
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* @typedef {object} PoolHost
|
|
380
|
+
* @property {string} id
|
|
381
|
+
* @property {import('@johnhenry/browsermesh-pod').PodHostDriver} driver
|
|
382
|
+
* @property {string} [boundary]
|
|
383
|
+
* @property {string[]} [caps]
|
|
384
|
+
* @property {{pods?: number, vcpus?: number, memMib?: number}} [capacity]
|
|
385
|
+
*/
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Apply the planner to a set of lane drivers.
|
|
389
|
+
*
|
|
390
|
+
* @param {object} opts
|
|
391
|
+
* @param {PoolHost[]} opts.hosts - `lane` and `verbs` come from each driver.
|
|
392
|
+
* @param {PlacementPolicy} [opts.policy]
|
|
393
|
+
* @param {() => number} [opts.now=Date.now]
|
|
394
|
+
* @param {HostHealth} [opts.health]
|
|
395
|
+
* @param {number} [opts.maxAttempts=1] - Hosts one spawn may try; only a
|
|
396
|
+
* transport-level failure moves it to the next.
|
|
397
|
+
* @param {string[]} [opts.failoverCodes=['ETIMEDOUT']]
|
|
398
|
+
*/
|
|
399
|
+
export function createHostPool({
|
|
400
|
+
hosts, policy = {}, now = Date.now, health = new HostHealth(), maxAttempts = 1,
|
|
401
|
+
failoverCodes = [POD_HOST_ERROR.ETIMEDOUT],
|
|
402
|
+
} = {}) {
|
|
403
|
+
if (!Array.isArray(hosts) || hosts.length === 0) throw new Error('createHostPool: hosts are required')
|
|
404
|
+
/** @type {Map<string, PoolHost>} */
|
|
405
|
+
const byId = new Map()
|
|
406
|
+
for (const host of hosts) {
|
|
407
|
+
if (!host?.id || typeof host.driver?.spawn !== 'function') throw new Error('createHostPool: every host needs an id and a driver')
|
|
408
|
+
if (byId.has(host.id)) throw new Error(`createHostPool: duplicate host id '${host.id}'`)
|
|
409
|
+
byId.set(host.id, host)
|
|
410
|
+
}
|
|
411
|
+
const ledger = new PlacementLedger()
|
|
412
|
+
const draining = new Set()
|
|
413
|
+
/** @type {Map<string, {hostId: string, spec: object, requester: object, restarts: number}>} */
|
|
414
|
+
const pods = new Map()
|
|
415
|
+
|
|
416
|
+
/** @returns {PlacementHost[]} */
|
|
417
|
+
function placementHosts() {
|
|
418
|
+
const t = now()
|
|
419
|
+
return [...byId.values()].map((host) => ({
|
|
420
|
+
id: host.id,
|
|
421
|
+
lane: host.driver.lane,
|
|
422
|
+
boundary: host.boundary,
|
|
423
|
+
verbs: host.driver.capabilities?.().verbs,
|
|
424
|
+
caps: host.caps,
|
|
425
|
+
capacity: host.capacity,
|
|
426
|
+
health: draining.has(host.id) ? 'draining' : health.state(host.id, t),
|
|
427
|
+
}))
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** @param {object} spec @returns {{vcpus: number, memMib: number}} */
|
|
431
|
+
function chargeOf(spec) {
|
|
432
|
+
return {
|
|
433
|
+
vcpus: spec.limits?.vcpus ?? policy.defaultLimits?.vcpus ?? DEFAULT_LIMITS.vcpus,
|
|
434
|
+
memMib: spec.limits?.memMib ?? policy.defaultLimits?.memMib ?? DEFAULT_LIMITS.memMib,
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* @param {object} specIn
|
|
440
|
+
* @param {object} opts
|
|
441
|
+
*/
|
|
442
|
+
async function place(specIn, { requester = {}, avoidHosts = [], restarts = 0 } = {}) {
|
|
443
|
+
const validated = validatePodSpec(specIn)
|
|
444
|
+
if (!validated.ok) throw planError({ ok: false, code: 'invalid-spec', ranked: [], rejected: [], errors: validated.errors })
|
|
445
|
+
const spec = validated.value
|
|
446
|
+
if (pods.has(spec.name)) {
|
|
447
|
+
throw new PodHostDriverError(POD_HOST_ERROR.EEXIST, `pod '${spec.name}' already exists`, { name: spec.name })
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** @type {Array<{hostId: string, outcome: string}>} */
|
|
451
|
+
const attempts = []
|
|
452
|
+
const avoid = new Set([...(policy.avoidHosts ?? []), ...avoidHosts])
|
|
453
|
+
/** @type {PodHostDriverError|null} */
|
|
454
|
+
let last = null
|
|
455
|
+
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
456
|
+
const plan = planPlacement({
|
|
457
|
+
spec,
|
|
458
|
+
hosts: placementHosts(),
|
|
459
|
+
requester,
|
|
460
|
+
usage: ledger.usage(),
|
|
461
|
+
requesterUsage: ledger.requesterUsage(),
|
|
462
|
+
policy: { ...policy, avoidHosts: [...avoid] },
|
|
463
|
+
})
|
|
464
|
+
if (!plan.ok) throw last ?? planError(plan)
|
|
465
|
+
|
|
466
|
+
const target = plan.host
|
|
467
|
+
// Reserved BEFORE the driver runs, so a second spawn that starts while
|
|
468
|
+
// this one is in flight already sees the capacity as taken.
|
|
469
|
+
ledger.reserve({ hostId: target.id, name: spec.name, requesterId: requester.id ?? null, limits: chargeOf(spec) })
|
|
470
|
+
try {
|
|
471
|
+
const status = await byId.get(target.id).driver.spawn(spec)
|
|
472
|
+
health.recordSuccess(target.id, now())
|
|
473
|
+
attempts.push({ hostId: target.id, outcome: 'ok' })
|
|
474
|
+
pods.set(spec.name, { hostId: target.id, spec, requester, restarts })
|
|
475
|
+
return { hostId: target.id, status, attempts }
|
|
476
|
+
} catch (err) {
|
|
477
|
+
ledger.release(target.id, spec.name)
|
|
478
|
+
const error = PodHostDriverError.from(err)
|
|
479
|
+
attempts.push({ hostId: target.id, outcome: error.code })
|
|
480
|
+
if (error.code === POD_HOST_ERROR.ETIMEDOUT || !(err instanceof PodHostDriverError)) {
|
|
481
|
+
health.recordFailure(target.id, now())
|
|
482
|
+
}
|
|
483
|
+
if (!failoverCodes.includes(error.code)) throw error
|
|
484
|
+
avoid.add(target.id)
|
|
485
|
+
last = error
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
throw last
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
return {
|
|
492
|
+
/**
|
|
493
|
+
* @param {object} spec
|
|
494
|
+
* @param {{requester?: {id?: string, trust?: string}}} [opts]
|
|
495
|
+
*/
|
|
496
|
+
spawn(spec, { requester = {} } = {}) {
|
|
497
|
+
return place(spec, { requester })
|
|
498
|
+
},
|
|
499
|
+
|
|
500
|
+
/** @param {string} name */
|
|
501
|
+
async drain(name) {
|
|
502
|
+
const entry = pods.get(name)
|
|
503
|
+
if (!entry) throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no pod named '${name}'`, { name })
|
|
504
|
+
const status = await byId.get(entry.hostId).driver.drain(name)
|
|
505
|
+
ledger.release(entry.hostId, name)
|
|
506
|
+
pods.delete(name)
|
|
507
|
+
return status
|
|
508
|
+
},
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Stop placing on a host, and move its pods elsewhere (or drain them).
|
|
512
|
+
* A pod that cannot be re-placed is left running and reported: draining a
|
|
513
|
+
* host never silently loses one.
|
|
514
|
+
*
|
|
515
|
+
* @param {string} hostId
|
|
516
|
+
* @param {{replace?: boolean}} [opts]
|
|
517
|
+
*/
|
|
518
|
+
async drainHost(hostId, { replace = true } = {}) {
|
|
519
|
+
if (!byId.has(hostId)) throw new PodHostDriverError(POD_HOST_ERROR.ENOENT, `no host '${hostId}'`, { hostId })
|
|
520
|
+
draining.add(hostId)
|
|
521
|
+
/** @type {Array<{name: string, from: string, to: string}>} */
|
|
522
|
+
const moved = []
|
|
523
|
+
/** @type {Array<{name: string, from: string, code: string, message: string}>} */
|
|
524
|
+
const failed = []
|
|
525
|
+
for (const [name, entry] of [...pods]) {
|
|
526
|
+
if (entry.hostId !== hostId) continue
|
|
527
|
+
if (!replace) {
|
|
528
|
+
await byId.get(hostId).driver.drain(name)
|
|
529
|
+
ledger.release(hostId, name)
|
|
530
|
+
pods.delete(name)
|
|
531
|
+
continue
|
|
532
|
+
}
|
|
533
|
+
try {
|
|
534
|
+
// Make before break: the new pod is up before the old one stops.
|
|
535
|
+
pods.delete(name)
|
|
536
|
+
const placed = await place(entry.spec, { requester: entry.requester, avoidHosts: [hostId], restarts: entry.restarts })
|
|
537
|
+
await byId.get(hostId).driver.drain(name)
|
|
538
|
+
ledger.release(hostId, name)
|
|
539
|
+
moved.push({ name, from: hostId, to: placed.hostId })
|
|
540
|
+
} catch (err) {
|
|
541
|
+
pods.set(name, entry)
|
|
542
|
+
const error = PodHostDriverError.from(err)
|
|
543
|
+
failed.push({ name, from: hostId, code: error.code, message: error.message })
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return { moved, failed }
|
|
547
|
+
},
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* What to do about a pod that exited. Releases its reservation, applies
|
|
551
|
+
* the shared restart policy and returns the decision; the caller
|
|
552
|
+
* schedules `delayMs` and then calls `run()`, which re-places the pod
|
|
553
|
+
* on a host other than the one that failed.
|
|
554
|
+
*
|
|
555
|
+
* @param {{hostId: string, name: string, exit: {code?: number, reason?: string}}} event
|
|
556
|
+
*/
|
|
557
|
+
handleExit({ hostId, name, exit }) {
|
|
558
|
+
const entry = pods.get(name)
|
|
559
|
+
if (!entry || entry.hostId !== hostId) return { restart: false, why: 'unknown' }
|
|
560
|
+
ledger.release(hostId, name)
|
|
561
|
+
pods.delete(name)
|
|
562
|
+
const decision = decideRestart({ restart: entry.spec.restart, exit, restartsSoFar: entry.restarts })
|
|
563
|
+
if (!decision.restart) return decision
|
|
564
|
+
return {
|
|
565
|
+
...decision,
|
|
566
|
+
avoidHosts: [hostId],
|
|
567
|
+
run: () => place(entry.spec, { requester: entry.requester, avoidHosts: [hostId], restarts: entry.restarts + 1 }),
|
|
568
|
+
}
|
|
569
|
+
},
|
|
570
|
+
|
|
571
|
+
usage: () => ledger.usage(),
|
|
572
|
+
requesterUsage: () => ledger.requesterUsage(),
|
|
573
|
+
/** @returns {Record<string, string>} Every host that is not healthy, plus draining ones. */
|
|
574
|
+
health() {
|
|
575
|
+
const out = health.snapshot(now())
|
|
576
|
+
for (const id of draining) out[id] = 'draining'
|
|
577
|
+
return out
|
|
578
|
+
},
|
|
579
|
+
/** @returns {Array<{name: string, hostId: string}>} */
|
|
580
|
+
pods: () => [...pods].map(([name, entry]) => ({ name, hostId: entry.hostId })),
|
|
581
|
+
}
|
|
582
|
+
}
|
package/src/pod-supervisor.mjs
CHANGED
|
@@ -54,6 +54,12 @@
|
|
|
54
54
|
import { validatePodSpec, PodHostDriverError } from '@johnhenry/browsermesh-pod'
|
|
55
55
|
import { createPodHostClient } from './pod-host-service.mjs'
|
|
56
56
|
import { pickAutoHost } from './orchestrator.mjs'
|
|
57
|
+
import {
|
|
58
|
+
DEFAULT_BACKOFF_MS,
|
|
59
|
+
DEFAULT_MAX_RESTARTS,
|
|
60
|
+
policyWantsRestart,
|
|
61
|
+
restartDelayMs,
|
|
62
|
+
} from './restart-policy.mjs'
|
|
57
63
|
|
|
58
64
|
/**
|
|
59
65
|
* Audit record kinds this file writes that are NOT already covered by
|
|
@@ -71,40 +77,14 @@ export const SUPERVISOR_AUDIT = Object.freeze({
|
|
|
71
77
|
HOST_LOST: 'supervisor_host_lost',
|
|
72
78
|
})
|
|
73
79
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
/** Default `restart.backoffMs` base. */
|
|
77
|
-
const DEFAULT_BACKOFF_MS = 1000
|
|
78
|
-
/** Backoff never waits longer than this, regardless of restart count. */
|
|
79
|
-
const MAX_BACKOFF_MS = 60_000
|
|
80
|
+
// Restart policy, default `maxRestarts`/backoff and the backoff curve live in
|
|
81
|
+
// restart-policy.mjs, shared with pod-placement.mjs.
|
|
80
82
|
|
|
81
83
|
/** @param {{host: string, name: string}} ref @returns {string} */
|
|
82
84
|
function refKey(ref) {
|
|
83
85
|
return `${ref.host}::${ref.name}`
|
|
84
86
|
}
|
|
85
87
|
|
|
86
|
-
/**
|
|
87
|
-
* Whether `policy` says to restart a pod that exited with `{code, reason}`.
|
|
88
|
-
* `reason === 'drained'` is handled by the CALLER, before this is ever
|
|
89
|
-
* consulted -- an intentional drain is never a restart candidate under any
|
|
90
|
-
* policy (see `#onExit()`).
|
|
91
|
-
*
|
|
92
|
-
* @param {'never'|'on-failure'|'always'} policy
|
|
93
|
-
* @param {{code?: number, reason?: string}} exit
|
|
94
|
-
* @returns {boolean}
|
|
95
|
-
*/
|
|
96
|
-
function policyWantsRestart(policy, { code, reason }) {
|
|
97
|
-
switch (policy) {
|
|
98
|
-
case 'always':
|
|
99
|
-
return true
|
|
100
|
-
case 'on-failure':
|
|
101
|
-
return code !== 0 || reason === 'crashed' || reason === 'host-lost'
|
|
102
|
-
case 'never':
|
|
103
|
-
default:
|
|
104
|
-
return false
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
88
|
/**
|
|
109
89
|
* Build the `PodSupervisor` (issue #185 item 6).
|
|
110
90
|
*
|
|
@@ -545,8 +525,7 @@ export function createPodSupervisor({
|
|
|
545
525
|
return
|
|
546
526
|
}
|
|
547
527
|
|
|
548
|
-
const
|
|
549
|
-
const delayMs = Math.min(base * (2 ** entry.restarts), MAX_BACKOFF_MS)
|
|
528
|
+
const delayMs = restartDelayMs(entry.restarts, entry.spec.restart?.backoffMs ?? DEFAULT_BACKOFF_MS)
|
|
550
529
|
entry.restarts += 1
|
|
551
530
|
const attempt = entry.restarts
|
|
552
531
|
|