summaryrefslogtreecommitdiff
path: root/u/server/activity/health.ts
blob: b3ae559539ad36547fa1e3ebcd07c479368dae2a (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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: IMetric = Metric.fromName('Health');
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
            .bimap(TraceUtil.withFunctionTrace(this.checkHealth))
            .bimap(TraceUtil.withMetricTrace(healthCheckMetric))
            .flatMap((r) => r.move(HealthCheckInput.CHECK).map((input) => this.check(input)))
            .peek(
                TraceUtil.promiseify((h) =>
                    h.get().fold(({ isLeft, value }) => {
                        if (!isLeft) {
                            h.trace.trace(healthCheckMetric.success);
                            return;
                        }
                        h.trace.trace(healthCheckMetric.failure);
                        h.trace.addTrace(LogLevel.ERROR).trace(value);
                    }),
                ),
            )
            .map(
                TraceUtil.promiseify((h) =>
                    h
                        .get()
                        .mapBoth(
                            () => 'oh no, i need to eat more vegetables (。•́︿•̀。)...',
                            () => 'think im healthy!! (✿˘◡˘) ready to do work~',
                        )
                        .fold(
                            ({ isLeft, value: message }) =>
                                new JsonResponse(req, message, {
                                    status: isLeft ? 500 : 200,
                                }),
                        ),
                ),
            )
            .get();
    }
}