Skip to content

chore: absorb http into packages/http - #13930

Merged
ChiragAgg5k merged 78 commits into
mainfrom
chore/absorb-http
Sep 28, 2026
Merged

ChiragAgg5k merged 78 commits into
mainfrom
chore/absorb-http

Conversation

@ChiragAgg5k

Copy link
Copy Markdown
Member

Summary

Moves utopia-php/http into packages/http so Appwrite loads it directly. Wave 3 of #13828, following the playbook in rfc/monorepo.md.

Stacked on #13921 (servers, which http requires). Merge #13921 first; GitHub then retargets this PR to main. Merge with a merge commit — a squash drops the git-subtree-* annotation and orphans the package from its mirror.

Commit What
Add 'packages/http/' from commit '7d534357…' Subtree import from the mirror with full history. Mirror head is the 2.0.0-rc33 tag Appwrite already locks, and utopia-php/monorepo's packages/http has the same manifest, so no version gap
chore(http): mirror plumbing mirror.yml calls this repository's mirror-redirect.yml; README banner points here
refactor: load http from packages/ Root autoload + replace entries, utopia-php/http dropped from require and the lock, step A shape (incl. the bare-prefix change), standalone phpstan.neon / rector.php, baseline
docs(rfc): list the http baseline for phase 8 One bullet in the phase 8 list
test(http): … (2) Keep the e2e base trait out of the suite; rename the UtopiaFPMRequestTest test double to FPMRequest so the root packages suite does not warn that it is not a TestCase

Step A

Change Detail
Prefix Utopia\ → Utopia\Http\ All 21 classes already live under Utopia\Http\ (none at the bare root), so the change is invisible to consumers. http leaves the bare list; the root Utopia\ entry keeps only packages/validators/src (plus vendored console)
src/Http/* → src/ src/ is identical to 2.0.0-rc33 apart from the move and Pint formatting (empty {} bodies on 7 files)
Test namespaces Utopia\Http, Utopia\Tests and Tests\E2E → Utopia\Http\Tests / Utopia\Http\Tests\E2E, with the use lines the move needs. ResponseTest.php (declaring FPMResponseTest) → FPMResponseTest.php
tests/e2e → tests/E2E Includes BaseTest (e2e-only trait); Dockerfile.swoole and tests/docker/nginx.conf paths follow
phpunit.xml Standard unit suite (tests/E2E, tests/bench excluded) and one e2e suite; test:e2e runs it against the package's docker-compose.yml (FPM on 19020, Swoole on 19501)
phpstan.neon Standalone, level max over src + tests (previously included ../../phpstan.neon at level 7), scanning swoole/ide-helper
rector.php Replaced: the old config used PHPUnit sets the root Rector no longer ships. PHP sets + type declarations, skipping every rule that would rewrite the released source or tests. Rector makes no changes
Removed example/ Its Dockerfile is banned (not an e2e service), and the app pinned utopia-php/http: latest on appwrite/base:0.5.0. The README link to it is dropped
phpstan-baseline.neon 394 findings: 81 in src (mixed request globals, Swoole server stats and coroutine context in the adapters, param/injection definitions in Http), 313 in tests (mostly nullable ?Request / ?Response / ?Route / ?Http fixtures)

Nothing to hoist: the package requires only php and siblings already in packages/ (compression di psr7 servers system telemetry validators). The vendored platform requires utopia-php/http, and replace now satisfies it.

Validation

Check Result
bin/monorepo validate all packages valid (incl. duplicate-class check)
bin/monorepo check http Rector, Pint, PHPStan level max (with baseline) pass
bin/monorepo test http unit 136 tests / 377 assertions; e2e (FPM + Swoole containers) 19 tests / 71 assertions
vendor/bin/phpunit --testsuite packages --filter 'Utopia\\Http' 136 tests / 377 assertions pass. Host-only: 3 cache CodecTest provider errors (no igbinary)
tests/unit in appwrite/appwrite:2.3.0 1350 tests; KeyTest needs _APP_OPENSSL_KEY_V1 (passes with it set); CertificatesDomainValidationTest::testAJobWithoutTheFlagStillChecksDns does a live DNS lookup and does not touch Utopia\Http
Root PHPStan (host) on 17 files no errors: app/http.php, app/realtime.php, general.php, shared/api.php, resources.php, resources/request.php, Utopia/Request.php, Utopia/Response.php, Platform/Appwrite.php, Compute/Base.php, and Teams, Users, Deployments status, GitHub events, Webhooks, Tokens files, Storage CacheControl
Autoload Utopia\Http\Http resolves to packages/http/src/Http.php; vendor/utopia-php/http is no longer installed
composer update --lock lock diff vs chore/absorb-servers drops only utopia-php/http (plus content hash)
composer validate --no-check-publish valid (only the existing utopia-php/platform exact-constraint warning)
bin/monorepo split http --dry-run 6bd4eb07, fast-forwards from mirror head 7d534357, tree identical to packages/http

Mirror

utopia-php/http already has a main ruleset (id 8820115: deletion, non-fast-forward, pull request) with the split app (4016286) as an always-bypass actor, so the absorb ran with --skip-ruleset. That ruleset also covers master, 0.33.x and 0.34.x. No classic branch protection on main.

After merge

Step
Confirm Split pushes to utopia-php/http
Retire remove packages/http from utopia-php/monorepo
Triage mirror PRs #253 chore: experiments, #205 Radix-trie with hash tables for static routes, #203 Improvements 🚧
Triage mirror issues #91 (App class docs out of date), #70 (external Router/Database class)
Triage monorepo PR utopia-php/monorepo#232 WIP: fix(http): trailing slash vs missing path param

🤖 Generated with Claude Code

ChiragAgg5k and others added 30 commits December 11, 2025 18:30
Headers can now be arrays (after recent changes allowing array headers).
The getSize() method was attempting to directly implode headers, causing
a warning when a header value was an array.

This fix properly handles both string and array header values by joining
array values with commas (standard HTTP header format) before calculating
the request size.

Added test case to verify the fix works correctly with array headers.
feat: remove validators and use utopia validators lib
* Use utopia-php/di for resource injection

* Move resource ownership into utopia-php/di

* Update DI branch dependency

* update getting started

* update

* update

* update appwrite base version

* update to use php 8.2

* fix: restore php 8.2 test runtime

* chore: use container scopes

* remove utopia keyword

* remove optional container in run

* remove optional container in run

* renaming

* remove public getContainer

* fix getcontainer

* fix getcontainer

* update

* remove tests

* make public

* remove tests

* add scoped request containers

* cleanup

* feat: request scopes

* fixes

---------

Co-authored-by: loks0n <[email protected]>
#230)

* feat: split Swoole adapters, add compression support, and adopt utopia-php/servers

- Split Swoole adapter into Swoole (SWOOLE_PROCESS) and SwooleCoroutine (coroutine-based) servers
- Add response compression support with configurable min size and algorithm selection
- Migrate Hook to utopia-php/servers and Route now extends Servers\Hook
- Add View class for template rendering
- Add trusted IP header support and IP validation in Request
- Enhance Response with cookie management, content-type helpers, and chunked transfer
- Add utopia-php/servers and utopia-php/compression dependencies
- Fix server-swoole.php test server to work with non-coroutine Swoole adapter
- Disable Swoole cookie parsing to preserve raw Cookie headers

* fix: address Greptile review comments on PR #230

- Remove Content-Length before re-adding after compression to prevent duplicate headers
- Defer onStart callback into coroutine event loop for SwooleCoroutine adapter consistency
- Add null-coalescing fallback for preg_replace in View::render
- Add void return types to compression setter methods for API consistency

* add telemetry
* Use Swoole parsed cookies again

* Skip Swoole test without extension

* Remove Swoole adapter unit test
* Skip action if response already sent by init hook

If an init hook (e.g. cache) calls $response->send(), the action should
not run — the response has already been delivered to the client. Without
this guard the action executes in full, wasting worker time on work
whose output is immediately discarded.

Shutdown hooks still run so metrics, billing, and other teardown logic
are unaffected.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Fix: pass Response to execute() so isSent() guard is in scope

The 0.34.x execute() method had dropped the Response parameter compared
to 0.33.x, meaning $response->isSent() in the action guard would be an
undefined variable. Restore the parameter and update all call sites in
the test suite.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Brotli defaulted to level 11 (near-max), which is too slow for an HTTP
response path. Set a fast, HTTP-sensible default of 4 and add an
explicit Zstd default of 3. GZIP and Deflate have no public level
setter in utopia-php/compression 0.1.4, so their PHP defaults (6) are
left as-is.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* Chore: Consolidate CI workflows and harden test infra

Merge test/lint/bench workflows into a single ci.yml, add PHPStan to CI,
parallelize adapter tests via matrix, replace fixed sleeps with compose
healthchecks, pin composer image to 2.7, and bump checkout to v4.

Also move ext-swoole to suggest so FPM-only consumers can install without
--ignore-platform-reqs, and simplify phpunit.xml discovery.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: Rename CI jobs and split tests into unit/e2e

Rename jobs per team convention: Lint -> Format, Static Analysis -> Analyze,
Benchmarks -> Benchmark. Split the single Tests matrix into three jobs:
Tests / Unit (runs on host PHP, no docker), Tests / E2E / FPM, and
Tests / E2E / Swoole.

Adds phpunit testsuites (unit, e2e-fpm, e2e-swoole) and moves BaseTest
trait to tests/ so it autoloads via its existing PSR-4 namespace.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Ignore ext-opentelemetry platform req for host PHP jobs

* Pin composer platform to PHP 8.2 so lock stays 8.2-compatible

* Group checks under Checks/ prefix and use matrix for E2E adapters

* Rename composer lint script to format:check and align CI job

* Rename composer check to analyze; remove misnamed CodeQL workflow

The CodeQL workflow did not actually run CodeQL — it ran PHPStan under a
misleading name. Checks / Analyze already covers that.

* Replace phpbench with k6 benchmark; post results as PR comment

Removes phpbench/phpbench (and its Symfony transitive deps) in favour of
a k6 HTTP load test targeting the swoole adapter. The CI benchmark job
runs k6 against the docker-compose swoole service, uploads the JSON +
text summary as an artifact, and posts a sticky PR comment with the
default k6 summary output.

* Bump k6 load to 60s, shorten PR comment, use grafana/run-k6-action

Also updates checkout, cache, upload-artifact, and sticky-comment actions
to their latest major versions.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
CI now triggers on push to main (was master + *.x), docs link the main
branch, and README uses a GitHub Actions badge (the Travis one was dead).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Bumps phpstan/phpstan from 1.* to ^2.0 and fixes the 3 errors surfaced
at level 5:
- curl_setopt CURLOPT_RETURNTRANSFER value uses bool instead of int
- drop redundant assertIsArray/assertIsInt on already-typed returns

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Adopts the PER-CS 2.0 coding standard (superset of PSR-12). Reformats
affected files with the preset's fixers: concat_space, trailing_comma_in_multiline,
single_line_empty_body, function_declaration, operator_linebreak,
nullable_type_declaration, types_spaces, cast_spaces.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
)

* Chore: Fix dev env friction, bump PHP floor to 8.3, add PHP matrix

- Dockerfiles now ship composer, composer.json/lock, phpstan.neon, pint.json
  so composer scripts (test/analyze/format) work in-container
- CONTRIBUTING: document host-native inner loop; fix wrong service name
  (web -> fpm); drop stale psalm reference; add swoole exec path
- Drop PHP 8.2 support; bump require/platform pin and FPM base image to 8.3
- CI unit job runs a matrix over PHP 8.3 / 8.4 / 8.5 with per-version
  composer cache keys; coverage (pcov + clover artifact) collected on 8.3
- example/docker-compose.yml: drop deprecated version key

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: Regenerate composer.lock for PHP 8.3 floor

The require.php / platform bump changed composer.json's content-hash,
so the lock was reporting out-of-date.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Adds generic array annotations and return types throughout src/ and
tests/ to satisfy level 6, then hardens a handful of unchecked
`string|false` / `resource|false` call sites for level 7.

Behaviour is unchanged on the happy path; the only runtime-visible
changes are in previously-broken error paths (e.g. opendir() returning
false, getHeader() on array-valued headers).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Introduces Rector for automated refactoring, wired up via:

- rector.php config targeting src/ and tests/ with PHP 8.3 level set
  plus CODE_QUALITY, DEAD_CODE, EARLY_RETURN, and INSTANCEOF sets.
  Rules with BC risk or behavioural shifts (readonly, explicit bool
  compare, empty() rewrites, type-hint additions, random_int swaps)
  are explicitly skipped.
- composer refactor / refactor:check scripts.
- Checks / Refactor CI job running rector in dry-run.
- Safe-bucket refactor applied across the codebase: strict_types
  declarations, #[\Override] attributes, str_contains / str_starts_with,
  null-coalescing, match over switch where safe, dead code removal,
  and docblock cleanup.
)

* Chore: Upgrade PHPUnit to 12, modernize tests, refresh Rector sets

- Bump phpunit/phpunit ^9.5 -> ^12.0, phpstan/phpstan ^2.0 -> ^2.1, rector/rector ^2.0 -> ^2.4.
- Migrate phpunit.xml to the PHPUnit 12 schema; exclude the BaseTest trait and
  the misnamed UtopiaFPMRequestTest mock helper from the unit suite.
- Add PHPUnit 10/11/12, code-quality, and annotations-to-attributes sets to
  rector.php; drop three skip entries rector reported as unregistered; skip
  AssertEmptyNullableObjectToAssertInstanceofRector since it weakens assertNull.
- Apply rector: declare(strict_types=1) in tests, final test classes, generator
  data provider, and assertEquals -> assertSame where types are inferable.
- Manual cleanup: assertEquals(null|true|false, x) -> specific methods; fix
  RequestTest::testCanRemoveHeaders which relied on null == '' loose equality
  (getHeader returns string); replace closure-vs-closure assertEquals in
  RouteTest::testCanSetAndGetAction with assertInstanceOf(Closure::class, ...).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: Bump swoole test image to appwrite/base:1.2.0 (PHP 8.5)

The CI e2e-swoole job failed because appwrite/base:0.5.0 ships PHP 8.2.6,
but PHPUnit 12 requires PHP >= 8.3. Bumping to 1.2.0 (PHP 8.5.4, swoole
included) matches the library's >=8.3 floor and the host test runtime.

Drop the now-redundant curl_close() call in tests/e2e/Client.php — PHP 8.5
deprecates it (the handle is released on last reference since 8.0 anyway).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: Declare coverage source in phpunit.xml

PHPUnit 12 requires a <source> section for coverage to run; without it the
runner emits "No filter is configured, code coverage will not be processed"
and CI's --coverage-* flags exit non-zero. Point coverage at ./src.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: Add PHPUnit schema reference, tighten Route/Response assertions

- phpunit.xml: add xmlns:xsi and xsi:noNamespaceSchemaLocation pointing at
  vendor/phpunit/phpunit/phpunit.xsd so PHPUnit 12 (and IDE tooling) get
  XML schema validation.
- HttpTest: swap reversed assertEquals(actual, expected) pairs in
  testCanSetRoute, testCanMatchRoute, and testCanMatchFreshRoute to the
  expected-first convention, and promote them to assertSame — setRoute
  and match return the exact Route instance, so identity is the precise
  check and the diff on failure reads correctly.
- ResponseTest: promote fluent-interface assertions on addHeader /
  addCookie to assertSame for the same reason.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Add explicit types to all 110 class constants across the public API
(string/int/array) — leveraging PHP 8.3 typed constants now that the
floor is 8.3.

Expand pint.json beyond the bare `per` preset with rules that match
common editor inspections, so CI catches what the editor flags:
- native_function_invocation (@compiler_optimized, namespaced scope)
- no_unused_imports, ordered_imports
- no_useless_else, no_useless_return
- no_empty_statement, no_empty_phpdoc, no_empty_comment
- array_syntax (short), single_quote
- trailing_comma_in_multiline

Pint applied the new rules across the codebase (mainly prefixing
compiler-optimized builtins with `\` in namespaced files and sorting
imports).
* parma alias + tests

* Simplify implementation

* implement e2e tests

* fix url param aliases

* Use stable servers 0.4.0

---------

Co-authored-by: Chirag Aggarwal <[email protected]>
* Refactor: split static resources from per-request context

Renames the request-scoped DI container concept to "context" and
splits adapter container access into two methods: resources() (static,
shared across requests) and context() (per-request). Removes the
Http::setResource / getResource / getResources(list) wrappers in favor
of going through resources()/context() directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Chore: apply Rector first-class callable refactor

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
* Make routing coroutine-safe by removing Route mutations

Router::match and the wildcard branch in Http::runInternal both wrote
to the shared Route singleton (setMatchedPath, path) on every request.
Under Swoole coroutines the Route is shared across in-flight requests,
so concurrent requests could observe each other's matched path.

- Router::match now returns [Route, matchedPath] instead of mutating
  the Route. A new Router::setFallback slot replaces Http::$wildcardRoute,
  so the method-agnostic catch-all flows through the same matching path
  as any other route.
- Route::matchedPath / setMatchedPath / getMatchedPath are removed.
- Http::execute takes the matched path as a parameter; runInternal
  threads it through. Public Http::match keeps its ?Route shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Move matched route + matched path into request context

The Http instance is shared across coroutines, so $this->route and
$this->matchedPath would race the same way Route's mutable fields did.
Store them in the per-request context() container instead, which is
already request-scoped post-#254. getRoute()/setRoute() now read/write
through the context too.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Inline context key strings

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Rename Router fallback slot to wildcard

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Introduce Router\Result DTO for match results

Replace the [Route, matchedPath] tuple with a readonly Router\Result
value object so callers get named, typed access instead of positional
unpacking.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Drop redundant preparePath in Http::execute

$matchedPath is already the prepared form (the key from Router::$routes),
so re-preparing it just returned the same string. Pass it straight to
Route::getPathValues.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Rename Router\Result to RouteMatch, drop matchInternal indirection

- Move the value object to Utopia\Http\RouteMatch (top-level), since
  'Match' is reserved by PHP 8.0+. RouteMatch is short, clear, and
  doesn't shadow the keyword.
- Rename matchedPath -> path on the DTO; the field name is qualified by
  the surrounding RouteMatch context.
- Inline matchInternal: public Http::match now returns ?RouteMatch
  directly instead of indirecting through a private helper.
- Http::execute now takes a RouteMatch (route + matched path together)
  instead of separate args, so callers can't pass mismatched pairs.
- Cache the whole RouteMatch under 'match' in the per-request context;
  keep 'route' set too for downstream injection compat.
- Add per-property docblocks on RouteMatch.
- Update tests to wrap raw Routes in RouteMatch when calling execute().

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Make execute(Request, Response) the public dispatch entry point

Aligns the API with how callers think about it: Route is a definition,
RouteMatch is the immutable result of matching, execute() is the verb
that ties them together (match -> resolve -> run).

- Http::execute now takes (Request, Response) and does match + dispatch
  internally, including OPTIONS/HEAD handling and 404 fallback. Replaces
  the prior shape that required callers to pre-build a RouteMatch.
- Http::match becomes stateless: drop the $fresh / context-cache that
  silently returned the previous request's match when a caller invoked
  execute() multiple times with different requests.
- runInternal collapses to: pre-checks (compression, request hooks,
  static files) + delegate to execute().
- Update tests: hand-built routes now register via Http::get/post/etc.,
  set $_SERVER['REQUEST_URI'] before execute(), and use
  Http::setAllowOverride(true) for tests that re-register the same path.
- Update Router::match callers to unwrap ->route from RouteMatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* RouteMatch carries resolved params, not the matched template

The matched-template string was purely instrumental — its only job was
to look up Route::pathParams[$template] so callers could resolve URL
segments into a name->value map. Now Router::match resolves the params
itself and stores them on RouteMatch directly, so dispatch is just
`$match->params` with no second-stage resolution.

- RouteMatch.path: string -> RouteMatch.params: array<string, string>.
- Route::getPathValues renamed to Route::resolveParams; takes a URL
  string instead of a Request (the resolution doesn't need anything
  else from the request).
- Router::match calls resolveParams at match time. Static and wildcard
  matches pass [] for params.
- Http::execute drops getPathValues call; reads $match->params directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Drop Http::setRoute()

The matched route is owned by the routing pipeline and lives in the
per-request context. setRoute let arbitrary code overwrite it post-match
without invalidating any other state — a footgun under coroutines and
not used in production. Drop it; getRoute() remains as a read-only view.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Drop Http::getRoute()

The supported way to consume the matched route is via the 'route'
injection inside hooks/actions:

  Http::init()
      ->inject('route')
      ->action(function (?Route $route) { ... });

getRoute() was a convenience accessor on the shared Http instance.
Reading mutable per-request state through a method on a shared object
encourages racy patterns under coroutines (e.g. caching a Route
reference, calling getRoute() outside a request scope). Drop it; tests
that needed the matched route now consume it via the injection or via
the RouteMatch returned from match() directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Tighten doc comments to user-facing intent

Drop internal narrative about coroutine safety, mutation-vs-immutability,
and "we used to do X." Comments now describe what each public surface
does for someone calling it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Document run vs execute as distinct entry points

run() is the top-level request lifecycle (compression, request hooks,
static files, match, dispatch, telemetry) — wired into the server
adapter. execute() is the re-entrant dispatch primitive — match +
handler + hooks only — for sub-requests from inside a handler (e.g.
GraphQL resolvers synthesizing Request/Response pairs).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Inline \$match->params in execute, drop \$pathValues alias

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Drop intermediate variables in run() telemetry

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Apply rector and pint to RouteMatch.php

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Save/restore context['route'] across execute() dispatch

match() no longer writes to context — that was leaking the inner
match into the outer's context whenever execute() was called for a
sub-request, breaking outer-request shutdown hooks doing
->inject('route') and the http.route telemetry attribute.

execute() now sets context['route'] right before dispatching and
restores the prior value (or null) in a finally clause, so nested
execute() calls don't trample each other's frame.

Adds testSubrequestRestoresOuterRoute as a regression test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Make 'route' injection frame-local instead of stateful

The save/restore pattern was just bookkeeping around a shared mutable
slot — anything else writing to context['route'] during dispatch would
break the restore, and a missed restore in any branch leaks the inner
match into the outer frame.

Drop context['route'] entirely. Pass the dispatch frame's Route through
to getArguments and special-case the 'route' injection there. Each
dispatch frame (including sub-requests via execute()) carries its own
matched Route as a parameter; nested calls can't trample each other
because there's no shared state to trample.

Telemetry in run() now reads the outer match by calling match() once
locally — match() is pure and cheap.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Apply rector to HttpTest

assertEquals -> assertSame in testSubrequestRestoresOuterRoute.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Coerce empty wildcard path to null in telemetry

Route::getPath() returns '' for the wildcard route by construction
(registered as 'new Route("", "")'). Emitting that as the OTel
http.route attribute would set the attribute to an empty string —
different from "unset" in OTel semantics. Coerce to null at the
attribute boundary so http.route is unset for wildcard / no-match
requests.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Wildcard is a Hook, not a Route

The wildcard fallback was modeled as `new Route('', '')` — a Route with
empty method and path, which are meaningless for a method-agnostic
catch-all. The empty strings were sentinels that leaked into
Route::getPath() at runtime for any handler doing inject('route').

Model honestly: Http::wildcard() returns a Hook (the parent class —
action + params + injections + groups). Router::\$wildcard is now
?Hook. RouteMatch::\$route is typed Hook so it can carry either —
consumers wanting Route-only fields (getMethod, getPath) check
instanceof Route first.

Behavior: inject('route') now correctly returns null inside a wildcard
handler (it never had a Route to begin with). Telemetry's http.route
attribute is unset for wildcard matches, matching OTel semantics.
Group hooks don't fire for wildcard matches (it has no groups beyond
'*'); the global init/shutdown blocks still run because there's no
Route::getHook() opt-out for the wildcard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Revert "Wildcard is a Hook, not a Route"

This reverts commit e89d58f2bf2333558f98f3fb4df917d39aaa286b.

* Add 'params' frame-local injection

Mirrors the 'route' injection: hooks can do ->inject('params') to receive
the resolved path params (array<string, string>) for the current dispatch
frame. Skips shared context for the same reason 'route' does — nested
execute() calls (sub-request dispatch) can't trample each other.

Refactor: collapse the per-name special-cases into a frame-local map for
clarity. Both 'route' and 'params' come from the dispatch frame; the map
makes that explicit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Rename frameLocals to locals

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Align the Request and Response header/cookie APIs with PSR-7 semantics
while keeping utopia's mutable style.

Headers:
- Names are case-insensitive and stored lowercased internally.
- getHeader() now returns a list of values (string[]); getHeaderLine()
  returns the comma-joined string; add hasHeader() and setHeader().
- getHeaders() returns array<string, string[]>.
- Header logic is centralized in the base Request; adapters only supply
  the raw source via generateHeaders()/generateCookies().

Cookies:
- Add getCookieParams()/setCookieParams() on Request, backed by a lazy
  generateCookies() per adapter. getCookie() reads through it.

Adapters:
- FPM sendHeader() title-cases header names on the wire to match Swoole
  and preserve prior output; emits one line per value (Set-Cookie).
- Swoole multi-value headers are passed as a single array (array_set in
  swoole-src overwrites, so per-value calls would drop all but the last).
- Harden cookie sending: coalesce null SameSite/value to typed defaults
  so they are not passed where a string is expected.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@ChiragAgg5k ChiragAgg5k added the absorb History-preserving package absorption; merge commit required label Sep 26, 2026
@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[High risk] Absorbs external HTTP package into monorepo.

The PR should not merge until the outstanding repository requirement to avoid new regular expressions is satisfied.

Fix All in Claude CodeFindings

  1. P2 Tests mirror mode configuration ▶
  2. P2 Guide uses obsolete HTTP API ▶
  3. P2 PHP minimum is incorrect ▶
  4. P2 Validator link is broken ▶
  5. P2 Added regular expressions ▶
Fix with agent prompt
### Issue 1
packages/http/tests/ModeTest.php:17-18
These assertions copy the exact Swoole settings defined in `Mode::settings()`. They test configuration values rather than whether requests work in either mode, so a tuning change can require a matching test edit without testing its effect. `RequestTest` also changes an internal property through reflection, and `RouteTest` checks the stored injection map. The repository requires tests of observable behavior, not mirrored source or configuration; that requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 2
packages/http/docs/Getting-Starting-Guide.md:128-139
The advanced example imports `Utopia\Http\Swoole` classes that do not exist and passes a callback to `Http::init()`, which now takes no arguments and returns a hook configured with `->action()`. Readers sent here from the README cannot follow this example to build the described request lifecycle.

### Issue 3
packages/http/README.md:undefined-295
The README says PHP 8.3 is supported, but the package manifest requires PHP 8.5 or later. Someone using PHP 8.3 or 8.4 based on this guidance cannot install the package. The getting-started guide repeats the incorrect minimum.

### Issue 4
packages/http/README.md:undefined-126
The “built-in validators” link points to `/src/Http/Validator`, which does not exist in this package. Validators are a separate package dependency, so readers following the parameter example cannot reach the referenced guidance.

### Issue 5
packages/http/src/Request.php:undefined-612
The imported request parser uses `preg_match()` to detect empty JSON objects. The imported view minifier also uses `preg_match_all()` and `preg_replace()`. The repository requires new code to avoid regular expressions, using string functions or an existing validator instead unless the PR explains why neither works. No such explanation is provided. This repository requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR absorbs Utopia HTTP into packages/http, switches root Composer autoloading and replacement to the in-tree package, and adds standalone tests and mirror plumbing.

  • The changes since the previous review reflect a merge of the updated base branch; the HTTP package itself is unchanged.

Reviews (6) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment on lines +17 to +18
$this->assertFalse($settings[Constant::OPTION_ENABLE_COROUTINE]);
$this->assertSame(3, $settings[Constant::OPTION_DISPATCH_MODE]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Tests mirror mode configuration
These assertions copy the exact Swoole settings defined in Mode::settings(). They test configuration values rather than whether requests work in either mode, so a tuning change can require a matching test edit without testing its effect. RequestTest also changes an internal property through reflection, and RouteTest checks the stored injection map. The repository requires tests of observable behavior, not mirrored source or configuration; that requirement must be satisfied before merging.

Context Used: Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/http/tests/ModeTest.php
Line: 17-18

Comment:
**Tests mirror mode configuration**
These assertions copy the exact Swoole settings defined in `Mode::settings()`. They test configuration values rather than whether requests work in either mode, so a tuning change can require a matching test edit without testing its effect. `RequestTest` also changes an internal property through reflection, and `RouteTest` checks the stored injection map. The repository requires tests of observable behavior, not mirrored source or configuration; that requirement must be satisfied before merging.

**Context Used:** Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

Comment on lines +128 to +139
```php
use Utopia\Http\Http;
use Utopia\Http\Swoole\Request;
use Utopia\Http\Swoole\Response;
use Swoole\Http\Server;
use Swoole\Http\Request as SwooleRequest;
use Swoole\Http\Response as SwooleResponse;
use Utopia\Validator\Wildcard;

$http = new Server("0.0.0.0", 8080);

Http::init(function($response) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Guide uses obsolete HTTP API
The advanced example imports Utopia\Http\Swoole classes that do not exist and passes a callback to Http::init(), which now takes no arguments and returns a hook configured with ->action(). Readers sent here from the README cannot follow this example to build the described request lifecycle.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/http/docs/Getting-Starting-Guide.md
Line: 128-139

Comment:
**Guide uses obsolete HTTP API**
The advanced example imports `Utopia\Http\Swoole` classes that do not exist and passes a callback to `Http::init()`, which now takes no arguments and returns a hook configured with `->action()`. Readers sent here from the README cannot follow this example to build the described request lifecycle.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

Comment thread packages/http/README.md

## System requirements

Utopia HTTP requires PHP 8.3 or later. We recommend using the latest PHP version whenever possible.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 PHP minimum is incorrect
The README says PHP 8.3 is supported, but the package manifest requires PHP 8.5 or later. Someone using PHP 8.3 or 8.4 based on this guidance cannot install the package. The getting-started guide repeats the incorrect minimum.

Knowledge Base Used: Reusable platform packages

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/http/README.md
Line: 295

Comment:
**PHP minimum is incorrect**
The README says PHP 8.3 is supported, but the package manifest requires PHP 8.5 or later. Someone using PHP 8.3 or 8.4 based on this guidance cannot install the package. The getting-started guide repeats the incorrect minimum.

**Knowledge Base Used:** [Reusable platform packages](https://app.greptile.com/appwrite/-/custom-context/knowledge-base/appwrite/appwrite/-/docs/reusable-platform-packages.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

Comment thread packages/http/README.md

Parameters are used to receive input into endpoint action from the HTTP request. Parameters could be defined as URL parameters or in a body with a structure such as JSON.

Every parameter must have a validator defined. Validators are simple classes that verify the input and ensure the security of inputs. You can define your own validators or use some of [built-in validators](/src/Http/Validator).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Validator link is broken
The “built-in validators” link points to /src/Http/Validator, which does not exist in this package. Validators are a separate package dependency, so readers following the parameter example cannot reach the referenced guidance.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/http/README.md
Line: 126

Comment:
**Validator link is broken**
The “built-in validators” link points to `/src/Http/Validator`, which does not exist in this package. Validators are a separate package dependency, so readers following the parameter example cannot reach the referenced guidance.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → chore/absorb-http (after).

Metric Before After Change
🚀 Requests/sec 190.74 198.35 ⚪ +4%
⏱️ Latency P50 88.38 ms 88.67 ms ⚪ +0.3%
⏱️ Latency P95 215.32 ms 201.06 ms 🟢 -6.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 88.67 201.06 12,540 198.35 -14.26
Account 165.15 314.59 660 10.96 -40.43
TablesDB 86.5 160.41 6,820 109.85 -1.97
Storage 79.58 168.53 3,300 54.94 -14.4
Functions 119.4 230.44 1,760 29.96 -47.92

Top API waits (after)

API request Max wait (ms)
account.prefs.update 452.24
account.name.update 439.05
tablesdb.rows.create 421.05
functions.delete 385.1
tablesdb.rows.decrement 378.12

Http's constructor sets the process timezone (Asia/Tel_Aviv in setUp), which leaked into later suites in the shared root run and broke the schedule package's time-based tests.
@ChiragAgg5k
ChiragAgg5k changed the base branch from chore/absorb-servers to main September 27, 2026 12:19
// An empty JSON object is always `{`, JSON whitespace, `}`, and `\s` covers
// every JSON whitespace character, so no match means no empty object at any
// depth. A `{}` inside a string literal matches and costs only the walk.
$decoded = preg_match('/\{\s*\}/', $raw) === 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Added regular expressions

The imported request parser uses preg_match() to detect empty JSON objects. The imported view minifier also uses preg_match_all() and preg_replace(). The repository requires new code to avoid regular expressions, using string functions or an existing validator instead unless the PR explains why neither works. No such explanation is provided. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/http/src/Request.php
Line: 612

Comment:
**Added regular expressions**

The imported request parser uses `preg_match()` to detect empty JSON objects. The imported view minifier also uses `preg_match_all()` and `preg_replace()`. The repository requires new code to avoid regular expressions, using string functions or an existing validator instead unless the PR explains why neither works. No such explanation is provided. This repository requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/appwrite/appwrite/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

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

Labels

absorb History-preserving package absorption; merge commit required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants