appwrite/src/Appwrite/Event/Usage.php

80 lines
1.5 KiB
PHP
Raw Normal View History

2022-11-24 07:53:52 +00:00
<?php
namespace Appwrite\Event;
2024-03-06 17:34:21 +00:00
use Utopia\Database\Document;
2022-11-24 07:53:52 +00:00
use Utopia\Queue\Client;
use Utopia\Queue\Connection;
class Usage extends Event
{
protected array $metrics = [];
protected array $reduce = [];
2022-11-24 07:53:52 +00:00
public function __construct(protected Connection $connection)
{
2023-06-02 03:54:34 +00:00
parent::__construct($connection);
$this
->setQueue(Event::USAGE_QUEUE_NAME)
->setClass(Event::USAGE_CLASS_NAME);
2022-11-24 07:53:52 +00:00
}
/**
* Add reduce.
*
* @param Document $document
* @return self
*/
public function addReduce(Document $document): self
{
$this->reduce[] = $document;
return $this;
}
2022-11-24 07:53:52 +00:00
/**
2022-12-04 17:06:23 +00:00
* Add metric.
2022-11-24 07:53:52 +00:00
*
* @param string $key
2022-12-15 09:45:43 +00:00
* @param int $value
2022-11-24 07:53:52 +00:00
* @return self
*/
2022-12-15 09:45:43 +00:00
public function addMetric(string $key, int $value): self
2022-11-24 07:53:52 +00:00
{
2022-11-24 07:53:52 +00:00
$this->metrics[] = [
'key' => $key,
'value' => $value,
];
return $this;
}
/**
2022-12-04 17:06:23 +00:00
* Sends metrics to the usage worker.
2022-11-24 07:53:52 +00:00
*
2022-12-04 17:06:23 +00:00
* @return string|bool
2022-11-24 07:53:52 +00:00
*/
public function trigger(): string|bool
{
2024-11-08 20:55:53 +00:00
if ($this->paused) {
return false;
}
2025-01-16 07:44:47 +00:00
$this->trimFields();
2022-11-24 07:53:52 +00:00
$client = new Client($this->queue, $this->connection);
$result = $client->enqueue([
2025-01-16 07:44:47 +00:00
'project' => $this->project,
'reduce' => $this->reduce,
2022-11-24 07:53:52 +00:00
'metrics' => $this->metrics,
]);
$this->metrics = [];
return $result;
2022-11-24 07:53:52 +00:00
}
}