-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfire.php
More file actions
executable file
·327 lines (276 loc) · 13.7 KB
/
fire.php
File metadata and controls
executable file
·327 lines (276 loc) · 13.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
#!/usr/bin/php
<?php
if (php_sapi_name() !== 'cli') {
exit;
}
require "cliautoload.php";
require "autoload.php";
require "./cli/Cli/clihelpers.php";
use Cli\Cli;
use Cli\CommandArgs;
use Fireline\Config\ConfigChecker;
use Fireline\Learning\BaselineBuilder;
use Fireline\Learning\RouteModelExporter;
use Fireline\Replay\ReplayRunner;
use Fireline\Rules\RuleValidator;
use Fireline\Telemetry\MetricsFormatter;
use Fireline\Telemetry\RuleMetrics;
use Fireline\Telemetry\MetricsStore;
$cli = new Cli();
$cli->registerCommand('help', function (array $argv) use ($cli) {
$menu = "+--------------+-------------------------------------------+
| usage: php fire.php [command] |
+--------------+-------------------------------------------+
| help | Show this menu. |
+--------------+-------------------------------------------+
| replay:run | Replay stored traffic and show changes. |
+--------------+-------------------------------------------+
| baseline:build | Build route model candidates from replay. |
+--------------+-------------------------------------------+
| baseline:export | Write route model candidates to a file. |
+--------------+-------------------------------------------+
| config:check | Validate Fireline config and writable paths. |
+--------------+-------------------------------------------+
| rules:validate | Validate rule metadata and regex syntax. |
+--------------+-------------------------------------------+
| metrics:show | Show in-process metrics snapshot. |
+--------------+-------------------------------------------+
| metrics:export | Export persisted metrics JSON. |
+--------------+-------------------------------------------+
| metrics:reset | Reset persisted metrics snapshot. |
+--------------+-------------------------------------------+
| examples | php fire.php replay:run storage/replay/traffic.ndjson |
| | php fire.php replay:run storage/replay/traffic.ndjson --json |
| | php fire.php replay:run storage/replay/traffic.ndjson --output storage/replay/report.json |
| | php fire.php baseline:build storage/replay/traffic.ndjson 10 --json |
| | php fire.php baseline:build storage/replay/traffic.ndjson 10 --json --report |
| | php fire.php baseline:export storage/replay/traffic.ndjson 10 storage/models/routes.generated.php |
| | php fire.php baseline:export storage/replay/traffic.ndjson 10 storage/models/routes.generated.php --dry-run |
| | php fire.php baseline:export storage/replay/traffic.ndjson 10 storage/models/routes.generated.php --force |
| | php fire.php rules:validate config/rules.php --json |
| | php fire.php metrics:show storage/metrics/fireline-metrics.json --summary |
| | php fire.php metrics:export storage/metrics/fireline-metrics.json storage/metrics/export.json |
+--------------+-------------------------------------------+";
$cli->getPrinter()->display( $menu );
});
$cli->registerCommand('replay:run', function (array $argv) use ($cli) {
$ciMode = CommandArgs::hasFlag($argv, '--ci');
$jsonMode = CommandArgs::hasFlag($argv, '--json');
$outputPath = CommandArgs::optionValue($argv, '--output');
$path = CommandArgs::firstValue($argv, 2, __DIR__ . '/storage/replay/traffic.ndjson', ['--output']);
$result = (new ReplayRunner())->replay($path);
if ($outputPath !== null && $outputPath !== '') {
if (is_file($outputPath) && !CommandArgs::hasFlag($argv, '--force')) {
$cli->getPrinter()->display('Replay report exists; use --force to overwrite: ' . $outputPath);
exit(1);
}
$dir = dirname($outputPath);
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
$cli->getPrinter()->display('Unable to create replay report directory: ' . $dir);
exit(1);
}
$encodedReport = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if (!is_string($encodedReport) || file_put_contents($outputPath, $encodedReport . PHP_EOL, LOCK_EX) === false) {
$cli->getPrinter()->display('Unable to write replay report: ' . $outputPath);
exit(1);
}
}
if ($jsonMode) {
$encoded = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$cli->getPrinter()->display(is_string($encoded) ? $encoded : '{}');
if ($ciMode && count($result['regressions']) > 0) {
exit(1);
}
return;
}
$lines = [
'Replay file: ' . $path,
'Events replayed: ' . $result['total'],
'Invalid lines: ' . ($result['invalid'] ?? 0),
'Regressions: ' . count($result['regressions']),
];
if ($outputPath !== null && $outputPath !== '') {
$lines[] = 'Report written: ' . $outputPath;
}
if (isset($result['summary']['decision_changes']) && is_array($result['summary']['decision_changes'])) {
$changes = $result['summary']['decision_changes'];
$lines[] = 'Decision changes: allowed_to_blocked=' . ($changes['allowed_to_blocked'] ?? 0)
. ', blocked_to_allowed=' . ($changes['blocked_to_allowed'] ?? 0)
. ', unchanged=' . ($changes['unchanged'] ?? 0);
}
if (isset($result['summary']['score_deltas']) && is_array($result['summary']['score_deltas'])) {
$deltas = $result['summary']['score_deltas'];
$lines[] = 'Score deltas: increased=' . ($deltas['increased'] ?? 0)
. ', decreased=' . ($deltas['decreased'] ?? 0)
. ', unchanged=' . ($deltas['unchanged'] ?? 0)
. ', total=' . ($deltas['total_delta'] ?? 0)
. ', average=' . round((float) ($deltas['average_delta'] ?? 0), 2);
}
if (isset($result['summary']['by_type']) && is_array($result['summary']['by_type']) && array_sum($result['summary']['by_type']) > 0) {
$lines[] = 'By type:';
foreach ($result['summary']['by_type'] as $type => $count) {
if ($count > 0) {
$lines[] = '- ' . $type . ': ' . $count;
}
}
}
if (isset($result['summary']['by_route']) && is_array($result['summary']['by_route']) && $result['summary']['by_route'] !== []) {
$lines[] = 'By route:';
foreach (array_slice($result['summary']['by_route'], 0, 10, true) as $route => $count) {
$lines[] = '- ' . $route . ': ' . $count;
}
}
foreach ($result['regressions'] as $index => $regression) {
$lines[] = '';
$lines[] = '#' . ($index + 1) . ' ' . ($regression['type'] ?? 'regression');
$lines[] = 'Route: ' . ($regression['route'] ?? '');
$lines[] = 'Previous Score: ' . ($regression['previous_score'] ?? 0);
$lines[] = 'Current Score: ' . ($regression['current_score'] ?? 0);
$lines[] = 'Previous Blocked: ' . (!empty($regression['previous_blocked']) ? 'yes' : 'no');
$lines[] = 'Current Blocked: ' . (!empty($regression['current_blocked']) ? 'yes' : 'no');
$lines[] = 'Metadata Changed: ' . (!empty($regression['metadata_changed']) ? 'yes' : 'no');
if (isset($regression['metadata_diff']['changed']) && is_array($regression['metadata_diff']['changed']) && $regression['metadata_diff']['changed'] !== []) {
$lines[] = 'Metadata Diff: ' . implode(', ', $regression['metadata_diff']['changed']);
}
if (isset($regression['explanation']) && is_array($regression['explanation'])) {
$lines[] = 'Reason: ' . ($regression['explanation']['reason'] ?? '');
}
}
$cli->getPrinter()->display(implode(PHP_EOL, $lines));
if ($ciMode && count($result['regressions']) > 0) {
exit(1);
}
});
$cli->registerCommand('baseline:build', function (array $argv) use ($cli) {
$path = CommandArgs::firstValue($argv, 2, __DIR__ . '/storage/replay/traffic.ndjson');
$minSamples = CommandArgs::intValue($argv, 3, 3);
$report = BaselineBuilder::buildReportFromReplayFile($path, $minSamples);
$model = $report['model'];
if (CommandArgs::hasFlag($argv, '--json')) {
$payload = CommandArgs::hasFlag($argv, '--report') ? $report : $model;
$encoded = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$cli->getPrinter()->display(is_string($encoded) ? $encoded : '{}');
return;
}
$cli->getPrinter()->display(
"Replay file: " . $path . PHP_EOL .
"Events read: " . $report['total'] . PHP_EOL .
"Invalid lines: " . $report['invalid'] . PHP_EOL .
"Minimum samples: " . $minSamples . PHP_EOL .
"Route model:" . PHP_EOL .
RouteModelExporter::toPhp($model)
);
});
$cli->registerCommand('baseline:export', function (array $argv) use ($cli) {
$values = CommandArgs::values($argv, 2);
$path = $values[0] ?? __DIR__ . '/storage/replay/traffic.ndjson';
$minSamples = max(1, (int) ($values[1] ?? 3));
$destination = $values[2] ?? __DIR__ . '/storage/models/routes.generated.php';
$report = BaselineBuilder::buildReportFromReplayFile($path, $minSamples);
$dir = dirname($destination);
$lines = [
(CommandArgs::hasFlag($argv, '--dry-run') ? 'Route model export preview: ' : 'Route model exported: ') . $destination,
'Replay file: ' . $path,
'Events read: ' . $report['total'],
'Invalid lines: ' . $report['invalid'],
'Minimum samples: ' . $minSamples,
];
if (CommandArgs::hasFlag($argv, '--dry-run')) {
$cli->getPrinter()->display(implode(PHP_EOL, $lines));
return;
}
if (is_file($destination) && !CommandArgs::hasFlag($argv, '--force')) {
$cli->getPrinter()->display('Route model exists; use --force to overwrite: ' . $destination);
exit(1);
}
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
$cli->getPrinter()->display('Unable to create route model directory: ' . $dir);
exit(1);
}
if (file_put_contents($destination, RouteModelExporter::toPhp($report['model']), LOCK_EX) === false) {
$cli->getPrinter()->display('Unable to export route model: ' . $destination);
exit(1);
}
$cli->getPrinter()->display(implode(PHP_EOL, $lines));
});
$cli->registerCommand('config:check', function (array $argv) use ($cli) {
$result = (new ConfigChecker(__DIR__))->check();
$lines = [
'Config status: ' . ($result['ok'] ? 'ok' : 'error'),
];
foreach ($result['checks'] as $check) {
$lines[] = '[' . strtoupper($check['status']) . '] ' . $check['name'] . ': ' . $check['message'];
}
$cli->getPrinter()->display(implode(PHP_EOL, $lines));
if (!$result['ok']) {
exit(1);
}
});
$cli->registerCommand('rules:validate', function (array $argv) use ($cli) {
$path = CommandArgs::firstValue($argv, 2, __DIR__ . '/config/rules.php');
$result = (new RuleValidator())->validateFile($path);
if (CommandArgs::hasFlag($argv, '--json')) {
$encoded = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$cli->getPrinter()->display(is_string($encoded) ? $encoded : '{}');
} else {
$lines = [
'Rule status: ' . ($result['ok'] ? 'ok' : 'error'),
'Rule file: ' . $path,
'Rules checked: ' . $result['total'],
'Errors: ' . count($result['errors']),
];
foreach ($result['errors'] as $error) {
$lines[] = '[ERROR] ' . $error['rule'] . ' ' . $error['field'] . ': ' . $error['message'];
}
$cli->getPrinter()->display(implode(PHP_EOL, $lines));
}
if (!$result['ok']) {
exit(1);
}
});
$cli->registerCommand('metrics:show', function (array $argv) use ($cli) {
$path = CommandArgs::firstValue($argv, 2, __DIR__ . '/storage/metrics/fireline-metrics.json');
$snapshot = CommandArgs::hasFlag($argv, '--live') || !is_readable($path)
? RuleMetrics::snapshot()
: MetricsStore::read($path);
if (CommandArgs::hasFlag($argv, '--json')) {
$output = MetricsFormatter::json($snapshot);
} elseif (CommandArgs::hasFlag($argv, '--summary')) {
$output = MetricsFormatter::summary($snapshot);
} else {
$output = MetricsFormatter::text($snapshot);
}
$cli->getPrinter()->display($output);
});
$cli->registerCommand('metrics:export', function (array $argv) use ($cli) {
$values = CommandArgs::values($argv, 2);
$source = $values[0] ?? __DIR__ . '/storage/metrics/fireline-metrics.json';
$destination = $values[1] ?? __DIR__ . '/storage/metrics/fireline-metrics-export.json';
$snapshot = CommandArgs::hasFlag($argv, '--live') || !is_readable($source)
? RuleMetrics::snapshot()
: MetricsStore::read($source);
$snapshot['exported_at'] = date('c');
$snapshot['source_path'] = $source;
$dir = dirname($destination);
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
$cli->getPrinter()->display('Unable to create metrics export directory: ' . $dir);
exit(1);
}
if (file_put_contents($destination, MetricsFormatter::json($snapshot) . PHP_EOL, LOCK_EX) === false) {
$cli->getPrinter()->display('Unable to export metrics: ' . $destination);
exit(1);
}
$cli->getPrinter()->display('Metrics exported: ' . $destination);
});
$cli->registerCommand('metrics:reset', function (array $argv) use ($cli) {
$path = CommandArgs::firstValue($argv, 2, __DIR__ . '/storage/metrics/fireline-metrics.json');
if (CommandArgs::hasFlag($argv, '--live')) {
RuleMetrics::reset();
}
if (!MetricsStore::reset($path)) {
$cli->getPrinter()->display('Unable to reset metrics file: ' . $path);
exit(1);
}
$cli->getPrinter()->display('Metrics reset: ' . $path);
});
$cli->runCommand($argv);