@adaptic/utils 0.0.990 → 0.0.991

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/dist/index.cjs CHANGED
@@ -6044,6 +6044,202 @@ async function createLimitOrder(auth, params = {
6044
6044
  }
6045
6045
 
6046
6046
  // Utility function for debug logging
6047
+ /** Sliding-window size (number of recent outcomes tracked per host). */
6048
+ const CIRCUIT_WINDOW_SIZE = 20;
6049
+ /** Maximum age (ms) of an outcome before it is dropped from the window. */
6050
+ const CIRCUIT_WINDOW_TTL_MS = 30_000;
6051
+ /**
6052
+ * Failure ratio (0..1) at which the breaker trips when the window
6053
+ * is full (i.e. CIRCUIT_WINDOW_SIZE outcomes recorded).
6054
+ *
6055
+ * Tuned to be permissive enough that a few transient failures during
6056
+ * normal operation do not trip the breaker, but tight enough that a
6057
+ * persistent upstream outage (where >= half of recent calls are
6058
+ * failing) is detected quickly. With WINDOW=20 and threshold=0.6 we
6059
+ * need 12 failures within the most recent 20 attempts to trip.
6060
+ */
6061
+ const CIRCUIT_TRIP_FAILURE_RATIO = 0.6;
6062
+ /**
6063
+ * Minimum number of recent outcomes required before the failure-ratio
6064
+ * gate is even evaluated. Without this guard, a single failure on a
6065
+ * cold host would give a 100 % ratio and trip the breaker on the
6066
+ * second attempt — which would be useless protection while also being
6067
+ * highly destructive.
6068
+ */
6069
+ const CIRCUIT_MIN_SAMPLES = 8;
6070
+ /**
6071
+ * How long the breaker stays open before transitioning to half-open
6072
+ * (i.e. allowing the next request through as a probe). The next
6073
+ * outcome — success or failure — fully recloses or re-opens the
6074
+ * breaker. 5 s aligns with typical upstream recovery times and is
6075
+ * short enough that the next caller drives the probe.
6076
+ */
6077
+ const CIRCUIT_OPEN_COOLDOWN_MS = 5_000;
6078
+ /**
6079
+ * Fail-fast latency. We sleep a short, deterministic amount before
6080
+ * rejecting so the upstream caller's outer timeout (commonly 10–25 s)
6081
+ * sees a clean rejection rather than a synchronous reject-storm that
6082
+ * could starve other event-loop work. 100 ms aligns with the user's
6083
+ * G1 analysis target: "cap per-symbol fallback latency at 100 ms
6084
+ * during outages — eliminating the 25 s × N-concurrent-symbols
6085
+ * event-loop hog."
6086
+ */
6087
+ const CIRCUIT_FAIL_FAST_LATENCY_MS = 100;
6088
+ const circuitStates = new Map();
6089
+ function getCircuitState(host) {
6090
+ let state = circuitStates.get(host);
6091
+ if (!state) {
6092
+ state = {
6093
+ host,
6094
+ recent: [],
6095
+ openedAt: 0,
6096
+ lastTripFailureRatio: 0,
6097
+ };
6098
+ circuitStates.set(host, state);
6099
+ }
6100
+ return state;
6101
+ }
6102
+ function pruneStaleSamples(state, now) {
6103
+ const cutoff = now - CIRCUIT_WINDOW_TTL_MS;
6104
+ // Remove entries older than the TTL. Window is small so a simple
6105
+ // filter is fine — no need for a deque structure.
6106
+ if (state.recent.length === 0)
6107
+ return;
6108
+ let firstFreshIndex = 0;
6109
+ while (firstFreshIndex < state.recent.length &&
6110
+ state.recent[firstFreshIndex].atMs < cutoff) {
6111
+ firstFreshIndex += 1;
6112
+ }
6113
+ if (firstFreshIndex > 0) {
6114
+ state.recent.splice(0, firstFreshIndex);
6115
+ }
6116
+ }
6117
+ function recordOutcome(host, ok) {
6118
+ const now = Date.now();
6119
+ const state = getCircuitState(host);
6120
+ pruneStaleSamples(state, now);
6121
+ state.recent.push({ atMs: now, ok });
6122
+ if (state.recent.length > CIRCUIT_WINDOW_SIZE) {
6123
+ state.recent.shift();
6124
+ }
6125
+ // If we are in the open or half-open window and just received an
6126
+ // outcome, decide whether to close or re-open.
6127
+ if (state.openedAt > 0) {
6128
+ if (now - state.openedAt >= CIRCUIT_OPEN_COOLDOWN_MS) {
6129
+ // Half-open probe outcome arrived.
6130
+ if (ok) {
6131
+ // Recovered. Close the breaker.
6132
+ state.openedAt = 0;
6133
+ state.lastTripFailureRatio = 0;
6134
+ getLogger().info(`Circuit breaker for ${host} closed — upstream recovered`, { host });
6135
+ }
6136
+ else {
6137
+ // Probe failed. Re-open the breaker for another cooldown.
6138
+ state.openedAt = now;
6139
+ }
6140
+ return;
6141
+ }
6142
+ // Still inside the cooldown window — outcomes are recorded for
6143
+ // statistics but the breaker stays open regardless.
6144
+ return;
6145
+ }
6146
+ // Closed breaker — evaluate whether the failure ratio has tripped.
6147
+ if (state.recent.length < CIRCUIT_MIN_SAMPLES)
6148
+ return;
6149
+ const failures = state.recent.reduce((acc, entry) => acc + (entry.ok ? 0 : 1), 0);
6150
+ const ratio = failures / state.recent.length;
6151
+ if (ratio >= CIRCUIT_TRIP_FAILURE_RATIO) {
6152
+ state.openedAt = now;
6153
+ state.lastTripFailureRatio = ratio;
6154
+ getLogger().warn(`Circuit breaker for ${host} opened — ${failures}/${state.recent.length} recent attempts failed (${(ratio * 100).toFixed(0)}%); fail-fast for ${CIRCUIT_OPEN_COOLDOWN_MS}ms`, {
6155
+ host,
6156
+ recentFailures: failures,
6157
+ recentSamples: state.recent.length,
6158
+ failureRatio: ratio,
6159
+ cooldownMs: CIRCUIT_OPEN_COOLDOWN_MS,
6160
+ });
6161
+ }
6162
+ }
6163
+ function isCircuitOpen(host, now) {
6164
+ const state = circuitStates.get(host);
6165
+ if (!state || state.openedAt === 0)
6166
+ return false;
6167
+ pruneStaleSamples(state, now);
6168
+ return now - state.openedAt < CIRCUIT_OPEN_COOLDOWN_MS;
6169
+ }
6170
+ /**
6171
+ * Error thrown by {@link fetchWithRetry} when the per-host circuit
6172
+ * breaker is open and fail-fast suppression is in effect.
6173
+ *
6174
+ * Carries the host, the failure ratio that tripped the breaker, and
6175
+ * the remaining cooldown so callers can render an actionable log.
6176
+ */
6177
+ class CircuitOpenError extends Error {
6178
+ code = "MASSIVE_CIRCUIT_OPEN";
6179
+ host;
6180
+ tripFailureRatio;
6181
+ cooldownRemainingMs;
6182
+ constructor(host, tripFailureRatio, cooldownRemainingMs) {
6183
+ super(`Circuit open for ${host} — fail-fast (recent failure ratio ${(tripFailureRatio * 100).toFixed(0)}%, retry in ${cooldownRemainingMs}ms)`);
6184
+ this.name = "CircuitOpenError";
6185
+ this.host = host;
6186
+ this.tripFailureRatio = tripFailureRatio;
6187
+ this.cooldownRemainingMs = cooldownRemainingMs;
6188
+ }
6189
+ }
6190
+ /**
6191
+ * Force-close the breaker for a given host. Exposed for tests and
6192
+ * operator-runbook scripts so a stuck-open breaker can be reset
6193
+ * without bouncing the process. Not intended for hot-path use.
6194
+ *
6195
+ * @param host The hostname whose breaker should be reset.
6196
+ */
6197
+ function resetCircuitBreaker(host) {
6198
+ const state = circuitStates.get(host);
6199
+ if (!state)
6200
+ return;
6201
+ state.openedAt = 0;
6202
+ state.lastTripFailureRatio = 0;
6203
+ state.recent = [];
6204
+ }
6205
+ /**
6206
+ * Snapshot of all known per-host circuit-breaker states. Intended for
6207
+ * an operational-truth / status endpoint to surface upstream health.
6208
+ *
6209
+ * @returns Map of host → {open, openedAt, recentSamples, failureRatio,
6210
+ * lastTripFailureRatio}.
6211
+ */
6212
+ function getCircuitBreakerSnapshot() {
6213
+ const now = Date.now();
6214
+ const snapshot = {};
6215
+ for (const [host, state] of circuitStates) {
6216
+ pruneStaleSamples(state, now);
6217
+ const failures = state.recent.reduce((acc, entry) => acc + (entry.ok ? 0 : 1), 0);
6218
+ const ratio = state.recent.length > 0 ? failures / state.recent.length : 0;
6219
+ snapshot[host] = {
6220
+ open: state.openedAt > 0 && now - state.openedAt < CIRCUIT_OPEN_COOLDOWN_MS,
6221
+ openedAt: state.openedAt,
6222
+ cooldownRemainingMs: state.openedAt > 0
6223
+ ? Math.max(0, CIRCUIT_OPEN_COOLDOWN_MS - (now - state.openedAt))
6224
+ : 0,
6225
+ recentSamples: state.recent.length,
6226
+ failureRatio: ratio,
6227
+ lastTripFailureRatio: state.lastTripFailureRatio,
6228
+ };
6229
+ }
6230
+ return snapshot;
6231
+ }
6232
+ function hostnameFromUrl(url) {
6233
+ try {
6234
+ return new URL(url).hostname;
6235
+ }
6236
+ catch {
6237
+ return null;
6238
+ }
6239
+ }
6240
+ function sleep(ms) {
6241
+ return new Promise((resolve) => setTimeout(resolve, ms));
6242
+ }
6047
6243
  /**
6048
6244
  * Debug logging utility that respects environment debug flags.
6049
6245
  * Logs messages through the configured structured logger when LUMIC_DEBUG
@@ -6155,9 +6351,46 @@ function hideApiKeyFromurl(url) {
6155
6351
  * @throws Will throw an error if the fetch fails after the specified number of retries.
6156
6352
  */
6157
6353
  async function fetchWithRetry(url, options = {}, retries = 3, initialBackoff = 1000) {
6354
+ // Per-host circuit-breaker check. When upstream is failing
6355
+ // pervasively (e.g. Massive REST in an outage), short-circuit to a
6356
+ // 100 ms fail-fast rejection so the caller's outer timeout (25 s,
6357
+ // 10 s, etc.) does not pile concurrent symbol fetches against a
6358
+ // dead host. Without this, an upstream outage during a screener tick
6359
+ // can lock up the event loop for up to (timeout × N-concurrent-symbols).
6360
+ const host = hostnameFromUrl(url);
6361
+ if (host) {
6362
+ const now = Date.now();
6363
+ if (isCircuitOpen(host, now)) {
6364
+ const state = getCircuitState(host);
6365
+ const cooldownRemainingMs = Math.max(0, CIRCUIT_OPEN_COOLDOWN_MS - (now - state.openedAt));
6366
+ await sleep(CIRCUIT_FAIL_FAST_LATENCY_MS);
6367
+ throw new CircuitOpenError(host, state.lastTripFailureRatio, cooldownRemainingMs);
6368
+ }
6369
+ }
6158
6370
  return withRetry(async () => {
6159
- const response = await fetch(url, options);
6371
+ let response;
6372
+ try {
6373
+ response = await fetch(url, options);
6374
+ }
6375
+ catch (networkError) {
6376
+ // Network failure (e.g. DNS, connection refused, TLS abort).
6377
+ // Record against the breaker so a sustained outage trips it
6378
+ // for subsequent calls; then re-throw so withRetry handles
6379
+ // its own retry policy.
6380
+ if (host)
6381
+ recordOutcome(host, false);
6382
+ throw networkError;
6383
+ }
6160
6384
  if (!response.ok) {
6385
+ // Classify the outcome for the circuit breaker. 5xx and 429
6386
+ // are upstream-health signals (record as failure). 4xx client
6387
+ // errors are caller-side and should NOT affect the breaker —
6388
+ // a request with a bad API key shouldn't trip the host's
6389
+ // breaker for everyone else.
6390
+ const upstreamUnhealthy = response.status === 429 ||
6391
+ (response.status >= 500 && response.status < 600);
6392
+ if (host)
6393
+ recordOutcome(host, !upstreamUnhealthy);
6161
6394
  // Enhanced HTTP error handling with specific error types
6162
6395
  if (response.status === 429) {
6163
6396
  // Check for Retry-After header
@@ -6189,6 +6422,10 @@ async function fetchWithRetry(url, options = {}, retries = 3, initialBackoff = 1
6189
6422
  error.response = response;
6190
6423
  throw error;
6191
6424
  }
6425
+ // Success — record against the breaker so a healthy upstream
6426
+ // closes any half-open state cleanly.
6427
+ if (host)
6428
+ recordOutcome(host, true);
6192
6429
  return response;
6193
6430
  }, {
6194
6431
  maxRetries: retries,
@@ -69379,6 +69616,17 @@ const adaptic = {
69379
69616
  logIfDebug: logIfDebug,
69380
69617
  fetchWithRetry: fetchWithRetry,
69381
69618
  validateMassiveApiKey: validateMassiveApiKey,
69619
+ /**
69620
+ * Force-close a stuck-open per-host circuit breaker. Operator
69621
+ * runbook utility — see {@link misc.resetCircuitBreaker}.
69622
+ */
69623
+ resetCircuitBreaker: resetCircuitBreaker,
69624
+ /**
69625
+ * Read-only snapshot of all per-host circuit-breaker states for
69626
+ * use in operational-truth endpoints. See
69627
+ * {@link misc.getCircuitBreakerSnapshot}.
69628
+ */
69629
+ getCircuitBreakerSnapshot: getCircuitBreakerSnapshot,
69382
69630
  },
69383
69631
  rateLimiter: {
69384
69632
  TokenBucketRateLimiter,
@@ -69417,6 +69665,7 @@ exports.AssetAllocationEngine = AssetAllocationEngine;
69417
69665
  exports.AuthenticationError = AuthenticationError;
69418
69666
  exports.BTC_PAIRS = BTC_PAIRS;
69419
69667
  exports.BarError = BarError;
69668
+ exports.CircuitOpenError = CircuitOpenError;
69420
69669
  exports.CryptoDataError = CryptoDataError;
69421
69670
  exports.CryptoOrderError = CryptoOrderError;
69422
69671
  exports.DEFAULT_CACHE_OPTIONS = DEFAULT_CACHE_OPTIONS;