Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function onSignal() {
console.log('server is starting cleanup');
return Promise.all([
// add any clean-up logic
]);
}
function onShutdown () {
console.log('cleanup finished, server is shutting down');
}
function onHealthCheck() {
return Promise.resolve();
}
createTerminus(server, {
signals: ['SIGHUP','SIGINT','SIGTERM'],
healthChecks: {
'/health': onHealthCheck,
'/': onHealthCheck
},
onSignal,
onShutdown
});
server.listen(port, () => {
console.log(`Listening on port ${port}`);
});
module.exports = server;
private generateHttpError(key: string, error: AxiosError) {
// TODO: Check for `error.isAxiosError`
// Upgrade axios for that as soon ^0.19.0 is released
if (error) {
const response: { [key: string]: any } = {
message: error.message,
};
if (error.response) {
response.statusCode = error.response.status;
response.statusText = error.response.statusText;
}
throw new HealthCheckError(
error.message,
this.getStatus(key, false, response),
);
}
}
import api from "./api";
import config from "./config.json";
import tracer from "./middleware/tracer";
import terminusOptions from "./utils/health";
import envVariables from "./envVariables";
import "./kafka/consumer";
var swaggerUi = require("swagger-ui-express"),
swaggerDocument = require("./swagger.json");
const { createTerminus } = require("@godaddy/terminus");
let app = express();
app.server = http.createServer(app);
// Enable health checks and kubernetes shutdown hooks
createTerminus(app.server, terminusOptions);
// logger
app.use(morgan("dev"));
// 3rd party middleware
app.use(
cors({
exposedHeaders: config.corsHeaders
})
);
app.use(
bodyParser.json({
limit: config.bodyLimit
})
);
'use strict'
const http = require('http')
const { createTerminus } = require('@godaddy/terminus')
const app = require('./lib/app')
const port = app.get('port')
const logger = app.get('logger')
const healthCheck = app.get('healthCheck')
const periodSeconds = app.get('periodSeconds')
const io = app.get('io')()
// create server
const server = http.createServer(app)
io.attach(server)
createTerminus(server, {
healthChecks: {
'/healthz': healthCheck
},
beforeShutdown,
onSignal,
onShutdown,
logger: (...args) => logger.error(...args)
})
server.listen(port, () => {
logger.info(`Server listening on port ${port}`)
})
async function onSignal () {
logger.debug('Server is starting cleanup')
try {
await new Promise(resolve => io.close(resolve))
it('should log an error to the custom logger if an error has been thrown', async () => {
const mockLogger = (message: string, error: HealthCheckError) => {
expect(message).toBe('healthcheck failed');
expect(error.causes).toEqual({ test: 'test' });
};
const healthError = new HealthCheckError('test', { test: 'test' });
const testHealthInidcator = async () => {
throw healthError;
};
const endpoints: TerminusEndpoint[] = [
{
url: '/health',
healthIndicators: [testHealthInidcator],
},
];
[app, port] = await bootstrapModule({
useFactory: (): TerminusModuleOptions => ({
endpoints,
logger: mockLogger,
}),
timeout: 1000,
healthServiceName: 'Health',
};
const settings = { ...defaultOptions, ...options };
const client = this.createClient(settings);
let healthService: GRPCHealthService;
try {
healthService = client.getService(
settings.healthServiceName,
);
} catch (err) {
if (err instanceof TypeError) throw err;
throw new HealthCheckError(
err.message,
this.getStatus(key, false, { message: err.message }),
);
}
let response: HealthCheckResponse;
try {
response = await promiseTimeout(
settings.timeout,
settings.healthServiceCheck(healthService, service),
);
} catch (err) {
if (err instanceof PromiseTimeoutError) {
throw new TimeoutError(
settings.timeout,
async isHealthy(key: string): Promise {
const isHealthy = MQProvider.enabled;
const result = this.getStatus(key, isHealthy, {
enabled: MQProvider.enabled,
});
if (isHealthy) {
return result;
}
throw new HealthCheckError('MQCheck failed', result);
}
}
async isHealthy(key: string): Promise {
const redisClientObject = RedisProvider.instance.getRedisClient();
const isHealthy = !redisClientObject.isEnabled || redisClientObject.isHealthy;
const result = this.getStatus(key, isHealthy, {
enabled: redisClientObject.isEnabled,
isHealthy: redisClientObject.isHealthy,
config: redisClientObject.redisOptions,
});
if (isHealthy) {
return result;
}
throw new HealthCheckError('RedisCheck failed', result);
}
}
private generateError(key: string, error: Error, timeout: number) {
if (!error) {
return;
}
if (error instanceof PromiseTimeoutError) {
throw new TimeoutError(
timeout,
this.getStatus(key, false, {
message: `timeout of ${timeout}ms exceeded`,
}),
);
}
throw new HealthCheckError(
error.message,
this.getStatus(key, false, {
message: error.message,
}),
);
}
return async () => {
const { results, errors } = await this.executeHealthIndicators(
endpoint.healthIndicators,
);
const info = (results || [])
.concat(errors || [])
.reduce(
(previous: Object, current: Object) =>
Object.assign(previous, current),
{},
);
if (errors.length) {
throw new HealthCheckError('Healthcheck failed', info);
} else {
return info;
}
};
}