Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New feature (Auto Restart): index.ts & Logger.ts #118

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions src/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"doDesktopSearch": true,
"doMobileSearch": true
},
"restartTime": 180000,
"globalTimeout": 30000,
"searchSettings": {
"useGeoLocaleQueries": false,
Expand Down
37 changes: 28 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,42 +56,61 @@ export class MicrosoftRewardsBot {
async run() {
log('MAIN', `Bot started with ${this.config.clusters} clusters`)

// Only cluster when there's more than 1 cluster demanded
if (this.config.clusters > 1) {
if (cluster.isPrimary) {
this.runMaster()
} else {
this.runWorker()
}
// No matter what the situation,
// a master will be started to monitor whether the worker needs to be restarted.
if (cluster.isPrimary) {
this.runMaster()
} else {
this.runTasks(this.accounts)
this.runWorker()
}
}

private runMaster() {
log('MAIN-PRIMARY', 'Primary process started')

const accountChunks = this.utils.chunkArray(this.accounts, this.config.clusters)
// Create a Map to store the worker's PID and corresponding account array to facilitate restarting
const workerAccountsMap = new Map<number, { accounts: Account[], restartCount: number }>()

for (let i = 0; i < accountChunks.length; i++) {
const worker = cluster.fork()
const chunk = accountChunks[i]
const chunk = accountChunks[i] as Account[]
worker.send({ chunk })
workerAccountsMap.set(<number>worker.process.pid, { accounts: chunk, restartCount: 0 })
}

cluster.on('exit', (worker, code) => {
this.activeWorkers -= 1

log('MAIN-WORKER', `Worker ${worker.process.pid} destroyed | Code: ${code} | Active workers: ${this.activeWorkers}`, 'warn')

// Restart worker if exit code is not 0 and restart count is less than 5
if (code !== 0) {
const workerId = worker.process.pid as number
const workerData = workerAccountsMap.get(workerId)
if (workerData) {
if (workerData.restartCount < 5) {
log('QuitUnexpectedly', `Restarting worker ${workerId}... Remaining restarts: ${5 - workerData.restartCount}`, 'warn')
const worker = cluster.fork()
worker.send({ chunk: workerData.accounts })
this.activeWorkers += 1
workerAccountsMap.set(<number>worker.process.pid, { accounts: workerData.accounts, restartCount: workerData.restartCount + 1 })
} else {
log('QuitUnexpectedly', `Worker ${workerId} has reached maximum restart limit.`, 'warn')
}
}
}

// Check if all workers have exited
if (this.activeWorkers === 0) {
log('MAIN-WORKER', 'All workers destroyed. Exiting main process!', 'warn')
process.exit(0)
}
workerAccountsMap.delete(worker.process.pid as number)
})
}


private runWorker() {
log('MAIN-WORKER', `Worker ${process.pid} spawned`)
// Receive the chunk of accounts from the master
Expand Down
1 change: 1 addition & 0 deletions src/interface/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export interface Config {
runOnZeroPoints: boolean;
clusters: number;
workers: Workers;
restartTime: number;
globalTimeout: number;
searchSettings: SearchSettings;
webhook: Webhook;
Expand Down
17 changes: 17 additions & 0 deletions src/util/Logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Webhook } from './Webhook'
import cluster from 'cluster'
import {loadConfig} from './Load'

let timer: NodeJS.Timeout | null = null

export function log(title: string, message: string, type?: 'log' | 'warn' | 'error') {
const currentTime = new Date().toLocaleString()
Expand All @@ -23,4 +27,17 @@ export function log(title: string, message: string, type?: 'log' | 'warn' | 'err
}

if (str) Webhook(str)

if (cluster.isMaster) {
// 如果是主进程,不设置定时器,直接返回
return
}
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
process.exit(1)
// Set a timer. If it is not triggered for a period of time, it will end abnormally.
}, loadConfig().restartTime)

}