Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: adds application snapshot and minimizes App::make #980

Open
wants to merge 32 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
5d2c26d
Replaced the 'sandbox' approach with a 'snapshot' approach.
May 13, 2024
72ad7b4
Adjusted the unit tests to reflect the new approach.
May 13, 2024
567100a
Removes some unnecessary event listeners.
May 13, 2024
addacbd
Adds more snapshot tests.
May 13, 2024
2de2e7b
Cleans up redundant code.
May 13, 2024
1af885d
Fixes style ci issues.
May 13, 2024
ad92af6
Fixes style ci issues.
May 13, 2024
8bd1193
Adds test for scoped container instances.
May 14, 2024
d2a2092
Gives event listeners access to the app snapshot.
May 14, 2024
24fc7c4
Adjusted method names.
May 14, 2024
ca23364
Fixes style ci issue.
May 14, 2024
d95ced3
Reverts deleting notification manager listener.
May 15, 2024
616bc37
Registers the listener and adds a test to ensure drivers are flushed.
May 15, 2024
fb89581
Fixes style ci.
May 15, 2024
e499184
Fixes style ci.
May 15, 2024
0290363
Fixes style ci.
May 15, 2024
8940e19
Adds a test to make sure all Application and Container properties can…
May 16, 2024
9b69cd7
Fixes style ci.
May 16, 2024
ef0a0d3
Merge branch 'refs/heads/2.x' into better_approach_to_memory_leaks_v2
Jun 30, 2024
d1af9d4
Testing.
Sep 8, 2024
a241248
Merge branch '2.x' into better_approach_to_memory_leaks_v2
Jan 3, 2025
e0e05c1
App resetter experimentation.
Jan 5, 2025
924fd9d
Cleans up reset logic.
Jan 5, 2025
395a7ff
Ignores line endings in tests.
Jan 5, 2025
8056951
Adds 'forget view engine' test.
Jan 5, 2025
943f25a
Laravel pint.
Jan 5, 2025
4687d48
Fixes str cache test with new Laravel version.
Jan 5, 2025
deb1411
Merge branch '2.x' into perf/application-snapshot
Jan 5, 2025
46a95c5
style.ci
Jan 5, 2025
599b853
style.ci
Jan 5, 2025
0307f79
Adds notice.
Jan 5, 2025
fd39022
Renames variables.
Jan 6, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions config/octane.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@
],

RequestReceived::class => [
...Octane::prepareApplicationForNextOperation(),
...Octane::prepareApplicationForNextRequest(),
//
],

Expand All @@ -85,7 +83,6 @@
],

TaskReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],

Expand All @@ -94,7 +91,6 @@
],

TickReceived::class => [
...Octane::prepareApplicationForNextOperation(),
//
],

Expand Down
15 changes: 9 additions & 6 deletions src/ApplicationGateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Laravel\Octane;

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
Expand All @@ -16,7 +15,7 @@ class ApplicationGateway
{
use DispatchesEvents;

public function __construct(protected Application $app, protected Application $sandbox)
public function __construct(protected ApplicationResetter $resetter, protected Application $snapshot, protected Application $sandbox)
{
}

Expand All @@ -27,13 +26,17 @@ public function handle(Request $request): Response
{
$request->enableHttpMethodParameterOverride();

$this->dispatchEvent($this->sandbox, new RequestReceived($this->app, $this->sandbox, $request));
// reset all default services
$this->resetter->prepareApplicationForNextRequest($request);
$this->resetter->prepareApplicationForNextOperation();

$this->dispatchEvent($this->sandbox, new RequestReceived($this->snapshot, $this->sandbox, $request));

if (Octane::hasRouteFor($request->getMethod(), '/'.$request->path())) {
return Octane::invokeRoute($request, $request->getMethod(), '/'.$request->path());
}

return tap($this->sandbox->make(Kernel::class)->handle($request), function ($response) use ($request) {
return tap($this->resetter->kernel->handle($request), function ($response) use ($request) {
$this->dispatchEvent($this->sandbox, new RequestHandled($this->sandbox, $request, $response));
});
}
Expand All @@ -43,9 +46,9 @@ public function handle(Request $request): Response
*/
public function terminate(Request $request, Response $response): void
{
$this->sandbox->make(Kernel::class)->terminate($request, $response);
$this->resetter->kernel->terminate($request, $response);

$this->dispatchEvent($this->sandbox, new RequestTerminated($this->app, $this->sandbox, $request, $response));
$this->dispatchEvent($this->sandbox, new RequestTerminated($this->snapshot, $this->sandbox, $request, $response));

$route = $request->route();

Expand Down
298 changes: 298 additions & 0 deletions src/ApplicationResetter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,298 @@
<?php

namespace Laravel\Octane;

use Carbon\Carbon;
use Carbon\Laravel\ServiceProvider as CarbonServiceProvider;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\NamespacedItemResolver;
use Illuminate\Support\Str;
use Inertia\ResponseFactory;
use Laravel\Scout\EngineManager;
use Laravel\Socialite\Contracts\Factory;
use Livewire\LivewireManager;
use Monolog\ResettableInterface;

// This class resets the application state efficiently between requests.
// By accessing the initial instances directly we are reducing the overhead
// coming from Application::make() and Container::make().
class ApplicationResetter
{
public Kernel $kernel;

private Application $sandbox;

private ApplicationSnapshot $snapshot;

private Repository $config;

private $url;

private $octaneHttps;

private $initialAppLocale;

private $initialAppFallbackLocale;

private $logDefaultDriver = null;

private $arrayCache = null;

public function __construct(ApplicationSnapshot $snapshot, Application $sandbox)
{
$this->sandbox = $sandbox;
$this->snapshot = $snapshot;
$this->config = $snapshot['config'];
$this->url = $snapshot['url'];
$this->octaneHttps = $this->config->get('octane.https');
$this->initialAppLocale = $this->config->get('app.locale');
$this->initialAppFallbackLocale = $this->config->get('app.fallback_locale');
$this->kernel = $this->snapshot->make(Kernel::class);

if ($this->config->get('cache.stores.array')) {
$this->arrayCache = $this->snapshot->make('cache')->store('array');
}

if ($snapshot->resolved('log')) {
$this->logDefaultDriver = $snapshot->make('log')->driver();
}

if ($snapshot->resolved('auth.driver')) {
$snapshot->forgetInstance('auth.driver');
}
}

public function prepareApplicationForNextRequest(Request $request): void
{
$this->flushLocaleState();
$this->flushCookies();
$this->flushSession();
$this->flushAuthenticationState();
$this->enforceRequestScheme($request);
$this->ensureRequestServerPortMatchesScheme($request);
$this->giveNewRequestInstanceToApplication($request);
}

public function prepareApplicationForNextOperation(): void
{
$this->createConfigurationSandbox();
$this->createUrlGeneratorSandbox();
$this->giveApplicationInstanceToMailManager();
$this->giveApplicationInstanceToNotificationChannelManager();
$this->flushDatabaseState();
$this->flushLogContext();
$this->flushMonologState();
$this->flushArrayCache();
Str::flushCache();
$this->flushTranslatorCache();
$this->forgetViewEngines();

// First-Party Packages...
$this->prepareInertiaForNextOperation();
$this->prepareLivewireForNextOperation();
$this->prepareScoutForNextOperation();
$this->prepareSocialiteForNextOperation();
}

private function flushLocaleState(): void
{
// resetting the locale is an expensive operation
// only do it if the locale has changed
if (Carbon::getLocale() !== $this->initialAppLocale) {
(new CarbonServiceProvider($this->sandbox))->updateLocale();
}
}

private function flushCookies()
{
$this->snapshot->resetInitialInstance('cookie', function ($cookie) {
$cookie->flushQueuedCookies();
});
}

private function flushSession(): void
{
$this->snapshot->resetInitialInstance('session', function ($session) {
$driver = $session->driver();
$driver->flush();
$driver->regenerate();
});
}

private function flushAuthenticationState(): void
{
$this->snapshot->resetInitialInstance('auth', function ($auth) {
$auth->forgetGuards();
});
}

private function enforceRequestScheme(Request $request): void
{
if (! $this->octaneHttps) {
return;
}

$this->snapshot->resetInitialInstance('url', function ($url) use ($request) {
$url->forceScheme('https');
$request->server->set('HTTPS', 'on');
});
}

private function ensureRequestServerPortMatchesScheme(Request $request): void
{
$port = $request->getPort();

if (is_null($port) || $port === '') {
$request->server->set(
'SERVER_PORT',
$request->getScheme() === 'https' ? 443 : 80
);
}
}

private function giveNewRequestInstanceToApplication(Request $request): void
{
$this->sandbox->instance('request', $request);
}

private function createConfigurationSandbox(): void
{
$this->sandbox->instance('config', clone $this->config);
}

private function createUrlGeneratorSandbox(): void
{
$this->sandbox->instance('url', clone $this->url);
}

private function giveApplicationInstanceToMailManager(): void
{
$this->snapshot->resetInitialInstance('mail.manager', function ($mailManager) {
$mailManager->forgetMailers();
});
}

private function giveApplicationInstanceToNotificationChannelManager(): void
{
$this->snapshot->resetInitialInstance(ChannelManager::class, function ($channelManager) {
$channelManager->forgetDrivers();
});
}

private function flushDatabaseState(): void
{
$this->snapshot->resetInitialInstance('db', function ($db) {
foreach ($db->getConnections() as $connection) {
$connection->forgetRecordModificationState();
$connection->flushQueryLog();

// refresh query duration handling
if (
method_exists($connection, 'resetTotalQueryDuration')
&& method_exists($connection, 'allowQueryDurationHandlersToRunAgain')
) {
$connection->resetTotalQueryDuration();
$connection->allowQueryDurationHandlersToRunAgain();
}
}
});
}

private function flushLogContext(): void
{
$this->snapshot->resetInitialInstance('log', function ($log) {
if (method_exists($log, 'flushSharedContext')) {
$log->flushSharedContext();
}

if (method_exists($this->logDefaultDriver, 'withoutContext')) {
$this->logDefaultDriver->withoutContext();
}

if (method_exists($log, 'withoutContext')) {
$log->withoutContext();
}
});
}

private function flushArrayCache(): void
{
if ($this->arrayCache) {
$this->arrayCache->flush();
}
}

private function flushMonologState(): void
{
$this->snapshot->resetInitialInstance('log', function ($log) {
foreach ($log->getChannels() as $channel) {
$logger = $channel->getLogger();
if ($logger instanceof ResettableInterface) {
$logger->reset();
}
}
});
}

private function flushTranslatorCache(): void
{
$this->snapshot->resetInitialInstance('translator', function ($translator) {
$translator->setLocale($this->initialAppLocale);
$translator->setFallback($this->initialAppFallbackLocale);

if ($translator instanceof NamespacedItemResolver) {
$translator->flushParsedKeys();
}
});
}

private function prepareInertiaForNextOperation(): void
{
$this->snapshot->resetInitialInstance(ResponseFactory::class, function ($responseFactory) {
if (method_exists($responseFactory, 'flushShared')) {
$responseFactory->flushShared();
}
});
}

private function prepareLivewireForNextOperation(): void
{
$this->snapshot->resetInitialInstance(LivewireManager::class, function ($livewireManager) {
if (method_exists($livewireManager, 'flushState')) {
$livewireManager->flushState();
}
});
}

private function prepareScoutForNextOperation(): void
{
$this->snapshot->resetInitialInstance(EngineManager::class, function ($engineManager) {
if (method_exists($engineManager, 'forgetEngines')) {
$engineManager->forgetEngines();
}
});
}

private function prepareSocialiteForNextOperation(): void
{
$this->snapshot->resetInitialInstance(Factory::class, function ($socialiteFactory) {
if (! method_exists($socialiteFactory, 'forgetDrivers')) {
return;
}

$socialiteFactory->forgetDrivers();
});
}

private function forgetViewEngines(): void
{
$this->snapshot->resetInitialInstance('view.engine.resolver', function ($resolver) {
$resolver->forget('blade');
$resolver->forget('php');
});
}
}
Loading
Loading