Skip to content

Commit 5a54c0d

Browse files
committed
Skips auth context restore for sync queues
Avoids unnecessary auth context restoration and payload modifications when using synchronous queues. This prevents potential issues and overhead in scenarios where jobs are executed immediately without serialization. Specifically: - It prevents adding extra payload for sync queues when creating a queue payload. - It skips restoring auth context when handling a job from a sync queue.
1 parent 7e05b14 commit 5a54c0d

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

src/LaravelAuthQueueServiceProvider.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,24 @@
33
namespace DatPM\LaravelAuthQueue;
44

55
use Illuminate\Queue\Queue;
6+
use Illuminate\Queue\SyncQueue;
67
use Illuminate\Support\Facades\Auth;
78
use Illuminate\Support\ServiceProvider;
89
use DatPM\LaravelAuthQueue\Guards\KernelGuard;
910
use Illuminate\Contracts\Database\ModelIdentifier;
1011
use DatPM\LaravelAuthQueue\Traits\WasAuthenticated;
12+
use Illuminate\Support\Facades\Queue as QueueManager;
1113

1214
class LaravelAuthQueueServiceProvider extends ServiceProvider
1315
{
1416
public function boot()
1517
{
1618
Queue::createPayloadUsing(function ($connectionName, $queue, $payload) {
19+
// Ignore adding extra payload for Sync Queue
20+
if (QueueManager::connection($connectionName) instanceof SyncQueue) {
21+
return [];
22+
}
23+
1724
// Skip attaching authUser when the job does not use WasAuthenticated Trait
1825
if (! in_array(WasAuthenticated::class, class_uses_recursive($payload['displayName']))) {
1926
return [];

src/Middlewares/RestoreAuthenticatedContextMiddleware.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace DatPM\LaravelAuthQueue\Middlewares;
44

5+
use Illuminate\Queue\Jobs\SyncJob;
56
use Illuminate\Support\Facades\Auth;
67
use Illuminate\Queue\SerializesModels;
78
use Illuminate\Contracts\Auth\Authenticatable;
@@ -12,6 +13,11 @@ class RestoreAuthenticatedContextMiddleware
1213

1314
public function handle($command, callable $next)
1415
{
16+
// If the job is being handled in sync, skip restore logic
17+
if ($command->job instanceof SyncJob) {
18+
return $next($command);
19+
}
20+
1521
Auth::shouldUse('kernel');
1622

1723
$guard = auth();

tests/AuthContextQueueListenerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
});
5757

5858
it('preserves auth context when Listener is executed', function () {
59-
Queue::setDefaultDriver('database');
59+
Queue::setDefaultDriver('sync');
6060

6161
/** @var \Mockery\Mock $loggerSpy */
6262
$loggerSpy = Mockery::spy('logger');

0 commit comments

Comments
 (0)