diff --git a/src/backend/clients/events/EventsWorkerInvokerClient.test.ts b/src/backend/clients/events/EventsWorkerInvokerClient.test.ts index bfeec2f88..b342a011a 100644 --- a/src/backend/clients/events/EventsWorkerInvokerClient.test.ts +++ b/src/backend/clients/events/EventsWorkerInvokerClient.test.ts @@ -23,16 +23,19 @@ */ import type { fetch as undiciFetch } from 'undici'; -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import type { IConfig } from '../../types.js'; import { DispatcherInvokeTransport, EVENTS_DEPLOYED_HEADER, + EVENTS_DEADLINE_MARGIN_MS, EVENTS_DISPATCH_BATCH_PATH, EVENTS_DISPATCH_ERROR_HEADER, EVENTS_DISPATCH_PATH, EVENTS_ERROR_HEADER, EVENTS_HANDLED_HEADER, + EVENTS_INVOKE_TIMEOUT_MS, + EVENTS_WORKER_LEASE_FACTOR, EventsWorkerInvokerClient, INVOKE_CONNECTIONS, SCHEDULE_INVOKE_CONNECTIONS, @@ -1302,3 +1305,90 @@ describe('outcomeForStatus', () => { }, ); }); + +describe('EventsWorkerInvokerClient overall deadline', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + const LEASE_MS = EVENTS_INVOKE_TIMEOUT_MS * EVENTS_WORKER_LEASE_FACTOR; + + /** + * A transport on a fake clock: each send costs what `cost` says, and + * answers a miss until the deployed header, then a handled 200. + */ + const timedTransport = (cost: (deployed: boolean) => number) => { + const sends: Array<{ deployed: boolean; timeoutMs: number }> = []; + const transport = { + send: async (call: { + deployed?: boolean; + timeoutMs: number; + }): Promise => { + const deployed = call.deployed === true; + sends.push({ deployed, timeoutMs: call.timeoutMs }); + // A send never outlasts its own timeout. + vi.advanceTimersByTime( + Math.min(cost(deployed), call.timeoutMs * 1.5), + ); + return deployed + ? { status: 200, handled: true } + : { + status: null, + dispatchReason: 'missing', + error: 'dispatcher: missing (404)', + }; + }, + }; + return { transport, sends }; + }; + + const run = async ( + cost: (deployed: boolean) => number, + deployMs: number, + ) => { + vi.useFakeTimers({ toFake: ['Date'] }); + const { transport, sends } = timedTransport(cost); + const client = makeClient(); + client.setTransport(transport as never); + client.setMissHandler(async () => { + vi.advanceTimersByTime(deployMs); + return 'deployed'; + }); + const started = Date.now(); + const result = await client.invoke(REQUEST); + return { result, sends, elapsed: Date.now() - started }; + }; + + it('leaves a fast miss as it was: a full-timeout resend', async () => { + const { result, sends } = await run(() => 100, 2_000); + expect(result).toEqual({ outcome: 'settled', status: 200 }); + expect(sends).toEqual([ + { deployed: false, timeoutMs: EVENTS_INVOKE_TIMEOUT_MS }, + { deployed: true, timeoutMs: EVENTS_INVOKE_TIMEOUT_MS }, + ]); + }); + + it('shortens the resend after a slow deploy, so the call ends before the lease', async () => { + // A miss that took 12 s, a deploy that took 30 s, and a resend that + // would use everything it is given. + const { result, sends, elapsed } = await run( + (deployed) => (deployed ? 1e9 : 12_000), + 30_000, + ); + expect(result.outcome).toBe('settled'); + expect(sends[1].deployed).toBe(true); + expect(sends[1].timeoutMs).toBeLessThan(EVENTS_INVOKE_TIMEOUT_MS); + expect(elapsed).toBeLessThanOrEqual( + LEASE_MS - EVENTS_DEADLINE_MARGIN_MS, + ); + }); + + it('does not resend when the deploy leaves less than the margin', async () => { + const { result, sends } = await run( + () => 100, + LEASE_MS - EVENTS_DEADLINE_MARGIN_MS * 2 + 1_000, + ); + expect(sends).toHaveLength(1); + expect(result).toMatchObject({ outcome: 'unavailable', status: null }); + }); +}); diff --git a/src/backend/clients/events/EventsWorkerInvokerClient.ts b/src/backend/clients/events/EventsWorkerInvokerClient.ts index 40bcaf4cf..2dea1b444 100644 --- a/src/backend/clients/events/EventsWorkerInvokerClient.ts +++ b/src/backend/clients/events/EventsWorkerInvokerClient.ts @@ -162,6 +162,19 @@ export type WorkerMissHandler = ( /** How long a handler has to answer before the attempt is abandoned. */ export const EVENTS_INVOKE_TIMEOUT_MS = 30_000; +/** + * How many invoke timeouts a delivery's worker lease lasts. The lease store + * reads this, and `invoke()` keeps a whole call, deploy and resend included, + * inside it. + */ +export const EVENTS_WORKER_LEASE_FACTOR = 2; + +/** + * Left unspent at the end of the lease, and the least a resend is worth + * starting with: below it the call is given up as `unavailable` and retried. + */ +export const EVENTS_DEADLINE_MARGIN_MS = 5_000; + /** * Connections held open to the dispatcher, so a busy fleet is not * re-handshaking. Also how many calls one transport makes at once: a call past @@ -255,10 +268,7 @@ export interface EventsInvokeTransport { * handler); retried like `retriable` but never the handler's fault. */ export type WorkerInvokeOutcome = - | 'settled' - | 'terminal' - | 'retriable' - | 'unavailable'; + 'settled' | 'terminal' | 'retriable' | 'unavailable'; export interface WorkerInvokeResult { outcome: WorkerInvokeOutcome; @@ -329,18 +339,49 @@ export class EventsWorkerInvokerClient extends PuterClient { ctx: request.ctx, token: request.token, }); - const send = (deployed: boolean): Promise => + const timeoutMs = this.#timeoutMs(); + // The whole call, deploy and resend included, ends before the lease a + // delivery holds would let it be claimed again mid-run. + // A short configured timeout gets a proportionally short margin. + const margin = Math.min(EVENTS_DEADLINE_MARGIN_MS, timeoutMs / 2); + const deadline = + Date.now() + timeoutMs * EVENTS_WORKER_LEASE_FACTOR - margin; + const send = ( + deployed: boolean, + sendTimeoutMs = timeoutMs, + ): Promise => transport.send({ script: request.script, appUid: request.appUid, key: request.key, body: render(), - timeoutMs: this.#timeoutMs(), + timeoutMs: sendTimeoutMs, ...(deployed ? { deployed: true } : {}), ...(options.lane ? { lane: options.lane } : {}), ...(stampEvent ? { render } : {}), }); + // A send may wait for a connection for half its timeout before the + // run's own timeout starts, so it is given what is left divided by that. + const resend = (): Promise | null => { + const remaining = deadline - Date.now(); + if (remaining < margin) return null; + return send( + true, + Math.floor( + Math.min( + timeoutMs, + remaining / (1 + CONNECTION_WAIT_SHARE), + ), + ), + ); + }; + const outOfTime = (): WorkerInvokeResult => ({ + outcome: 'unavailable', + status: null, + error: 'out of time to resend after deploy', + }); + let result = await send(false); if (this.#missHandler && selfDeployable(result)) { const outcome = await this.#missHandler( @@ -355,7 +396,9 @@ export class EventsWorkerInvokerClient extends PuterClient { error: `deploy: ${outcome}`, ...(outcome === DEPLOY_BUSY ? { deployBusy: true } : {}), }; - result = await send(true); + const resent = await resend(); + if (!resent) return outOfTime(); + result = resent; } else if ( result.status === null && result.dispatchReason && @@ -363,7 +406,9 @@ export class EventsWorkerInvokerClient extends PuterClient { ) { // No deploy to trigger — just give propagation the one retry // it usually needs, without spending an upload on it. - result = await send(true); + const resent = await resend(); + if (!resent) return outOfTime(); + result = resent; } const { status, handled, error, timedOut, retryAfterMs } = result; diff --git a/src/backend/stores/events/PendingDeliveryStore.ts b/src/backend/stores/events/PendingDeliveryStore.ts index 2d7868bc8..272761e1b 100644 --- a/src/backend/stores/events/PendingDeliveryStore.ts +++ b/src/backend/stores/events/PendingDeliveryStore.ts @@ -18,7 +18,10 @@ */ import { randomUUID } from 'node:crypto'; -import { EVENTS_INVOKE_TIMEOUT_MS } from '../../clients/events/EventsWorkerInvokerClient.js'; +import { + EVENTS_INVOKE_TIMEOUT_MS, + EVENTS_WORKER_LEASE_FACTOR, +} from '../../clients/events/EventsWorkerInvokerClient.js'; import { EVENTS_FAILURE_COUNTER_TTL_MS, EVENTS_PENDING_DELIVERIES_PER_SUBSCRIPTION, @@ -316,7 +319,7 @@ export class PendingDeliveryStore extends PuterStore { typeof configured === 'number' && configured > 0 ? configured : EVENTS_INVOKE_TIMEOUT_MS; - return invokeTimeoutMs * 2; + return invokeTimeoutMs * EVENTS_WORKER_LEASE_FACTOR; } // -- Writes ------------------------------------------------------