summaryrefslogtreecommitdiff
path: root/u/server/activity/health.ts
blob: 93964906c683bef6a634f50a3550a01d15f54960 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {
    type IActivity,
    type IEither,
    IMetric,
    type ITraceable,
    JsonResponse,
    LogLevel,
    type Mapper,
    Metric,
    type PenguenoRequest,
    type ServerTrace,
    TraceUtil,
} from '@emprespresso/pengueno';

export enum HealthCheckInput {
    CHECK,
}
export enum HealthCheckOutput {
    YAASSSLAYQUEEN,
}

export interface IHealthCheckActivity {
    checkHealth: IActivity;
}

const healthCheckMetric = Metric.fromName('Health').asResult();
export interface HealthChecker
    extends Mapper<ITraceable<HealthCheckInput, ServerTrace>, Promise<IEither<Error, HealthCheckOutput>>> {}
export class HealthCheckActivityImpl implements IHealthCheckActivity {
    constructor(private readonly check: HealthChecker) {}

    public checkHealth(req: ITraceable<PenguenoRequest, ServerTrace>) {
        return req
            .flatMap(TraceUtil.withFunctionTrace(this.checkHealth))
            .flatMap(TraceUtil.withMetricTrace(healthCheckMetric))
            .flatMap((r) => r.move(HealthCheckInput.CHECK).map((input) => this.check(input)))
            .peek(TraceUtil.promiseify(TraceUtil.traceResultingEither(healthCheckMetric)))
            .map(
                TraceUtil.promiseify((h) => {
                    const { status, message } = h.get().fold(
                        () => ({ status: 500, message: 'err' }),
                        () => ({ status: 200, message: 'ok' }),
                    );
                    return new JsonResponse(req, message, { status });
                }),
            )
            .get();
    }
}