Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Scheduler] add dependency on symfony/messenger #50096

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Symfony\Component\Scheduler\Generator;

/**
* @author Kevin Bond <[email protected]>
*/
final class ChainMessageGenerator implements MessageGeneratorInterface
{
/**
* @param MessageGeneratorInterface[] $generators
*/
public function __construct(private iterable $generators)
{
}

public function getMessages(): iterable
{
foreach ($this->generators as $generator) {
yield from $generator->getMessages();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

use Psr\Clock\ClockInterface;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Scheduler\Messenger\ScheduledStamp;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\Trigger\TriggerInterface;

Expand All @@ -29,6 +31,7 @@ public function __construct(
private readonly Schedule $schedule,
string|CheckpointInterface $checkpoint,
private readonly ClockInterface $clock = new Clock(),
private readonly ?string $name = null,
) {
$this->waitUntil = new \DateTimeImmutable('@0');
if (\is_string($checkpoint)) {
Expand Down Expand Up @@ -70,7 +73,7 @@ public function getMessages(): \Generator
}

if ($yield) {
yield $message;
yield Envelope::wrap($message, [new ScheduledStamp($this->name, $trigger, $time, $nextTime)]);
$this->checkpoint->save($time, $index);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,18 @@
namespace Symfony\Component\Scheduler\Messenger;

use Symfony\Component\Messenger\Stamp\NonSendableStampInterface;
use Symfony\Component\Scheduler\Trigger\TriggerInterface;

/**
* @experimental
*/
final class ScheduledStamp implements NonSendableStampInterface
{
public function __construct(
public readonly ?string $name,
public readonly TriggerInterface $trigger,
public readonly \DateTimeImmutable $runAt,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we need a better name? This might not be the true run date (if the scheduler is catching up). Maybe $expectedRunAt?

/cc @tucksaun

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expectedRunAt sounds indeed better than runAt.

Other suggestions:

  • scheduledAt
  • triggeredAt (to keep the idea of the trigger)

public readonly \DateTimeImmutable $nextRun,
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct(
public function get(): iterable
{
foreach ($this->messageGenerator->getMessages() as $message) {
yield Envelope::wrap($message, [new ScheduledStamp()]);
yield Envelope::wrap($message);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function createTransport(string $dsn, array $options, SerializerInterface
$schedule = $this->scheduleProviders->get($scheduleName)->getSchedule();
$checkpoint = new Checkpoint('scheduler_checkpoint_'.$scheduleName, $schedule->getLock(), $schedule->getState());

return new SchedulerTransport(new MessageGenerator($schedule, $checkpoint, $this->clock));
return new SchedulerTransport(new MessageGenerator($schedule, $checkpoint, $this->clock, $scheduleName));
}

public function supports(string $dsn, array $options): bool
Expand Down
57 changes: 36 additions & 21 deletions src/Symfony/Component/Scheduler/Scheduler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,12 @@

use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Worker;
use Symfony\Component\Scheduler\Generator\ChainMessageGenerator;
use Symfony\Component\Scheduler\Generator\MessageGenerator;
use Symfony\Component\Scheduler\Messenger\SchedulerTransport;

/**
* @experimental
Expand All @@ -25,19 +30,39 @@ final class Scheduler
*/
private array $generators = [];
private int $index = 0;
private bool $shouldStop = false;
private MessageBusInterface $bus;
private Worker $worker;

/**
* @param array<class-string,callable> $handlers
* @param iterable<Schedule> $schedules
*/
public function __construct(
private readonly array $handlers,
array $handlers,
array $schedules,
private readonly ClockInterface $clock = new Clock(),
) {
foreach ($schedules as $schedule) {
$this->addSchedule($schedule);
}

$this->bus = new class($handlers) implements MessageBusInterface {
/**
* @param array<class-string,callable> $handlers
*/
public function __construct(private array $handlers)
{
}

public function dispatch(object $message, array $stamps = []): Envelope
{
$envelope = Envelope::wrap($message, $stamps);

$this->handlers[$envelope->getMessage()::class]($envelope->getMessage());

return $envelope;
}
};
}

public function addSchedule(Schedule $schedule): void
Expand All @@ -58,29 +83,19 @@ public function addMessageGenerator(MessageGenerator $generator): void
*/
public function run(array $options = []): void
{
$options += ['sleep' => 1e6];
$this->worker = new Worker(
[new SchedulerTransport(new ChainMessageGenerator($this->generators))],
$this->bus,
clock: $this->clock,
);

while (!$this->shouldStop) {
$start = $this->clock->now();

$ran = false;
foreach ($this->generators as $generator) {
foreach ($generator->getMessages() as $message) {
$this->handlers[$message::class]($message);
$ran = true;
}
}

if (!$ran) {
if (0 < $sleep = (int) ($options['sleep'] - 1e6 * ($this->clock->now()->format('U.u') - $start->format('U.u')))) {
$this->clock->sleep($sleep / 1e6);
}
}
}
$this->worker->run($options + ['sleep' => 1e6]);
}

public function stop(): void
{
$this->shouldStop = true;
if (isset($this->worker)) {
$this->worker->stop();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Scheduler\Generator\MessageGenerator;
use Symfony\Component\Scheduler\Messenger\ScheduledStamp;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\Trigger\TriggerInterface;
Expand All @@ -40,14 +42,20 @@ public function testGetMessages(string $startTime, array $runs, array $schedule)
$schedule = (new Schedule())->add(...$schedule);
$schedule->stateful(new ArrayAdapter());

$scheduler = new MessageGenerator($schedule, 'dummy', $clock);
$scheduler = new MessageGenerator($schedule, 'dummy', $clock, 'dummy');

// Warmup. The first run is always returns nothing.
$this->assertSame([], iterator_to_array($scheduler->getMessages()));

foreach ($runs as $time => $expected) {
$now = self::makeDateTime($time);
$this->assertSame($expected, iterator_to_array($scheduler->getMessages()));
$messages = iterator_to_array($scheduler->getMessages());
$this->assertSame($expected, \array_map(fn(Envelope $e) => $e->getMessage(), $messages));

foreach ($messages as $envelope) {
$this->assertNotNull($stamp = $envelope->last(ScheduledStamp::class));
$this->assertSame('dummy', $stamp->name);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public function testCreateTransport()
$defaultRecurringMessage = RecurringMessage::trigger($trigger, (object) ['id' => 'default']);
$customRecurringMessage = RecurringMessage::trigger($trigger, (object) ['id' => 'custom']);

$default = new SchedulerTransport(new MessageGenerator((new SomeScheduleProvider([$defaultRecurringMessage]))->getSchedule(), 'default', $clock));
$custom = new SchedulerTransport(new MessageGenerator((new SomeScheduleProvider([$customRecurringMessage]))->getSchedule(), 'custom', $clock));
$default = new SchedulerTransport(new MessageGenerator((new SomeScheduleProvider([$defaultRecurringMessage]))->getSchedule(), 'default', $clock, 'default'));
$custom = new SchedulerTransport(new MessageGenerator((new SomeScheduleProvider([$customRecurringMessage]))->getSchedule(), 'custom', $clock, 'custom'));

$factory = new SchedulerTransportFactory(
new Container([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Scheduler\Exception\LogicException;
use Symfony\Component\Scheduler\Generator\MessageGeneratorInterface;
use Symfony\Component\Scheduler\Messenger\ScheduledStamp;
use Symfony\Component\Scheduler\Messenger\SchedulerTransport;

class SchedulerTransportTest extends TestCase
Expand All @@ -33,7 +32,6 @@ public function testGetFromIterator()

foreach ($transport->get() as $envelope) {
$this->assertInstanceOf(Envelope::class, $envelope);
$this->assertNotNull($envelope->last(ScheduledStamp::class));
$this->assertSame(array_shift($messages), $envelope->getMessage());
}

Expand Down
43 changes: 43 additions & 0 deletions src/Symfony/Component/Scheduler/Tests/SchedulerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Symfony\Component\Scheduler\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\Scheduler;

class SchedulerTest extends TestCase
{
/**
* @test
*/
public function can_run(): void
{
$handler = new Handler();
$schedule = (new Schedule())->add(RecurringMessage::every('1 microseconds', new Message()));
$scheduler = new Scheduler([Message::class => $handler], [$schedule]);
$handler->scheduler = $scheduler;

$scheduler->run(['sleep' => 0]);

$this->assertSame(3, $handler->count);
}
}

class Message
{
}

class Handler
{
public int $count = 0;
public Scheduler $scheduler;

public function __invoke(Message $message): void
{
if (3 === ++$this->count) {
$this->scheduler->stop();
}
}
}
6 changes: 3 additions & 3 deletions src/Symfony/Component/Scheduler/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
],
"require": {
"php": ">=8.1",
"symfony/clock": "^6.3"
"symfony/clock": "^6.3",
"symfony/messenger": "^6.3"
},
"require-dev": {
"dragonmantank/cron-expression": "^3",
"symfony/cache": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/lock": "^5.4|^6.0",
"symfony/messenger": "^6.3"
"symfony/lock": "^5.4|^6.0"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Scheduler\\": "" },
Expand Down