|
| 1 | +import * as NodeSdk from "@effect/opentelemetry/NodeSdk" |
| 2 | +import { PrometheusExporter } from "@opentelemetry/exporter-prometheus" |
| 3 | +import { Config, Effect, Layer, Metric, Schedule } from "effect" |
| 4 | + |
| 5 | +// App metrics |
| 6 | +export const messagesProcessed = Metric.counter("messages_processed_total", { |
| 7 | + description: "Total websocket messages processed", |
| 8 | +}) |
| 9 | + |
| 10 | +export const cursorGauge = Metric.gauge("cursor_value", { |
| 11 | + description: "Current cursor position", |
| 12 | +}) |
| 13 | + |
| 14 | +export const listOperations = Metric.counter("list_operations_total", { |
| 15 | + description: "List add/remove operations", |
| 16 | +}) |
| 17 | + |
| 18 | +export const wsReconnects = Metric.counter("websocket_reconnects_total", { |
| 19 | + description: "WebSocket reconnection attempts", |
| 20 | +}) |
| 21 | + |
| 22 | +// Memory metrics |
| 23 | +export const heapUsed = Metric.gauge("nodejs_heap_used_bytes", { |
| 24 | + description: "Node.js heap used in bytes", |
| 25 | +}) |
| 26 | + |
| 27 | +export const rss = Metric.gauge("nodejs_rss_bytes", { |
| 28 | + description: "Node.js resident set size in bytes", |
| 29 | +}) |
| 30 | + |
| 31 | +// Record memory metrics every 30 seconds |
| 32 | +export const recordMemoryMetrics = Effect.gen(function* () { |
| 33 | + const mem = process.memoryUsage() |
| 34 | + yield* Metric.set(heapUsed, mem.heapUsed) |
| 35 | + yield* Metric.set(rss, mem.rss) |
| 36 | + yield* Effect.log( |
| 37 | + `Memory: heap=${Math.round(mem.heapUsed / 1024 / 1024)}MB, rss=${Math.round(mem.rss / 1024 / 1024)}MB` |
| 38 | + ) |
| 39 | +}).pipe(Effect.repeat(Schedule.spaced("30 seconds")), Effect.forkScoped) |
| 40 | + |
| 41 | +// Prometheus exporter config |
| 42 | +const MetricsConfig = Config.integer("METRICS_PORT").pipe( |
| 43 | + Config.withDefault(9464) |
| 44 | +) |
| 45 | + |
| 46 | +// NodeSdk layer with Prometheus exporter |
| 47 | +export const MetricsLive = Layer.unwrapEffect( |
| 48 | + Effect.gen(function* () { |
| 49 | + const port = yield* MetricsConfig |
| 50 | + yield* Effect.log(`Starting Prometheus metrics exporter on port ${port}`) |
| 51 | + |
| 52 | + return NodeSdk.layer(() => ({ |
| 53 | + resource: { |
| 54 | + serviceName: "bsky-label-watcher", |
| 55 | + serviceVersion: "1.0.0", |
| 56 | + }, |
| 57 | + metricReader: new PrometheusExporter({ port }), |
| 58 | + })) |
| 59 | + }) |
| 60 | +) |
| 61 | + |
| 62 | +// Layer that starts memory recording |
| 63 | +export const MemoryMetricsLive = Layer.scopedDiscard(recordMemoryMetrics) |
0 commit comments