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

Skip to content

[Messenger][Scheduler] Add AsCronTask & AsPeriodicTask attributes #51525

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

Merged
merged 1 commit into from
Oct 1, 2023
Merged
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
Expand Up @@ -84,6 +84,7 @@ class UnusedTagsPass implements CompilerPassInterface
'routing.loader',
'routing.route_loader',
'scheduler.schedule_provider',
'scheduler.task',
'security.authenticator.login_linker',
'security.expression_language_provider',
'security.remember_me_handler',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@
use Symfony\Component\RemoteEvent\Attribute\AsRemoteEventConsumer;
use Symfony\Component\RemoteEvent\RemoteEvent;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Scheduler\Attribute\AsCronTask;
use Symfony\Component\Scheduler\Attribute\AsPeriodicTask;
use Symfony\Component\Scheduler\Attribute\AsSchedule;
use Symfony\Component\Scheduler\Messenger\SchedulerTransportFactory;
use Symfony\Component\Security\Core\AuthenticationEvents;
Expand Down Expand Up @@ -701,6 +703,26 @@ public function load(array $configs, ContainerBuilder $container)
$container->registerAttributeForAutoconfiguration(AsSchedule::class, static function (ChildDefinition $definition, AsSchedule $attribute): void {
$definition->addTag('scheduler.schedule_provider', ['name' => $attribute->name]);
});
foreach ([AsPeriodicTask::class, AsCronTask::class] as $taskAttributeClass) {
$container->registerAttributeForAutoconfiguration(
$taskAttributeClass,
static function (ChildDefinition $definition, AsPeriodicTask|AsCronTask $attribute, \ReflectionClass|\ReflectionMethod $reflector): void {
$tagAttributes = get_object_vars($attribute) + [
'trigger' => match ($attribute::class) {
AsPeriodicTask::class => 'every',
AsCronTask::class => 'cron',
},
];
if ($reflector instanceof \ReflectionMethod) {
if (isset($tagAttributes['method'])) {
throw new LogicException(sprintf('%s attribute cannot declare a method on "%s::%s()".', $attribute::class, $reflector->class, $reflector->name));
}
$tagAttributes['method'] = $reflector->getName();
}
$definition->addTag('scheduler.task', $tagAttributes);
}
);
}

if (!$container->getParameter('kernel.debug')) {
// remove tagged iterator argument for resource checkers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,15 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\Scheduler\Messenger\SchedulerTransportFactory;
use Symfony\Component\Scheduler\Messenger\ServiceCallMessageHandler;

return static function (ContainerConfigurator $container) {
$container->services()
->set('scheduler.messenger.service_call_message_handler', ServiceCallMessageHandler::class)
->args([
tagged_locator('scheduler.task'),
])
->tag('messenger.message_handler')
->set('scheduler.messenger_transport_factory', SchedulerTransportFactory::class)
->args([
tagged_locator('scheduler.schedule_provider', 'name'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Fixtures\Messenger;

use Symfony\Component\Scheduler\Attribute\AsCronTask;
use Symfony\Component\Scheduler\Attribute\AsPeriodicTask;

#[AsCronTask(expression: '* * * * *', arguments: [1], schedule: 'dummy')]
#[AsCronTask(expression: '0 * * * *', timezone: 'Europe/Berlin', arguments: ['2'], schedule: 'dummy', method: 'method2')]
#[AsPeriodicTask(frequency: 5, arguments: [3], schedule: 'dummy')]
#[AsPeriodicTask(frequency: 'every day', from: '00:00:00', jitter: 60, arguments: ['4'], schedule: 'dummy', method: 'method4')]
class DummyTask
{
public static array $calls = [];

#[AsPeriodicTask(frequency: 'every hour', from: '09:00:00', until: '17:00:00', arguments: ['b' => 6, 'a' => '5'], schedule: 'dummy')]
#[AsCronTask(expression: '0 0 * * *', arguments: ['7', 8], schedule: 'dummy')]
public function attributesOnMethod(string $a, int $b): void
{
self::$calls[__FUNCTION__][] = [$a, $b];
}

public function __call(string $name, array $arguments)
{
self::$calls[$name][] = $arguments;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ services:
Symfony\Bundle\FrameworkBundle\Tests\Fixtures\Messenger\DummySchedule:
autoconfigure: true

Symfony\Bundle\FrameworkBundle\Tests\Fixtures\Messenger\DummyTask:
autoconfigure: true
Copy link
Member

Choose a reason for hiding this comment

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

There are no tests associated with this, can you add some @valtzu?
I've moved these to a new schedule to avoid breaking the existing tests (#51802).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@fabpot I'm not too familiar with the framework tests yet, and I'm also a bit busy now. I would need a week or two, if that's ok then I can try.

Copy link
Member

Choose a reason for hiding this comment

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

Sure, there is no rush. Ping me if you need help.


clock:
synthetic: true

Expand Down
11 changes: 9 additions & 2 deletions src/Symfony/Component/Messenger/Message/RedispatchMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,22 @@

use Symfony\Component\Messenger\Envelope;

final class RedispatchMessage
final class RedispatchMessage implements \Stringable
{
/**
* @param object|Envelope $message The message or the message pre-wrapped in an envelope
* @param object|Envelope $envelope The message or the message pre-wrapped in an envelope
* @param string[]|string $transportNames Transport names to be used for the message
*/
public function __construct(
public readonly object $envelope,
public readonly array|string $transportNames = [],
) {
}

public function __toString(): string
{
$message = $this->envelope instanceof Envelope ? $this->envelope->getMessage() : $this->envelope;

return sprintf('%s via %s', $message instanceof \Stringable ? (string) $message : $message::class, implode(', ', (array) $this->transportNames));
}
}
32 changes: 32 additions & 0 deletions src/Symfony/Component/Scheduler/Attribute/AsCronTask.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Scheduler\Attribute;

/**
* A marker to call a service method from scheduler.
*
* @author valtzu <[email protected]>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class AsCronTask
{
public function __construct(
public readonly string $expression,
public readonly ?string $timezone = null,
public readonly ?int $jitter = null,
public readonly array|string|null $arguments = null,
public readonly string $schedule = 'default',
public readonly ?string $method = null,
public readonly array|string|null $transports = null,
) {
}
}
33 changes: 33 additions & 0 deletions src/Symfony/Component/Scheduler/Attribute/AsPeriodicTask.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Scheduler\Attribute;

/**
* A marker to call a service method from scheduler.
*
* @author valtzu <[email protected]>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class AsPeriodicTask
{
public function __construct(
public readonly string|int $frequency,
public readonly ?string $from = null,
public readonly ?string $until = null,
public readonly ?int $jitter = null,
public readonly array|string|null $arguments = null,
public readonly string $schedule = 'default',
public readonly ?string $method = null,
public readonly array|string|null $transports = null,
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@

namespace Symfony\Component\Scheduler\DependencyInjection;

use Symfony\Component\Console\Messenger\RunCommandMessage;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Messenger\Message\RedispatchMessage;
use Symfony\Component\Messenger\Transport\TransportInterface;
use Symfony\Component\Scheduler\Messenger\ServiceCallMessage;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;

/**
* @internal
Expand All @@ -29,8 +35,69 @@ public function process(ContainerBuilder $container): void
$receivers[$tags[0]['alias']] = true;
}

foreach ($container->findTaggedServiceIds('scheduler.schedule_provider') as $tags) {
$scheduleProviderIds = [];
foreach ($container->findTaggedServiceIds('scheduler.schedule_provider') as $serviceId => $tags) {
$name = $tags[0]['name'];
$scheduleProviderIds[$name] = $serviceId;
}

$tasksPerSchedule = [];
foreach ($container->findTaggedServiceIds('scheduler.task') as $serviceId => $tags) {
foreach ($tags as $tagAttributes) {
$serviceDefinition = $container->getDefinition($serviceId);
$scheduleName = $tagAttributes['schedule'] ?? 'default';

if ($serviceDefinition->hasTag('console.command')) {
$message = new Definition(RunCommandMessage::class, [$serviceDefinition->getClass()::getDefaultName().(empty($tagAttributes['arguments']) ? '' : " {$tagAttributes['arguments']}")]);
} else {
$message = new Definition(ServiceCallMessage::class, [$serviceId, $tagAttributes['method'] ?? '__invoke', (array) ($tagAttributes['arguments'] ?? [])]);
}

if ($tagAttributes['transports'] ?? null) {
$message = new Definition(RedispatchMessage::class, [$message, $tagAttributes['transports']]);
}

$taskArguments = [
'$message' => $message,
] + array_filter(match ($tagAttributes['trigger'] ?? throw new InvalidArgumentException("Tag 'scheduler.task' is missing attribute 'trigger' on service $serviceId.")) {
'every' => [
'$frequency' => $tagAttributes['frequency'] ?? throw new InvalidArgumentException("Tag 'scheduler.task' is missing attribute 'frequency' on service $serviceId."),
'$from' => $tagAttributes['from'] ?? null,
'$until' => $tagAttributes['until'] ?? null,
],
'cron' => [
'$expression' => $tagAttributes['expression'] ?? throw new InvalidArgumentException("Tag 'scheduler.task' is missing attribute 'expression' on service $serviceId."),
'$timezone' => $tagAttributes['timezone'] ?? null,
],
}, fn ($value) => null !== $value);

$tasksPerSchedule[$scheduleName][] = $taskDefinition = (new Definition(RecurringMessage::class))
->setFactory([RecurringMessage::class, $tagAttributes['trigger']])
->setArguments($taskArguments);

if ($tagAttributes['jitter'] ?? false) {
$taskDefinition->addMethodCall('withJitter', [$tagAttributes['jitter']], true);
}
}
}

foreach ($tasksPerSchedule as $scheduleName => $tasks) {
$id = "scheduler.provider.$scheduleName";
$schedule = (new Definition(Schedule::class))->addMethodCall('add', $tasks);

if (isset($scheduleProviderIds[$scheduleName])) {
$schedule
->setFactory([new Reference('.inner'), 'getSchedule'])
->setDecoratedService($scheduleProviderIds[$scheduleName]);
} else {
$schedule->addTag('scheduler.schedule_provider', ['name' => $scheduleName]);
$scheduleProviderIds[$scheduleName] = $id;
}

$container->setDefinition($id, $schedule);
}

foreach (array_keys($scheduleProviderIds) as $name) {
$transportName = 'scheduler_'.$name;

// allows to override the default transport registration
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Scheduler\Messenger;

/**
* Represents a service call.
*
* @author valtzu <[email protected]>
*/
class ServiceCallMessage implements \Stringable
{
public function __construct(
private readonly string $serviceId,
private readonly string $method = '__invoke',
private readonly array $arguments = [],
) {
}

public function getServiceId(): string
{
return $this->serviceId;
}

public function getMethod(): string
{
return $this->method;
}

public function getArguments(): array
{
return $this->arguments;
}

public function __toString(): string
{
return "@$this->serviceId".('__invoke' !== $this->method ? "::$this->method" : '');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Scheduler\Messenger;

use Psr\Container\ContainerInterface;

/**
* Handler to call any service.
*
* @author valtzu <[email protected]>
*/
class ServiceCallMessageHandler
{
public function __construct(private readonly ContainerInterface $serviceLocator)
{
}

public function __invoke(ServiceCallMessage $message): void
{
$this->serviceLocator->get($message->getServiceId())->{$message->getMethod()}(...$message->getArguments());
}
}