-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathSocketTransport.ts
More file actions
281 lines (228 loc) · 8.6 KB
/
SocketTransport.ts
File metadata and controls
281 lines (228 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { io, type Socket, type SocketOptions, type ManagerOptions } from "socket.io-client"
import { ConnectionState, type RetryConfig } from "@roo-code/types"
export interface SocketTransportOptions {
url: string
socketOptions: Partial<ManagerOptions & SocketOptions>
onConnect?: () => void | Promise<void>
onDisconnect?: (reason: string) => void
onReconnect?: (attemptNumber: number) => void | Promise<void>
logger?: {
log: (message: string, ...args: unknown[]) => void
error: (message: string, ...args: unknown[]) => void
warn: (message: string, ...args: unknown[]) => void
}
}
/**
* Manages the WebSocket transport layer for the bridge system.
* Handles connection lifecycle, retries, and reconnection logic.
*/
export class SocketTransport {
private socket: Socket | null = null
private connectionState: ConnectionState = ConnectionState.DISCONNECTED
private retryTimeout: NodeJS.Timeout | null = null
private hasConnectedOnce: boolean = false
private readonly retryConfig: RetryConfig = {
maxInitialAttempts: Infinity,
initialDelay: 1_000,
maxDelay: 15_000,
backoffMultiplier: 2,
}
private readonly CONNECTION_TIMEOUT = 2_000
private readonly options: SocketTransportOptions
constructor(options: SocketTransportOptions, retryConfig?: Partial<RetryConfig>) {
this.options = options
if (retryConfig) {
this.retryConfig = { ...this.retryConfig, ...retryConfig }
}
}
// This is the initial connnect attempt. We need to implement our own
// infinite retry mechanism since Socket.io's automatic reconnection only
// kicks in after a successful initial connection.
public async connect(): Promise<void> {
if (this.connectionState === ConnectionState.CONNECTED) {
console.log(`[SocketTransport] Already connected`)
return
}
if (this.connectionState === ConnectionState.CONNECTING || this.connectionState === ConnectionState.RETRYING) {
console.log(`[SocketTransport] Connection attempt already in progress`)
return
}
let attempt = 0
let delay = this.retryConfig.initialDelay
while (attempt < this.retryConfig.maxInitialAttempts) {
console.log(`[SocketTransport] Initial connect attempt ${attempt + 1}`)
this.connectionState = attempt === 0 ? ConnectionState.CONNECTING : ConnectionState.RETRYING
try {
await this._connect()
console.log(`[SocketTransport] Connected to ${this.options.url}`)
this.connectionState = ConnectionState.CONNECTED
if (this.options.onConnect) {
await this.options.onConnect()
}
break
} catch (_error) {
attempt++
if (this.socket) {
this.socket.disconnect()
this.socket = null
}
console.log(`[SocketTransport] Waiting ${delay}ms before retry...`)
const promise = new Promise((resolve) => {
this.retryTimeout = setTimeout(resolve, delay)
})
await promise
delay = Math.min(delay * this.retryConfig.backoffMultiplier, this.retryConfig.maxDelay)
}
}
if (this.retryTimeout) {
clearTimeout(this.retryTimeout)
this.retryTimeout = null
}
if (this.connectionState === ConnectionState.CONNECTED) {
console.log(`[SocketTransport] Connected to ${this.options.url}`)
} else {
this.connectionState = ConnectionState.FAILED
console.error(`[SocketTransport] Failed to connect to ${this.options.url}, giving up`)
}
}
private async _connect(): Promise<void> {
return new Promise((resolve, reject) => {
this.socket = io(this.options.url, this.options.socketOptions)
let connectionTimeout: NodeJS.Timeout | null = setTimeout(() => {
console.error(`[SocketTransport] failed to connect after ${this.CONNECTION_TIMEOUT}ms`)
if (this.connectionState !== ConnectionState.CONNECTED) {
this.socket?.disconnect()
reject(new Error("Connection timeout"))
}
}, this.CONNECTION_TIMEOUT)
// https://socket.io/docs/v4/client-api/#event-connect
this.socket.on("connect", async () => {
console.log(`[SocketTransport] on(connect)`)
if (connectionTimeout) {
clearTimeout(connectionTimeout)
connectionTimeout = null
}
if (this.hasConnectedOnce) {
this.connectionState = ConnectionState.CONNECTED
if (this.options.onReconnect) {
await this.options.onReconnect(0)
}
}
this.hasConnectedOnce = true
resolve()
})
// https://socket.io/docs/v4/client-api/#event-connect_error
this.socket.on("connect_error", (error) => {
if (connectionTimeout && this.connectionState !== ConnectionState.CONNECTED) {
console.error(`[SocketTransport] on(connect_error): ${error.message}`)
clearTimeout(connectionTimeout)
connectionTimeout = null
reject(error)
}
})
// https://socket.io/docs/v4/client-api/#event-disconnect
this.socket.on("disconnect", (reason, details) => {
console.log(`[SocketTransport] on(disconnect) (reason: ${reason}, details: ${JSON.stringify(details)})`)
this.connectionState = ConnectionState.DISCONNECTED
if (this.options.onDisconnect) {
this.options.onDisconnect(reason)
}
// Don't attempt to reconnect if we're manually disconnecting.
const isManualDisconnect = reason === "io client disconnect"
if (!isManualDisconnect && this.hasConnectedOnce) {
// After successful initial connection, rely entirely on
// Socket.IO's reconnection logic.
console.log("[SocketTransport] will attempt to reconnect")
} else {
console.log("[SocketTransport] will *NOT* attempt to reconnect")
}
})
// https://socket.io/docs/v4/client-api/#event-error
// Fired upon a connection error.
this.socket.io.on("error", (error) => {
// Connection error.
if (connectionTimeout && this.connectionState !== ConnectionState.CONNECTED) {
console.error(`[SocketTransport] on(error): ${error.message}`)
clearTimeout(connectionTimeout)
connectionTimeout = null
reject(error)
}
// Post-connection error.
if (this.connectionState === ConnectionState.CONNECTED) {
console.error(`[SocketTransport] on(error): ${error.message}`)
}
})
// https://socket.io/docs/v4/client-api/#event-reconnect
// Fired upon a successful reconnection.
this.socket.io.on("reconnect", (attempt) => {
console.log(`[SocketTransport] on(reconnect) - ${attempt}`)
this.connectionState = ConnectionState.CONNECTED
if (this.options.onReconnect) {
this.options.onReconnect(attempt)
}
})
// https://socket.io/docs/v4/client-api/#event-reconnect_attempt
// Fired upon an attempt to reconnect.
this.socket.io.on("reconnect_attempt", (attempt) => {
console.log(`[SocketTransport] on(reconnect_attempt) - ${attempt}`)
})
// https://socket.io/docs/v4/client-api/#event-reconnect_error
// Fired upon a reconnection attempt error.
this.socket.io.on("reconnect_error", (error) => {
console.error(`[SocketTransport] on(reconnect_error): ${error.message}`)
})
// https://socket.io/docs/v4/client-api/#event-reconnect_failed
// Fired when couldn't reconnect within `reconnectionAttempts`.
// Since we use infinite retries, this should never fire.
this.socket.io.on("reconnect_failed", () => {
console.error(`[SocketTransport] on(reconnect_failed) - giving up`)
this.connectionState = ConnectionState.FAILED
})
// This is a custom event fired by the server.
this.socket.on("auth_error", (error) => {
console.error(
`[SocketTransport] on(auth_error): ${error instanceof Error ? error.message : String(error)}`,
)
if (connectionTimeout && this.connectionState !== ConnectionState.CONNECTED) {
clearTimeout(connectionTimeout)
connectionTimeout = null
reject(new Error(error.message || "Authentication failed"))
}
})
})
}
public async disconnect(): Promise<void> {
console.log(`[SocketTransport] Disconnecting...`)
if (this.retryTimeout) {
clearTimeout(this.retryTimeout)
this.retryTimeout = null
}
if (this.socket) {
this.socket.removeAllListeners()
this.socket.io.removeAllListeners()
this.socket.disconnect()
this.socket = null
}
this.connectionState = ConnectionState.DISCONNECTED
console.log(`[SocketTransport] Disconnected`)
}
public getSocket(): Socket | null {
return this.socket
}
public getConnectionState(): ConnectionState {
return this.connectionState
}
public isConnected(): boolean {
return this.connectionState === ConnectionState.CONNECTED && this.socket?.connected === true
}
public async reconnect(): Promise<void> {
console.log(`[SocketTransport] Manually reconnecting...`)
if (this.connectionState === ConnectionState.CONNECTED) {
console.log(`[SocketTransport] Already connected`)
return
}
this.hasConnectedOnce = false
await this.disconnect()
await this.connect()
}
}