Skip to content

feat: infer health check result #2626

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

Open
wants to merge 1 commit into
base: master
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions lib/health-check/health-check-executor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from './health-check-result.interface';
import { type HealthCheckError } from '../health-check/health-check.error';
import {
type InferHealthIndicatorResults,
type HealthIndicatorFunction,
type HealthIndicatorResult,
} from '../health-indicator';
Expand Down Expand Up @@ -37,13 +38,15 @@ export class HealthCheckExecutor implements BeforeApplicationShutdown {
* @returns the result of given health indicators
* @param healthIndicators The health indicators which should get executed
*/
async execute(
healthIndicators: HealthIndicatorFunction[],
): Promise<HealthCheckResult> {
async execute<const TFns extends HealthIndicatorFunction[]>(
healthIndicators: TFns,
) {
const { results, errors } =
await this.executeHealthIndicators(healthIndicators);

return this.getResult(results, errors);
return this.getResult(results, errors) as HealthCheckResult<
InferHealthIndicatorResults<TFns>
>;
}

/**
Expand Down
18 changes: 13 additions & 5 deletions lib/health-check/health-check-result.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ export type HealthCheckStatus = 'error' | 'ok' | 'shutting_down';
* The result of a health check
* @publicApi
*/
export interface HealthCheckResult {
export type HealthCheckResult<
TDetails extends HealthIndicatorResult = HealthIndicatorResult,
TInfo extends Partial<HealthIndicatorResult> | undefined =
| Partial<TDetails>
| undefined,
TError extends Partial<HealthIndicatorResult> | undefined =
| Partial<TDetails>
| undefined,
> = {
/**
* The overall status of the Health Check
*/
Expand All @@ -18,14 +26,14 @@ export interface HealthCheckResult {
* The info object contains information of each health indicator
* which is of status "up"
*/
info?: HealthIndicatorResult;
info?: TInfo;
/**
* The error object contains information of each health indicator
* which is of status "down"
*/
error?: HealthIndicatorResult;
error?: TError;
/**
* The details object contains information of every health indicator.
*/
details: HealthIndicatorResult;
}
details: TDetails;
};
39 changes: 24 additions & 15 deletions lib/health-check/health-check.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import {
Inject,
ConsoleLogger,
LoggerService,
InternalServerErrorException,
} from '@nestjs/common';
import { ErrorLogger } from './error-logger/error-logger.interface';
import { ERROR_LOGGER } from './error-logger/error-logger.provider';
import { HealthCheckExecutor } from './health-check-executor.service';
import { type HealthCheckResult } from './health-check-result.interface';
import { type HealthIndicatorFunction } from '../health-indicator';
import { TERMINUS_LOGGER } from './logger/logger.provider';

Expand Down Expand Up @@ -43,22 +43,31 @@ export class HealthCheckService {
* ```
* @param healthIndicators The health indicators which should be checked
*/
async check(
healthIndicators: HealthIndicatorFunction[],
): Promise<HealthCheckResult> {
async check<const TFns extends HealthIndicatorFunction[]>(
healthIndicators: TFns,
) {
const result = await this.healthCheckExecutor.execute(healthIndicators);
if (result.status === 'ok') {
return result;
}

if (result.status === 'error') {
const msg = this.errorLogger.getErrorMessage(
'Health Check has failed!',
result.details,
);
this.logger.error(msg);
}
switch (result.status) {
case 'ok':
return result;

throw new ServiceUnavailableException(result);
case 'error':
const msg = this.errorLogger.getErrorMessage(
'Health Check has failed!',
result.details,
);
this.logger.error(msg);
throw new ServiceUnavailableException(result);

case 'shutting_down':
throw new ServiceUnavailableException(result);

default:
// Ensure that we have exhaustively checked all cases
// eslint-disable-next-line unused-imports/no-unused-vars
const exhaustiveCheck: never = result.status;
throw new InternalServerErrorException();
}
}
}
23 changes: 23 additions & 0 deletions lib/health-indicator/health-indicator-result.interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { type HealthIndicatorFunction } from './health-indicator';

/**
* @publicApi
*/
Expand All @@ -12,3 +14,24 @@ export type HealthIndicatorResult<
Status extends HealthIndicatorStatus = HealthIndicatorStatus,
OptionalData extends Record<string, any> = Record<string, any>,
> = Record<Key, { status: Status } & OptionalData>;

/**
* @internal
*/
export type InferHealthIndicatorResult<
Fn extends HealthIndicatorFunction = HealthIndicatorFunction,
> = Awaited<ReturnType<Fn>>;

/**
* @internal
*/
export type InferHealthIndicatorResults<
Fns extends readonly HealthIndicatorFunction[] = HealthIndicatorFunction[],
R extends readonly any[] = [],
> = Fns extends readonly [
infer Fn extends HealthIndicatorFunction,
...infer Rest extends readonly HealthIndicatorFunction[],
]
? InferHealthIndicatorResults<Rest, [...R, Fn]> &
InferHealthIndicatorResult<Fn>
: HealthIndicatorResult;
6 changes: 3 additions & 3 deletions lib/health-indicator/health-indicator.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ export class HealthIndicatorSession<Key extends Readonly<string> = string> {
*/
down<T extends AdditionalData>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down', T>;
): HealthIndicatorResult<Key, 'down', T>;
down<T extends string>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down', { message: T }>;
): HealthIndicatorResult<Key, 'down', { message: T }>;
down<T extends AdditionalData | string>(
data?: T,
): HealthIndicatorResult<typeof this.key, 'down'> {
): HealthIndicatorResult<Key, 'down'> {
let additionalData: AdditionalData = {};

if (typeof data === 'string') {
Expand Down