Skip to content

Commit 76a8678

Browse files
authored
feat: add retry mechanism to socket connect (#950)
1 parent 996cb5a commit 76a8678

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

Diff for: packages/cli/src/services/socket-client.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,23 @@ import { getProxyForUrl } from 'proxy-from-env'
55
import { httpsOverHttp, httpsOverHttps } from 'tunnel'
66

77
const isHttps = (protocol: string) => protocol.startsWith('https')
8+
9+
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
10+
11+
async function backOffConnect (url: string, options: mqtt.IClientOptions, retryCount = 0):
12+
Promise<mqtt.AsyncMqttClient> {
13+
try {
14+
return mqtt.connectAsync(url, options, false)
15+
} catch (error) {
16+
if (retryCount > 3) {
17+
throw error
18+
}
19+
retryCount += 1
20+
await wait(100 * retryCount)
21+
return backOffConnect(url, options, retryCount)
22+
}
23+
}
24+
825
export class SocketClient {
926
static connect (): Promise<mqtt.AsyncMqttClient> {
1027
const url = config.getMqttUrl()
@@ -39,6 +56,6 @@ export class SocketClient {
3956
}
4057
}
4158
}
42-
return mqtt.connectAsync(`${url}?authenticationScheme=userApiKey`, options, false)
59+
return backOffConnect(`${url}?authenticationScheme=userApiKey`, options, 0)
4360
}
4461
}

0 commit comments

Comments
 (0)