50 lines
1.5 KiB
JavaScript
50 lines
1.5 KiB
JavaScript
/** @type {Map<string, number>} */
|
|
const delegateInflight = new Map()
|
|
|
|
/**
|
|
* @param {string} kind
|
|
* @param {Record<string, string | undefined> | null | undefined} env
|
|
* @returns {number} max concurrent (0 = unlimited)
|
|
*/
|
|
function delegateMaxConcurrent(kind, env) {
|
|
if (!env) return 0
|
|
const spec =
|
|
env[`BARE_OS_DELEGATE_${String(kind).toUpperCase()}_MAX_CONCURRENT`]
|
|
if (spec != null && String(spec).trim() !== '') {
|
|
const n = Number.parseInt(String(spec), 10)
|
|
if (Number.isFinite(n) && n > 0) return Math.min(64, n)
|
|
}
|
|
const g = env.BARE_OS_DELEGATE_MAX_CONCURRENT
|
|
if (g != null && String(g).trim() !== '') {
|
|
const n = Number.parseInt(String(g), 10)
|
|
if (Number.isFinite(n) && n > 0) return Math.min(64, n)
|
|
}
|
|
return 0
|
|
}
|
|
|
|
/**
|
|
* @param {string} kind
|
|
* @param {Record<string, string | undefined> | null | undefined} env
|
|
* @returns {boolean}
|
|
*/
|
|
export function bareOsDelegateConcurrentTryEnter(kind, env) {
|
|
const max = delegateMaxConcurrent(kind, env)
|
|
if (!max) return true
|
|
const cur = delegateInflight.get(kind) || 0
|
|
if (cur >= max) return false
|
|
delegateInflight.set(kind, cur + 1)
|
|
return true
|
|
}
|
|
|
|
/** @param {string} kind */
|
|
export function bareOsDelegateConcurrentExit(kind) {
|
|
const cur = (delegateInflight.get(kind) || 0) - 1
|
|
if (cur <= 0) delegateInflight.delete(kind)
|
|
else delegateInflight.set(kind, cur)
|
|
}
|
|
|
|
/** Snapshot for metrics / fairness introspection (not a security boundary). */
|
|
export function bareOsDelegateInflightSnapshot() {
|
|
return Object.fromEntries(delegateInflight)
|
|
}
|