Repository navigation
feat: add self-hosted usage service - #13286
Conversation
|
Console companion draft: https://github.com/appwrite/vibes/pull/155 (kept draft until this backend PR is merged and available in a test image). |
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Greptile SummaryThe PR adds a self-hosted usage service backed by ClickHouse, including tenant-scoped ingestion and query APIs.
Confidence Score: 4/5The PR is not yet safe to merge because a failed post-delete usage sweep can permanently retain late usage rows after their project mapping is removed. The readiness-cache and team pre-purge issues are addressed, but the delete worker still catches and suppresses final-sweep failures after deleting project records, leaving queued late-arriving usage data without a retry or reconciliation path. Files Needing Attention: src/Appwrite/Platform/Workers/Deletes.php Important Files Changed
Reviews (8): Last reviewed commit: "fix(usage): span the swallowed post-dele..." | Re-trigger Greptile |
Every other schema in self-hosted Appwrite is created at boot by app/http.php -- platform DB, project DB, shared-tables metadata, bucket collections -- with a retry ladder and an already-exists skip. Usage was the only one with its own container, and Cloud has no equivalent: there an operator runs the setup script by hand against the migration endpoint. Gating `appwrite` on `service_completed_successfully` also meant an unhealthy ClickHouse stopped the API from starting at all, which lets analytics storage take down the core API. The gating was inconsistent too: only the dev override waited on the one-shot, so in the shipped compose it was an orphan sitting at Exited (0), which reads as a failure. Call Connection::setup() from the existing boot block instead. It retries on the same 15x2s ladder as the databases above so a cold start wins the race against ClickHouse, then gives up with a warning rather than blocking boot. Reads and ingestion already gate on Connection::isReady(), so both stay correct while the schema is missing. Keep bin/usage-setup and the CLI task -- they repair a dropped table without a restart, the closest analogue to Cloud's manual script -- and put its retry on the same ladder.
Cloud has to enforce plan history limits, the premium geo addon, and its
affiliate metric carve-out on the same two endpoints, and today it does
that by keeping a full copy of both actions. The copies have already
drifted behind this branch's gauge fixes, so the duplication is actively
losing correctness rather than merely costing lines.
Make the upstream actions subclassable instead:
- widen the dimension/filter/interval constants and the query helpers from
private to protected
- read them through `static::` so an override actually takes effect --
`self::` binds to the defining class and would silently ignore Cloud
- inject a `usagePolicy` object the actions consult before querying. The
self-hosted implementation allows everything, since self-hosted has no
plans, addons, or reseller namespaces. Cloud binds a subclass that
carries the checks its endpoints do today.
The policy is injected rather than hung off the action because actions are
shared across coroutines, so per-request state cannot live on `$this`.
Also fold `country` filters through Context::normalizeCountry() on the way
in. Writes have always stored the column lowercased, readers did not fold
the filter, and ClickHouse compares case-sensitively -- so
`equal("country", ["US"])` returned an empty series. Both sides now share
one rule, with a unit test pinning them together.
Cloud carried these two constants with the rationale attached; upstream now owns them, so bring the reasoning along rather than leaving bare values here and a duplicate definition there.
Cloud's stats-resources task carries a near-verbatim copy of this fold -- same method names, same three constants, same values -- so the two editions each own an arithmetic they should agree on. They had already diverged: Cloud opens its first window at `_APP_STATS_RESOURCES_INTERVAL` unfloored, so an interval below the 300s bucket size yields a window that closes before any whole bucket has elapsed and samples nothing at all. Subclassing does not work here: this task injects `usageConnection`, which Cloud's container does not define, and inject() is positional and cannot be dropped by a subclass. The fold is a well-defined domain concept and takes only a Usage instance, so it becomes Appwrite\Usage\Concurrency and both editions call it. Task drops 157 -> 63 lines. The flooring fix lives in the shared code, with a unit test that fails on the old unfloored behaviour.
The suite was added with the endpoints but never wired into the E2E matrix, so it has not run in CI once -- the endpoints were only ever covered by whatever ran locally. ClickHouse is in the default compose profile, so `compose up --wait` already starts it; the job needs no other setup. Marked functional so paratest parallelizes the single class per method, matching the other one-class suites.
Two real defects the project-wide scan caught: - app/http.php annotated $usageConnection with an aliased class name that PHPStan would not resolve in that docblock, so isEnabled() and setup() were both calls on an unknown type. Use the fully-qualified name and drop the now-unused alias. - the test fake bound $queued by reference before checking isset(), which created the array key as a side effect and made the guard always true. Read through the key instead and shift in place. Also return the Context setters to `static` rather than `self`, so a subclass can chain them. Cloud adds a team dimension on top of this class and chains its own setter after a dozen inherited ones; with `self` the chain degrades to the base type halfway through and the subclass method is unreachable. That is what kept Cloud's copy of every setter alive.
Three of the five _APP_EDITION checks this branch added were the wrong mechanism for what they were guarding. The one in Platform\Appwrite was simply dead: Cloud composes Core() plus its own modules through Appwrite\Cloud\Platform\Appwrite and never instantiates this class, so the guard could not fire there. The two in the shared Core services were load-bearing but env-dependent. Cloud registers its own stats-usage and stats-resources, and Core is added first, so without a guard getWorkerAction() would hand Cloud the generic worker instead of its billing-aware one -- silently, and only when _APP_EDITION happened to be unset. Move both registrations into the Usage module's own Services/Workers.php and Services/Tasks.php, which is where Databases and Functions already keep theirs. Cloud never registers that module, so the collision cannot occur regardless of environment. Verified with _APP_EDITION unset: Cloud drops from three duplicated usage actions to none, and usage-setup is no longer registered there at all, which matches Cloud provisioning its schema out-of-band. The remaining two guards stay, for reasons that are not registration: Deletes would begin purging Cloud's usage rows on project deletion, and Schedule would run a second usage loop alongside Cloud's own scheduler.
Removes the unit tests this branch introduced. The e2e suite covers the usage endpoints, and tests/unit/Usage/Fakes/Adapter.php only existed to serve them. Also allow utopia-php/usage ^0.14.0 rather than pinning 0.14.0 exactly, so patch releases come in without a lock edit. The lock still resolves 0.14.0; only its content hash changed. RegistrationTest keeps its Usage service entry -- that is not new coverage, it is the existing duplicate-worker assertion following the registration move.
Cloud's merged entitlement work asserts access, geo dimensions and history at three different points, and it has to: access is checked before the request is parsed so an unauthorised caller is refused rather than told whether their query was valid, while the geo gate needs the parsed filters and the history check needs the resolved window. A single assert() could only run after parsing, which turned that 401 into a 400. Match the three-call shape so Cloud can inherit the query unchanged. Gauges asserts history only, as Cloud's does -- it has no geo dimensions and no metric carve-out.
Cloud's version of this class, merged in appwrite-labs/cloud#5399, typed these; keep that when the two converge here.
vibes 0.6.0 includes appwrite/vibes#155, which enables the usage screens against the endpoints this branch adds. Older console builds have no UI for them.
ClickHouse readiness was cached forever after the first success, so later outages were treated as healthy and usage writes were dropped. Team-owned project deletes also never reached the tenant purge path.
The self-hosted stats-resources worker only counted rows, so the console's storage charts — which read the unified `storage` gauge Cloud writes per bucket, database, function, and site — stayed empty. Port Cloud's collectUnifiedStorage projection: per-resource storage bytes plus the files/collections/documents/deployments/builds companions and project totals, with explicit service/resourceType/resourceId tags. Flat dimensioned gauge aggregates also returned time: null, which crashes the console's top-resources parser; the window end now stands in, matching the flat max-aggregate precedent.
Team deletion removed the platform project records inside the action and purged ClickHouse afterwards, but retries reconstruct tenant sequences from those records — a purge failure after the delete left the tenants unrecoverable. Purge first, so a failure fails the message while a retry can still resolve the mapping, and sweep again after the delete for rows that landed in between (best-effort, logged). A purge returning false now also fails the message instead of being silently acknowledged.
20e89c6 to
63f810f
Compare
Type the request usage context, split disabled vs schema-not-ready catalog errors, and late-bind overridable interval constants. Co-authored-by: Chirag Aggarwal <[email protected]>
63f810f to
ef6bfa2
Compare
Keep the best-effort Console::error, and add Span attributes so a failed sweep is visible on the worker span, not only stdout. Co-authored-by: Chirag Aggarwal <[email protected]>
StatsUsage and StatsResources became ClickHouse-only in #13286, so nothing writes the project-DB or logs-DB `stats` collection any more. Remove the definition from both collection sets and everything that existed only to prune it. Removing the definition makes the sweeper a hazard rather than dead weight: new projects get no `stats` metadata row, so deleteByGroup('stats', ...) would throw. deleteUsageStats() and both its dispatch sites go, taking DELETE_TYPE_USAGE, the hourlyUsageRetentionDatetime message field, the maintenance scheduling and _APP_MAINTENANCE_RETENTION_USAGE_HOURLY with them. The logs collection set is now empty but the file and the getLogsDB plumbing stay: the database itself is still created and other editions merge their own collections into that set. Also sweeps the Usage* response models that no endpoint returns any more, and the V19 filter arms that reshaped two of them. UsageDataPoint, UsageMetric, UsageEventList and UsageGaugeList are the live ClickHouse models and stay. The spec test that pinned "a list of a sub-model emits array + $ref items, not allOf" used UsageProject as its fixture; re-point it at UsageMetric/UsageDataPoint rather than lose the generator guarantee typed SDKs depend on. Migrations are untouched. Utopia resolves a collection from the database metadata table, not from this config, so V20's createDocument('stats', ...) still works on the <=1.5.x installs those migrations run against.
StatsUsage and StatsResources became ClickHouse-only in #13286, so nothing writes the project-DB or logs-DB `stats` collection any more. Remove the definition from both collection sets and everything that existed only to prune it. Removing the definition makes the sweeper a hazard rather than dead weight: new projects get no `stats` metadata row, so deleteByGroup('stats', ...) would throw. deleteUsageStats() and both its dispatch sites go, taking DELETE_TYPE_USAGE, the hourlyUsageRetentionDatetime message field, the maintenance scheduling and _APP_MAINTENANCE_RETENTION_USAGE_HOURLY with them. The logs collection set is now empty but the file and the getLogsDB plumbing stay: the database itself is still created and other editions merge their own collections into that set. No API surface changes. The Usage* response models that are still returned somewhere keep their classes, constants and registrations; only the ones with no referee left in any edition go: UsageFunction(s), UsageSite, UsageDocumentsDB(s) and UsageVectorsDB(s), along with the two V19 filter arms that reshaped responses nothing emits. The spec test that pinned "a list of a sub-model emits array + $ref items, not allOf" used UsageProject as its fixture; re-point it at UsageMetric/UsageDataPoint so the generator guarantee typed SDKs depend on keeps its regression net. Migrations are untouched. Utopia resolves a collection from the database metadata table, not from this config, so V20's createDocument('stats', ...) still works on the <=1.5.x installs those migrations run against.
Summary
Adds the generic Usage service to self-hosted Appwrite, backed by a private single-node ClickHouse instance.
_APP_USAGE_STATS=enabled, with an explicit disabled no-op pathv1-stats-usageandv1-stats-resourcesqueue contracts and DI namesGET /v1/usage/eventsandGET /v1/usage/gaugeswithusage.read, filtering/grouping/bucket budgets,last|max, and empty-series responses26.4.3-alpineCompose wiring, persistent storage, authentication, healthcheck, and combined/separate worker/task registrationutopia-php/usage^0.14.0 (baeef33bbcb673265550c83fe437cfa5c400a1e0)Architecture
Appwrite\\Usage\\Contextnow captures generic request/resource metadata while preserving its existing API and Cloud subclass compatibility. Legacy Usage and StatsResources payload envelopes remain readable; dimensions are additive fields inside metric/gauge rows.countryis stored lowercased and filter values are folded the same way throughContext::normalizeCountry(). ClickHouse compares case-sensitively, so before this anequal("country", ["US"])filter returned an empty series.Appwrite\\Usage\\Connectionowns a lifecycle-local pooled ClickHouse client and the sharedprojects_*namespace. Request reads bindUtopia\\Usage\\Tenantto the authenticated project's sequence; tenant is never request-controlled.The existing publishers feed one consumer per stable queue. Inserts intentionally retain Cloud's current best-effort, non-idempotent behavior; arbitrary insert retries or deduplication were not added. Schema-not-ready is treated separately and fails message handling before insert, making the failure visible rather than acknowledging a missing-schema write.
Schema setup runs from
app/http.phpat boot, alongside the platform and project databases, on the same retry ladder. Giving up logs a warning rather than blocking boot: reads and ingestion both gate onConnection::isReady(), so they stay correct while the schema is missing. Theusage-setupCLI task is retained for repair without a restart. There is deliberately no one-shot setup container -- no other schema in the repo has one, and gating the API on it let analytics storage take the API down.Health probes connectivity plus the raw event, daily aggregate, and gauge objects. Raw events and daily aggregates have a 180-day TTL; gauges remain unlimited per the approved retention policy.
Cloud compatibility
Generic Usage module, worker, and task registration is gated to
_APP_EDITION=self-hosted, preventing duplicate Cloud routes and competing queue consumers before downstream adoption.The read endpoints are built to be subclassed rather than copied. Dimension/filter/interval constants and the query helpers are
protectedand read throughstatic::, so an override actually takes effect. Entitlement is an injectedusagePolicyobject: the self-hosted implementation allows everything, since self-hosted has no plans, addons, or reseller namespaces, and Cloud binds a subclass carrying its plan-history, premium-geo, and affiliate rules. It is injected rather than hung off the action because actions are shared across coroutines, so per-request state cannot live on$this. This lets the Cloud PR delete its duplicated copies of both endpoints instead of maintaining them in parallel.Verified directly against the current Cloud checkout:
Appwrite\\Cloud\\Usage\\Contextloads against the enriched parentAppwrite\\Cloud\\Event\\Message\\Usageretains constructor compatibilityCloud-only policy remains downstream: billing/legacy dual-write, affiliates and
console_*tenants, premium geo, team billing dimensions, plan history, WAF/dedicated database metrics, Audit ClickHouse, and multi-region infrastructure.ClickHouse operations
Default Compose includes authenticated
clickhouse/clickhouse-server:26.4.3-alpineon the internalappwritenetwork only, with no published ports, a persistent/var/lib/clickhousevolume, authenticatedSELECT 1healthcheck, and raisednofile.External
_APP_CONNECTIONS_DB_USAGEremains supported._APP_USAGE_PASSis used to bootstrap the bundled user; on an existing volume operators must runALTER USERbefore changing the environment and DSN because image initialization does not rotate persisted credentials.Live checks performed:
usage-setupsucceeded repeatedlyprojects_usage_gaugesmade schema health returnhealthy=false, schemaReady=false; rerunning setup repaired it3and gauge7Validation
Library unit tests were dropped in
c88c65d8and have been restored and extended:tests/unit/Usage— concurrency flooring, country fold,isReadyTTL / cache expiry,parseFilterQueries, late-bound bucket budget, catalogued disabled / not-ready exceptionstests/unit/Event/Message/UsageTest.php— legacy and dimensioned payload envelopestests/unit/Workers/StatsUsageTest.php— tenant resolution and disabled no-op (adapted to Accumulator +getDatabasesDB)E2E (
tests/e2e/Services/Usageis already in the CI matrix and is now also listed inphpunit.xml):_APP_USAGE_STATS=disabled)queries[]returnsgeneral_query_invalid(400), not 500_APP_USAGE_STATS=disabledreturns cataloguedgeneral_usage_disabled(403), not 500 — skipped on the default enabled CI stackQueue-to-API ingest and tenant isolation are not in this suite. This repo has no existing usage-worker E2E harness, and this CI job does not run a dedicated ingest path. Inventing one would be fake coverage.
Review-fix follow-ups also landed:
$usagein the api init/shutdown hooks is typed asAppwrite\\Usage\\Context; the redundantinstanceofguards are goneGENERAL_USAGE_DISABLEDis 403 (service-disabled neighbor). Schema-not-ready is a distinctGENERAL_USAGE_NOT_READY503, so a missing catalog row cannot become an undefined-index 500static::This branch was rebased onto latest
origin/main.Why this PR is draft
The focused implementation checks are green, but queue-to-API ingestion still needs a real worker harness before this is merge-ready. Remaining before marking ready:
Best-effort insert loss/duplication remains intentional and must stay observable/documented. Dimensioned sparse
aggregate=maxretains Cloud's current no-carry-forward limitation.Required follow-up dependencies
usageStatsfor self-hosted only when backend readiness is exposed, replace the current hardcoded self-hosted-off profile, and complete the site usage surface decision.aggregate=last|max, and update the Console SDK dependency in lockstep.No merge is requested until those gates and downstream compatibility checks pass.