Skip to content

Commit

Permalink
refactor: 调整keep alive写法
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Apr 2, 2024
1 parent 0614ea5 commit f713cbd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 19 deletions.
17 changes: 17 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"ms": "^2.1.2",
"p-map": "^7.0.1",
"p-retry": "^6.2.0",
"p-timeout": "^6.1.2",
"pino": "^8.19.0",
"pino-pretty": "^10.3.1",
"pretty-bytes": "^6.1.1",
Expand Down
40 changes: 21 additions & 19 deletions src/cluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {clearTimeout} from 'node:timers'
import {tmpdir} from 'os'
import pMap from 'p-map'
import pRetry from 'p-retry'
import pTimeout from 'p-timeout'
import {basename, dirname, join} from 'path'
import prettyBytes from 'pretty-bytes'
import {connect, Socket} from 'socket.io-client'
Expand Down Expand Up @@ -439,24 +440,22 @@ export class Cluster {
if (!this.isEnabled) {
throw new Error('节点未启用')
}
return await new Promise((resolve, reject) => {
const counters = clone(this.counters)
this.socket?.emit(
'keep-alive',
{
time: new Date(),
...counters,
},
([err, date]: [unknown, string]) => {
if (err) return reject(err)
const bytes = prettyBytes(counters.bytes, {binary: true})
logger.info(`keep alive success, serve ${counters.hits} files, ${bytes}`)
this.counters.hits -= counters.hits
this.counters.bytes -= counters.bytes
resolve(!!date)
},
)
})
if (!this.socket) {
throw new Error('未连接到服务器')
}

const counters = clone(this.counters)
const [err, date] = (await this.socket.emitWithAck('keep-alive', {
time: new Date(),
...counters,
})) as [object, unknown]

if (err) throw new Error('keep alive error', {cause: err})
const bytes = prettyBytes(counters.bytes, {binary: true})
logger.info(`keep alive success, serve ${counters.hits} files, ${bytes}`)
this.counters.hits -= counters.hits
this.counters.bytes -= counters.bytes
return !!date
}

public async requestCert(): Promise<void> {
Expand Down Expand Up @@ -516,8 +515,11 @@ export class Cluster {
}

private async _keepAlive(): Promise<void> {
logger.trace('start keep alive')
try {
const status = await Bluebird.try(async () => await this.keepAlive()).timeout(ms('10s'), 'keep alive timeout')
const status = await pTimeout(this.keepAlive(), {
milliseconds: ms('10s'),
})
if (!status) {
logger.fatal('kicked by server')
this.exit(1)
Expand Down

0 comments on commit f713cbd

Please sign in to comment.