Skip to content

Commit 05aeff8

Browse files
committed
perf(Config): retain stateless config instances in Worker Mode
- add Factories::resetExcept() to selectively clear factory components - add Factories::resetForWorkerMode() preserving persistent factories - add $persistentFactories property to Config\WorkerMode (default: ['config']) - update frankenphp-worker.php.tpl to call Factories::resetForWorkerMode($workerConfig) - update Worker Mode documentation, upgrading guide, and changelog - add unit tests covering selective reset, worker mode persistence, and state isolation
1 parent fbc5fcf commit 05aeff8

8 files changed

Lines changed: 183 additions & 5 deletions

File tree

‎app/Config/WorkerMode.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,22 @@ class WorkerMode
4040
'cache',
4141
];
4242

43+
/**
44+
* Persistent Factory Components
45+
*
46+
* List of factory component names that should persist across requests.
47+
* Configuration instances ('config') are stateless and safe to retain,
48+
* avoiding repeated file location, parsing, and instantiation.
49+
*
50+
* Components not in this list (such as 'models' or 'cells') will be reset
51+
* between requests to prevent state leakage.
52+
*
53+
* @var list<string>
54+
*/
55+
public array $persistentFactories = [
56+
'config',
57+
];
58+
4359
/**
4460
* Reset Event Listeners
4561
*

‎docs/changelogs/v4.7.7.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Release Date: Unreleased
1010

1111
## Changes
1212

13+
- **Worker Mode:** Added `Factories::resetForWorkerMode()` and `Factories::resetExcept()` to retain stateless factory components (by default `'config'`) across requests in FrankenPHP Worker Mode, avoiding repeated class location, parsing, and instantiation. Added `$persistentFactories` property to `Config\WorkerMode`.
14+
1315
## Deprecations
1416

1517
## Bugs Fixed

‎docs/installation/upgrade_477.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@ Please refer to the upgrade instructions corresponding to your installation meth
88

99
## Mandatory File Changes
1010

11+
### Worker Mode
12+
13+
If you are using Worker Mode, you should update **public/frankenphp-worker.php** after upgrading to benefit from stateless config retention between requests. The easiest way is to re-run the install command:
14+
15+
```console
16+
php spark worker:install --force
17+
```
18+
1119
## Breaking Changes
1220

1321
## Breaking Enhancements
@@ -25,10 +33,11 @@ The following files received significant changes (including deprecations or visu
2533

2634
#### Config
2735

28-
- @TODO
36+
- **app/Config/WorkerMode.php**
37+
- `Config\WorkerMode::$persistentFactories` has been added, with a default value set to `['config']`. See [Worker Mode](worker_mode.md#persistent-factories) for details.
2938

3039
### All Changes
3140

3241
This is a list of all files in the **project space** that received changes; many will be simple comments or formatting that have no effect on the runtime:
3342

34-
- @TODO
43+
- **app/Config/WorkerMode.php**

‎docs/installation/worker_mode.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ The key challenge in Worker Mode is preventing state from leaking between reques
5252
Most services are destroyed and recreated for each request. Only services listed in `$persistentServices` survive between requests.
5353

5454
**Factories Reset**
55-
All Factories (Models, Config instances) are reset between requests, ensuring fresh instances without stale data.
55+
Factories are reset between requests to ensure fresh instances without stale data (such as Models and Cells), while stateless components listed in `$persistentFactories` (by default `config`) survive between requests to avoid repeated file location, parsing, and instantiation.
5656

5757
**Superglobals Isolation**
5858
Request data (`$_GET`, `$_POST`, `$_SERVER`, etc.) is properly isolated per request through the Superglobals service.
@@ -137,6 +137,7 @@ All worker mode configuration is managed through the **app/Config/WorkerMode.php
137137
| Option | Type | Description |
138138
|----|----|----|
139139
| **$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+
| **$persistentFactories** | array | Factory components that persist across requests and are not reset. Default: `['config']` |
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

@@ -158,6 +159,18 @@ The `$persistentServices` array controls which services survive between requests
158159
!!! warning "Warning"
159160
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.
160161

162+
### Persistent Factories
163+
164+
!!! success "Available from version 4.7.7"
165+
166+
The `$persistentFactories` array controls which factory components survive between requests.
167+
168+
By default, `'config'` is retained across requests:
169+
170+
- Configuration objects (subclasses of `BaseConfig`) represent immutable application and environment settings.
171+
- Retaining them eliminates repetitive file location searches, class existence checks, environment parsing, and instantiation on every request.
172+
- Factory components not listed (such as `'models'` and `'cells'`) are reset between requests to prevent state leakage.
173+
161174
### Reset Event Listeners
162175

163176
!!! success "Available from version 4.7.1"

‎system/Commands/Worker/Views/frankenphp-worker.php.tpl‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,8 @@ while (frankenphp_handle_request($handler)) {
118118
// Cleanup connections with uncommitted transactions
119119
DatabaseConfig::cleanupForWorkerMode();
120120

121-
// Reset factories
122-
Factories::reset();
121+
// Reset factories except persistent ones
122+
Factories::resetForWorkerMode($workerConfig);
123123

124124
// Reset services except persistent ones
125125
Services::resetForWorkerMode($workerConfig);

‎system/Config/Factories.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\Database\ConnectionInterface;
1818
use CodeIgniter\Exceptions\InvalidArgumentException;
1919
use CodeIgniter\Model;
20+
use Config\WorkerMode;
2021

2122
/**
2223
* Factories for creating instances.
@@ -469,6 +470,55 @@ public static function reset(?string $component = null)
469470
self::$updated = [];
470471
}
471472

473+
/**
474+
* Resets the static arrays for all components except the specified ones.
475+
*
476+
* @param list<string> $components Component names to keep
477+
*/
478+
public static function resetExcept(array $components): void
479+
{
480+
$components = array_map(strtolower(...), $components);
481+
482+
foreach (array_keys(self::$options) as $component) {
483+
if (! in_array($component, $components, true)) {
484+
unset(self::$options[$component]);
485+
}
486+
}
487+
488+
foreach (array_keys(self::$aliases) as $component) {
489+
if (! in_array($component, $components, true)) {
490+
unset(self::$aliases[$component]);
491+
}
492+
}
493+
494+
foreach (array_keys(self::$instances) as $component) {
495+
if (! in_array($component, $components, true)) {
496+
unset(self::$instances[$component]);
497+
}
498+
}
499+
500+
foreach (array_keys(self::$updated) as $component) {
501+
if (! in_array($component, $components, true)) {
502+
unset(self::$updated[$component]);
503+
}
504+
}
505+
}
506+
507+
/**
508+
* Resets factories for Worker Mode.
509+
*
510+
* Preserves only persistent factory components defined in WorkerMode config.
511+
*
512+
* Called at the END of each request to clean up state.
513+
*/
514+
public static function resetForWorkerMode(?WorkerMode $config = null): void
515+
{
516+
$config ??= self::config(WorkerMode::class);
517+
$persistentFactories = $config instanceof WorkerMode ? $config->persistentFactories : ['config'];
518+
519+
self::resetExcept($persistentFactories);
520+
}
521+
472522
/**
473523
* Helper method for injecting mock instances
474524
*

‎tests/system/Commands/Worker/WorkerCommandsTest.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ public function testWorkerInstallCreatesValidPHPFile(): void
165165
$this->assertStringContainsString('frankenphp_handle_request', (string) $content);
166166
$this->assertStringContainsString('DatabaseConfig::reconnectForWorkerMode', (string) $content);
167167
$this->assertStringContainsString('DatabaseConfig::cleanupForWorkerMode', (string) $content);
168+
$this->assertStringContainsString('Factories::resetForWorkerMode', (string) $content);
168169
}
169170

170171
public function testWorkerInstallCreatesValidCaddyfile(): void

‎tests/system/Config/FactoriesTest.php‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\Test\CIUnitTestCase;
1818
use Config\App;
1919
use Config\Database;
20+
use Config\WorkerMode;
2021
use PHPUnit\Framework\Attributes\Depends;
2122
use PHPUnit\Framework\Attributes\Group;
2223
use ReflectionClass;
@@ -526,4 +527,90 @@ public function testGetNonexistentClass(): void
526527

527528
$this->assertNull($config);
528529
}
530+
531+
public function testResetExcept(): void
532+
{
533+
$config = Factories::config('App');
534+
$model = Factories::models(UserModel::class);
535+
536+
$this->assertSame($config, Factories::get('config', 'App'));
537+
$this->assertSame($model, Factories::get('models', UserModel::class));
538+
539+
Factories::resetExcept(['config']);
540+
541+
$this->assertSame($config, Factories::get('config', 'App'));
542+
$this->assertNotSame($model, Factories::models(UserModel::class));
543+
}
544+
545+
public function testResetExceptCaseInsensitive(): void
546+
{
547+
$config = Factories::config('App');
548+
$model = Factories::models(UserModel::class);
549+
550+
Factories::resetExcept(['CONFIG']);
551+
552+
$this->assertSame($config, Factories::get('config', 'App'));
553+
$this->assertNotSame($model, Factories::models(UserModel::class));
554+
}
555+
556+
public function testResetExceptEmptyArrayResetsAll(): void
557+
{
558+
$config = Factories::config('App');
559+
$model = Factories::models(UserModel::class);
560+
561+
Factories::resetExcept([]);
562+
563+
$this->assertNotSame($config, Factories::config('App'));
564+
$this->assertNotSame($model, Factories::models(UserModel::class));
565+
}
566+
567+
public function testResetForWorkerModeWithConfig(): void
568+
{
569+
$workerConfig = new WorkerMode();
570+
$workerConfig->persistentFactories = ['config'];
571+
572+
$config = Factories::config('App');
573+
$model = Factories::models(UserModel::class);
574+
575+
Factories::resetForWorkerMode($workerConfig);
576+
577+
$this->assertSame($config, Factories::get('config', 'App'));
578+
$this->assertNotSame($model, Factories::models(UserModel::class));
579+
}
580+
581+
public function testResetForWorkerModeDefault(): void
582+
{
583+
$config = Factories::config('App');
584+
$model = Factories::models(UserModel::class);
585+
586+
Factories::resetForWorkerMode();
587+
588+
$this->assertSame($config, Factories::get('config', 'App'));
589+
$this->assertNotSame($model, Factories::models(UserModel::class));
590+
}
591+
592+
public function testStateIsolationSequentialCycles(): void
593+
{
594+
$workerConfig = new WorkerMode();
595+
596+
// Cycle 1
597+
$config1 = Factories::config('App');
598+
$model1 = Factories::models(UserModel::class);
599+
$model1->allowCallbacks(false);
600+
$this->assertFalse($this->getPrivateProperty($model1, 'tempAllowCallbacks'));
601+
602+
// End of Cycle 1 cleanup
603+
Factories::resetForWorkerMode($workerConfig);
604+
605+
// Cycle 2
606+
$config2 = Factories::config('App');
607+
$model2 = Factories::models(UserModel::class);
608+
609+
// Config is retained across cycles
610+
$this->assertSame($config1, $config2);
611+
612+
// Model is fresh and not polluted by cycle 1 state
613+
$this->assertNotSame($model1, $model2);
614+
$this->assertTrue($this->getPrivateProperty($model2, 'tempAllowCallbacks'));
615+
}
529616
}

0 commit comments

Comments
 (0)