summaryrefslogtreecommitdiff
path: root/u/server/activity/health.ts
blob: 83be399940901cb33fa6f7062e375c8f4e39faaf (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
68
69
import {
  type IActivity,
  type IEither,
  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");
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(this.check))
      .peek(
        TraceUtil.promiseify((h) =>
          h.get().fold((err) => {
            if (err) {
              h.trace.trace(healthCheckMetric.failure);
              h.trace.addTrace(LogLevel.ERROR).trace(`${err}`);
              return;
            }
            h.trace.trace(healthCheckMetric.success);
          }),
        ),
      )
      .map(
        TraceUtil.promiseify((h) =>
          h
            .get()
            .mapBoth(
              () => "oh no, i need to eat more vegetables (。•́︿•̀。)...",
              () => "think im healthy!! (✿˘◡˘) ready to do work~",
            )
            .fold(
              (errMsg, okMsg) =>
                new JsonResponse(req, errMsg ?? okMsg, {
                  status: errMsg ? 500 : 200,
                }),
            ),
        ),
      )
      .get();
  }
}