feat(relay,server,web,mobile): opt-in to hold webhooks while offline #15487
Mergedjuliusmarmingemerged 35 commits into
t3code/webhooks-web fromt3code/webhooks-mailboxmerged by juliusmarminge View on GitHubjuliusmarminge changed the title
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- @@ -249,4 +258,18 @@249258 const baseUrl = endpoint.httpBaseUrl.endsWith("/")250259 ? endpoint.httpBaseUrl251260 : `${endpoint.httpBaseUrl}/`;252- const headers = forwardedHeaders(request.headers);261+ // One id per attempt, so a request that reached the environment before a262+ // timeout and is later replayed from the mailbox dispatches only once.263+ const deliveryId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);264+ const headers: Record<string, string> = {265+ ...forwardedHeaders(request.headers),266+ [RELAY_DELIVERY_ID_HEADER]: deliveryId,267+ };268+ // Held only for environments that opted in; otherwise the relay is a plain proxy.269+ const holdOrFail = (status: 503 | 504, error: string) =>270+ Effect.gen(function* () {271+ if (!endpoint.holdWhileOffline) {272+ yield* outcome(error);273+ return errorResponse(status, error);274+ }275+ const stored = yield* mailboxinfra/relay/src/http/Api.ts line 519OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -513,3 +514,6 @@513514 environmentId: link.environmentId,514515 environmentPublicKey: link.environmentPublicKey,515516 });517+ // Held webhook requests belong to the environment, not one user's link;518+ // drop them once no user has it linked any more.519+ const remaining = yield* links.findActiveManagedForEnvironment({apps/server/src/relay/HookMailboxDrain.ts lines 175 to 175OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +155,21 @@155+ if (now < current.nextAt) return;156+ const enabled = yield* readHoldWebhooksWhileOffline(secrets);157+ // One last pass after the opt-in is turned off, so nothing already held158+ // is stranded; after that the loop stays idle.159+ if (!enabled && !current.wasEnabled) return;160+ const outcome = yield* drainOnce().pipe(161+ Effect.provideService(HookMailboxRelay, relay),162+ Effect.provideService(ScheduledTaskService.ScheduledTaskService, scheduledTasks),163+ Effect.result,164+ );165+ const failures = outcome._tag === "Failure" ? current.failures + 1 : 0;166+ if (outcome._tag === "Failure") {167+ yield* Effect.logWarning("Could not deliver held webhook requests", {168+ cause: outcome.failure,169+ });170+ }171+ const delay =172+ failures === 0173+ ? DRAIN_INTERVAL_MS174+ : Math.min(DRAIN_INTERVAL_MS * 2 ** failures, MAX_BACKOFF_MS);175+ yield* Ref.set(state, { nextAt: now + delay, failures, wasEnabled: enabled });apps/server/src/cloud/http.ts line 1391OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1346,6 +1375,17 @@1375+ .pipe(1376+ Effect.timeout("10 seconds"),1377+ Effect.catch(1378+ failEnvironmentCloudInternalError("Could not update T3 Connect webhook settings."),1379+ ),1380+ );1381+ },1382+);1383+13461384 const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(1347- function* (1348- dependencies: CloudHttpDependencies,1349- payload: { readonly publishAgentActivity: boolean },1350- ) {1385+ function* (dependencies: CloudHttpDependencies, payload: EnvironmentCloudPreferencesRequest) {13511386 yield* requireEnvironmentScope(AuthRelayWriteScope);1387+ if (payload.holdWebhooksWhileOffline !== undefined) {1388+ // The relay decides whether to hold a request, so it is told first; the1389+ // local copy is only saved once the relay has the same value.1390+ yield* pushHoldWebhooksWhileOffline(dependencies, payload.holdWebhooksWhileOffline);1391+ yield* dependencies.secrets.set(apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1321OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1299,6 +1305,17 @@129913051300- const receivedAt = yield* localNow;1301- const deliveryUuid = yield* crypto.randomUUIDv4.pipe(1302- Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })),1306+ const now = yield* localNow;1307+ const receivedAt =1308+ request.receivedAt === undefined1309+ ? now1310+ : Option.getOrElse(DateTime.make(request.receivedAt), () => now);1311+ const deliveryId = ScheduledTaskWebhookDeliveryId.make(1312+ request.relayDeliveryId === undefined1313+ ? `delivery:${yield* crypto.randomUUIDv4.pipe(1314+ Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })),1315+ )}`1316+ : `delivery:relay:${request.relayDeliveryId}`,13031317 );1304- const deliveryId = ScheduledTaskWebhookDeliveryId.make(`delivery:${deliveryUuid}`);1318+ // A held request may already have reached this environment directly1319+ // before a timeout; it runs once.1320+ if (request.relayDeliveryId !== undefined) {1321+ const seen = yield* sql<{ delivery_id: string }>`@@ -513,3 +514,11 @@513514 environmentId: link.environmentId,514515 environmentPublicKey: link.environmentPublicKey,515516 });517+ // Held webhook requests belong to the environment, not one user's link;518+ // drop them once no user has it linked any more.519+ const remaining = yield* links.findActiveManagedForEnvironment({520+ environmentId: input.environmentId,521+ });522+ if (remaining.length === 0) {523+ const mailbox = yield* HookMailbox.HookMailbox;524+ yield* mailbox.clearEnvironment({ environmentId: input.environmentId });apps/web/src/cloud/linkEnvironment.ts lines 206 to 206Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -199,6 +199,8 @@199199 export function updatePrimaryCloudPreferences(input: {200200 readonly target: CloudLinkTarget;201201 readonly publishAgentActivity: boolean;202+ readonly holdWebhooksWhileOffline?: boolean;202203 }): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {203204 return Effect.gen(function* () {204205 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);206+ const { target: _target, ...payload } = input;apps/web/src/components/settings/ScheduledTasksSettings.tsx line 1180Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1131,3 +1136,20 @@11311136 "Each request runs the prompt. Use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} or {{request}} in the prompt; only what it names reaches the agent."11321137 }11331138 </p>1139+ <Field1140+ label="Skip requests older than"1141+ hint="minutes, optional"1142+ htmlFor="scheduled-task-max-age"1143+ >1144+ <Input1145+ id="scheduled-task-max-age"1146+ type="number"1147+ nativeInput1148+ min={1}1149+ max={MAX_WEBHOOK_DELIVERY_AGE_MINUTES}1150+ placeholder="Run every request"1151+ value={draft.maxDeliveryAgeMinutes}1152+ onChange={(event) =>1153+ setDraft((current) => ({1154+ ...current,1155+ maxDeliveryAgeMinutes: event.target.value,infra/relay/src/hooks/HookMailbox.ts line 81OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ readonly clearEnvironment: (input: {62+ readonly environmentId: string;63+ }) => Effect.Effect<void, HookMailboxPersistenceError>;64+ }65+>()("t3code-relay/hooks/HookMailbox") {}66+67+export const make = Effect.gen(function* () {68+ const db = yield* RelayDb.RelayDb;69+ const fail =70+ (operation: HookMailboxPersistenceError["operation"], environmentId?: string) =>71+ (cause: unknown) =>72+ new HookMailboxPersistenceError({73+ operation,74+ ...(environmentId === undefined ? {} : { environmentId }),75+ cause,76+ });77+78+ return HookMailbox.of({79+ enqueue: Effect.fn("relay.hook_mailbox.enqueue")(function* (hook) {80+ yield* Effect.annotateCurrentSpan({ "relay.environment_id": hook.environmentId });81+ const [held] = yield* dbinfra/relay/src/hooks/HookForwarder.ts line 201OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -189,4 +198,4 @@189198 baseDomain: settings.managedEndpointBaseDomain,190199 });191200 if (Result.isSuccess(result)) {192- return result.success;201+ return { ...result.success, holdWhileOffline: link.holdWebhooksWhileOffline };
- apps/server/src/cloud/config.ts line 86Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -73,3 +74,13 @@7374 environmentCredential !== ""7475 );7576 }).pipe(Effect.orElseSucceed(() => false));77+78+const readSecretString = (79+ secrets: ServerSecretStore.ServerSecretStore["Service"],80+ name: string,81+): Effect.Effect<string | null> =>82+ secrets.get(name).pipe(83+ Effect.map((bytes) =>84+ Option.isSome(bytes) && bytes.value.length > 0 ? new TextDecoder().decode(bytes.value) : null,85+ ),86+ Effect.orElseSucceed(() => null),@@ -1346,6 +1377,17 @@1377+ Effect.catch(1378+ failEnvironmentCloudInternalError("Could not update T3 Connect webhook settings."),1379+ ),1380+ );1381+ },1382+);1383+13461384 const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(1347- function* (1348- dependencies: CloudHttpDependencies,1349- payload: { readonly publishAgentActivity: boolean },1350- ) {1385+ function* (dependencies: CloudHttpDependencies, payload: EnvironmentCloudPreferencesRequest) {13511386 yield* requireEnvironmentScope(AuthRelayWriteScope);1387+ if (payload.holdWebhooksWhileOffline !== undefined) {1388+ // The relay decides whether to hold a request, so it is told first; the1389+ // local copy is only saved once the relay has the same value.1390+ yield* pushHoldWebhooksWhileOffline(dependencies, payload.holdWebhooksWhileOffline);1391+ yield* dependencies.secrets.set(1392+ HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,1393+ stringToBytes(String(payload.holdWebhooksWhileOffline)),apps/server/src/relay/HookMailboxDrain.ts lines 129 to 136OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ let delivered = 0;117+ // Bounded so one pass cannot run forever against a relay that keeps returning work.118+ for (let page = 0; page < 50; page++) {119+ const pending = yield* relay.pending;120+ if (pending === null || pending.length === 0) return delivered;121+ const ack: Array<string> = [];122+ let rateLimited = false;123+ for (const hook of pending) {124+ const request = toTriggerRequest(hook);125+ if (request === null) {126+ ack.push(hook.id);127+ continue;128+ }129+ const result = yield* scheduledTasks.triggerWebhook(request);130+ if (result._tag === "rate_limited") {131+ rateLimited = true;132+ continue;133+ }134+ ack.push(hook.id);135+ delivered++;136+ }@@ -262,0 +275,21 @@275+ ...forwardedHeaders(request.headers),276+ [RELAY_DELIVERY_ID_HEADER]: deliveryId,277+ };278+ // Held only for environments that opted in; otherwise the relay is a plain proxy.279+ const holdOrFail = (status: 503 | 504, error: string) =>280+ Effect.gen(function* () {281+ if (!endpoint.holdWhileOffline) {282+ yield* outcome(error);283+ return errorResponse(status, error);284+ }285+ const stored = yield* mailbox286+ .enqueue({287+ id: deliveryId,288+ environmentId: parsed.environmentId,289+ receivedAt: DateTime.formatIso(yield* DateTime.now),290+ method: request.method,291+ rawHookId: parsed.rawHookId,292+ rawToken: parsed.rawToken,293+ query: parsed.search.replace(/^\?/, ""),294+ headers: forwardedHeaders(request.headers),295+ body: body.success,@@ -261,2 +270,20 @@261270 : `${endpoint.httpBaseUrl}/`;262- const headers = forwardedHeaders(request.headers);271+ // One id per attempt, so a request that reached the environment before a272+ // timeout and is later replayed from the mailbox dispatches only once.273+ const deliveryId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);274+ const headers: Record<string, string> = {275+ ...forwardedHeaders(request.headers),276+ [RELAY_DELIVERY_ID_HEADER]: deliveryId,277+ };278+ // Held only for environments that opted in; otherwise the relay is a plain proxy.279+ const holdOrFail = (status: 503 | 504, error: string) =>280+ Effect.gen(function* () {281+ if (!endpoint.holdWhileOffline) {282+ yield* outcome(error);283+ return errorResponse(status, error);284+ }285+ const stored = yield* mailbox286+ .enqueue({287+ id: deliveryId,288+ environmentId: parsed.environmentId,289+ receivedAt: DateTime.formatIso(yield* DateTime.now),infra/relay/src/hooks/HookMailbox.ts lines 81 to 86OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +66,21 @@66+67+export const make = Effect.gen(function* () {68+ const db = yield* RelayDb.RelayDb;69+ const fail =70+ (operation: HookMailboxPersistenceError["operation"], environmentId?: string) =>71+ (cause: unknown) =>72+ new HookMailboxPersistenceError({73+ operation,74+ ...(environmentId === undefined ? {} : { environmentId }),75+ cause,76+ });77+78+ return HookMailbox.of({79+ enqueue: Effect.fn("relay.hook_mailbox.enqueue")(function* (hook) {80+ yield* Effect.annotateCurrentSpan({ "relay.environment_id": hook.environmentId });81+ const [held] = yield* db82+ .select({ value: count() })83+ .from(relayHookMailbox)84+ .where(eq(relayHookMailbox.environmentId, hook.environmentId))85+ .pipe(Effect.mapError(fail("enqueue", hook.environmentId)));86+ if ((held?.value ?? 0) >= HOOK_MAILBOX_MAX_PER_ENVIRONMENT) return false;infra/relay/src/persistence/schema.ts line 78Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -74,3 +75,5 @@7475 notificationsEnabled: boolean("notifications_enabled").notNull().default(true),7576 liveActivitiesEnabled: boolean("live_activities_enabled").notNull().default(true),7677 managedTunnelsEnabled: boolean("managed_tunnels_enabled").notNull().default(false),78+ // Opt-in: hold webhook requests while the environment is offline.79+ holdWebhooksWhileOffline: boolean("hold_webhooks_while_offline").notNull().default(false),
juliusmarminge changed the title
- apps/server/src/scheduledTasks/ScheduledTaskService.ts line 1429Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1297,6 +1311,5 @@12971311 const task = yield* decodeRow(row);12981312 if (task.schedule.type !== "webhook") return { _tag: "not_found" as const };129913131300- const receivedAt = yield* localNow;1301- const deliveryUuid = yield* crypto.randomUUIDv4.pipe(1302- Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })),1314+ const now = yield* localNow;1315+ const receivedAt =infra/relay/src/hooks/upstream.ts line 54OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ * Sends a webhook request through the environment's tunnel. Fails when the35+ * environment cannot be reached, and succeeds with None on timeout.36+ */37+export const sendUpstream = (baseUrl: string, hook: UpstreamHook) =>38+ Effect.gen(function* () {39+ const httpClient = yield* HttpClient.HttpClient;40+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;41+ const headers: Record<string, string> = {42+ ...hook.headers,43+ [RELAY_DELIVERY_ID_HEADER]: hook.id,44+ };45+ let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(46+ `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,47+ { headers },48+ );49+ if (hook.method !== "GET") {50+ request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);51+ }52+ return yield* httpClient.execute(request).pipe(53+ Effect.flatMap((response) =>54+ response.arrayBuffer.pipe(
- infra/relay/src/hooks/HookForwarder.ts line 296OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -272,0 +276,21 @@276+ const hook = {277+ id: yield* crypto.randomUUIDv4.pipe(Effect.orDie),278+ method: request.method,279+ rawHookId: parsed.rawHookId,280+ rawToken: parsed.rawToken,281+ query: parsed.search.replace(/^\?/, ""),282+ headers: forwardedHeaders(request.headers),283+ body: body.success,284+ };285+ // Held only for environments that opted in; otherwise the relay is a plain proxy.286+ const holdOrFail = (status: 503 | 504, error: string) =>287+ Effect.gen(function* () {288+ if (!endpoint.holdWhileOffline) {289+ yield* outcome(error);290+ return errorResponse(status, error);291+ }292+ const stored = yield* inbox293+ .hold({294+ environmentId: parsed.environmentId,295+ baseUrl: endpoint.httpBaseUrl,296+ hook: { ...hook, receivedAt },
- @@ -0,0 +174,21 @@174+175+/**176+ * Pushes the oldest held requests to the environment, one at a time, and177+ * stops at the first one that has to be retried. Drops requests older than178+ * the TTL. Returns when the next run is due, or null when nothing is left.179+ */180+export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(181+ send: (baseUrl: string, hook: HeldHook) => Effect.Effect<DeliveryOutcome, never, R>,182+) {183+ const sql = yield* SqlClient.SqlClient;184+ const startedAt = yield* Clock.currentTimeMillis;185+ yield* sql`DELETE FROM held_hooks WHERE received_at < ${iso(startedAt - HOOK_INBOX_TTL_MS)}`;186+ const target = yield* readTarget;187+ const batch = yield* sql<HeldHookRow>`188+ SELECT id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body189+ FROM held_hooks ORDER BY seq LIMIT ${DELIVERIES_PER_RUN}190+ `;191+ if (batch.length === 0 || target === null) {192+ if (target === null) yield* sql`DELETE FROM held_hooks`;193+ return null;194+ }@@ -513,3 +515,11 @@513515 environmentId: link.environmentId,514516 environmentPublicKey: link.environmentPublicKey,515517 });518+ // Held webhook requests belong to the environment, not one user's link;519+ // drop them once no user has it linked any more.520+ const remaining = yield* links.findActiveManagedForEnvironment({521+ environmentId: input.environmentId,522+ });523+ if (remaining.length === 0) {524+ const inbox = yield* HookInbox.HookInbox;525+ yield* inbox.clear({ environmentId: input.environmentId });@@ -513,3 +515,11 @@513515 environmentId: link.environmentId,514516 environmentPublicKey: link.environmentPublicKey,515517 });518+ // Held webhook requests belong to the environment, not one user's link;519+ // drop them once no user has it linked any more.520+ const remaining = yield* links.findActiveManagedForEnvironment({521+ environmentId: input.environmentId,522+ });523+ if (remaining.length === 0) {524+ const inbox = yield* HookInbox.HookInbox;525+ yield* inbox.clear({ environmentId: input.environmentId });
- @@ -523,3 +537,15 @@523537 environmentId: input.environmentId,524538 target: deprovisionTarget,525539 });540+ // Requests held for this link's endpoint go with it. Best effort: the link541+ // is already gone, and its inbox drops anything left after its TTL.542+ const endpointKey =543+ deprovisionTarget && input.managedEndpointNamespace544+ ? HookForwarder.endpointKeyForTunnelName(545+ input.managedEndpointNamespace,546+ deprovisionTarget.tunnelName,547+ )548+ : null;549+ if (endpointKey !== null) {550+ const inbox = yield* HookInbox.HookInbox;551+ yield* inbox.clear({ endpointKey }).pipe(@@ -1179,11 +1209,13 @@11791209 * Public, stateless webhook forwarding to an environment's managed tunnel.11801210 * Unauthenticated: the token in the path is the environment's credential, and11811211 * the relay only routes and forwards. Raw, so the body reaches the1182- * environment byte for byte and signatures still verify there.1212+ * environment byte for byte and signatures still verify there. `endpointKey`1213+ * names one managed endpoint (its tunnel's hash of user and environment), not1214+ * the environment id, which any account can link.11831215 */11841216 const RelayHookParams = Schema.Struct({1185- environmentId: Schema.String,1217+ endpointKey: Schema.String,11861218 hookId: Schema.String,11871219 token: Schema.String,11881220 });1189-const RELAY_HOOK_PATH = "/v1/hooks/:environmentId/:hookId/:token";1221+const RELAY_HOOK_PATH = "/v1/hooks/:endpointKey/:hookId/:token";infra/relay/src/environments/EnvironmentLinks.ts lines 190 to 196Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -166,3 +183,11 @@166183 const now = DateTime.formatIso(yield* DateTime.now);167184 const { request, proof } = input;168185 const environmentId = proof.environmentId;186+ // The webhook-hold opt-in belongs to the environment: a new or re-made187+ // link carries it over from the environment's other active links.188+ const inheritedHoldWebhooks = sql<boolean>`EXISTS (189+ SELECT 1 FROM ${relayEnvironmentLinks} AS other190+ WHERE other.environment_id = ${environmentId}191+ AND other.revoked_at IS NULL192+ AND other.hold_webhooks_while_offline193+ )`;@@ -1322,0 +1378,21 @@1378+ WHERE relay_delivery_id = ${request.relayDeliveryId}1379+ `.pipe(Effect.ignore, Effect.as(result));1380+ // From the claim until the run is forked nothing may interrupt: a1381+ // request dropped in between (the relay hangs up after its timeout)1382+ // would leave a claimed delivery that never runs, or a queue slot1383+ // that is never released. Everything in here is local and quick.1384+ return yield* Effect.uninterruptible(1385+ Effect.gen(function* () {1386+ if (request.relayDeliveryId !== undefined) {1387+ const claimed = yield* sql<{ relay_delivery_id: string }>`1388+ INSERT INTO scheduled_task_webhook_relay_deliveries1389+ (relay_delivery_id, task_id, seen_at)1390+ VALUES (${request.relayDeliveryId}, ${task.id}, ${iso(now)})1391+ ON CONFLICT (relay_delivery_id) DO NOTHING1392+ RETURNING relay_delivery_id1393+ `.pipe(1394+ Effect.mapError((cause) =>1395+ taskError("Could not record webhook delivery.", { taskId: task.id, cause }),1396+ ),1397+ );1398+ if (claimed.length === 0) return { _tag: "accepted" as const, deliveryId };
- infra/relay/src/hooks/HookInboxStore.ts line 233OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +213,21 @@213+ const sql = yield* SqlClient.SqlClient;214+ yield* sql`DELETE FROM held_hooks`;215+ yield* sql`DELETE FROM held_hooks_target`;216+});217+218+/**219+ * Pushes the oldest held requests to the environment, one at a time, in220+ * order per hook. Stops at the first sign the environment is unreachable;221+ * skips past a hook whose environment answered busy. Drops requests older222+ * than the TTL. Returns when the next run is due, or null when nothing is left.223+ */224+export const deliverDue = Effect.fn("HookInboxStore.deliverDue")(function* <R>(225+ send: (baseUrl: string, hook: HeldHook) => Effect.Effect<DeliveryOutcome, never, R>,226+) {227+ const sql = yield* SqlClient.SqlClient;228+ const startedAt = yield* Clock.currentTimeMillis;229+ yield* sql`DELETE FROM held_hooks WHERE received_at < ${iso(startedAt - HOOK_INBOX_TTL_MS)}`;230+ const target = yield* readTarget;231+ const batch = yield* sql<HeldHookRow>`232+ SELECT id, received_at, method, raw_hook_id, raw_token, hook_key, query, headers, body233+ FROM held_hooks ORDER BY seq LIMIT ${ROWS_READ_PER_RUN}
- @@ -1322,0 +1378,21 @@1378+ WHERE relay_delivery_id = ${request.relayDeliveryId}1379+ `.pipe(Effect.ignore, Effect.as(result));1380+ // From the claim until the run is forked nothing may interrupt: a1381+ // request dropped in between (the relay hangs up after its timeout)1382+ // would leave a claimed delivery that never runs, or a queue slot1383+ // that is never released. Everything in here is local and quick.1384+ return yield* Effect.uninterruptible(1385+ Effect.gen(function* () {1386+ if (request.relayDeliveryId !== undefined) {1387+ const claimed = yield* sql<{ relay_delivery_id: string }>`1388+ INSERT INTO scheduled_task_webhook_relay_deliveries1389+ (relay_delivery_id, task_id, seen_at)1390+ VALUES (${request.relayDeliveryId}, ${task.id}, ${iso(now)})1391+ ON CONFLICT (relay_delivery_id) DO NOTHING1392+ RETURNING relay_delivery_id1393+ `.pipe(1394+ Effect.mapError((cause) =>1395+ taskError("Could not record webhook delivery.", { taskId: task.id, cause }),1396+ ),1397+ );1398+ if (claimed.length === 0) return { _tag: "accepted" as const, deliveryId };@@ -1812,3 +1813,17 @@18121813 setIsUpdatingPreference(false);18131814 };181418151816+ const updateHoldWebhooks = async (enabled: boolean) => {1817+ setIsUpdatingPreference(true);1818+ const ok = await reconcileCloudState({1819+ managedTunnel: managedTunnelActive,1820+ publish: publishAgentActivity,1821+ holdWebhooksWhileOffline: enabled,1822+ });1823+ if (ok) {1824+ toastManager.add({1825+ type: "success",1826+ title: enabled ? "Webhooks held while offline" : "Webhooks no longer held",1827+ description: enabled1828+ ? "T3 Connect keeps webhook requests for up to 24 hours while this environment is offline."1829+ : "Requests to an offline environment now fail. Anything already held is still delivered.",@@ -671,4 +670,5 @@671670 if (!task || !endpoint) {672671 return <p className="text-sm text-muted-foreground">The URL appears after you save.</p>;673672 }674- const url = webhookUrl(endpoint, httpBaseUrl);673+ // Only the server's public URL is copyable; the path alone is not something a sender can call.674+ const url = endpoint.url;@@ -1179,11 +1209,13 @@11791209 * Public, stateless webhook forwarding to an environment's managed tunnel.11801210 * Unauthenticated: the token in the path is the environment's credential, and11811211 * the relay only routes and forwards. Raw, so the body reaches the1182- * environment byte for byte and signatures still verify there.1212+ * environment byte for byte and signatures still verify there. `endpointKey`1213+ * names one managed endpoint (its tunnel's hash of user and environment), not1214+ * the environment id, which any account can link.11831215 */11841216 const RelayHookParams = Schema.Struct({1185- environmentId: Schema.String,1217+ endpointKey: Schema.String,11861218 hookId: Schema.String,11871219 token: Schema.String,11881220 });1189-const RELAY_HOOK_PATH = "/v1/hooks/:environmentId/:hookId/:token";1221+const RELAY_HOOK_PATH = "/v1/hooks/:endpointKey/:hookId/:token";
- apps/server/src/scheduledTasks/ScheduledTaskService.ts lines 1524 to 1524OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1328,17 +1521,4 @@1328- if (slot !== "allowed") {1329- if (slot === "first_rejected") yield* log("rate_limited");1330- return { _tag: "rate_limited" as const };1331- }1332- if (!task.enabled) {1333- yield* log("disabled");1334- return { _tag: "disabled" as const };1335- }1336- const signature = task.schedule.signature;1337- if (signature !== null) {1338- const verified =1339- row.webhook_secret !== null &&1340- verifyWebhookSignature({1341- signature,1342- secret: row.webhook_secret,1343- headers: request.headers,1344- body: request.body,1521+ const rendered = renderWebhookPrompt(task.prompt, request);1522+ // A provider refuses a turn this long, so it is not started. The1523+ // delivery is not retryable, so the claim is kept.1524+ if (rendered.prompt.length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) {
- @@ -0,0 +1,21 @@1+import * as Effect from "effect/Effect";2+import * as Layer from "effect/Layer";3+import * as Schedule from "effect/Schedule";4+import * as Stream from "effect/Stream";5+6+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";7+import * as CloudManagedEndpointRuntime from "../cloud/ManagedEndpointRuntime.ts";8+import { readHoldWebhooksWhileOffline, readRelayConnection } from "../cloud/config.ts";9+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";10+import { makeRelayEnvironmentClient } from "./relayEnvironmentClient.ts";11+12+/**13+ * Tells T3 Connect this environment is reachable again, so the relay delivers14+ * the webhook requests it held while we were offline now rather than at its15+ * next backoff step. Nothing happens unless the environment opted in.16+ */17+const wakeHeldHooks = Effect.fn("HeldHooksWaker.wake")(function* () {18+ const secrets = yield* ServerSecretStore.ServerSecretStore;19+ if (!(yield* readHoldWebhooksWhileOffline(secrets))) return false;20+ const connection = yield* readRelayConnection(secrets);21+ if (connection === null) return false;@@ -386,3 +386,9 @@386386 `t3_provider_turns_total`387387 `t3_git_commands_total`388388389+Webhooks have their own families:390+391+`t3_webhook_deliveries_total` by `outcome` and `source` (`relay` or `direct`). Beyond what the392+ sender sees, `queue_full` means a task already had its limit of deliveries waiting,393+ `prompt_too_long` means the filled-in prompt passed the provider limit, and `duplicate` means394+ the relay delivered a request this environment had already run.@@ -57,3 +57,9 @@5757 window. It can point to a date or time problem on either device, but it can also result from a5858 delayed request. The client uses this category, and the absence of a category from an older relay,5959 to decide whether clock skew is confirmed or only one possible cause.60+61+## Webhooks62+63+A public webhook request is one `relay.hooks.forward` span. Its `relay.hook.outcome` says what64+happened: `forwarded`, `held`, `rate_limited`, `inbox_full`, `not_found`, `payload_too_large`,65+`environment_unavailable`, or `environment_timeout`. `relay.hook.endpoint_key` identifies the
- infra/relay/src/hooks/HookInboxObject.ts line 146OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+ Effect.gen(function* () {127+ const pending = yield* run(HookInboxStore.wake(baseUrl));128+ yield* Effect.annotateCurrentSpan({ "relay.inbox.pending": pending });129+ if (pending) yield* state.storage.setAlarm(yield* Clock.currentTimeMillis);130+ return pending;131+ }).pipe(withInboxSpan("relay.inbox.wake", inboxId)),132+ clear: () =>133+ Effect.gen(function* () {134+ yield* run(HookInboxStore.clear);135+ yield* state.storage.deleteAlarm();136+ }).pipe(withInboxSpan("relay.inbox.clear", inboxId)),137+ alarm: () =>138+ run(HookInboxStore.deliverDue(deliver)).pipe(139+ // A wake during this run may already have asked for an earlier140+ // run; a backoff must not push it out.141+ Effect.flatMap((nextAt) => (nextAt === null ? Effect.void : scheduleBy(nextAt))),142+ Effect.catchCause((cause) =>143+ Effect.logWarning("Held webhook delivery run failed", { cause }).pipe(144+ Effect.andThen(Effect.annotateCurrentSpan({ "relay.inbox.run_result": "failed" })),145+ Effect.andThen(Clock.currentTimeMillis),146+ Effect.flatMap((now) => state.storage.setAlarm(now + RUN_FAILURE_RETRY_MS)),apps/server/src/scheduledTasks/webhookRoute.ts line 79OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -48,10 +60,20 @@60+ }).pipe(Effect.as(json(413, { error }, "body_too_large")));61+ if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable");4862 if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) {49- return json(413, { error: "body_too_large" });63+ return yield* tooLarge("body_too_large");5064 }51655266 const headers: Record<string, string> = {};5367 for (const [name, value] of Object.entries(request.headers)) {5468 if (typeof value === "string") headers[name.toLowerCase()] = value;5569 }5670 const queryIndex = request.url.indexOf("?");71+ // Only the relay sets these; it strips any copy a sender supplied. The72+ // receive time matters for requests the relay held while we were offline.73+ const relayDeliveryId = headers["x-t3-relay-delivery-id"];74+ const relayReceivedAt = relayDeliveryId ? headers["x-t3-relay-received-at"] : undefined;577576+ // A relay delivery joins the relay's trace, and goes to the T3 Connect77+ // tracer with it. A sender's own traceparent is never trusted: anyone78+ // calling the URL directly could otherwise attach to our traces.79+ const relayParent = relayDeliveryId
juliusmarminge merged thisf33b060
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
734a2fe· 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.