|
| 1 | +import { env } from "~/env.server"; |
| 2 | +import { logger } from "~/services/logger.server"; |
| 3 | +import { FEATURE_FLAG, FeatureFlagCatalog } from "~/v3/featureFlags"; |
| 4 | +import { getMollifierBuffer } from "./mollifierBuffer.server"; |
| 5 | +import { createRealTripEvaluator } from "./mollifierTripEvaluator.server"; |
| 6 | +import { |
| 7 | + recordDecision, |
| 8 | + type DecisionOutcome, |
| 9 | + type DecisionReason, |
| 10 | +} from "./mollifierTelemetry.server"; |
| 11 | + |
| 12 | +// `count` is the fleet-wide fixed-window counter for the env (INCR with a |
| 13 | +// PEXPIRE armed on the first tick of each window — see |
| 14 | +// `mollifierEvaluateTrip` in `packages/redis-worker/src/mollifier/buffer.ts`). |
| 15 | +// All webapp replicas pointing at the same Redis share the key |
| 16 | +// `mollifier:rate:${envId}`, so the threshold is the fleet-wide ceiling |
| 17 | +// rather than a per-instance one. At a window boundary an env can briefly |
| 18 | +// admit up to ~2x threshold across the fleet before tripping (fixed-window |
| 19 | +// not sliding-window). The tripped marker is refreshed on every overage |
| 20 | +// call, so a sustained burst holds the divert state until the rate falls |
| 21 | +// below threshold within a window. |
| 22 | +export type TripDecision = |
| 23 | + | { divert: false } |
| 24 | + | { |
| 25 | + divert: true; |
| 26 | + reason: "per_env_rate"; |
| 27 | + count: number; |
| 28 | + threshold: number; |
| 29 | + windowMs: number; |
| 30 | + holdMs: number; |
| 31 | + }; |
| 32 | + |
| 33 | +export type GateOutcome = |
| 34 | + | { action: "pass_through" } |
| 35 | + | { action: "mollify"; decision: Extract<TripDecision, { divert: true }> } |
| 36 | + | { action: "shadow_log"; decision: Extract<TripDecision, { divert: true }> }; |
| 37 | + |
| 38 | +export type GateInputs = { |
| 39 | + envId: string; |
| 40 | + orgId: string; |
| 41 | + taskId: string; |
| 42 | + // Org-scoped flag overrides — taken from `Organization.featureFlags` on the |
| 43 | + // AuthenticatedEnvironment at the call site. The repo-wide `flag()` helper |
| 44 | + // queries the global `FeatureFlag` table; passing per-org overrides lets the |
| 45 | + // mollifier opt in a single org without touching the global row, matching |
| 46 | + // the pattern used by `canAccessAi`, `canAccessPrivateConnections`, and the |
| 47 | + // compute-template beta gate. |
| 48 | + orgFeatureFlags: Record<string, unknown> | null; |
| 49 | +}; |
| 50 | + |
| 51 | +export type TripEvaluator = (inputs: GateInputs) => Promise<TripDecision>; |
| 52 | + |
| 53 | +// DI seam type for consumers (e.g. triggerTask.server.ts) that inject the |
| 54 | +// gate at construction time. Deliberately narrower than `evaluateGate`'s |
| 55 | +// real signature — no `deps` param — because consumers only call it with |
| 56 | +// inputs and rely on the module-level defaults. |
| 57 | +export type MollifierEvaluateGate = (inputs: GateInputs) => Promise<GateOutcome>; |
| 58 | + |
| 59 | +export type GateDependencies = { |
| 60 | + isMollifierEnabled: () => boolean; |
| 61 | + isShadowModeOn: () => boolean; |
| 62 | + resolveOrgFlag: (inputs: GateInputs) => Promise<boolean>; |
| 63 | + evaluator: TripEvaluator; |
| 64 | + logShadow: ( |
| 65 | + inputs: GateInputs, |
| 66 | + decision: Extract<TripDecision, { divert: true }>, |
| 67 | + ) => void; |
| 68 | + logMollified: ( |
| 69 | + inputs: GateInputs, |
| 70 | + decision: Extract<TripDecision, { divert: true }>, |
| 71 | + ) => void; |
| 72 | + recordDecision: (outcome: DecisionOutcome, reason?: DecisionReason) => void; |
| 73 | +}; |
| 74 | + |
| 75 | +// `options` is a thunk so env reads happen per-evaluation, not at module load. |
| 76 | +// Don't "simplify" to a plain object — Phase 2 dynamic config relies on the |
| 77 | +// gate observing whichever env values are live at trigger time. |
| 78 | +const defaultEvaluator = createRealTripEvaluator({ |
| 79 | + getBuffer: () => getMollifierBuffer(), |
| 80 | + options: () => ({ |
| 81 | + windowMs: env.TRIGGER_MOLLIFIER_TRIP_WINDOW_MS, |
| 82 | + threshold: env.TRIGGER_MOLLIFIER_TRIP_THRESHOLD, |
| 83 | + holdMs: env.TRIGGER_MOLLIFIER_HOLD_MS, |
| 84 | + }), |
| 85 | +}); |
| 86 | + |
| 87 | +function logDivertDecision( |
| 88 | + message: "mollifier.would_mollify" | "mollifier.mollified", |
| 89 | + inputs: GateInputs, |
| 90 | + decision: Extract<TripDecision, { divert: true }>, |
| 91 | +): void { |
| 92 | + logger.info(message, { |
| 93 | + envId: inputs.envId, |
| 94 | + orgId: inputs.orgId, |
| 95 | + taskId: inputs.taskId, |
| 96 | + reason: decision.reason, |
| 97 | + count: decision.count, |
| 98 | + threshold: decision.threshold, |
| 99 | + windowMs: decision.windowMs, |
| 100 | + holdMs: decision.holdMs, |
| 101 | + }); |
| 102 | +} |
| 103 | + |
| 104 | +// Resolve the per-org mollifier flag purely from the in-memory |
| 105 | +// `Organization.featureFlags` JSON. No DB query — `triggerTask` is the |
| 106 | +// trigger hot path and the webapp CLAUDE.md forbids adding Prisma calls |
| 107 | +// there. The fleet-wide kill switch lives in `TRIGGER_MOLLIFIER_ENABLED`; rollout |
| 108 | +// is per-org via the JSON, matching the pattern used by `canAccessAi`, |
| 109 | +// `hasComputeAccess`, etc. There is no global `FeatureFlag` table read |
| 110 | +// in this path by design. |
| 111 | +export function makeResolveMollifierFlag(): (inputs: GateInputs) => Promise<boolean> { |
| 112 | + return (inputs) => { |
| 113 | + const override = inputs.orgFeatureFlags?.[FEATURE_FLAG.mollifierEnabled]; |
| 114 | + if (override !== undefined) { |
| 115 | + const parsed = FeatureFlagCatalog[FEATURE_FLAG.mollifierEnabled].safeParse(override); |
| 116 | + if (parsed.success) { |
| 117 | + return Promise.resolve(parsed.data); |
| 118 | + } |
| 119 | + } |
| 120 | + return Promise.resolve(false); |
| 121 | + }; |
| 122 | +} |
| 123 | + |
| 124 | +const resolveMollifierFlag = makeResolveMollifierFlag(); |
| 125 | + |
| 126 | +export const defaultGateDependencies: GateDependencies = { |
| 127 | + isMollifierEnabled: () => env.TRIGGER_MOLLIFIER_ENABLED === "1", |
| 128 | + isShadowModeOn: () => env.TRIGGER_MOLLIFIER_SHADOW_MODE === "1", |
| 129 | + resolveOrgFlag: resolveMollifierFlag, |
| 130 | + evaluator: defaultEvaluator, |
| 131 | + logShadow: (inputs, decision) => |
| 132 | + logDivertDecision("mollifier.would_mollify", inputs, decision), |
| 133 | + logMollified: (inputs, decision) => |
| 134 | + logDivertDecision("mollifier.mollified", inputs, decision), |
| 135 | + recordDecision, |
| 136 | +}; |
| 137 | + |
| 138 | +export async function evaluateGate( |
| 139 | + inputs: GateInputs, |
| 140 | + deps: Partial<GateDependencies> = {}, |
| 141 | +): Promise<GateOutcome> { |
| 142 | + const d = { ...defaultGateDependencies, ...deps }; |
| 143 | + |
| 144 | + if (!d.isMollifierEnabled()) { |
| 145 | + d.recordDecision("pass_through"); |
| 146 | + return { action: "pass_through" }; |
| 147 | + } |
| 148 | + |
| 149 | + // Fail open: a transient DB error resolving the per-org flag must not |
| 150 | + // block triggers. Mirror the evaluator's fail-open posture in |
| 151 | + // `mollifierTripEvaluator.server.ts`. |
| 152 | + let orgFlagEnabled: boolean; |
| 153 | + try { |
| 154 | + orgFlagEnabled = await d.resolveOrgFlag(inputs); |
| 155 | + } catch (error) { |
| 156 | + logger.warn("mollifier.resolve_org_flag_failed", { |
| 157 | + envId: inputs.envId, |
| 158 | + orgId: inputs.orgId, |
| 159 | + taskId: inputs.taskId, |
| 160 | + error: error instanceof Error ? error.message : String(error), |
| 161 | + }); |
| 162 | + orgFlagEnabled = false; |
| 163 | + } |
| 164 | + const shadowOn = d.isShadowModeOn(); |
| 165 | + |
| 166 | + if (!orgFlagEnabled && !shadowOn) { |
| 167 | + d.recordDecision("pass_through"); |
| 168 | + return { action: "pass_through" }; |
| 169 | + } |
| 170 | + |
| 171 | + // Fail open on evaluator errors too. The default `createRealTripEvaluator` |
| 172 | + // catches its own errors and returns `{ divert: false }`, but injected or |
| 173 | + // future evaluators may not — keep the contract symmetric with the org |
| 174 | + // flag resolution above so the trigger hot path can never be broken by a |
| 175 | + // gate-internal failure. |
| 176 | + let decision: TripDecision; |
| 177 | + try { |
| 178 | + decision = await d.evaluator(inputs); |
| 179 | + } catch (error) { |
| 180 | + logger.warn("mollifier.evaluator_failed", { |
| 181 | + envId: inputs.envId, |
| 182 | + orgId: inputs.orgId, |
| 183 | + taskId: inputs.taskId, |
| 184 | + error: error instanceof Error ? error.message : String(error), |
| 185 | + }); |
| 186 | + decision = { divert: false }; |
| 187 | + } |
| 188 | + if (!decision.divert) { |
| 189 | + d.recordDecision("pass_through"); |
| 190 | + return { action: "pass_through" }; |
| 191 | + } |
| 192 | + |
| 193 | + if (orgFlagEnabled) { |
| 194 | + d.logMollified(inputs, decision); |
| 195 | + d.recordDecision("mollify", decision.reason); |
| 196 | + return { action: "mollify", decision }; |
| 197 | + } |
| 198 | + |
| 199 | + d.logShadow(inputs, decision); |
| 200 | + d.recordDecision("shadow_log", decision.reason); |
| 201 | + return { action: "shadow_log", decision }; |
| 202 | +} |
0 commit comments