|
| 1 | +import type { MiddlewareHandler } from "hono/types"; |
| 2 | +import { createMiddleware } from "hono/factory"; |
| 3 | +import { readFileSync } from "fs"; |
| 4 | +import type { ContentfulStatusCode } from "hono/utils/http-status"; |
| 5 | + |
| 6 | +type ErrorRule = { |
| 7 | + pattern: string; |
| 8 | + effect: "error"; |
| 9 | + status: number; |
| 10 | + chance: number; // 0–1 |
| 11 | +}; |
| 12 | + |
| 13 | +type DelayRule = { |
| 14 | + pattern: string; |
| 15 | + effect: "delay"; |
| 16 | + ms: number | [number, number]; |
| 17 | +}; |
| 18 | + |
| 19 | +type ChaosRule = ErrorRule | DelayRule; |
| 20 | + |
| 21 | +function patternToRegex(pattern: string): RegExp { |
| 22 | + const escaped = pattern |
| 23 | + .replace(/[.+?^${}()|[\]\\]/g, "\\$&") |
| 24 | + .replace(/\*/g, ".*") |
| 25 | + .replace(/:[^/]+/g, "[^/]+"); |
| 26 | + // Allow any number of leading path segments so patterns work regardless of |
| 27 | + // mount prefix (e.g. /works/:id matches both /works/123 and /api/v2/works/123). |
| 28 | + return new RegExp(`^(/[^/]+)*${escaped}(/.*)?$`); |
| 29 | +} |
| 30 | + |
| 31 | +function loadConfig(): ChaosRule[] | null { |
| 32 | + const raw = process.env["CHAOS_CONFIG"]; |
| 33 | + if (!raw) return null; |
| 34 | + |
| 35 | + try { |
| 36 | + return JSON.parse(raw) as ChaosRule[]; |
| 37 | + } catch { |
| 38 | + try { |
| 39 | + return JSON.parse(readFileSync(raw, "utf-8")) as ChaosRule[]; |
| 40 | + } catch { |
| 41 | + console.error(`[chaos] Failed to load config from path: ${raw}`); |
| 42 | + return null; |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +const rules = loadConfig(); |
| 48 | + |
| 49 | +import type { Context } from "hono"; |
| 50 | + |
| 51 | +// Each handler returns true if it short-circuits (i.e. a response was sent). |
| 52 | +type RuleHandler<T extends ChaosRule> = ( |
| 53 | + c: Context, |
| 54 | + rule: T, |
| 55 | +) => ReturnType<MiddlewareHandler>; |
| 56 | + |
| 57 | +const applyError: RuleHandler<ErrorRule> = async (c, rule) => { |
| 58 | + if (Math.random() >= rule.chance) return; |
| 59 | + return c.json( |
| 60 | + { error: `Chaos rule triggered: ${rule.pattern}` }, |
| 61 | + rule.status as ContentfulStatusCode, |
| 62 | + ); |
| 63 | +}; |
| 64 | + |
| 65 | +const applyDelay: RuleHandler<DelayRule> = async (_c, rule) => { |
| 66 | + const [lo, hi] = Array.isArray(rule.ms) ? rule.ms : [rule.ms, rule.ms]; |
| 67 | + await new Promise((res) => setTimeout(res, lo + Math.random() * (hi - lo))); |
| 68 | +}; |
| 69 | + |
| 70 | +const handlers = { |
| 71 | + error: applyError, |
| 72 | + delay: applyDelay, |
| 73 | +} satisfies { |
| 74 | + [K in ChaosRule["effect"]]: RuleHandler<Extract<ChaosRule, { effect: K }>>; |
| 75 | +}; |
| 76 | + |
| 77 | +// Iterate all matching rules. Delay rules accumulate; an error rule that fires |
| 78 | +// short-circuits immediately. If an error rule doesn't fire, keep checking. |
| 79 | +const createChaos = (rules: ChaosRule[] | null) => { |
| 80 | + if (!rules || rules.length === 0) return null; |
| 81 | + |
| 82 | + return createMiddleware(async (c, next) => { |
| 83 | + const path = new URL(c.req.url).pathname; |
| 84 | + |
| 85 | + for (const rule of rules) { |
| 86 | + if (!patternToRegex(rule.pattern).test(path)) continue; |
| 87 | + const handler = handlers[rule.effect] as RuleHandler<typeof rule>; |
| 88 | + const handlerResponse = await handler(c, rule); |
| 89 | + if (handlerResponse) return handlerResponse; |
| 90 | + } |
| 91 | + |
| 92 | + await next(); |
| 93 | + }); |
| 94 | +}; |
| 95 | + |
| 96 | +const logRules = (rules: ChaosRule[] | null) => { |
| 97 | + if (!rules || rules.length === 0) return; |
| 98 | + console.warn("[chaos] Loaded rules:"); |
| 99 | + for (const rule of rules) { |
| 100 | + if (rule.effect === "error") { |
| 101 | + console.warn( |
| 102 | + `[chaos] ${rule.pattern} -> error ${rule.status} (${rule.chance})`, |
| 103 | + ); |
| 104 | + } else if (rule.effect === "delay") { |
| 105 | + const ms = Array.isArray(rule.ms) |
| 106 | + ? `${rule.ms[0]}-${rule.ms[1]}` |
| 107 | + : rule.ms; |
| 108 | + console.warn(`[chaos] ${rule.pattern} -> delay ${ms}ms`); |
| 109 | + } |
| 110 | + } |
| 111 | +}; |
| 112 | + |
| 113 | +logRules(rules ?? []); |
| 114 | +export default createChaos(rules); |
0 commit comments