-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetricsExporter.cs
More file actions
426 lines (381 loc) · 16.7 KB
/
MetricsExporter.cs
File metadata and controls
426 lines (381 loc) · 16.7 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
#if Mono
using ScheduleOne.DevUtilities;
using ScheduleOne.Economy;
using ScheduleOne.Levelling;
using ScheduleOne.Money;
#else
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Levelling;
using Il2CppScheduleOne.Money;
#endif
namespace ScheduleObserved;
/// <summary>
/// Lightweight Prometheus metrics exporter built on a raw TcpListener.
///
/// Why not HttpListener? Schedule 1 runs under Proton/Wine, and Wine's
/// HttpListener pretends to be Windows's HTTP.SYS — it binds the socket but
/// frequently fails to route requests to GetContext(), leaving connections
/// hung. TcpListener is a straight BSD socket wrapper with no kernel driver
/// emulation, so it works cleanly under Wine.
///
/// Gauges are snapshotted on the main thread (OnUpdate, throttled) into a
/// volatile string. Each accepted TCP connection reads the request line,
/// drains headers, and writes back the snapshot. No concurrency issues —
/// reads are of an immutable string reference.
/// </summary>
internal static class MetricsExporter
{
private static TcpListener? _listener;
private static Thread? _acceptThread;
private static volatile string _body = "";
private static DateTime _lastRefresh = DateTime.MinValue;
// Counters — only mutated from the Unity main thread (patch callbacks).
// Stored as double so money-valued counters (e.g. s1_customer_spend_*_total) can
// accumulate fractional amounts without precision loss.
private static readonly Dictionary<string, double> _counters = new();
/// <summary>Add to a counter with {save_slot, customer} labels.</summary>
public static void AddCustomerCounter(string metricName, string customer, double amount)
{
string slot = SavePersistence.CurrentSaveLabel;
string key = $"{metricName}{{save_slot=\"{Esc(slot)}\",customer=\"{Esc(customer)}\"}}";
_counters.TryGetValue(key, out double val);
_counters[key] = val + amount;
}
/// <summary>Add to a counter with {save_slot, product_id, drug_type} labels.</summary>
public static void AddProductCounter(string metricName, string productId, string drugType, double amount)
{
string slot = SavePersistence.CurrentSaveLabel;
string key = $"{metricName}{{save_slot=\"{Esc(slot)}\",product_id=\"{Esc(productId)}\",drug_type=\"{Esc(drugType)}\"}}";
_counters.TryGetValue(key, out double val);
_counters[key] = val + amount;
}
/// <summary>
/// Serialize all counters belonging to the given save slot to TSV.
/// Format: one line per counter, "key\tvalue\n". Empty if no entries.
/// </summary>
public static string SerializeCountersForSlot(string slot)
{
string marker = $"save_slot=\"{Esc(slot)}\",";
var sb = new StringBuilder();
foreach (var kv in _counters)
{
if (!kv.Key.Contains(marker)) continue;
sb.Append(kv.Key);
sb.Append('\t');
sb.Append(kv.Value.ToString("R", CultureInfo.InvariantCulture));
sb.Append('\n');
}
return sb.ToString();
}
/// <summary>
/// Replace all in-memory counters for the given save slot with the TSV contents.
/// Empty or null input clears the slot's counters (used on first-load of a save
/// that has no persisted state yet).
/// </summary>
public static void LoadCountersForSlot(string slot, string? tsv)
{
string marker = $"save_slot=\"{Esc(slot)}\",";
var toRemove = new List<string>();
foreach (var kv in _counters)
{
if (kv.Key.Contains(marker)) toRemove.Add(kv.Key);
}
foreach (var k in toRemove) _counters.Remove(k);
if (string.IsNullOrEmpty(tsv)) return;
foreach (string line in tsv!.Split('\n'))
{
if (string.IsNullOrWhiteSpace(line)) continue;
int tab = line.IndexOf('\t');
if (tab < 0) continue;
string key = line.Substring(0, tab);
string valStr = line.Substring(tab + 1).Trim();
if (double.TryParse(valStr, NumberStyles.Float, CultureInfo.InvariantCulture, out double val))
{
_counters[key] = val;
}
}
}
public static void Start(int port)
{
if (_listener != null) return;
try
{
// Bind on all interfaces so Docker containers (Prometheus) can reach us
// via host-gateway / host.docker.internal when running on a bridged network.
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
_acceptThread = new Thread(AcceptLoop) { IsBackground = true, Name = "ScheduleObservedMetricsAccept" };
_acceptThread.Start();
Plugin.Log.Msg($"Metrics server listening on 0.0.0.0:{port}/metrics");
}
catch (Exception ex)
{
Plugin.Log.Warning($"Failed to start metrics server on port {port}: {ex.Message}");
_listener = null;
}
}
public static void Stop()
{
try { _listener?.Stop(); } catch { }
_listener = null;
}
/// <summary>
/// Refresh the metrics snapshot from live game state.
/// Call from OnUpdate (main thread). Internally throttled by MetricsRefreshInterval.
/// </summary>
public static void Refresh()
{
if (_listener == null) return;
if ((DateTime.UtcNow - _lastRefresh).TotalSeconds < Plugin.MetricsRefreshInterval.Value) return;
_lastRefresh = DateTime.UtcNow;
try
{
_body = BuildMetrics();
}
catch (Exception ex)
{
Plugin.Log.Warning($"Metrics refresh failed: {ex.Message}");
}
}
// ────────────────── HTTP serving ──────────────────
private static void AcceptLoop()
{
while (_listener != null)
{
try
{
var client = _listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(_ => HandleClient(client));
}
catch (ObjectDisposedException) { break; }
catch (SocketException) { break; }
catch { /* ignore per-accept errors */ }
}
}
private static void HandleClient(TcpClient client)
{
try
{
using (client)
{
client.ReceiveTimeout = 5000;
client.SendTimeout = 5000;
using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.ASCII, false, 4096, leaveOpen: true);
// Parse request line.
string? requestLine = reader.ReadLine();
if (requestLine == null) return;
var parts = requestLine.Split(' ');
string method = parts.Length > 0 ? parts[0] : "";
string path = parts.Length > 1 ? parts[1] : "";
// Drain headers (don't care about their values).
string? line;
while ((line = reader.ReadLine()) != null && line.Length > 0) { }
if (method == "GET" && (path == "/metrics" || path.StartsWith("/metrics?")))
{
byte[] body = Encoding.UTF8.GetBytes(_body);
var header = Encoding.ASCII.GetBytes(
"HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain; version=0.0.4; charset=utf-8\r\n" +
$"Content-Length: {body.Length}\r\n" +
"Connection: close\r\n\r\n");
stream.Write(header, 0, header.Length);
stream.Write(body, 0, body.Length);
}
else
{
var resp = Encoding.ASCII.GetBytes(
"HTTP/1.1 404 Not Found\r\n" +
"Content-Length: 0\r\n" +
"Connection: close\r\n\r\n");
stream.Write(resp, 0, resp.Length);
}
stream.Flush();
}
}
catch { /* swallow per-client errors; don't kill the listener */ }
}
// ────────────────── exposition format ──────────────────
private static string BuildMetrics()
{
var sb = new StringBuilder(4096);
Heading(sb, "s1_mod_info", "gauge", "ScheduleObserved mod metadata");
sb.AppendLine("s1_mod_info{version=\"0.2.0\"} 1");
sb.AppendLine();
// Snapshot customer data on the main thread.
int count = Customer.UnlockedCustomers.Count;
var snap = new List<CSnap>(count);
for (int i = 0; i < count; i++)
{
try
{
var c = Customer.UnlockedCustomers[i];
if (c?.NPC == null || c.CustomerData == null) continue;
float rel = c.NPC.RelationData.RelationDelta / 5f;
snap.Add(new CSnap
{
Name = c.NPC.fullName ?? "?",
WeeklyBudget = c.CustomerData.GetAdjustedWeeklySpend(rel),
PerOrderCap = BudgetMath.GetPerOrderCap(c),
Addiction = c.CurrentAddiction,
Relationship = c.NPC.RelationData.RelationDelta,
OrdersPerWeek = c.CustomerData.GetOrderDays(c.CurrentAddiction, rel).Count,
});
}
catch { /* skip customers that throw during property access */ }
}
string slotLabel = $"save_slot=\"{Esc(SavePersistence.CurrentSaveLabel)}\"";
Heading(sb, "s1_unlocked_customers", "gauge", "Number of unlocked customers");
sb.AppendLine($"s1_unlocked_customers{{{slotLabel}}} {count}");
sb.AppendLine();
WriteGauge(sb, "s1_customer_weekly_budget", "Customer weekly budget (post-multiplier if Pocketchange installed)", snap, s => s.WeeklyBudget);
WriteGauge(sb, "s1_customer_per_order_cap", "Max affordable single-deal price", snap, s => s.PerOrderCap);
WriteGauge(sb, "s1_customer_addiction", "Addiction level 0-1", snap, s => s.Addiction, "F4");
WriteGauge(sb, "s1_customer_relationship", "Relationship delta (raw)", snap, s => s.Relationship, "F4");
WriteGaugeInt(sb, "s1_customer_orders_per_week", "Effective orders per week", snap, s => s.OrdersPerWeek);
EmitPlayerGauges(sb, slotLabel);
EmitDealerGauges(sb, slotLabel);
if (_counters.Count > 0)
{
Heading(sb, "s1_customer_spend_base_total", "counter", "Base contract payment per completed deal (pre-bonus)");
Heading(sb, "s1_customer_spend_total", "counter", "Total contract payment per completed deal (includes bonuses)");
Heading(sb, "s1_customer_deals_completed_total", "counter", "Completed deals by customer");
Heading(sb, "s1_product_sold_total", "counter", "Units of product sold (Amount * Quantity per handover)");
foreach (var kv in _counters)
{
sb.Append(kv.Key);
sb.Append(' ');
sb.AppendLine(kv.Value.ToString("G", CultureInfo.InvariantCulture));
}
sb.AppendLine();
}
// Wine's Environment.NewLine is \r\n, but the Prometheus exposition format is
// strictly \n-delimited ("invalid metric type \"gauge\\r\"" otherwise). Normalize
// once here so every AppendLine call in this file stays safe.
return sb.ToString().Replace("\r\n", "\n");
}
private static void WriteGauge(StringBuilder sb, string name, string help, List<CSnap> data, Func<CSnap, float> selector, string fmt = "F2")
{
Heading(sb, name, "gauge", help);
string slot = Esc(SavePersistence.CurrentSaveLabel);
foreach (var s in data)
{
sb.Append(name);
sb.Append("{save_slot=\"");
sb.Append(slot);
sb.Append("\",customer=\"");
sb.Append(Esc(s.Name));
sb.Append("\"} ");
sb.AppendLine(selector(s).ToString(fmt, CultureInfo.InvariantCulture));
}
sb.AppendLine();
}
private static void WriteGaugeInt(StringBuilder sb, string name, string help, List<CSnap> data, Func<CSnap, int> selector)
{
Heading(sb, name, "gauge", help);
string slot = Esc(SavePersistence.CurrentSaveLabel);
foreach (var s in data)
{
sb.Append(name);
sb.Append("{save_slot=\"");
sb.Append(slot);
sb.Append("\",customer=\"");
sb.Append(Esc(s.Name));
sb.Append("\"} ");
sb.AppendLine(selector(s).ToString(CultureInfo.InvariantCulture));
}
sb.AppendLine();
}
private static void EmitPlayerGauges(StringBuilder sb, string slotLabel)
{
var money = NetworkSingleton<MoneyManager>.Instance;
if (money != null)
{
Heading(sb, "s1_player_cash_balance", "gauge", "Player cash on hand");
sb.Append("s1_player_cash_balance{").Append(slotLabel).Append("} ")
.AppendLine(money.cashBalance.ToString("F2", CultureInfo.InvariantCulture));
sb.AppendLine();
Heading(sb, "s1_player_online_balance", "gauge", "Player ATM (online) balance");
#if Mono
float online = money.SyncAccessor_onlineBalance;
#else
// On IL2CPP, SyncAccessor_X is generated as a parameterized property that C# can't
// access normally — fall back to the synthesized accessor method.
float online = money.sync___get_value_onlineBalance();
#endif
sb.Append("s1_player_online_balance{").Append(slotLabel).Append("} ")
.AppendLine(online.ToString("F2", CultureInfo.InvariantCulture));
sb.AppendLine();
}
var level = NetworkSingleton<LevelManager>.Instance;
if (level != null)
{
// Rank as an enum-label gauge: value is always 1 so the label carries meaning.
Heading(sb, "s1_player_rank", "gauge", "Player rank enum (value always 1; rank name carried in label)");
sb.Append("s1_player_rank{").Append(slotLabel).Append(",rank=\"").Append(Esc(level.Rank.ToString())).AppendLine("\"} 1");
sb.AppendLine();
Heading(sb, "s1_player_xp", "gauge", "XP within the current tier");
sb.Append("s1_player_xp{").Append(slotLabel).Append("} ")
.AppendLine(level.XP.ToString(CultureInfo.InvariantCulture));
sb.AppendLine();
Heading(sb, "s1_player_total_xp", "gauge", "Cumulative XP across all tiers");
sb.Append("s1_player_total_xp{").Append(slotLabel).Append("} ")
.AppendLine(level.TotalXP.ToString(CultureInfo.InvariantCulture));
sb.AppendLine();
Heading(sb, "s1_player_xp_to_next_tier", "gauge", "XP threshold to reach the next tier");
sb.Append("s1_player_xp_to_next_tier{").Append(slotLabel).Append("} ")
.AppendLine(level.XPToNextTier.ToString("F0", CultureInfo.InvariantCulture));
sb.AppendLine();
}
}
private static void EmitDealerGauges(StringBuilder sb, string slotLabel)
{
int count = Dealer.AllPlayerDealers.Count;
if (count == 0) return;
Heading(sb, "s1_dealer_cash", "gauge", "Cash on hand per player-recruited dealer");
for (int i = 0; i < count; i++)
{
try
{
var d = Dealer.AllPlayerDealers[i];
if (d == null) continue;
string name = d.fullName ?? "?";
sb.Append("s1_dealer_cash{").Append(slotLabel).Append(",dealer=\"").Append(Esc(name)).Append("\"} ")
.AppendLine(d.Cash.ToString("F2", CultureInfo.InvariantCulture));
}
catch { /* skip dealers that throw during property access */ }
}
sb.AppendLine();
}
private static void Heading(StringBuilder sb, string name, string type, string help)
{
sb.Append("# HELP ");
sb.Append(name);
sb.Append(' ');
sb.AppendLine(help);
sb.Append("# TYPE ");
sb.Append(name);
sb.Append(' ');
sb.AppendLine(type);
}
private static string Esc(string labelValue)
=> labelValue.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n");
private struct CSnap
{
public string Name;
public float WeeklyBudget;
public float PerOrderCap;
public float Addiction;
public float Relationship;
public int OrdersPerWeek;
}
}