// Traffic switch for merchant code (Node 18+): send a payment to the incumbent provider or to Knox. // Same assignment as knox_switch.py: sha256("salt:key"), first 8 bytes big-endian, modulo 10000, below share*100 -> knox. import { createHash } from "node:crypto"; const BUCKETS = 10000n; const MAX_BATCH = 500; // Meta observation API limit export function bucket(salt, key) { const digest = createHash("sha256").update(`${salt}:${key}`).digest(); return Number(digest.readBigUInt64BE(0) % BUCKETS); } export function assign(salt, key, sharePercent) { return bucket(salt, key) < Math.round((sharePercent * Number(BUCKETS)) / 100) ? "knox" : "incumbent"; } export class KnoxSwitch { constructor({ apiBase = "https://meta.knoxapi.com", secretKey, rampTtlMs = 60000, batchSize = 50, controlPrefix = "/v1", timeoutMs = 5000 }) { this.apiBase = apiBase.replace(/\/$/, "") + "/" + controlPrefix.replace(/^\/+|\/+$/g, ""); this.headers = { Authorization: `Bearer ${secretKey}`, "Content-Type": "application/json" }; this.rampTtlMs = rampTtlMs; this.batchSize = batchSize; this.rampState = null; this.fetchedAt = null; this.refresh = null; this.timeoutMs = timeoutMs; this.pending = []; } async ramp() { if (this.fetchedAt === null || Date.now() - this.fetchedAt >= this.rampTtlMs) { if (this.refresh === null) { this.refresh = this.refreshRamp().finally(() => { this.refresh = null; }); } await this.refresh; } return this.rampState; } async refreshRamp() { try { const response = await fetch(`${this.apiBase}/traffic/ramp`, { headers: this.headers, signal: AbortSignal.timeout(this.timeoutMs) }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const ramp = await response.json(); if (!ramp || !["running", "paused"].includes(ramp.state) || typeof ramp.salt !== "string" || !ramp.salt || typeof ramp.share_percent !== "number" || !Number.isFinite(ramp.share_percent) || ramp.share_percent < 0 || ramp.share_percent > 100) throw new Error("Invalid migration control state"); this.rampState = ramp; } catch { this.rampState = null; } this.fetchedAt = Date.now(); } async armFor(key, existingArm = null) { if (existingArm !== null) { if (!["incumbent", "knox"].includes(existingArm)) throw new Error("Unknown existing payment owner"); return existingArm; } const ramp = await this.ramp(); if (!ramp || ramp.state !== "running") return "incumbent"; return assign(ramp.salt, key, ramp.share_percent); } async record(arm, outcome, startedMs, { declineCode = null, amount = null, currency = null } = {}) { this.pending.push({ arm, outcome, latency_ms: Math.max(0, Math.round(Date.now() - startedMs)), observed_at: Math.floor(Date.now() / 1000), decline_code: declineCode, amount, currency }); if (this.pending.length >= this.batchSize) await this.flush(); } async flush() { const batch = this.pending.splice(0, MAX_BATCH); if (batch.length === 0) return 0; try { const response = await fetch(`${this.apiBase}/traffic/observations`, { method: "POST", headers: this.headers, body: JSON.stringify({ observations: batch }), signal: AbortSignal.timeout(this.timeoutMs), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return batch.length; } catch { this.pending.unshift(...batch); return 0; } } }