1
0
Fork 0
mirror of synced 2024-05-17 11:12:41 +12:00
appwrite/src/Appwrite/Usage/Calculators/Database.php

365 lines
12 KiB
PHP
Raw Normal View History

2022-06-13 22:56:24 +12:00
<?php
2022-08-09 13:22:18 +12:00
namespace Appwrite\Usage\Calculators;
2022-06-13 22:56:24 +12:00
2022-07-12 03:12:41 +12:00
use Exception;
use Utopia\App;
2022-08-09 13:22:18 +12:00
use Appwrite\Usage\Calculator;
2022-08-26 02:56:15 +12:00
use DateTime;
2022-08-09 13:22:18 +12:00
use Utopia\Database\Database as UtopiaDatabase;
2022-06-13 23:11:26 +12:00
use Utopia\Database\Document;
use Utopia\Database\Exception\Authorization;
use Utopia\Database\Exception\Structure;
2022-08-12 11:53:52 +12:00
use Utopia\Database\Query;
2022-06-13 22:56:24 +12:00
2022-08-09 13:22:18 +12:00
class Database extends Calculator
2022-06-13 22:56:24 +12:00
{
2022-08-09 13:22:18 +12:00
protected array $periods = [
[
'key' => '30m',
'multiplier' => 1800,
],
[
'key' => '1d',
'multiplier' => 86400,
],
];
public function __construct(string $region, UtopiaDatabase $database, callable $errorHandler = null)
2022-06-13 22:56:24 +12:00
{
parent::__construct($region);
2022-06-13 22:56:24 +12:00
$this->database = $database;
2022-06-13 23:11:26 +12:00
$this->errorHandler = $errorHandler;
2022-06-13 22:56:24 +12:00
}
2022-07-12 03:12:41 +12:00
2022-06-13 23:11:26 +12:00
/**
2022-08-09 13:22:18 +12:00
* Create Per Period Metric
*
2022-08-09 13:22:18 +12:00
* Create given metric for each defined period
2022-06-13 23:11:26 +12:00
*
* @param string $projectId
* @param string $metric
* @param int $value
* @param bool $monthly
2022-06-13 23:11:26 +12:00
* @return void
* @throws Authorization
* @throws Structure
2022-06-13 23:11:26 +12:00
*/
2022-08-09 13:22:18 +12:00
protected function createPerPeriodMetric(string $projectId, string $metric, int $value, bool $monthly = false): void
2022-06-13 22:56:24 +12:00
{
2022-06-13 23:11:26 +12:00
foreach ($this->periods as $options) {
$period = $options['key'];
2022-08-25 18:45:05 +12:00
$date = new \DateTime();
if ($period === '30m') {
$minutes = $date->format('i') >= '30' ? "30" : "00";
$time = $date->format('Y-m-d H:' . $minutes . ':00');
} elseif ($period === '1d') {
$time = $date->format('Y-m-d 00:00:00');
} else {
throw new Exception("Period type not found", 500);
}
2022-08-09 13:22:18 +12:00
$this->createOrUpdateMetric($projectId, $metric, $period, $time, $value);
}
2022-07-12 03:12:41 +12:00
2022-08-09 13:22:18 +12:00
// Required for billing
if ($monthly) {
2022-08-26 02:56:15 +12:00
$time = DateTime::createFromFormat('Y-m-d\TH:i:s.v', \date('Y-m-01\T00:00:00.000'))->format(DateTime::RFC3339);
2022-08-09 13:22:18 +12:00
$this->createOrUpdateMetric($projectId, $metric, '1mo', $time, $value);
}
}
2022-08-09 13:22:18 +12:00
/**
* Create or Update Metric
*
2022-08-09 13:22:18 +12:00
* Create or update each metric in the stats collection for the given project
*
* @param string $projectId
* @param string $metric
* @param string $period
2022-08-25 18:45:05 +12:00
* @param string $time
2022-08-09 13:22:18 +12:00
* @param int $value
*
* @return void
* @throws Authorization
* @throws Structure
2022-08-09 13:22:18 +12:00
*/
2022-08-25 18:45:05 +12:00
protected function createOrUpdateMetric(string $projectId, string $metric, string $period, string $time, int $value): void
2022-08-09 13:22:18 +12:00
{
$id = \md5("{$time}_{$period}_{$metric}");
$this->database->setNamespace('_' . $projectId);
2022-08-09 13:22:18 +12:00
try {
$document = $this->database->getDocument('stats', $id);
if ($document->isEmpty()) {
$this->database->createDocument('stats', new Document([
'$id' => $id,
'period' => $period,
'time' => $time,
'metric' => $metric,
'value' => $value,
'region' => $this->region,
2022-08-10 19:59:16 +12:00
'type' => 2, // these are cumulative metrics
2022-08-09 13:22:18 +12:00
]));
} else {
$this->database->updateDocument(
'stats',
$document->getId(),
$document->setAttribute('value', $value)
);
}
} catch (\Exception$e) { // if projects are deleted this might fail
if (is_callable($this->errorHandler)) {
call_user_func($this->errorHandler, $e, "sync_project_{$projectId}_metric_{$metric}");
} else {
throw $e;
2022-06-13 23:11:26 +12:00
}
}
2022-06-13 22:56:24 +12:00
}
2022-06-13 23:11:26 +12:00
/**
* Foreach Document
*
2022-06-13 23:11:26 +12:00
* Call provided callback for each document in the collection
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
* @param string $collection
* @param array $queries
* @param callable $callback
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return void
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
2022-08-09 13:22:18 +12:00
protected function foreachDocument(string $projectId, string $collection, array $queries, callable $callback): void
2022-06-13 22:56:24 +12:00
{
$limit = 50;
$results = [];
$sum = $limit;
$latestDocument = null;
while ($sum === $limit) {
2022-06-14 12:58:25 +12:00
try {
2022-08-12 11:53:52 +12:00
$paginationQueries = [Query::limit($limit)];
if ($latestDocument !== null) {
$paginationQueries[] = Query::cursorAfter($latestDocument);
}
$this->database->setNamespace('_' . $projectId);
2022-08-12 11:53:52 +12:00
$results = $this->database->find($collection, \array_merge($paginationQueries, $queries));
} catch (\Exception $e) {
2022-06-14 12:58:25 +12:00
if (is_callable($this->errorHandler)) {
2022-06-15 11:40:56 +12:00
call_user_func($this->errorHandler, $e, "fetch_documents_project_{$projectId}_collection_{$collection}");
2022-06-14 12:58:25 +12:00
return;
} else {
throw $e;
}
}
2022-06-14 03:49:27 +12:00
if (empty($results)) {
return;
}
2022-06-13 22:56:24 +12:00
$sum = count($results);
foreach ($results as $document) {
if (is_callable($callback)) {
$callback($document);
}
}
$latestDocument = $results[array_key_last($results)];
}
}
2022-06-13 23:11:26 +12:00
/**
* Sum
*
* Calculate sum of an attribute of documents in collection
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
* @param string $collection
* @param string $attribute
* @param string|null $metric
* @param int $multiplier
2022-06-13 23:11:26 +12:00
* @return int
2022-07-12 03:12:41 +12:00
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
2022-08-09 13:22:18 +12:00
private function sum(string $projectId, string $collection, string $attribute, string $metric = null, int $multiplier = 1): int
2022-06-13 22:56:24 +12:00
{
2022-06-24 18:08:25 +12:00
$this->database->setNamespace('_' . $projectId);
2022-06-14 12:58:25 +12:00
try {
2022-08-09 13:22:18 +12:00
$sum = $this->database->sum($collection, $attribute);
$sum = (int) ($sum * $multiplier);
if (!is_null($metric)) {
2022-08-09 13:22:18 +12:00
$this->createPerPeriodMetric($projectId, $metric, $sum);
}
2022-06-14 12:58:25 +12:00
return $sum;
2022-07-12 03:12:41 +12:00
} catch (Exception $e) {
2022-06-14 12:58:25 +12:00
if (is_callable($this->errorHandler)) {
2022-06-15 11:40:56 +12:00
call_user_func($this->errorHandler, $e, "fetch_sum_project_{$projectId}_collection_{$collection}");
2022-06-14 12:58:25 +12:00
} else {
throw $e;
}
}
2022-08-09 13:22:18 +12:00
return 0;
2022-06-13 22:56:24 +12:00
}
2022-06-13 23:11:26 +12:00
/**
* Count
*
2022-06-13 23:11:26 +12:00
* Count number of documents in collection
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
* @param string $collection
* @param ?string $metric
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return int
2022-07-12 03:12:41 +12:00
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
private function count(string $projectId, string $collection, ?string $metric = null): int
2022-06-13 22:56:24 +12:00
{
2022-06-24 18:08:25 +12:00
$this->database->setNamespace('_' . $projectId);
2022-06-14 12:58:25 +12:00
try {
$count = $this->database->count($collection);
if (!is_null($metric)) {
2022-08-09 13:22:18 +12:00
$this->createPerPeriodMetric($projectId, (string) $metric, $count);
}
2022-06-14 12:58:25 +12:00
return $count;
2022-07-12 03:12:41 +12:00
} catch (Exception $e) {
2022-06-14 12:58:25 +12:00
if (is_callable($this->errorHandler)) {
2022-06-15 11:40:56 +12:00
call_user_func($this->errorHandler, $e, "fetch_count_project_{$projectId}_collection_{$collection}");
2022-06-14 12:58:25 +12:00
} else {
throw $e;
}
}
2022-08-09 13:22:18 +12:00
return 0;
2022-06-13 22:56:24 +12:00
}
2022-06-13 23:11:26 +12:00
/**
* Deployments Total
*
2022-06-13 23:11:26 +12:00
* Total sum of storage used by deployments
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return int
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
private function deploymentsTotal(string $projectId): int
{
2022-08-09 13:22:18 +12:00
return $this->sum($projectId, 'deployments', 'size', 'deployments.$all.storage.size');
2022-06-13 23:11:26 +12:00
}
/**
* Users Stats
*
2022-06-13 23:11:26 +12:00
* Metric: users.count
*
* @param string $projectId
*
* @return void
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
private function usersStats(string $projectId): void
{
2022-08-09 13:22:18 +12:00
$this->count($projectId, 'users', 'users.$all.count.total');
2022-06-13 23:11:26 +12:00
}
/**
* Storage Stats
*
2022-08-09 13:22:18 +12:00
* Metrics: buckets.$all.count.total, files.$all.count.total, files.bucketId,count.total,
* files.$all.storage.size, files.bucketId.storage.size, project.$all.storage.size
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return void
* @throws Authorization
* @throws Structure
2022-06-13 23:11:26 +12:00
*/
private function storageStats(string $projectId): void
{
$projectFilesTotal = 0;
$projectFilesCount = 0;
2022-08-09 13:22:18 +12:00
$metric = 'buckets.$all.count.total';
2022-06-13 23:11:26 +12:00
$this->count($projectId, 'buckets', $metric);
2022-06-14 03:49:27 +12:00
$this->foreachDocument($projectId, 'buckets', [], function ($bucket) use (&$projectFilesCount, &$projectFilesTotal, $projectId,) {
2022-08-09 13:22:18 +12:00
$metric = "files.{$bucket->getId()}.count.total";
2022-06-14 12:40:33 +12:00
$count = $this->count($projectId, 'bucket_' . $bucket->getInternalId(), $metric);
2022-06-13 23:11:26 +12:00
$projectFilesCount += $count;
2022-08-09 13:22:18 +12:00
$metric = "files.{$bucket->getId()}.storage.size";
2022-06-13 23:11:26 +12:00
$sum = $this->sum($projectId, 'bucket_' . $bucket->getInternalId(), 'sizeOriginal', $metric);
$projectFilesTotal += $sum;
});
2022-08-09 13:22:18 +12:00
$this->createPerPeriodMetric($projectId, 'files.$all.count.total', $projectFilesCount);
$this->createPerPeriodMetric($projectId, 'files.$all.storage.size', $projectFilesTotal);
2022-06-13 23:11:26 +12:00
2022-08-09 13:22:18 +12:00
$deploymentsTotal = $this->deploymentsTotal($projectId);
$this->createPerPeriodMetric($projectId, 'project.$all.storage.size', $projectFilesTotal + $deploymentsTotal);
2022-06-13 23:11:26 +12:00
}
/**
* Database Stats
*
2022-06-13 23:11:26 +12:00
* Collect all database stats
2022-08-09 13:22:18 +12:00
* Metrics: databases.$all.count.total, collections.$all.count.total, collections.databaseId.count.total,
* documents.$all.count.all, documents.databaseId.count.total, documents.databaseId/collectionId.count.total
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @param string $projectId
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return void
* @throws Authorization
* @throws Structure
2022-06-13 23:11:26 +12:00
*/
private function databaseStats(string $projectId): void
{
$projectDocumentsCount = 0;
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
$projectCollectionsCount = 0;
2022-06-13 23:11:26 +12:00
2022-08-09 13:22:18 +12:00
$this->count($projectId, 'databases', 'databases.$all.count.total');
2022-06-13 23:11:26 +12:00
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
$this->foreachDocument($projectId, 'databases', [], function ($database) use (&$projectDocumentsCount, &$projectCollectionsCount, $projectId) {
2022-08-09 13:22:18 +12:00
$metric = "collections.{$database->getId()}.count.total";
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
$count = $this->count($projectId, 'database_' . $database->getInternalId(), $metric);
$projectCollectionsCount += $count;
$databaseDocumentsCount = 0;
2022-06-13 23:11:26 +12:00
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
$this->foreachDocument($projectId, 'database_' . $database->getInternalId(), [], function ($collection) use (&$projectDocumentsCount, &$databaseDocumentsCount, $projectId, $database) {
2022-08-09 13:22:18 +12:00
$metric = "documents.{$database->getId()}/{$collection->getId()}.count.total";
Database layer (#3338) * database response model * database collection config * new database scopes * database service update * database execption codes * remove read write permission from database model * updating tests and fixing some bugs * server side tests are now passing * databases api * tests for database endpoint * composer update * fix error * formatting * formatting fixes * get database test * more updates to events and usage * more usage updates * fix delete type * fix test * delete database * more fixes * databaseId in attributes and indexes * more fixes * fix issues * fix index subquery * fix console scope and index query * updating tests as required * fix phpcs errors and warnings * updates to review suggestions * UI progress * ui updates and cleaning up * fix type * rework database events * update tests * update types * event generation fixed * events config updated * updating context to support multiple * realtime updates * fix ids * update context * validator updates * fix naming conflict * fix tests * fix lint errors * fix wprler and realtime tests * fix webhooks test * fix event validator and other tests * formatting fixes * removing leftover var_dumps * remove leftover comment * update usage params * usage metrics updates * update database usage * fix usage * specs update * updates to usage * fix UI and usage * fix lints * internal id fixes * fixes for internal Id * renaming services and related files * rename tests * rename doc link * rename readme * fix test name * tests: fixes for 0.15.x sync Co-authored-by: Torsten Dittmann <torsten.dittmann@googlemail.com>
2022-06-22 22:51:49 +12:00
$count = $this->count($projectId, 'database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $metric);
$projectDocumentsCount += $count;
$databaseDocumentsCount += $count;
});
2022-08-09 13:22:18 +12:00
$this->createPerPeriodMetric($projectId, "documents.{$database->getId()}.count.total", $databaseDocumentsCount);
2022-06-13 23:11:26 +12:00
});
2022-08-09 13:22:18 +12:00
$this->createPerPeriodMetric($projectId, 'collections.$all.count.total', $projectCollectionsCount);
$this->createPerPeriodMetric($projectId, 'documents.$all.count.total', $projectDocumentsCount);
2022-06-13 23:11:26 +12:00
}
/**
* Collect Stats
*
2022-06-13 23:11:26 +12:00
* Collect all database related stats
2022-06-14 03:49:27 +12:00
*
2022-06-13 23:11:26 +12:00
* @return void
* @throws Exception
2022-06-13 23:11:26 +12:00
*/
public function collect(): void
{
$this->foreachDocument('console', 'projects', [], function (Document $project) {
2022-06-24 18:08:25 +12:00
$projectId = $project->getInternalId();
$this->usersStats($projectId);
$this->databaseStats($projectId);
$this->storageStats($projectId);
2022-06-13 23:11:26 +12:00
});
}
2022-06-13 22:56:24 +12:00
}