Skip to content

Commit 4e2e355

Browse files
authored
Merge pull request #9 from GenerationSoftware/GEN-1989-dev-agent
Run custom handlers in Dynamic Workers
2 parents 7a79b57 + 0b3299f commit 4e2e355

11 files changed

Lines changed: 56 additions & 93 deletions

‎docs/custom-sources-rollout.md‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22

33
Custom sources remain disabled unless `CUSTOM_SOURCES_ENABLED=true`. Before enabling them:
44

5-
1. Provision the `factorize-custom-handlers` Workers for Platforms dispatch namespace in default untrusted mode.
6-
2. Deploy `wrangler.custom-egress.jsonc` and configure that service as the namespace outbound Worker. The outbound Worker always returns 403 and does not inspect or log requests; configuring it also disables outbound TCP.
7-
3. Deploy `wrangler.custom-deployer.jsonc`. Store the least-privilege Workers Scripts API token as its `CLOUDFLARE_API_TOKEN` secret and configure `CLOUDFLARE_ACCOUNT_ID` there. The main Factorize Worker receives only a service binding; management credentials are never present in tenant objects or user Workers.
8-
4. Run production probes that attempt HTTP and TCP egress, service binding access, cache persistence, and reads of secrets and every supported binding. Enable only when every access fails.
9-
5. Enable one internal tenant and monitor deployment/invocation failures, CPU termination, outbound attempts, and overflow drops.
5+
1. Confirm the `CUSTOM_HANDLER_LOADER` Dynamic Worker Loader binding is available in production.
6+
2. Run production probes that attempt HTTP and TCP egress, service binding access, cache persistence, and reads of secrets and every supported binding. Dynamic handlers receive an empty environment and `globalOutbound: null`; enable only when every access fails.
7+
3. Enable one internal tenant and monitor invocation failures, CPU termination, and overflow drops.
108

119
Custom triggers are intentionally lossy once a flow has 100 pending jobs. Valid signed provider deliveries are still acknowledged to prevent retry storms.

‎src/custom-deployer.ts‎

Lines changed: 0 additions & 28 deletions
This file was deleted.

‎src/custom-egress-deny.ts‎

Lines changed: 0 additions & 3 deletions
This file was deleted.

‎src/custom-handler.ts‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { CustomOrigin, CustomSource, Env } from "./types";
1+
import type { CustomOrigin, CustomSource } from "./types";
22

33
export const CUSTOM_HANDLER_SCAFFOLD = `function handler(webhook) {
44
return true;
@@ -48,14 +48,21 @@ export default { async fetch(request) {
4848
} };`;
4949
}
5050

51-
export async function invokeCustomHandler(dispatch: DispatchNamespace, source: CustomSource, payload: unknown): Promise<HandlerDecision> {
51+
export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSource, payload: unknown): Promise<HandlerDecision> {
5252
const body = JSON.stringify(payload);
5353
if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" };
5454
const controller = new AbortController();
5555
const deadline = setTimeout(() => controller.abort(), CUSTOM_HANDLER_DEADLINE_MS);
5656
try {
57-
const worker = dispatch.get(source.handlerDeployment.scriptName, {}, { limits: { cpuMs: 10, subRequests: 1 } });
58-
const response = await worker.fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal });
57+
const worker = loader.load({
58+
compatibilityDate: CUSTOM_HANDLER_COMPATIBILITY_DATE,
59+
mainModule: "worker.js",
60+
modules: { "worker.js": userWorkerModule(source.handlerCode) },
61+
env: {},
62+
globalOutbound: null,
63+
limits: { cpuMs: 10, subRequests: 0 },
64+
});
65+
const response = await worker.getEntrypoint().fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal });
5966
if (!response.ok) return { ok: false, category: "platform_error" };
6067
const result = await response.json() as HandlerDecision;
6168
return result?.ok === true && typeof result.decision === "boolean" ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" };
@@ -64,18 +71,9 @@ export async function invokeCustomHandler(dispatch: DispatchNamespace, source: C
6471
} finally { clearTimeout(deadline); }
6572
}
6673

67-
export async function deployCustomHandler(env: Env, tenantId: string, flowId: string, source: Omit<CustomSource, "handlerDeployment">, previous?: CustomSource): Promise<CustomSource> {
68-
if (!env.CUSTOM_DEPLOYER) throw new Error("Custom handler deployment is not configured.");
74+
export async function prepareCustomHandler(tenantId: string, flowId: string, source: Omit<CustomSource, "handlerDeployment">, previous?: CustomSource): Promise<CustomSource> {
6975
const scriptName = await customScriptName(tenantId, flowId);
7076
const codeDigest = await sha256(source.handlerCode);
7177
if (previous?.handlerDeployment.state === "ready" && previous.handlerDeployment.codeDigest === codeDigest) return { ...source, handlerDeployment: previous.handlerDeployment };
72-
const response = await env.CUSTOM_DEPLOYER.fetch("https://deployer.internal/scripts", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ scriptName, module: userWorkerModule(source.handlerCode) }) });
73-
if (!response.ok) throw new Error(`Handler deployment failed (${response.status}).`);
7478
return { ...source, handlerDeployment: { scriptName, codeDigest, state: "ready" } };
7579
}
76-
77-
export async function deleteCustomHandler(env: Env, scriptName: string): Promise<boolean> {
78-
if (!env.CUSTOM_DEPLOYER) return false;
79-
const response = await env.CUSTOM_DEPLOYER.fetch(`https://deployer.internal/scripts/${encodeURIComponent(scriptName)}`, { method: "DELETE" });
80-
return response.ok || response.status === 404;
81-
}

‎src/index.ts‎

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./g
77
import { flowDetailPage, flowPage, flowsPage, landingPage } from "./ui";
88
import type { Env } from "./types";
99
import type { CustomSource, PipeInput } from "./types";
10-
import { deleteCustomHandler, deployCustomHandler, invokeCustomHandler, validateCustomHandler } from "./custom-handler";
10+
import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler";
1111

1212
const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>();
1313

@@ -171,18 +171,14 @@ app.post("/api/connections/exe/test", async (c) => {
171171
app.post("/api/pipes", async (c) => {
172172
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
173173
const input = await c.req.json() as PipeInput;
174-
let newlyDeployed: CustomSource | undefined;
175174
if (input.source?.kind === "custom") {
176175
if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404);
177176
const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode);
178177
const pipeId = crypto.randomUUID();
179178
input.pipeId = pipeId;
180-
newlyDeployed = await deployCustomHandler(c.env, session.tenantId, pipeId, { kind: "custom", ...valid });
181-
input.source = newlyDeployed;
179+
input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid });
182180
}
183-
const response = await tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) });
184-
if (!response.ok && newlyDeployed) await deleteCustomHandler(c.env, newlyDeployed.handlerDeployment.scriptName);
185-
return response;
181+
return tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) });
186182
});
187183
app.put("/api/pipes/:id", async (c) => {
188184
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
@@ -195,31 +191,24 @@ app.put("/api/pipes/:id", async (c) => {
195191
let previous: CustomSource | undefined;
196192
try { const source = JSON.parse(current.flow.source_config ?? "{}"); if (source.kind === "custom") previous = source; } catch { /* fail closed */ }
197193
const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode);
198-
input.source = await deployCustomHandler(c.env, session.tenantId, pipeId, { kind: "custom", ...valid }, previous);
194+
input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid }, previous);
199195
}
200196
return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) });
201197
});
202198
app.delete("/api/pipes/:id", async (c) => {
203199
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
204200
const pipeId = c.req.param("id");
205-
const currentResponse = await tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`);
206-
if (!currentResponse.ok) return currentResponse;
207-
const current = await currentResponse.json() as { flow: { source_config?: string } };
208-
const response = await tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "DELETE" });
209-
if (response.ok) { try { const source = JSON.parse(current.flow.source_config ?? "{}"); if (source.kind === "custom") await deleteCustomHandler(c.env, source.handlerDeployment.scriptName); } catch { /* cleanup reconciliation can retry */ } }
210-
return response;
201+
return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "DELETE" });
211202
});
212203

213204
app.post("/api/custom-handlers/test", async (c) => {
214205
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
215-
if (c.env.CUSTOM_SOURCES_ENABLED !== "true" || !c.env.CUSTOM_HANDLERS) return c.json({ error: "Custom sources are not enabled." }, 404);
206+
if (c.env.CUSTOM_SOURCES_ENABLED !== "true" || !c.env.CUSTOM_HANDLER_LOADER) return c.json({ error: "Custom sources are not enabled." }, 404);
216207
const input = await c.req.json() as { origin?: unknown; handlerName?: unknown; handlerCode?: unknown; payload?: unknown };
217208
const valid = validateCustomHandler(input.origin, input.handlerName, input.handlerCode);
218209
const testId = `test-${crypto.randomUUID()}`;
219-
try {
220-
const source = await deployCustomHandler(c.env, session.tenantId, testId, { kind: "custom", ...valid });
221-
return c.json(await invokeCustomHandler(c.env.CUSTOM_HANDLERS, source, input.payload));
222-
} finally { await deleteCustomHandler(c.env, await (await import("./custom-handler")).customScriptName(session.tenantId, testId)); }
210+
const source = await prepareCustomHandler(session.tenantId, testId, { kind: "custom", ...valid });
211+
return c.json(await invokeCustomHandler(c.env.CUSTOM_HANDLER_LOADER, source, input.payload));
223212
});
224213

225214
app.post("/webhooks/linear", async (c) => {

‎src/tenant.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,11 +380,11 @@ export class Tenant extends DurableObject<Env> {
380380
private async evaluateCustom(pipe: Row, origin: "linear" | "github", deliveryId: string, payload: Record<string, any>): Promise<void> {
381381
const source = this.sourceFor(pipe);
382382
if (source.kind !== "custom" || source.origin !== origin || source.handlerDeployment.state !== "ready") return;
383-
if (!this.env.CUSTOM_HANDLERS) {
383+
if (!this.env.CUSTOM_HANDLER_LOADER) {
384384
this.recordFlowEvent(pipe, deliveryId, deliveryId, null, payload, "handler_error", "Custom handler platform is unavailable.", origin);
385385
return;
386386
}
387-
const result = await invokeCustomHandler(this.env.CUSTOM_HANDLERS, source, payload);
387+
const result = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, source, payload);
388388
if (!result.ok) {
389389
const detail = result.category === "timeout" ? "Handler exceeded its execution deadline." : result.category === "invalid_return" ? "Handler must return the literal boolean true or false synchronously." : "Handler failed closed without starting a run.";
390390
this.recordFlowEvent(pipe, deliveryId, deliveryId, null, payload, result.category, detail, origin);

‎src/types.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ export interface Env {
1919
GITHUB_WEBHOOK_SECRET?: string;
2020
GITHUB_INTEGRATION_ENABLED?: string;
2121
CUSTOM_SOURCES_ENABLED?: string;
22-
CUSTOM_HANDLERS?: DispatchNamespace;
23-
CUSTOM_DEPLOYER?: Fetcher;
24-
CUSTOM_DISPATCH_NAMESPACE?: string;
22+
CUSTOM_HANDLER_LOADER?: WorkerLoader;
2523
}
2624

2725
export type CustomOrigin = "linear" | "github";

‎test/custom-handler.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it } from "vitest";
2-
import { CUSTOM_HANDLER_MAX_CODE_BYTES, customScriptName, userWorkerModule, validateCustomHandler } from "../src/custom-handler";
2+
import { CUSTOM_HANDLER_MAX_CODE_BYTES, customScriptName, invokeCustomHandler, userWorkerModule, validateCustomHandler } from "../src/custom-handler";
3+
import type { CustomSource } from "../src/types";
34

45
describe("custom handlers", () => {
56
const runAdapter = async (body: string) => {
@@ -37,6 +38,32 @@ describe("custom handlers", () => {
3738
expect(module).not.toContain("error.stack");
3839
});
3940

41+
it("loads handlers without bindings or outbound network access", async () => {
42+
let loaded: WorkerLoaderWorkerCode | undefined;
43+
const loader = {
44+
load(code: WorkerLoaderWorkerCode) {
45+
loaded = code;
46+
return {
47+
getEntrypoint: () => ({
48+
fetch: async () => Response.json({ ok: true, decision: true }),
49+
}),
50+
};
51+
},
52+
} as unknown as WorkerLoader;
53+
const source: CustomSource = {
54+
kind: "custom",
55+
origin: "github",
56+
handlerName: "isolated",
57+
handlerCode: "function handler(webhook) { return true; }",
58+
handlerDeployment: { scriptName: "fh-0000000000000000000000000000000000000000", codeDigest: "0".repeat(64), state: "ready" },
59+
};
60+
61+
await expect(invokeCustomHandler(loader, source, {})).resolves.toEqual({ ok: true, decision: true });
62+
expect(loaded?.env).toEqual({});
63+
expect(loaded?.globalOutbound).toBeNull();
64+
expect(loaded?.limits).toEqual({ cpuMs: 10, subRequests: 0 });
65+
});
66+
4067
it("admits literal booleans and fails closed on invalid synchronous results", async () => {
4168
await expect(runAdapter("return true;")).resolves.toEqual({ ok: true, decision: true });
4269
await expect(runAdapter("return false;")).resolves.toEqual({ ok: true, decision: false });

‎wrangler.custom-deployer.jsonc‎

Lines changed: 0 additions & 8 deletions
This file was deleted.

‎wrangler.custom-egress.jsonc‎

Lines changed: 0 additions & 6 deletions
This file was deleted.

0 commit comments

Comments
 (0)