MCPcopy Create free account
hub / github.com/UsefulSoftwareCo/executor / makeExecutionLimitGate

Function makeExecutionLimitGate

apps/cloud/src/engine/execution-gate.ts:127–191  ·  view source on GitHub ↗
(checkBalance: ExecutionBalanceCheck)

Source from the content-addressed store, hash-verified

125 * instance so all engines it decorates share it.
126 */
127export const makeExecutionLimitGate = (checkBalance: ExecutionBalanceCheck) => {
128 const timeoutMs = BALANCE_CHECK_TIMEOUT_MS;
129 const cache = new Map<string, { readonly allowed: boolean; readonly expiresAtMs: number }>();
130
131 const writeCache = (organizationId: string, allowed: boolean, nowMs: number): void => {
132 if (cache.size >= BALANCE_CACHE_MAX_ENTRIES) {
133 for (const [key, entry] of cache) {
134 if (entry.expiresAtMs <= nowMs) cache.delete(key);
135 }
136 // Still saturated after dropping expired entries: reset rather than grow.
137 if (cache.size >= BALANCE_CACHE_MAX_ENTRIES) cache.clear();
138 }
139 cache.set(organizationId, { allowed, expiresAtMs: nowMs + BALANCE_CACHE_TTL_MS });
140 };
141
142 const toDecision = (organizationId: string, allowed: boolean): GateDecision =>
143 allowed
144 ? { blocked: false }
145 : {
146 blocked: true,
147 error: new ExecutionLimitReachedError({
148 organizationId,
149 message: EXECUTION_LIMIT_BLOCKED_MESSAGE,
150 }),
151 };
152
153 const decide = (organizationId: string): Effect.Effect<GateDecision> =>
154 Effect.suspend(() => {
155 const nowMs = Date.now();
156 const cached = cache.get(organizationId);
157 if (cached && cached.expiresAtMs > nowMs) {
158 return Effect.succeed(toDecision(organizationId, cached.allowed));
159 }
160 return checkBalance(organizationId).pipe(
161 Effect.timeoutOrElse({
162 duration: `${timeoutMs} millis`,
163 orElse: () => Effect.fail(new GateCheckTimeoutError({ timeoutMs })),
164 }),
165 Effect.map(({ allowed }) => {
166 writeCache(organizationId, allowed, nowMs);
167 return toDecision(organizationId, allowed);
168 }),
169 // FAIL OPEN: Autumn errors, timeouts, and missing customers/features
170 // must never block executions. Reported like `trackExecution` so a
171 // billing outage still pages; the error outcome is never cached.
172 Effect.catch((error: unknown) =>
173 Effect.gen(function* () {
174 yield* Effect.sync(() => {
175 console.warn("[billing] execution balance check failed open:", error);
176 });
177 yield* captureCauseEffect(error);
178 return { blocked: false } as const satisfies GateDecision;
179 }),
180 ),
181 );
182 });
183
184 return {

Callers 1

Calls 2

withPreExecutionGateFunction · 0.85
decideFunction · 0.70

Tested by

no test coverage detected