grpc-ts-health-check
Version:
An implementation of gRPC health checks, written in typescript.
65 lines • 2.58 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GrpcHealthCheck = void 0;
const grpc_boom_1 = __importDefault(require("grpc-boom"));
const HealthCheckResponse_1 = require("./proto/grpc/health/v1/HealthCheckResponse");
class GrpcHealthCheck {
statusMap;
watchStatusMap = {};
watchErrorMap = {};
constructor(statusMap) {
this.statusMap = statusMap;
}
setStatus(service, status) {
this.statusMap[service] = status;
}
check(call, callback) {
const service = call.request.service;
const status = this.statusMap[service];
if (status) {
callback(undefined, { status });
}
else {
callback(grpc_boom_1.default.notFound(`Unknown service: ${service}`), undefined);
}
}
watch(call) {
const service = call.request.service;
// tslint:disable no-console
const interval = setInterval(() => {
// Updated status is used for getting service status updates.
let updatedStatus = HealthCheckResponse_1._grpc_health_v1_HealthCheckResponse_ServingStatus.SERVING;
if (!this.statusMap[service]) {
// Set the initial status
updatedStatus = HealthCheckResponse_1._grpc_health_v1_HealthCheckResponse_ServingStatus.SERVICE_UNKNOWN;
this.setStatus(service, updatedStatus);
call.write({ status: updatedStatus });
}
// Add to the watch status map
this.watchStatusMap[service] = updatedStatus;
if (this.watchErrorMap[service]) {
clearInterval(interval);
// Terminate the stream
call.end(this.watchErrorMap[service]);
}
else {
const lastStatus = this.statusMap[service] || -1;
if (lastStatus !== updatedStatus) {
// Status has changed
this.setStatus(service, updatedStatus);
call.write({ status: updatedStatus }, (error) => {
if (error) {
// Terminate stream on next tick
this.watchErrorMap[service] = error;
}
});
}
}
}, 1000);
}
}
exports.GrpcHealthCheck = GrpcHealthCheck;
//# sourceMappingURL=index.js.map