@goodandready/dsh-key-rotation 0.7.30 → 0.7.32

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.
@@ -1,72 +1,73 @@
1
- // concurrency.js — per-key in-flight counter + least-connections picking (issue #193).
2
-
3
- export const CONCURRENCY_DEFAULT_LIMIT = 0;
4
- export const CONCURRENCY_STALE_LOCK_MS = 5 * 60 * 1000;
5
-
6
- export class ConcurrencyTracker {
7
- constructor(opts) {
8
- opts = opts || {};
9
- const limit = opts.limit !== undefined ? opts.limit : CONCURRENCY_DEFAULT_LIMIT;
10
- this._limit = (Number.isFinite(limit) && limit >= 0) ? Math.floor(limit) : 0;
11
- this._staleMs = opts.staleMs || CONCURRENCY_STALE_LOCK_MS;
12
- this._inFlight = new Map();
13
- }
14
-
15
- isEnabled() { return this._limit > 0; }
16
- get limit() { return this._limit; }
17
-
18
- acquire(ref, now) {
19
- now = now || Date.now();
20
- if (!this.isEnabled()) return true;
21
- let e = this._inFlight.get(ref);
22
- if (!e) {
23
- e = { count: 0, lastAcquired: now };
24
- this._inFlight.set(ref, e);
25
- }
26
- if (now - e.lastAcquired > this._staleMs) {
27
- e.count = 0;
28
- }
29
- if (e.count >= this._limit) return false;
30
- e.count += 1;
31
- e.lastAcquired = now;
32
- return true;
33
- }
34
-
35
- release(ref, now) {
36
- now = now || Date.now();
37
- const e = this._inFlight.get(ref);
38
- if (!e) return;
39
- e.count = Math.max(0, e.count - 1);
40
- e.lastAcquired = now;
41
- }
42
-
43
- snapshot() {
44
- const out = {};
45
- for (const [k, v] of this._inFlight) out[k] = { count: v.count };
46
- return out;
47
- }
48
-
49
- pickLeastLoaded(candidates, now) {
50
- now = now || Date.now();
51
- if (!Array.isArray(candidates) || candidates.length === 0) return null;
52
- let best = null;
53
- let bestCount = Infinity;
54
- for (const ref of candidates) {
55
- const e = this._inFlight.get(ref);
56
- const count = e ? e.count : 0;
57
- if (this.isEnabled() && count >= this._limit) continue;
58
- if (count < bestCount) {
59
- best = ref;
60
- bestCount = count;
61
- }
62
- }
63
- return best;
64
- }
65
-
66
- clear(ref) {
67
- if (ref) this._inFlight.delete(ref);
68
- else this._inFlight.clear();
69
- }
70
-
71
- get size() { return this._inFlight.size; }
72
- }
1
+ // concurrency.js — per-key in-flight counter + least-connections picking (issue #193).
2
+
3
+ export const CONCURRENCY_DEFAULT_LIMIT = 0;
4
+ export const CONCURRENCY_STALE_LOCK_MS = 5 * 60 * 1000;
5
+
6
+ export class ConcurrencyTracker {
7
+ constructor(opts) {
8
+ opts = opts || {};
9
+ const limit = opts.limit !== undefined ? opts.limit : CONCURRENCY_DEFAULT_LIMIT;
10
+ this._limit = (Number.isFinite(limit) && limit >= 0) ? Math.floor(limit) : 0;
11
+ this._staleMs = opts.staleMs || CONCURRENCY_STALE_LOCK_MS;
12
+ this._inFlight = new Map();
13
+ }
14
+
15
+ isEnabled() { return this._limit > 0; }
16
+ get limit() { return this._limit; }
17
+
18
+ acquire(ref, now) {
19
+ now = now || Date.now();
20
+ if (!this.isEnabled()) return true;
21
+ let e = this._inFlight.get(ref);
22
+ if (!e) {
23
+ e = { count: 0, lastAcquired: now };
24
+ this._inFlight.set(ref, e);
25
+ }
26
+ if (now - e.lastAcquired > this._staleMs) {
27
+ e.count = 0;
28
+ }
29
+ if (e.count >= this._limit) return false;
30
+ e.count += 1;
31
+ e.lastAcquired = now;
32
+ return true;
33
+ }
34
+
35
+ release(ref, now) {
36
+ now = now || Date.now();
37
+ const e = this._inFlight.get(ref);
38
+ if (!e) return;
39
+ e.count = Math.max(0, e.count - 1);
40
+ e.lastAcquired = now;
41
+ }
42
+
43
+ snapshot() {
44
+ const out = {};
45
+ for (const [k, v] of this._inFlight) out[k] = { count: v.count };
46
+ return out;
47
+ }
48
+
49
+ pickLeastLoaded(candidates, now) {
50
+ now = now || Date.now();
51
+ if (!Array.isArray(candidates) || candidates.length === 0) return null;
52
+ let best = null;
53
+ let bestCount = Infinity;
54
+ for (const ref of candidates) {
55
+ const e = this._inFlight.get(ref);
56
+ let count = e ? e.count : 0;
57
+ if (e && now - e.lastAcquired > this._staleMs) count = 0;
58
+ if (this.isEnabled() && count >= this._limit) continue;
59
+ if (count < bestCount) {
60
+ best = ref;
61
+ bestCount = count;
62
+ }
63
+ }
64
+ return best;
65
+ }
66
+
67
+ clear(ref) {
68
+ if (ref) this._inFlight.delete(ref);
69
+ else this._inFlight.clear();
70
+ }
71
+
72
+ get size() { return this._inFlight.size; }
73
+ }
package/lib/heal.js CHANGED
@@ -1,35 +1,35 @@
1
- // heal.js — self-healing idle cooldowns.
2
- // ponytail: pure function, easy to test, no side effects beyond mutation of passed-in state.
3
-
4
- // Returns array of { ref, poolBase } entries that were healed in this tick.
5
- // Mutates `pools` (removes from failedUntil, pushes heal event into events).
6
- // `now` parameter is injectable for tests.
7
- export function healIdleCooldowns(pools, idleMs, now = Date.now()) {
8
- if (!Array.isArray(pools) || pools.length === 0) return [];
9
- if (!Number.isFinite(idleMs) || idleMs <= 0) return [];
10
- const healed = [];
11
- for (const pool of pools) {
12
- if (!pool || !pool.state || !pool.base) continue;
13
- const fu = pool.state.failedUntil;
14
- const lu = pool.state.lastUsed;
15
- if (!fu || fu.size === 0) continue;
16
- const expiredRefs = [];
17
- for (const [ref, until] of fu.entries()) {
18
- if (!Number.isFinite(until)) continue;
19
- if (until > now) continue; // cooldown still active
20
- const last = lu ? lu.get(ref) : undefined;
21
- if (!Number.isFinite(last)) continue; // never used → no signal, skip
22
- if (now - last < idleMs) continue; // used recently → don't heal
23
- expiredRefs.push(ref);
24
- }
25
- for (const ref of expiredRefs) {
26
- fu.delete(ref);
27
- if (Array.isArray(pool.state.events)) {
28
- pool.state.events.push({ at: now, ref, reason: 'self-heal', cooldownMs: 0, type: 'heal' });
29
- if (pool.state.events.length > 50) pool.state.events.shift();
30
- }
31
- healed.push({ ref, poolBase: pool.base });
32
- }
33
- }
34
- return healed;
35
- }
1
+ // heal.js — self-healing idle cooldowns.
2
+ // ponytail: pure function, easy to test, no side effects beyond mutation of passed-in state.
3
+
4
+ // Returns array of { ref, poolBase } entries that were healed in this tick.
5
+ // Mutates `pools` (removes from failedUntil, pushes heal event into events).
6
+ // `now` parameter is injectable for tests.
7
+ export function healIdleCooldowns(pools, idleMs, now = Date.now()) {
8
+ if (!Array.isArray(pools) || pools.length === 0) return [];
9
+ if (!Number.isFinite(idleMs) || idleMs <= 0) return [];
10
+ const healed = [];
11
+ for (const pool of pools) {
12
+ if (!pool || !pool.state || !pool.base) continue;
13
+ const fu = pool.state.failedUntil;
14
+ const lu = pool.state.lastUsed;
15
+ if (!fu || fu.size === 0) continue;
16
+ const expiredRefs = [];
17
+ for (const [ref, until] of fu.entries()) {
18
+ if (!Number.isFinite(until)) continue;
19
+ if (until > now) continue; // cooldown still active
20
+ const last = lu ? lu.get(ref) : undefined;
21
+ if (!Number.isFinite(last)) continue; // never used → no signal, skip
22
+ if (now - last < idleMs) continue; // used recently → don't heal
23
+ expiredRefs.push(ref);
24
+ }
25
+ for (const ref of expiredRefs) {
26
+ fu.delete(ref);
27
+ if (Array.isArray(pool.state.events)) {
28
+ pool.state.events.push({ at: now, ref, reason: 'self-heal', cooldownMs: 0, type: 'heal' });
29
+ if (pool.state.events.length > 50) pool.state.events.shift();
30
+ }
31
+ healed.push({ ref, poolBase: pool.base });
32
+ }
33
+ }
34
+ return healed;
35
+ }
package/lib/histogram.js CHANGED
@@ -1,66 +1,66 @@
1
- // histogram.js — per-ref latency ring buffer + percentile.
2
- // ponytail: ring buffer of fixed size, sort-on-read for percentile, no libraries.
3
-
4
- export const LATENCY_DEFAULT_WINDOW = 200;
5
-
6
- export class LatencyHistogram {
7
- constructor({ window = LATENCY_DEFAULT_WINDOW } = {}) {
8
- const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : LATENCY_DEFAULT_WINDOW;
9
- this._window = w;
10
- this._buffers = new Map(); // ref -> Float64Array of size w, plus index/count
11
- this._lastAt = new Map(); // ref -> epochMs of last sample
12
- }
13
-
14
- record(ref, ms) {
15
- if (!ref || !Number.isFinite(ms) || ms < 0) return;
16
- let entry = this._buffers.get(ref);
17
- if (!entry) {
18
- entry = { buf: new Float64Array(this._window), head: 0, count: 0 };
19
- this._buffers.set(ref, entry);
20
- }
21
- entry.buf[entry.head] = ms;
22
- entry.head = (entry.head + 1) % this._window;
23
- if (entry.count < this._window) entry.count += 1;
24
- this._lastAt.set(ref, Date.now());
25
- }
26
-
27
- // Returns p50/p95/p99 in milliseconds, plus count and lastAt. Sorted copy.
28
- snapshot(ref) {
29
- const entry = this._buffers.get(ref);
30
- const lastAt = this._lastAt.get(ref);
31
- if (!entry || entry.count === 0) {
32
- return { count: 0, lastAt: lastAt || null };
33
- }
34
- const arr = entry.buf.subarray(0, entry.count);
35
- const sorted = Array.from(arr).sort((a, b) => a - b);
36
- const n = sorted.length;
37
- return {
38
- count: n,
39
- lastAt: lastAt || null,
40
- p50: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.5))],
41
- p95: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.95))],
42
- p99: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.99))],
43
- };
44
- }
45
-
46
- // Returns { [ref]: snapshot }
47
- snapshotAll() {
48
- const out = {};
49
- for (const ref of this._buffers.keys()) out[ref] = this.snapshot(ref);
50
- return out;
51
- }
52
-
53
- clear(ref) {
54
- if (ref) {
55
- this._buffers.delete(ref);
56
- this._lastAt.delete(ref);
57
- } else {
58
- this._buffers.clear();
59
- this._lastAt.clear();
60
- }
61
- }
62
-
63
- get size() {
64
- return this._buffers.size;
65
- }
66
- }
1
+ // histogram.js — per-ref latency ring buffer + percentile.
2
+ // ponytail: ring buffer of fixed size, sort-on-read for percentile, no libraries.
3
+
4
+ export const LATENCY_DEFAULT_WINDOW = 200;
5
+
6
+ export class LatencyHistogram {
7
+ constructor({ window = LATENCY_DEFAULT_WINDOW } = {}) {
8
+ const w = Number.isFinite(window) && window > 0 ? Math.floor(window) : LATENCY_DEFAULT_WINDOW;
9
+ this._window = w;
10
+ this._buffers = new Map(); // ref -> Float64Array of size w, plus index/count
11
+ this._lastAt = new Map(); // ref -> epochMs of last sample
12
+ }
13
+
14
+ record(ref, ms) {
15
+ if (!ref || !Number.isFinite(ms) || ms < 0) return;
16
+ let entry = this._buffers.get(ref);
17
+ if (!entry) {
18
+ entry = { buf: new Float64Array(this._window), head: 0, count: 0 };
19
+ this._buffers.set(ref, entry);
20
+ }
21
+ entry.buf[entry.head] = ms;
22
+ entry.head = (entry.head + 1) % this._window;
23
+ if (entry.count < this._window) entry.count += 1;
24
+ this._lastAt.set(ref, Date.now());
25
+ }
26
+
27
+ // Returns p50/p95/p99 in milliseconds, plus count and lastAt. Sorted copy.
28
+ snapshot(ref) {
29
+ const entry = this._buffers.get(ref);
30
+ const lastAt = this._lastAt.get(ref);
31
+ if (!entry || entry.count === 0) {
32
+ return { count: 0, lastAt: lastAt || null };
33
+ }
34
+ const arr = entry.buf.subarray(0, entry.count);
35
+ const sorted = Array.from(arr).sort((a, b) => a - b);
36
+ const n = sorted.length;
37
+ return {
38
+ count: n,
39
+ lastAt: lastAt || null,
40
+ p50: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.5))],
41
+ p95: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.95))],
42
+ p99: sorted[Math.min(n - 1, Math.floor((n - 1) * 0.99))],
43
+ };
44
+ }
45
+
46
+ // Returns { [ref]: snapshot }
47
+ snapshotAll() {
48
+ const out = {};
49
+ for (const ref of this._buffers.keys()) out[ref] = this.snapshot(ref);
50
+ return out;
51
+ }
52
+
53
+ clear(ref) {
54
+ if (ref) {
55
+ this._buffers.delete(ref);
56
+ this._lastAt.delete(ref);
57
+ } else {
58
+ this._buffers.clear();
59
+ this._lastAt.clear();
60
+ }
61
+ }
62
+
63
+ get size() {
64
+ return this._buffers.size;
65
+ }
66
+ }
package/lib/incident.js CHANGED
@@ -1,76 +1,76 @@
1
- // lib/incident.js — auto-create Gitea issue when pool exhausted > threshold.
2
- // ponytail: minimal — caller provides a token + base URL. No retries on rate-limit.
3
-
4
- export const INCIDENT_DEFAULT_THRESHOLD_MS = 5 * 60 * 1000; // 5 min
5
- export const INCIDENT_DEFAULT_COOLDOWN_MS = 30 * 60 * 1000; // 30 min between incidents per provider
6
- export const INCIDENT_TIMEOUT_MS = 5000;
7
-
8
- export class IncidentReporter {
9
- constructor({ token, baseUrl, repo, thresholdMs = INCIDENT_DEFAULT_THRESHOLD_MS, cooldownMs = INCIDENT_DEFAULT_COOLDOWN_MS, fetchImpl } = {}) {
10
- if (!token) throw new Error('incident: token required');
11
- if (!baseUrl) throw new Error('incident: baseUrl required');
12
- if (!repo || !repo.includes('/')) throw new Error('incident: repo (owner/name) required');
13
- this._token = token;
14
- this._baseUrl = baseUrl.replace(/\/+$/, '');
15
- this._repo = repo;
16
- this._thresholdMs = thresholdMs;
17
- this._cooldownMs = cooldownMs;
18
- this._lastIncidentAt = new Map(); // provider -> epochMs
19
- this._fetch = fetchImpl || (typeof fetch !== 'undefined' ? fetch : () => { throw new Error('incident: no fetch available'); });
20
- }
21
-
22
- // Should we report now? Pure; does not perform I/O.
23
- shouldReport(provider, exhaustedSince, now = Date.now()) {
24
- if (!provider) return false;
25
- if (!Number.isFinite(exhaustedSince)) return false;
26
- if (now - exhaustedSince < this._thresholdMs) return false;
27
- const last = this._lastIncidentAt.get(provider);
28
- if (Number.isFinite(last) && now - last < this._cooldownMs) return false;
29
- return true;
30
- }
31
-
32
- markReported(provider, at = Date.now()) {
33
- this._lastIncidentAt.set(provider, at);
34
- }
35
-
36
- resetCooldown(provider) {
37
- if (provider) this._lastIncidentAt.delete(provider);
38
- else this._lastIncidentAt.clear();
39
- }
40
-
41
- // Open a Gitea issue. ponytail: minimal payload, ignore failures.
42
- async open(provider, exhaustedSince, now = Date.now()) {
43
- if (!this.shouldReport(provider, exhaustedSince, now)) return { reported: false };
44
- const url = `${this._baseUrl}/api/v1/repos/${this._repo}/issues`;
45
- const body = {
46
- title: `prod-incident: pool ${provider} exhausted since ${new Date(exhaustedSince).toISOString()}`,
47
- body: [
48
- 'Auto-generated by `dsh-key-rotation`.',
49
- '',
50
- `- provider: \`${provider}\``,
51
- `- exhaustedSince: \`${new Date(exhaustedSince).toISOString()}\``,
52
- '',
53
- 'All keys in the pool are in cooldown or missing. Check OpenCode provider status and rotate keys.',
54
- ].join('\n'),
55
- labels: ['prod-incident'],
56
- };
57
- const ctrl = new AbortController();
58
- const timer = setTimeout(() => ctrl.abort(), INCIDENT_TIMEOUT_MS);
59
- try {
60
- const res = await this._fetch(url, {
61
- method: 'POST',
62
- headers: { authorization: `token ${this._token}`, 'content-type': 'application/json' },
63
- body: JSON.stringify(body),
64
- signal: ctrl.signal,
65
- });
66
- if (!res.ok) return { reported: false, status: res.status };
67
- const data = await res.json();
68
- this.markReported(provider, now);
69
- return { reported: true, number: data.number, url: data.html_url };
70
- } catch (_) {
71
- return { reported: false };
72
- } finally {
73
- clearTimeout(timer);
74
- }
75
- }
76
- }
1
+ // lib/incident.js — auto-create Gitea issue when pool exhausted > threshold.
2
+ // ponytail: minimal — caller provides a token + base URL. No retries on rate-limit.
3
+
4
+ export const INCIDENT_DEFAULT_THRESHOLD_MS = 5 * 60 * 1000; // 5 min
5
+ export const INCIDENT_DEFAULT_COOLDOWN_MS = 30 * 60 * 1000; // 30 min between incidents per provider
6
+ export const INCIDENT_TIMEOUT_MS = 5000;
7
+
8
+ export class IncidentReporter {
9
+ constructor({ token, baseUrl, repo, thresholdMs = INCIDENT_DEFAULT_THRESHOLD_MS, cooldownMs = INCIDENT_DEFAULT_COOLDOWN_MS, fetchImpl } = {}) {
10
+ if (!token) throw new Error('incident: token required');
11
+ if (!baseUrl) throw new Error('incident: baseUrl required');
12
+ if (!repo || !repo.includes('/')) throw new Error('incident: repo (owner/name) required');
13
+ this._token = token;
14
+ this._baseUrl = baseUrl.replace(/\/+$/, '');
15
+ this._repo = repo;
16
+ this._thresholdMs = thresholdMs;
17
+ this._cooldownMs = cooldownMs;
18
+ this._lastIncidentAt = new Map(); // provider -> epochMs
19
+ this._fetch = fetchImpl || (typeof fetch !== 'undefined' ? fetch : () => { throw new Error('incident: no fetch available'); });
20
+ }
21
+
22
+ // Should we report now? Pure; does not perform I/O.
23
+ shouldReport(provider, exhaustedSince, now = Date.now()) {
24
+ if (!provider) return false;
25
+ if (!Number.isFinite(exhaustedSince)) return false;
26
+ if (now - exhaustedSince < this._thresholdMs) return false;
27
+ const last = this._lastIncidentAt.get(provider);
28
+ if (Number.isFinite(last) && now - last < this._cooldownMs) return false;
29
+ return true;
30
+ }
31
+
32
+ markReported(provider, at = Date.now()) {
33
+ this._lastIncidentAt.set(provider, at);
34
+ }
35
+
36
+ resetCooldown(provider) {
37
+ if (provider) this._lastIncidentAt.delete(provider);
38
+ else this._lastIncidentAt.clear();
39
+ }
40
+
41
+ // Open a Gitea issue. ponytail: minimal payload, ignore failures.
42
+ async open(provider, exhaustedSince, now = Date.now()) {
43
+ if (!this.shouldReport(provider, exhaustedSince, now)) return { reported: false };
44
+ const url = `${this._baseUrl}/api/v1/repos/${this._repo}/issues`;
45
+ const body = {
46
+ title: `prod-incident: pool ${provider} exhausted since ${new Date(exhaustedSince).toISOString()}`,
47
+ body: [
48
+ 'Auto-generated by `dsh-key-rotation`.',
49
+ '',
50
+ `- provider: \`${provider}\``,
51
+ `- exhaustedSince: \`${new Date(exhaustedSince).toISOString()}\``,
52
+ '',
53
+ 'All keys in the pool are in cooldown or missing. Check OpenCode provider status and rotate keys.',
54
+ ].join('\n'),
55
+ labels: ['prod-incident'],
56
+ };
57
+ const ctrl = new AbortController();
58
+ const timer = setTimeout(() => ctrl.abort(), INCIDENT_TIMEOUT_MS);
59
+ try {
60
+ const res = await this._fetch(url, {
61
+ method: 'POST',
62
+ headers: { authorization: `token ${this._token}`, 'content-type': 'application/json' },
63
+ body: JSON.stringify(body),
64
+ signal: ctrl.signal,
65
+ });
66
+ if (!res.ok) return { reported: false, status: res.status };
67
+ const data = await res.json();
68
+ this.markReported(provider, now);
69
+ return { reported: true, number: data.number, url: data.html_url };
70
+ } catch (_) {
71
+ return { reported: false };
72
+ } finally {
73
+ clearTimeout(timer);
74
+ }
75
+ }
76
+ }