Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/main/runtime/relay/relay-control-client-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ export type RelayControlClientOptions = {
createSocket?: (url: string, relayJwt: string) => WebSocket
connectDeadlineMs?: number
silenceLimitMs?: number
probeDeadlineMs?: number
}
118 changes: 118 additions & 0 deletions src/main/runtime/relay/relay-control-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,20 @@ class FakeControlSocket extends EventEmitter {
this.close(1006)
}

pings = 0

ping(): void {
if (this.readyState !== 1) {
throw new Error('socket_not_open')
}
this.pings += 1
}

/** The RFC 6455 reply a live peer owes any ping, delivered out of band. */
pong(): void {
this.emit('pong')
}

deliver(message: ControlFrame): void {
this.emit('message', JSON.stringify(message), false)
}
Expand Down Expand Up @@ -631,3 +645,107 @@ describe('RelayControlClient scripted-socket lifecycle', () => {
expect(onClose).toHaveBeenCalledWith(MOBILE_RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL)
})
})

// STA-7672: a Windows desktop behind NAT/VPN (or resuming from sleep) can hold a
// half-open control socket that send() writes into happily while nothing comes
// back. Every pairing request then failed at its 10s deadline against a socket
// the 75s silence watchdog would not reap for another minute-plus.
describe('RelayControlClient half-open recovery', () => {
afterEach(() => {
vi.useRealTimers()
})

it('probes and tears down a control whose request timed out with no inbound traffic', async () => {
vi.useFakeTimers()
const { client, socket, onClose } = scriptedControl()
await client.connect()
const invite = client.createInvite('device-1').catch((error: Error) => error.message)

await vi.advanceTimersByTimeAsync(10_000)

// The request deadline alone must not close the control — a close would have
// rejected as relay_control_closed_<code> instead.
expect(await invite).toContain('relay_control_request_timeout')
expect(socket.pings).toBe(1)
expect(socket.readyState).toBe(1)

// Neither a pong nor the relay's own 15s ping inside the probe deadline: the
// pipe carried nothing, so the origin gets its close now rather than after
// the 75s silence bound.
await vi.advanceTimersByTimeAsync(20_000)
expect(socket.readyState).toBe(3)
expect(onClose).toHaveBeenCalledWith(1006)
expect(client.isLive()).toBe(false)
})

it('keeps a control that answers the probe', async () => {
vi.useFakeTimers()
const { client, socket, onClose } = scriptedControl()
await client.connect()
const invite = client.createInvite('device-1').catch((error: Error) => error.message)

await vi.advanceTimersByTimeAsync(10_000)
await invite
socket.pong()

await vi.advanceTimersByTimeAsync(40_000)
expect(socket.readyState).toBe(1)
expect(onClose).not.toHaveBeenCalled()
expect(client.isLive()).toBe(true)
})

it("clears an armed probe on the relay's next ping, with no pong involved", async () => {
vi.useFakeTimers()
const { client, socket, onClose } = scriptedControl()
await client.connect()
const invite = client.createInvite('device-1').catch((error: Error) => error.message)

await vi.advanceTimersByTimeAsync(10_000)
expect(socket.pings).toBe(1)
await invite

// The probe window outlasts the relay's 15s ping cadence on purpose: relay
// liveness runs at the application layer, so a middlebox that swallows RFC
// 6455 control frames must not be able to turn this into a reconnect loop.
await vi.advanceTimersByTimeAsync(15_000)
socket.deliver({ type: 'ping', t: Date.now() })
await vi.advanceTimersByTimeAsync(10_000)

expect(socket.readyState).toBe(1)
expect(onClose).not.toHaveBeenCalled()
expect(client.isLive()).toBe(true)
})

it('does not probe a control that kept talking while a request went unanswered', async () => {
vi.useFakeTimers()
const { client, socket } = scriptedControl()
await client.connect()
const invite = client.createInvite('device-1').catch((error: Error) => error.message)

await vi.advanceTimersByTimeAsync(5_000)
socket.deliver({ type: 'ping', t: Date.now() })
await vi.advanceTimersByTimeAsync(5_000)

// A reply running past its deadline under relay DB load is not a dead
// socket; tearing this control down would strand every phone on the cell.
expect(await invite).toContain('relay_control_request_timeout')
expect(socket.pings).toBe(0)
expect(client.isLive()).toBe(true)
})

it('names the cell and the silence in the timeout error', async () => {
vi.useFakeTimers()
const { client } = scriptedControl()
await client.connect()
const invite = client.createInvite('device-1').catch((error: Error) => error.message)

await vi.advanceTimersByTimeAsync(10_000)

const message = await invite
expect(message).toContain('reqKind=invite')
expect(message).toContain('cell=http://relay.test')
expect(message).toContain('socketAgeMs=10000')
expect(message).toContain('sinceInboundMs=10000')
expect(message).toContain('probe=armed')
})
})
31 changes: 17 additions & 14 deletions src/main/runtime/relay/relay-control-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ import {
import { RelayControlRequests } from './relay-control-requests'
import type { DeviceCredentialInstallAuthorization } from './relay-control-requests'
import { answerRelayHostChallenge } from './relay-host-proof'
import {
RELAY_CONTROL_SILENCE_LIMIT_MS,
RelayControlSilenceWatchdog
} from './relay-control-silence-watchdog'
import { RelayControlLiveness } from './relay-control-liveness'
import { closeRelayControlSocket } from './relay-control-socket-close'
import { controlWebSocketUrl } from './relay-control-url'

Expand All @@ -40,18 +37,23 @@ export class RelayControlClient {
private connectResolve: ((ack: RelayHostHelloAckMessage) => void) | null = null
private connectReject: ((error: Error) => void) | null = null
private connectTimer: ReturnType<typeof setTimeout> | null = null
private readonly silenceWatchdog: RelayControlSilenceWatchdog
private readonly liveness: RelayControlLiveness

constructor(options: RelayControlClientOptions) {
this.options = options
this.requests = new RelayControlRequests(options.onPendingChanged)
this.requests = new RelayControlRequests(options.onPendingChanged, (timeout) =>
this.liveness.describeTimeout(timeout, this.isLive())
)
const endpoint = controlWebSocketUrl(options.cellUrl)
this.relayOrigin = endpoint.origin
this.controlUrl = endpoint.url
this.silenceWatchdog = new RelayControlSilenceWatchdog(
options.silenceLimitMs ?? RELAY_CONTROL_SILENCE_LIMIT_MS,
() => this.socket?.terminate()
)
this.liveness = new RelayControlLiveness({
cellUrl: this.relayOrigin,
ping: () => this.socket?.ping(),
onDead: () => this.socket?.terminate(),
...(options.silenceLimitMs !== undefined ? { silenceLimitMs: options.silenceLimitMs } : {}),
...(options.probeDeadlineMs !== undefined ? { probeDeadlineMs: options.probeDeadlineMs } : {})
})
this.createSocket =
options.createSocket ??
((url, token) =>
Expand All @@ -70,8 +72,9 @@ export class RelayControlClient {
const socket = this.createSocket(this.controlUrl, this.options.relayJwt)
this.socket = socket
socket.once('open', () => this.sendHostHello())
socket.on('pong', () => this.liveness.notePong())
socket.on('message', (raw, isBinary) => {
this.silenceWatchdog.noteInbound()
this.liveness.noteInbound()
if (isBinary) {
this.failProtocol('binary control message')
return
Expand Down Expand Up @@ -154,7 +157,7 @@ export class RelayControlClient {
closeNow(hostCloseReason?: RelayHostCloseReason): void {
const wasConnecting = this.state === 'opening' || this.state === 'proving'
this.state = 'closed'
this.silenceWatchdog.stop()
this.liveness.stop()
if (wasConnecting) {
this.connectReject?.(new Error('relay_control_closed'))
this.clearConnectPromise()
Expand Down Expand Up @@ -264,7 +267,7 @@ export class RelayControlClient {
return
}
this.state = 'active'
this.silenceWatchdog.start()
this.liveness.start()
this.connectResolve?.(ack.data)
this.clearConnectPromise()
}
Expand All @@ -285,7 +288,7 @@ export class RelayControlClient {
private handleClose(code: number): void {
const wasConnecting = this.state === 'opening' || this.state === 'proving'
this.state = 'closed'
this.silenceWatchdog.stop()
this.liveness.stop()
if (wasConnecting) {
this.connectReject?.(new Error(`relay_control_closed_${code}`))
this.clearConnectPromise()
Expand Down
116 changes: 116 additions & 0 deletions src/main/runtime/relay/relay-control-liveness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import type { RelayControlRequestTimeout } from './relay-control-requests'
import {
RELAY_CONTROL_SILENCE_LIMIT_MS,
RelayControlSilenceWatchdog
} from './relay-control-silence-watchdog'

// A control request that times out has two indistinguishable causes: a loaded
// relay whose reply is late, or a half-open TCP socket that swallowed the send
// (common on Windows behind NAT/VPN or across sleep-resume, where the OS reports
// the write as succeeding). Only the relay's 75s silence bound catches the
// second, and pairing has already failed by then. An RFC 6455 ping settles it in
// seconds and needs no application opcode: any live peer must answer with a pong.
//
// The deadline deliberately exceeds the relay's own 15s ping cadence. The relay
// keeps its liveness at the application layer (a JSON `ping` frame), so nothing
// in normal operation depends on control frames surviving end to end; a window
// shorter than that cadence would turn a middlebox that swallows pongs into a
// reconnect loop. At 20s a healthy cell clears the probe either way — its own
// ping lands inside the window — so a fired probe means the pipe carried
// neither, which is the definition of dead.
export const RELAY_CONTROL_PROBE_DEADLINE_MS = 20_000

export type RelayControlLivenessOptions = {
cellUrl: string
ping: () => void
onDead: () => void
silenceLimitMs?: number
probeDeadlineMs?: number
}

/** Everything that decides whether a control socket is still reachable. */
export class RelayControlLiveness {
private readonly watchdog: RelayControlSilenceWatchdog
private readonly probeDeadlineMs: number
private probeTimer: ReturnType<typeof setTimeout> | null = null
private openedAt = 0

constructor(private readonly options: RelayControlLivenessOptions) {
this.watchdog = new RelayControlSilenceWatchdog(
options.silenceLimitMs ?? RELAY_CONTROL_SILENCE_LIMIT_MS,
options.onDead
)
this.probeDeadlineMs = options.probeDeadlineMs ?? RELAY_CONTROL_PROBE_DEADLINE_MS
}

start(): void {
this.openedAt = Date.now()
this.watchdog.start()
}

noteInbound(): void {
this.watchdog.noteInbound()
this.disarmProbe()
}

// A pong proves the pipe and nothing more — it can come from a socket the
// relay has already unindexed — so it clears a probe but never feeds the
// watchdog, whose job is to mirror the relay's own 75s bound.
notePong(): void {
this.disarmProbe()
}

stop(): void {
this.watchdog.stop()
this.disarmProbe()
}

/**
* STA-7672: a close rejects as `relay_control_closed_<code>`, so a request that
* times out instead proves the socket stayed open and never answered. When
* nothing at all arrived since the send, the relay's 15s ping is overdue too —
* the signature of a half-open pipe rather than a reply running late under
* load. Probe now instead of waiting out the 75s silence bound, which on
* Windows let a user burn every pairing attempt against an already-dead socket.
*/
describeTimeout(timeout: RelayControlRequestTimeout, live: boolean): string {
const now = Date.now()
const lastInboundAt = this.watchdog.lastInboundTime
const diagnostics = [
`reqKind=${timeout.kind}`,
`cell=${this.options.cellUrl}`,
`socketAgeMs=${this.openedAt === 0 ? 'n/a' : now - this.openedAt}`,
`sinceInboundMs=${lastInboundAt === 0 ? 'n/a' : now - lastInboundAt}`
]
if (live && lastInboundAt <= timeout.sentAt) {
diagnostics.push(this.probe() ? 'probe=armed' : 'probe=in-flight')
}
return diagnostics.join(' ')
}

private probe(): boolean {
if (this.probeTimer) {
return false
}
try {
this.options.ping()
} catch {
// A ping that throws on a live control is already the answer.
this.options.onDead()
return false
}
this.probeTimer = setTimeout(() => {
this.probeTimer = null
this.options.onDead()
}, this.probeDeadlineMs)
this.probeTimer.unref?.()
return true
}

private disarmProbe(): void {
if (this.probeTimer) {
clearTimeout(this.probeTimer)
this.probeTimer = null
}
}
}
28 changes: 25 additions & 3 deletions src/main/runtime/relay/relay-control-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,22 @@ type PendingRequest = {
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
sentAt: number
}

export type RelayControlRequestTimeout = {
reqId: string
kind: PendingRequest['kind']
sentAt: number
}

/**
* Returns a diagnostic suffix appended to the timeout error. A bare
* `relay_control_request_timeout` cost a full code trace to interpret in
* STA-7672, because the same string covers a slow relay and a dead socket.
*/
export type OnRelayControlRequestTimeout = (timeout: RelayControlRequestTimeout) => string

export type DeviceCredentialInstallAuthorization =
| { mode: 'relay-basis'; basisConnId: string }
| { mode: 'authenticated-direct'; directAuthId: string }
Expand All @@ -42,7 +56,10 @@ type SendRelayControlRequest = (payload: RelayControlRequestPayload) => void
export class RelayControlRequests {
private readonly pending = new Map<string, PendingRequest>()

constructor(private readonly onPendingChanged?: () => void) {}
constructor(
private readonly onPendingChanged?: () => void,
private readonly onTimeout?: OnRelayControlRequestTimeout
) {}

get size(): number {
return this.pending.size
Expand Down Expand Up @@ -170,12 +187,17 @@ export class RelayControlRequests {
if (this.pending.has(reqId)) {
return Promise.reject(new Error('duplicate_relay_request_id'))
}
const sentAt = Date.now()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.finish(reqId)
reject(new Error('relay_control_request_timeout'))
// Runs before the reject so the diagnostics describe the socket as the
// deadline found it, and so a proven-dead socket is torn down while the
// caller still learns it was a timeout rather than a close.
const diagnostics = this.onTimeout?.({ reqId, kind, sentAt }) ?? ''
reject(new Error(`relay_control_request_timeout${diagnostics && ` ${diagnostics}`}`))
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}, 10_000)
this.pending.set(reqId, { kind, resolve, reject, timer })
this.pending.set(reqId, { kind, resolve, reject, timer, sentAt })
try {
send(payload)
} catch (error) {
Expand Down
5 changes: 5 additions & 0 deletions src/main/runtime/relay/relay-control-silence-watchdog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export class RelayControlSilenceWatchdog {
this.lastInboundAt = Date.now()
}

/** 0 before the control activates; callers treat that as "no inbound yet". */
get lastInboundTime(): number {
return this.lastInboundAt
}

start(): void {
this.lastInboundAt = Date.now()
this.timer = setInterval(() => {
Expand Down
Loading