Skip to content

Commit

Permalink
feat(core): support ws reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Mar 5, 2020
1 parent 92aca4b commit f95f794
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
3 changes: 1 addition & 2 deletions packages/koishi-cli/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ if (process.env.KOISHI_LOG_LEVEL !== undefined) {
}

function handleException (error: any) {
const message = types.isNativeError(error) ? error.stack : String(error)
logger.error(message, baseLogLevel)
logger.error(error, baseLogLevel)
process.exit(1)
}

Expand Down
3 changes: 3 additions & 0 deletions packages/koishi-core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export interface AppOptions {
type?: ServerType
database?: DatabaseConfig
nickname?: string | string[]
retryTimes?: number
retryTimeout?: number
maxMiddlewares?: number
commandPrefix?: string | string[]
quickOperationTimeout?: number
Expand Down Expand Up @@ -75,6 +77,7 @@ function createLeadingRE (patterns: string[], prefix = '', suffix = '') {

const defaultOptions: AppOptions = {
maxMiddlewares: 64,
retryTimeout: 15000,
}

export enum Status { closed, opening, open, closing }
Expand Down
22 changes: 16 additions & 6 deletions packages/koishi-core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Meta, VersionInfo, ContextType } from './meta'
import { App } from './app'
import { CQResponse } from './sender'
import { format } from 'util'
import ms from 'ms'

export abstract class Server {
public appList: App[] = []
Expand All @@ -29,7 +30,7 @@ export abstract class Server {
}

protected debug (format: any, ...params: any[]) {
this.app?.logger('koishi:sender').debug(format, ...params)
this.app?.logger('koishi:server').debug(format, ...params)
}

protected prepareMeta (data: any) {
Expand Down Expand Up @@ -277,6 +278,7 @@ let counter = 0

export class WsClient extends Server {
public socket: WebSocket
private _retryCount = 0
private _listeners: Record<number, (response: CQResponse) => void> = {}

send (data: any): Promise<CQResponse> {
Expand All @@ -290,14 +292,21 @@ export class WsClient extends Server {
}

_listen (): Promise<void> {
return new Promise((resolve, reject) => {
const connect = (resolve: () => void, reject: (reason: Error) => void) => {
this.debug('websocket client opening')
const headers: Record<string, string> = {}
const { token, server } = this.app.options
const { token, server, retryTimeout, retryTimes } = this.app.options
if (token) headers.Authorization = `Bearer ${token}`
this.socket = new WebSocket(server, { headers })

this.socket.once('error', reject)
this.socket.once('error', (error: Error) => {
if (!retryTimeout) reject(error)
if (this._retryCount >= retryTimes) reject(error)
this._retryCount++
this.debug(error)
this.app?.logger('koishi').warn(`failed to connect to ${server}, will retry in ${ms(this.app.options.retryTimeout)}...`)
setTimeout(() => connect(resolve, reject), this.app.options.retryTimeout)
})

this.socket.once('open', () => {
this.socket.send(JSON.stringify({
Expand All @@ -306,7 +315,7 @@ export class WsClient extends Server {
}), (error) => {
if (error) reject(error)
})

let resolved = false
this.socket.on('message', (data) => {
data = data.toString()
Expand All @@ -333,7 +342,8 @@ export class WsClient extends Server {
}
})
})
})
}
return new Promise(connect)
}

_close () {
Expand Down

0 comments on commit f95f794

Please sign in to comment.