-
-
Notifications
You must be signed in to change notification settings - Fork 142
feat(commandbus): async commands #685
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
Changes from 16 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
b18f25f
add async middleware and repository
brendt 2a88647
wip
brendt 8ba561b
wip
brendt bfe223a
wip
brendt 0768cc7
Merge branch 'main' into async-commands
brendt 3cf590e
Merge branch 'main' into async-commands
brendt b9f02ce
Add tests
brendt c01d4b1
wip state management
brendt dfe8291
wip state management
brendt bb7a6c9
Merge branch 'main' into async-commands
brendt 07f9e20
Merge remote-tracking branch 'origin/async-commands' into async-commands
brendt 76bd908
wip
brendt de5127e
wip
brendt 0ed5d9a
wip
brendt 1a8a522
wip
brendt 531bd4b
wip
brendt f5f732d
wip
brendt feaf4f9
wip
brendt 7bbd628
merge
brendt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| use Attribute; | ||
|
|
||
| #[Attribute] | ||
| final readonly class AsyncCommand | ||
| { | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| use Ramsey\Uuid\Uuid; | ||
| use Tempest\Core\KernelEvent; | ||
| use Tempest\EventBus\EventHandler; | ||
| use Tempest\Reflection\ClassReflector; | ||
|
|
||
| final readonly class AsyncCommandMiddleware implements CommandBusMiddleware | ||
| { | ||
| public function __construct( | ||
| private CommandBusConfig $commandBusConfig, | ||
| private CommandRepository $repository, | ||
| ) { | ||
| } | ||
|
|
||
| #[EventHandler(KernelEvent::BOOTED)] | ||
| public function onBooted(): void | ||
| { | ||
| $this->commandBusConfig->addMiddleware(self::class); | ||
| } | ||
|
|
||
| public function __invoke(object $command, CommandBusMiddlewareCallable $next): void | ||
| { | ||
| $reflector = new ClassReflector($command); | ||
|
|
||
| if ($reflector->hasAttribute(AsyncCommand::class)) { | ||
| $this->repository->store(Uuid::uuid7()->toString(), $command); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| $next($command); | ||
| } | ||
| } |
56 changes: 56 additions & 0 deletions
56
src/Tempest/CommandBus/src/AsyncCommandRepositories/FileCommandRepository.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus\AsyncCommandRepositories; | ||
|
|
||
| use Tempest\CommandBus\CommandRepository; | ||
| use Tempest\CommandBus\Exceptions\CouldNotResolveCommand; | ||
| use function Tempest\Support\arr; | ||
|
|
||
| final readonly class FileCommandRepository implements CommandRepository | ||
| { | ||
| public function store(string $uuid, object $command): void | ||
| { | ||
| $payload = serialize($command); | ||
|
|
||
| file_put_contents(__DIR__ . "/../stored-commands/{$uuid}.pending.txt", $payload); | ||
| } | ||
|
|
||
| public function find(string $uuid): object | ||
| { | ||
| $path = __DIR__ . "/../stored-commands/{$uuid}.pending.txt"; | ||
|
|
||
| if (! file_exists($path)) { | ||
| throw new CouldNotResolveCommand($uuid); | ||
| } | ||
|
|
||
| $payload = file_get_contents($path); | ||
|
|
||
| return unserialize($payload); | ||
| } | ||
|
|
||
| public function markAsDone(string $uuid): void | ||
| { | ||
| $path = __DIR__ . "/../stored-commands/{$uuid}.pending.txt"; | ||
|
|
||
| unlink($path); | ||
| } | ||
|
|
||
| public function markAsFailed(string $uuid): void | ||
| { | ||
| rename( | ||
| from: __DIR__ . "/../stored-commands/{$uuid}.pending.txt", | ||
| to: __DIR__ . "/../stored-commands/{$uuid}.failed.txt", | ||
| ); | ||
| } | ||
|
|
||
| public function getPendingUuids(): array | ||
| { | ||
| return arr(glob(__DIR__ . "/../stored-commands/*.pending.txt")) | ||
| ->map(function (string $path) { | ||
| return str_replace('.pending.txt', '', pathinfo($path, PATHINFO_BASENAME)); | ||
| }) | ||
| ->toArray(); | ||
| } | ||
| } | ||
37 changes: 37 additions & 0 deletions
37
src/Tempest/CommandBus/src/AsyncCommandRepositories/MemoryRepository.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus\AsyncCommandRepositories; | ||
|
|
||
| use Tempest\CommandBus\CommandRepository; | ||
|
|
||
| final class MemoryRepository implements CommandRepository | ||
| { | ||
| private array $commands = []; | ||
|
|
||
| public function store(string $uuid, object $command): void | ||
| { | ||
| $this->commands[$uuid] = $command; | ||
| } | ||
|
|
||
| public function find(string $uuid): object | ||
| { | ||
| return $this->commands[$uuid]; | ||
| } | ||
|
|
||
| public function markAsDone(string $uuid): void | ||
| { | ||
| unset($this->commands[$uuid]); | ||
| } | ||
|
|
||
| public function markAsFailed(string $uuid): void | ||
| { | ||
| unset($this->commands[$uuid]); | ||
| } | ||
|
|
||
| public function getPendingUuids(): array | ||
| { | ||
| return array_keys($this->commands); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| interface CommandRepository | ||
| { | ||
| public function store(string $uuid, object $command): void; | ||
|
|
||
| public function find(string $uuid): object; | ||
|
|
||
| public function markAsDone(string $uuid): void; | ||
|
|
||
| public function markAsFailed(string $uuid): void; | ||
|
|
||
| /** @return string[] */ | ||
| public function getPendingUuids(): array; | ||
| } |
20 changes: 20 additions & 0 deletions
20
src/Tempest/CommandBus/src/CommandRepositoryInitializer.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| use Tempest\Container\Container; | ||
| use Tempest\Container\Initializer; | ||
| use Tempest\Container\Singleton; | ||
|
|
||
| final readonly class CommandRepositoryInitializer implements Initializer | ||
| { | ||
| #[Singleton] | ||
| public function initialize(Container $container): CommandRepository | ||
| { | ||
| $commandRepositoryClass = $container->get(CommandBusConfig::class)->commandRepositoryClass; | ||
|
|
||
| return $container->get($commandRepositoryClass); | ||
| } | ||
| } |
11 changes: 11 additions & 0 deletions
11
src/Tempest/CommandBus/src/Exceptions/CouldNotResolveCommand.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus\Exceptions; | ||
|
|
||
| use Exception; | ||
|
|
||
| final class CouldNotResolveCommand extends Exception | ||
| { | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| use Tempest\Console\Console; | ||
| use Tempest\Console\ConsoleCommand; | ||
| use Tempest\Console\ExitCode; | ||
| use Tempest\Console\HasConsole; | ||
| use Tempest\Container\Container; | ||
| use Throwable; | ||
|
|
||
| final readonly class HandleAsyncCommand | ||
| { | ||
| use HasConsole; | ||
|
|
||
| public function __construct( | ||
| private CommandBusConfig $commandBusConfig, | ||
| private Container $container, | ||
| private Console $console, | ||
| private CommandRepository $repository, | ||
| ) { | ||
| } | ||
|
|
||
| #[ConsoleCommand(name: 'command:handle')] | ||
| public function __invoke(?string $uuid = null): ExitCode | ||
| { | ||
| $uuid ??= $this->repository->getPendingUuids()[0] ?? null; | ||
|
|
||
| if (! $uuid) { | ||
| $this->error('No pending command found'); | ||
|
|
||
| return ExitCode::ERROR; | ||
| } | ||
|
|
||
| try { | ||
| $command = $this->repository->find($uuid); | ||
|
|
||
| $commandHandler = $this->commandBusConfig->handlers[$command::class] ?? null; | ||
|
|
||
| if (! $commandHandler) { | ||
| $commandClass = $command::class; | ||
|
|
||
| $this->error("No handler found for command {$commandClass}"); | ||
|
|
||
| return ExitCode::ERROR; | ||
| } | ||
|
|
||
| $commandHandler->handler->invokeArgs( | ||
| $this->container->get($commandHandler->handler->getDeclaringClass()->getName()), | ||
| [$command], | ||
| ); | ||
|
|
||
| $this->repository->markAsDone($uuid); | ||
|
|
||
| $this->success('Done'); | ||
|
|
||
| return ExitCode::SUCCESS; | ||
| } catch (Throwable $throwable) { | ||
| $this->repository->markAsFailed($uuid); | ||
|
|
||
| $this->error($throwable->getMessage()); | ||
|
|
||
| return ExitCode::ERROR; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace Tempest\CommandBus; | ||
|
|
||
| use DateTimeImmutable; | ||
| use Symfony\Component\Process\Process; | ||
| use Tempest\Console\Console; | ||
| use Tempest\Console\ConsoleCommand; | ||
| use Tempest\Console\HasConsole; | ||
| use Tempest\Console\Input\ConsoleArgumentBag; | ||
| use function Tempest\Support\arr; | ||
|
|
||
| final readonly class MonitorAsyncCommands | ||
| { | ||
| use HasConsole; | ||
|
|
||
| public function __construct( | ||
| private CommandRepository $repository, | ||
| private ConsoleArgumentBag $argumentBag, | ||
| private Console $console, | ||
| ) { | ||
| } | ||
|
|
||
| #[ConsoleCommand(name: 'command:monitor')] | ||
| public function __invoke(): void | ||
| { | ||
| $this->success("Monitoring for new commands. Press ctrl+c to stop."); | ||
|
|
||
| /** @var \Symfony\Component\Process\Process[] $processes */ | ||
| $processes = []; | ||
|
|
||
| while (true) { // @phpstan-ignore-line | ||
| foreach ($processes as $uuid => $process) { | ||
| $time = new DateTimeImmutable(); | ||
|
|
||
| if ($process->isTerminated()) { | ||
| if ($process->isSuccessful()) { | ||
| $this->writeln("<success>{$uuid}</success> finished at {$time->format('Y-m-d H:i:s')}"); | ||
| } else { | ||
| $this->writeln("<error>{$uuid}</error> failed at {$time->format('Y-m-d H:i:s')}"); | ||
| } | ||
|
|
||
| if ($output = trim($process->getOutput())) { | ||
| $this->writeln($output); | ||
| } | ||
|
|
||
| if ($errorOutput = trim($process->getErrorOutput())) { | ||
| $this->writeln($errorOutput); | ||
| } | ||
|
|
||
| unset($processes[$uuid]); | ||
| } | ||
| } | ||
|
|
||
| $availableUuids = arr($this->repository->getPendingUuids()) | ||
| ->filter(fn (string $uuid) => ! in_array($uuid, array_keys($processes))); | ||
|
|
||
| if (count($processes) === 5) { | ||
| $this->sleep(0.5); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| if ($availableUuids->isEmpty()) { | ||
| $this->sleep(0.5); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| // Start a task | ||
| $uuid = $availableUuids->first(); | ||
|
|
||
| $time = new DateTimeImmutable(); | ||
| $this->writeln("<h2>{$uuid}</h2> started at {$time->format('Y-m-d H:i:s')}"); | ||
|
|
||
| $process = new Process([ | ||
| $this->argumentBag->getBinaryPath(), | ||
| $this->argumentBag->getCliName(), | ||
| 'command:handle', | ||
| $uuid, | ||
| ], getcwd()); | ||
|
|
||
| $process->start(); | ||
|
|
||
| $processes[$uuid] = $process; | ||
| } | ||
| } | ||
|
|
||
| private function sleep(float $seconds): void | ||
| { | ||
| usleep((int) ($seconds * 1_000_000)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| *.txt |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.