-
Notifications
You must be signed in to change notification settings - Fork 9
/
exercise-02.ts
150 lines (136 loc) · 4.19 KB
/
exercise-02.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import { Metrics, Resource } from "@effect/opentelemetry"
import { NodeContext, NodeHttpServer } from "@effect/platform-node"
import * as Middleware from "@effect/platform/Http/Middleware"
import * as ServerRequest from "@effect/platform/Http/ServerRequest"
import * as Http from "@effect/platform/HttpServer"
import { PrometheusExporter, PrometheusSerializer } from "@opentelemetry/exporter-prometheus"
import {
Console,
Context,
Effect,
flow,
Layer,
Metric,
MetricLabel,
Runtime,
RuntimeFlags,
Schedule
} from "effect"
import { createServer } from "node:http"
const trackSuccessfulRequests = (
method: string,
route: string
): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =>
Metric.counter("http_request_successes", {
description: "Track the count of successful HTTP requests by method and route",
incremental: true
}).pipe(
Metric.withConstantInput(1),
Metric.taggedWithLabels([
MetricLabel.make("method", method),
MetricLabel.make("route", route)
])
)
const trackMethodFrequency = (
method: string,
route: string
): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =>
Metric.frequency(
"http_method",
"Track the frequency of all HTTP requests by method and route"
).pipe(
Metric.tagged("route", route),
Metric.trackAll(method)
)
const trackRequestLatency = Metric.timerWithBoundaries(
"request_latency",
[50, 75, 100, 150, 200, 250, 300, 350, 400],
"Track request latency"
)
const metricMiddleware = Middleware.make((httpApp) =>
ServerRequest.ServerRequest.pipe(Effect.flatMap((request) =>
httpApp.pipe(
trackSuccessfulRequests(request.method, request.url),
trackMethodFrequency(request.method, request.url),
Metric.trackDuration(trackRequestLatency)
)
))
)
const router = Http.router.empty.pipe(
Http.router.get(
"/",
Effect.flatMap(
Http.request.ServerRequest,
(req) => Effect.sleep("200 millis").pipe(Effect.as(Http.response.text(req.url)))
)
),
Http.router.get(
"/healthz",
Http.response.text("ok").pipe(
Http.middleware.withLoggerDisabled
)
),
Http.router.get(
"/metrics",
Effect.gen(function*(_) {
const prometheusReporter = yield* _(PrometheusMetricReporter)
const report = yield* _(prometheusReporter.report)
return Http.response.text(report)
})
)
)
class PrometheusMetricReporter extends Context.Tag("PrometheusMetricReporter")<
PrometheusMetricReporter,
{
readonly report: Effect.Effect<string>
}
>() {
static readonly Live = Layer.scoped(
PrometheusMetricReporter,
Effect.gen(function*(_) {
const serializer = new PrometheusSerializer()
const producer = yield* _(Metrics.makeProducer)
const reader = yield* _(Metrics.registerProducer(producer, () => new PrometheusExporter()))
return {
report: Effect.promise(() => reader.collect()).pipe(
Effect.map(({ resourceMetrics }) => serializer.serialize(resourceMetrics))
)
}
})
)
}
class ConsoleMetricReporter extends Context.Tag("ConsoleReporter")<ConsoleMetricReporter, void>() {
static readonly Live = Layer.scopedDiscard(Effect.gen(function*(_) {
const prometheusReporter = yield* _(PrometheusMetricReporter)
yield* _(
prometheusReporter.report,
Effect.flatMap((report) => Console.log(report)),
Effect.repeat({ schedule: Schedule.spaced("5 seconds") }),
Effect.fork
)
}))
}
const ServerLive = NodeHttpServer.server.layer(() => createServer(), { port: 8888 })
const MetricReportingLive = ConsoleMetricReporter.Live.pipe(
Layer.provideMerge(PrometheusMetricReporter.Live),
Layer.provide(Resource.layer({
serviceName: "advanced-effect-workshop",
serviceVersion: "1.0.0"
}))
)
const middleware = flow(Http.middleware.logger, metricMiddleware)
const HttpLive = router.pipe(
Http.server.serve(middleware),
Http.server.withLogAddress,
Layer.provide(ServerLive),
Layer.provide(NodeContext.layer)
)
const MainLive = HttpLive.pipe(
Layer.provide(MetricReportingLive)
)
const runtime = Runtime.defaultRuntime.pipe(
Runtime.disableRuntimeFlag(RuntimeFlags.RuntimeMetrics)
)
Layer.launch(MainLive).pipe(
Runtime.runFork(runtime)
)