1
0
Fork 0
mirror of synced 2024-06-01 10:29:48 +12:00
appwrite/src/Appwrite/Platform/Workers/UsageHook.php

104 lines
3.6 KiB
PHP
Raw Normal View History

2023-10-25 21:38:44 +13:00
<?php
namespace Appwrite\Platform\Workers;
use Utopia\App;
use Utopia\Database\Document;
use Utopia\Database\Exception\Duplicate;
use Utopia\Platform\Action;
use Utopia\CLI\Console;
use Swoole\Timer;
2023-12-25 22:32:40 +13:00
use Utopia\Database\DateTime;
2023-10-25 21:38:44 +13:00
class UsageHook extends Usage
{
public static function getName(): string
{
return 'usageHook';
}
public function __construct()
{
$this
->setType(Action::TYPE_WORKER_START)
->inject('register')
2023-12-25 07:38:15 +13:00
->inject('getProjectDB')
->callback(function ($register, callable $getProjectDB) {
$this->action($register, $getProjectDB);
2023-10-25 21:38:44 +13:00
})
;
}
/**
* @param $register
2023-12-25 07:38:15 +13:00
* @param $getProjectDB
2023-10-25 21:38:44 +13:00
* @return void
*/
2023-12-25 07:38:15 +13:00
public function action($register, $getProjectDB): void
2023-10-25 21:38:44 +13:00
{
2023-12-25 22:32:40 +13:00
$interval = (int) App::getEnv('_APP_USAGE_AGGREGATION_INTERVAL', '60000');
Timer::tick($interval, function () use ($register, $getProjectDB) {
$offset = count(self::$stats);
$projects = array_slice(self::$stats, 0, $offset, true);
array_splice(self::$stats, 0, $offset);
foreach ($projects as $data) {
$numberOfKeys = !empty($data['keys']) ? count($data['keys']) : 0;
2024-01-19 05:52:20 +13:00
$projectInternalId = $data['project']->getInternalId();
$database = $data['project']['database'] ?? '';
console::warning('Ticker started ' . DateTime::now());
2023-12-25 22:32:40 +13:00
if ($numberOfKeys === 0) {
continue;
}
try {
$dbForProject = $getProjectDB($data['project']);
foreach ($data['keys'] ?? [] as $key => $value) {
if ($value == 0) {
continue;
}
2023-10-25 21:38:44 +13:00
2023-12-25 22:32:40 +13:00
foreach ($this->periods as $period => $format) {
$time = 'inf' === $period ? null : date($format, time());
$id = \md5("{$time}_{$period}_{$key}");
2023-10-25 21:38:44 +13:00
2023-12-25 22:32:40 +13:00
try {
2024-02-01 23:21:50 +13:00
$dbForProject->createDocument('stats', new Document([
2023-10-25 21:38:44 +13:00
'$id' => $id,
'period' => $period,
'time' => $time,
'metric' => $key,
'value' => $value,
'region' => App::getEnv('_APP_REGION', 'default'),
2023-12-25 22:32:40 +13:00
]));
} catch (Duplicate $th) {
if ($value < 0) {
$dbForProject->decreaseDocumentAttribute(
2024-02-01 23:21:50 +13:00
'stats',
2023-12-25 22:32:40 +13:00
$id,
'value',
abs($value)
);
} else {
$dbForProject->increaseDocumentAttribute(
2024-02-01 23:21:50 +13:00
'stats',
2023-12-25 22:32:40 +13:00
$id,
'value',
$value
);
2023-10-25 21:38:44 +13:00
}
}
}
}
} catch (\Throwable $e) {
2023-12-25 22:32:40 +13:00
console::error(DateTime::now() . ' ' . $projectInternalId . ' ' . $e->getMessage());
2023-10-25 21:38:44 +13:00
}
2023-12-25 22:32:40 +13:00
}
});
2023-10-25 21:38:44 +13:00
}
}