Repository navigation
Expand file tree
/
Copy pathPerfbaseSettingsForm.php
More file actions
638 lines (550 loc) · 20.1 KB
/
Copy pathPerfbaseSettingsForm.php
File metadata and controls
638 lines (550 loc) · 20.1 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<?php
namespace Perfbase\Drupal\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\ConfigFormBase;
use Perfbase\Drupal\Config\ConfigResolver;
use Perfbase\SDK\FeatureFlags;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Admin settings form for configuring the Perfbase module.
*
* @phpstan-import-type PerfbaseConfig from \Perfbase\Drupal\Config\ConfigResolver
*/
final class PerfbaseSettingsForm extends ConfigFormBase {
protected ConfigResolver $configResolver;
public function __construct(
ConfigResolver $configResolver,
ConfigFactoryInterface $configFactory,
TypedConfigManagerInterface $typedConfigManager,
) {
parent::__construct($configFactory, $typedConfigManager);
$this->configResolver = $configResolver;
}
/**
*
*/
public static function create(ContainerInterface $container): self {
$configResolver = $container->get('perfbase.config_resolver');
$configFactory = $container->get('config.factory');
$typedConfigManager = $container->get('config.typed');
if (!$configResolver instanceof ConfigResolver) {
throw new \RuntimeException('Perfbase config resolver service is not available.');
}
if (!$configFactory instanceof ConfigFactoryInterface) {
throw new \RuntimeException('Drupal config factory service is not available.');
}
if (!$typedConfigManager instanceof TypedConfigManagerInterface) {
throw new \RuntimeException('Drupal typed config manager service is not available.');
}
return new self(
$configResolver,
$configFactory,
$typedConfigManager
);
}
/**
*
*/
public function getFormId(): string {
return 'perfbase_settings_form';
}
/**
* @return array<int, string>
*/
protected function getEditableConfigNames(): array {
return ['perfbase.settings'];
}
/**
* @param array<string, mixed> $form
* @return array<string, mixed>
*/
public function buildForm(array $form, FormStateInterface $form_state): array {
$config = $this->configResolver->getConfig();
$form['enabled'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable Perfbase'),
'#default_value' => !empty($config['enabled']),
];
$form['debug'] = [
'#type' => 'checkbox',
'#title' => $this->t('Debug mode'),
'#default_value' => !empty($config['debug']),
];
$form['log_errors'] = [
'#type' => 'checkbox',
'#title' => $this->t('Log profiling errors'),
'#default_value' => !empty($config['log_errors']),
];
$form['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API key'),
'#default_value' => $config['api_key'],
];
$form['api_url'] = [
'#type' => 'url',
'#title' => $this->t('API URL'),
'#default_value' => $config['api_url'],
];
$form['timeout'] = [
'#type' => 'number',
'#title' => $this->t('Timeout'),
'#default_value' => $config['timeout'],
'#min' => 1,
];
$form['proxy'] = [
'#type' => 'textfield',
'#title' => $this->t('Proxy'),
'#default_value' => $config['proxy'],
];
$form['flags'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Feature flags'),
'#options' => $this->flagOptions(),
'#default_value' => $this->selectedFlags($config['flags']),
'#description' => $this->t('Profiler features to enable. "Use Precise Clock" and "Track CPU Time" add per-call overhead and are opt-in. Leaving every box unchecked enables every feature except those two.'),
];
$form['sample_rate'] = [
'#type' => 'number',
'#title' => $this->t('Sample rate'),
'#default_value' => $config['sample_rate'],
'#step' => 0.01,
'#min' => 0,
'#max' => 1,
];
$form['profile_http_status_codes'] = [
'#type' => 'textarea',
'#title' => $this->t('HTTP status codes to submit'),
'#default_value' => $this->formatStatusCodes($config['profile_http_status_codes']),
'#description' => $this->t('Comma-separated or newline-separated HTTP status codes or ranges. Only HTTP responses with these codes will be submitted. Example: 200-299, 500-599, 404.'),
];
$form['environment'] = [
'#type' => 'textfield',
'#title' => $this->t('Environment'),
'#default_value' => $config['environment'],
];
$form['app_version'] = [
'#type' => 'textfield',
'#title' => $this->t('Application version'),
'#default_value' => $config['app_version'],
];
$form['profile_http'] = [
'#type' => 'checkbox',
'#title' => $this->t('Profile HTTP requests'),
'#default_value' => !empty($config['profile_http']),
];
$form['exclude_admin_routes'] = [
'#type' => 'checkbox',
'#title' => $this->t('Exclude Drupal admin routes'),
'#default_value' => !empty($config['exclude_admin_routes']),
'#description' => $this->t("Skip profiling requests for routes marked with Drupal's admin-route metadata."),
];
$form['profile_console'] = [
'#type' => 'checkbox',
'#title' => $this->t('Profile console commands'),
'#default_value' => !empty($config['profile_console']),
];
$form['profile_cron'] = [
'#type' => 'checkbox',
'#title' => $this->t('Profile cron'),
'#default_value' => !empty($config['profile_cron']),
];
$form['profile_queue'] = [
'#type' => 'checkbox',
'#title' => $this->t('Profile queue workers'),
'#default_value' => !empty($config['profile_queue']),
];
foreach (['http', 'console', 'cron', 'queue'] as $context) {
$form['include_' . $context] = [
'#type' => 'textarea',
'#title' => $this->t('Include filters for @context', ['@context' => $context]),
'#default_value' => implode("\n", $config['include'][$context]),
];
$form['exclude_' . $context] = [
'#type' => 'textarea',
'#title' => $this->t('Exclude filters for @context', ['@context' => $context]),
'#default_value' => implode("\n", $config['exclude'][$context]),
];
}
$this->lockOverriddenElements($form);
return parent::buildForm($form, $form_state);
}
/**
* @param array<mixed> $form
*/
public function validateForm(array &$form, FormStateInterface $form_state): void {
// Values supplied by settings.php are locked above and never submitted.
if (!$this->isOverridden('timeout')) {
$timeout = $this->intValue($form_state->getValue('timeout'));
if ($timeout < 1) {
$form_state->setErrorByName('timeout', $this->t('Timeout must be at least 1 second.'));
}
}
if (!$this->isOverridden('sample_rate')) {
$sampleRate = $this->floatValue($form_state->getValue('sample_rate'));
if ($sampleRate < 0.0 || $sampleRate > 1.0) {
$form_state->setErrorByName('sample_rate', $this->t('Sample rate must be between 0 and 1.'));
}
}
if (!$this->isOverridden('profile_http_status_codes')) {
$this->validateStatusCodes(
$form_state,
'profile_http_status_codes',
$this->stringValue($form_state->getValue('profile_http_status_codes'))
);
}
// The SDK refuses the whole client over a bad endpoint, which leaves
// profiling off with nothing but a line in the log. Catch it here instead.
if (!$this->isOverridden('api_url')) {
$apiUrl = trim($this->stringValue($form_state->getValue('api_url')));
if ($apiUrl !== '' && !$this->isUrlWithScheme($apiUrl, ['https'])) {
$form_state->setErrorByName('api_url', $this->t('API URL must be a valid URL using HTTPS.'));
}
}
if (!$this->isOverridden('proxy')) {
$proxy = trim($this->stringValue($form_state->getValue('proxy')));
if ($proxy !== '' && !$this->isUrlWithScheme($proxy, ['http', 'https', 'socks5', 'socks5h'])) {
$form_state->setErrorByName('proxy', $this->t('Proxy must be a valid URL using http, https, socks5, or socks5h.'));
}
}
foreach (['http', 'console', 'cron', 'queue'] as $context) {
if (!$this->isOverridden('include', $context)) {
$this->validateRegexFilters(
$form_state,
'include_' . $context,
$this->stringValue($form_state->getValue('include_' . $context)),
'Include'
);
}
if (!$this->isOverridden('exclude', $context)) {
$this->validateRegexFilters(
$form_state,
'exclude_' . $context,
$this->stringValue($form_state->getValue('exclude_' . $context)),
'Exclude'
);
}
}
parent::validateForm($form, $form_state);
}
/**
* @param array<mixed> $form
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$config = $this->config('perfbase.settings');
$values = [
'enabled' => (bool) $form_state->getValue('enabled'),
'debug' => (bool) $form_state->getValue('debug'),
'log_errors' => (bool) $form_state->getValue('log_errors'),
'api_key' => $this->stringValue($form_state->getValue('api_key')),
'api_url' => $this->stringValue($form_state->getValue('api_url')),
'timeout' => $this->intValue($form_state->getValue('timeout')),
'proxy' => $this->stringValue($form_state->getValue('proxy')),
'flags' => $this->flagsValue($form_state->getValue('flags')),
'sample_rate' => $this->floatValue($form_state->getValue('sample_rate')),
'profile_http_status_codes' => $this->parseStatusCodes($this->stringValue($form_state->getValue('profile_http_status_codes'))),
'environment' => $this->stringValue($form_state->getValue('environment')),
'app_version' => $this->stringValue($form_state->getValue('app_version')),
'profile_http' => (bool) $form_state->getValue('profile_http'),
'exclude_admin_routes' => (bool) $form_state->getValue('exclude_admin_routes'),
'profile_console' => (bool) $form_state->getValue('profile_console'),
'profile_cron' => (bool) $form_state->getValue('profile_cron'),
'profile_queue' => (bool) $form_state->getValue('profile_queue'),
];
// Values supplied by settings.php win at runtime, so they are left as
// stored instead of being copied into configuration, which would move a
// key that is meant to live only in settings.php into the database and
// any exported YAML.
foreach ($values as $key => $value) {
if (!$this->isOverridden($key)) {
$config->set($key, $value);
}
}
foreach (['include', 'exclude'] as $tree) {
$filters = $config->get($tree);
if (!is_array($filters)) {
$filters = [];
}
foreach (['http', 'console', 'cron', 'queue'] as $context) {
if (!$this->isOverridden($tree, $context)) {
$filters[$context] = $this->parseFilterLines($this->stringValue($form_state->getValue($tree . '_' . $context)));
}
}
$config->set($tree, $filters);
}
$config->save();
parent::submitForm($form, $form_state);
}
/**
* Disables the elements whose value settings.php provides.
*
* Those values win at runtime, so editing them here would have no effect.
* Locking them also means they are never submitted, which submitForm()
* relies on.
*
* @param array<string, mixed> $form
*/
private function lockOverriddenElements(array &$form): void {
$locked = [];
foreach (array_keys($form) as $name) {
if (is_string($name) && $this->isOverridden($name)) {
$locked[$name] = $this->settingPath($name);
}
}
foreach (['include', 'exclude'] as $tree) {
foreach (['http', 'console', 'cron', 'queue'] as $context) {
if ($this->isOverridden($tree, $context)) {
$locked[$tree . '_' . $context] = $this->settingPath($tree, $context);
}
}
}
foreach ($locked as $name => $setting) {
$element = $form[$name] ?? NULL;
if (!is_array($element)) {
continue;
}
$element['#disabled'] = TRUE;
$element['#description'] = $this->t('Set in settings.php by @setting, which takes precedence over this form. Remove the override to change it here.', ['@setting' => $setting]);
// Never send a secret that lives in settings.php to the browser.
if ($name === 'api_key' || $name === 'proxy') {
$element['#default_value'] = '';
}
$form[$name] = $element;
}
}
/**
* Whether settings.php supplies this value, either as a scalar key or as
* one context of the include or exclude filters.
*/
private function isOverridden(string $key, ?string $context = NULL): bool {
$overrides = $this->configResolver->getSettingsOverrides();
if ($context === NULL) {
return array_key_exists($key, $overrides);
}
$tree = $overrides[$key] ?? NULL;
return is_array($tree) && array_key_exists($context, $tree);
}
/**
* The settings.php expression that supplies a value, for form messages.
*/
private function settingPath(string $key, ?string $context = NULL): string {
$path = "\$settings['perfbase']['" . $key . "']";
if ($context !== NULL) {
$path = "\$settings['perfbase']['" . $key . "']['" . $context . "']";
}
return $path;
}
/**
* Flags the extension honours. Deprecated SDK constants are not offered.
*
* @return array<int, \Drupal\Core\StringTranslation\TranslatableMarkup>
*/
private function flagOptions(): array {
return [
FeatureFlags::UsePreciseClock => $this->t('Use Precise Clock'),
FeatureFlags::TrackCpuTime => $this->t('Track CPU Time'),
FeatureFlags::TrackMemoryAllocation => $this->t('Track Memory Allocation'),
FeatureFlags::TrackExceptions => $this->t('Track Exceptions'),
FeatureFlags::TrackErrors => $this->t('Track PHP Errors'),
FeatureFlags::TrackMagicMethods => $this->t('Track Magic Methods'),
FeatureFlags::TrackFileCompilation => $this->t('Track File Compilation'),
FeatureFlags::TrackOpcache => $this->t('Track OPcache Stats'),
FeatureFlags::TrackPdo => $this->t('Track Database Queries (PDO, mysqli)'),
FeatureFlags::TrackMongodb => $this->t('Track MongoDB Operations'),
FeatureFlags::TrackElasticsearch => $this->t('Track Elasticsearch Operations'),
FeatureFlags::TrackCaches => $this->t('Track Cache Operations (Redis, Memcached)'),
FeatureFlags::TrackHttp => $this->t('Track Outbound HTTP Requests'),
FeatureFlags::TrackMail => $this->t('Track Mail'),
FeatureFlags::TrackFileOperations => $this->t('Track File Operations'),
FeatureFlags::TrackStreams => $this->t('Track Stream Errors (PHP 8.6+)'),
FeatureFlags::TrackProc => $this->t('Track Process Execution'),
FeatureFlags::TrackProcessList => $this->t('Track Process List'),
];
}
/**
* @return array<int, int>
*/
private function selectedFlags(int $flags): array {
$selected = [];
foreach (array_keys($this->flagOptions()) as $flag) {
if (($flags & $flag) !== 0) {
$selected[] = $flag;
}
}
return $selected;
}
/**
* Combines the checked flags (checkboxes submit unchecked boxes as 0).
*
* @param mixed $value
*/
private function flagsValue($value): int {
if (!is_array($value)) {
return max(0, $this->intValue($value)) & FeatureFlags::ValidFlagsMask;
}
$flags = 0;
foreach ($value as $flag) {
$flags |= $this->intValue($flag);
}
return $flags & FeatureFlags::ValidFlagsMask;
}
/**
* @return array<int, string>
*/
private function parseFilterLines(string $value): array {
$lines = preg_split('/\r?\n/', $value) ?: [];
$lines = array_map('trim', $lines);
$lines = array_filter($lines, static function (string $line): bool {
return $line !== '';
});
return array_values($lines);
}
/**
* @param array<int, int> $statusCodes
*/
private function formatStatusCodes(array $statusCodes): string {
if ($statusCodes === []) {
return '';
}
$statusCodes = array_values(array_unique($statusCodes));
sort($statusCodes);
$ranges = [];
$rangeStart = $statusCodes[0];
$rangeEnd = $statusCodes[0];
foreach (array_slice($statusCodes, 1) as $statusCode) {
if ($statusCode === $rangeEnd + 1) {
$rangeEnd = $statusCode;
continue;
}
$ranges[] = $rangeStart === $rangeEnd ? (string) $rangeStart : $rangeStart . '-' . $rangeEnd;
$rangeStart = $statusCode;
$rangeEnd = $statusCode;
}
$ranges[] = $rangeStart === $rangeEnd ? (string) $rangeStart : $rangeStart . '-' . $rangeEnd;
return implode(', ', $ranges);
}
/**
* @return array<int, int>
*/
private function parseStatusCodes(string $value): array {
$tokens = preg_split('/[\s,]+/', trim($value)) ?: [];
$statusCodes = [];
foreach ($tokens as $token) {
if ($token === '') {
continue;
}
if (preg_match('/^\d{3}$/', $token) === 1) {
$statusCodes[] = (int) $token;
continue;
}
if (preg_match('/^(\d{3})-(\d{3})$/', $token, $matches) === 1) {
$rangeStart = (int) $matches[1];
$rangeEnd = (int) $matches[2];
if ($rangeStart > $rangeEnd) {
continue;
}
foreach (range($rangeStart, $rangeEnd) as $statusCode) {
$statusCodes[] = $statusCode;
}
}
}
$statusCodes = array_values(array_filter(array_unique($statusCodes), static function (int $statusCode): bool {
return $statusCode >= 100 && $statusCode <= 599;
}));
sort($statusCodes);
return $statusCodes;
}
private function validateStatusCodes(FormStateInterface $form_state, string $fieldName, string $value): void {
$tokens = preg_split('/[\s,]+/', trim($value)) ?: [];
foreach ($tokens as $token) {
if ($token === '') {
continue;
}
if (preg_match('/^\d{3}$/', $token) === 1) {
$statusCode = (int) $token;
if ($statusCode >= 100 && $statusCode <= 599) {
continue;
}
}
if (preg_match('/^(\d{3})-(\d{3})$/', $token, $matches) === 1) {
$rangeStart = (int) $matches[1];
$rangeEnd = (int) $matches[2];
if ($rangeStart >= 100 && $rangeEnd <= 599 && $rangeStart <= $rangeEnd) {
continue;
}
}
$form_state->setErrorByName(
$fieldName,
$this->t('HTTP status codes must be comma-separated or newline-separated 3-digit codes or ranges such as 200-299 or 500-599.')
);
return;
}
}
private function validateRegexFilters(FormStateInterface $form_state, string $fieldName, string $value, string $label): void {
foreach ($this->parseFilterLines($value) as $filter) {
if (!preg_match('/^\/.*\/$/', $filter)) {
continue;
}
if (@preg_match($filter, '') === FALSE) {
$form_state->setErrorByName(
$fieldName,
$this->t('@label filter contains an invalid regular expression: @filter', [
'@label' => $label,
'@filter' => $filter,
])
);
return;
}
}
}
/**
* Whether a value is an absolute URL with one of the given schemes.
*
* @param array<int, string> $schemes
*/
private function isUrlWithScheme(string $value, array $schemes): bool {
$parts = parse_url($value);
$scheme = is_array($parts) && is_string($parts['scheme'] ?? NULL) ? strtolower($parts['scheme']) : '';
return filter_var($value, FILTER_VALIDATE_URL) !== FALSE && in_array($scheme, $schemes, TRUE);
}
/**
* @param mixed $value
*/
private function stringValue($value): string {
if (is_string($value)) {
return $value;
}
if (is_int($value) || is_float($value)) {
return (string) $value;
}
return '';
}
/**
* @param mixed $value
*/
private function intValue($value): int {
if (is_int($value)) {
return $value;
}
if (is_numeric($value)) {
return (int) $value;
}
return 0;
}
/**
* @param mixed $value
*/
private function floatValue($value): float {
if (is_float($value)) {
return $value;
}
if (is_int($value)) {
return (float) $value;
}
if (is_numeric($value)) {
return (float) $value;
}
return 0.0;
}
}