|
| 1 | +import type { PrismaClient } from "@trigger.dev/database"; |
| 2 | +import { logger } from "~/services/logger.server"; |
| 3 | +import { BoundedTtlCache } from "~/services/realtime/boundedTtlCache"; |
| 4 | +import { FEATURE_FLAG, FeatureFlagCatalog } from "../featureFlags"; |
| 5 | + |
| 6 | +// The per-organization flag cache of the snapshot store rollout: its default lifetime and its cap. |
| 7 | +const FLAGS_CACHE_TTL_MS = 5_000; |
| 8 | +const FLAGS_CACHE_MAX_ENTRIES = 10_000; |
| 9 | +// The audit recording flag's default lookup timeout. |
| 10 | +const LOOKUP_TIMEOUT_MS = 5_000; |
| 11 | + |
| 12 | +const LOOKUP_FAILED = Symbol("lookupFailed"); |
| 13 | + |
| 14 | +type ParentDecision = ( |
| 15 | + organizationId: string, |
| 16 | + organizationFlags: unknown |
| 17 | +) => boolean | Promise<boolean>; |
| 18 | + |
| 19 | +/** |
| 20 | + * Whether the outflow may move an organization's runs: `outflowEnabled` (organization override, then |
| 21 | + * the global value, then off) and both parent decisions. One cached lookup serves all three; never rejects. |
| 22 | + * A lookup that takes longer than `lookupTimeoutMs` (default 5 seconds) counts as a failed one. |
| 23 | + */ |
| 24 | +export function createOutflowDecision(deps: { |
| 25 | + readGlobalFlags: () => { outflowEnabled?: boolean } | undefined; |
| 26 | + prisma: Pick<PrismaClient, "organization">; |
| 27 | + archiveStoreEnabled: ParentDecision; |
| 28 | + archiveReadPathEnabled: ParentDecision; |
| 29 | + lookupTimeoutMs?: number; |
| 30 | +}): (organizationId: string) => Promise<boolean> { |
| 31 | + const lookupTimeoutMs = deps.lookupTimeoutMs ?? LOOKUP_TIMEOUT_MS; |
| 32 | + // Holds the lookup's promise from when it starts, so concurrent calls share it. |
| 33 | + const cache = new BoundedTtlCache<Promise<unknown>>(FLAGS_CACHE_TTL_MS, FLAGS_CACHE_MAX_ENTRIES); |
| 34 | + |
| 35 | + async function lookUp(organizationId: string): Promise<unknown> { |
| 36 | + // A silent connection can hold the query far past any driver timeout. The query keeps |
| 37 | + // running; only the decision stops waiting for it. |
| 38 | + let timer: NodeJS.Timeout | undefined; |
| 39 | + const timedOut = new Promise<never>((_, reject) => { |
| 40 | + timer = setTimeout( |
| 41 | + () => reject(new Error(`timed out after ${lookupTimeoutMs} ms`)), |
| 42 | + lookupTimeoutMs |
| 43 | + ); |
| 44 | + }); |
| 45 | + try { |
| 46 | + const row = await Promise.race([ |
| 47 | + deps.prisma.organization.findFirst({ |
| 48 | + where: { id: organizationId }, |
| 49 | + select: { featureFlags: true }, |
| 50 | + }), |
| 51 | + timedOut, |
| 52 | + ]); |
| 53 | + return row?.featureFlags ?? null; |
| 54 | + } catch (error) { |
| 55 | + // Cached like an answer, so an outage costs one read and one line per org per lifetime. |
| 56 | + logger.error("Outflow flag decision: failed to read the organization's flags, not moving", { |
| 57 | + organizationId, |
| 58 | + error: error instanceof Error ? error.message : String(error), |
| 59 | + }); |
| 60 | + return LOOKUP_FAILED; |
| 61 | + } finally { |
| 62 | + clearTimeout(timer); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + function organizationFlags(organizationId: string): Promise<unknown> { |
| 67 | + const cached = cache.get(organizationId); |
| 68 | + if (cached !== undefined) return cached; |
| 69 | + |
| 70 | + const flags = lookUp(organizationId); |
| 71 | + cache.set(organizationId, flags); |
| 72 | + void flags.then((result) => { |
| 73 | + if (result !== LOOKUP_FAILED) return; |
| 74 | + // A failure's lifetime starts when it settles, else a timeout as long as the lifetime is never |
| 75 | + // served. A newer lookup that has replaced this entry keeps its place. An entry that is gone |
| 76 | + // comes back only into a cache with room: one evicted at capacity must not evict another |
| 77 | + // organization's live entry. Reading an expired entry deletes it, which makes that room. |
| 78 | + const current = cache.get(organizationId); |
| 79 | + if (current === flags || (current === undefined && cache.size < FLAGS_CACHE_MAX_ENTRIES)) { |
| 80 | + cache.set(organizationId, flags); |
| 81 | + } |
| 82 | + }); |
| 83 | + return flags; |
| 84 | + } |
| 85 | + |
| 86 | + return async (organizationId) => { |
| 87 | + const flags = await organizationFlags(organizationId); |
| 88 | + if (flags === LOOKUP_FAILED) return false; |
| 89 | + |
| 90 | + try { |
| 91 | + const value = |
| 92 | + typeof flags === "object" && flags !== null && "outflowEnabled" in flags |
| 93 | + ? flags.outflowEnabled |
| 94 | + : undefined; |
| 95 | + const parsed = FeatureFlagCatalog[FEATURE_FLAG.outflowEnabled].safeParse(value); |
| 96 | + const enabled = parsed.success |
| 97 | + ? parsed.data |
| 98 | + : (deps.readGlobalFlags()?.outflowEnabled ?? false); |
| 99 | + if (!enabled) return false; |
| 100 | + |
| 101 | + if (!(await deps.archiveStoreEnabled(organizationId, flags))) return false; |
| 102 | + return await deps.archiveReadPathEnabled(organizationId, flags); |
| 103 | + } catch (error) { |
| 104 | + logger.error("Outflow flag decision failed, not moving", { |
| 105 | + organizationId, |
| 106 | + error: error instanceof Error ? error.message : String(error), |
| 107 | + }); |
| 108 | + return false; |
| 109 | + } |
| 110 | + }; |
| 111 | +} |
0 commit comments