keloola / quota
Billing quota management for Keloola apps. Supports snapshot (fixed) and counter (monthly-reset) quota metrics integrated with the pricing & subscription model.
Requires
- php: ^8.0|^8.2|^8.4
- guzzlehttp/guzzle: ^7.8.2
- illuminate/cache: ^10.0|^11.0|^12|^13
- illuminate/console: ^10.0|^11.0|^12|^13
- illuminate/database: ^10.0|^11.0|^12|^13
- illuminate/encryption: ^10.0|^11.0|^12|^13
- illuminate/http: ^10.0|^11.0|^12|^13
- illuminate/support: ^10.0|^11.0|^12|^13
Requires (Dev)
- orchestra/testbench: ^9.0|^10
- phpunit/phpunit: ^10.0|^11.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Package Laravel untuk mengelola billing quota per-app. Mendukung dua tipe quota:
| Type | Perilaku | Contoh |
|---|---|---|
snapshot |
Quota tetap/fixed. Nilai usage mencerminkan kondisi saat ini, naik-turun mengikuti data, tidak pernah di-reset otomatis. | Jumlah user, storage space, jumlah hardware, jumlah ebook |
counter |
Quota yang di-reset setiap bulan (per periode billing). Hanya bertambah sampai reset. | Jumlah transaksi, automation run |
Terintegrasi dengan model QuotaMetric dan AppPlanQuota dari ERD Pricing & Subscription Anda.
Instalasi
Install via composer:
composer require keloola/quota
Publish & jalankan migration:
php artisan vendor:publish --tag=keloola-quota-config php artisan vendor:publish --tag=keloola-quota-migrations php artisan migrate
Migration juga otomatis ter-load lewat
loadMigrationsFrom, jadiphp artisan migratebisa langsung jalan tanpa publish.
Konfigurasi referensi tabel
Package tidak memiliki tabel apps, app_plans, dan organizations. Di config/keloola-quota.php atur tipe kolom dan apakah pakai foreign key constraint:
'references' => [ 'app' => ['table' => 'apps', 'column' => 'id', 'type' => 'unsignedBigInteger'], 'app_plan' => ['table' => 'app_plans', 'column' => 'id', 'type' => 'unsignedBigInteger'], 'organization' => ['table' => 'organizations', 'column' => 'id', 'type' => 'uuid'], 'constrained' => false, // set true bila tabel referensi ada di DB yang sama ],
Di setup SSO/distributed (tabel apps ada di service lain), biarkan constrained => false.
Tabel yang dibuat
quota_metrics— definisi metrik per app (type= snapshot|counter)app_plan_quotas— limit aktual tiap metrik per plan (limit,is_unlimited)quota_usages— pemakaian per organization per metrik (counter punyaperiod_key)quota_usage_logs— audit trail setiap perubahan
Penggunaan
use Keloola\Quota\Facades\Quota; // Cek apakah masih bisa menambah transaksi $can = Quota::canConsume('transactions', 1); // Catat 1 transaksi (counter — akan reset bulan depan) Quota::increment('transactions', 1, ['ref' => $invoice->id]); // Tambah user (snapshot — naik turun, tidak di-reset) Quota::increment('users'); // User dihapus Quota::decrement('users'); // Set absolut (cocok untuk storage yang dihitung ulang dari file) Quota::set('storage_mb', 4096); // Sisa & laporan $sisa = Quota::remaining('storage_mb'); // null = unlimited $report = Quota::report();
Bila config('keloola-quota.strict') true (default), increment yang melewati limit melempar QuotaExceededException:
use Keloola\Quota\Exceptions\QuotaExceededException; try { Quota::increment('transactions'); } catch (QuotaExceededException $e) { return response()->json(['message' => 'Kuota transaksi habis untuk bulan ini'], 429); }
Context Middleware (Otomatis dari JWT SSO)
Bila aplikasi satelit Anda menerima request dengan Bearer JWT Token dari SSO, Anda dapat menggunakan middleware keloola.quota.context. Middleware ini akan otomatis menembak endpoint SSO (/api/jwt/user), menarik data profil, dan men-set konteks quota (App ID, Organization ID, dan Plan ID) ke Facade.
// di rute aplikasi satelit Anda Route::middleware(['keloola.quota.context'])->group(function () { Route::post('/transactions', function () { // Konteks app, org, dan plan sudah di-set oleh middleware // sehingga Anda cukup memanggil metriknya saja: Quota::increment('transactions'); }); });
Pastikan Anda mengatur konfigurasi SSO di .env aplikasi satelit:
KELOOLA_AUTH_SSO_HOST=http://sso-keloola.test KELOOLA_AUTH_APP_ID=2
Catatan Validasi:
- Middleware ini secara otomatis memvalidasi token JWT. Jika token kosong atau tidak valid, middleware akan mengembalikan pesan error
401 Unauthorized.- Middleware akan mencocokkan
KELOOLA_AUTH_APP_IDdengan dataapplicationspada JWT. Jika aplikasi tidak ditemukan atau array aplikasi kosong, akan dikembalikan pesan error403 Forbidden.
Check Quota Middleware
Selain memanggil Quota::canConsume() secara manual di controller, Anda juga bisa menggunakan middleware keloola.quota.check untuk memblokir request di level route jika kuota tidak mencukupi. Middleware ini menerima parameter berupa metric_code dan opsional amount (default: 1).
Penting: Anda harus meletakkan middleware keloola.quota.context sebelum middleware ini agar konteks kuota sudah disiapkan.
// Cek apakah masih memiliki kuota transactions (amount: 1) Route::post('/transactions', [TransactionController::class, 'store']) ->middleware(['keloola.quota.context', 'keloola.quota.check:transactions']); // Cek dengan amount yang spesifik (misal butuh 5 kuota) Route::post('/bulk-transactions', [TransactionController::class, 'bulkStore']) ->middleware(['keloola.quota.context', 'keloola.quota.check:transactions,5']);
Jika kuota tidak cukup, akan muncul response JSON (429 Too Many Requests). Pesan error akan menyesuaikan bahasa yang diatur pada aplikasi (contoh: config/app.php locale id):
{
"message": "Anda telah melewati batas kuota untuk 'transactions'. Silakan tingkatkan paket Anda."
}
Reset counter bulanan
Jadwalkan command di routes/console.php (Laravel 11+) atau Kernel:
use Illuminate\Support\Facades\Schedule; Schedule::command('keloola-quota:reset-counters')->monthlyOn(1, '00:05');
Reset juga terjadi lazy: saat usage counter diakses pada periode baru, period_key otomatis berganti dan nilai mulai dari 0. Command hanya untuk membersihkan/mencatat secara eksplisit.
Plan & Metrik default (QuotaSeeder)
Seeder QuotaSeeder mendefinisikan metrik dan limit untuk 5 app. Sesuaikan map $apps dan $plans dengan id asli di DB Anda, lalu:
php artisan db:seed --class="Keloola\Quota\Database\Seeders\QuotaSeeder"
| App | Metrik | Type |
|---|---|---|
| Accounting | Jumlah Transaksi | counter |
| Jumlah User | snapshot | |
| Jumlah Invoice, Jurnal | counter | |
| Cloud Storage | Storage Space (MB), Jumlah File, User | snapshot |
| POS | Jumlah Transaksi | counter |
| Jumlah Outlet, Produk | snapshot | |
| Ebook | Jumlah Ebook | snapshot |
| Automate | Jumlah Hardware, User | snapshot |
| Jumlah Automation Run | counter |
Limit per plan (Basic / Pro / Enterprise) ada di dalam QuotaSeeder; Enterprise umumnya is_unlimited = true.
Provisioning saat instalasi (SSO push)
Alih-alih menjalankan seeder manual di tiap app, SSO dapat mendorong (push) definisi quota ke app saat sebuah organization meng-install app, dan kembali mendorong update saat plan/quota berubah. App menyimpan definisi ini lokal (quota_metrics + app_plan_quotas).
Sisi app (otomatis dari package)
Package mendaftarkan endpoint berikut secara otomatis:
POST /api/quota/provision # install + update (idempotent / upsert)
DELETE /api/quota/provision/{planId} # uninstall / plan dihapus
Secara default, endpoint dilindungi middleware keloola.quota.sso (dapat disesuaikan secara dinamis melalui config('keloola-quota.provisioning.middleware')).
Payload yang dikirim SSO
{
"app_id": 2,
"app_plan_id": 202,
"metrics": [
{ "name": "Storage Space", "code": "storage_mb", "type": "snapshot", "unit": "MB", "limit": 102400, "is_unlimited": false },
{ "name": "Jumlah User", "code": "users", "type": "snapshot", "unit": "users", "limit": 10, "is_unlimited": false }
]
}
Karena operasinya upsert, payload yang sama aman dikirim berulang — install pertama mengisi, perubahan plan memperbarui. Tidak perlu logika "sudah ada atau belum" di sisi SSO.
Sisi SSO
Contoh dispatcher ada di examples/sso-side/QuotaProvisioningDispatcher.php (bukan bagian package — disalin ke project keloola-sso). Pemicunya:
// Saat organization install app app(QuotaProvisioningDispatcher::class)->pushPlan($appPlan); // Otomatis saat limit diubah, lewat observer AppPlanQuota app(QuotaProvisioningDispatcher::class)->pushPlan($quota->appPlan);
Bungkus dalam queued job agar tidak memblok request bila app satelit lambat/down.
Catatan: provisioning ini hanya untuk definisi quota (limit per plan). Status subscription aktif/expired tetap dicek terpisah (mis. API call + cache ke SSO), karena status berubah lebih dinamis daripada definisi limit.
Pengecekan Quota Lintas Aplikasi (Cross-App)
Kadang-kadang satu aplikasi (misalnya SSO atau aplikasi lainnya) perlu mengecek limit quota dari aplikasi lain. Package ini menyediakan endpoint bawaan dan service khusus untuk kebutuhan tersebut.
Endpoint Pengecekan Quota
Package ini secara otomatis mengekspos endpoint GET /api/quota/check/{metricCode} yang mengembalikan status penggunaan quota untuk suatu metrik secara langsung (lengkap dengan limit, used, remaining, dan lain-lain).
// GET /api/quota/check/storage_space { "status": "ok", "data": { "code": "storage_space", "name": "Storage Space", "type": "snapshot", "unit": "MB", "used": 500, "limit": 1024, "is_unlimited": false, "remaining": 524, "percent": 48.8 } }
QuotaCheckService
Untuk melakukan panggilan ke endpoint tersebut dari backend PHP Anda, package ini menyediakan Keloola\Quota\Services\QuotaCheckService. Service ini dapat menangani pemanggilan lintas aplikasi (Cross-App) secara aman dan sudah diregistrasikan sebagai Singleton di Service Provider.
Penggunaan via API URL & Token Dinamis
use Keloola\Quota\Services\QuotaCheckService; $service = app(QuotaCheckService::class); $response = $service->checkQuota('https://app.keloola.in', 'storage_space', $jwtToken); if ($response && $response['status'] === 'ok') { $remaining = $response['data']['remaining']; // ... logic }
Pengaturan Konfigurasi Cross-App (Misal: Storage)
Package ini juga mendukung konfigurasi untuk layanan spesifik di config/keloola-quota.php. Anda bisa mengatur api_url dan metric_code via .env.
config/keloola-quota.php:
'storage' => [ 'api_url' => env('KELOOLA_FILE_API_URL', 'https://file.keloola.in'), 'metric_code' => env('KELOOLA_FILE_METRIC_CODE', 'storage_space'), ],
Penggunaan di Service:
$apiUrl = config('keloola-quota.storage.api_url'); $metricCode = config('keloola-quota.storage.metric_code'); $response = app(QuotaCheckService::class)->checkQuota($apiUrl, $metricCode, $jwtToken);
Konteks kuota service bersama (SQ-PKG-01)
Kuota aplikasi existing tetap memakai manager dan tabel lokal. Jalur service merupakan opt-in terpisah: service() selalu membuat scope baru dan tidak mewarisi app(), for() atau plan() dari manager lokal.
use Keloola\Quota\Facades\Quota; $context = Quota::service('keloola-file') ->app($authorizedOriginAppId) ->for($ssoOrganizationId) ->withToken($request->bearerToken()) ->context(); $context->serviceCode(); // keloola-file $context->parameters(); // organization_id (UUID SSO), app_id (integer)
Setiap selector mengembalikan scope baru. Simpan hasil chain jika hendak digunakan ulang. app_id ditentukan backend setelah pemeriksaan akses, dan organisasi harus UUID SSO; jangan memakai slug atau UUID lokal Keloola File. Kode metric dikirim eksplisit pada operasi client berikutnya, tanpa memilih metric pertama.
Konteks tidak lengkap/tidak valid melempar ServiceQuotaContextException; nilainya tidak berubah menjadi unlimited, saldo nol atau konteks lokal. Pembuatan konteks tidak membaca/mengubah tabel kuota lokal, tidak memanggil provider/upload, dan tidak menambahkan credential backend baru. Autentikasi Bearer dan otorisasi terkini tetap diverifikasi SSO ketika client mengirim request; konteks sendiri bukan izin memakai kuota.
json_encode($context) hanya berisi identitas, tanpa Bearer. Debug output menyamarkan token dan serialisasi PHP ditolak agar token tidak terbawa ke queue secara tidak sengaja. Simpan identifier/bukti hasil pada outbox, lalu resolve Bearer saat pelaporan. Jangan menyimpan Bearer pada metadata MinIO.
Middleware opsional keloola.quota.service.context:keloola-file tersedia untuk route yang telah melewati autentikasi dan pemetaan organisasi/aplikasi pada backend host. Mapper host harus mengisi request attributes berikut sebelum middleware ini:
use Keloola\Quota\Http\Middleware\SetServiceQuotaContext; $request->attributes->set(SetServiceQuotaContext::APP_ATTRIBUTE, $authorizedOriginAppId); $request->attributes->set(SetServiceQuotaContext::ORGANIZATION_ATTRIBUTE, $ssoOrganizationId); // Setelah middleware keloola.quota.service.context:keloola-file berjalan: $context = $request->attributes->get(SetServiceQuotaContext::CONTEXT_ATTRIBUTE);
Middleware hanya memakai Bearer dari header dan attributes backend; body/query/cookie tidak menjadi fallback. Konteks lama dihapus sebelum memetakan request baru. Ini tidak mengganti autentikasi host atau reservasi SSO. Middleware kuota lokal existing tetap kompatibel dan tidak diubah.
Membaca kuota bersama dari SSO (SQ-PKG-02)
use Keloola\Quota\Exceptions\ServiceQuotaException; use Keloola\Quota\Facades\Quota; $service = Quota::service('ai-chat') ->app($authorizedOriginAppId) ->for($ssoOrganizationId) ->withToken($request->bearerToken()); try { $summary = $service->check('ai_chat'); // kode metric dari konfigurasi SSO $available = $summary->available(); $isUnlimited = $summary->isUnlimited(); $isReady = $summary->isReady(); $grant = $service->grant($grantReference); $reservation = $service->reservation($reservationReference); } catch (ServiceQuotaException $e) { // Tangani sebagai unavailable/error; jangan izinkan operasi dengan saldo tebakan. $code = $e->errorCode(); $status = $e->httpStatus(); // null untuk kegagalan koneksi/kontrak respons $retryable = $e->isRetryable(); // klasifikasi, bukan retry otomatis }
check() mengembalikan ServiceQuotaSummary, grant() mengembalikan ServiceQuotaGrant, dan reservation() mengembalikan ServiceQuotaReservation. Ketiganya mendukung jsonSerialize() untuk seluruh data respons, termasuk sumber subscription/purchase, masa berlaku, penggunaan per aplikasi dan satuan metric. Referensi grant/reservasi diperlakukan sebagai identifier, bukan URL.
Client mengirim GET ke /api/services/{service_code}/quota/v1/check/{metric_code}, /grants/{reference}, atau /reservations/{reference} dengan query organization_id + app_id dan Bearer dari scope saat ini. Tidak ada pemanggilan profil, cache saldo/token, retry otomatis, redirect, atau perubahan saldo lokal. SSO tetap memeriksa izin terkini. check() hanya membaca kondisi saat itu; gunakan reservasi sebelum operasi bisnis.
available() bernilai 0 untuk kapasitas habis. Nilai null hanya berarti unlimited jika isUnlimited() bernilai true; penggunaan yang belum diketahui tetap null dengan status unavailable. isReady() berarti data penggunaan tersedia, termasuk saat depleted/over capacity, bukan jaminan cukup untuk sebuah operasi. Client tidak menghitung ulang available dari limit - used - reserved, tidak mengonversi satuan, dan tidak mereset storage setiap bulan.
Gunakan HTTPS untuk host SSO; HTTP hanya didukung untuk localhost/loopback pada pengujian lokal. Host dikonfigurasi backend, bukan berasal dari input request:
KELOOLA_AUTH_SSO_HOST=https://sso.example.com KELOOLA_QUOTA_SSO_TIMEOUT=15 KELOOLA_QUOTA_SSO_CONNECT_TIMEOUT=5
Config yang sudah pernah dipublish dapat menambahkan sso.timeout dan sso.connect_timeout; jika belum ada, client memakai default 15/5 detik. Timeout total harus lebih dari 0 sampai 120 detik; connect timeout lebih dari 0 sampai 30 detik dan tidak melebihi total. Error 401/403/404 diteruskan sebagai klasifikasi HTTP; 429/5xx dan gangguan koneksi ditandai retryable. Respons tidak lengkap/tidak sesuai konteks ditolak sebagai invalid_response, tanpa menyimpan body/request sensitif pada exception.
Reservasi dan hasil pemakaian bersama (SQ-PKG-03)
Gunakan scope service yang sama. Semua referensi harus berasal dari operasi bisnis yang stabil dan disimpan aplikasi; jangan membuat UUID baru pada setiap retry.
// Sebelum provider/upload. Jumlah dalam satuan dasar metric SSO. $held = $service->reserve( metricCode: 'ai_chat', amount: 1, reservationReference: $reservationReference, requestReference: $businessRequestReference, );
wasCreated() === true pada hasil reserve berarti SSO baru membuat hold (HTTP 201). HTTP 200 berarti replay, termasuk reservasi yang sudah committed/released/uncertain. Aplikasi hanya boleh memulai pekerjaan baru setelah hold baru berstatus held; replay dipulihkan memakai status bisnis yang tersimpan, bukan memanggil provider/upload kembali secara buta. Status held pada respons replay saja tidak membuktikan pekerjaan belum berjalan. Read reservation() mengembalikan wasCreated() === null.
Sesudah satu balasan final provider berhasil disimpan ke database aplikasi:
$committed = $service->commit( reservationReference: $reservationReference, resultReference: $commitResultReference, completionReference: $storedReplyReference, actualAmount: 1, );
Satu balasan final dihitung satu kali. Stream chunks dan tool/MCP calls tidak melakukan commit terpisah. Untuk hasil commit/release/uncertain, wasCreated() menunjukkan apakah event hasil baru, bukan izin memulai pekerjaan bisnis. SSO menetapkan jumlah tetap/bervariasi sesuai metric; package tidak mengasumsikan semua service berjumlah satu.
// Hanya setelah ada bukti bahwa operasi tidak menghasilkan balasan/file tersimpan. $released = $service->release($reservationReference, $releaseResultReference); // Jika hasil bisnis belum dapat dipastikan: tahan, jangan release karena timeout semata. $uncertain = $service->uncertain($reservationReference, $uncertainResultReference); // Finalisasi hold uncertain/lease lewat batas memerlukan permission reconcile dan bukti terverifikasi. $resolved = $service->commit($reservationReference, $resolveResultReference, $storedReplyReference, 1, $evidenceReference);
Reserve mengirim PUT /reservations/{reservationReference}. Commit/release/uncertain mengirim PUT /reservation-results/{resultReference}; release/uncertain mengirim completion_reference dan actual_amount bernilai null sesuai kontrak. evidenceReference opsional pada commit/release dan dikirim hanya jika diisi. Setiap PUT membawa organization_id + app_id pada JSON, beserta Bearer scope saat ini. Referensi event uncertain, commit, dan release berbeda karena payload outcome berbeda; replay event yang sama harus mempertahankan payload termasuk bukti.
Timeout/gangguan koneksi, 5xx, redirect atau acknowledgement rusak pada operasi tulis dapat berarti perubahan sudah tersimpan. ServiceQuotaException::outcomeUnknown() menandai ketidakpastian ini. Jangan mengganti referensi, me-release hold atau menjalankan provider lagi karena error tersebut. Baca reservasi, cocokkan dengan bukti bisnis, lalu replay operasi yang sama dengan payload yang sama. isRetryable() hanya klasifikasi kegagalan transport/HTTP, bukan jaminan operasi bisnis belum berjalan. Tidak ada retry, release, renew lease, atau pemanggilan provider otomatis.
Untuk snapshot storage dengan satuan dasar byte:
$held = $fileService->reserve('storage_space', $maximumBytes, $uploadReservationReference, $uploadRequestReference); // Aplikasi melakukan upload setelah hold baru; verifikasi ukuran objek yang benar-benar tersimpan. $stored = $fileService->commit($uploadReservationReference, $uploadResultReference, $storedFileReference, $actualBytes); // Setelah objek benar-benar terhapus dan bukti penghapusan tersedia: $deleted = $fileService->deleteResource($storedFileReference, $deletionEvidenceReference);
Jumlah harus integer positif dalam satuan dasar metric dan tidak dikonversi package. Commit aktual tidak boleh melebihi reservasi; SSO memeriksa kapasitas/permission saat finalisasi. deleteResource() melaporkan lifecycle ke SSO melalui DELETE /resources/{reference} dengan query app/organisasi/bukti; metode ini tidak menghapus objek MinIO. Hasil bertipe ServiceQuotaResource mempertahankan tombstone, sehingga laporan penghapusan berulang tidak membebaskan kapasitas dua kali. Webhook File memperbarui inventaris tanpa commit pemakaian lagi.
Outbox pelaporan dan recovery (SQ-PKG-04)
Outbox bersifat opt-in. Satu tabel service_quota_outbox menyimpan niat pelaporan, referensi bukti dan status pengiriman pada database aplikasi. Saldo kuota tetap berada di SSO. Migration outbox terpisah dari migration kuota lokal dan hanya otomatis dimuat ketika diaktifkan:
KELOOLA_QUOTA_OUTBOX_ENABLED=true # Jika memakai named connection, samakan dengan koneksi penyimpanan balasan/file: KELOOLA_QUOTA_OUTBOX_CONNECTION=pgsql
Jalankan migration pada database konsumen yang sesuai setelah konfigurasi. Tag publish opsional adalah keloola-quota-outbox-migrations; config lama yang sudah dipublish perlu menambahkan bagian outbox dari config package. Default enabled=false mempertahankan jalur lokal existing.
Backend host harus menyediakan dua adapter dan mendaftarkannya pada service container:
$this->app->bind(\Keloola\Quota\Contracts\ServiceQuotaEvidenceVerifier::class, AppQuotaEvidenceVerifier::class); $this->app->bind(\Keloola\Quota\Contracts\ServiceQuotaTokenResolver::class, AppQuotaTokenResolver::class);
ServiceQuotaEvidenceVerifier::verify($report, $connection) memeriksa bukti bisnis lokal: app/organisasi/actor, metric, balasan final atau ukuran/file aktual, serta kepastian kegagalan/penghapusan sesuai operasi. Pemeriksaan dilakukan di transaksi pembuatan report dan sebelum setiap pengiriman. Pada low-level outbox, verifier bawaan mengembalikan false sampai adapter host tersedia; mode operations menyediakan verifier bukti milik package.
ServiceQuotaTokenResolver::resolve($report) mengambil Bearer yang masih berlaku melalui integrasi auth host berdasarkan actor dan konteks report. Resolver tidak menerima token dari job/outbox. Pada low-level outbox, resolver bawaan mengembalikan null; mode operations menyediakan cache token terenkripsi. Token tidak tersedia, invalid atau ditolak SSO menahan laporan untuk perbaikan akses, tanpa credential backend baru atau fallback ke saldo lokal.
use Illuminate\Database\ConnectionInterface; use Keloola\Quota\Services\ServiceQuotaOutbox; use Keloola\Quota\Support\ServiceQuotaReport; // Provider sudah menghasilkan balasan; buat report dengan referensi yang stabil. $report = new ServiceQuotaReport( serviceCode: 'ai-chat', organizationId: $ssoOrganizationId, appId: $authorizedAppId, actorReference: $actorReference, metricCode: 'ai_chat', operation: 'committed', reference: $resultReference, reservationReference: $reservationReference, completionReference: $storedReplyReference, actualAmount: 1, evidenceReference: $evidenceReference, ); $outbox = app(ServiceQuotaOutbox::class); $reportId = $outbox->record($report, function (ConnectionInterface $connection) use ($replyValues, $evidenceValues) { // Contoh tabel host. Keduanya memakai connection yang sama dengan outbox. $connection->table('ai_replies')->insert($replyValues); $connection->table('quota_business_evidence')->insert($evidenceValues); });
Callback hanya menyimpan hasil/bukti database; jangan memanggil provider/upload di dalamnya. Record, balasan dan bukti rollback bersama jika salah satu gagal. Replay report yang identik mengembalikan ID semula tanpa menjalankan callback lagi; payload/dependency berbeda pada referensi sama ditolak. actorReference dan evidenceReference adalah identifier lokal yang stabil, bukan token atau isi balasan.
Setelah transaksi terluar selesai, kirim segera melalui app(ServiceQuotaOutboxWorker::class)->deliver($reportId) atau dispatch new DeliverServiceQuotaReport($reportId) melalui bus host sesudah commit. Import class dari Keloola\Quota\Services / Keloola\Quota\Jobs. Job hanya membawa UUID outbox. Pengiriman di dalam transaksi ditolak.
Jadwalkan recovery durabel agar laporan tetap ditemukan jika dispatch/job hilang atau worker mati:
Schedule::command('keloola-quota:deliver-reports --limit=100')->everyMinute();
Worker mengirim event/result yang sama, tanpa reserve atau provider baru. State pending menunggu pengiriman/backoff; processing memiliki claim 5 menit; delivered sudah diakui SSO; blocked memerlukan perbaikan bukti/auth/konflik. Retry memakai backoff 30 detik sampai 1 jam. Claim kadaluwarsa dapat diambil worker berikutnya; token claim mencegah acknowledgement worker lama menimpa claim baru. SSO tetap melakukan deduplikasi event. Tidak ada lock/transaksi database yang ditahan selama HTTP.
$outbox->inspect($reportId) membaca status/report. Setelah penyebab blocked diperbaiki, $outbox->resume($reportId) mengaktifkan ulang report yang sama. Ini tidak mengubah identitas, payload atau bukti. Timeout/5xx/ack rusak tetap pending, bukan release atau provider ulang; kode error aman disimpan tanpa raw exception/request/token.
Untuk deletion storage, buat report operation: 'deleted', reference: $storedFileReference, reservation/completion/actualAmount null, dan bukti penghapusan fisik. Jika commit file masih antre, gunakan $outbox->record($deletionReport, $persistDeletionEvidence, dependsOn: $fileCommitReportId) agar deletion menunggu parent delivered. Dependency harus menunjuk app/organisasi/service/metric yang sama; deletion juga harus menunjuk completion file parent yang sama. Report uncertain dapat menjadi parent report finalisasi dengan bukti baru dan referensi event baru.
File legacy yang sudah diinventarisasi SSO dapat dilaporkan deletion dengan referensi yang sama. Respons resource_not_found ditahan untuk rekonsiliasi inventaris; package tidak membuat upload/reservasi baru untuk menebak penggunaan lama. Impor baseline File adalah bagian rollout konsumen, bukan prasyarat pemakaian baru.
Pemulihan setelah provider berhasil bergantung pada hasil/bukti yang sudah tersimpan. Crash sebelum hasil provider disimpan memerlukan pemulihan memakai identifier provider atau penanganan uncertain oleh host; outbox tidak menjalankan provider ulang. Adapter auth/bukti production, integrasi Accounting/Projects/File dan publish package tetap tahap konsumen berikutnya.
Endpoint check dan laporan service (SQ-PKG-05)
Endpoint aplikasi existing GET /api/quota/check/{metricCode} dan Quota::report() tetap membaca kuota lokal sesuai konteks/kontrak existing. Pembacaan service memiliki route terpisah yang default-nya nonaktif:
// config/keloola-quota.php 'service_routes' => [ 'enabled' => true, // atau KELOOLA_QUOTA_SERVICE_ROUTES_ENABLED=true 'prefix' => 'api/quota', 'middleware' => ['auth:api', App\Http\Middleware\MapAuthorizedQuotaContext::class], ],
Gunakan guard/middleware autentikasi aplikasi Anda. Mapper host memeriksa akses dan mengisi attributes SetServiceQuotaContext::APP_ATTRIBUTE serta ORGANIZATION_ATTRIBUTE seperti contoh SQ-PKG-01. Package menambahkan keloola.quota.service.context sesudah middleware host, membaca service dari route dan Bearer dari header. Jangan memakai middleware kuota lokal yang memilih app/organisasi default untuk route service.
GET /api/quota/services/ai-chat/check/ai_chat Authorization: Bearer <current-token> Accept: application/json
App/organisasi berasal dari attributes backend yang telah diotorisasi. Endpoint ini tidak menerima query/body, termasuk app_id atau organization_id dari caller; gunakan pemetaan tenant host yang sudah diautentikasi. Parameter query/body ditolak, dan cookie token tidak menjadi fallback Bearer. SSO menerima identitas app/organisasi tersebut secara eksplisit melalui client dan tetap memeriksa izin terkini.
Respons {status: "ok", data: ...} berisi ringkasan SSO lengkap: metric/unit, limit, used, reserved, available, is_unlimited, usage_status, availability, resets_at, as_of, grants subscription/purchase beserta expiry dan usage_by_app. Storage mempertahankan satuan dasar tanpa konversi atau reset bulanan. Package tidak menghitung ulang saldo dari angka ringkasan. Tidak ada akses saldo/database lokal pada handler service.
200 bisa berisi usage unavailable dengan nilai null; hanya is_unlimited=true berarti unlimited. Error konteks memakai 401/422, query/body 400, penolakan SSO mempertahankan klasifikasi 401/403/404/409/422/429, kegagalan upstream/protokol 502 dan koneksi/unavailable/configuration 503. Respons controller/context service memuat Cache-Control: no-store; error tidak memuat data saldo atau raw response/credential upstream. Respons autentikasi/global handler host mengikuti kontrak host. Precheck bukan hold: lakukan reserve atomik sebelum provider/upload.
Untuk PHP, Quota::service(...)->app(...)->for(...)->withToken(...)->report($metricCode) mengembalikan ServiceQuotaSummary yang sama seperti check(), melalui satu request SSO. Metric tetap eksplisit; tidak menebak metric pertama atau menjumlahkan metric berbeda. Tidak ada endpoint tulis/reservasi proxy baru.
Route service dapat diaktifkan terpisah dari provisioning.register_routes dan outbox. Config yang sudah dipublish perlu menambahkan bagian service_routes; menonaktifkan route ini tidak mengubah endpoint lokal. Kontrak dan collection verifikasi berada di root workspace api/service-quota-package.openapi.yaml dan postman/collections/service-quota-package-check, sesuai penempatan artefak workspace.
Pengujian package
composer install
composer test
Jika dependencies Laravel/PHPUnit yang kompatibel sudah tersedia pada checkout lokal lain, tes juga dapat memakai autoloader tersebut tanpa mengubah dependencies checkout itu:
KELOOLA_QUOTA_TEST_AUTOLOAD=/absolute/path/vendor/autoload.php /absolute/path/vendor/bin/phpunit -c phpunit.xml
Bootstrap pengujian memetakan namespace package ke source checkout ini. Tes kompatibilitas lokal menggunakan SQLite in-memory dan tidak memuat database atau konfigurasi aplikasi konsumen.
Low-level durable service operations (explicit technical identity)
Opt in with keloola-quota.operations.enabled=true (or KELOOLA_QUOTA_OPERATIONS_ENABLED=true). This API owns operation replay/evidence, scoped encrypted credential caching, outbox reporting and scheduled recovery. Applications only map an already authorized context, run their service and persist the result. Existing low-level client/outbox APIs remain available; operation mode is off by default.
use Keloola\Quota\Services\ServiceQuotaOperations; use Keloola\Quota\Support\ServiceQuotaContext; $operations = app(ServiceQuotaOperations::class); // Derive these from authenticated host membership/config, never trust frontend scope or usage. $context = new ServiceQuotaContext($serviceCode, $authorizedOrganizationId, $configuredAppId, $loginToken); $operation = $operations->begin($context, 'user:'.$authorizedUserId, $stableRequestUuid, $metricCode, 1, $immutableInput); if ($operation->state === 'completed') { return $operation->result; } try { $result = $provider->reply($immutableInput); // Outside a database transaction; no automatic replay. $operations->complete($operation, $result, function ($connection) use ($result) { // Optional: persist host business evidence on THIS connection, atomically with quota evidence. $connection->table('messages')->insert(['body' => $result['answer']]); }); } catch (Throwable $error) { $operations->failed($operation); // Conservative uncertain default. Never calls the provider. throw $error; }
Use complete(..., billable: false) for a saved local/fallback result: it is replayable and releases the hold. failed($operation, definitive: true) is only for a host-verified refusal with no result or side effects; partial output, ambiguous timeout or service effects stay uncertain. Streaming applications call begin before opening SSE and complete after saving final output. Never invoke providers from the persistence callback or retry them from a reporting job.
begin requires UUID request identity, stable metric/amount/input, and authorized actor. Identity is scoped by service/organization/app/actor; changing input, metric or amount conflicts. Running/uncertain retries are blocked, completed retries return the saved result. Lists remain order-sensitive; object key order does not affect fingerprints. No credentials or original input are stored in operation/report rows; replay results may contain private data and are hidden from model serialization.
The package automatically loads two opt-in migrations for service_quota_operations and service_quota_outbox from its migration directories. Run migrations on the consumer database; no app model or copied migration is required. Call begin outside any host database transaction, so its execution claim is durable before service work starts. The operation model, outbox and persistence callback must use the same database connection (outbox.connection, default application connection). Keep migration basenames if publishing; do not publish timestamp-renamed copies. Package low-level/local quota migrations retain their existing behavior.
When enabled, the package schedules keloola-quota:deliver-reports --limit=100 every minute with overlap protection. This command first marks expired running executions uncertain and then retries due reports. Run the host Laravel scheduler. Set operations.schedule=false if the host deliberately supplies its own schedule. No provider retry is performed. Uncertain/blocked reports still require operational inspection.
Cache credentials are encrypted and scoped to actor/organization/app, retained up to operations.token_cache_seconds (capped at900 seconds and JWT expiry). Use persistent cache shared by web and scheduler with the same encryption key. Expired/rejected credentials block reporting; the next authorized begin refreshes its scoped credential and resumes matching authentication-blocked reports. There is no refresh-token mechanism or global backend secret. The host remains responsible for authentication and live SSO authorization.
Default evidence/token adapters handle package operations in operation mode. Hosts with custom low-level adapters can delegate package operation reports to OperationQuotaEvidenceVerifier / ServiceQuotaTokens while verifying their own evidence separately; existing explicit container bindings are retained. Do not override these with permissive evidence checks.
Configured service usage (recommended for application integrations)
ServiceQuotaUsage is the generic application integration for all configured services. Consumers do not need a custom quota service/model/migration. Configure profiles in keloola-quota.services with enabled, service_code, metric_code, amount. Enable operations.enabled for the package-owned tables/outbox/recovery. Unknown profiles fail closed; a configured disabled profile bypasses quota without resolving context or using the database.
'services' => [ 'ai_chat' => ['enabled' => true, 'service_code' => 'ai-chat', 'metric_code' => 'ai_chat', 'amount' => 1], 'documents' => ['enabled' => true, 'service_code' => 'document-analysis', 'metric_code' => 'pages', 'amount' => 3], ],
Bind ServiceQuotaUsage once in the host provider, supplying a closure (Request $request, string $serviceCode, array $scope): array that returns ['context' => new ServiceQuotaContext(...), 'actor_reference' => 'user:...']. Authorize membership and map the organization/app/token from trusted server context; the default resolver denies access. The package has no dependency on host User/Company tables. Configuration is cacheable; runtime authorization closures belong in service providers.
$usage = app(ServiceQuotaUsage::class); $operation = $usage->begin($request, 'ai_chat', $authorizedScope, $immutableServiceInput); // Disabled profile: operation is null. Otherwise, execute the service outside DB transactions. $result = $provider->reply($immutableServiceInput); $usage->complete($operation, $result, $optionalPersistenceCallback);
The package generates a UUID and writes service_quota_operations before making the first reservation request. Callers do not provide an operation/request UUID. Re-entry on the same server Request object and authorized scope reuses its generated ID; new HTTP Request objects always create new operations, even with identical input/client_message_id/request_id/Idempotency-Key. No heuristic time-window or payload deduplication is used. This is an intentional per-HTTP-call policy: public HTTP retries can incur new service work and quota. Internal reservation/report attempts retain references from durable operation/outbox rows. Do not automatically retry provider work after ambiguous/partial outcomes.
begin accepts an optional fifth integer amount override in metric base units (computed by trusted backend logic). complete(..., billable: false) saves a replayable local result and releases its hold. failed($operation, $error, $progress) classifies explicit400/401/403/404/422/429 refusals before any service progress as definitive; all other failures remain uncertain. Hosts with non-HTTP failure semantics can call ServiceQuotaOperations::failed with their verified definitive flag directly. Hosts must verify that result data represents a completed business action before completing/charging it. Token, transactions, outbox, scheduler and evidence rules from the low-level sections still apply.