Skip to content

Commit a03f94e

Browse files
committed
fix: stop persisting routes service in worker mode (hostname/subdomain route options)
1 parent e4d791d commit a03f94e

5 files changed

Lines changed: 84 additions & 7 deletions

File tree

‎app/Config/WorkerMode.php‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,14 @@ class WorkerMode
2424
* - `commands`: CLI commands registry
2525
* - `codeigniter`: Main application instance
2626
* - `superglobals`: Superglobals wrapper
27-
* - `routes`: Router configuration
2827
* - `cache`: Cache instance
2928
*
29+
* The `routes` service is intentionally not persistent. `RouteCollection`
30+
* reads the request host and drops the routes limited with the `hostname`
31+
* or `subdomain` options while the route file is loaded. Persisting it
32+
* would make those decisions once, from the first request the worker
33+
* served, so route definitions are loaded again for each request.
34+
*
3035
* @var list<string>
3136
*/
3237
public array $persistentServices = [
@@ -36,7 +41,6 @@ class WorkerMode
3641
'commands',
3742
'codeigniter',
3843
'superglobals',
39-
'routes',
4044
'cache',
4145
];
4246

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,5 +50,6 @@ Release Date: Unreleased
5050
- **Session:** Fixed a bug where `MemcachedHandler` did not reset lock state in `close()` or release an existing lock for a different session ID in `lockSession()`, causing subsequent reads and session ID regeneration on the same handler instance to fail.
5151
- **Session:** Fixed a bug where `Session::start()` did not remove an invalid session cookie from `Request`'s cached cookie global if cookies had already been read from `Request`.
5252
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.
53+
- **Worker Mode:** Fixed a bug where routes limited with the `hostname` or `subdomain` options were matched against the first request the worker served, so a host-restricted route became reachable from any host, and a route limited to another host stayed unreachable, until the worker restarted. The `routes` service is no longer persistent by default, so route definitions are loaded for each request. See [Worker Mode Routes Are Reloaded Per Request](../installation/upgrade_477.md#worker-mode-routes-are-reloaded-per-request) for migration instructions.
5354

5455
See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed.

‎docs/installation/upgrade_477.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,38 @@ With the default configuration most applications are unaffected, because `/`, `\
1818

1919
## Breaking Enhancements
2020

21+
## Behavior Changes
22+
23+
### Worker Mode Routes Are Reloaded Per Request
24+
25+
`Config\WorkerMode::$persistentServices` no longer contains `routes`.
26+
27+
`RouteCollection` reads the request host while it loads the route definitions, and drops the routes limited with the `hostname` or `subdomain` options that do not match the current request. While the routes service was persistent, those decisions were made once, from the first request the worker served, and were kept for the lifetime of the process. A route limited to a hostname then became reachable from any `Host` after that first request, and a route that lost the first decision stayed unreachable until the worker restarted. The routes service is not persistent anymore, so the route definitions are loaded for each request and the host is evaluated on every request, as in traditional PHP.
28+
29+
A new installation gets the updated default. Existing installations have their own copy of **app/Config/WorkerMode.php** in the project space, so it is not changed on upgrade. If your application uses the `hostname` or `subdomain` route options in Worker Mode, remove `routes` from `$persistentServices`:
30+
31+
```php
32+
<?php
33+
34+
namespace Config;
35+
36+
class WorkerMode
37+
{
38+
// ...
39+
public array $persistentServices = [
40+
'autoloader',
41+
'locator',
42+
'exceptions',
43+
'commands',
44+
'codeigniter',
45+
'superglobals',
46+
'cache',
47+
];
48+
}
49+
```
50+
51+
See [Persistent Services](worker_mode.md#persistent-services) for details.
52+
2153
## Project Files
2254

2355
Some files in the **project space** (root, app, public, writable) received updates. Due to these files being outside of the **system** scope they will not be changed without your intervention.
@@ -31,7 +63,8 @@ The following files received significant changes (including deprecations or visu
3163

3264
#### Config
3365

34-
- @TODO
66+
- **app/Config/WorkerMode.php**
67+
- `Config\WorkerMode::$persistentServices` no longer contains `routes`. See [Worker Mode Routes Are Reloaded Per Request](#worker-mode-routes-are-reloaded-per-request).
3568

3669
### All Changes
3770

‎docs/installation/worker_mode.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,11 @@ In Worker Mode, the lifecycle changes dramatically:
3333

3434
1. Worker process starts and performs one-time initialization:
3535
- Loads and parses all required files (cached in OPcache)
36-
- Bootstraps framework: autoloader, configuration, services, routes
36+
- Bootstraps framework: autoloader, configuration, services
3737
- Establishes database and cache connections
3838
2. For each incoming request:
3939
- Reuses existing connections and cached resources
40+
- Reloads the route definitions, so the routes limited with the `hostname` or `subdomain` options are matched against the current request
4041
- Resets only request-specific state (superglobals, request/response objects)
4142
- Processes request and sends response
4243
- Cleans up request-specific data
@@ -118,7 +119,7 @@ Worker Mode typically provides **2-3x performance improvements** for database-dr
118119
|----|----|
119120
| **Simple endpoints** | Applications returning minimal JSON responses show modest improvements (10-30%), as there's little bootstrap overhead to eliminate. |
120121
| **Database queries** | Endpoints performing database queries typically see **2-3x** improvements from connection reuse and reduced initialization overhead. |
121-
| **Complex bootstrap** | Applications with many services, routes, or configuration see the largest gains, as this overhead is eliminated entirely. |
122+
| **Complex bootstrap** | Applications with many services or configuration see the largest gains, as this overhead is eliminated entirely. |
122123

123124
### Worker Count Considerations
124125

@@ -136,7 +137,7 @@ All worker mode configuration is managed through the **app/Config/WorkerMode.php
136137

137138
| Option | Type | Description |
138139
|----|----|----|
139-
| **$persistentServices** | array | Services that persist across requests and are not reset. Services not in this list are destroyed after each request to prevent state leakage. Default: `['autoloader', 'locator', 'exceptions', 'commands', 'codeigniter', 'superglobals', 'routes', 'cache']` |
140+
| **$persistentServices** | array | Services that persist across requests and are not reset. Services not in this list are destroyed after each request to prevent state leakage. Default: `['autoloader', 'locator', 'exceptions', 'commands', 'codeigniter', 'superglobals', 'cache']` |
140141
| **$resetEventListeners** | array | Event names whose listeners are removed between requests. Use this when you register event listeners inside other event callbacks rather than at the top level of **Config/Events.php**, which would cause them to accumulate across requests. Default: `[]` |
141142
| **$forceGarbageCollection** | bool | Whether to force garbage collection after each request. `true` (default, recommended): Prevents memory leaks. `false`: Relies on PHP's automatic garbage collection. |
142143

@@ -152,9 +153,11 @@ The `$persistentServices` array controls which services survive between requests
152153
| `commands` | CLI commands registry. Only used during worker startup. |
153154
| `codeigniter` | Main application instance. Orchestrates the request/response cycle. |
154155
| `superglobals` | Superglobals wrapper. Properly isolated per request internally. |
155-
| `routes` | Router configuration. Route definitions don't change between requests. |
156156
| `cache` | Cache service. Maintains connections to cache backends (Redis, Memcached). |
157157

158+
!!! note "Note"
159+
The `routes` service is **not** persistent by default. `RouteCollection` reads the request host while it loads the route definitions, and drops the routes limited with the `hostname` or `subdomain` options that do not match the current request. A persistent route collection would keep the decision made for the first request the worker served, so the routes restricted to a hostname would be reachable from any host, or not reachable at all, until the worker restarted. The route definitions are therefore loaded again for each request. The cost is small compared with the bootstrap work Worker Mode already removes, and it keeps the route behavior identical to traditional PHP.
160+
158161
!!! warning "Warning"
159162
Adding services to `$persistentServices` without understanding their state management can cause data leakage between requests. Only persist services that are truly stateless or manage their own request isolation.
160163

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Config;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
use Config\WorkerMode;
18+
use PHPUnit\Framework\Attributes\Group;
19+
20+
/**
21+
* @internal
22+
*/
23+
#[Group('Others')]
24+
final class WorkerModeTest extends CIUnitTestCase
25+
{
26+
public function testRoutesServiceIsNotPersistentByDefault(): void
27+
{
28+
$config = new WorkerMode();
29+
30+
$this->assertNotContains(
31+
'routes',
32+
$config->persistentServices,
33+
'The routes service must not be persistent, or the hostname/subdomain route options are decided once per worker process instead of once per request.',
34+
);
35+
}
36+
}

0 commit comments

Comments
 (0)