Files
archived-orca/src/shared/remote-runtime/requests/remote-runtime-shared-control-requests.ts
T
NeilandBlue Thunder Somogyi 66695b1e9d Route federation ack and import over the shared control connection (#38735)
* fix(runtime-environments): route federation ack and import over shared control

The one-second federation sync pulls over the retained shared-control
connection but sent orchestration.federationAck and
orchestration.federationImport on a fresh one-shot socket, closed on the
main thread after every tick that carries progress. On a Mac whose
network content filter holds each TCP close for about a second, that
close froze keystroke relay for the whole app.

Allowlist the two relay mutations in shouldUseSharedControlEnvelope so
they take the same support-routed path as federationPull, including the
one-shot fallback for hosts without shared control. Both handlers are
synchronous and idempotent by request id and cursor. Long-running
mutations such as orchestration.workerStart stay one-shot, and
ORCHESTRATION_MUTATION_METHODS is unchanged.

* test(runtime-environments): pin federation relay transport to shared control

Cover the transport of one federation sync tick so a change that
reintroduces a per-tick one-shot socket fails a test:

- a pull, ack and import for one dispatch open no one-shot socket beyond
  the initial status.get when the host advertises shared control, and
  keep all three on one-shot sockets when it does not
- federationAck and federationImport fall back to one-shot with their
  envelope intact when shared control is unavailable
- shouldUseSharedControlEnvelope shares control for the relay reads and
  the two allowlisted mutations, and keeps orchestration.workerStart and
  other mutations on one-shot

* fix(orchestration): prove the worker server contract once per host incarnation

Every federation mutation without caller-proven contract first fetched
status.get to check the orchestration contract capability, then sent the
mutation as a separate call. The contract is now proven once per host
incarnation (runtime id) and each later mutation is pinned to that
incarnation through the existing expectedRuntimeId routing. A restarted host
answers runtime_environment_changed before any effect; the new incarnation is
proved and the mutation resent. A downgraded restart without the contract
receives no mutation, closing the window the old probe left between its check
and the send.

Fixes #37516

* fix(remote-runtime): honour request preparation on shared control

Federation import selects the prefix of its relay batch that fits the
host's inbound request bound through prepareRequest. That preparation was
only applied on one-shot sockets, so once import moved to shared control
its full batch was sent unprepared. Shared-control requests now serialize
through the same preparation step as one-shot requests, and every route an
import can take (shared or one-shot, pinned to a runtime or not) carries it.
The orchestration transport takes prepareRequest and expectedRuntimeId as
one send-options object.

Fixes #37516

---------

Co-authored-by: Blue Thunder Somogyi <bluethunder.somogyi@bastion.com>
2026-11-05 18:19:16 -08:00

132 lines
4.6 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { abortSignalReason } from '../../abort-signal-reason'
import { serializeRemoteRuntimeRpcRequest } from '../remote-runtime-memory-limits'
import {
prepareRemoteRuntimeRequest,
releaseRemoteRuntimePreparedRequest,
type RemoteRuntimePreparedRequest
} from './remote-runtime-prepared-request-admission'
import { remoteRuntimeTimeoutError } from './remote-runtime-request-frames'
import type {
RuntimeOrchestrationEnvelope,
RuntimeRequestPreparation,
RuntimeRpcResponse
} from '../../runtime-rpc-envelope'
import { serializePreparedRemoteRuntimeRequest } from './remote-runtime-request-preparation'
import { toRemoteRuntimeClientError } from '../control/remote-runtime-shared-control-protocol'
import { rejectSharedControlPendingRequest } from '../control/remote-runtime-shared-control-state'
import type { SharedControlPendingRequest } from '../control/remote-runtime-shared-control-types'
const MAX_RETAINED_METHOD_CHARS = 256
export function requestSharedControl<TResult>(args: {
pendingRequests: Map<string, SharedControlPendingRequest<unknown>>
deviceToken: string
method: string
params: unknown
timeoutMs: number
envelope?: RuntimeOrchestrationEnvelope
/** Picks the params actually sent, e.g. the prefix of a batch that fits the host's request bound. */
prepareRequest?: RuntimeRequestPreparation
ensureReady: () => Promise<void>
send: (requestId: string) => void
retireRequestId?: (requestId: string) => void
signal?: AbortSignal
// Only long-polls opt into keepalive refresh; short RPCs retain absolute deadlines.
refreshTimeoutOnKeepalive?: boolean
/** Runs once the socket is ready, just before sending; a throw rejects without sending. */
beforeSend?: () => void
}): Promise<RuntimeRpcResponse<TResult>> {
const { ensureReady, pendingRequests, send } = args
if (args.signal?.aborted) {
return Promise.reject(abortSignalReason(args.signal))
}
const requestId = randomUUID()
let preparedRequest: RemoteRuntimePreparedRequest
try {
preparedRequest = prepareRemoteRuntimeRequest(pendingRequests, () =>
serializePreparedRemoteRuntimeRequest(
(params, envelope) =>
serializeRemoteRuntimeRpcRequest({
requestId,
deviceToken: args.deviceToken,
method: args.method,
params,
envelope
}),
args.params,
args.envelope,
args.prepareRequest
)
)
} catch (error) {
return Promise.reject(error)
}
return new Promise<RuntimeRpcResponse<TResult>>((resolve, reject) => {
const onAbort = (): void => {
args.retireRequestId?.(requestId)
rejectSharedControlPendingRequest(pendingRequests, requestId, abortSignalReason(args.signal!))
}
const timeout = setTimeout(() => {
const pending = pendingRequests.get(requestId)
if (!pending) {
return
}
pendingRequests.delete(requestId)
releaseRemoteRuntimePreparedRequest(pending)
args.retireRequestId?.(requestId)
// Why: one stalled method does not prove the shared socket is dead;
// socket liveness owns connection-wide teardown so other RPCs survive.
pending.reject(remoteRuntimeTimeoutError())
}, args.timeoutMs)
pendingRequests.set(requestId, {
method: args.method.slice(0, MAX_RETAINED_METHOD_CHARS),
resolve: resolve as (response: RuntimeRpcResponse<unknown>) => void,
reject,
timeout,
preparedRequest,
refreshTimeoutOnKeepalive: args.refreshTimeoutOnKeepalive ?? false
})
args.signal?.addEventListener('abort', onAbort, { once: true })
const removeAbortListener = (): void => args.signal?.removeEventListener('abort', onAbort)
const pending = pendingRequests.get(requestId)
if (pending) {
const resolvePending = pending.resolve
const rejectPending = pending.reject
pending.resolve = (response) => {
removeAbortListener()
resolvePending(response)
}
pending.reject = (error) => {
removeAbortListener()
rejectPending(error)
}
}
if (args.signal?.aborted) {
onAbort()
return
}
void ensureReady().then(
() => {
try {
args.beforeSend?.()
} catch (error) {
rejectSharedControlPendingRequest(
pendingRequests,
requestId,
toRemoteRuntimeClientError(error)
)
return
}
send(requestId)
},
(error) =>
rejectSharedControlPendingRequest(
pendingRequests,
requestId,
toRemoteRuntimeClientError(error)
)
)
})
}