Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -3,18 +3,7 @@ import WebSocket from 'ws'
|
||||
import type { PairingOffer } from './pairing'
|
||||
import { decrypt, encrypt } from './e2ee-crypto'
|
||||
import type { RuntimeRpcResponse } from './runtime-rpc-envelope'
|
||||
import {
|
||||
serializeRemoteRuntimePayload,
|
||||
serializeRemoteRuntimeRpcRequest
|
||||
} from './remote-runtime-memory-limits'
|
||||
import {
|
||||
prepareRemoteRuntimeRequest,
|
||||
releaseRemoteRuntimePreparedRequest,
|
||||
takeRemoteRuntimePreparedRequest,
|
||||
toRemoteRuntimeRequestError,
|
||||
type RemoteRuntimePendingRequest,
|
||||
type RemoteRuntimePreparedRequest
|
||||
} from './remote-runtime-prepared-request-admission'
|
||||
import { RemoteRuntimeClientError } from './remote-runtime-client'
|
||||
import {
|
||||
invalidRemoteRuntimeResponseError,
|
||||
parseAuthenticatedFrame,
|
||||
@@ -23,49 +12,44 @@ import {
|
||||
remoteRuntimeTimeoutError,
|
||||
remoteRuntimeUnavailableError
|
||||
} from './remote-runtime-request-frames'
|
||||
import {
|
||||
rejectRemoteRuntimeRequestReadyWaiters,
|
||||
resolveRemoteRuntimeRequestReadyWaiters,
|
||||
waitForRemoteRuntimeRequestReady,
|
||||
type RemoteRuntimeRequestReadyWaiter
|
||||
} from './remote-runtime-request-ready-waiters'
|
||||
import { openRemoteRuntimeWebSocket } from './remote-runtime-request-websocket'
|
||||
|
||||
type ConnectionState = 'closed' | 'awaiting_ready' | 'awaiting_authenticated' | 'ready'
|
||||
|
||||
type PendingRequest<TResult> = {
|
||||
resolve: (response: RuntimeRpcResponse<TResult>) => void
|
||||
reject: (error: Error) => void
|
||||
timeout: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
type ReadyWaiter = {
|
||||
resolve: () => void
|
||||
reject: (error: Error) => void
|
||||
}
|
||||
|
||||
const IDLE_CLOSE_MS = 60_000
|
||||
|
||||
export class RemoteRuntimeRequestConnection {
|
||||
private readonly pairing: PairingOffer
|
||||
private state: ConnectionState = 'closed'
|
||||
private ws: WebSocket | null = null
|
||||
private sharedKey: Uint8Array | null = null
|
||||
private socketCleanup: (() => void) | null = null
|
||||
private readonly pendingRequests = new Map<string, RemoteRuntimePendingRequest<unknown>>()
|
||||
private readonly readyWaiters: RemoteRuntimeRequestReadyWaiter[] = []
|
||||
private readonly pendingRequests = new Map<string, PendingRequest<unknown>>()
|
||||
private readonly readyWaiters: ReadyWaiter[] = []
|
||||
private idleCloseTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
constructor(private readonly pairing: PairingOffer) {}
|
||||
constructor(pairing: PairingOffer) {
|
||||
this.pairing = pairing
|
||||
}
|
||||
|
||||
request<TResult>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
): Promise<RuntimeRpcResponse<TResult>> {
|
||||
const requestId = randomUUID()
|
||||
let preparedRequest: RemoteRuntimePreparedRequest
|
||||
try {
|
||||
preparedRequest = prepareRemoteRuntimeRequest(this.pendingRequests, () =>
|
||||
serializeRemoteRuntimeRpcRequest({
|
||||
requestId,
|
||||
deviceToken: this.pairing.deviceToken,
|
||||
method,
|
||||
params
|
||||
})
|
||||
)
|
||||
} catch (error) {
|
||||
return Promise.reject(toRemoteRuntimeRequestError(error))
|
||||
}
|
||||
this.clearIdleCloseTimer()
|
||||
const requestId = randomUUID()
|
||||
return new Promise<RuntimeRpcResponse<TResult>>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
const pending = this.pendingRequests.get(requestId)
|
||||
@@ -73,7 +57,6 @@ export class RemoteRuntimeRequestConnection {
|
||||
return
|
||||
}
|
||||
this.pendingRequests.delete(requestId)
|
||||
releaseRemoteRuntimePreparedRequest(pending)
|
||||
const error = remoteRuntimeTimeoutError()
|
||||
pending.reject(error)
|
||||
this.close(error)
|
||||
@@ -81,13 +64,12 @@ export class RemoteRuntimeRequestConnection {
|
||||
this.pendingRequests.set(requestId, {
|
||||
resolve: resolve as (response: RuntimeRpcResponse<unknown>) => void,
|
||||
reject,
|
||||
timeout,
|
||||
preparedRequest
|
||||
timeout
|
||||
})
|
||||
|
||||
void this.ensureReady().then(
|
||||
() => this.sendRequest(requestId),
|
||||
(error) => this.rejectPendingRequest(requestId, toRemoteRuntimeRequestError(error))
|
||||
() => this.sendRequest(requestId, method, params),
|
||||
(error) => this.rejectPendingRequest(requestId, toClientError(error))
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -95,17 +77,17 @@ export class RemoteRuntimeRequestConnection {
|
||||
close(error?: Error): void {
|
||||
const ws = this.ws
|
||||
const cleanup = this.socketCleanup
|
||||
this.ws = this.sharedKey = null
|
||||
this.ws = null
|
||||
this.sharedKey = null
|
||||
this.socketCleanup = null
|
||||
this.state = 'closed'
|
||||
this.clearIdleCloseTimer()
|
||||
|
||||
const closeError = error ?? remoteRuntimeUnavailableError()
|
||||
rejectRemoteRuntimeRequestReadyWaiters(this.readyWaiters, closeError)
|
||||
this.rejectReadyWaiters(closeError)
|
||||
for (const [requestId, pending] of this.pendingRequests) {
|
||||
clearTimeout(pending.timeout)
|
||||
this.pendingRequests.delete(requestId)
|
||||
releaseRemoteRuntimePreparedRequest(pending)
|
||||
pending.reject(closeError)
|
||||
}
|
||||
|
||||
@@ -123,14 +105,12 @@ export class RemoteRuntimeRequestConnection {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
const promise = waitForRemoteRuntimeRequestReady(this.readyWaiters)
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
this.readyWaiters.push({ resolve, reject })
|
||||
})
|
||||
|
||||
if (!ws || ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
|
||||
try {
|
||||
this.open()
|
||||
} catch (error) {
|
||||
this.close(toRemoteRuntimeRequestError(error))
|
||||
}
|
||||
this.open()
|
||||
}
|
||||
|
||||
return promise
|
||||
@@ -203,10 +183,7 @@ export class RemoteRuntimeRequestConnection {
|
||||
}
|
||||
this.ws?.send(
|
||||
encrypt(
|
||||
serializeRemoteRuntimePayload({
|
||||
type: 'e2ee_auth',
|
||||
deviceToken: this.pairing.deviceToken
|
||||
}),
|
||||
JSON.stringify({ type: 'e2ee_auth', deviceToken: this.pairing.deviceToken }),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
@@ -219,7 +196,7 @@ export class RemoteRuntimeRequestConnection {
|
||||
return
|
||||
}
|
||||
this.state = 'ready'
|
||||
resolveRemoteRuntimeRequestReadyWaiters(this.readyWaiters)
|
||||
this.resolveReadyWaiters()
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
@@ -240,12 +217,11 @@ export class RemoteRuntimeRequestConnection {
|
||||
}
|
||||
this.pendingRequests.delete(response.id)
|
||||
clearTimeout(pending.timeout)
|
||||
releaseRemoteRuntimePreparedRequest(pending)
|
||||
pending.resolve(response)
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
private sendRequest(requestId: string): void {
|
||||
private sendRequest(requestId: string, method: string, params: unknown): void {
|
||||
const pending = this.pendingRequests.get(requestId)
|
||||
const ws = this.ws
|
||||
const sharedKey = this.sharedKey
|
||||
@@ -256,16 +232,17 @@ export class RemoteRuntimeRequestConnection {
|
||||
this.rejectPendingRequest(requestId, remoteRuntimeUnavailableError())
|
||||
return
|
||||
}
|
||||
const serializedRequest = takeRemoteRuntimePreparedRequest(pending)
|
||||
if (serializedRequest === null) {
|
||||
this.rejectPendingRequest(requestId, remoteRuntimeUnavailableError())
|
||||
return
|
||||
}
|
||||
try {
|
||||
ws.send(encrypt(serializedRequest, sharedKey))
|
||||
} catch (error) {
|
||||
this.rejectPendingRequest(requestId, toRemoteRuntimeRequestError(error))
|
||||
}
|
||||
ws.send(
|
||||
encrypt(
|
||||
JSON.stringify({
|
||||
id: requestId,
|
||||
deviceToken: this.pairing.deviceToken,
|
||||
method,
|
||||
params
|
||||
}),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private rejectPendingRequest(requestId: string, error: Error): void {
|
||||
@@ -275,11 +252,24 @@ export class RemoteRuntimeRequestConnection {
|
||||
}
|
||||
this.pendingRequests.delete(requestId)
|
||||
clearTimeout(pending.timeout)
|
||||
releaseRemoteRuntimePreparedRequest(pending)
|
||||
pending.reject(error)
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
private resolveReadyWaiters(): void {
|
||||
const waiters = this.readyWaiters.splice(0)
|
||||
for (const waiter of waiters) {
|
||||
waiter.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
private rejectReadyWaiters(error: Error): void {
|
||||
const waiters = this.readyWaiters.splice(0)
|
||||
for (const waiter of waiters) {
|
||||
waiter.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleIdleCloseIfUnused(): void {
|
||||
if (this.pendingRequests.size > 0 || this.readyWaiters.length > 0 || this.state !== 'ready') {
|
||||
return
|
||||
@@ -298,3 +288,10 @@ export class RemoteRuntimeRequestConnection {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toClientError(error: unknown): Error {
|
||||
if (error instanceof Error) {
|
||||
return error
|
||||
}
|
||||
return new RemoteRuntimeClientError('runtime_error', String(error))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user