brefphp / laravel-bridge

Package to use Laravel on AWS Lambda with Bref
https://bref.sh/docs/frameworks/laravel.html
MIT License
319 stars 63 forks source link

Allow Lambda invocation context to be injected #18

Closed i906 closed 1 year ago

i906 commented 3 years ago

With this PR, I can inject the Lambda invocation context into jobs.

<?php

namespace App\Jobs;

use Bref\Context\Context;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class LambdaTest implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $work = 0;

    public function handle(Context $context)
    {
        $shouldPause = false;

        while (!$this->isWorkDone() && !$shouldPause) {
            $this->doWork();

            // check deadline
            $remaining = $context->getRemainingTimeInMillis();
            $shouldPause = $remaining < 1500;
        }

        if (!$this->isWorkDone()) {
            // pause and requeue
        } else {
            // cleanup
        }
    }

    protected function doWork()
    {
        $this->work++;
    }

    protected function isWorkDone()
    {
        return $this->work >= 100;
    }
}
mnapoli commented 1 year ago

Closing as this PR is from 2020 and the Queues integration will radically change in https://github.com/brefphp/laravel-bridge/pull/94