From 67ef2ab5529d4487b86eec24226a409b895d4fd3 Mon Sep 17 00:00:00 2001 From: Darshan Date: Sat, 3 Jan 2026 15:13:34 +0530 Subject: [PATCH] add: return bucket actual size. --- .../Modules/Storage/Http/Buckets/Get.php | 39 +++++++++++++++++++ src/Appwrite/Utopia/Response/Model/Bucket.php | 6 +++ 2 files changed, 45 insertions(+) diff --git a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php index dd14feef6e..d2b002f6c3 100644 --- a/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php +++ b/src/Appwrite/Platform/Modules/Storage/Http/Buckets/Get.php @@ -8,6 +8,9 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; use Utopia\Database\Database; +use Utopia\Database\Document; +use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\UID; use Utopia\Platform\Action; use Utopia\Platform\Scope\HTTP; @@ -60,6 +63,42 @@ class Get extends Action throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } + $this->addBucketStorageSize($dbForProject, $bucket); + $response->dynamic($bucket, Response::MODEL_BUCKET); } + + private function addBucketStorageSize(Database $dbForProject, Document $bucket): void + { + $metric = str_replace( + '{bucketInternalId}', + $bucket->getSequence(), + METRIC_BUCKET_ID_FILES_STORAGE + ); + + /** + * StatsUsage does this create an ID - + * + * `$time = null;`\ + * `$id = md5("{$time}_{$period}_{$key}");` + * + * but when $time is null it just makes the $id as md5('_inf_' . $key); + * + * Why do this though?\ + * Using `getDocument()` below to leverage cache! + */ + $statsDocId = md5('_inf_' . $metric); + + $storageStats = Authorization::skip( + fn () => $dbForProject->getDocument( + 'stats', + $statsDocId, + [Query::select(['value'])] + ) + ); + + $totalSize = $storageStats->isEmpty() ? 0 : $storageStats->getAttribute('value', 0); + + $bucket->setAttribute('totalSize', $totalSize); + } } diff --git a/src/Appwrite/Utopia/Response/Model/Bucket.php b/src/Appwrite/Utopia/Response/Model/Bucket.php index f51c8b6527..707815eff0 100644 --- a/src/Appwrite/Utopia/Response/Model/Bucket.php +++ b/src/Appwrite/Utopia/Response/Model/Bucket.php @@ -92,6 +92,12 @@ class Bucket extends Model 'default' => true, 'example' => false, ]) + ->addRule('totalSize', [ + 'type' => self::TYPE_INTEGER, + 'description' => 'Total size of this bucket in bytes.', + 'default' => 0, + 'example' => 128, + ]) ; }