UNPKG

wechaty-puppet

Version:

Abstract Puppet for Wechaty

70 lines 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WatchdogAgent = void 0; const watchdog_1 = require("watchdog"); const config_js_1 = require("../config.js"); const DEFAULT_WATCHDOG_TIMEOUT_SECONDS = 60; class WatchdogAgent { puppet; watchdog; cleanCallbackList; constructor(puppet) { this.puppet = puppet; config_js_1.log.verbose('PuppetWatchdogAgent', 'constructor(%s)', puppet.id); this.cleanCallbackList = []; /** * 1. Setup Watchdog * puppet implementation class only need to do one thing: * feed the watchdog by `this.emit('heartbeat', ...)` */ const timeoutSeconds = puppet.options.timeoutSeconds || DEFAULT_WATCHDOG_TIMEOUT_SECONDS; config_js_1.log.verbose('PuppetWatchdogAgent', 'constructor() timeout %d seconds', timeoutSeconds); this.watchdog = new watchdog_1.Watchdog(1000 * timeoutSeconds, 'Puppet'); // /** // * 2. Setup `reset` Event via a 1 second Throttle Queue: // */ // this.resetThrottleQueue = new ThrottleQueue<string>(1000) // this.resetThrottleQueue.subscribe(reason => { // log.silly('PuppetWatchdogAgent', 'constructor() resetThrottleQueue.subscribe() reason: "%s"', reason) // puppet.reset(reason) // }) } start() { /** * puppet event `heartbeat` to feed() watchdog */ const feed = (food) => { this.watchdog.feed(food); }; this.puppet.on('heartbeat', e => feed({ data: e.data })); config_js_1.log.verbose('PuppetWatchdogAgent', 'start() "heartbeat" event listener added'); this.cleanCallbackList.push(() => { this.puppet.off('heartbeat', e => feed({ data: e.data })); config_js_1.log.verbose('PuppetWatchdogAgent', 'start() "heartbeat" event listener removed'); }); /** * watchdog event `reset` to reset() puppet */ const reset = (lastFood) => { config_js_1.log.warn('PuppetWatchdogAgent', 'start() reset() reason: %s', JSON.stringify(lastFood)); this.puppet.emit('error', new Error(`WatchdogAgent reset: lastFood: "${JSON.stringify(lastFood)}"`)); this.puppet.wrapAsync(this.puppet.reset()); }; this.watchdog.on('reset', reset); config_js_1.log.verbose('PuppetWatchdogAgent', 'start() "reset" event listener added'); this.cleanCallbackList.push(() => { this.puppet.off('reset', e => reset({ data: e.data })); config_js_1.log.verbose('PuppetWatchdogAgent', 'start() "reset" event listener removed'); }); // this.puppet.on('reset', this.throttleReset) } stop() { while (this.cleanCallbackList.length) { const callback = this.cleanCallbackList.shift(); if (callback) { callback(); } } this.watchdog.sleep(); } } exports.WatchdogAgent = WatchdogAgent; //# sourceMappingURL=watchdog-agent.js.map