Skip to content

Report misnamespaced ServiceLoader clearly instead of cascading into fatal errors and duplicate output #741

Open

Description

@g105b

Problem

Forgetting the namespace in an application's ServiceLoader.php turns a common setup mistake into a misleading chain of errors. Instead of explaining which namespace is required, WebEngine silently ignores the loader, reports a missing injected service, then can fatally redeclare the loader while attempting to render the error. In the reported v5.1.0 application, the browser displayed both logged-in and logged-out template branches twice, separated by a headers already sent warning.

Reproduced in a minimal Authwave client using phpgt/webengine v5.1.0 (dd0b6827b6ce1681b5b6fc271d6ede2542c71ab5). Also inspected the local WebEngine checkout at ca0fde874824f56b37e5e6e4639f51fe4240455c: the relevant loader lookup, dispatcher reconstruction, and shutdown double-write paths remain present. The complete browser symptom was reproduced against v5.1.0, not independently against this checkout.

Reproduction

Configure Composer autoloading:

{"autoload":{"psr-4":{"AWTest\\":"./class"}}}

Set app.namespace=AWTest in config.ini (app.service_loader defaults to ServiceLoader). Create class/ServiceLoader.php, accidentally omitting namespace AWTest;:

<?php
use Authwave\Authenticator;
use GT\WebEngine\Service\DefaultServiceLoader;

class ServiceLoader extends DefaultServiceLoader {
    public function loadAuthenticator():Authenticator {
        // Actual application constructs Authenticator using config,
        // the request URI, and its session store here.
        // This method is never reached in the failing request.
        throw new \LogicException("Not reached");
    }
}

Request a page whose go() function requires Authwave\Authenticator, with HTML containing logged-in/logged-out branches that go() would normally select between. Authwave is incidental: any application-only service registered by this loader should exercise the same missing-service path. Regenerate Composer autoload files as appropriate, then request the page.

Observed error sequence from the reproduced request:

GT\ServiceContainer\ServiceNotFoundException:
Service can not be located within Container: "Authwave\Authenticator"

PHP Fatal error: Cannot redeclare class ServiceLoader
(previously declared in .../class/ServiceLoader.php:8)

Warning: http_response_code(): Cannot set response code - headers already sent
(output started at .../vendor/phpgt/webengine/src/Application.php:680)

The template showed both auth branches (including the placeholder email), then appeared again after the warning. These are secondary failure symptoms, not evidence that authentication succeeded. Adding namespace AWTest; resolved the underlying loader discovery failure.

Cause and suggested fix locations

  1. Detect an invalid loader rather than silently falling back. ContainerFactory::create() requests AWTest\ServiceLoader via class_exists(). Composer finds and includes the file, but it defines the global ServiceLoader, so the requested class still does not exist. The factory treats this exactly like an absent optional loader and registers DefaultServiceLoader. A diagnostic should distinguish an absent optional file from an existing file that fails to declare the expected class. Resolve candidate files using the configured application class directory and/or Composer's mapping, rather than assuming every app uses class/. Validate the declaration after loading without triggering another autoload attempt. Keep the no-custom-loader case working.

  2. Prevent repeated inclusion from hiding the original error. AppAutoloader::autoload() uses require, and the reproduced fatal stack specifically shows Composer including the misnamespaced file again during error-dispatcher construction. Changing only WebEngine's fallback to require_once would not fix the demonstrated Composer path. Diagnose the first invalid load and avoid repeating the failing application-loader discovery while rendering its error. A fallback-loader inclusion guard is useful additional hardening, but not a complete solution.

  3. Make dispatcher setup failures renderable. Application::start() / handleThrowable() construct the initial dispatcher and replacement error dispatcher outside their respective response-generation try blocks. The replacement dispatcher creates another service container and repeats the failed lookup. Ensure setup exceptions are caught and have a minimal, safe error response that does not depend on successfully constructing the same broken application services. Merely throwing a better exception in ContainerFactory is insufficient unless this setup-error path is handled too. Preserve the original exception in diagnostics.

  4. Write shutdown responses once. In Application::handleShutdown(), the success path calls $this->finish($response) and then falls through to outputHeaders() and outputResponseBody() for the same response. Route both successful error rendering and its fallback through one finalization path, or return after successful finish(). This explains the duplicate output and late header warning in the reproduced shutdown path. The existing $this->finished check at the start of shutdown does not prevent a second write later in that same invocation.

There is also a setup-order concern in Dispatcher::__construct(): the service container is created before AppAutoloader::setup(). A loader diagnostic should work with the documented fallback autoloader as well as Composer; establish application autoloading before attempting custom loader discovery, and cover both modes.

Expected developer experience

Return one HTTP 500 response with an actionable development diagnostic, for example:

Unable to load application service loader AWTest\ServiceLoader.
class/ServiceLoader.php was found, but did not declare AWTest\ServiceLoader.
Check that the file begins with `namespace AWTest;` and declares class ServiceLoader.

If the actual declaration can be identified reliably, include it too. Do not guess that every mismatch is a missing namespace: wrong namespaces and wrong class names should also receive accurate guidance. Retain appropriate production-safe error presentation while logging enough detail to diagnose the mistake. No repeated template, class redeclaration fatal error, or secondary header warning should obscure the cause.

Suggested regression coverage

  • Missing namespace and wrong namespace in a loader file produce an actionable diagnostic naming the expected class and candidate file.
  • A genuinely absent optional loader still uses the default loader; a correctly declared loader still registers application services.
  • Exercise Composer and fallback application autoloading separately, including repeated lookup/error rendering (use isolated PHP processes for redeclaration/fatal cases).
  • An exception during initial or error-dispatcher construction produces one safe 500 response and preserves the original cause.
  • Shutdown handling emits headers/body once both when error rendering succeeds and when it falls back.

Existing test entry points: test/phpunit/Service/ContainerFactoryTest.php, test/phpunit/Logic/AppAutoloaderTest.php, and the Application/Dispatcher lifecycle tests.

Related developer-experience issue: #646 (forgotten class import); this report concerns service-loader declarations and the subsequent error-handling cascade.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions