Skip to content

Make the abuse library immutable #14046

Closed

Description

@ChiragAgg5k

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 param
  • app/init/resources.php: the timelimit resource that leases a Redis connection and passes the adapter to a callback
  • app/realtime.php: connect abuse check
  • src/Appwrite/Mqtt/Handler.php: MQTT CONNECT limit
  • src/Appwrite/Platform/Modules/Functions/Http/Functions/Create.php: function creation limit
  • src/Appwrite/Platform/Workers/Deletes.php: only uses TimeLimit\Database::COLLECTION
  • Cloud: app/http.php (slow functions/queries), app/realtime.php, and the Pool/None subclasses of TimeLimit, SlidingWindow and TokenBucket

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 by withParams(array $params): static (and/or withParam()), which returns a clone. The key is resolved on each call with strtr(), which is single-pass and prefers the longest match, so $this->key is never written to.
  • check() returns a final readonly class Result instead of a bool. The separate remaining(), limit() and time() calls go away, along with the cached $count. That also removes the extra Redis/DB reads per request that api.php makes today: the shared hook calls remaining() and then check().
  • 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 readonly where 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.
  • ReCaptcha is either moved out of the Adapter hierarchy into its own final readonly verifier, 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 raw curl_* in ReCaptcha (use packages/client if it stays).

Tasks

  • Refactor packages/abuse as 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/abuse 3.0.0
  • Migrate Cloud: the Pool/None subclasses for TimeLimit, SlidingWindow and TokenBucket, plus the http.php and realtime.php call sites
  • Check that the X-RateLimit-* headers are unchanged. Today remaining is 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 Abuse wrapper class? It only forwards to the adapter. Callers could use the adapter directly, as most other packages do.
  • Should getLogs() and cleanup() stay on the rate-limit interface? They are only meaningful for the Database/TablesDB adapters, and the Redis adapters return true or scan everything.

Activity

  1. self-assigned this
    on Oct 1, 2026
  2. added
    api / graphql
    api / realtime
    product / databases
    product / functions
    product / sites
    product / vcs
    sdk / cli
    on Oct 1, 2026
  3. changed the title [-]refactor(abuse): make adapters immutable — replace fluent setters with readonly classes and with*() clones[/-] [+]Make the abuse library immutable[/+] on Oct 1, 2026
  4. ChiragAgg5k commented on Oct 1, 2026

    @ChiragAgg5k
    MemberAuthor

    Implementation plan pinned (branch refactor/abuse-immutable):

    • Base stays Utopia\Abuse\Adapter (src/Adapter.php, abstract readonly); algorithms move to Utopia\Abuse\Adapter\{TimeLimit,SlidingWindow,TokenBucket}\*. Abuse wrapper removed.
    • withParams(array): static / withParam() via PHP 8.5 clone($this, [...]); key() resolves with strtr() per call.
    • check(): Result (records a hit) and peek(): Result (read-only, keeps headers for API-key/privileged requests where no hit is recorded today). Result = limited, limit, remaining, reset.
    • Each algorithm base owns check/peek/reset (final) and the window math; storage subclasses implement three primitives (hit returns 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 value X-RateLimit-Remaining reports today. reset = window start + seconds.
    • Redis key formats are unchanged, so counters carry over the deploy.
    • ReCaptcha becomes a standalone final readonly verifier on utopia-php/client. Package minimum PHP becomes 8.5.
  5. ChiragAgg5k commented on Oct 1, 2026

    @ChiragAgg5k
    MemberAuthor

    Consolidation status (local branch refactor/abuse-immutable, not pushed yet): all 8 parallel subtask branches merged onto efd2707 with no conflicts. packages/abuse PHPStan 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 without APPWRITE_ENDPOINT) against Redis, RedisCluster, RedisPool, RedisPoolCluster, MySQL, SlidingWindow x3 and TokenBucket x3. Root composer lint, composer analyze and composer refactor:check pass. The TimeLimit clock and param-reuse regressions fail at efd2707 and pass on the branch. Behaviour note: SlidingWindow and TokenBucket Redis adapters now throw RuntimeException on a non-numeric Lua result, like TimeLimit; fail-open is left to subclasses (Cloud Pool breakers). Next: Appwrite abuseEnabled e2e group and the Cloud impact checklist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api / graphqlapi / realtimeproduct / databasesproduct / functionsproduct / sitesproduct / vcssdk / cli

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions