Skip to content

Commit

Permalink
feat: 动态backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
bangbang93 committed Aug 3, 2023
1 parent b49b552 commit 7890db9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
3 changes: 3 additions & 0 deletions src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ export async function bootstrap(version: string): Promise<void> {
cluster.exit(1)
}
console.log(colors.rainbow(`done, serving ${files.files.length} files`))
if (process.env.NODE_UNIQUE_ID && typeof process.send === 'function') {
process.send('ready')
}

let checkFileInterval = setTimeout(checkFile, ms('10m'))
async function checkFile(): Promise<void> {
Expand Down
13 changes: 10 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import cluster from 'cluster'
import {config} from 'dotenv'
import {readFileSync} from 'fs'
import ms from 'ms'
import {fileURLToPath} from 'url'
import {bootstrap} from './bootstrap.js'

Expand All @@ -21,10 +20,18 @@ if (!process.env.NO_DEMAON && cluster.isPrimary) {
forkWorker()
}

const BACKOFF_FACTOR = 2
let backoff = 1

function forkWorker(): void {
const worker = cluster.fork()
worker.on('exit', () => {
console.log(`工作进程 ${worker.id} 异常退出,60秒后重启`)
setTimeout(() => forkWorker(), ms('60s'))
console.log(`工作进程 ${worker.id} 异常退出,${backoff}秒后重启`)
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
setTimeout(() => forkWorker(), backoff * 1000)
backoff = Math.max(backoff * BACKOFF_FACTOR, 60)
})
worker.on('ready', () => {
backoff = 1
})
}

0 comments on commit 7890db9

Please sign in to comment.