Repository navigation
Closed
Labels
api / graphqlFixes and upgrades for the Appwrite GraphQL API.api / realtimeFixes and upgrades for the Appwrite Realtime API.product / databasesFixes and upgrades for the Appwrite Database.product / functionsFixes and upgrades for the Appwrite Functions.product / sitesFixes and upgrades for Appwrite Sites.product / vcsFixes and upgrades for the Appwrite VCS.sdk / cliFixes and upgrades for the Appwrite CLI.
Description
Summary
packages/abuse (utopia-php/abuse, currently 2.0.1) is the last of the absorbed libraries still built around mutable adapters and fluent setters. Each adapter is a stateful object: setParam() mutates it, parseKey() rewrites $this->key in place, and count()/time() cache their results on the instance. Refactor it to the immutable style already used across packages/: final readonly classes with promoted constructor properties, with*() methods that return a clone, and value objects for results. Ship it as a major (3.0.0).
Where the mutation is today
| Location | Mutable behaviour | Problem |
|---|---|---|
Adapter::setParam() |
Fluent $this->params[$key] = $value; return $this; |
The adapter is configured after construction, so an instance has no fixed identity. |
Adapter::parseKey() |
$this->key = str_replace(...) writes over the key pattern |
After the first parse the placeholders are gone. A later setParam() on the same instance has no effect, and a reused adapter keeps the old resolved key. Replacement order also follows insertion order, so {param-id} and {param-idx} can collide. |
TimeLimit::$count (Redis, Database, TablesDB) |
count() caches the result and hit()/set() update it |
remaining() and check() read the cached count, which goes stale if the instance lives longer than one request. Cloud realtime keeps one adapter per coroutine context. |
TimeLimit::$timestamp |
Fixed in the constructor | A reused instance keeps counting into a window that has already ended. |
SlidingWindow\RedisBase, TokenBucket\RedisBase |
check(), count(), reset() and time() write to $this->timestamp |
This works around the problem above, but it means that even getters mutate the object. |
| All adapter properties | protected, non-readonly, assigned in constructor bodies |
Subclasses (including Cloud's Pool/None adapters for all three algorithms) write to parent state directly. |
ReCaptcha::check(float $score = 0.5) |
Signature differs from Adapter::check() |
getLogs(), cleanup() and reset() throw "Method not supported". It is not really a rate-limit adapter. |
Current call sites
All of them follow the same pattern: build the adapter, chain setParam(), then call remaining(), limit(), time() and check()/reset() one after another on the same instance.
app/controllers/shared/api.php: the init hook (check) and the shutdown hook (reset), with 7 fixed params plus one{param-*}per request paramapp/init/resources.php: thetimelimitresource that leases a Redis connection and passes the adapter to a callbackapp/realtime.php: connect abuse checksrc/Appwrite/Mqtt/Handler.php: MQTT CONNECT limitsrc/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php: function creation limitsrc/Appwrite/Platform/Workers/Deletes.php: only usesTimeLimit\Database::COLLECTION- Cloud:
app/http.php(slow functions/queries),app/realtime.php, and thePool/Nonesubclasses ofTimeLimit,SlidingWindowandTokenBucket
Existing patterns to follow
| Package | Pattern |
|---|---|
packages/client |
with*(): static clones (withTimeout, withHeaders, withBaseUri, …) |
packages/circuit-breaker |
final readonly class Redis adapter with promoted constructor properties |
packages/schedule |
final readonly stores, triggers and value objects (Claim, Occurrence) |
packages/smtp |
Entirely final readonly value objects (Message, Envelope, Result, …) |
Proposed shape
// Pattern stays a template. Resolution is pure and does not mutate the adapter.
$limit = new TimeLimit\Redis(key: 'url:{url},ip:{ip}', limit: 10, seconds: 60, redis: $redis)
->withParams([
'{url}' => $url,
'{ip}' => $ip,
]);
$result = $limit->check(); // one round trip
$result->limited; // bool
$result->limit; // int
$result->remaining; // int
$result->reset; // int, unix timestamp the window resets at
$limit->reset();setParam()is replaced bywithParams(array $params): static(and/orwithParam()), which returns a clone. The key is resolved on each call withstrtr(), which is single-pass and prefers the longest match, so$this->keyis never written to.check()returns afinal readonly class Resultinstead of abool. The separateremaining(),limit()andtime()calls go away, along with the cached$count. That also removes the extra Redis/DB reads per request thatapi.phpmakes today: the shared hook callsremaining()and thencheck().- The window start is computed from the clock on each call, as
SlidingWindow\RedisBase::window()already does, and is not stored on the instance. - Adapters become
final readonlywhere they have no subclasses. Shared Redis logic stays in abstract bases, and their state is passed in through the constructor rather than through protected writable properties. ReCaptchais either moved out of theAdapterhierarchy into its ownfinal readonlyverifier, or dropped (it has no callers in appwrite or cloud).- Since this is a breaking release anyway, fix the remaining house-rule violations:
Adapters→Adapter(singular namespace), full type hints, and no rawcurl_*in ReCaptcha (usepackages/clientif it stays).
Tasks
- Refactor
packages/abuseas above, including unit tests and the E2E suites for Redis, RedisCluster, RedisPool, Database, TablesDB, SlidingWindow and TokenBucket - Add a regression test showing that a reused adapter resolves new params correctly and counts in the current window, not the one from construction
- Update the README examples
- Migrate the appwrite call sites listed above, then tag
utopia-php/abuse3.0.0 - Migrate Cloud: the
Pool/Nonesubclasses for TimeLimit, SlidingWindow and TokenBucket, plus thehttp.phpandrealtime.phpcall sites - Check that the
X-RateLimit-*headers are unchanged. Todayremainingis read before the hit, so decide whether to keep that off-by-one or report the post-hit value, and note the decision in the PR.
Open questions
- Keep the
Abusewrapper class? It only forwards to the adapter. Callers could use the adapter directly, as most other packages do. - Should
getLogs()andcleanup()stay on the rate-limit interface? They are only meaningful for the Database/TablesDB adapters, and the Redis adapters returntrueor scan everything.
Metadata
Metadata
Assignees
Labels
api / graphqlFixes and upgrades for the Appwrite GraphQL API.api / realtimeFixes and upgrades for the Appwrite Realtime API.product / databasesFixes and upgrades for the Appwrite Database.product / functionsFixes and upgrades for the Appwrite Functions.product / sitesFixes and upgrades for Appwrite Sites.product / vcsFixes and upgrades for the Appwrite VCS.sdk / cliFixes and upgrades for the Appwrite CLI.
Activity
[-]refactor(abuse): make adapters immutable — replace fluent setters with readonly classes and with*() clones[/-][+]Make the abuse library immutable[/+]ChiragAgg5k commentedon Oct 1, 2026
Implementation plan pinned (branch
refactor/abuse-immutable):Utopia\Abuse\Adapter(src/Adapter.php,abstract readonly); algorithms move toUtopia\Abuse\Adapter\{TimeLimit,SlidingWindow,TokenBucket}\*.Abusewrapper removed.withParams(array): static/withParam()via PHP 8.5clone($this, [...]);key()resolves withstrtr()per call.check(): Result(records a hit) andpeek(): Result(read-only, keeps headers for API-key/privileged requests where no hit is recorded today).Result=limited,limit,remaining,reset.check/peek/reset(final) and the window math; storage subclasses implement three primitives (hitreturns the pre-hit count and only records under the limit,count,set/clear). TimeLimit Redis moves to one Lua round trip.remaining = max(0, limit - count_before - 1), the same valueX-RateLimit-Remainingreports today.reset = window start + seconds.ReCaptchabecomes a standalonefinal readonlyverifier onutopia-php/client. Package minimum PHP becomes 8.5.ChiragAgg5k commentedon Oct 1, 2026
Consolidation status (local branch
refactor/abuse-immutable, not pushed yet): all 8 parallel subtask branches merged onto efd2707 with no conflicts.packages/abusePHPStan level max is clean, so the 44-entry baseline was deleted. Abuse unit suite 35/35 passes, and the E2E suite has 139 tests (125 pass, 14 TablesDB skipped withoutAPPWRITE_ENDPOINT) against Redis, RedisCluster, RedisPool, RedisPoolCluster, MySQL, SlidingWindow x3 and TokenBucket x3. Rootcomposer lint,composer analyzeandcomposer refactor:checkpass. The TimeLimit clock and param-reuse regressions fail at efd2707 and pass on the branch. Behaviour note: SlidingWindow and TokenBucket Redis adapters now throwRuntimeExceptionon a non-numeric Lua result, like TimeLimit; fail-open is left to subclasses (Cloud Pool breakers). Next: AppwriteabuseEnablede2e group and the Cloud impact checklist.ChiragAgg5k commentedon Oct 5, 2026
Child PRs for this theme: