diff --git a/README.md b/README.md index 22070274..9f42e312 100644 --- a/README.md +++ b/README.md @@ -732,6 +732,21 @@ argument of `OTelConfig`. The following options are supported by `MetricsConfig` Other aspects of the aggregation, such as using exponential histograms, are configured with the views of the OpenTelemetry SDK. +The `command` group reports `db.client.operation.duration`, a histogram of the time spent executing +each command as seen by the application, retries and cluster redirects included: + +- Pipelines and transactions are reported as a single operation named `PIPELINE` or `MULTI`, with the + number of commands in `db.operation.batch.size`. +- Failed operations carry `error.type` and `redis.client.errors.category` (`network`, `auth`, `server` + or `other`), plus `db.response.status_code` with the error prefix returned by the server. +- `redis.client.operation.retry_attempts` is the number of retries performed by Predis. Retries made + by Relay are not visible to Predis and are not counted. +- `db.namespace` is the database selected when connecting, later `SELECT` commands are not tracked. +- `server.address` and `server.port` are the connection parameters of the node, while + `network.peer.address` and `network.peer.port` are the resolved address of the socket (not available + with Relay). With aggregate connections they are reported only when the node is known: always with + replication, and for commands that succeeded or failed with a connection error with cluster. + PHP has no background exporter, so metrics leave the process only when the meter provider is flushed or shut down, which usually happens once at the end of each request. Long-running processes such as queue workers should flush periodically using `ObservabilityInstance::getInstance()->forceFlush()`. diff --git a/src/Client.php b/src/Client.php index 9b09bf28..f48ed4ec 100644 --- a/src/Client.php +++ b/src/Client.php @@ -31,6 +31,7 @@ use Predis\Consumer\PubSub\Consumer as PubSubConsumer; use Predis\Consumer\PubSub\RelayConsumer as RelayPubSubConsumer; use Predis\Consumer\Push\Consumer as PushConsumer; use Predis\Monitor\Consumer as MonitorConsumer; +use Predis\Observability\ObservabilityInstance; use Predis\Pipeline\Atomic; use Predis\Pipeline\FireAndForget; use Predis\Pipeline\Pipeline; @@ -313,9 +314,21 @@ class Client implements ClientInterface, IteratorAggregate $error = false; $commandID = array_shift($arguments); - $response = $this->connection->executeCommand( - new RawCommand($commandID, $arguments) - ); + $command = new RawCommand($commandID, $arguments); + $collector = ObservabilityInstance::getInstance()->getCollector(); + + if ($collector === null || !$collector->tracksOperation($commandID)) { + $response = $this->connection->executeCommand($command); + } else { + $response = $collector->measureOperation( + $commandID, + $this->connection, + function () use ($command) { + return $this->connection->executeCommand($command); + }, + $command + ); + } if ($response instanceof ResponseInterface) { if ($response instanceof ErrorResponseInterface) { @@ -413,6 +426,31 @@ class Client implements ClientInterface, IteratorAggregate * @throws Throwable */ public function executeCommand(CommandInterface $command) + { + $collector = ObservabilityInstance::getInstance()->getCollector(); + + if ($collector === null || !$collector->tracksOperation($command->getId())) { + return $this->sendCommand($command); + } + + return $collector->measureOperation( + $command->getId(), + $this->connection, + function () use ($command) { + return $this->sendCommand($command); + }, + $command + ); + } + + /** + * Sends the command to the server, retrying on failure, and returns its parsed response. + * + * @param CommandInterface $command + * @return mixed + * @throws Throwable + */ + protected function sendCommand(CommandInterface $command) { $parameters = $this->connection->getParameters(); diff --git a/src/Connection/Resource/Stream.php b/src/Connection/Resource/Stream.php index a7f28d1d..643e4883 100644 --- a/src/Connection/Resource/Stream.php +++ b/src/Connection/Resource/Stream.php @@ -318,6 +318,20 @@ class Stream implements StreamInterface return stream_get_contents($this->stream); } + /** + * Returns the address of the remote end of a socket stream, such as "127.0.0.1:6379". + * + * @return string|null + */ + public function getPeerName(): ?string + { + if (!isset($this->stream)) { + return null; + } + + return @stream_socket_get_name($this->stream, true) ?: null; + } + /** * {@inheritDoc} * @return mixed diff --git a/src/Connection/StreamConnection.php b/src/Connection/StreamConnection.php index 1dd5d830..62afa472 100644 --- a/src/Connection/StreamConnection.php +++ b/src/Connection/StreamConnection.php @@ -16,6 +16,7 @@ use Predis\Command\CommandInterface; use Predis\Command\RawCommand; use Predis\CommunicationException; use Predis\Connection\Resource\Exception\StreamInitException; +use Predis\Connection\Resource\Stream; use Predis\Connection\Resource\StreamFactory; use Predis\Connection\Resource\StreamFactoryInterface; use Predis\Consumer\Push\PushNotificationException; @@ -52,6 +53,11 @@ class StreamConnection extends AbstractConnection */ protected $streamFactory; + /** + * @var string|null + */ + protected $peerName; + /** * @param ParametersInterface $parameters * @param StreamFactoryInterface|null $factory @@ -93,6 +99,8 @@ class StreamConnection extends AbstractConnection return; } + $this->peerName = null; + if ($this->initCommands) { $responses = $this->sendPipeline($this->initCommands); @@ -163,6 +171,24 @@ class StreamConnection extends AbstractConnection return $responses; } + /** + * Returns the address of the server the connection is, or was last, connected to. + * + * It is the resolved peer of the socket (for example "127.0.0.1:6379"), which may + * differ from the host given in the connection parameters. + * + * @return string|null + */ + public function getPeerName(): ?string + { + if ($this->peerName === null && $this->isConnected()) { + $stream = $this->getResource(); + $this->peerName = $stream instanceof Stream ? $stream->getPeerName() : null; + } + + return $this->peerName; + } + /** * {@inheritdoc} */ diff --git a/src/Observability/MetricsCollector.php b/src/Observability/MetricsCollector.php index 88536aae..45336947 100644 --- a/src/Observability/MetricsCollector.php +++ b/src/Observability/MetricsCollector.php @@ -12,8 +12,19 @@ namespace Predis\Observability; +use OpenTelemetry\API\Metrics\HistogramInterface; use OpenTelemetry\API\Metrics\MeterInterface; use Predis\Client; +use Predis\Command\CommandInterface; +use Predis\CommunicationException; +use Predis\Connection\Cluster\ClusterInterface; +use Predis\Connection\ConnectionInterface; +use Predis\Connection\NodeConnectionInterface; +use Predis\Connection\Replication\ReplicationInterface; +use Predis\Connection\Resource\Exception\StreamInitException; +use Predis\Connection\StreamConnection; +use Predis\Response\ErrorInterface as ErrorResponseInterface; +use Throwable; /** * Owns the OpenTelemetry instruments of the enabled metric groups and records measurements on them. @@ -32,6 +43,16 @@ class MetricsCollector */ protected $config; + /** + * @var HistogramInterface|null + */ + protected $operationDuration; + + /** + * @var int + */ + protected $retryAttempts = 0; + /** * @param MeterInterface $meter * @param MetricsConfig $config @@ -40,6 +61,209 @@ class MetricsCollector { $this->meter = $meter; $this->config = $config; + + if ($config->isGroupEnabled(MetricGroup::COMMAND)) { + $this->operationDuration = $meter->createHistogram( + 'db.client.operation.duration', + 's', + 'Duration of operations as seen by the application, retries included.', + ['ExplicitBucketBoundaries' => $config->getBucketsOperationDuration()] + ); + } + } + + /** + * Tells if the duration of the given operation must be measured. + * + * @param string $operation Command ID, PIPELINE or MULTI. + * @return bool + */ + public function tracksOperation(string $operation): bool + { + return $this->operationDuration !== null + && $this->operationDuration->isEnabled() + && $this->config->shouldTrackCommand($operation); + } + + /** + * Counts a retry of the operation being measured. + */ + public function countRetry(): void + { + ++$this->retryAttempts; + } + + /** + * Runs an operation and records its duration, including the error it ended with. + * + * @param string $operation Command ID, PIPELINE or MULTI. + * @param ConnectionInterface $connection Connection of the client running the operation. + * @param callable $callback Executes the operation and returns its response. + * @param CommandInterface|null $command Command being executed, NULL for pipelines and transactions. + * @param int|null $batchSize Number of commands in a pipeline or transaction, defaults + * to the number of responses. + * @return mixed + * @throws Throwable + */ + public function measureOperation( + string $operation, + ConnectionInterface $connection, + callable $callback, + ?CommandInterface $command = null, + ?int $batchSize = null + ) { + $this->retryAttempts = 0; + $start = hrtime(true); + + try { + $response = $callback(); + } catch (Throwable $exception) { + $this->recordOperationDuration($operation, $start, $connection, $command, $batchSize, $exception); + + throw $exception; + } + + if ($command === null && $batchSize === null && is_array($response)) { + $batchSize = count($response); + } + + $error = $response instanceof ErrorResponseInterface ? $response : null; + $this->recordOperationDuration($operation, $start, $connection, $command, $batchSize, $error); + + return $response; + } + + /** + * @param string $operation + * @param int|float $start Value of hrtime(true) when the operation started. + * @param ConnectionInterface $connection + * @param CommandInterface|null $command + * @param int|null $batchSize + * @param Throwable|ErrorResponseInterface|null $error + */ + protected function recordOperationDuration( + string $operation, + $start, + ConnectionInterface $connection, + ?CommandInterface $command, + ?int $batchSize, + $error + ): void { + $duration = (hrtime(true) - $start) / 1e9; + + try { + $attributes = [ + 'db.operation.name' => $operation, + 'redis.client.operation.retry_attempts' => $this->retryAttempts, + ]; + + if ($batchSize !== null) { + $attributes['db.operation.batch.size'] = $batchSize; + } + + $attributes += $this->nodeAttributes($this->resolveNode($connection, $command, $error)); + $attributes += $this->errorAttributes($error); + + $this->operationDuration->record($duration, $this->buildAttributes($attributes)); + } catch (Throwable $exception) { + // Telemetry must never break the operation it observes. + } + } + + /** + * Returns the node an operation was executed on, when it is known without contacting any server. + * + * @param ConnectionInterface $connection + * @param CommandInterface|null $command + * @param Throwable|ErrorResponseInterface|null $error + * @return NodeConnectionInterface|null + */ + protected function resolveNode(ConnectionInterface $connection, ?CommandInterface $command, $error) + { + if ($error instanceof CommunicationException) { + return $error->getConnection(); + } + + if ($connection instanceof NodeConnectionInterface) { + return $connection; + } + + if ($connection instanceof ReplicationInterface) { + return $connection->getCurrent(); + } + + // After a successful command the slots map already points to the node that served it. + if ($connection instanceof ClusterInterface && $command !== null && $error === null) { + return $connection->getConnectionByCommand($command); + } + + return null; + } + + /** + * @param NodeConnectionInterface|null $node + * @return array + */ + protected function nodeAttributes(?NodeConnectionInterface $node): array + { + if ($node === null) { + return []; + } + + $parameters = $node->getParameters(); + // The database selected when connecting, a later SELECT is not tracked. + $attributes = ['db.namespace' => (string) ($parameters->database ?? 0)]; + + if ($parameters->scheme === 'unix') { + $attributes['server.address'] = $parameters->path; + } else { + $attributes['server.address'] = $parameters->host; + $attributes['server.port'] = (int) $parameters->port; + } + + if ($node instanceof StreamConnection && null !== $peer = $node->getPeerName()) { + $separator = strrpos($peer, ':'); + + if ($separator === false) { + $attributes['network.peer.address'] = $peer; + } else { + $attributes['network.peer.address'] = trim(substr($peer, 0, $separator), '[]'); + $attributes['network.peer.port'] = (int) substr($peer, $separator + 1); + } + } + + return $attributes; + } + + /** + * @param Throwable|ErrorResponseInterface|null $error + * @return array + */ + protected function errorAttributes($error): array + { + if ($error === null) { + return []; + } + + // Error responses and the exceptions created from them carry the error prefix sent by the server. + if ($error instanceof ErrorResponseInterface) { + $status = $error->getErrorType(); + + return [ + 'error.type' => $status, + 'db.response.status_code' => $status, + 'redis.client.errors.category' => in_array($status, ['NOAUTH', 'WRONGPASS', 'NOPERM'], true) + ? 'auth' + : 'server', + ]; + } + + $isNetwork = $error instanceof CommunicationException || $error instanceof StreamInitException; + + return [ + 'error.type' => get_class($error), + 'redis.client.errors.category' => $isNetwork ? 'network' : 'other', + ]; } /** diff --git a/src/Pipeline/Pipeline.php b/src/Pipeline/Pipeline.php index 83f4fe38..d2edca9a 100644 --- a/src/Pipeline/Pipeline.php +++ b/src/Pipeline/Pipeline.php @@ -23,6 +23,7 @@ use Predis\Connection\Cluster\RedisCluster; use Predis\Connection\ConnectionException; use Predis\Connection\ConnectionInterface; use Predis\Connection\Replication\ReplicationInterface; +use Predis\Observability\ObservabilityInstance; use Predis\Response\ErrorInterface as ErrorResponseInterface; use Predis\Response\ResponseInterface; use Predis\Response\ServerException; @@ -309,8 +310,22 @@ class Pipeline implements ClientContextInterface if ($send && !$this->pipeline->isEmpty()) { $connection = $this->getConnection(); + $collector = ObservabilityInstance::getInstance()->getCollector(); + try { - $responses = $this->executePipeline($connection, $this->pipeline); + if ($collector === null || !$collector->tracksOperation('PIPELINE')) { + $responses = $this->executePipeline($connection, $this->pipeline); + } else { + $responses = $collector->measureOperation( + 'PIPELINE', + $connection, + function () use ($connection) { + return $this->executePipeline($connection, $this->pipeline); + }, + null, + count($this->pipeline) + ); + } } catch (Throwable $exception) { $this->pipeline = new SplQueue(); diff --git a/src/Retry/Retry.php b/src/Retry/Retry.php index d93c2a45..4e6f51ac 100644 --- a/src/Retry/Retry.php +++ b/src/Retry/Retry.php @@ -14,6 +14,7 @@ namespace Predis\Retry; use Predis\Connection\ConnectionException; use Predis\Connection\Resource\Exception\StreamInitException; +use Predis\Observability\ObservabilityInstance; use Predis\Retry\Strategy\RetryStrategyInterface; use Predis\TimeoutException; use Throwable; @@ -138,6 +139,10 @@ class Retry throw $e; } + if ($collector = ObservabilityInstance::getInstance()->getCollector()) { + $collector->countRetry(); + } + if ($fail !== null) { $fail($e); } diff --git a/src/Transaction/MultiExec.php b/src/Transaction/MultiExec.php index 996e6365..9c903e51 100644 --- a/src/Transaction/MultiExec.php +++ b/src/Transaction/MultiExec.php @@ -20,6 +20,7 @@ use Predis\Command\CommandInterface; use Predis\CommunicationException; use Predis\Connection\AggregateConnectionInterface; use Predis\NotSupportedException; +use Predis\Observability\ObservabilityInstance; use Predis\Protocol\ProtocolException; use Predis\Response\Error; use Predis\Response\ErrorInterface as ErrorResponseInterface; @@ -420,6 +421,30 @@ class MultiExec implements ClientContextInterface * @throws ServerException */ public function execute($callable = null) + { + $collector = ObservabilityInstance::getInstance()->getCollector(); + + if ($collector === null || !$collector->tracksOperation('MULTI')) { + return $this->executeTransaction($callable); + } + + return $collector->measureOperation( + 'MULTI', + $this->client->getConnection(), + function () use ($callable) { + return $this->executeTransaction($callable); + } + ); + } + + /** + * @param mixed $callable Optional callback for execution. + * @return array|null + * @throws CommunicationException + * @throws AbortedMultiExecException + * @throws ServerException + */ + protected function executeTransaction($callable) { $this->assertNotAborted(); $this->checkBeforeExecution($callable); diff --git a/tests/Predis/Connection/Resource/StreamTest.php b/tests/Predis/Connection/Resource/StreamTest.php index 160812fa..c24e6719 100644 --- a/tests/Predis/Connection/Resource/StreamTest.php +++ b/tests/Predis/Connection/Resource/StreamTest.php @@ -425,6 +425,20 @@ class StreamTest extends TestCase $this->assertNull($stream->getMetadata()); } + /** + * @return void + */ + public function testGetPeerNameReturnsNullWithoutRemoteEnd(): void + { + $stream = new Stream(fopen('php://temp', 'rb+')); + + $this->assertNull($stream->getPeerName()); + + $stream->detach(); + + $this->assertNull($stream->getPeerName()); + } + /** * @return void */ diff --git a/tests/Predis/Connection/StreamConnectionTest.php b/tests/Predis/Connection/StreamConnectionTest.php index 96b14dcf..87a30f64 100644 --- a/tests/Predis/Connection/StreamConnectionTest.php +++ b/tests/Predis/Connection/StreamConnectionTest.php @@ -783,6 +783,25 @@ class StreamConnectionTest extends PredisConnectionTestCase // ---- INTEGRATION TESTS --------------------------------------------- // // ******************************************************************** // + /** + * @group connected + */ + public function testGetPeerNameReturnsAddressOfLastConnectedServer(): void + { + $connection = $this->createConnection(); + + $this->assertNull($connection->getPeerName()); + + $connection->connect(); + $peerName = $connection->getPeerName(); + + $this->assertStringEndsWith(':' . constant('REDIS_SERVER_PORT'), $peerName); + + $connection->disconnect(); + + $this->assertSame($peerName, $connection->getPeerName()); + } + /** * @group connected * @requires PHP 5.4 diff --git a/tests/Predis/Observability/OperationDurationTest.php b/tests/Predis/Observability/OperationDurationTest.php new file mode 100644 index 00000000..c1276074 --- /dev/null +++ b/tests/Predis/Observability/OperationDurationTest.php @@ -0,0 +1,404 @@ +markTestSkipped('The OpenTelemetry API is not installed.'); + } + } + + protected function tearDown(): void + { + ObservabilityInstance::getInstance()->init(new OTelConfig()); + } + + /** + * @group disconnected + */ + public function testCreatesHistogramWithConfiguredBuckets(): void + { + $meter = $this->createMock(MeterInterface::class); + $meter + ->expects($this->once()) + ->method('createHistogram') + ->with('db.client.operation.duration', 's', $this->isType('string'), ['ExplicitBucketBoundaries' => [0.1, 1]]) + ->willReturn($this->createMock(HistogramInterface::class)); + + new MetricsCollector($meter, new MetricsConfig([ + 'enabled_metric_groups' => [MetricGroup::COMMAND], + 'buckets_operation_duration' => [0.1, 1], + ])); + } + + /** + * @group disconnected + */ + public function testDoesNotCreateHistogramWhenCommandGroupIsDisabled(): void + { + $meter = $this->createMock(MeterInterface::class); + $meter->expects($this->never())->method('createHistogram'); + + $collector = new MetricsCollector($meter, new MetricsConfig()); + + $this->assertFalse($collector->tracksOperation('GET')); + } + + /** + * @group disconnected + */ + public function testRecordsDurationOfSuccessfulCommand(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://redis.example:6380?database=5'); + $connection->expects($this->once())->method('executeCommand')->willReturn('bar'); + + $this->assertSame('bar', (new Client($connection))->get('foo')); + + $this->assertCount(1, $this->records); + [$duration, $attributes] = $this->records[0]; + + $this->assertIsFloat($duration); + $this->assertGreaterThanOrEqual(0, $duration); + $this->assertEquals([ + 'db.system.name' => 'redis', + 'redis.client.library' => 'predis:' . Client::VERSION, + 'db.operation.name' => 'GET', + 'db.namespace' => '5', + 'server.address' => 'redis.example', + 'server.port' => 6380, + 'redis.client.operation.retry_attempts' => 0, + ], $attributes); + } + + /** + * @group disconnected + */ + public function testRecordsServerErrorThrownAsException(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn(new Error('WRONGTYPE Operation against a key')); + + try { + (new Client($connection))->get('foo'); + $this->fail('Expected a ServerException'); + } catch (ServerException $exception) { + // Expected. + } + + $attributes = $this->records[0][1]; + + $this->assertSame('WRONGTYPE', $attributes['error.type']); + $this->assertSame('WRONGTYPE', $attributes['db.response.status_code']); + $this->assertSame('server', $attributes['redis.client.errors.category']); + } + + /** + * @group disconnected + */ + public function testRecordsServerErrorReturnedAsResponse(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn(new Error('NOAUTH Authentication required.')); + + $response = (new Client($connection, ['exceptions' => false]))->get('foo'); + + $this->assertInstanceOf(Error::class, $response); + $this->assertSame('NOAUTH', $this->records[0][1]['db.response.status_code']); + $this->assertSame('auth', $this->records[0][1]['redis.client.errors.category']); + } + + /** + * @group disconnected + */ + public function testRecordsRetryAttemptsOfCommandThatEventuallySucceeds(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection(['retry' => new Retry(new NoBackoff(), 3)]); + $connection + ->expects($this->exactly(3)) + ->method('executeCommand') + ->willReturnOnConsecutiveCalls( + $this->throwException(new ConnectionException($connection, 'boom')), + $this->throwException(new ConnectionException($connection, 'boom')), + 'bar' + ); + + $this->assertSame('bar', (new Client($connection))->get('foo')); + + $this->assertCount(1, $this->records); + $this->assertSame(2, $this->records[0][1]['redis.client.operation.retry_attempts']); + $this->assertArrayNotHasKey('error.type', $this->records[0][1]); + } + + /** + * @group disconnected + */ + public function testRecordsNetworkErrorAndResetsRetryAttemptsBetweenOperations(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection(['retry' => new Retry(new NoBackoff(), 1)]); + $connection + ->method('executeCommand') + ->willReturnOnConsecutiveCalls( + $this->throwException(new ConnectionException($connection, 'boom')), + $this->throwException(new ConnectionException($connection, 'boom')), + 'bar' + ); + $client = new Client($connection); + + try { + $client->get('foo'); + $this->fail('Expected a ConnectionException'); + } catch (ConnectionException $exception) { + // Expected. + } + + $client->get('foo'); + + $failed = $this->records[0][1]; + $this->assertSame(ConnectionException::class, $failed['error.type']); + $this->assertSame('network', $failed['redis.client.errors.category']); + $this->assertSame(1, $failed['redis.client.operation.retry_attempts']); + $this->assertArrayNotHasKey('db.response.status_code', $failed); + $this->assertSame(0, $this->records[1][1]['redis.client.operation.retry_attempts']); + } + + /** + * @group disconnected + */ + public function testRecordsOtherErrors(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willThrowException(new RuntimeException('boom')); + + try { + (new Client($connection))->get('foo'); + $this->fail('Expected a RuntimeException'); + } catch (RuntimeException $exception) { + // Expected. + } + + $this->assertSame(RuntimeException::class, $this->records[0][1]['error.type']); + $this->assertSame('other', $this->records[0][1]['redis.client.errors.category']); + } + + /** + * @group disconnected + */ + public function testHonorsCommandFilters(): void + { + $this->enableCommandMetrics(['exclude_commands' => ['get']]); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn('bar'); + $client = new Client($connection); + + $client->get('foo'); + $client->echo('foo'); + + $this->assertCount(1, $this->records); + $this->assertSame('ECHO', $this->records[0][1]['db.operation.name']); + } + + /** + * @group disconnected + */ + public function testDoesNotRecordWhenInstrumentIsDisabled(): void + { + $this->enableCommandMetrics([], false); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn('bar'); + + $this->assertSame('bar', (new Client($connection))->get('foo')); + $this->assertSame([], $this->records); + } + + /** + * @group disconnected + */ + public function testRecordingFailureDoesNotBreakCommand(): void + { + $histogram = $this->createMock(HistogramInterface::class); + $histogram->method('isEnabled')->willReturn(true); + $histogram->expects($this->once())->method('record')->willThrowException(new RuntimeException('boom')); + $this->initObservability($histogram, []); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn('bar'); + + $this->assertSame('bar', (new Client($connection))->get('foo')); + } + + /** + * @group disconnected + */ + public function testRecordsRawCommand(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('executeCommand')->willReturn(new Error('ERR unknown command')); + + $response = (new Client($connection))->executeRaw(['FOO', 'bar'], $error); + + $this->assertTrue($error); + $this->assertSame('ERR unknown command', $response); + $this->assertSame('FOO', $this->records[0][1]['db.operation.name']); + $this->assertSame('ERR', $this->records[0][1]['db.response.status_code']); + } + + /** + * @group disconnected + */ + public function testRecordsUnixSocketAndPeerAddress(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockBuilder(StreamConnection::class)->disableOriginalConstructor()->getMock(); + $connection->method('getParameters')->willReturn($this->getParameters(['scheme' => 'unix', 'path' => '/tmp/redis.sock'])); + $connection->method('getPeerName')->willReturn('[::1]:6379'); + $connection->method('executeCommand')->willReturn('bar'); + + (new Client($connection))->get('foo'); + + $attributes = $this->records[0][1]; + $this->assertSame('/tmp/redis.sock', $attributes['server.address']); + $this->assertArrayNotHasKey('server.port', $attributes); + $this->assertSame('::1', $attributes['network.peer.address']); + $this->assertSame(6379, $attributes['network.peer.port']); + } + + /** + * @group disconnected + */ + public function testRecordsPipelineAsSingleOperation(): void + { + $this->enableCommandMetrics(); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('readResponse')->willReturnOnConsecutiveCalls(new Status('OK'), 'bar'); + + $responses = (new Client($connection))->pipeline(function ($pipe) { + $pipe->set('foo', 'bar'); + $pipe->get('foo'); + }); + + $this->assertCount(2, $responses); + $this->assertCount(1, $this->records); + $this->assertSame('PIPELINE', $this->records[0][1]['db.operation.name']); + $this->assertSame(2, $this->records[0][1]['db.operation.batch.size']); + $this->assertSame('127.0.0.1', $this->records[0][1]['server.address']); + } + + /** + * @group disconnected + */ + public function testRecordsTransactionAsSingleOperation(): void + { + $this->enableCommandMetrics(['include_commands' => ['MULTI']]); + + $connection = $this->getMockConnection('tcp://127.0.0.1:6379'); + $connection->method('isConnected')->willReturn(true); + $connection + ->method('executeCommand') + ->willReturnCallback(function (CommandInterface $command) { + switch ($command->getId()) { + case 'MULTI': + return new Status('OK'); + case 'EXEC': + return [new Status('OK'), 'bar']; + default: + return new Status('QUEUED'); + } + }); + + $responses = (new Client($connection))->transaction(function ($tx) { + $tx->set('foo', 'bar'); + $tx->get('foo'); + }); + + $this->assertCount(2, $responses); + $this->assertCount(1, $this->records); + $this->assertSame('MULTI', $this->records[0][1]['db.operation.name']); + $this->assertSame(2, $this->records[0][1]['db.operation.batch.size']); + } + + /** + * Enables the command group with a histogram that stores what is recorded on it. + * + * @param array $options Additional metrics options. + * @param bool $enabled Value returned by the instrument's isEnabled(). + */ + private function enableCommandMetrics(array $options = [], bool $enabled = true): void + { + $histogram = $this->createMock(HistogramInterface::class); + $histogram->method('isEnabled')->willReturn($enabled); + $histogram->method('record')->willReturnCallback(function ($amount, $attributes) { + $this->records[] = [$amount, $attributes]; + }); + + $this->initObservability($histogram, $options); + } + + private function initObservability(HistogramInterface $histogram, array $options): void + { + $meter = $this->createMock(MeterInterface::class); + $meter->method('createHistogram')->willReturn($histogram); + $provider = $this->createMock(MeterProviderInterface::class); + $provider->method('getMeter')->willReturn($meter); + + ObservabilityInstance::getInstance()->init(new OTelConfig( + new MetricsConfig($options + ['enabled' => true, 'enabled_metric_groups' => [MetricGroup::COMMAND]]), + $provider + )); + } +}