Repository navigation
chore: absorb http into packages/http - #13930
Conversation
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]>
chore: stop committing package lock files
fix(http): allow System 0.11
fix(http): retain Validators 0.6 compatibility
* fix(http): recycle Hyperloop B workers after bounded requests * fix(http): retain default Swoole request recycling jitter
chore(domains,dns,http,queue): require Validators ^1.0
feat(http): state which forwarded headers a deployment trusts
fix(http): treat an explicit null optional param as omitted
|
| $this->assertFalse($settings[Constant::OPTION_ENABLE_COROUTINE]); | ||
| $this->assertSame(3, $settings[Constant::OPTION_DISPATCH_MODE]); |
There was a problem hiding this 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)
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!
| ```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) { |
There was a problem hiding this 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.
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.|
|
||
| ## System requirements | ||
|
|
||
| Utopia HTTP requires PHP 8.3 or later. We recommend using the latest PHP version whenever possible. |
There was a problem hiding this 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
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.|
|
||
| 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). |
There was a problem hiding this 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.
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.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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.
| // 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 |
There was a problem hiding this comment.
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!
# Conflicts: # composer.lock
# Conflicts: # composer.lock
Summary
Moves
utopia-php/httpintopackages/httpso Appwrite loads it directly. Wave 3 of #13828, following the playbook inrfc/monorepo.md.Stacked on #13921 (
servers, whichhttprequires). Merge #13921 first; GitHub then retargets this PR tomain. Merge with a merge commit — a squash drops thegit-subtree-*annotation and orphans the package from its mirror.Add 'packages/http/' from commit '7d534357…'2.0.0-rc33tag Appwrite already locks, andutopia-php/monorepo'spackages/httphas the same manifest, so no version gapchore(http): mirror plumbingmirror.ymlcalls this repository'smirror-redirect.yml; README banner points hererefactor: load http from packages/replaceentries,utopia-php/httpdropped fromrequireand the lock, step A shape (incl. the bare-prefix change), standalonephpstan.neon/rector.php, baselinedocs(rfc): list the http baseline for phase 8test(http): …(2)UtopiaFPMRequestTesttest double toFPMRequestso the rootpackagessuite does not warn that it is not aTestCaseStep A
Utopia\→Utopia\Http\Utopia\Http\(none at the bare root), so the change is invisible to consumers.httpleaves the bare list; the rootUtopia\entry keeps onlypackages/validators/src(plus vendoredconsole)src/Http/*→src/src/is identical to2.0.0-rc33apart from the move and Pint formatting (empty{}bodies on 7 files)Utopia\Http,Utopia\TestsandTests\E2E→Utopia\Http\Tests/Utopia\Http\Tests\E2E, with theuselines the move needs.ResponseTest.php(declaringFPMResponseTest) →FPMResponseTest.phptests/e2e→tests/E2EBaseTest(e2e-only trait);Dockerfile.swooleandtests/docker/nginx.confpaths followphpunit.xmlunitsuite (tests/E2E,tests/benchexcluded) and onee2esuite;test:e2eruns it against the package'sdocker-compose.yml(FPM on 19020, Swoole on 19501)phpstan.neonsrc+tests(previously included../../phpstan.neonat level 7), scanningswoole/ide-helperrector.phpexample/Dockerfileis banned (not an e2e service), and the app pinnedutopia-php/http: latestonappwrite/base:0.5.0. The README link to it is droppedphpstan-baseline.neonsrc(mixedrequest globals, Swoole server stats and coroutine context in the adapters, param/injection definitions inHttp), 313 in tests (mostly nullable?Request/?Response/?Route/?Httpfixtures)Nothing to hoist: the package requires only
phpand siblings already inpackages/(compression di psr7 servers system telemetry validators). The vendoredplatformrequiresutopia-php/http, andreplacenow satisfies it.Validation
bin/monorepo validatebin/monorepo check httpbin/monorepo test httpvendor/bin/phpunit --testsuite packages --filter 'Utopia\\Http'cacheCodecTestprovider errors (no igbinary)tests/unitinappwrite/appwrite:2.3.0KeyTestneeds_APP_OPENSSL_KEY_V1(passes with it set);CertificatesDomainValidationTest::testAJobWithoutTheFlagStillChecksDnsdoes a live DNS lookup and does not touchUtopia\Httpapp/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, StorageCacheControlUtopia\Http\Httpresolves topackages/http/src/Http.php;vendor/utopia-php/httpis no longer installedcomposer update --lockchore/absorb-serversdrops onlyutopia-php/http(plus content hash)composer validate --no-check-publishutopia-php/platformexact-constraint warning)bin/monorepo split http --dry-run6bd4eb07, fast-forwards from mirror head7d534357, tree identical topackages/httpMirror
utopia-php/httpalready has amainruleset (id8820115: 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 coversmaster,0.33.xand0.34.x. No classic branch protection onmain.After merge
Splitutopia-php/httppackages/httpfromutopia-php/monorepochore: experiments, #205Radix-trie with hash tables for static routes, #203Improvements 🚧WIP: fix(http): trailing slash vs missing path param🤖 Generated with Claude Code