|
| 1 | +import { |
| 2 | + ClientConnected, |
| 3 | + ClientDisconnected, |
| 4 | + Opcode, |
| 5 | + PacketReceived, |
| 6 | + PacketSent, |
| 7 | + RiftCloseCode, |
| 8 | + type RiftServer, |
| 9 | + Tick, |
| 10 | + TickCompleted, |
| 11 | +} from "@rift/core"; |
| 12 | +import { |
| 13 | + collectDefaultMetrics, |
| 14 | + exponentialBuckets, |
| 15 | + MetricsCounter, |
| 16 | + MetricsGague, |
| 17 | + MetricsHistogram, |
| 18 | + metricsRegister, |
| 19 | +} from "@mp/telemetry/prom"; |
| 20 | + |
| 21 | +export interface AttachedRiftMetrics { |
| 22 | + readonly renderText: () => Promise<string>; |
| 23 | + readonly dispose: () => void; |
| 24 | +} |
| 25 | + |
| 26 | +// Attaches a passive observer to a RiftServer that derives prom-client metrics |
| 27 | +// purely from the server's existing event bus and getters. No coupling back |
| 28 | +// into rift internals — if the observable surface ever grows, this is the |
| 29 | +// only place that needs to learn about it. |
| 30 | +export function attachRiftMetrics(server: RiftServer): AttachedRiftMetrics { |
| 31 | + collectDefaultMetrics({ register: metricsRegister }); |
| 32 | + |
| 33 | + const ticksTotal = new MetricsCounter({ |
| 34 | + name: "rift_ticks_total", |
| 35 | + help: "Cumulative count of server ticks observed.", |
| 36 | + }); |
| 37 | + |
| 38 | + // Histogram of wall-clock spacing between consecutive ticks. A healthy |
| 39 | + // tick loop produces values near 1/tickRateHz; sustained higher values |
| 40 | + // mean the loop is overrunning its budget. |
| 41 | + const tickIntervalSeconds = new MetricsHistogram({ |
| 42 | + name: "rift_tick_interval_seconds", |
| 43 | + help: "Wall-clock seconds between consecutive ticks.", |
| 44 | + buckets: exponentialBuckets(0.001, 2, 12), |
| 45 | + }); |
| 46 | + |
| 47 | + // Histogram of how long the tick body itself spent (event drain + delta |
| 48 | + // build + per-client flush). Headroom = tick_interval - tick_duration. |
| 49 | + const tickDurationSeconds = new MetricsHistogram({ |
| 50 | + name: "rift_tick_duration_seconds", |
| 51 | + help: "Wall-clock seconds spent inside one tick.", |
| 52 | + buckets: exponentialBuckets(0.0005, 2, 12), |
| 53 | + }); |
| 54 | + |
| 55 | + const clientsConnected = new MetricsGague({ |
| 56 | + name: "rift_clients_connected", |
| 57 | + help: "Number of clients currently tracked by the server (sampled per tick).", |
| 58 | + }); |
| 59 | + |
| 60 | + const entities = new MetricsGague({ |
| 61 | + name: "rift_entities", |
| 62 | + help: "Number of entities currently in the world (sampled per tick).", |
| 63 | + }); |
| 64 | + |
| 65 | + const connectionsOpenedTotal = new MetricsCounter({ |
| 66 | + name: "rift_client_connections_opened_total", |
| 67 | + help: "Cumulative count of clients that completed the handshake.", |
| 68 | + }); |
| 69 | + |
| 70 | + const connectionsClosedTotal = new MetricsCounter({ |
| 71 | + name: "rift_client_connections_closed_total", |
| 72 | + help: "Cumulative count of post-handshake disconnections, labeled by rift close code.", |
| 73 | + labelNames: ["code"] as const, |
| 74 | + }); |
| 75 | + |
| 76 | + // event_index is the schema-assigned position. Stable for the lifetime of |
| 77 | + // a schema version; if the schema changes order, series rotate. A future |
| 78 | + // pass can layer human names on top via a Map<RiftType, string>. |
| 79 | + const eventsSentTotal = new MetricsCounter({ |
| 80 | + name: "rift_events_sent_total", |
| 81 | + help: "Cumulative count of events dispatched toward connected clients.", |
| 82 | + labelNames: ["event_index"] as const, |
| 83 | + }); |
| 84 | + |
| 85 | + const eventsReceivedTotal = new MetricsCounter({ |
| 86 | + name: "rift_events_received_total", |
| 87 | + help: "Cumulative count of events received from connected clients.", |
| 88 | + labelNames: ["event_index"] as const, |
| 89 | + }); |
| 90 | + |
| 91 | + const bytesSentTotal = new MetricsCounter({ |
| 92 | + name: "rift_bytes_sent_total", |
| 93 | + help: "Total bytes dispatched to clients (byteSize * recipientCount), labeled by opcode.", |
| 94 | + labelNames: ["opcode"] as const, |
| 95 | + }); |
| 96 | + |
| 97 | + const bytesReceivedTotal = new MetricsCounter({ |
| 98 | + name: "rift_bytes_received_total", |
| 99 | + help: "Total bytes received from clients, labeled by opcode.", |
| 100 | + labelNames: ["opcode"] as const, |
| 101 | + }); |
| 102 | + |
| 103 | + const packetSizeBytes = new MetricsHistogram({ |
| 104 | + name: "rift_packet_size_bytes", |
| 105 | + help: "Size distribution of outbound packets (one observation per logical send, regardless of recipientCount).", |
| 106 | + buckets: exponentialBuckets(32, 2, 14), |
| 107 | + labelNames: ["opcode"] as const, |
| 108 | + }); |
| 109 | + |
| 110 | + let lastTickAt = 0; |
| 111 | + |
| 112 | + const unsubs: Array<() => void> = [ |
| 113 | + server.on(Tick, () => { |
| 114 | + ticksTotal.inc(); |
| 115 | + const now = performance.now(); |
| 116 | + if (lastTickAt !== 0) { |
| 117 | + tickIntervalSeconds.observe((now - lastTickAt) / 1000); |
| 118 | + } |
| 119 | + lastTickAt = now; |
| 120 | + clientsConnected.set(server.getClientIds().length); |
| 121 | + entities.set(server.world.entities().size); |
| 122 | + }), |
| 123 | + server.on(TickCompleted, (ev) => { |
| 124 | + tickDurationSeconds.observe(ev.data.durationUs / 1_000_000); |
| 125 | + }), |
| 126 | + server.on(ClientConnected, () => { |
| 127 | + connectionsOpenedTotal.inc(); |
| 128 | + }), |
| 129 | + server.on(ClientDisconnected, (ev) => { |
| 130 | + connectionsClosedTotal.inc({ code: closeCodeLabel(ev.data.code) }); |
| 131 | + }), |
| 132 | + server.on(PacketSent, (ev) => { |
| 133 | + const opcode = opcodeLabel(ev.data.opcode); |
| 134 | + bytesSentTotal.inc( |
| 135 | + { opcode }, |
| 136 | + ev.data.byteSize * ev.data.recipientCount, |
| 137 | + ); |
| 138 | + packetSizeBytes.observe({ opcode }, ev.data.byteSize); |
| 139 | + }), |
| 140 | + server.on(PacketReceived, (ev) => { |
| 141 | + bytesReceivedTotal.inc( |
| 142 | + { opcode: opcodeLabel(ev.data.opcode) }, |
| 143 | + ev.data.byteSize, |
| 144 | + ); |
| 145 | + }), |
| 146 | + server.onAny((ev) => { |
| 147 | + // source.type === "wire" means the event came in from a client; |
| 148 | + // target.type === "wire" means it's being dispatched out to clients. |
| 149 | + // Lifecycle events (Tick/Packet*/ClientConnected/ClientDisconnected) |
| 150 | + // are local on both ends and are accounted for above instead. |
| 151 | + if (ev.source.type === "wire") { |
| 152 | + eventsReceivedTotal.inc({ |
| 153 | + event_index: eventIndexLabel(server, ev.type), |
| 154 | + }); |
| 155 | + } else if (ev.target.type === "wire") { |
| 156 | + eventsSentTotal.inc({ |
| 157 | + event_index: eventIndexLabel(server, ev.type), |
| 158 | + }); |
| 159 | + } |
| 160 | + }), |
| 161 | + ]; |
| 162 | + |
| 163 | + return { |
| 164 | + renderText: () => metricsRegister.metrics(), |
| 165 | + dispose: () => { |
| 166 | + for (const u of unsubs) { |
| 167 | + u(); |
| 168 | + } |
| 169 | + }, |
| 170 | + }; |
| 171 | +} |
| 172 | + |
| 173 | +function eventIndexLabel( |
| 174 | + server: RiftServer, |
| 175 | + ty: Parameters<RiftServer["schema"]["eventIndexOf"]>[0], |
| 176 | +): string { |
| 177 | + const idx = server.schema.eventIndexOf(ty); |
| 178 | + return idx === undefined ? "unknown" : String(idx); |
| 179 | +} |
| 180 | + |
| 181 | +function opcodeLabel(opcode: Opcode): string { |
| 182 | + switch (opcode) { |
| 183 | + case Opcode.Hello: |
| 184 | + return "hello"; |
| 185 | + case Opcode.Accept: |
| 186 | + return "accept"; |
| 187 | + case Opcode.Delta: |
| 188 | + return "delta"; |
| 189 | + case Opcode.EventFromClient: |
| 190 | + return "event_from_client"; |
| 191 | + case Opcode.EventToClient: |
| 192 | + return "event_to_client"; |
| 193 | + default: |
| 194 | + return String(opcode); |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +function closeCodeLabel(code: RiftCloseCode): string { |
| 199 | + switch (code) { |
| 200 | + case RiftCloseCode.Normal: |
| 201 | + return "normal"; |
| 202 | + case RiftCloseCode.SchemaMismatch: |
| 203 | + return "schema_mismatch"; |
| 204 | + case RiftCloseCode.ProtocolError: |
| 205 | + return "protocol_error"; |
| 206 | + case RiftCloseCode.HandshakeTimeout: |
| 207 | + return "handshake_timeout"; |
| 208 | + case RiftCloseCode.ServerShutdown: |
| 209 | + return "server_shutdown"; |
| 210 | + default: |
| 211 | + return String(code); |
| 212 | + } |
| 213 | +} |
0 commit comments