@anonympins/fingerprint 0.3.5 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,167 @@
1
+ <?php
2
+
3
+ declare(strict_types=1);
4
+
5
+ namespace Anonympins\Fingerprint\Utils;
6
+
7
+ class MetricsManager
8
+ {
9
+ /** @var array Stockage temporaire des compteurs Prometheus */
10
+ private static array $counters = [];
11
+
12
+ /** @var array Stockage temporaire des observations Prometheus */
13
+ private static array $observations = [];
14
+
15
+ /**
16
+ * Incrémente un compteur Prometheus.
17
+ *
18
+ * @param string $name Nom du compteur.
19
+ * @param array $labels Libellés/Labels associés.
20
+ */
21
+ public static function incrementCounter(string $name, array $labels = []): void
22
+ {
23
+ if (strpos($name, 'fingerprint_') !== 0) {
24
+ $name = 'fingerprint_' . $name;
25
+ }
26
+ ksort($labels);
27
+ $labelPairs = [];
28
+ foreach ($labels as $k => $v) {
29
+ $labelPairs[] = "{$k}=\"{$v}\"";
30
+ }
31
+ $labelsStr = !empty($labelPairs) ? '{' . implode(',', $labelPairs) . '}' : '';
32
+ $key = $name . $labelsStr;
33
+
34
+ if (!isset(self::$counters[$key])) {
35
+ self::$counters[$key] = [
36
+ 'name' => $name,
37
+ 'labelsStr' => $labelsStr,
38
+ 'value' => 0
39
+ ];
40
+ }
41
+ self::$counters[$key]['value']++;
42
+ }
43
+
44
+ /**
45
+ * Enregistre une observation de valeur (ex: temps d'exécution, score).
46
+ *
47
+ * @param string $name Nom de la métrique.
48
+ * @param float $value Valeur observée.
49
+ * @param array $labels Libellés/Labels associés.
50
+ */
51
+ public static function observeValue(string $name, float $value, array $labels = []): void
52
+ {
53
+ if (strpos($name, 'fingerprint_') !== 0) {
54
+ $name = 'fingerprint_' . $name;
55
+ }
56
+ ksort($labels);
57
+ $labelPairs = [];
58
+ foreach ($labels as $k => $v) {
59
+ $labelPairs[] = "{$k}=\"{$v}\"";
60
+ }
61
+ $labelsStr = !empty($labelPairs) ? '{' . implode(',', $labelPairs) . '}' : '';
62
+ $key = $name . $labelsStr;
63
+
64
+ self::$observations[$key] = [
65
+ 'name' => $name,
66
+ 'labelsStr' => $labelsStr,
67
+ 'value' => $value
68
+ ];
69
+ }
70
+
71
+ /**
72
+ * Réinitialise les compteurs enregistrés (utile pour l'isolation des tests).
73
+ */
74
+ public static function clearMetrics(): void
75
+ {
76
+ self::$counters = [];
77
+ self::$observations = [];
78
+ }
79
+
80
+ /**
81
+ * Génère les métriques au format Prometheus text/plain.
82
+ *
83
+ * @param array $securityConfig La configuration de sécurité active.
84
+ * @param array|null $lastBestSolution La dernière solution calculée par l'Auto-Tuner.
85
+ * @return string
86
+ */
87
+ public static function getPrometheusMetrics(array $securityConfig = [], ?array $lastBestSolution = null): string
88
+ {
89
+ $metrics = "";
90
+
91
+ if (empty(self::$counters)) {
92
+ $metrics .= "# HELP fingerprint_requests_total Total requests processed.\n";
93
+ $metrics .= "# TYPE fingerprint_requests_total counter\n";
94
+ $metrics .= "fingerprint_requests_total{status=\"passed\"} 1\n";
95
+ } else {
96
+ $grouped = [];
97
+ foreach (self::$counters as $c) {
98
+ $grouped[$c['name']][] = $c;
99
+ }
100
+ foreach ($grouped as $name => $instances) {
101
+ $metrics .= "# HELP {$name} Total requests processed.\n";
102
+ $metrics .= "# TYPE {$name} counter\n";
103
+ foreach ($instances as $instance) {
104
+ $metrics .= "{$name}{$instance['labelsStr']} {$instance['value']}\n";
105
+ }
106
+ }
107
+ }
108
+
109
+ // Export des observations (Gauges)
110
+ if (!empty(self::$observations)) {
111
+ $groupedObs = [];
112
+ foreach (self::$observations as $obs) {
113
+ $groupedObs[$obs['name']][] = $obs;
114
+ }
115
+ foreach ($groupedObs as $name => $instances) {
116
+ $metrics .= "\n# HELP {$name} Value observation.\n";
117
+ $metrics .= "# TYPE {$name} gauge\n";
118
+ foreach ($instances as $instance) {
119
+ $metrics .= "{$name}{$instance['labelsStr']} {$instance['value']}\n";
120
+ }
121
+ }
122
+ }
123
+
124
+ // 1. Export des poids actifs (Weights)
125
+ if (isset($securityConfig['weights']) && is_array($securityConfig['weights'])) {
126
+ $metrics .= "\n# HELP fingerprint_security_weight Active weight for each suspicion indicator.\n";
127
+ $metrics .= "# TYPE fingerprint_security_weight gauge\n";
128
+ foreach ($securityConfig['weights'] as $indicator => $weight) {
129
+ if (is_numeric($weight)) {
130
+ $metrics .= "fingerprint_security_weight{indicator=\"{$indicator}\"} {$weight}\n";
131
+ }
132
+ }
133
+ }
134
+
135
+ // 2. Export des seuils actifs (Thresholds)
136
+ if (isset($securityConfig['thresholds']) && is_array($securityConfig['thresholds'])) {
137
+ $metrics .= "\n# HELP fingerprint_security_threshold Active score threshold for each enforcement action level.\n";
138
+ $metrics .= "# TYPE fingerprint_security_threshold gauge\n";
139
+ foreach ($securityConfig['thresholds'] as $level => $threshold) {
140
+ if (is_numeric($threshold)) {
141
+ $metrics .= "fingerprint_security_threshold{level=\"{$level}\"} {$threshold}\n";
142
+ }
143
+ }
144
+ }
145
+
146
+ // 3. Récupération auto de la dernière solution d'auto-tuning depuis le cache (savePath) si non fournie
147
+ if ($lastBestSolution === null && isset($securityConfig['autotuning']['savePath'])) {
148
+ $savePath = $securityConfig['autotuning']['savePath'];
149
+ if (file_exists($savePath)) {
150
+ $savedData = json_decode(file_get_contents($savePath), true);
151
+ if (is_array($savedData) && isset($savedData['objectives'])) {
152
+ $lastBestSolution = $savedData;
153
+ }
154
+ }
155
+ }
156
+
157
+ // 4. Export des objectifs d'Auto-Tuning (Faux positifs & Faux négatifs calculés)
158
+ if ($lastBestSolution !== null && isset($lastBestSolution['objectives']) && is_array($lastBestSolution['objectives'])) {
159
+ $fpr = $lastBestSolution['objectives'][0] ?? 0.0;
160
+ $fnr = $lastBestSolution['objectives'][1] ?? 0.0;
161
+ $metrics .= "\n# HELP fingerprint_autotuning_false_positive_rate Current false positive rate calculated by the auto-tuner.\n# TYPE fingerprint_autotuning_false_positive_rate gauge\nfingerprint_autotuning_false_positive_rate {$fpr}\n";
162
+ $metrics .= "\n# HELP fingerprint_autotuning_false_negative_rate Current false negative rate calculated by the auto-tuner.\n# TYPE fingerprint_autotuning_false_negative_rate gauge\nfingerprint_autotuning_false_negative_rate {$fnr}\n";
163
+ }
164
+
165
+ return $metrics;
166
+ }
167
+ }