diff --git a/composer.json b/composer.json index 53f147b..a4d4788 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,6 @@ "require": { "php": ">=8.2", "cakephp/cakephp": "^5.4.0", - "enqueue/simple-client": "^0.10", "psr/log": "^3.0", "ramsey/uuid": "^4.7.0" }, @@ -67,7 +66,7 @@ "phpstan": "tools/phpstan analyse", "stan-baseline": "tools/phpstan --generate-baseline", "stan-setup": "phive install", - "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.5.0\" && mv composer.backup composer.json", + "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.8.0\" && mv composer.backup composer.json", "rector-check": "vendor/bin/rector process --dry-run", "rector-fix": "vendor/bin/rector process", "test": "phpunit", diff --git a/docs/.vitepress/toc_en.json b/docs/.vitepress/toc_en.json index 0b3cec8..f27190c 100644 --- a/docs/.vitepress/toc_en.json +++ b/docs/.vitepress/toc_en.json @@ -15,6 +15,7 @@ "items": [ { "text": "Queueing Mail", "link": "/mail" }, { "text": "Custom Processors", "link": "/processors" }, + { "text": "Custom Clients", "link": "/clients" }, { "text": "Running Workers", "link": "/workers" } ] }, diff --git a/docs/en/clients.md b/docs/en/clients.md new file mode 100644 index 0000000..a85f4a0 --- /dev/null +++ b/docs/en/clients.md @@ -0,0 +1,70 @@ +# Custom Clients + +Queue connections use `Cake\Queue\Client\EnqueueClient` by default. A connection can use a custom client class by setting the `clientClass` option in the queue configuration. The class must extend `Cake\Queue\Client\EnqueueClient`. + +```php +'Queue' => [ + 'default' => [ + 'url' => 'null:', + 'queue' => 'default', + ], + 'audited' => [ + 'url' => 'redis://localhost:6379', + 'queue' => 'audited', + 'clientClass' => \App\Queue\AuditedClient::class, + ], +], +``` + +If no client class is configured, the plugin uses `Cake\Queue\Client\EnqueueClient`. + +## Configuration + +`EnqueueClient` is built from the `url` value without any Symfony configuration processing. The `url` value can be a DSN string or an array with `transport`, `client` and `extensions` sections. Extra transport keys are passed to the connection factory. Use `connection_factory_class` inside the `transport` section to provide a custom `Interop\Queue\ConnectionFactory`. + +## Produce Events + +The client dispatches two events around every produce operation. Subscribe to these events on the client event manager to observe publishing. + +- `Queue.produce.success` is dispatched after the transport accepts the message. Payload keys: `topic` or `command`, `messageId`, `transportDestination`. For commands the payload also includes `promise`. +- `Queue.produce.failure` is dispatched when the transport throws. Payload keys: `topic` or `command`, `exception`. The original exception is rethrown after dispatch. + +Produce events carry identifiers and routing metadata only, never message bodies. The sender already holds the message object, while events are broadcast to every listener, so bodies are deliberately excluded. Event payloads are safe to log. + +The `messageId` value is assigned by the transport during `sendEvent` or `sendCommand`. The client only observes it through the post send extension and never generates it. `QueueManager::push()` returns this value on success and `null` when a unique push is skipped as duplicate. + +Direct calls on `$client->getProducer()->sendEvent()` or `sendCommand()` bypass these events. Only `EnqueueClient::sendEvent()`, `EnqueueClient::sendCommand()` and `QueueManager::push()` dispatch produce events. + +When binding processors, always pass an explicit `$processorName`. Names generated with `uniqid()` are a fallback for tests and prototypes, not a naming scheme. + +Custom client classes with a non-standard producer must assign a message id on the passed message before returning, otherwise `QueueManager::push()` reports `null` on success, indistinguishable from a push skipped as duplicate. + +## Example + +```php +getEventManager()->on('Queue.produce.success', function ($event) { + $messageId = $event->getData('messageId'); +}); +``` + +The worker side keeps its own event set. See Worker Events for processing events. diff --git a/docs/en/events.md b/docs/en/events.md index 677b516..f80d6d2 100644 --- a/docs/en/events.md +++ b/docs/en/events.md @@ -11,3 +11,10 @@ Workers dispatch events during normal message processing. If your queue config d - `Processor.message.failure`: dispatched when a message finishes with `Processor::REQUEUE`. Arguments: `message`. - `Processor.message.seen`: dispatched when a message is first observed by the worker. Arguments: `message`. - `Processor.message.start`: dispatched immediately before processing begins. Arguments: `message`. + +## Produce Events + +Producing is separate from processing. The queue client dispatches these events on its own event manager. See Custom Clients for setup. + +- `Queue.produce.success`: dispatched after the transport accepts the message. Arguments: `topic` or `command`, `message`, `messageId`, `transportDestination`, `transportMessage`, and `promise` for commands. +- `Queue.produce.failure`: dispatched when the transport throws. Arguments: `topic` or `command`, `message`, `exception`. diff --git a/docs/en/index.md b/docs/en/index.md index 0bd8b38..379569e 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -13,3 +13,4 @@ Queue jobs are regular PHP classes. They can receive constructor dependencies fr - [Running Workers](/workers) documents the worker command and its options. - [Failed Jobs](/failed-jobs) covers storing, requeueing, and purging failed jobs. - [Worker Events](/events) lists the events emitted while jobs are processed. +- [Custom Clients](/clients) explains how to replace the default queue client and observe produce events. diff --git a/docs/en/installation.md b/docs/en/installation.md index 0719c2a..fda782e 100644 --- a/docs/en/installation.md +++ b/docs/en/installation.md @@ -42,6 +42,9 @@ Define one or more queue connections in `config/app.php`: // Optional processor class. Defaults to Cake\Queue\Queue\Processor. 'processor' => \App\Queue\CustomProcessor::class, + // Optional client class. Defaults to Cake\Queue\Client\EnqueueClient. + 'clientClass' => \App\Queue\AuditedClient::class, + // Sleep time in milliseconds when no messages are available. 'receiveTimeout' => 10000, diff --git a/src/Client/EnqueueClient.php b/src/Client/EnqueueClient.php new file mode 100644 index 0000000..18e5918 --- /dev/null +++ b/src/Client/EnqueueClient.php @@ -0,0 +1,424 @@ + $config DSN string or ['transport'=>..., 'client'=>..., 'extensions'=>...] + * @param \Psr\Log\LoggerInterface|null $logger Logger instance. + * @param \Psr\Container\ContainerInterface|null $container PSR-11 container used to resolve `connection_factory_class`. + */ + public function __construct( + string|array $config, + ?LoggerInterface $logger = null, + ?ContainerInterface $container = null, + ) { + $this->logger = $logger ?: new NullLogger(); + $this->container = $container; + $this->build($config); + } + + /** + * Bind a processor to a topic. + * + * @param callable|\Interop\Queue\Processor $processor Processor callback or instance. + * @param string $topic Topic name. + * @param string|null $processorName Custom processor name. + * @return void + */ + public function bindTopic(string $topic, callable|Processor $processor, ?string $processorName = null): void + { + if (is_callable($processor)) { + $processor = new CallbackProcessor($processor); + } + + $processorName = $processorName ?: uniqid($processor::class); + $this->driver->getRouteCollection()->add(new Route($topic, Route::TOPIC, $processorName)); + $this->processorRegistry->add($processorName, $processor); + } + + /** + * Bind a processor to a command. + * + * @param callable|\Interop\Queue\Processor $processor Processor callback or instance. + * @param string $command Command name. + * @param string|null $processorName Custom processor name. + * @return void + */ + public function bindCommand(string $command, callable|Processor $processor, ?string $processorName = null): void + { + if (is_callable($processor)) { + $processor = new CallbackProcessor($processor); + } + + $processorName = $processorName ?: uniqid($processor::class); + $this->driver->getRouteCollection()->add(new Route($command, Route::COMMAND, $processorName)); + $this->processorRegistry->add($processorName, $processor); + } + + /** + * Send a command message and dispatch produce events. + * + * @param string $command Command name. + * @param string|array|\JsonSerializable|\Enqueue\Client\Message $message Message body or instance. + * @param bool $needReply Whether a reply is expected. + * @return \Enqueue\Rpc\Promise|null Promise when a reply is expected, null otherwise. + */ + public function sendCommand(string $command, string|array|JsonSerializable|Message $message, bool $needReply = false): ?Promise + { + $this->postSendExtension->clear(); + if (!$message instanceof Message) { + $message = new Message($message); + } + + try { + $promise = $this->producer->sendCommand($command, $message, $needReply); + } catch (Throwable $throwable) { + $this->dispatchEvent('Queue.produce.failure', [ + 'command' => $command, + 'exception' => $throwable, + ]); + throw $throwable; + } + + $postSend = $this->postSendExtension->getLastPostSend(); + $this->dispatchEvent('Queue.produce.success', [ + 'command' => $command, + 'messageId' => $postSend?->getMessage()->getMessageId(), + 'transportDestination' => $postSend?->getTransportDestination(), + 'promise' => $promise, + ]); + + return $promise; + } + + /** + * Send an event message and dispatch produce events. + * + * @param string $topic Topic name. + * @param string|array|\JsonSerializable|\Enqueue\Client\Message $message Message body or instance. + * @return void + */ + public function sendEvent(string $topic, string|array|JsonSerializable|Message $message): void + { + $this->postSendExtension->clear(); + if (!$message instanceof Message) { + $message = new Message($message); + } + + try { + $this->producer->sendEvent($topic, $message); + } catch (Throwable $throwable) { + $this->dispatchEvent('Queue.produce.failure', [ + 'topic' => $topic, + 'exception' => $throwable, + ]); + throw $throwable; + } + + $postSend = $this->postSendExtension->getLastPostSend(); + $this->dispatchEvent('Queue.produce.success', [ + 'topic' => $topic, + 'messageId' => $postSend?->getMessage()->getMessageId(), + 'transportDestination' => $postSend?->getTransportDestination(), + ]); + } + + /** + * Consume messages from bound queues. + * + * @param \Enqueue\Consumption\ExtensionInterface|null $runtimeExtension Runtime extension. + * @return void + */ + public function consume(?ExtensionInterface $runtimeExtension = null): void + { + $this->setupBroker(); + + $boundQueues = []; + + $routerQueue = $this->driver->createQueue($this->driver->getConfig()->getRouterQueue()); + $this->queueConsumer->bind($routerQueue, $this->delegateProcessor); + $boundQueues[$routerQueue->getQueueName()] = true; + + foreach ($this->driver->getRouteCollection()->all() as $route) { + $queue = $this->driver->createRouteQueue($route); + if (array_key_exists($queue->getQueueName(), $boundQueues)) { + continue; + } + + $this->queueConsumer->bind($queue, $this->delegateProcessor); + $boundQueues[$queue->getQueueName()] = true; + } + + $this->queueConsumer->consume($runtimeExtension); + } + + /** + * Get queue consumer instance. + * + * @return \Enqueue\Consumption\QueueConsumerInterface Queue consumer. + */ + public function getQueueConsumer(): QueueConsumerInterface + { + return $this->queueConsumer; + } + + /** + * Get driver instance. + * + * @return \Enqueue\Client\DriverInterface Driver. + */ + public function getDriver(): DriverInterface + { + return $this->driver; + } + + /** + * Get producer instance. + * + * Direct sends through the returned producer bypass the + * `Queue.produce.success` and `Queue.produce.failure` events. + * Use `sendEvent()` and `sendCommand()` for observable publishing. + * + * @param bool $setupBroker Whether to setup broker before returning producer. + * @return \Enqueue\Client\ProducerInterface Producer. + */ + public function getProducer(bool $setupBroker = false): ProducerInterface + { + if ($setupBroker) { + $this->setupBroker(); + } + + return $this->producer; + } + + /** + * Get delegate processor instance. + * + * @return \Enqueue\Client\DelegateProcessor Delegate processor. + */ + public function getDelegateProcessor(): DelegateProcessor + { + return $this->delegateProcessor; + } + + /** + * Setup broker queues and exchanges. + * + * @return void + */ + public function setupBroker(): void + { + $this->driver->setupBroker(); + } + + /** + * Build driver, producer and consumer from the given config. + * + * @param string|array $config DSN string or normalized config array. + * @return void + */ + protected function build(string|array $config): void + { + $normalized = EnqueueClientConfig::normalize($config); + + $connection = $this->createConnection($normalized['transport']); + + $client = $normalized['client']; + $configObj = new Config( + $client['prefix'], + $client['separator'], + $client['app_name'], + $client['router_topic'], + $client['router_queue'], + $client['default_queue'], + EnqueueClientConfig::ROUTER_PROCESSOR, + $normalized['transport'], + $client['driver_options'] ?? [], + ); + + $routeCollection = new RouteCollection([]); + $driver = (new DriverFactory())->create($connection, $configObj, $routeCollection); + $this->postSendExtension = new EnqueuePostSendExtension(); + $producer = new Producer($driver, new RpcFactory($driver->getContext()), new ClientChainExtensions([$this->postSendExtension])); + + $processorRegistry = new ArrayProcessorRegistry([]); + $delegateProcessor = new DelegateProcessor($processorRegistry); + + $consumptionExtensions = []; + if (!empty($client['redelivered_delay_time'])) { + $consumptionExtensions[] = new DelayRedeliveredMessageExtension($driver, (int)$client['redelivered_delay_time']); + } + + if ($normalized['extensions']['signal_extension']) { + $consumptionExtensions[] = new SignalExtension(); + } + + if ($normalized['extensions']['reply_extension']) { + $consumptionExtensions[] = new ReplyExtension(); + } + + $consumptionExtensions[] = new SetRouterPropertiesExtension($driver); + $consumptionExtensions[] = new LogExtension(); + + $queueConsumer = new QueueConsumer( + $driver->getContext(), + new ConsumptionChainExtension($consumptionExtensions), + [], + $this->logger, + ); + + $processorRegistry->add($configObj->getRouterProcessor(), new RouterProcessor($driver)); + + $this->driver = $driver; + $this->producer = $producer; + $this->queueConsumer = $queueConsumer; + $this->delegateProcessor = $delegateProcessor; + $this->processorRegistry = $processorRegistry; + } + + /** + * Create a connection factory from transport config. + * + * Supports a custom factory class directly or through a PSR-11 container. + * The container path is tried first when a container is available and + * contains the requested class, otherwise the class is instantiated + * directly with the transport config array. + * + * @param array $transport Transport config including DSN. + * @return \Interop\Queue\ConnectionFactory Connection factory instance. + * @throws \LogicException When the factory class cannot be resolved. + */ + protected function createConnection(array $transport): ConnectionFactory + { + if (isset($transport['connection_factory_class'])) { + $class = $transport['connection_factory_class']; + if (!is_string($class) || $class === '') { + throw new LogicException('Transport `connection_factory_class` must be a non-empty class name string.'); + } + + if ($this->container instanceof ContainerInterface && $this->container->has($class)) { + $factory = $this->container->get($class); + if (!$factory instanceof ConnectionFactory) { + throw new LogicException(sprintf('Service `%s` must implement `%s`.', $class, ConnectionFactory::class)); + } + + return $factory; + } + + if (!is_a($class, ConnectionFactory::class, true)) { + throw new LogicException(sprintf('Connection factory class `%s` must implement `%s`.', $class, ConnectionFactory::class)); + } + + return new $class($transport); + } + + if (isset($transport['factory_service']) || isset($transport['factory_class'])) { + throw new LogicException('transport.factory_service and transport.factory_class are not supported by EnqueueClient prototype. Use connection_factory_class.'); + } + + return (new ConnectionFactoryFactory())->create($transport); + } +} diff --git a/src/Client/EnqueueClientConfig.php b/src/Client/EnqueueClientConfig.php new file mode 100644 index 0000000..97af7ad --- /dev/null +++ b/src/Client/EnqueueClientConfig.php @@ -0,0 +1,200 @@ +|null $config DSN string or ['transport'=>..., 'client'=>..., 'extensions'=>...] + * @return array{transport: array, client: array, extensions: array} Normalized config. + * @throws \InvalidArgumentException When the config has an unexpected shape or unknown keys. + */ + public static function normalize(string|array|null $config): array + { + if (in_array($config, [null, '', []], true)) { + $config = ['transport' => ['dsn' => 'null:']]; + } + + if (is_string($config)) { + $config = [ + 'transport' => $config, + 'client' => true, + ]; + } + + $unknown = array_diff(array_keys($config), ['transport', 'client', 'extensions']); + if ($unknown !== []) { + throw new InvalidArgumentException(sprintf('Unknown queue config key(s): `%s`. Allowed keys: transport, client, extensions.', implode('`, `', $unknown))); + } + + return [ + 'transport' => self::normalizeTransport($config['transport'] ?? null), + 'client' => self::normalizeClient($config['client'] ?? true), + 'extensions' => self::normalizeExtensions($config['extensions'] ?? []), + ]; + } + + /** + * Normalize the transport section. + * + * Accepts an empty value, a DSN string or a full array. Extra keys are + * passed through to the connection factory. + * + * @param string|array|null $transport DSN string or transport array. + * @return array Normalized transport config. + * @throws \InvalidArgumentException When the transport section has an unexpected shape. + */ + public static function normalizeTransport(string|array|null $transport): array + { + if (in_array($transport, [null, '', []], true)) { + return ['dsn' => 'null:']; + } + + if (is_string($transport)) { + return ['dsn' => $transport]; + } + + if (!isset($transport['dsn']) || !is_string($transport['dsn']) || $transport['dsn'] === '') { + throw new InvalidArgumentException('Transport config must contain a non-empty `dsn` key.'); + } + + return $transport; + } + + /** + * Normalize the client section. + * + * Merges user values over the default prefix, separator, app name, + * router and queue names. + * + * @param bool|array $client Client config or true for defaults. + * @return array Normalized client config. + * @throws \InvalidArgumentException When the client section has an unexpected shape. + */ + public static function normalizeClient(bool|array $client = true): array + { + $defaults = [ + 'prefix' => 'enqueue', + 'separator' => '.', + 'app_name' => 'app', + 'router_topic' => 'default', + 'router_queue' => 'default', + 'default_queue' => 'default', + 'router_processor' => null, + 'redelivered_delay_time' => 0, + 'driver_options' => [], + ]; + + if ($client === true) { + return $defaults; + } + + if ($client === false) { + throw new InvalidArgumentException('Client config `false` is not supported, use `true` for defaults or an array with client options.'); + } + + $unknown = array_diff(array_keys($client), array_keys($defaults)); + if ($unknown !== []) { + throw new InvalidArgumentException(sprintf('Unknown client config key(s): `%s`.', implode('`, `', $unknown))); + } + + $merged = array_merge($defaults, $client); + + foreach (['prefix', 'separator', 'app_name'] as $key) { + if (!is_string($merged[$key])) { + throw new InvalidArgumentException(sprintf('Client config `%s` must be a string.', $key)); + } + } + + foreach (['router_topic', 'router_queue', 'default_queue'] as $key) { + if (!is_string($merged[$key]) || trim($merged[$key]) === '') { + throw new InvalidArgumentException(sprintf('Client config `%s` must be a non-empty string.', $key)); + } + } + + if (!is_int($merged['redelivered_delay_time']) || $merged['redelivered_delay_time'] < 0) { + throw new InvalidArgumentException('Client config `redelivered_delay_time` must be an integer >= 0.'); + } + + if (!is_array($merged['driver_options'])) { + throw new InvalidArgumentException('Client config `driver_options` must be an array.'); + } + + return $merged; + } + + /** + * Normalize the extensions section. + * + * @param array $extensions User extensions config. + * @return array{signal_extension: bool, reply_extension: bool} Normalized extensions config. + * @throws \InvalidArgumentException When the extensions section has an unexpected shape. + */ + public static function normalizeExtensions(array $extensions = []): array + { + $unknown = array_diff(array_keys($extensions), ['signal_extension', 'reply_extension']); + if ($unknown !== []) { + throw new InvalidArgumentException(sprintf('Unknown extensions config key(s): `%s`.', implode('`, `', $unknown))); + } + + return [ + 'signal_extension' => self::normalizeBoolean($extensions['signal_extension'] ?? function_exists('pcntl_signal_dispatch'), 'signal_extension'), + 'reply_extension' => self::normalizeBoolean($extensions['reply_extension'] ?? true, 'reply_extension'), + ]; + } + + /** + * Normalize a boolean config value. + * + * Accepts booleans as well as integer and string representations + * (`1`, `0`, `'true'`, `'false'`, `'yes'`, `'no'`, `'on'`, `'off'`). + * + * @param mixed $value Raw config value. + * @param string $key Config key used in the exception message. + * @return bool Normalized value. + * @throws \InvalidArgumentException When the value is not recognizable as boolean. + */ + protected static function normalizeBoolean(mixed $value, string $key): bool + { + if (is_bool($value)) { + return $value; + } + + if (is_int($value) || is_string($value)) { + $normalized = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + if (is_bool($normalized)) { + return $normalized; + } + } + + throw new InvalidArgumentException(sprintf('Extensions config `%s` must be a boolean.', $key)); + } +} diff --git a/src/Client/EnqueuePostSendExtension.php b/src/Client/EnqueuePostSendExtension.php new file mode 100644 index 0000000..ce16a7f --- /dev/null +++ b/src/Client/EnqueuePostSendExtension.php @@ -0,0 +1,64 @@ +lastPostSend = $context; + } + + /** + * Get last post send context. + * + * @return \Enqueue\Client\PostSend|null Last post send context or null. + */ + public function getLastPostSend(): ?PostSend + { + return $this->lastPostSend; + } + + /** + * Clear stored context. + * + * @return void + */ + public function clear(): void + { + $this->lastPostSend = null; + } +} diff --git a/src/Command/WorkerCommand.php b/src/Command/WorkerCommand.php index 7efa802..471701e 100644 --- a/src/Command/WorkerCommand.php +++ b/src/Command/WorkerCommand.php @@ -227,7 +227,7 @@ public function execute(Arguments $args, ConsoleIo $io): int } } - $client = QueueManager::engine($config); + $client = QueueManager::engine($config, $this->container); $queue = $args->getOption('queue') ? (string)$args->getOption('queue') : Configure::read(sprintf('Queue.%s.queue', $config), 'default'); diff --git a/src/Job/Message.php b/src/Job/Message.php index 4b328d1..75a8b71 100644 --- a/src/Job/Message.php +++ b/src/Job/Message.php @@ -100,7 +100,7 @@ public function getCallable(): Closure } $target = $this->getTarget(); - if ($this->container && $this->container->has($target[0])) { + if ($this->container instanceof ContainerInterface && $this->container->has($target[0])) { $object = $this->container->get($target[0]); } else { $object = new $target[0](); @@ -114,8 +114,7 @@ public function getCallable(): Closure /** * Get the target class and method. * - * @return array{string, string} - * @phpstan-return array{class-string, string} + * @return array{class-string, string} */ public function getTarget(): array { diff --git a/src/QueueManager.php b/src/QueueManager.php index 6111c6c..0541ca7 100644 --- a/src/QueueManager.php +++ b/src/QueueManager.php @@ -20,11 +20,12 @@ use Cake\Cache\Cache; use Cake\Core\App; use Cake\Log\Log; +use Cake\Queue\Client\EnqueueClient; use Cake\Queue\Dto\DtoManager; use Enqueue\Client\Message as ClientMessage; -use Enqueue\SimpleClient\SimpleClient; use InvalidArgumentException; use LogicException; +use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; class QueueManager @@ -39,10 +40,47 @@ class QueueManager /** * Queue clients * - * @var array + * @var array */ protected static array $_clients = []; + /** + * PSR-11 container used to resolve queue services. + * + * Set automatically from `QueuePlugin::services()` when the application + * uses dependency injection. Only `has()` and `get()` are used, so any + * PSR-11 container is accepted. + */ + protected static ?ContainerInterface $container = null; + + /** + * Set the PSR-11 container used to resolve queue services. + * + * Cached clients are dropped when the container instance changes so that + * already built clients never keep a stale container. + * + * @param \Psr\Container\ContainerInterface|null $container Container instance or null to detach. + * @return void + */ + public static function setContainer(?ContainerInterface $container): void + { + if ($container !== static::$container) { + static::$_clients = []; + } + + static::$container = $container; + } + + /** + * Get the PSR-11 container used to resolve queue services. + * + * @return \Psr\Container\ContainerInterface|null Container instance or null when unavailable. + */ + public static function getContainer(): ?ContainerInterface + { + return static::$container; + } + /** * This method can be used to define configuration adapters for an application. * @@ -176,23 +214,43 @@ public static function drop(string $key): void /** * Get a queueing engine * + * A per-call container overrides the static one for the initial build only. + * Already cached clients are reused as is, call `drop()` to rebuild them. + * * @param string $name Key name of a configured adapter to get. - * @return \Enqueue\SimpleClient\SimpleClient + * @param \Psr\Container\ContainerInterface|null $container Optional PSR-11 container, falls back to `getContainer()`. + * @return \Cake\Queue\Client\EnqueueClient */ - public static function engine(string $name): SimpleClient + public static function engine(string $name, ?ContainerInterface $container = null): EnqueueClient { if (isset(static::$_clients[$name])) { return static::$_clients[$name]; } - $config = static::getConfig($name) + [ + $config = static::getConfig($name); + if ($config === null) { + throw new InvalidArgumentException(sprintf('Queue config `%s` not found.', $name)); + } + + $config += [ 'logger' => null, 'receiveTimeout' => null, + 'clientClass' => EnqueueClient::class, ]; $logger = $config['logger'] ? Log::engine($config['logger']) : null; - static::$_clients[$name] = new SimpleClient($config['url'], $logger); + $clientClass = $config['clientClass']; + if (!is_string($clientClass) || !class_exists($clientClass)) { + throw new InvalidArgumentException(sprintf('Client class `%s` not found.', is_string($clientClass) ? $clientClass : gettype($clientClass))); + } + + if (!is_a($clientClass, EnqueueClient::class, true)) { + throw new InvalidArgumentException(sprintf('Client class `%s` must extend `%s`.', $clientClass, EnqueueClient::class)); + } + + $resolvedContainer = $container ?? static::$container; + static::$_clients[$name] = new $clientClass($config['url'], $logger, $resolvedContainer); static::$_clients[$name]->setupBroker(); if ($config['receiveTimeout'] !== null) { @@ -235,8 +293,9 @@ public static function engine(string $name): SimpleClient * - `\Enqueue\Client\MessagePriority::VERY_HIGH` * - `queue` - The name of a queue to use, from queue `config` array or * string 'default' if empty. + * @return string|null MessageId assigned by the transport on success, null when skipped as duplicate. */ - public static function push(string|array $className, array|object $data = [], array $options = []): void + public static function push(string|array $className, array|object $data = [], array $options = []): ?string { [$class, $method] = is_array($className) ? $className : [$className, 'execute']; @@ -281,7 +340,7 @@ public static function push(string|array $className, array|object $data = [], ar ); } - return; + return null; } } @@ -328,6 +387,8 @@ public static function push(string|array $className, array|object $data = [], ar Cache::add($uniqueId, true, $config['uniqueCacheKey']); } + + return $message->getMessageId(); } /** diff --git a/src/QueuePlugin.php b/src/QueuePlugin.php index 9f7202b..f3d694c 100644 --- a/src/QueuePlugin.php +++ b/src/QueuePlugin.php @@ -96,5 +96,7 @@ public function services(ContainerInterface $container): void $container ->add(WorkerCommand::class) ->addArgument(ContainerInterface::class); + + QueueManager::setContainer($container); } } diff --git a/tests/TestCase/Client/EnqueueClientConfigTest.php b/tests/TestCase/Client/EnqueueClientConfigTest.php new file mode 100644 index 0000000..f43e671 --- /dev/null +++ b/tests/TestCase/Client/EnqueueClientConfigTest.php @@ -0,0 +1,159 @@ +assertSame(['dsn' => 'null:'], $normalized['transport']); + $this->assertSame('default', $normalized['client']['router_queue']); + $this->assertTrue($normalized['extensions']['reply_extension']); + } + + public function testNormalizeStringDsn(): void + { + $normalized = EnqueueClientConfig::normalize('null:'); + $this->assertSame(['dsn' => 'null:'], $normalized['transport']); + $this->assertSame('enqueue', $normalized['client']['prefix']); + $this->assertSame('.', $normalized['client']['separator']); + $this->assertSame('app', $normalized['client']['app_name']); + } + + public function testNormalizeArrayWithClientTrue(): void + { + $normalized = EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => true]); + $this->assertSame(['dsn' => 'null:'], $normalized['transport']); + $this->assertSame('default', $normalized['client']['default_queue']); + } + + public function testNormalizeTransportExtraKeysPassthrough(): void + { + $normalized = EnqueueClientConfig::normalize(['transport' => ['dsn' => 'null:', 'foo' => 'bar']]); + $this->assertSame('bar', $normalized['transport']['foo']); + } + + public function testNormalizeClientMerge(): void + { + $normalized = EnqueueClientConfig::normalize([ + 'transport' => 'null:', + 'client' => ['router_queue' => 'billing', 'prefix' => 'cake'], + ]); + $this->assertSame('billing', $normalized['client']['router_queue']); + $this->assertSame('cake', $normalized['client']['prefix']); + $this->assertSame('default', $normalized['client']['router_topic']); + } + + public function testNormalizeExtensionsDefaultsAndOverrides(): void + { + $defaults = EnqueueClientConfig::normalize('null:'); + $this->assertSame(function_exists('pcntl_signal_dispatch'), $defaults['extensions']['signal_extension']); + + $normalized = EnqueueClientConfig::normalize([ + 'transport' => 'null:', + 'extensions' => ['signal_extension' => false, 'reply_extension' => false], + ]); + $this->assertFalse($normalized['extensions']['signal_extension']); + $this->assertFalse($normalized['extensions']['reply_extension']); + } + + public function testNormalizeTransportRequiresDsn(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => ['foo' => 'bar']]); + } + + public function testNormalizeClientFalseThrows(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => false]); + } + + public function testNormalizeUnknownTopLevelKeyThrows(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'transprot' => 'null:']); + } + + public function testNormalizeUnknownClientKeyThrows(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['router_qeue' => 'billing']]); + } + + public function testNormalizeUnknownExtensionKeyThrows(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'extensions' => ['signal' => true]]); + } + + public function testNormalizeClientRejectsEmptyRouterQueue(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['router_queue' => ' ']]); + } + + public function testNormalizeClientRejectsNonStringPrefix(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['prefix' => 123]]); + } + + public function testNormalizeClientRejectsNegativeRedeliveredDelayTime(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['redelivered_delay_time' => -1]]); + } + + public function testNormalizeClientRejectsNonIntegerRedeliveredDelayTime(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['redelivered_delay_time' => '5']]); + } + + public function testNormalizeClientRejectsNonArrayDriverOptions(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'client' => ['driver_options' => 'foo']]); + } + + public function testNormalizeExtensionsAcceptsStringBooleans(): void + { + $normalized = EnqueueClientConfig::normalize([ + 'transport' => 'null:', + 'extensions' => ['signal_extension' => 'false', 'reply_extension' => 'true'], + ]); + $this->assertFalse($normalized['extensions']['signal_extension']); + $this->assertTrue($normalized['extensions']['reply_extension']); + } + + public function testNormalizeExtensionsRejectsUnrecognizedValue(): void + { + $this->expectException(InvalidArgumentException::class); + EnqueueClientConfig::normalize(['transport' => 'null:', 'extensions' => ['reply_extension' => 'maybe']]); + } + + public function testRouterProcessorConstant(): void + { + $this->assertSame('enqueue.client.router_processor', EnqueueClientConfig::ROUTER_PROCESSOR); + } +} diff --git a/tests/TestCase/Client/EnqueueClientTest.php b/tests/TestCase/Client/EnqueueClientTest.php new file mode 100644 index 0000000..2a357b2 --- /dev/null +++ b/tests/TestCase/Client/EnqueueClientTest.php @@ -0,0 +1,426 @@ +assertInstanceOf(DriverInterface::class, $client->getDriver()); + $this->assertInstanceOf(Producer::class, $client->getProducer()); + $this->assertNotEmpty($client->getDriver()->getConfig()->getRouterProcessor()); + $client->setupBroker(); + $this->assertTrue(true); + } + + public function testBindTopicAndCommand(): void + { + $client = new EnqueueClient('null:'); + $client->bindTopic('demo-topic', function () { + return 'ack'; + }, 'demo-topic-proc'); + $client->bindCommand('demo-command', function () { + return 'ack'; + }, 'demo-command-proc'); + + $routes = $client->getDriver()->getRouteCollection()->all(); + $this->assertNotEmpty($routes); + } + + public function testSendEventEmitsSuccessWithMessageId(): void + { + $client = new EnqueueClient('null:'); + $captured = []; + $client->getEventManager()->on('Queue.produce.success', function (EventInterface $event) use (&$captured) { + $captured = $event->getData(); + }); + + $client->sendEvent('demo', new Message(['a' => 1])); + + $this->assertNotEmpty($captured['messageId']); + $this->assertSame('demo', $captured['topic']); + $this->assertNotNull($captured['transportDestination']); + $this->assertArrayNotHasKey('message', $captured); + $this->assertArrayNotHasKey('transportMessage', $captured); + } + + public function testSendEventAcceptsJsonSerializableBody(): void + { + $client = new EnqueueClient('null:'); + $captured = []; + $client->getEventManager()->on('Queue.produce.success', function (EventInterface $event) use (&$captured) { + $captured = $event->getData(); + }); + + $client->sendEvent('demo', new class implements JsonSerializable { + public function jsonSerialize(): array + { + return ['a' => 1]; + } + }); + + $this->assertNotEmpty($captured['messageId']); + $this->assertSame('demo', $captured['topic']); + } + + public function testSendEventEmitsFailureAndRethrows(): void + { + $client = new EnqueueClient('null:'); + $failingProducer = $this->createMock(ProducerInterface::class); + $failingProducer->expects($this->once())->method('sendEvent')->willThrowException(new RuntimeException('broker down')); + + $ref = new ReflectionProperty(EnqueueClient::class, 'producer'); + $ref->setValue($client, $failingProducer); + + $failures = []; + $successes = []; + $client->getEventManager()->on('Queue.produce.failure', function (EventInterface $event) use (&$failures) { + $failures = $event->getData(); + }); + $client->getEventManager()->on('Queue.produce.success', function () use (&$successes) { + $successes[] = true; + }); + + try { + $client->sendEvent('demo', new Message('x')); + $this->fail('Expected exception was not thrown'); + } catch (RuntimeException $runtimeException) { + $this->assertSame('broker down', $runtimeException->getMessage()); + } + + $this->assertSame('demo', $failures['topic']); + $this->assertInstanceOf(RuntimeException::class, $failures['exception']); + $this->assertArrayNotHasKey('message', $failures); + $this->assertSame([], $successes); + } + + public function testSendCommandEmitsSuccess(): void + { + $client = new EnqueueClient('null:'); + $client->bindCommand('demo-cmd', function () { + return 'ack'; + }, 'demo-cmd-proc'); + $captured = []; + $client->getEventManager()->on('Queue.produce.success', function (EventInterface $event) use (&$captured) { + $captured = $event->getData(); + }); + + $client->sendCommand('demo-cmd', new Message(['a' => 1])); + + $this->assertNotEmpty($captured['messageId']); + $this->assertSame('demo-cmd', $captured['command']); + } + + public function testConnectionFactoryClassIsUsed(): void + { + $client = new EnqueueClient(['transport' => ['dsn' => 'null:', 'connection_factory_class' => NullConnectionFactory::class]]); + $this->assertInstanceOf(DriverInterface::class, $client->getDriver()); + } + + public function testConnectionFactoryClassIsResolvedFromContainer(): void + { + $factory = new NullConnectionFactory(); + $container = $this->createMock(ContainerInterface::class); + $container->method('has')->willReturn(true); + $container->expects($this->once())->method('get')->with(NullConnectionFactory::class)->willReturn($factory); + + $client = new EnqueueClient( + ['transport' => ['dsn' => 'null:', 'connection_factory_class' => NullConnectionFactory::class]], + null, + $container, + ); + $this->assertInstanceOf(DriverInterface::class, $client->getDriver()); + } + + public function testConnectionFactoryServiceMustImplementConnectionFactory(): void + { + $container = $this->createStub(ContainerInterface::class); + $container->method('has')->willReturn(true); + $container->method('get')->willReturn(new stdClass()); + + $this->expectException(LogicException::class); + new EnqueueClient( + ['transport' => ['dsn' => 'null:', 'connection_factory_class' => NullConnectionFactory::class]], + null, + $container, + ); + } + + public function testConnectionFactoryClassIsValidatedBeforeInstantiation(): void + { + $this->expectException(LogicException::class); + new EnqueueClient(['transport' => ['dsn' => 'null:', 'connection_factory_class' => 'NoSuch\\FactoryClass']]); + } + + public function testConnectionFactoryClassMustBeNonEmptyString(): void + { + $this->expectException(LogicException::class); + new EnqueueClient(['transport' => ['dsn' => 'null:', 'connection_factory_class' => 123]]); + } + + public function testNestedSendKeepsOuterPostSendResult(): void + { + $client = new EnqueueClient('null:'); + $events = []; + $client->getEventManager()->on('Queue.produce.success', function (EventInterface $event) use (&$events, $client) { + $data = $event->getData(); + if ($data['topic'] === 'outer') { + $client->sendEvent('inner', new Message(['nested' => true])); + } + + $events[] = $data; + }); + + $client->sendEvent('outer', new Message(['outer' => true])); + + $this->assertCount(2, $events); + $byTopic = []; + foreach ($events as $data) { + $byTopic[$data['topic']] = $data; + } + + $this->assertNotEmpty($byTopic['outer']['messageId']); + $this->assertNotEmpty($byTopic['inner']['messageId']); + $this->assertNotSame($byTopic['inner']['messageId'], $byTopic['outer']['messageId']); + } + + /** + * String body roundtrip through one topic subscriber. + * + * @return void + */ + public function testSendEventWithOneSubscriber(): void + { + $dir = $this->fsTransportDir(); + try { + $client = $this->fsClient($dir); + + $actualMessage = null; + $client->bindTopic('foo_topic', function ($message) use (&$actualMessage) { + $actualMessage = $message; + + return Result::ACK; + }, 'foo-topic-proc'); + + $client->setupBroker(); + $client->sendEvent('foo_topic', 'Hello there!'); + + $client->getQueueConsumer()->setReceiveTimeout(1000); + $client->consume(new ChainExtension([ + new LimitConsumedMessagesExtension(2), + ])); + + $this->assertNotNull($actualMessage); + $this->assertSame('Hello there!', $actualMessage->getBody()); + } finally { + $this->removeFsTransportDir($dir); + } + } + + /** + * Two subscribers on the same topic both receive the event. + * + * @return void + */ + public function testSendEventWithTwoSubscribers(): void + { + $dir = $this->fsTransportDir(); + try { + $client = $this->fsClient($dir); + + $received = 0; + $client->bindTopic('foo_topic', function () use (&$received) { + ++$received; + + return Result::ACK; + }, 'foo-topic-proc-one'); + $client->bindTopic('foo_topic', function () use (&$received) { + ++$received; + + return Result::ACK; + }, 'foo-topic-proc-two'); + + $client->setupBroker(); + $client->sendEvent('foo_topic', 'Hello there!'); + + $client->getQueueConsumer()->setReceiveTimeout(1000); + $client->consume(new ChainExtension([ + new LimitConsumedMessagesExtension(3), + ])); + + $this->assertSame(2, $received); + } finally { + $this->removeFsTransportDir($dir); + } + } + + /** + * Command roundtrip to a bound command processor. + * + * @return void + */ + public function testSendCommandRoundtrip(): void + { + $dir = $this->fsTransportDir(); + try { + $client = $this->fsClient($dir); + + $received = 0; + $client->bindCommand('foo_command', function () use (&$received) { + ++$received; + + return Result::ACK; + }, 'foo-command-proc'); + + $client->setupBroker(); + $client->sendCommand('foo_command', 'Hello there!'); + + $client->getQueueConsumer()->setReceiveTimeout(1000); + $client->consume(new ChainExtension([ + new LimitConsumedMessagesExtension(1), + ])); + + $this->assertSame(1, $received); + } finally { + $this->removeFsTransportDir($dir); + } + } + + /** + * Create a client on the file transport with a unique prefix per test. + * + * Uses a partial client config on purpose: separator, extensions and + * delay options must fall back to defaults. + * + * @param string $dir Transport directory. + * @return \Cake\Queue\Client\EnqueueClient + */ + protected function fsClient(string $dir): EnqueueClient + { + return new EnqueueClient([ + 'transport' => 'file:///' . $dir, + 'client' => [ + 'prefix' => str_replace('.', '', uniqid('enqueue', true)), + 'app_name' => 'enqueue_client', + 'router_topic' => 'test', + 'router_queue' => 'test', + 'default_queue' => 'test', + ], + ]); + } + + /** + * Create an isolated directory for the file transport. + * + * @return string Directory path with trailing separator. + */ + protected function fsTransportDir(): string + { + $dir = TMP . 'enqueue-client-test-' . uniqid() . DS; + mkdir($dir, 0777, true); + + return $dir; + } + + /** + * Remove an isolated file transport directory. + * + * @param string $dir Directory path with trailing separator. + * @return void + */ + protected function removeFsTransportDir(string $dir): void + { + array_map('unlink', glob($dir . '*')); + rmdir($dir); + } + + public function testFactoryServiceIsRejected(): void + { + $this->expectException(LogicException::class); + new EnqueueClient(['transport' => ['dsn' => 'null:', 'factory_service' => 'some_service']]); + } + + public function testQueueManagerPushReturnsMessageIdAndEmitsSuccess(): void + { + QueueManager::setConfig('test-produce', ['url' => 'null:', 'queue' => 'default']); + $engine = QueueManager::engine('test-produce'); + + $captured = []; + $engine->getEventManager()->on('Queue.produce.success', function (EventInterface $event) use (&$captured) { + $captured = $event->getData(); + }); + + $messageId = QueueManager::push(LogToDebugJob::class, ['foo' => 'bar'], ['config' => 'test-produce']); + + $this->assertNotEmpty($messageId); + $this->assertSame($messageId, $captured['messageId']); + } + + public function testQueueManagerUsesCustomClientClass(): void + { + QueueManager::setConfig('test-custom-client', [ + 'url' => 'null:', + 'queue' => 'default', + 'clientClass' => TestCustomClient::class, + ]); + $engine = QueueManager::engine('test-custom-client'); + $this->assertInstanceOf(TestCustomClient::class, $engine); + } + + public function testQueueManagerRejectsInvalidClientClass(): void + { + QueueManager::setConfig('test-bad-client', [ + 'url' => 'null:', + 'queue' => 'default', + 'clientClass' => stdClass::class, + ]); + $this->expectException(InvalidArgumentException::class); + QueueManager::engine('test-bad-client'); + } +} diff --git a/tests/TestCase/Client/EnqueuePostSendExtensionTest.php b/tests/TestCase/Client/EnqueuePostSendExtensionTest.php new file mode 100644 index 0000000..cc78247 --- /dev/null +++ b/tests/TestCase/Client/EnqueuePostSendExtensionTest.php @@ -0,0 +1,71 @@ +assertNull($extension->getLastPostSend()); + } + + public function testOnPostSendStoresContext(): void + { + $extension = new EnqueuePostSendExtension(); + $postSend = $this->makePostSend(); + $extension->onPostSend($postSend); + $this->assertSame($postSend, $extension->getLastPostSend()); + } + + public function testClearResetsState(): void + { + $extension = new EnqueuePostSendExtension(); + $extension->onPostSend($this->makePostSend()); + $extension->clear(); + $this->assertNull($extension->getLastPostSend()); + } + + /** + * @return \Enqueue\Client\PostSend + */ + protected function makePostSend(): PostSend + { + $message = new Message('body'); + $message->setMessageId('test-id'); + + /** @var \Enqueue\Client\ProducerInterface $producer */ + $producer = $this->createStub(ProducerInterface::class); + /** @var \Enqueue\Client\DriverInterface $driver */ + $driver = $this->createStub(DriverInterface::class); + /** @var \Interop\Queue\Destination $destination */ + $destination = $this->createStub(Destination::class); + /** @var \Interop\Queue\Message $transportMessage */ + $transportMessage = $this->createStub(TransportMessage::class); + + return new PostSend($message, $producer, $driver, $destination, $transportMessage); + } +} diff --git a/tests/TestCase/QueueManagerTest.php b/tests/TestCase/QueueManagerTest.php index 5ff9867..514aabd 100644 --- a/tests/TestCase/QueueManagerTest.php +++ b/tests/TestCase/QueueManagerTest.php @@ -20,10 +20,13 @@ use BadMethodCallException; use Cake\Cache\Cache; use Cake\Log\Log; +use Cake\Queue\Client\EnqueueClient; use Cake\Queue\QueueManager; use Cake\TestSuite\TestCase; -use Enqueue\SimpleClient\SimpleClient; +use Enqueue\Null\NullConnectionFactory; +use InvalidArgumentException; use LogicException; +use Psr\Container\ContainerInterface; use TestApp\Dto\OrderDto; use TestApp\Dto\OrderItemDto; use TestApp\Job\LogToDebugJob; @@ -55,6 +58,7 @@ public function tearDown(): void } QueueManager::drop('test'); + QueueManager::setContainer(null); Log::drop('test'); // delete file based queues @@ -121,6 +125,70 @@ public function testGetUniqueIdWithDtoClass() $this->assertSame($withOrderDto, $withOrderDtoAgain, 'same dtoClass and data are the same'); } + public function testSetAndGetContainer() + { + $this->assertNull(QueueManager::getContainer()); + + $container = $this->createStub(ContainerInterface::class); + QueueManager::setContainer($container); + $this->assertSame($container, QueueManager::getContainer()); + + QueueManager::setContainer(null); + $this->assertNull(QueueManager::getContainer()); + } + + public function testEngineUsesStaticContainer() + { + $container = $this->createMock(ContainerInterface::class); + $container->method('has')->willReturn(true); + $container->expects($this->once())->method('get')->with(NullConnectionFactory::class)->willReturn(new NullConnectionFactory()); + + QueueManager::setContainer($container); + try { + QueueManager::setConfig('test-container', [ + 'url' => ['transport' => ['dsn' => 'null:', 'connection_factory_class' => NullConnectionFactory::class]], + ]); + $engine = QueueManager::engine('test-container'); + $this->assertInstanceOf(EnqueueClient::class, $engine); + } finally { + QueueManager::setContainer(null); + } + } + + public function testEnginePerCallContainerOverridesStatic() + { + $container = $this->createMock(ContainerInterface::class); + $container->method('has')->willReturn(true); + $container->expects($this->once())->method('get')->with(NullConnectionFactory::class)->willReturn(new NullConnectionFactory()); + + $this->assertNull(QueueManager::getContainer()); + QueueManager::setConfig('test-container', [ + 'url' => ['transport' => ['dsn' => 'null:', 'connection_factory_class' => NullConnectionFactory::class]], + ]); + try { + $engine = QueueManager::engine('test-container', $container); + $this->assertInstanceOf(EnqueueClient::class, $engine); + } finally { + QueueManager::setContainer(null); + } + } + + public function testSetContainerDropsCachedClients() + { + QueueManager::setConfig('test', [ + 'url' => 'null:', + ]); + $first = QueueManager::engine('test'); + + QueueManager::setContainer($this->createStub(ContainerInterface::class)); + try { + $second = QueueManager::engine('test'); + $this->assertNotSame($first, $second); + } finally { + QueueManager::setContainer(null); + } + } + public function testSetConfig() { QueueManager::setConfig('test', [ @@ -196,7 +264,7 @@ public function testNonDefaultQueueNameString() 'queue' => 'other', ]); $engine = QueueManager::engine('test'); - $this->assertInstanceOf(SimpleClient::class, $engine); + $this->assertInstanceOf(EnqueueClient::class, $engine); $this->assertSame('other', $engine->getDriver()->getConfig()->getRouterQueue()); } @@ -212,7 +280,7 @@ public function testNonDefaultQueueNameArray() 'queue' => 'ignored', ]); $engine = QueueManager::engine('test'); - $this->assertInstanceOf(SimpleClient::class, $engine); + $this->assertInstanceOf(EnqueueClient::class, $engine); $this->assertSame('other', $engine->getDriver()->getConfig()->getRouterQueue()); } @@ -223,11 +291,18 @@ public function testEngine() 'url' => 'null:', ]); $engine = QueueManager::engine('test'); - $this->assertInstanceOf(SimpleClient::class, $engine); + $this->assertInstanceOf(EnqueueClient::class, $engine); $this->assertSame($engine, QueueManager::engine('test')); } + public function testEngineUnknownConfigThrows() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Queue config `missing` not found.'); + QueueManager::engine('missing'); + } + public function testPushInvalidClass() { $this->expectException('\InvalidArgumentException'); diff --git a/tests/test_app/src/Queue/TestCustomClient.php b/tests/test_app/src/Queue/TestCustomClient.php new file mode 100644 index 0000000..d4fcdc5 --- /dev/null +++ b/tests/test_app/src/Queue/TestCustomClient.php @@ -0,0 +1,23 @@ +