feat(server): scheduled tasks can run on a webhook #15085
Mergedjuliusmarmingemerged 14 commits into
main fromrefs/pull/15085/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
juliusmarminge changed the title
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1139OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1119,21 @@1119+ bodyTruncated: row.body_truncated === 1,1120+ renderedPrompt: row.rendered_prompt,1121+ },1122+ };1123+ });1124+1125+ const recordDelivery = (input: {1126+ readonly id: string;1127+ readonly taskId: ScheduledTaskId;1128+ readonly receivedAt: string;1129+ readonly request: WebhookTriggerRequest;1130+ readonly outcome: ScheduledTaskWebhookDeliveryOutcome;1131+ readonly signatureVerified: boolean;1132+ readonly missing: ReadonlyArray<string>;1133+ readonly renderedPrompt: string | null;1134+ }) => {1135+ const truncated = input.request.bodyText.length > WEBHOOK_DELIVERY_LOG_BODY_LIMIT;1136+ return sql1137+ .withTransaction(1138+ Effect.gen(function* () {1139+ yield* sql`INSERT INTO scheduled_task_webhook_deliveries ${sql.insert({apps/web/src/components/settings/ScheduledTasksSettings.tsx line 316Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -312,4 +313,4 @@312313 const linkedTask = tasks?.find((task) => task.id === taskId);313314 const openedLink = useRef(false);314315 useEffect(() => {315- if (!openedLink.current && linkedTask) {316+ if (!openedLink.current && linkedTask && linkedTask.schedule.type !== "webhook") {apps/server/src/auth/RpcAuthorization.ts line 95OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -90,3 +90,6 @@9090 [WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,9191 [WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,9292 [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope,93+ [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope,94+ [WS_METHODS.scheduledTasksListWebhookDeliveries]: AuthOrchestrationReadScope,95+ [WS_METHODS.scheduledTasksGetWebhookDelivery]: AuthOrchestrationReadScope,apps/server/src/scheduledTasks/webhookRoute.ts line 102OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ switch (result._tag) {83+ case "accepted":84+ return json(202, { deliveryId: result.deliveryId });85+ case "not_found":86+ return json(404, { error: "hook_not_found" });87+ case "rejected_signature":88+ return json(401, { error: "invalid_signature" });89+ case "disabled":90+ return json(409, { error: "hook_disabled" });91+ case "rate_limited":92+ return json(429, { error: "rate_limited" });93+ case "error":94+ return json(500, { error: "internal_error" });95+ }96+ });97+98+export const webhookRouteLayer = Layer.effectDiscard(99+ Effect.gen(function* () {100+ const router = yield* HttpRouter.HttpRouter;101+ const handler = handleWebhook(yield* ScheduledTaskService);102+ for (const method of ["POST", "PUT", "PATCH", "GET"] as const) {apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1398Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1289,21 @@1289+ row.webhook_secret !== null &&1290+ verifyWebhookSignature({1291+ signature,1292+ secret: row.webhook_secret,1293+ headers: request.headers,1294+ body: request.body,1295+ });1296+ if (!verified) {1297+ yield* log("rejected_signature");1298+ return { _tag: "rejected_signature" as const };1299+ }1300+ }1301+1302+ const rendered = renderWebhookPrompt(task.prompt, request);1303+ yield* log("accepted", {1304+ signatureVerified: signature !== null,1305+ missing: rendered.missing,1306+ renderedPrompt: rendered.prompt,1307+ });1308+ const permit = yield* webhookPermit(task.id);1309+ yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(
- apps/server/src/scheduledTasks/webhookRoute.ts line 11Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,11 @@1+import * as ByteSize from "effect/ByteSize";2+import * as Effect from "effect/Effect";3+import * as Layer from "effect/Layer";4+import * as Option from "effect/Option";5+import * as HttpIncomingMessage from "effect/unstable/http/HttpIncomingMessage";6+import * as HttpRouter from "effect/unstable/http/HttpRouter";7+import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";8+import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";9+10+import { ScheduledTaskService, WEBHOOK_ROUTE_PREFIX } from "./ScheduledTaskService.ts";11+apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1394OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1285,21 @@1285+ }1286+ const signature = task.schedule.signature;1287+ if (signature !== null) {1288+ const verified =1289+ row.webhook_secret !== null &&1290+ verifyWebhookSignature({1291+ signature,1292+ secret: row.webhook_secret,1293+ headers: request.headers,1294+ body: request.body,1295+ });1296+ if (!verified) {1297+ yield* log("rejected_signature");1298+ return { _tag: "rejected_signature" as const };1299+ }1300+ }1301+1302+ const rendered = renderWebhookPrompt(task.prompt, request);1303+ yield* log("accepted", {1304+ signatureVerified: signature !== null,1305+ missing: rendered.missing,apps/server/src/scheduledTasks/webhookRoute.ts line 80OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +60,21 @@60+ if (typeof value === "string") headers[name.toLowerCase()] = value;61+ }62+63+ const result = yield* scheduledTasks64+ .triggerWebhook({65+ hookId: taskId,66+ token,67+ method: request.method,68+ path: `${WEBHOOK_ROUTE_PREFIX}/${hookId}`,69+ query: url.value.search.replace(/^\?/, ""),70+ headers,71+ body: body.value,72+ bodyText: new TextDecoder().decode(body.value),73+ })74+ .pipe(75+ Effect.catch((error) =>76+ Effect.logWarning("Webhook delivery failed", { error: error.message }).pipe(77+ Effect.as({ _tag: "error" as const }),78+ ),79+ ),80+ );
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1139 to 1156OutdatedResolvedby juliusmarminge@@ -819,0 +1136,21 @@1136+ return sql1137+ .withTransaction(1138+ Effect.gen(function* () {1139+ yield* sql`INSERT INTO scheduled_task_webhook_deliveries ${sql.insert({1140+ delivery_id: input.id,1141+ task_id: input.taskId,1142+ received_at: input.receivedAt,1143+ method: input.request.method,1144+ query: input.request.query,1145+ headers_json: encodeHeadersJson(input.request.headers),1146+ body: truncated1147+ ? input.request.bodyText.slice(0, WEBHOOK_DELIVERY_LOG_BODY_LIMIT)1148+ : input.request.bodyText,1149+ body_bytes: input.request.body.byteLength,1150+ body_truncated: truncated ? 1 : 0,1151+ outcome: input.outcome,1152+ signature_verified: input.signatureVerified ? 1 : 0,1153+ missing_fields_json: encodeMissingFieldsJson(input.missing),1154+ rendered_prompt: input.renderedPrompt,1155+ error: null,1156+ })}`;
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 525OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -361,4 +515,11 @@361515 interaction_mode = excluded.interaction_mode,362516 creation_source = excluded.creation_source,363517 updated_at = excluded.updated_at,364- next_run_at = excluded.next_run_at518+ next_run_at = excluded.next_run_at,519+ -- Only rotate changes a live token, so a save racing a rotation520+ -- cannot bring the old URL back.521+ webhook_token = CASE522+ WHEN excluded.webhook_token IS NULL THEN NULL523+ ELSE COALESCE(scheduled_tasks.webhook_token, excluded.webhook_token)524+ END,525+ webhook_secret = excluded.webhook_secretapps/server/src/scheduledTasks/ScheduledTaskService.ts line 1414Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1297,21 @@1297+ if (!verified) {1298+ yield* log("rejected_signature");1299+ return { _tag: "rejected_signature" as const };1300+ }1301+ }1302+1303+ const rendered = renderWebhookPrompt(task.prompt, request);1304+ yield* log("accepted", {1305+ signatureVerified: signature !== null,1306+ missing: rendered.missing,1307+ renderedPrompt: rendered.prompt,1308+ });1309+ const permit = yield* webhookPermit(task.id);1310+ yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(1311+ Effect.flatMap((completed) =>1312+ completed.lastRunStatus === "failed"1313+ ? markDeliveryFailed(deliveryId, completed.lastRunError ?? "Dispatch failed.")1314+ : Effect.void,1315+ ),1316+ Effect.catchCause((cause) => markDeliveryFailed(deliveryId, errorMessage(cause))),1317+ permit.withPermits(1),apps/server/src/scheduledTasks/ScheduledTaskService.ts line 728Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -504 +672 @@504672 yield* markRunning(active.id, startedAtIso);apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1414Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1297,21 @@1297+ if (!verified) {1298+ yield* log("rejected_signature");1299+ return { _tag: "rejected_signature" as const };1300+ }1301+ }1302+1303+ const rendered = renderWebhookPrompt(task.prompt, request);1304+ yield* log("accepted", {1305+ signatureVerified: signature !== null,1306+ missing: rendered.missing,1307+ renderedPrompt: rendered.prompt,1308+ });1309+ const permit = yield* webhookPermit(task.id);1310+ yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe(1311+ Effect.flatMap((completed) =>1312+ completed.lastRunStatus === "failed"1313+ ? markDeliveryFailed(deliveryId, completed.lastRunError ?? "Dispatch failed.")1314+ : Effect.void,1315+ ),1316+ Effect.catchCause((cause) => markDeliveryFailed(deliveryId, errorMessage(cause))),1317+ permit.withPermits(1),
- @@ -819,0 +1115,21 @@1115+ ...decodeDeliverySummary(row),1116+ query: row.query,1117+ headers: deliveryHeaders(row),1118+ body: row.body,1119+ bodyTruncated: row.body_truncated === 1,1120+ renderedPrompt: row.rendered_prompt,1121+ },1122+ };1123+ });1124+1125+ const recordDelivery = (input: {1126+ readonly id: string;1127+ readonly taskId: ScheduledTaskId;1128+ readonly receivedAt: string;1129+ readonly request: WebhookTriggerRequest;1130+ readonly outcome: ScheduledTaskWebhookDeliveryOutcome;1131+ readonly signatureVerified: boolean;1132+ readonly missing: ReadonlyArray<string>;1133+ readonly renderedPrompt: string | null;1134+ }) => {1135+ const truncated = input.request.bodyText.length > WEBHOOK_DELIVERY_LOG_BODY_LIMIT;
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1155OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -819,0 +1135,21 @@1135+ ...decodeDeliverySummary(row),1136+ query: row.query,1137+ headers: deliveryHeaders(row),1138+ body: row.body,1139+ bodyTruncated: row.body_truncated === 1,1140+ renderedPrompt: row.rendered_prompt,1141+ },1142+ };1143+ });1144+1145+ const recordDelivery = (input: {1146+ readonly id: string;1147+ readonly taskId: ScheduledTaskId;1148+ readonly receivedAt: string;1149+ readonly request: WebhookTriggerRequest;1150+ readonly outcome: ScheduledTaskWebhookDeliveryOutcome;1151+ readonly signatureVerified: boolean;1152+ readonly missing: ReadonlyArray<string>;1153+ readonly renderedPrompt: string | null;1154+ }) => {1155+ const truncated = input.request.bodyText.length > WEBHOOK_DELIVERY_LOG_BODY_LIMIT;
- apps/web/src/components/settings/ScheduledTasksSettings.tsx line 464Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -449,8 +456,9 @@449456 <MoreHorizontalIcon className="size-4" />450457 </MenuTrigger>451458 <MenuPopup align="end">452- <MenuItem onClick={onEdit}>459+ {/* Webhook tasks are not editable here yet; saving would drop their URL. */}460+ <MenuItem onClick={onEdit} disabled={task.schedule.type === "webhook"}>453461 <PencilIcon />454462 Edit455463 </MenuItem>456- <MenuItem onClick={() => void act("run")}>464+ <MenuItem onClick={() => void act("run")} disabled={task.schedule.type === "webhook"}>
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1095 to 1103OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -817,3 +1084,20 @@8171084 return { task: next };8181085 });81910861087+ const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = (input) =>1088+ Effect.gen(function* () {1089+ const task = yield* loadTask(input.id);1090+ if (task.schedule.type !== "webhook") {1091+ return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id });1092+ }1093+ const token = yield* newWebhookToken;1094+ const now = yield* localNow;1095+ yield* sql`1096+ UPDATE scheduled_tasks1097+ SET webhook_token = ${token}, updated_at = ${iso(now)}1098+ WHERE task_id = ${input.id}1099+ `.pipe(1100+ Effect.mapError((cause) =>1101+ taskError("Could not rotate webhook token.", { taskId: input.id, cause }),1102+ ),1103+ );
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1349 to 1367OutdatedResolvedby juliusmarminge@@ -819,0 +1347,21 @@1347+ renderedPrompt: rendered.prompt,1348+ });1349+ // Bound the deliveries waiting behind a slow run, so steady traffic to1350+ // a stuck task cannot pile up parked fibers.1351+ const queued = yield* Ref.modify(webhookQueued, (counts) => {1352+ const count = counts.get(task.id) ?? 0;1353+ return count >= WEBHOOK_MAX_QUEUED_PER_TASK1354+ ? ([false, counts] as const)1355+ : ([true, new Map(counts).set(task.id, count + 1)] as const);1356+ });1357+ if (!queued) {1358+ yield* markDeliveryFailed(deliveryId, "Too many deliveries are waiting for this task.");1359+ return { _tag: "rate_limited" as const };1360+ }1361+ const release = Ref.update(webhookQueued, (counts) => {1362+ const next = new Map(counts);1363+ const count = (next.get(task.id) ?? 1) - 1;1364+ if (count <= 0) next.delete(task.id);1365+ else next.set(task.id, count);1366+ return next;1367+ });
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1065 to 1069OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -806,2 +1050,20 @@8061050 const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) =>807- deleteRow(input.id).pipe(Effect.andThen(notifyChanged), Effect.as({ id: input.id }));1051+ deleteRow(input.id).pipe(1052+ Effect.andThen(1053+ Effect.all([1054+ Ref.update(webhookRateWindows, (windows) => {1055+ const next = new Map(windows);1056+ next.delete(input.id);1057+ return next;1058+ }),1059+ Ref.update(webhookPermits, (permits) => {1060+ const next = new Map(permits);1061+ next.delete(input.id);1062+ return next;1063+ }),1064+ // Old deliveries still finishing must not fill a recreated task's queue.1065+ Ref.update(webhookQueued, (queued) => {1066+ const next = new Map(queued);1067+ next.delete(input.id);1068+ return next;1069+ }),
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 704 to 704OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -500,3 +699,6 @@500699 ) {501700 return active;502701 }702+ // A queued delivery must not run a task that was paused, or deleted703+ // and recreated under the same id, while it waited for its turn.704+ if (webhook !== undefined && (!active.enabled || active.createdAt !== task.createdAt)) {
juliusmarminge merged this7dfb86a
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
2a68a77· PR result:08df570· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.