Skip to content

Commit

Permalink
fix(core): keep retrying after connecting, fix #180
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Mar 25, 2021
1 parent f15df3b commit ff470d5
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions packages/koishi-core/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export namespace Adapter {
}

export interface WsClientOptions {
retryLazy?: number
retryTimes?: number
retryInterval?: number
}
Expand All @@ -98,6 +99,7 @@ export namespace Adapter {
public options: WsClientOptions

static options: WsClientOptions = {
retryLazy: Time.minute,
retryInterval: 5 * Time.second,
retryTimes: 6,
}
Expand All @@ -109,7 +111,7 @@ export namespace Adapter {

private async _listen(bot: Bot.Instance<P>) {
let _retryCount = 0
const { retryTimes, retryInterval } = this.options
const { retryTimes, retryInterval, retryLazy } = this.options

const connect = async (resolve: (value: void) => void, reject: (reason: Error) => void) => {
logger.debug('websocket client opening')
Expand All @@ -125,15 +127,20 @@ export namespace Adapter {
if (!this._listening) return

const message = reason || `failed to connect to ${socket.url}`
if (!retryInterval || _retryCount >= retryTimes) {
return reject(new Error(message))
let timeout = retryInterval
if (_retryCount >= retryTimes) {
if (this.app.status === App.Status.open) {
timeout = retryLazy
} else {
return reject(new Error(message))
}
}

_retryCount++
logger.warn(`${message}, will retry in ${Time.formatTimeShort(retryInterval)}...`)
logger.warn(`${message}, will retry in ${Time.formatTimeShort(timeout)}...`)
setTimeout(() => {
if (this._listening) connect(resolve, reject)
}, retryInterval)
}, timeout)
})

socket.on('open', () => {
Expand Down

0 comments on commit ff470d5

Please sign in to comment.