UNPKG

wechaty-puppet-service

Version:
55 lines 2.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.healthImplementation = void 0; /* eslint-disable sort-keys */ const wechaty_grpc_1 = require("wechaty-grpc"); const wechaty_puppet_1 = require("wechaty-puppet"); const HEARTBEAT_TIMEOUT_SECONDS = 60; function healthImplementation(puppet) { let lastHeartbeatTimestamp = -1; const healthCheckResponse = () => { const response = new wechaty_grpc_1.google.HealthCheckResponse(); if (lastHeartbeatTimestamp < 0 || lastHeartbeatTimestamp > Date.now()) { response.setStatus(wechaty_grpc_1.google.HealthCheckResponse.ServingStatus.SERVICE_UNKNOWN); } else if (Date.now() - lastHeartbeatTimestamp < HEARTBEAT_TIMEOUT_SECONDS * 1000) { response.setStatus(wechaty_grpc_1.google.HealthCheckResponse.ServingStatus.SERVING); } else { response.setStatus(wechaty_grpc_1.google.HealthCheckResponse.ServingStatus.NOT_SERVING); } return response; }; puppet.on('heartbeat', () => { lastHeartbeatTimestamp = Date.now(); }); const healthServerImpl = { check: async (call, callback) => { wechaty_puppet_1.log.verbose('HealthServiceImpl', 'check()'); const service = call.request.getService(); wechaty_puppet_1.log.verbose('HealServiceImpl', 'check() service="%s"', service); const response = healthCheckResponse(); callback(null, response); }, watch: async (call) => { wechaty_puppet_1.log.verbose('HealthServiceImpl', 'watch()'); const firstResponse = healthCheckResponse(); let currentStatus = firstResponse.getStatus(); call.write(firstResponse); const timer = setInterval(() => { const nextResponse = healthCheckResponse(); if (nextResponse.getStatus() !== currentStatus) { currentStatus = nextResponse.getStatus(); call.write(nextResponse); } }, 5 * 1000); const clear = () => clearInterval(timer); call.on('end', clear); call.on('error', clear); call.on('close', clear); }, }; return healthServerImpl; } exports.healthImplementation = healthImplementation; //# sourceMappingURL=health-implementation.js.map