|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Sentry\ClientReport; |
| 6 | + |
| 7 | +use Sentry\Event; |
| 8 | +use Sentry\State\HubAdapter; |
| 9 | +use Sentry\Transport\DataCategory; |
| 10 | + |
| 11 | +class ClientReportAggregator |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var self |
| 15 | + */ |
| 16 | + private static $instance; |
| 17 | + |
| 18 | + /** |
| 19 | + * Nested array for local aggregation. The first key is the category and the second one is the reason. |
| 20 | + * |
| 21 | + * ``` |
| 22 | + * [ |
| 23 | + * 'example-category' => [ |
| 24 | + * 'example-reason' => 10 |
| 25 | + * ] |
| 26 | + * ] |
| 27 | + *``` |
| 28 | + * |
| 29 | + * @var array<array<string, int>> |
| 30 | + */ |
| 31 | + private $reports = []; |
| 32 | + |
| 33 | + public function add(DataCategory $category, Reason $reason, int $quantity): void |
| 34 | + { |
| 35 | + $category = $category->getValue(); |
| 36 | + $reason = $reason->getValue(); |
| 37 | + if ($quantity <= 0) { |
| 38 | + $client = HubAdapter::getInstance()->getClient(); |
| 39 | + if ($client !== null) { |
| 40 | + $logger = $client->getOptions()->getLoggerOrNullLogger(); |
| 41 | + $logger->debug('Dropping Client report with category={category} and reason={reason} because quantity is zero or negative ({quantity})', [ |
| 42 | + 'category' => $category, |
| 43 | + 'reason' => $reason, |
| 44 | + 'quantity' => $quantity, |
| 45 | + ]); |
| 46 | + } |
| 47 | + |
| 48 | + return; |
| 49 | + } |
| 50 | + $this->reports[$category][$reason] = ($this->reports[$category][$reason] ?? 0) + $quantity; |
| 51 | + } |
| 52 | + |
| 53 | + public function flush(): void |
| 54 | + { |
| 55 | + if (empty($this->reports)) { |
| 56 | + return; |
| 57 | + } |
| 58 | + $reports = []; |
| 59 | + foreach ($this->reports as $category => $reasons) { |
| 60 | + foreach ($reasons as $reason => $quantity) { |
| 61 | + $reports[] = new DiscardedEvent($category, $reason, $quantity); |
| 62 | + } |
| 63 | + } |
| 64 | + $event = Event::createClientReport(); |
| 65 | + $event->setClientReports($reports); |
| 66 | + |
| 67 | + $client = HubAdapter::getInstance()->getClient(); |
| 68 | + |
| 69 | + // Reset the client reports only if we successfully sent an event. If it fails it |
| 70 | + // can be sent on the next flush, or it gets discarded anyway. |
| 71 | + if ($client !== null && $client->captureEvent($event) !== null) { |
| 72 | + $this->reports = []; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + public static function getInstance(): self |
| 77 | + { |
| 78 | + if (self::$instance === null) { |
| 79 | + self::$instance = new self(); |
| 80 | + } |
| 81 | + |
| 82 | + return self::$instance; |
| 83 | + } |
| 84 | +} |
0 commit comments