From c95a071ce90d367107e85decbc9c0ec76d3441ba Mon Sep 17 00:00:00 2001 From: Daniel Badura Date: Mon, 31 Aug 2026 16:03:46 +0200 Subject: [PATCH] PoC otel integration --- composer.json | 9 +- composer.lock | 1062 ++++++++++++++++- docs/correlation-causation.md | 181 +++ docs/message-decorator.md | 29 + docs/message.md | 5 + docs/opentelemetry.md | 183 +++ docs/project.json | 8 + src/CommandBus/SyncCommandBus.php | 18 +- src/EventBus/DefaultConsumer.php | 26 +- src/Message/Context/MessageContext.php | 86 ++ .../Message/MessageHeaderRegistry.php | 6 + .../CorrelationCausationDecorator.php | 48 + src/Store/Header/CausationIdHeader.php | 14 + src/Store/Header/CorrelationIdHeader.php | 14 + src/Store/Header/TraceHeader.php | 22 + .../Engine/DefaultSubscriptionEngine.php | 9 + .../Listener/MessageContextSubscriber.php | 85 ++ src/Telemetry/ForceFlushListener.php | 38 + src/Telemetry/Instrumentation.php | 78 ++ src/Telemetry/MessageAttributes.php | 42 + src/Telemetry/SpanEventLogger.php | 43 + src/Telemetry/StoreDoesNotSupport.php | 23 + src/Telemetry/TraceAttributes.php | 41 + src/Telemetry/TraceDecorator.php | 54 + src/Telemetry/TraceableCommandBus.php | 31 + src/Telemetry/TraceableConsumer.php | 39 + src/Telemetry/TraceableEventBus.php | 41 + src/Telemetry/TraceableQueryBus.php | 29 + src/Telemetry/TraceableRepository.php | 68 ++ src/Telemetry/TraceableRepositoryManager.php | 49 + src/Telemetry/TraceableStore.php | 172 +++ src/Telemetry/TraceableSubscriptionEngine.php | 86 ++ src/Telemetry/TracingSubscriber.php | 144 +++ tests/Architecture/LayerDependenciesTest.php | 20 + .../CorrelationCausationIntegrationTest.php | 133 +++ .../Events/InvoiceCreated.php | 18 + .../Events/OrderPlaced.php | 18 + .../CorrelationCausation/Invoice.php | 44 + .../CorrelationCausation/InvoiceId.php | 13 + .../CorrelationCausation/Order.php | 44 + .../CorrelationCausation/OrderId.php | 13 + .../Processor/CreateInvoiceProcessor.php | 29 + .../Telemetry/Events/InvoiceCreated.php | 18 + .../Telemetry/Events/OrderPlaced.php | 18 + tests/Integration/Telemetry/Invoice.php | 44 + tests/Integration/Telemetry/InvoiceId.php | 13 + tests/Integration/Telemetry/Order.php | 44 + tests/Integration/Telemetry/OrderId.php | 13 + .../Processor/CreateInvoiceProcessor.php | 29 + .../Telemetry/TelemetryIntegrationTest.php | 182 +++ tests/Unit/CommandBus/SyncCommandBusTest.php | 117 +- tests/Unit/EventBus/DefaultConsumerTest.php | 81 ++ .../Message/Context/MessageContextTest.php | 125 ++ .../CorrelationCausationDecoratorTest.php | 135 +++ .../Listener/MessageContextSubscriberTest.php | 237 ++++ .../Engine/MessageProcessorTest.php | 75 ++ .../Unit/Telemetry/ForceFlushListenerTest.php | 45 + tests/Unit/Telemetry/InMemoryTracer.php | 70 ++ tests/Unit/Telemetry/InstrumentationTest.php | 99 ++ .../Unit/Telemetry/MessageAttributesTest.php | 57 + tests/Unit/Telemetry/SpanEventLoggerTest.php | 61 + tests/Unit/Telemetry/TraceDecoratorTest.php | 70 ++ .../Telemetry/TraceableCommandBusTest.php | 37 + .../Unit/Telemetry/TraceableConsumerTest.php | 52 + .../Unit/Telemetry/TraceableEventBusTest.php | 42 + .../Unit/Telemetry/TraceableQueryBusTest.php | 39 + .../TraceableRepositoryManagerTest.php | 43 + .../Telemetry/TraceableRepositoryTest.php | 100 ++ tests/Unit/Telemetry/TraceableStoreTest.php | 224 ++++ .../TraceableSubscriptionEngineTest.php | 111 ++ .../Unit/Telemetry/TracingSubscriberTest.php | 316 +++++ 71 files changed, 5560 insertions(+), 52 deletions(-) create mode 100644 docs/correlation-causation.md create mode 100644 docs/opentelemetry.md create mode 100644 src/Message/Context/MessageContext.php create mode 100644 src/Repository/MessageDecorator/CorrelationCausationDecorator.php create mode 100644 src/Store/Header/CausationIdHeader.php create mode 100644 src/Store/Header/CorrelationIdHeader.php create mode 100644 src/Store/Header/TraceHeader.php create mode 100644 src/Subscription/Engine/Listener/MessageContextSubscriber.php create mode 100644 src/Telemetry/ForceFlushListener.php create mode 100644 src/Telemetry/Instrumentation.php create mode 100644 src/Telemetry/MessageAttributes.php create mode 100644 src/Telemetry/SpanEventLogger.php create mode 100644 src/Telemetry/StoreDoesNotSupport.php create mode 100644 src/Telemetry/TraceAttributes.php create mode 100644 src/Telemetry/TraceDecorator.php create mode 100644 src/Telemetry/TraceableCommandBus.php create mode 100644 src/Telemetry/TraceableConsumer.php create mode 100644 src/Telemetry/TraceableEventBus.php create mode 100644 src/Telemetry/TraceableQueryBus.php create mode 100644 src/Telemetry/TraceableRepository.php create mode 100644 src/Telemetry/TraceableRepositoryManager.php create mode 100644 src/Telemetry/TraceableStore.php create mode 100644 src/Telemetry/TraceableSubscriptionEngine.php create mode 100644 src/Telemetry/TracingSubscriber.php create mode 100644 tests/Integration/CorrelationCausation/CorrelationCausationIntegrationTest.php create mode 100644 tests/Integration/CorrelationCausation/Events/InvoiceCreated.php create mode 100644 tests/Integration/CorrelationCausation/Events/OrderPlaced.php create mode 100644 tests/Integration/CorrelationCausation/Invoice.php create mode 100644 tests/Integration/CorrelationCausation/InvoiceId.php create mode 100644 tests/Integration/CorrelationCausation/Order.php create mode 100644 tests/Integration/CorrelationCausation/OrderId.php create mode 100644 tests/Integration/CorrelationCausation/Processor/CreateInvoiceProcessor.php create mode 100644 tests/Integration/Telemetry/Events/InvoiceCreated.php create mode 100644 tests/Integration/Telemetry/Events/OrderPlaced.php create mode 100644 tests/Integration/Telemetry/Invoice.php create mode 100644 tests/Integration/Telemetry/InvoiceId.php create mode 100644 tests/Integration/Telemetry/Order.php create mode 100644 tests/Integration/Telemetry/OrderId.php create mode 100644 tests/Integration/Telemetry/Processor/CreateInvoiceProcessor.php create mode 100644 tests/Integration/Telemetry/TelemetryIntegrationTest.php create mode 100644 tests/Unit/Message/Context/MessageContextTest.php create mode 100644 tests/Unit/Repository/MessageDecorator/CorrelationCausationDecoratorTest.php create mode 100644 tests/Unit/Subscription/Engine/Listener/MessageContextSubscriberTest.php create mode 100644 tests/Unit/Telemetry/ForceFlushListenerTest.php create mode 100644 tests/Unit/Telemetry/InMemoryTracer.php create mode 100644 tests/Unit/Telemetry/InstrumentationTest.php create mode 100644 tests/Unit/Telemetry/MessageAttributesTest.php create mode 100644 tests/Unit/Telemetry/SpanEventLoggerTest.php create mode 100644 tests/Unit/Telemetry/TraceDecoratorTest.php create mode 100644 tests/Unit/Telemetry/TraceableCommandBusTest.php create mode 100644 tests/Unit/Telemetry/TraceableConsumerTest.php create mode 100644 tests/Unit/Telemetry/TraceableEventBusTest.php create mode 100644 tests/Unit/Telemetry/TraceableQueryBusTest.php create mode 100644 tests/Unit/Telemetry/TraceableRepositoryManagerTest.php create mode 100644 tests/Unit/Telemetry/TraceableRepositoryTest.php create mode 100644 tests/Unit/Telemetry/TraceableStoreTest.php create mode 100644 tests/Unit/Telemetry/TraceableSubscriptionEngineTest.php create mode 100644 tests/Unit/Telemetry/TracingSubscriberTest.php diff --git a/composer.json b/composer.json index 11d2345fb..4f45fc155 100644 --- a/composer.json +++ b/composer.json @@ -52,6 +52,9 @@ "doctrine/orm": "^2.18.0 || ^3.0.0", "infection/infection": "^0.32.0", "league/commonmark": "^2.6.1", + "nyholm/psr7": "^1.8", + "open-telemetry/api": "^1.5", + "open-telemetry/sdk": "^1.5", "patchlevel/coding-standard": "^1.3.0", "patchlevel/event-sourcing-phpstan-extension": "^1.2.0", "phpat/phpat": "^0.12.0", @@ -60,11 +63,13 @@ "phpstan/phpstan-phpunit": "^2.0", "phpunit/phpunit": "^11.5.15", "symfony/cache": "^6.4.0 || ^7.0.0 || ^8.0.0", + "symfony/http-client": "^8.1", "symfony/messenger": "^5.4.31 || ^6.4.0 || ^7.0.1 || ^8.0.0", "symfony/var-dumper": "^5.4.29 || ^6.4.0 || ^7.0.0 || ^8.0.0", "wnx/commonmark-markdown-renderer": "^1.5.0" }, "suggest": { + "open-telemetry/api": "for OpenTelemetry tracing with Patchlevel\\EventSourcing\\Telemetry", "patchlevel/event-sourcing-psalm-plugin": "for psalm support" }, "config": { @@ -73,9 +78,11 @@ }, "sort-packages": true, "allow-plugins": { + "composer/package-versions-deprecated": true, "dealerdirect/phpcodesniffer-composer-installer": true, "infection/extension-installer": true, - "composer/package-versions-deprecated": true + "php-http/discovery": true, + "tbachert/spi": true } }, "autoload": { diff --git a/composer.lock b/composer.lock index 8ba19c9bd..bebf463cc 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "d6be649e1b37cd5e48593ac3929ccf1c", + "content-hash": "83478322005be259c81f8d1c1c3580ae", "packages": [ { "name": "brick/math", @@ -2484,6 +2484,83 @@ ], "time": "2026-06-07T11:47:49+00:00" }, + { + "name": "composer/semver", + "version": "3.6.0", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "d92543b7ede9c4ec6b59853cefb061e39866d2cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/d92543b7ede9c4ec6b59853cefb061e39866d2cf", + "reference": "d92543b7ede9c4ec6b59853cefb061e39866d2cf", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^1.11", + "symfony/phpunit-bridge": "^3 || ^7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Version comparison library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "ircs://irc.libera.chat:6697/composer", + "issues": "https://github.com/composer/semver/issues", + "source": "https://github.com/composer/semver/tree/3.6.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + } + ], + "time": "2026-10-29T09:13:34+00:00" + }, { "name": "composer/xdebug-handler", "version": "3.0.5", @@ -4346,6 +4423,150 @@ }, "time": "2025-12-06T11:56:16+00:00" }, + { + "name": "nyholm/psr7", + "version": "1.8.2", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7.git", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7/zipball/a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "reference": "a71f2b11690f4b24d099d6b16690a90ae14fc6f3", + "shasum": "" + }, + "require": { + "php": ">=7.2", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0", + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "http-interop/http-factory-tests": "^0.9", + "php-http/message-factory": "^1.0", + "php-http/psr7-integration-tests": "^1.0", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.4", + "symfony/error-handler": "^4.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8-dev" + } + }, + "autoload": { + "psr-4": { + "Nyholm\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "A fast PHP7 implementation of PSR-7", + "homepage": "https://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7/issues", + "source": "https://github.com/Nyholm/psr7/tree/1.8.2" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2024-09-09T07:06:30+00:00" + }, + { + "name": "nyholm/psr7-server", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Nyholm/psr7-server.git", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nyholm/psr7-server/zipball/4335801d851f554ca43fa6e7d2602141538854dc", + "reference": "4335801d851f554ca43fa6e7d2602141538854dc", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "require-dev": { + "nyholm/nsa": "^1.1", + "nyholm/psr7": "^1.3", + "phpunit/phpunit": "^7.0 || ^8.5 || ^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Nyholm\\Psr7Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com" + }, + { + "name": "Martijn van der Ven", + "email": "martijn@vanderven.se" + } + ], + "description": "Helper classes to handle PSR-7 server requests", + "homepage": "http://tnyholm.se", + "keywords": [ + "psr-17", + "psr-7" + ], + "support": { + "issues": "https://github.com/Nyholm/psr7-server/issues", + "source": "https://github.com/Nyholm/psr7-server/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/Zegnat", + "type": "github" + }, + { + "url": "https://github.com/nyholm", + "type": "github" + } + ], + "time": "2023-11-08T09:30:43+00:00" + }, { "name": "ondram/ci-detector", "version": "4.2.0", @@ -4424,6 +4645,297 @@ }, "time": "2024-03-12T13:22:30+00:00" }, + { + "name": "open-telemetry/api", + "version": "1.11.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/api.git", + "reference": "bc169d9ecd11858e941657770dc708c6a15fc5f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/bc169d9ecd11858e941657770dc708c6a15fc5f4", + "reference": "bc169d9ecd11858e941657770dc708c6a15fc5f4", + "shasum": "" + }, + "require": { + "open-telemetry/context": "^1.4", + "php": "^8.2", + "psr/log": "^1.1|^2.0|^3.0" + }, + "conflict": { + "open-telemetry/sdk": "<=1.11", + "open-telemetry/sdk-configuration": "<0.10" + }, + "suggest": { + "symfony/config": "To implement a ComponentProvider for declarative configuration" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Configuration\\Config\\ComponentProvider": [ + "OpenTelemetry\\API\\Baggage\\Propagation\\Config\\TextMapPropagatorBaggage", + "OpenTelemetry\\API\\Trace\\Propagation\\Config\\TextMapPropagatorTraceContext" + ], + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.11.x-dev" + } + }, + "autoload": { + "files": [ + "Trace/functions.php" + ], + "psr-4": { + "OpenTelemetry\\API\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "API for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "api", + "apm", + "logging", + "opentelemetry", + "otel", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2026-11-05T11:54:49+00:00" + }, + { + "name": "open-telemetry/context", + "version": "1.6.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/context.git", + "reference": "711e7291d9cf8a984c059c5afd926e45ab444b7f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/711e7291d9cf8a984c059c5afd926e45ab444b7f", + "reference": "711e7291d9cf8a984c059c5afd926e45ab444b7f", + "shasum": "" + }, + "require": { + "php": "^8.2" + }, + "suggest": { + "ext-ffi": "To allow context switching in Fibers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.6.x-dev" + } + }, + "autoload": { + "files": [ + "fiber/initialize_fiber_handler.php" + ], + "psr-4": { + "OpenTelemetry\\Context\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Context implementation for OpenTelemetry PHP.", + "keywords": [ + "Context", + "opentelemetry", + "otel" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2026-11-05T11:54:49+00:00" + }, + { + "name": "open-telemetry/sdk", + "version": "1.16.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sdk.git", + "reference": "51ebca2563dd580d682d4f32b1611c1779424dac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sdk/zipball/51ebca2563dd580d682d4f32b1611c1779424dac", + "reference": "51ebca2563dd580d682d4f32b1611c1779424dac", + "shasum": "" + }, + "require": { + "ext-json": "*", + "nyholm/psr7-server": "^1.1", + "open-telemetry/api": "^1.11", + "open-telemetry/context": "^1.4", + "open-telemetry/sem-conv": "^1.45.0", + "php": "^8.2", + "php-http/discovery": "^1.14", + "psr/http-client": "^1.0", + "psr/http-client-implementation": "^1.0", + "psr/http-factory-implementation": "^1.0", + "psr/http-message": "^1.0.1|^2.0", + "psr/log": "^1.1|^2.0|^3.0", + "ramsey/uuid": "^3.0 || ^4.0", + "symfony/polyfill-mbstring": "^1.23", + "tbachert/spi": "^1.0.5" + }, + "suggest": { + "ext-gmp": "To support unlimited number of synchronous metric readers", + "ext-mbstring": "To increase performance of string operations", + "open-telemetry/sdk-configuration": "File-based OpenTelemetry SDK configuration" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Configuration\\ConfigEnv\\EnvComponentLoader": [ + "OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderHttpConfig", + "OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderPeerConfig", + "OpenTelemetry\\SDK\\ConfigEnv\\Trace\\SpanSuppressionStrategySemConv", + "OpenTelemetry\\SDK\\ConfigEnv\\Trace\\SpanSuppressionStrategySpanKind", + "OpenTelemetry\\SDK\\ConfigEnv\\Distribution\\DistributionConfigurationSdk" + ], + "OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\ResolverInterface": [ + "OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\SdkConfigurationResolver" + ], + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.16.x-dev" + } + }, + "autoload": { + "files": [ + "Common/Util/functions.php", + "Logs/Exporter/_register.php", + "Metrics/MetricExporter/_register.php", + "Propagation/_register.php", + "Trace/SpanExporter/_register.php", + "Common/Dev/Compatibility/_load.php", + "_autoload.php" + ], + "psr-4": { + "OpenTelemetry\\SDK\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "SDK for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "sdk", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2026-11-06T02:25:35+00:00" + }, + { + "name": "open-telemetry/sem-conv", + "version": "1.45.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/sem-conv.git", + "reference": "7a42562cf5891f56f6f8ea2ecc945f31108c8806" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/sem-conv/zipball/7a42562cf5891f56f6f8ea2ecc945f31108c8806", + "reference": "7a42562cf5891f56f6f8ea2ecc945f31108c8806", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "OpenTelemetry\\SemConv\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Semantic conventions for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "apm", + "logging", + "opentelemetry", + "otel", + "semantic conventions", + "semconv", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2026-11-03T22:37:22+00:00" + }, { "name": "patchlevel/coding-standard", "version": "1.3.0", @@ -4653,6 +5165,85 @@ }, "time": "2022-02-21T01:04:05+00:00" }, + { + "name": "php-http/discovery", + "version": "1.20.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/discovery.git", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/discovery/zipball/82fe4c73ef3363caed49ff8dd1539ba06044910d", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0|^2.0", + "php": "^7.1 || ^8.0" + }, + "conflict": { + "nyholm/psr7": "<1.0", + "zendframework/zend-diactoros": "*" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "*", + "psr/http-factory-implementation": "*", + "psr/http-message-implementation": "*" + }, + "require-dev": { + "composer/composer": "^1.0.2|^2.0", + "graham-campbell/phpspec-skip-example-extension": "^5.0", + "php-http/httplug": "^1.0 || ^2.0", + "php-http/message-factory": "^1.0", + "phpspec/phpspec": "^5.1 || ^6.1 || ^7.3", + "sebastian/comparator": "^3.0.5 || ^4.0.8", + "symfony/phpunit-bridge": "^6.4.4 || ^7.0.1" + }, + "type": "composer-plugin", + "extra": { + "class": "Http\\Discovery\\Composer\\Plugin", + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Http\\Discovery\\": "src/" + }, + "exclude-from-classmap": [ + "src/Composer/Plugin.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations", + "homepage": "http://php-http.org", + "keywords": [ + "adapter", + "client", + "discovery", + "factory", + "http", + "message", + "psr17", + "psr7" + ], + "support": { + "issues": "https://github.com/php-http/discovery/issues", + "source": "https://github.com/php-http/discovery/tree/1.20.0" + }, + "time": "2024-10-02T11:20:13+00:00" + }, { "name": "phpat/phpat", "version": "0.12.4", @@ -5426,63 +6017,223 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "11.5-dev" + "dev-main": "11.5-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.55" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsors.html", + "type": "custom" + }, + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit", + "type": "tidelift" + } + ], + "time": "2026-02-18T12:37:06+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" } }, "autoload": { - "files": [ - "src/Framework/Assert/Functions.php" - ], - "classmap": [ - "src/" - ] + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], "authors": [ { - "name": "Sebastian Bergmann", - "email": "sebastian@phpunit.de", - "role": "lead" + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" } ], - "description": "The PHP Unit Testing framework.", - "homepage": "https://phpunit.de/", + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", "keywords": [ - "phpunit", - "testing", - "xunit" + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" ], "support": { - "issues": "https://github.com/sebastianbergmann/phpunit/issues", - "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.55" + "source": "https://github.com/php-fig/http-factory" }, - "funding": [ - { - "url": "https://phpunit.de/sponsors.html", - "type": "custom" - }, - { - "url": "https://github.com/sebastianbergmann", - "type": "github" - }, - { - "url": "https://liberapay.com/sebastianbergmann", - "type": "liberapay" - }, - { - "url": "https://thanks.dev/u/gh/sebastianbergmann", - "type": "thanks_dev" - }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ { - "url": "https://tidelift.com/funding/github/packagist/phpunit/phpunit", - "type": "tidelift" + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" } ], - "time": "2026-02-18T12:37:06+00:00" + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" }, { "name": "sanmai/di-container", @@ -7331,6 +8082,185 @@ ], "time": "2026-05-29T05:06:50+00:00" }, + { + "name": "symfony/http-client", + "version": "v8.1.11", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client.git", + "reference": "1758b323ba9c5e88b42602b9c2cb27b640de4d36" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client/zipball/1758b323ba9c5e88b42602b9c2cb27b640de4d36", + "reference": "1758b323ba9c5e88b42602b9c2cb27b640de4d36", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "psr/log": "^1|^2|^3", + "symfony/deprecation-contracts": "^2.5|^3.0", + "symfony/http-client-contracts": "^3.7", + "symfony/service-contracts": "^2.5|^3" + }, + "conflict": { + "amphp/amp": "<3", + "php-http/discovery": "<1.15" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "1.0", + "symfony/http-client-implementation": "3.0" + }, + "require-dev": { + "amphp/http-client": "^5.3.2", + "amphp/http-tunnel": "^2.0", + "guzzlehttp/guzzle": "^7.10|^8.0", + "nyholm/psr7": "^1.0", + "php-http/httplug": "^1.0|^2.0", + "psr/http-client": "^1.0", + "symfony/cache": "^7.4|^8.0", + "symfony/dependency-injection": "^7.4|^8.0", + "symfony/http-kernel": "^7.4|^8.0", + "symfony/messenger": "^7.4|^8.0", + "symfony/process": "^7.4|^8.0", + "symfony/rate-limiter": "^7.4|^8.0", + "symfony/stopwatch": "^7.4|^8.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously", + "homepage": "https://symfony.com", + "keywords": [ + "http" + ], + "support": { + "source": "https://github.com/symfony/http-client/tree/v8.1.11" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-11-04T08:39:20+00:00" + }, + { + "name": "symfony/http-client-contracts", + "version": "v3.8.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "f9f94260f787446c6fd430b2ae1969fe41ae1ba8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/f9f94260f787446c6fd430b2ae1969fe41ae1ba8", + "reference": "f9f94260f787446c6fd430b2ae1969fe41ae1ba8", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Test/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v3.8.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-10-04T15:04:25+00:00" + }, { "name": "symfony/messenger", "version": "v8.1.0", @@ -7810,6 +8740,58 @@ ], "time": "2026-05-29T05:06:50+00:00" }, + { + "name": "tbachert/spi", + "version": "v1.0.5", + "source": { + "type": "git", + "url": "https://github.com/Nevay/spi.git", + "reference": "e7078767866d0a9e0f91d3f9d42a832df5e39002" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Nevay/spi/zipball/e7078767866d0a9e0f91d3f9d42a832df5e39002", + "reference": "e7078767866d0a9e0f91d3f9d42a832df5e39002", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.0", + "composer/semver": "^1.0 || ^2.0 || ^3.0", + "php": "^8.1" + }, + "require-dev": { + "composer/composer": "^2.0", + "infection/infection": "^0.27.9", + "phpunit/phpunit": "^10.5", + "psalm/phar": "^5.18" + }, + "type": "composer-plugin", + "extra": { + "class": "Nevay\\SPI\\Composer\\Plugin", + "branch-alias": { + "dev-main": "1.0.x-dev" + }, + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Nevay\\SPI\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Service provider loading facility", + "keywords": [ + "service provider" + ], + "support": { + "issues": "https://github.com/Nevay/spi/issues", + "source": "https://github.com/Nevay/spi/tree/v1.0.5" + }, + "time": "2025-06-29T15:42:06+00:00" + }, { "name": "thecodingmachine/safe", "version": "v3.4.0", diff --git a/docs/correlation-causation.md b/docs/correlation-causation.md new file mode 100644 index 000000000..0c77d3d44 --- /dev/null +++ b/docs/correlation-causation.md @@ -0,0 +1,181 @@ +# Correlation and Causation + +When one event triggers a processor which records the next event, you end up with a chain of events that belong +together. To follow such a chain later on, every message can carry two ids: a correlation id which stays the same for +the whole business transaction, and a causation id which points to the event that directly caused this message. + +The library can set both ids for you, so you don't have to pass them through your domain code. + +## Headers + +Both ids are stored as headers on the [message](message.md) and are persisted with the event. + +* `CorrelationIdHeader` - the id of the whole business transaction. +* `CausationIdHeader` - the id of the event that directly caused this message. + +```php +use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\Store\Header\CausationIdHeader; +use Patchlevel\EventSourcing\Store\Header\CorrelationIdHeader; + +/** @var Message $message */ +$message->header(CorrelationIdHeader::class)->correlationId; +$message->header(CausationIdHeader::class)->causationId; +``` +:::note +A message that starts a new transaction has no causation id, because nothing caused it. Its correlation id is the id of +the transaction it opens: the one generated by the command bus if you dispatch commands, the one you seeded yourself, or +as a last resort its own event id. +::: + +## Message context + +The ids are derived from the message which is currently being handled. The `MessageContext` holds exactly that +information and is shared between the event bus, the subscription engine, the command bus and the decorator. + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; + +$messageContext = new MessageContext(); +``` +:::warning +Use one single instance everywhere. If you wire a second instance somewhere, the ids will not be propagated. +::: + +## Enable the automatic propagation + +The ids are added by the `CorrelationCausationDecorator`, which is a [message decorator](message-decorator.md). +Pass it to the `DefaultRepositoryManager` together with the shared context. + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; +use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootRegistry; +use Patchlevel\EventSourcing\Repository\DefaultRepositoryManager; +use Patchlevel\EventSourcing\Repository\MessageDecorator\CorrelationCausationDecorator; +use Patchlevel\EventSourcing\Store\Store; + +/** + * @var AggregateRootRegistry $aggregateRootRegistry + * @var Store $store + */ +$messageContext = new MessageContext(); + +$repositoryManager = new DefaultRepositoryManager( + $aggregateRootRegistry, + $store, + null, + null, + new CorrelationCausationDecorator($messageContext), +); +``` +:::note +If you use multiple decorators, combine them with the `ChainMessageDecorator` as described on the +[message decorator](message-decorator.md) page. +::: + +The decorator only knows which message is currently being handled if the context is filled. Pass the same instance to +the [subscription engine](subscription.md), so that everything a processor records while handling an event inherits the +ids of that event. + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; +use Patchlevel\EventSourcing\Subscription\Engine\DefaultSubscriptionEngine; +use Patchlevel\EventSourcing\Subscription\Engine\MessageLoader; +use Patchlevel\EventSourcing\Subscription\Store\SubscriptionStore; +use Patchlevel\EventSourcing\Subscription\Subscriber\SubscriberAccessorRepository; + +/** + * @var MessageLoader $messageLoader + * @var SubscriptionStore $subscriptionStore + * @var SubscriberAccessorRepository $subscriberRepository + * @var MessageContext $messageContext + */ +$engine = new DefaultSubscriptionEngine( + $messageLoader, + $subscriptionStore, + $subscriberRepository, + messageContext: $messageContext, +); +``` +If you dispatch events synchronously over the [event bus](event-bus.md), pass the context to the consumer as well. + +```php +use Patchlevel\EventSourcing\EventBus\DefaultConsumer; +use Patchlevel\EventSourcing\Message\Context\MessageContext; + +/** @var MessageContext $messageContext */ +$consumer = DefaultConsumer::create([], $messageContext); +``` +## Correlate a whole command + +A command handler often records more than one event. All of these events belong to the same transaction, so they should +share one correlation id. The `SyncCommandBus` takes care of this if you pass the context to it. + +```php +use Patchlevel\EventSourcing\CommandBus\HandlerProvider; +use Patchlevel\EventSourcing\CommandBus\SyncCommandBus; +use Patchlevel\EventSourcing\Message\Context\MessageContext; + +/** + * @var HandlerProvider $handlerProvider + * @var MessageContext $messageContext + */ +$commandBus = new SyncCommandBus($handlerProvider, null, $messageContext); +``` +:::success +The bus generates a fresh correlation id for every dispatch, unless the context already holds one. Nested dispatches and +commands dispatched from a processor therefore keep the correlation id of the transaction they belong to. +::: + +## Set the ids yourself + +Sometimes the transaction starts outside of the library, for example with an http request. You can push your own ids +onto the context and remove them afterwards. + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; + +/** @var MessageContext $messageContext */ +$messageContext->push(correlationId: $request->headers->get('X-Request-Id')); + +try { + $repository->save($profile); +} finally { + $messageContext->pop(); +} +``` +:::warning +Every `push` needs a matching `pop`, otherwise the ids leak into the next transaction. Always pop in a `finally` block. +::: + +You can also set the headers directly on a message in your own [message decorator](message-decorator.md). Headers that +are already set are never overwritten by the `CorrelationCausationDecorator`. + +## Limitations + +The ids are added when an aggregate is saved over a repository. Events which are written directly with `Store::save` +bypass the decorator and therefore get no ids. + +Events recorded before the decorator was enabled have no correlation id. Such an event is treated as the root of its own +correlation: everything caused by it gets the event id of that event as correlation id. The old event itself is not +changed. + +:::warning +The ids are only available while a subscribe method runs. Everything the subscription engine does around a message, the +flush method of a [batchable subscriber](subscription.md) and the failure hooks, is not caused by one single message, so +writes made there get no ids automatically. A batch flush covers many messages, no matter which one happened to trigger +it. If you need ids in those places, read them from the `Message` inside the subscriber and set the headers yourself. +::: + +:::note +The `MessageContext` is a stack per process and is not fiber aware. If you process messages concurrently in fibers, for +example with Swoole or ReactPHP, the frames of the different fibers interleave. +::: + +## Learn more + +* [How to decorate messages](message-decorator.md) +* [How to create messages](message.md) +* [How to configure repositories](repository.md) +* [How to trace with OpenTelemetry](opentelemetry.md) +* [How to process events with subscriptions](subscription.md) diff --git a/docs/message-decorator.md b/docs/message-decorator.md index bac58e800..4cbcf63f7 100644 --- a/docs/message-decorator.md +++ b/docs/message-decorator.md @@ -19,6 +19,33 @@ use Patchlevel\EventSourcing\Repository\MessageDecorator\SplitStreamDecorator; $eventMetadataFactory = new AttributeEventMetadataFactory(); $decorator = new SplitStreamDecorator($eventMetadataFactory); ``` +### CorrelationCausationDecorator + +To track which event caused which other event, the `CorrelationCausationDecorator` adds +[correlation and causation ids](correlation-causation.md) to every recorded message. + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; +use Patchlevel\EventSourcing\Repository\MessageDecorator\CorrelationCausationDecorator; + +$messageContext = new MessageContext(); +$decorator = new CorrelationCausationDecorator($messageContext); +``` +:::note +The same `MessageContext` instance also needs to be passed to the subscription engine and the buses, so that the ids +can be propagated. You can find out more about [correlation and causation](correlation-causation.md). +::: + +### TraceDecorator + +To connect asynchronous processing back to the trace which recorded the event, the `TraceDecorator` stores the current +W3C trace context on the message. More about this on the [OpenTelemetry](opentelemetry.md) page. + +```php +use Patchlevel\EventSourcing\Telemetry\TraceDecorator; + +$decorator = new TraceDecorator(); +``` ### ChainMessageDecorator To use multiple decorators at the same time, you can use the `ChainMessageDecorator`. @@ -110,4 +137,6 @@ You can also set multiple headers with `withHeaders` which expects a list of hea * [How to create messages](message.md) * [How to define events](events.md) * [How to configure repositories](repository.md) +* [How to track correlation and causation](correlation-causation.md) +* [How to trace with OpenTelemetry](opentelemetry.md) * [How to upcast events](upcasting.md) diff --git a/docs/message.md b/docs/message.md index 7eb4a3dbf..779886e2d 100644 --- a/docs/message.md +++ b/docs/message.md @@ -54,6 +54,9 @@ The message object has some built-in headers which are used internally. * `PlayheadHeader` - The position of the message within its stream. * `RecordedOnHeader` - The date and time when the message was recorded. * `EventIdHeader` - The unique id of the event. +* `CorrelationIdHeader` - The id of the business transaction the message belongs to. +* `CausationIdHeader` - The id of the event which caused this message. +* `TraceHeader` - The W3C trace context of the trace in which the message was recorded. * `IndexHeader` - The global position of the message in the store. * `TagsHeader` - The tags attached to the message (experimental). * `ArchivedHeader` - Flag if the message is archived. @@ -474,6 +477,8 @@ $state = (new Reducer()) ## Learn more * [How to decorate messages](message-decorator.md) +* [How to track correlation and causation](correlation-causation.md) +* [How to trace with OpenTelemetry](opentelemetry.md) * [How to load aggregates](repository.md) * [How to store messages](store.md) * [How to use subscriptions](subscription.md) diff --git a/docs/opentelemetry.md b/docs/opentelemetry.md new file mode 100644 index 000000000..da8008130 --- /dev/null +++ b/docs/opentelemetry.md @@ -0,0 +1,183 @@ +# OpenTelemetry + +With [OpenTelemetry](https://opentelemetry.io/) you can follow a command through your whole system: which aggregate was +saved, which store query it triggered, which subscription processed the resulting event and which projection was +written. The library ships wrappers for all of its entry points which create spans, plus a header that carries the trace +context into asynchronous processing. + +## Installation + +The OpenTelemetry packages are optional. Install the api package to use the wrappers, and an sdk to actually export +spans. + +```bash +composer require open-telemetry/api +composer require open-telemetry/sdk +``` +:::note +Without a configured sdk the api falls back to a noop implementation. The wrappers are then still safe to wire, they +just don't record anything. +::: + +## Wrap the services + +Every wrapper takes the service it decorates and an optional `TracerProviderInterface`. Without one, the globally +configured provider is used. + +```php +use OpenTelemetry\API\Trace\TracerProviderInterface; +use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootRegistry; +use Patchlevel\EventSourcing\Repository\RepositoryManager; +use Patchlevel\EventSourcing\Store\Store; +use Patchlevel\EventSourcing\Telemetry\TraceableRepositoryManager; +use Patchlevel\EventSourcing\Telemetry\TraceableStore; + +/** + * @var RepositoryManager $repositoryManager + * @var AggregateRootRegistry $aggregateRootRegistry + * @var Store $store + * @var TracerProviderInterface $tracerProvider + */ +$repositoryManager = new TraceableRepositoryManager( + $repositoryManager, + $aggregateRootRegistry, + $tracerProvider, +); + +$store = new TraceableStore($store, $tracerProvider); +``` +These wrappers are available: + +* `TraceableRepositoryManager` and `TraceableRepository` for loading and saving aggregates. +* `TraceableStore` for store operations. +* `TraceableEventBus` and `TraceableConsumer` for the [event bus](event-bus.md). +* `TraceableCommandBus` and `TraceableQueryBus` for the [command bus](command-bus.md) and [query bus](query-bus.md). +* `TraceableSubscriptionEngine` for the engine commands like boot and run. + +:::warning +The `TraceableStore` implements `Store` and `AppendStore` only. Pass the concrete store to the schema director and to +the console commands, they need `DoctrineSchemaConfigurator`, `ProvideDbalConnection` and `SubscriptionStore`, which +the wrapper does not forward. Wrap the store only where it is injected into repositories and buses. +::: + +## Trace asynchronous processing + +A subscription processes an event long after it was recorded, often in a different process. To connect both, the trace +context of the recording is stored on the message with the `TraceDecorator`, a [message decorator](message-decorator.md). + +```php +use Patchlevel\EventSourcing\Message\Context\MessageContext; +use Patchlevel\EventSourcing\Repository\MessageDecorator\ChainMessageDecorator; +use Patchlevel\EventSourcing\Repository\MessageDecorator\CorrelationCausationDecorator; +use Patchlevel\EventSourcing\Telemetry\TraceDecorator; + +/** @var MessageContext $messageContext */ +$decorator = new ChainMessageDecorator([ + new CorrelationCausationDecorator($messageContext), + new TraceDecorator(), +]); +``` +:::tip +Combine it with [correlation and causation](correlation-causation.md) ids. The ids describe the business transaction, +the trace describes the technical execution. +::: + +On the reading side, the `TracingSubscriber` creates one span per message and subscription. Register it on the event +dispatcher of the [subscription engine](subscription.md). + +```php +use OpenTelemetry\API\Trace\TracerProviderInterface; +use Patchlevel\EventSourcing\Subscription\Engine\DefaultSubscriptionEngine; +use Patchlevel\EventSourcing\Subscription\Engine\MessageLoader; +use Patchlevel\EventSourcing\Subscription\Store\SubscriptionStore; +use Patchlevel\EventSourcing\Subscription\Subscriber\SubscriberAccessorRepository; +use Patchlevel\EventSourcing\Telemetry\TracingSubscriber; +use Symfony\Component\EventDispatcher\EventDispatcher; + +/** + * @var MessageLoader $messageLoader + * @var SubscriptionStore $subscriptionStore + * @var SubscriberAccessorRepository $subscriberRepository + * @var TracerProviderInterface $tracerProvider + */ +$eventDispatcher = new EventDispatcher(); +$eventDispatcher->addSubscriber(new TracingSubscriber($tracerProvider)); + +$engine = new DefaultSubscriptionEngine( + $messageLoader, + $subscriptionStore, + $subscriberRepository, + eventDispatcher: $eventDispatcher, +); +``` +:::note +The processing span does not become a child of the recording span, it references it as a span link. One event is +processed by many subscriptions at arbitrary points in time, so a parent child relation would be wrong. This follows the +OpenTelemetry messaging conventions. +::: + +## Flush spans in long running workers + +The subscription worker runs for hours. With a batching span processor the spans stay in memory until the process ends, +so nothing shows up in your backend, and everything is lost if the process is killed. The `ForceFlushListener` flushes +after every worker cycle. + +```php +use OpenTelemetry\API\Trace\TracerProviderInterface; +use Patchlevel\EventSourcing\Telemetry\ForceFlushListener; +use Patchlevel\Worker\Event\WorkerRunningEvent; +use Symfony\Component\EventDispatcher\EventDispatcher; + +/** @var TracerProviderInterface $tracerProvider */ +$workerEventDispatcher = new EventDispatcher(); +$workerEventDispatcher->addListener( + WorkerRunningEvent::class, + new ForceFlushListener($tracerProvider), +); +``` +:::danger +Without flushing you will see no traces at all from the subscription worker. This is the most common cause of missing +spans. +::: + +## Add the log output to your spans + +The library logs at all of its seams. The `SpanEventLogger` writes every log record as an event onto the active span, so +you also see what happened inside parts which have no dedicated span. + +```php +use Patchlevel\EventSourcing\Telemetry\SpanEventLogger; +use Psr\Log\LoggerInterface; + +/** @var LoggerInterface $logger */ +$logger = new SpanEventLogger($logger); +``` +## Span reference + +| Span | Kind | +|---|---| +| `event_sourcing.repository.load` / `.has` / `.save` | internal | +| `event_sourcing.store.load` / `.count` / `.streams` / `.remove` / `.archive` / `.transactional` | internal | +| `event_sourcing.store.save` | producer | +| `event_sourcing.event_bus.dispatch` | producer | +| `event_sourcing.event_bus.consume` | consumer | +| `event_sourcing.command_bus.dispatch` / `event_sourcing.query_bus.dispatch` | internal | +| `event_sourcing.subscription.run` (and the other engine commands) | internal | +| `event_sourcing.subscription.process` | consumer | + +Where the OpenTelemetry messaging conventions define an attribute, it is used: `messaging.message.id` is the event id, +`messaging.message.conversation_id` is the correlation id and `messaging.destination.name` is the stream name. +Everything else uses the `event_sourcing.` prefix, for example `event_sourcing.aggregate.name`, +`event_sourcing.causation_id` and `event_sourcing.subscription.id`. + +:::warning +Event payloads are never attached to spans, because they regularly contain personal data. If you add your own +attributes, keep [personal data](personal-data.md) out of them. +::: + +## Learn more + +* [How to track correlation and causation](correlation-causation.md) +* [How to decorate messages](message-decorator.md) +* [How to process events with subscriptions](subscription.md) +* [How to protect personal data](personal-data.md) diff --git a/docs/project.json b/docs/project.json index 1e3ff96d8..0384277ea 100644 --- a/docs/project.json +++ b/docs/project.json @@ -80,6 +80,14 @@ "title": "Message Decorator", "file": "message-decorator.md" }, + { + "title": "Correlation and Causation", + "file": "correlation-causation.md" + }, + { + "title": "OpenTelemetry", + "file": "opentelemetry.md" + }, { "title": "Split Stream", "file": "split-stream.md" diff --git a/src/CommandBus/SyncCommandBus.php b/src/CommandBus/SyncCommandBus.php index ca930c000..364c76e58 100644 --- a/src/CommandBus/SyncCommandBus.php +++ b/src/CommandBus/SyncCommandBus.php @@ -4,10 +4,12 @@ namespace Patchlevel\EventSourcing\CommandBus; +use Patchlevel\EventSourcing\Message\Context\MessageContext; use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootRegistry; use Patchlevel\EventSourcing\Repository\RepositoryManager; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; +use Ramsey\Uuid\Uuid; use function count; use function is_array; @@ -21,6 +23,7 @@ final class SyncCommandBus implements CommandBus public function __construct( iterable|HandlerProvider $handlerProviders, private readonly LoggerInterface|null $logger = null, + private readonly MessageContext|null $messageContext = null, ) { if (!$handlerProviders instanceof HandlerProvider) { $this->handlerProvider = new ChainHandlerProvider($handlerProviders); @@ -50,7 +53,18 @@ public function dispatch(object $command): void throw new MultipleHandlersFound($command::class); } - ($handlers[0]->callable())($command); + // seed the correlation id once per command, so that all messages + // recorded while handling this command share the same correlation id + $this->messageContext?->push( + $this->messageContext->causationId(), + $this->messageContext->correlationId() ?? Uuid::uuid7()->toString(), + ); + + try { + ($handlers[0]->callable())($command); + } finally { + $this->messageContext?->pop(); + } } public static function createForAggregateHandlers( @@ -58,6 +72,7 @@ public static function createForAggregateHandlers( RepositoryManager $repositoryManager, ContainerInterface|null $container = null, LoggerInterface|null $logger = null, + MessageContext|null $messageContext = null, ): self { return new self( new AggregateHandlerProvider( @@ -66,6 +81,7 @@ public static function createForAggregateHandlers( $container, ), $logger, + $messageContext, ); } } diff --git a/src/EventBus/DefaultConsumer.php b/src/EventBus/DefaultConsumer.php index 7ceff10c2..99489e32b 100644 --- a/src/EventBus/DefaultConsumer.php +++ b/src/EventBus/DefaultConsumer.php @@ -4,6 +4,7 @@ namespace Patchlevel\EventSourcing\EventBus; +use Patchlevel\EventSourcing\Message\Context\MessageContext; use Patchlevel\EventSourcing\Message\Message; use Psr\Log\LoggerInterface; @@ -14,6 +15,7 @@ final class DefaultConsumer implements Consumer public function __construct( private readonly ListenerProvider $listenerProvider, private readonly LoggerInterface|null $logger = null, + private readonly MessageContext|null $messageContext = null, ) { } @@ -28,20 +30,26 @@ public function consume(Message $message): void $listeners = $this->listenerProvider->listenersForEvent($eventClass); - foreach ($listeners as $listener) { - $this->logger?->info(sprintf( - 'EventBus: Listener "%s" consume message with event "%s".', - $listener->name(), - $eventClass, - )); + $this->messageContext?->pushMessage($message); - ($listener->callable())($message); + try { + foreach ($listeners as $listener) { + $this->logger?->info(sprintf( + 'EventBus: Listener "%s" consume message with event "%s".', + $listener->name(), + $eventClass, + )); + + ($listener->callable())($message); + } + } finally { + $this->messageContext?->pop(); } } /** @param iterable $listeners */ - public static function create(iterable $listeners = []): self + public static function create(iterable $listeners = [], MessageContext|null $messageContext = null): self { - return new self(new AttributeListenerProvider($listeners)); + return new self(new AttributeListenerProvider($listeners), null, $messageContext); } } diff --git a/src/Message/Context/MessageContext.php b/src/Message/Context/MessageContext.php new file mode 100644 index 000000000..1a2599285 --- /dev/null +++ b/src/Message/Context/MessageContext.php @@ -0,0 +1,86 @@ + */ + private array $stack = []; + + /** + * Push the ids of the given message onto the stack. + * + * A message without a correlation id, like one recorded before the ids were + * introduced, is the root of its own correlation: everything caused by it + * shares its event id as correlation id. Messages without any headers push + * an empty frame, so that every push is still balanced by exactly one pop. + */ + public function pushMessage(Message $message): void + { + $eventId = $message->hasHeader(EventIdHeader::class) ? $message->header(EventIdHeader::class)->eventId : null; + + $this->push( + $eventId, + $message->hasHeader(CorrelationIdHeader::class) + ? $message->header(CorrelationIdHeader::class)->correlationId + : $eventId, + ); + } + + public function push(string|null $causationId = null, string|null $correlationId = null): void + { + $this->stack[] = [ + 'causationId' => $causationId, + 'correlationId' => $correlationId, + ]; + } + + public function pop(): void + { + array_pop($this->stack); + } + + public function clear(): void + { + $this->stack = []; + } + + public function causationId(): string|null + { + return $this->current()['causationId']; + } + + public function correlationId(): string|null + { + return $this->current()['correlationId']; + } + + /** @return array{causationId: string|null, correlationId: string|null} */ + private function current(): array + { + $count = count($this->stack); + + if ($count === 0) { + return ['causationId' => null, 'correlationId' => null]; + } + + return $this->stack[$count - 1]; + } +} diff --git a/src/Metadata/Message/MessageHeaderRegistry.php b/src/Metadata/Message/MessageHeaderRegistry.php index 43ac22549..33ac795c7 100644 --- a/src/Metadata/Message/MessageHeaderRegistry.php +++ b/src/Metadata/Message/MessageHeaderRegistry.php @@ -5,12 +5,15 @@ namespace Patchlevel\EventSourcing\Metadata\Message; use Patchlevel\EventSourcing\Store\ArchivedHeader; +use Patchlevel\EventSourcing\Store\Header\CausationIdHeader; +use Patchlevel\EventSourcing\Store\Header\CorrelationIdHeader; use Patchlevel\EventSourcing\Store\Header\EventIdHeader; use Patchlevel\EventSourcing\Store\Header\IndexHeader; use Patchlevel\EventSourcing\Store\Header\PlayheadHeader; use Patchlevel\EventSourcing\Store\Header\RecordedOnHeader; use Patchlevel\EventSourcing\Store\Header\StreamNameHeader; use Patchlevel\EventSourcing\Store\Header\TagsHeader; +use Patchlevel\EventSourcing\Store\Header\TraceHeader; use Patchlevel\EventSourcing\Store\StreamStartHeader; use function array_flip; @@ -86,6 +89,9 @@ public static function createWithInternalHeaders(array $headerNameToClassMap = [ 'eventId' => EventIdHeader::class, 'index' => IndexHeader::class, 'tags' => TagsHeader::class, + 'correlationId' => CorrelationIdHeader::class, + 'causationId' => CausationIdHeader::class, + 'trace' => TraceHeader::class, ]; return new self($headerNameToClassMap + $internalHeaders); diff --git a/src/Repository/MessageDecorator/CorrelationCausationDecorator.php b/src/Repository/MessageDecorator/CorrelationCausationDecorator.php new file mode 100644 index 000000000..9e815b032 --- /dev/null +++ b/src/Repository/MessageDecorator/CorrelationCausationDecorator.php @@ -0,0 +1,48 @@ +hasHeader(EventIdHeader::class)) { + $message = $message->withHeader(new EventIdHeader(Uuid::uuid7()->toString())); + } + + $causationId = $this->messageContext->causationId(); + + if ($causationId !== null && !$message->hasHeader(CausationIdHeader::class)) { + $message = $message->withHeader(new CausationIdHeader($causationId)); + } + + if (!$message->hasHeader(CorrelationIdHeader::class)) { + $message = $message->withHeader(new CorrelationIdHeader( + $this->messageContext->correlationId() ?? $message->header(EventIdHeader::class)->eventId, + )); + } + + return $message; + } +} diff --git a/src/Store/Header/CausationIdHeader.php b/src/Store/Header/CausationIdHeader.php new file mode 100644 index 000000000..d18805873 --- /dev/null +++ b/src/Store/Header/CausationIdHeader.php @@ -0,0 +1,14 @@ +subscriptionManager = new SubscriptionManager($subscriptionStore, $this->logger); @@ -204,6 +207,12 @@ public function __construct( $this->eventDispatcher->addSubscriber(new FailSubscriber($failedMessageProcessor)); + if ($messageContext instanceof MessageContext) { + $this->eventDispatcher->addSubscriber( + new MessageContextSubscriber($messageContext), + ); + } + $this->eventDispatcher->addListener( OnCommand::class, new DetachListener( diff --git a/src/Subscription/Engine/Listener/MessageContextSubscriber.php b/src/Subscription/Engine/Listener/MessageContextSubscriber.php new file mode 100644 index 000000000..adaeab7c6 --- /dev/null +++ b/src/Subscription/Engine/Listener/MessageContextSubscriber.php @@ -0,0 +1,85 @@ +popIfPushed(); + } + + public function onHandleMessage(OnHandleMessage $event): void + { + $this->messageContext->pushMessage($event->message); + $this->pushed = true; + } + + public function onHandleMessageSuccess(OnHandleMessageSuccess $event): void + { + $this->popIfPushed(); + } + + public function onHandleMessageError(OnHandleMessageError $event): void + { + $this->popIfPushed(); + } + + /** + * A subscriber without a matching subscribe method is reported as success + * without a preceding OnHandleMessage, so we must not pop in that case. + * The same guard keeps a second terminal event from popping twice. + */ + private function popIfPushed(): void + { + if (!$this->pushed) { + return; + } + + $this->messageContext->pop(); + $this->pushed = false; + } + + /** @return array */ + public static function getSubscribedEvents(): array + { + // the frame is removed before any other listener reacts to the terminal event, + // so writes which are not attributable to this message, like a batch flush, + // do not inherit its ids + return [ + OnCommand::class => ['onCommand', 64], + OnHandleMessage::class => ['onHandleMessage', 64], + OnHandleMessageSuccess::class => ['onHandleMessageSuccess', 64], + OnHandleMessageError::class => ['onHandleMessageError', 64], + ]; + } +} diff --git a/src/Telemetry/ForceFlushListener.php b/src/Telemetry/ForceFlushListener.php new file mode 100644 index 000000000..427d8755c --- /dev/null +++ b/src/Telemetry/ForceFlushListener.php @@ -0,0 +1,38 @@ +tracerProvider ?? Globals::tracerProvider(); + + if (!$tracerProvider instanceof SdkTracerProviderInterface) { + return; + } + + $tracerProvider->forceFlush(); + } +} diff --git a/src/Telemetry/Instrumentation.php b/src/Telemetry/Instrumentation.php new file mode 100644 index 000000000..26627171c --- /dev/null +++ b/src/Telemetry/Instrumentation.php @@ -0,0 +1,78 @@ +tracer = ($tracerProvider ?? Globals::tracerProvider())->getTracer(self::SCOPE); + } + + /** + * @param non-empty-string $name + * @param Closure():T $function + * @param 0|1|2|3|4 $kind + * @param array $attributes + * + * @return T + * + * @template T + */ + public function span( + string $name, + Closure $function, + int $kind = SpanKind::KIND_INTERNAL, + array $attributes = [], + SpanContextInterface|null $link = null, + ): mixed { + $spanBuilder = $this->tracer + ->spanBuilder($name) + ->setSpanKind($kind) + ->setAttributes(array_filter($attributes, static fn (mixed $value) => $value !== null)); + + if ($link instanceof SpanContextInterface && $link->isValid()) { + $spanBuilder = $spanBuilder->addLink($link); + } + + $span = $spanBuilder->startSpan(); + $scope = $span->activate(); + + try { + return $function(); + } catch (Throwable $throwable) { + $span->recordException($throwable); + $span->setStatus(StatusCode::STATUS_ERROR, $throwable->getMessage()); + + throw $throwable; + } finally { + $scope->detach(); + $span->end(); + } + } +} diff --git a/src/Telemetry/MessageAttributes.php b/src/Telemetry/MessageAttributes.php new file mode 100644 index 000000000..457fb541d --- /dev/null +++ b/src/Telemetry/MessageAttributes.php @@ -0,0 +1,42 @@ + */ + public static function from(Message $message): array + { + return [ + TraceAttributes::EVENT_NAME => $message->event()::class, + TraceAttributes::MESSAGING_MESSAGE_ID => $message->hasHeader(EventIdHeader::class) + ? $message->header(EventIdHeader::class)->eventId + : null, + TraceAttributes::MESSAGING_MESSAGE_CONVERSATION_ID => $message->hasHeader(CorrelationIdHeader::class) + ? $message->header(CorrelationIdHeader::class)->correlationId + : null, + TraceAttributes::CAUSATION_ID => $message->hasHeader(CausationIdHeader::class) + ? $message->header(CausationIdHeader::class)->causationId + : null, + TraceAttributes::MESSAGING_DESTINATION_NAME => $message->hasHeader(StreamNameHeader::class) + ? $message->header(StreamNameHeader::class)->streamName + : null, + ]; + } +} diff --git a/src/Telemetry/SpanEventLogger.php b/src/Telemetry/SpanEventLogger.php new file mode 100644 index 000000000..d1006ab6d --- /dev/null +++ b/src/Telemetry/SpanEventLogger.php @@ -0,0 +1,43 @@ + $context */ + public function log(mixed $level, string|Stringable $message, array $context = []): void + { + $span = Span::getCurrent(); + + if ($span->isRecording()) { + $span->addEvent((string)$message, [ + 'log.level' => is_scalar($level) ? (string)$level : 'unknown', + ]); + } + + $this->logger?->log($level, $message, $context); + } +} diff --git a/src/Telemetry/StoreDoesNotSupport.php b/src/Telemetry/StoreDoesNotSupport.php new file mode 100644 index 000000000..6b0f1032b --- /dev/null +++ b/src/Telemetry/StoreDoesNotSupport.php @@ -0,0 +1,23 @@ +propagator = $propagator ?? TraceContextPropagator::getInstance(); + } + + public function __invoke(Message $message): Message + { + if ($message->hasHeader(TraceHeader::class)) { + return $message; + } + + $carrier = []; + $this->propagator->inject($carrier); + + if (!is_array($carrier)) { + return $message; + } + + $traceparent = $carrier[TraceContextPropagator::TRACEPARENT] ?? null; + + if (!is_string($traceparent)) { + return $message; + } + + $tracestate = $carrier[TraceContextPropagator::TRACESTATE] ?? null; + + return $message->withHeader( + new TraceHeader($traceparent, is_string($tracestate) ? $tracestate : null), + ); + } +} diff --git a/src/Telemetry/TraceableCommandBus.php b/src/Telemetry/TraceableCommandBus.php new file mode 100644 index 000000000..4ba54a54c --- /dev/null +++ b/src/Telemetry/TraceableCommandBus.php @@ -0,0 +1,31 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function dispatch(object $command): void + { + $this->instrumentation->span( + 'event_sourcing.command_bus.dispatch', + function () use ($command): void { + $this->commandBus->dispatch($command); + }, + attributes: [TraceAttributes::COMMAND_NAME => $command::class], + ); + } +} diff --git a/src/Telemetry/TraceableConsumer.php b/src/Telemetry/TraceableConsumer.php new file mode 100644 index 000000000..1aaae6ef2 --- /dev/null +++ b/src/Telemetry/TraceableConsumer.php @@ -0,0 +1,39 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function consume(Message $message): void + { + $this->instrumentation->span( + 'event_sourcing.event_bus.consume', + function () use ($message): void { + $this->consumer->consume($message); + }, + SpanKind::KIND_CONSUMER, + [ + TraceAttributes::MESSAGING_SYSTEM => TraceAttributes::SYSTEM, + TraceAttributes::MESSAGING_OPERATION_NAME => 'consume', + TraceAttributes::MESSAGING_OPERATION_TYPE => TraceAttributes::OPERATION_TYPE_PROCESS, + ...MessageAttributes::from($message), + ], + ); + } +} diff --git a/src/Telemetry/TraceableEventBus.php b/src/Telemetry/TraceableEventBus.php new file mode 100644 index 000000000..013bfe3cb --- /dev/null +++ b/src/Telemetry/TraceableEventBus.php @@ -0,0 +1,41 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function dispatch(Message ...$messages): void + { + $this->instrumentation->span( + 'event_sourcing.event_bus.dispatch', + function () use ($messages): void { + $this->eventBus->dispatch(...$messages); + }, + SpanKind::KIND_PRODUCER, + [ + TraceAttributes::MESSAGING_SYSTEM => TraceAttributes::SYSTEM, + TraceAttributes::MESSAGING_OPERATION_NAME => 'dispatch', + TraceAttributes::MESSAGING_OPERATION_TYPE => TraceAttributes::OPERATION_TYPE_SEND, + TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT => count($messages), + ], + ); + } +} diff --git a/src/Telemetry/TraceableQueryBus.php b/src/Telemetry/TraceableQueryBus.php new file mode 100644 index 000000000..b84f4c641 --- /dev/null +++ b/src/Telemetry/TraceableQueryBus.php @@ -0,0 +1,29 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function dispatch(object $query): mixed + { + return $this->instrumentation->span( + 'event_sourcing.query_bus.dispatch', + fn (): mixed => $this->queryBus->dispatch($query), + attributes: [TraceAttributes::QUERY_NAME => $query::class], + ); + } +} diff --git a/src/Telemetry/TraceableRepository.php b/src/Telemetry/TraceableRepository.php new file mode 100644 index 000000000..21698c1e2 --- /dev/null +++ b/src/Telemetry/TraceableRepository.php @@ -0,0 +1,68 @@ + + */ +final class TraceableRepository implements Repository +{ + private readonly Instrumentation $instrumentation; + + /** @param Repository $repository */ + public function __construct( + private readonly Repository $repository, + private readonly string $aggregateName, + TracerProviderInterface|null $tracerProvider = null, + ) { + $this->instrumentation = new Instrumentation($tracerProvider); + } + + /** @return T */ + public function load(Identifier $id): AggregateRoot + { + return $this->instrumentation->span( + 'event_sourcing.repository.load', + fn (): AggregateRoot => $this->repository->load($id), + attributes: [ + TraceAttributes::AGGREGATE_NAME => $this->aggregateName, + TraceAttributes::AGGREGATE_ID => $id->toString(), + ], + ); + } + + public function has(Identifier $id): bool + { + return $this->instrumentation->span( + 'event_sourcing.repository.has', + fn (): bool => $this->repository->has($id), + attributes: [ + TraceAttributes::AGGREGATE_NAME => $this->aggregateName, + TraceAttributes::AGGREGATE_ID => $id->toString(), + ], + ); + } + + /** @param T $aggregate */ + public function save(AggregateRoot $aggregate): void + { + $this->instrumentation->span( + 'event_sourcing.repository.save', + function () use ($aggregate): void { + $this->repository->save($aggregate); + }, + attributes: [ + TraceAttributes::AGGREGATE_NAME => $this->aggregateName, + TraceAttributes::AGGREGATE_ID => $aggregate->aggregateRootId()->toString(), + ], + ); + } +} diff --git a/src/Telemetry/TraceableRepositoryManager.php b/src/Telemetry/TraceableRepositoryManager.php new file mode 100644 index 000000000..3986fe71e --- /dev/null +++ b/src/Telemetry/TraceableRepositoryManager.php @@ -0,0 +1,49 @@ +, Repository> */ + private array $instances = []; + + public function __construct( + private readonly RepositoryManager $repositoryManager, + private readonly AggregateRootRegistry $aggregateRootRegistry, + private readonly TracerProviderInterface|null $tracerProvider = null, + ) { + } + + /** + * @param class-string $aggregateClass + * + * @return Repository + * + * @template T of AggregateRoot + */ + public function get(string $aggregateClass): Repository + { + if (array_key_exists($aggregateClass, $this->instances)) { + /** @var Repository $repository */ + $repository = $this->instances[$aggregateClass]; + + return $repository; + } + + return $this->instances[$aggregateClass] = new TraceableRepository( + $this->repositoryManager->get($aggregateClass), + $this->aggregateRootRegistry->aggregateName($aggregateClass), + $this->tracerProvider, + ); + } +} diff --git a/src/Telemetry/TraceableStore.php b/src/Telemetry/TraceableStore.php new file mode 100644 index 000000000..f4fb22fb4 --- /dev/null +++ b/src/Telemetry/TraceableStore.php @@ -0,0 +1,172 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function load( + Criteria|null $criteria = null, + int|null $limit = null, + int|null $offset = null, + bool $backwards = false, + ): Stream { + return $this->instrumentation->span( + 'event_sourcing.store.load', + fn (): Stream => $this->store->load($criteria, $limit, $offset, $backwards), + ); + } + + public function count(Criteria|null $criteria = null): int + { + return $this->instrumentation->span( + 'event_sourcing.store.count', + fn (): int => $this->store->count($criteria), + ); + } + + public function save(Message ...$messages): void + { + $this->instrumentation->span( + 'event_sourcing.store.save', + function () use ($messages): void { + $this->store->save(...$messages); + }, + SpanKind::KIND_PRODUCER, + [ + TraceAttributes::MESSAGING_SYSTEM => TraceAttributes::SYSTEM, + TraceAttributes::MESSAGING_OPERATION_NAME => 'save', + TraceAttributes::MESSAGING_OPERATION_TYPE => TraceAttributes::OPERATION_TYPE_SEND, + TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT => count($messages), + ], + ); + } + + /** + * @param Closure():ClosureReturn $function + * + * @template ClosureReturn + */ + public function transactional(Closure $function): void + { + $this->instrumentation->span( + 'event_sourcing.store.transactional', + function () use ($function): void { + $this->store->transactional($function); + }, + ); + } + + /** @return list */ + public function streams(): array + { + return $this->instrumentation->span( + 'event_sourcing.store.streams', + fn (): array => $this->store->streams(), + ); + } + + public function remove(Criteria|null $criteria = null): void + { + $this->instrumentation->span( + 'event_sourcing.store.remove', + function () use ($criteria): void { + $this->store->remove($criteria); + }, + ); + } + + public function archive(Criteria|null $criteria = null): void + { + $this->instrumentation->span( + 'event_sourcing.store.archive', + function () use ($criteria): void { + $this->store->archive($criteria); + }, + ); + } + + /** @param iterable $messages */ + public function append(iterable $messages, AppendCondition|null $appendCondition = null): void + { + $store = $this->appendStore(); + + // the messages are counted for the span attribute, so a generator has to be materialized + $messages = is_array($messages) ? $messages : iterator_to_array($messages, false); + + $this->instrumentation->span( + 'event_sourcing.store.append', + static function () use ($store, $messages, $appendCondition): void { + $store->append($messages, $appendCondition); + }, + SpanKind::KIND_PRODUCER, + [ + TraceAttributes::MESSAGING_SYSTEM => TraceAttributes::SYSTEM, + TraceAttributes::MESSAGING_OPERATION_NAME => 'append', + TraceAttributes::MESSAGING_OPERATION_TYPE => TraceAttributes::OPERATION_TYPE_SEND, + TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT => count($messages), + ], + ); + } + + /** @param positive-int|0 $from */ + public function query(Query $query, int $from = 0): Stream + { + $store = $this->appendStore(); + + return $this->instrumentation->span( + 'event_sourcing.store.query', + static fn (): Stream => $store->query($query, $from), + ); + } + + /** @return positive-int|0 */ + public function head(): int + { + $store = $this->appendStore(); + + return $this->instrumentation->span( + 'event_sourcing.store.head', + static fn (): int => $store->head(), + ); + } + + private function appendStore(): AppendStore + { + if (!$this->store instanceof AppendStore) { + throw StoreDoesNotSupport::interface($this->store, AppendStore::class); + } + + return $this->store; + } +} diff --git a/src/Telemetry/TraceableSubscriptionEngine.php b/src/Telemetry/TraceableSubscriptionEngine.php new file mode 100644 index 000000000..bb345545a --- /dev/null +++ b/src/Telemetry/TraceableSubscriptionEngine.php @@ -0,0 +1,86 @@ +instrumentation = new Instrumentation($tracerProvider); + } + + public function execute(Command $command): Result + { + return $this->instrumentation->span( + 'event_sourcing.subscription.' . self::commandName($command), + function () use ($command): Result { + $result = $this->subscriptionEngine->execute($command); + + $span = Span::getCurrent(); + $span->setAttribute(TraceAttributes::ERROR_COUNT, count($result->errors)); + + if ($result instanceof ProcessedResult) { + $span->setAttribute( + TraceAttributes::SUBSCRIPTION_PROCESSED_MESSAGES, + $result->processedMessages, + ); + $span->setAttribute(TraceAttributes::SUBSCRIPTION_FINISHED, $result->finished); + } + + return $result; + }, + attributes: [ + TraceAttributes::SUBSCRIPTION_ID => $command->ids === null ? null : implode(',', $command->ids), + TraceAttributes::SUBSCRIPTION_GROUP => $command->groups === null + ? null + : implode(',', $command->groups), + ], + ); + } + + /** @return list */ + public function subscriptions(SubscriptionEngineCriteria|null $criteria = null): array + { + return $this->instrumentation->span( + 'event_sourcing.subscription.subscriptions', + fn (): array => $this->subscriptionEngine->subscriptions($criteria), + ); + } + + public function stats(SubscriptionEngineCriteria|null $criteria = null): SubscriptionStats + { + return $this->instrumentation->span( + 'event_sourcing.subscription.stats', + fn (): SubscriptionStats => $this->subscriptionEngine->stats($criteria), + ); + } + + private static function commandName(Command $command): string + { + $shortName = strrchr($command::class, '\\'); + + return strtolower($shortName === false ? $command::class : substr($shortName, 1)); + } +} diff --git a/src/Telemetry/TracingSubscriber.php b/src/Telemetry/TracingSubscriber.php new file mode 100644 index 000000000..59ece63d6 --- /dev/null +++ b/src/Telemetry/TracingSubscriber.php @@ -0,0 +1,144 @@ +tracer = ($tracerProvider ?? Globals::tracerProvider())->getTracer(Instrumentation::SCOPE); + $this->propagator = $propagator ?? TraceContextPropagator::getInstance(); + } + + public function onCommand(OnCommand $event): void + { + // a span may have leaked if a listener threw before the message was finished + $this->closeSpan(); + } + + public function onHandleMessage(OnHandleMessage $event): void + { + $this->closeSpan(); + + $spanBuilder = $this->tracer + ->spanBuilder(self::SPAN_NAME) + ->setSpanKind(SpanKind::KIND_CONSUMER) + ->setAttributes(array_filter( + [ + TraceAttributes::MESSAGING_SYSTEM => TraceAttributes::SYSTEM, + TraceAttributes::MESSAGING_OPERATION_NAME => 'process', + TraceAttributes::MESSAGING_OPERATION_TYPE => TraceAttributes::OPERATION_TYPE_PROCESS, + TraceAttributes::SUBSCRIPTION_ID => $event->subscription->id(), + TraceAttributes::SUBSCRIPTION_GROUP => $event->subscription->group(), + ...MessageAttributes::from($event->message), + ], + static fn (mixed $value) => $value !== null, + )); + + $link = $this->linkFor($event->message); + + if ($link instanceof SpanContextInterface && $link->isValid()) { + $spanBuilder = $spanBuilder->addLink($link); + } + + $this->span = $spanBuilder->startSpan(); + $this->scope = $this->span->activate(); + } + + public function onHandleMessageSuccess(OnHandleMessageSuccess $event): void + { + $this->span?->setStatus(StatusCode::STATUS_OK); + $this->closeSpan(); + } + + public function onHandleMessageError(OnHandleMessageError $event): void + { + $this->span?->recordException($event->throwable); + $this->span?->setStatus(StatusCode::STATUS_ERROR, $event->throwable->getMessage()); + $this->closeSpan(); + } + + private function linkFor(Message $message): SpanContextInterface|null + { + if (!$message->hasHeader(TraceHeader::class)) { + return null; + } + + $header = $message->header(TraceHeader::class); + + $carrier = [TraceContextPropagator::TRACEPARENT => $header->traceparent]; + + if ($header->tracestate !== null) { + $carrier[TraceContextPropagator::TRACESTATE] = $header->tracestate; + } + + // extract against the root context: the propagator falls back to the given context + // for an invalid traceparent, and the current context would then link the span to + // its own parent + return Span::fromContext($this->propagator->extract($carrier, null, Context::getRoot()))->getContext(); + } + + private function closeSpan(): void + { + $this->scope?->detach(); + $this->span?->end(); + + $this->scope = null; + $this->span = null; + } + + /** @return array */ + public static function getSubscribedEvents(): array + { + // the span is closed after every other listener reacted to the terminal event, so + // that work they do is measured and a listener which fails marks the span as + // failed. MessageProcessor guarantees a terminal event, so the span cannot leak. + return [ + OnCommand::class => ['onCommand', 32], + OnHandleMessage::class => ['onHandleMessage', 32], + OnHandleMessageSuccess::class => ['onHandleMessageSuccess', -256], + OnHandleMessageError::class => ['onHandleMessageError', -256], + ]; + } +} diff --git a/tests/Architecture/LayerDependenciesTest.php b/tests/Architecture/LayerDependenciesTest.php index 2e4e559a5..4f9580a26 100644 --- a/tests/Architecture/LayerDependenciesTest.php +++ b/tests/Architecture/LayerDependenciesTest.php @@ -48,6 +48,7 @@ public function testCommandBusCanOnlyDependOnAllowedLayers(): Rule [ $this->layer('Aggregate'), $this->layer('Attribute'), + $this->layer('Message'), $this->layer('Metadata\AggregateRoot'), $this->layer('Repository'), $this->layer('Identifier'), @@ -244,6 +245,25 @@ public function testSubscriptionCanOnlyDependOnAllowedLayers(): Rule ); } + public function testTelemetryCanOnlyDependOnAllowedLayers(): Rule + { + return $this->layerCanOnlyDependOnAllowedLayers( + $this->layer('Telemetry'), + [ + $this->layer('Aggregate'), + $this->layer('CommandBus'), + $this->layer('EventBus'), + $this->layer('Identifier'), + $this->layer('Message'), + $this->layer('Metadata\AggregateRoot'), + $this->layer('QueryBus'), + $this->layer('Repository'), + $this->layer('Store'), + $this->layer('Subscription'), + ], + ); + } + public function testTestCanOnlyDependOnAllowedLayers(): Rule { return $this->layerCanOnlyDependOnAllowedLayers($this->layer('Test')); diff --git a/tests/Integration/CorrelationCausation/CorrelationCausationIntegrationTest.php b/tests/Integration/CorrelationCausation/CorrelationCausationIntegrationTest.php new file mode 100644 index 000000000..82b9b764a --- /dev/null +++ b/tests/Integration/CorrelationCausation/CorrelationCausationIntegrationTest.php @@ -0,0 +1,133 @@ +connection = DbalManager::createConnection(); + } + + public function tearDown(): void + { + $this->connection->close(); + } + + public function testCausationChainWithStreamStore(): void + { + $this->assertCausationChain( + new StreamDoctrineDbalStore( + $this->connection, + DefaultEventSerializer::createFromPaths([__DIR__ . '/Events']), + DefaultHeadersSerializer::createFromPaths([__DIR__ . '/Events']), + ), + ); + } + + public function testCausationChainWithTaggableStore(): void + { + $this->assertCausationChain( + new TaggableDoctrineDbalStore( + $this->connection, + DefaultEventSerializer::createFromPaths([__DIR__ . '/Events']), + (new AttributeEventRegistryFactory())->create([__DIR__ . '/Events']), + DefaultHeadersSerializer::createFromPaths([__DIR__ . '/Events']), + ), + ); + } + + private function assertCausationChain(Store&DoctrineSchemaConfigurator $store): void + { + $messageContext = new MessageContext(); + + $engine = new DefaultSubscriptionEngine( + new StoreMessageLoader($store), + new InMemorySubscriptionStore(), + new MetadataSubscriberAccessorRepository([ + new CreateInvoiceProcessor($this->createRepositoryManager($store, $messageContext)), + ]), + messageContext: $messageContext, + ); + + $manager = new RunSubscriptionEngineRepositoryManager( + $this->createRepositoryManager($store, $messageContext), + $engine, + ); + + (new DoctrineSchemaDirector($this->connection, $store))->create(); + $engine->execute(new Setup(skipBooting: true)); + + $manager->get(Order::class)->save( + Order::place(OrderId::generate(), 'coffee'), + ); + + [$orderPlaced, $invoiceCreated] = $store->load()->toList(); + + self::assertInstanceOf(OrderPlaced::class, $orderPlaced->event()); + self::assertInstanceOf(InvoiceCreated::class, $invoiceCreated->event()); + + // the order is the root of the transaction: it correlates to itself and has no cause + $orderEventId = $orderPlaced->header(EventIdHeader::class)->eventId; + + self::assertFalse($orderPlaced->hasHeader(CausationIdHeader::class)); + self::assertSame($orderEventId, $orderPlaced->header(CorrelationIdHeader::class)->correlationId); + + // the invoice was recorded while the processor handled the order event + self::assertSame($orderEventId, $invoiceCreated->header(CausationIdHeader::class)->causationId); + self::assertSame($orderEventId, $invoiceCreated->header(CorrelationIdHeader::class)->correlationId); + + // the context is balanced again after the engine run + self::assertNull($messageContext->causationId()); + self::assertNull($messageContext->correlationId()); + } + + private function createRepositoryManager(Store $store, MessageContext $messageContext): RepositoryManager + { + return new DefaultRepositoryManager( + new AggregateRootRegistry([ + 'order' => Order::class, + 'invoice' => Invoice::class, + ]), + $store, + null, + null, + new CorrelationCausationDecorator($messageContext), + ); + } +} diff --git a/tests/Integration/CorrelationCausation/Events/InvoiceCreated.php b/tests/Integration/CorrelationCausation/Events/InvoiceCreated.php new file mode 100644 index 000000000..841a1024d --- /dev/null +++ b/tests/Integration/CorrelationCausation/Events/InvoiceCreated.php @@ -0,0 +1,18 @@ +recordThat(new InvoiceCreated($id, $product)); + + return $self; + } + + #[Apply(InvoiceCreated::class)] + protected function applyInvoiceCreated(InvoiceCreated $event): void + { + $this->id = $event->invoiceId; + $this->product = $event->product; + } + + public function invoiceId(): InvoiceId + { + return $this->id; + } + + public function product(): string + { + return $this->product; + } +} diff --git a/tests/Integration/CorrelationCausation/InvoiceId.php b/tests/Integration/CorrelationCausation/InvoiceId.php new file mode 100644 index 000000000..e022486cd --- /dev/null +++ b/tests/Integration/CorrelationCausation/InvoiceId.php @@ -0,0 +1,13 @@ +recordThat(new OrderPlaced($id, $product)); + + return $self; + } + + #[Apply(OrderPlaced::class)] + protected function applyOrderPlaced(OrderPlaced $event): void + { + $this->id = $event->orderId; + $this->product = $event->product; + } + + public function orderId(): OrderId + { + return $this->id; + } + + public function product(): string + { + return $this->product; + } +} diff --git a/tests/Integration/CorrelationCausation/OrderId.php b/tests/Integration/CorrelationCausation/OrderId.php new file mode 100644 index 000000000..8f515d52c --- /dev/null +++ b/tests/Integration/CorrelationCausation/OrderId.php @@ -0,0 +1,13 @@ +product); + + $this->repositoryManager->get(Invoice::class)->save($invoice); + } +} diff --git a/tests/Integration/Telemetry/Events/InvoiceCreated.php b/tests/Integration/Telemetry/Events/InvoiceCreated.php new file mode 100644 index 000000000..1cb2e6252 --- /dev/null +++ b/tests/Integration/Telemetry/Events/InvoiceCreated.php @@ -0,0 +1,18 @@ +recordThat(new InvoiceCreated($id, $product)); + + return $self; + } + + #[Apply(InvoiceCreated::class)] + protected function applyInvoiceCreated(InvoiceCreated $event): void + { + $this->id = $event->invoiceId; + $this->product = $event->product; + } + + public function invoiceId(): InvoiceId + { + return $this->id; + } + + public function product(): string + { + return $this->product; + } +} diff --git a/tests/Integration/Telemetry/InvoiceId.php b/tests/Integration/Telemetry/InvoiceId.php new file mode 100644 index 000000000..41762f7fc --- /dev/null +++ b/tests/Integration/Telemetry/InvoiceId.php @@ -0,0 +1,13 @@ +recordThat(new OrderPlaced($id, $product)); + + return $self; + } + + #[Apply(OrderPlaced::class)] + protected function applyOrderPlaced(OrderPlaced $event): void + { + $this->id = $event->orderId; + $this->product = $event->product; + } + + public function orderId(): OrderId + { + return $this->id; + } + + public function product(): string + { + return $this->product; + } +} diff --git a/tests/Integration/Telemetry/OrderId.php b/tests/Integration/Telemetry/OrderId.php new file mode 100644 index 000000000..77b87dba7 --- /dev/null +++ b/tests/Integration/Telemetry/OrderId.php @@ -0,0 +1,13 @@ +product); + + $this->repositoryManager->get(Invoice::class)->save($invoice); + } +} diff --git a/tests/Integration/Telemetry/TelemetryIntegrationTest.php b/tests/Integration/Telemetry/TelemetryIntegrationTest.php new file mode 100644 index 000000000..5c49d3d6d --- /dev/null +++ b/tests/Integration/Telemetry/TelemetryIntegrationTest.php @@ -0,0 +1,182 @@ + */ + private ArrayObject $spanStorage; + + private TracerProvider $tracerProvider; + + public function setUp(): void + { + $this->connection = DbalManager::createConnection(); + + /** @var ArrayObject $storage */ + $storage = new ArrayObject(); + + $this->spanStorage = $storage; + $this->tracerProvider = new TracerProvider( + new SimpleSpanProcessor(new InMemoryExporter($storage)), + ); + } + + public function tearDown(): void + { + $this->connection->close(); + } + + public function testTraceIsLinkedAcrossTheSubscriptionEngine(): void + { + $store = new StreamDoctrineDbalStore( + $this->connection, + DefaultEventSerializer::createFromPaths([__DIR__ . '/Events']), + DefaultHeadersSerializer::createFromPaths([__DIR__ . '/Events']), + ); + + $messageContext = new MessageContext(); + + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addSubscriber(new TracingSubscriber($this->tracerProvider)); + + $engine = new DefaultSubscriptionEngine( + new StoreMessageLoader($store), + new InMemorySubscriptionStore(), + new MetadataSubscriberAccessorRepository([ + new CreateInvoiceProcessor($this->repositoryManager($store, $messageContext)), + ]), + eventDispatcher: $eventDispatcher, + messageContext: $messageContext, + ); + + $manager = new RunSubscriptionEngineRepositoryManager( + $this->repositoryManager($store, $messageContext), + $engine, + ); + + (new DoctrineSchemaDirector($this->connection, $store))->create(); + $engine->execute(new Setup(skipBooting: true)); + + // the order is placed inside an application span, which becomes the producing trace + $instrumentation = new Instrumentation($this->tracerProvider); + + $instrumentation->span( + 'app.place_order', + static function () use ($manager): void { + $manager->get(Order::class)->save( + Order::place(OrderId::generate(), 'coffee'), + ); + }, + ); + + [$orderPlaced, $invoiceCreated] = $store->load()->toList(); + + // both messages carry the trace they were recorded in + self::assertTrue($orderPlaced->hasHeader(TraceHeader::class)); + self::assertTrue($invoiceCreated->hasHeader(TraceHeader::class)); + + $applicationSpan = $this->spanByName('app.place_order'); + $processSpan = $this->spanByName(TracingSubscriber::SPAN_NAME); + + self::assertSame(SpanKind::KIND_CONSUMER, $processSpan->getKind()); + self::assertSame( + 'telemetry_create_invoice', + $processSpan->getAttributes()->get(TraceAttributes::SUBSCRIPTION_ID), + ); + + // the processing span links back to the trace which recorded the order + $links = $processSpan->getLinks(); + + self::assertCount(1, $links); + self::assertSame( + $applicationSpan->getContext()->getTraceId(), + $links[0]->getSpanContext()->getTraceId(), + ); + + // the invoice was recorded inside the processing span, so its trace context points there + self::assertTrue(str_contains( + $invoiceCreated->header(TraceHeader::class)->traceparent, + $processSpan->getContext()->getTraceId(), + )); + } + + private function repositoryManager(Store $store, MessageContext $messageContext): RepositoryManager + { + $aggregateRootRegistry = new AggregateRootRegistry([ + 'telemetry_order' => Order::class, + 'telemetry_invoice' => Invoice::class, + ]); + + return new TraceableRepositoryManager( + new DefaultRepositoryManager( + $aggregateRootRegistry, + $store, + null, + null, + new ChainMessageDecorator([ + new CorrelationCausationDecorator($messageContext), + new TraceDecorator(), + ]), + ), + $aggregateRootRegistry, + $this->tracerProvider, + ); + } + + private function spanByName(string $name): ImmutableSpan + { + foreach (array_values(iterator_to_array($this->spanStorage)) as $span) { + if ($span->getName() === $name) { + return $span; + } + } + + self::fail('span not found: ' . $name); + } +} diff --git a/tests/Unit/CommandBus/SyncCommandBusTest.php b/tests/Unit/CommandBus/SyncCommandBusTest.php index cad8ce42f..3e68356cd 100644 --- a/tests/Unit/CommandBus/SyncCommandBusTest.php +++ b/tests/Unit/CommandBus/SyncCommandBusTest.php @@ -9,12 +9,16 @@ use Patchlevel\EventSourcing\CommandBus\HandlerProvider; use Patchlevel\EventSourcing\CommandBus\MultipleHandlersFound; use Patchlevel\EventSourcing\CommandBus\SyncCommandBus; +use Patchlevel\EventSourcing\Identifier\FakeRamseyUuidFactory; +use Patchlevel\EventSourcing\Message\Context\MessageContext; use Patchlevel\EventSourcing\Metadata\AggregateRoot\AggregateRootRegistry; use Patchlevel\EventSourcing\Repository\RepositoryManager; use Patchlevel\EventSourcing\Tests\Unit\Fixture\CreateProfile; use Patchlevel\EventSourcing\Tests\Unit\Fixture\ProfileId; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +use Ramsey\Uuid\Uuid as RamseyUuid; +use RuntimeException; #[CoversClass(SyncCommandBus::class)] final class SyncCommandBusTest extends TestCase @@ -148,7 +152,118 @@ public function testCreateForAggregateHandlers(): void ); $this->expectException(HandlerNotFound::class); - $commandBus->dispatch(new CreateProfile(ProfileId::fromString('1'), 'foo')); } + + public function testSeedsCorrelationIdForDispatch(): void + { + $previousUuidFactory = RamseyUuid::getFactory(); + RamseyUuid::setFactory(new FakeRamseyUuidFactory()); + + try { + $command = new class { + }; + + $context = new MessageContext(); + + $handler = new class ($context) { + public string|null $causationId = null; + public string|null $correlationId = null; + + public function __construct(private readonly MessageContext $context) + { + } + + public function __invoke(object $command): void + { + $this->causationId = $this->context->causationId(); + $this->correlationId = $this->context->correlationId(); + } + }; + + $handlerProvider = $this->createMock(HandlerProvider::class); + $handlerProvider + ->expects($this->once()) + ->method('handlerForCommand') + ->with($command::class) + ->willReturn([new HandlerDescriptor($handler)]); + + $commandBus = new SyncCommandBus($handlerProvider, null, $context); + $commandBus->dispatch($command); + + self::assertNull($handler->causationId); + self::assertSame('10000000-7000-0000-0000-000000000001', $handler->correlationId); + self::assertNull($context->correlationId()); + } finally { + RamseyUuid::setFactory($previousUuidFactory); + } + } + + public function testInheritsIdsFromOuterContext(): void + { + $command = new class { + }; + + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + + $handler = new class ($context) { + public string|null $causationId = null; + public string|null $correlationId = null; + + public function __construct(private readonly MessageContext $context) + { + } + + public function __invoke(object $command): void + { + $this->causationId = $this->context->causationId(); + $this->correlationId = $this->context->correlationId(); + } + }; + + $handlerProvider = $this->createMock(HandlerProvider::class); + $handlerProvider + ->expects($this->once()) + ->method('handlerForCommand') + ->with($command::class) + ->willReturn([new HandlerDescriptor($handler)]); + + $commandBus = new SyncCommandBus($handlerProvider, null, $context); + $commandBus->dispatch($command); + + self::assertSame('causation-1', $handler->causationId); + self::assertSame('correlation-1', $handler->correlationId); + self::assertSame('correlation-1', $context->correlationId()); + } + + public function testPopsContextOnException(): void + { + $command = new class { + }; + + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + + $handlerProvider = $this->createMock(HandlerProvider::class); + $handlerProvider + ->expects($this->once()) + ->method('handlerForCommand') + ->with($command::class) + ->willReturn([ + new HandlerDescriptor( + static fn (object $command) => throw new RuntimeException('ERROR'), + ), + ]); + + $commandBus = new SyncCommandBus($handlerProvider, null, $context); + + try { + $commandBus->dispatch($command); + } catch (RuntimeException) { + // expected + } + + self::assertSame('correlation-1', $context->correlationId()); + } } diff --git a/tests/Unit/EventBus/DefaultConsumerTest.php b/tests/Unit/EventBus/DefaultConsumerTest.php index 563bae602..f754447c2 100644 --- a/tests/Unit/EventBus/DefaultConsumerTest.php +++ b/tests/Unit/EventBus/DefaultConsumerTest.php @@ -8,12 +8,16 @@ use Patchlevel\EventSourcing\EventBus\DefaultConsumer; use Patchlevel\EventSourcing\EventBus\ListenerDescriptor; use Patchlevel\EventSourcing\EventBus\ListenerProvider; +use Patchlevel\EventSourcing\Message\Context\MessageContext; use Patchlevel\EventSourcing\Message\Message; +use Patchlevel\EventSourcing\Store\Header\CorrelationIdHeader; +use Patchlevel\EventSourcing\Store\Header\EventIdHeader; use Patchlevel\EventSourcing\Tests\Unit\Fixture\Email; use Patchlevel\EventSourcing\Tests\Unit\Fixture\ProfileCreated; use Patchlevel\EventSourcing\Tests\Unit\Fixture\ProfileId; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +use RuntimeException; #[CoversClass(DefaultConsumer::class)] final class DefaultConsumerTest extends TestCase @@ -73,4 +77,81 @@ public function __invoke(Message $message): void self::assertSame($message, $listener->message); } + + public function testPushMessageContextWhileConsuming(): void + { + $context = new MessageContext(); + + $listener = new class ($context) { + public string|null $causationId = null; + public string|null $correlationId = null; + + public function __construct(private readonly MessageContext $context) + { + } + + public function __invoke(Message $message): void + { + $this->causationId = $this->context->causationId(); + $this->correlationId = $this->context->correlationId(); + } + }; + + $message = Message::create( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + ), + ) + ->withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')); + + $provider = $this->createMock(ListenerProvider::class); + $provider + ->expects($this->once()) + ->method('listenersForEvent') + ->with(ProfileCreated::class) + ->willReturn([new ListenerDescriptor($listener->__invoke(...))]); + + $consumer = new DefaultConsumer($provider, null, $context); + $consumer->consume($message); + + self::assertSame('event-1', $listener->causationId); + self::assertSame('correlation-1', $listener->correlationId); + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testPopMessageContextOnException(): void + { + $context = new MessageContext(); + + $message = Message::create( + new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + ), + )->withHeader(new EventIdHeader('event-1')); + + $provider = $this->createMock(ListenerProvider::class); + $provider + ->expects($this->once()) + ->method('listenersForEvent') + ->with(ProfileCreated::class) + ->willReturn([ + new ListenerDescriptor( + static fn (Message $message) => throw new RuntimeException('ERROR'), + ), + ]); + + $consumer = new DefaultConsumer($provider, null, $context); + + try { + $consumer->consume($message); + } catch (RuntimeException) { + // expected + } + + self::assertNull($context->causationId()); + } } diff --git a/tests/Unit/Message/Context/MessageContextTest.php b/tests/Unit/Message/Context/MessageContextTest.php new file mode 100644 index 000000000..60f7fcd55 --- /dev/null +++ b/tests/Unit/Message/Context/MessageContextTest.php @@ -0,0 +1,125 @@ +causationId()); + self::assertNull($context->correlationId()); + } + + public function testPush(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + + self::assertSame('causation-1', $context->causationId()); + self::assertSame('correlation-1', $context->correlationId()); + } + + public function testNestedPushAndPop(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + $context->push('causation-2', 'correlation-2'); + + self::assertSame('causation-2', $context->causationId()); + self::assertSame('correlation-2', $context->correlationId()); + + $context->pop(); + + self::assertSame('causation-1', $context->causationId()); + self::assertSame('correlation-1', $context->correlationId()); + + $context->pop(); + + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testPopOnEmptyContext(): void + { + $context = new MessageContext(); + $context->pop(); + + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testClear(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + $context->push('causation-2', 'correlation-2'); + + $context->clear(); + + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testPushMessage(): void + { + $message = Message::create($this->event()) + ->withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')); + + $context = new MessageContext(); + $context->pushMessage($message); + + self::assertSame('event-1', $context->causationId()); + self::assertSame('correlation-1', $context->correlationId()); + } + + public function testPushMessageWithoutCorrelationIdIsRootOfCorrelation(): void + { + $message = Message::create($this->event()) + ->withHeader(new EventIdHeader('event-1')); + + $context = new MessageContext(); + $context->pushMessage($message); + + self::assertSame('event-1', $context->causationId()); + self::assertSame('event-1', $context->correlationId()); + } + + public function testPushMessageWithoutHeaders(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + $context->pushMessage(Message::create($this->event())); + + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + + $context->pop(); + + self::assertSame('causation-1', $context->causationId()); + self::assertSame('correlation-1', $context->correlationId()); + } + + private function event(): ProfileCreated + { + return new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + ); + } +} diff --git a/tests/Unit/Repository/MessageDecorator/CorrelationCausationDecoratorTest.php b/tests/Unit/Repository/MessageDecorator/CorrelationCausationDecoratorTest.php new file mode 100644 index 000000000..c84cdd447 --- /dev/null +++ b/tests/Unit/Repository/MessageDecorator/CorrelationCausationDecoratorTest.php @@ -0,0 +1,135 @@ +previousUuidFactory = RamseyUuid::getFactory(); + + RamseyUuid::setFactory(new FakeRamseyUuidFactory()); + } + + protected function tearDown(): void + { + RamseyUuid::setFactory($this->previousUuidFactory); + } + + public function testRootMessageCorrelatesToItself(): void + { + $decorator = new CorrelationCausationDecorator(new MessageContext()); + + $message = $decorator(Message::create($this->event())); + + $eventId = $message->header(EventIdHeader::class)->eventId; + + self::assertSame('10000000-7000-0000-0000-000000000001', $eventId); + self::assertSame($eventId, $message->header(CorrelationIdHeader::class)->correlationId); + self::assertFalse($message->hasHeader(CausationIdHeader::class)); + } + + public function testInheritsIdsFromContext(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + + $decorator = new CorrelationCausationDecorator($context); + + $message = $decorator(Message::create($this->event())); + + self::assertSame('10000000-7000-0000-0000-000000000001', $message->header(EventIdHeader::class)->eventId); + self::assertSame('causation-1', $message->header(CausationIdHeader::class)->causationId); + self::assertSame('correlation-1', $message->header(CorrelationIdHeader::class)->correlationId); + } + + public function testCorrelatesToItselfWhenContextHasOnlyCausationId(): void + { + $context = new MessageContext(); + $context->push('causation-1'); + + $decorator = new CorrelationCausationDecorator($context); + + $message = $decorator(Message::create($this->event())); + + $eventId = $message->header(EventIdHeader::class)->eventId; + + self::assertSame('causation-1', $message->header(CausationIdHeader::class)->causationId); + self::assertSame($eventId, $message->header(CorrelationIdHeader::class)->correlationId); + } + + public function testKeepsExistingEventId(): void + { + $decorator = new CorrelationCausationDecorator(new MessageContext()); + + $message = $decorator( + Message::create($this->event())->withHeader(new EventIdHeader('event-1')), + ); + + self::assertSame('event-1', $message->header(EventIdHeader::class)->eventId); + self::assertSame('event-1', $message->header(CorrelationIdHeader::class)->correlationId); + } + + public function testDoesNotOverwriteExplicitHeaders(): void + { + $context = new MessageContext(); + $context->push('causation-1', 'correlation-1'); + + $decorator = new CorrelationCausationDecorator($context); + + $message = $decorator( + Message::create($this->event()) + ->withHeader(new CausationIdHeader('explicit-causation')) + ->withHeader(new CorrelationIdHeader('explicit-correlation')), + ); + + self::assertSame('explicit-causation', $message->header(CausationIdHeader::class)->causationId); + self::assertSame('explicit-correlation', $message->header(CorrelationIdHeader::class)->correlationId); + } + + public function testEveryMessageOfOneContextSharesCorrelationId(): void + { + $context = new MessageContext(); + $context->push(null, 'correlation-1'); + + $decorator = new CorrelationCausationDecorator($context); + + $first = $decorator(Message::create($this->event())); + $second = $decorator(Message::create($this->event())); + + self::assertNotSame( + $first->header(EventIdHeader::class)->eventId, + $second->header(EventIdHeader::class)->eventId, + ); + self::assertSame('correlation-1', $first->header(CorrelationIdHeader::class)->correlationId); + self::assertSame('correlation-1', $second->header(CorrelationIdHeader::class)->correlationId); + } + + private function event(): ProfileCreated + { + return new ProfileCreated( + ProfileId::fromString('1'), + Email::fromString('info@patchlevel.de'), + ); + } +} diff --git a/tests/Unit/Subscription/Engine/Listener/MessageContextSubscriberTest.php b/tests/Unit/Subscription/Engine/Listener/MessageContextSubscriberTest.php new file mode 100644 index 000000000..f83dbc833 --- /dev/null +++ b/tests/Unit/Subscription/Engine/Listener/MessageContextSubscriberTest.php @@ -0,0 +1,237 @@ +addSubscriber(new MessageContextSubscriber($context)); + + // a batch flush runs on the terminal event and can fail + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static fn (): never => throw new RuntimeException('FLUSH FAILED'), + ); + + $error = $this->processor($eventDispatcher)->process( + 1, + $this->message(), + new Subscription('test'), + ); + + self::assertNotNull($error); + + // the failed message must not contaminate whatever is recorded next + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testContextIsPoppedBeforeOtherTerminalListeners(): void + { + $context = new MessageContext(); + + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addSubscriber(new MessageContextSubscriber($context)); + + $causationIdDuringFlush = 'not called'; + + // a batch flush covers many messages, so it must not be attributed to the one + // which happened to trip the threshold + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static function () use ($context, &$causationIdDuringFlush): void { + $causationIdDuringFlush = $context->causationId(); + }, + ); + + $this->processor($eventDispatcher)->process(1, $this->message(), new Subscription('test')); + + self::assertNull($causationIdDuringFlush); + } + + private function processor(EventDispatcher $eventDispatcher): MessageProcessor + { + $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] + class { + #[Subscribe(ProfileVisited::class)] + public function onProfileVisited(ProfileVisited $event): void + { + } + }; + + return new MessageProcessor( + new MetadataSubscriberAccessorRepository([$subscriber]), + $eventDispatcher, + [], + new NullLogger(), + ); + } + + public function testPushesAndPopsAroundMessage(): void + { + $context = new MessageContext(); + $listener = new MessageContextSubscriber($context); + + $subscription = new Subscription('test'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + + self::assertSame('event-1', $context->causationId()); + self::assertSame('correlation-1', $context->correlationId()); + + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + + self::assertNull($context->causationId()); + self::assertNull($context->correlationId()); + } + + public function testPopsOnError(): void + { + $context = new MessageContext(); + $listener = new MessageContextSubscriber($context); + + $subscription = new Subscription('test'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageError(new OnHandleMessageError( + $subscription, + new RuntimeException('ERROR'), + $message, + 1, + )); + + self::assertNull($context->causationId()); + } + + public function testSuccessWithoutHandleMessageDoesNotPop(): void + { + $context = new MessageContext(); + $context->push('outer-causation', 'outer-correlation'); + + $listener = new MessageContextSubscriber($context); + + // a subscriber without a matching subscribe method is reported as + // success without a preceding OnHandleMessage + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess( + new Subscription('test'), + $this->message(), + 1, + )); + + self::assertSame('outer-causation', $context->causationId()); + self::assertSame('outer-correlation', $context->correlationId()); + } + + public function testDoubleSuccessPopsOnlyOnce(): void + { + $context = new MessageContext(); + $context->push('outer-causation', 'outer-correlation'); + + $listener = new MessageContextSubscriber($context); + + $subscription = new Subscription('test'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 2)); + + self::assertSame('outer-causation', $context->causationId()); + self::assertSame('outer-correlation', $context->correlationId()); + } + + public function testCommandKeepsFramesOfEnclosingScopes(): void + { + $context = new MessageContext(); + + // the command bus seeded a correlation id for the command it is handling + $context->push('outer-causation', 'outer-correlation'); + + $listener = new MessageContextSubscriber($context); + + // saving an aggregate can run the engine synchronously, which dispatches OnCommand + // inside the scope of the command bus + $listener->onCommand(new OnCommand(new Run())); + + self::assertSame('outer-causation', $context->causationId()); + self::assertSame('outer-correlation', $context->correlationId()); + } + + public function testCommandRemovesOnlyItsOwnFrame(): void + { + $context = new MessageContext(); + $context->push('outer-causation', 'outer-correlation'); + + $listener = new MessageContextSubscriber($context); + + $listener->onHandleMessage(new OnHandleMessage(new Subscription('test'), $this->message())); + $listener->onCommand(new OnCommand(new Run())); + + self::assertSame('outer-causation', $context->causationId()); + self::assertSame('outer-correlation', $context->correlationId()); + + // the healed frame must not be popped a second time + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess( + new Subscription('test'), + $this->message(), + 1, + )); + + self::assertSame('outer-causation', $context->causationId()); + } + + public function testSubscribedEvents(): void + { + self::assertSame( + [ + OnCommand::class, + OnHandleMessage::class, + OnHandleMessageSuccess::class, + OnHandleMessageError::class, + ], + array_keys(MessageContextSubscriber::getSubscribedEvents()), + ); + } + + private function message(): Message + { + return Message::create(new ProfileVisited(ProfileId::fromString('test'))) + ->withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')); + } +} diff --git a/tests/Unit/Subscription/Engine/MessageProcessorTest.php b/tests/Unit/Subscription/Engine/MessageProcessorTest.php index 41cf43e12..9bd6b5d4f 100644 --- a/tests/Unit/Subscription/Engine/MessageProcessorTest.php +++ b/tests/Unit/Subscription/Engine/MessageProcessorTest.php @@ -12,6 +12,8 @@ use Patchlevel\EventSourcing\Subscription\Engine\Error; use Patchlevel\EventSourcing\Subscription\Engine\Event\OnBeforeHandleMessage; use Patchlevel\EventSourcing\Subscription\Engine\Event\OnHandleMessage; +use Patchlevel\EventSourcing\Subscription\Engine\Event\OnHandleMessageError; +use Patchlevel\EventSourcing\Subscription\Engine\Event\OnHandleMessageSuccess; use Patchlevel\EventSourcing\Subscription\Engine\MessageProcessor; use Patchlevel\EventSourcing\Subscription\Engine\ProcessingStopped; use Patchlevel\EventSourcing\Subscription\Partitioner\StreamPartitioner; @@ -25,11 +27,84 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Psr\Log\NullLogger; +use RuntimeException; use Symfony\Component\EventDispatcher\EventDispatcher; #[CoversClass(MessageProcessor::class)] final class MessageProcessorTest extends TestCase { + public function testFailingTerminalListenerIsReportedAsError(): void + { + $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] + class { + #[Subscribe(ProfileVisited::class)] + public function onProfileVisited(ProfileVisited $event): void + { + } + }; + + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static fn (): never => throw new RuntimeException('FLUSH FAILED'), + ); + + $errorEvents = []; + $eventDispatcher->addListener( + OnHandleMessageError::class, + static function (OnHandleMessageError $event) use (&$errorEvents): void { + $errorEvents[] = $event; + }, + ); + + $processor = new MessageProcessor( + new MetadataSubscriberAccessorRepository([$subscriber]), + $eventDispatcher, + [], + new NullLogger(), + ); + + $message = Message::create(new ProfileVisited(ProfileId::fromString('1'))); + $subscription = new Subscription('test', status: Status::Active); + + $error = $processor->process(1, $message, $subscription); + + // a listener which fails on the terminal event must not escape as an exception, + // and must not leave the message without a terminal event + self::assertInstanceOf(Error::class, $error); + self::assertSame('FLUSH FAILED', $error->message); + self::assertCount(1, $errorEvents); + self::assertNull($subscription->position()); + } + + public function testFailingTerminalListenerWithoutSubscribeMethodIsReportedAsError(): void + { + $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] + class { + }; + + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static fn (): never => throw new RuntimeException('FLUSH FAILED'), + ); + + $processor = new MessageProcessor( + new MetadataSubscriberAccessorRepository([$subscriber]), + $eventDispatcher, + [], + new NullLogger(), + ); + + $message = Message::create(new ProfileVisited(ProfileId::fromString('1'))); + $subscription = new Subscription('test', status: Status::Active); + + $error = $processor->process(1, $message, $subscription); + + self::assertInstanceOf(Error::class, $error); + self::assertSame('FLUSH FAILED', $error->message); + } + public function testProcessInvokesSubscribeMethod(): void { $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] diff --git a/tests/Unit/Telemetry/ForceFlushListenerTest.php b/tests/Unit/Telemetry/ForceFlushListenerTest.php new file mode 100644 index 000000000..0b61dbd67 --- /dev/null +++ b/tests/Unit/Telemetry/ForceFlushListenerTest.php @@ -0,0 +1,45 @@ +createBatchingTracerProvider(); + $instrumentation = new Instrumentation($tracerProvider); + + $instrumentation->span('test.span', static fn (): null => null); + + // with a batching processor the span is still buffered + self::assertCount(0, $this->spans()); + + $listener = new ForceFlushListener($tracerProvider); + $listener(new WorkerRunningEvent($this->createMock(Worker::class))); + + self::assertCount(1, $this->spans()); + } + + public function testDoesNothingWithoutSdk(): void + { + $this->createTracerProvider(); + + $listener = new ForceFlushListener(new NoopTracerProvider()); + $listener(new WorkerRunningEvent($this->createMock(Worker::class))); + + self::assertCount(0, $this->spans()); + } +} diff --git a/tests/Unit/Telemetry/InMemoryTracer.php b/tests/Unit/Telemetry/InMemoryTracer.php new file mode 100644 index 000000000..e7ac31b0d --- /dev/null +++ b/tests/Unit/Telemetry/InMemoryTracer.php @@ -0,0 +1,70 @@ + */ + private ArrayObject $spanStorage; + + private TracerProvider $tracerProvider; + + private function createTracerProvider(): TracerProvider + { + /** @var ArrayObject $storage */ + $storage = new ArrayObject(); + + $this->spanStorage = $storage; + $this->tracerProvider = new TracerProvider( + new SimpleSpanProcessor(new InMemoryExporter($storage)), + ); + + return $this->tracerProvider; + } + + /** + * Buffers spans until they are flushed, so that the effect of the + * ForceFlushListener becomes observable. + */ + private function createBatchingTracerProvider(): TracerProvider + { + /** @var ArrayObject $storage */ + $storage = new ArrayObject(); + + $this->spanStorage = $storage; + $this->tracerProvider = new TracerProvider( + new BatchSpanProcessor( + new InMemoryExporter($storage), + Clock::getDefault(), + scheduledDelayMillis: 60_000, + autoFlush: false, + ), + ); + + return $this->tracerProvider; + } + + /** @return list */ + private function spans(): array + { + return array_values(iterator_to_array($this->spanStorage)); + } + + private function span(int $index = 0): ImmutableSpan + { + return $this->spans()[$index]; + } +} diff --git a/tests/Unit/Telemetry/InstrumentationTest.php b/tests/Unit/Telemetry/InstrumentationTest.php new file mode 100644 index 000000000..37bba0527 --- /dev/null +++ b/tests/Unit/Telemetry/InstrumentationTest.php @@ -0,0 +1,99 @@ +createTracerProvider()); + + $expected = uniqid('result-'); + + $result = $instrumentation->span( + 'test.span', + static fn (): string => $expected, + SpanKind::KIND_PRODUCER, + ['foo' => 'bar'], + ); + + self::assertSame($expected, $result); + self::assertCount(1, $this->spans()); + + $span = $this->span(); + + self::assertSame('test.span', $span->getName()); + self::assertSame(SpanKind::KIND_PRODUCER, $span->getKind()); + self::assertSame('bar', $span->getAttributes()->get('foo')); + self::assertSame(StatusCode::STATUS_UNSET, $span->getStatus()->getCode()); + } + + public function testNullAttributesAreRemoved(): void + { + $instrumentation = new Instrumentation($this->createTracerProvider()); + + $instrumentation->span( + 'test.span', + static fn (): null => null, + attributes: ['foo' => null, 'bar' => 'baz'], + ); + + $attributes = $this->span()->getAttributes(); + + self::assertFalse($attributes->has('foo')); + self::assertSame('baz', $attributes->get('bar')); + } + + public function testSpanRecordsException(): void + { + $instrumentation = new Instrumentation($this->createTracerProvider()); + + $this->expectException(RuntimeException::class); + + try { + $instrumentation->span( + 'test.span', + static fn (): never => throw new RuntimeException('ERROR'), + ); + } finally { + $span = $this->span(); + + self::assertSame(StatusCode::STATUS_ERROR, $span->getStatus()->getCode()); + self::assertSame('ERROR', $span->getStatus()->getDescription()); + self::assertCount(1, $span->getEvents()); + self::assertSame('exception', $span->getEvents()[0]->getName()); + } + } + + public function testNestedSpansAreLinkedByParent(): void + { + $instrumentation = new Instrumentation($this->createTracerProvider()); + + $instrumentation->span( + 'outer', + static function () use ($instrumentation): void { + $instrumentation->span('inner', static fn (): null => null); + }, + ); + + [$inner, $outer] = $this->spans(); + + self::assertSame('inner', $inner->getName()); + self::assertSame('outer', $outer->getName()); + self::assertSame($outer->getContext()->getSpanId(), $inner->getParentContext()->getSpanId()); + } +} diff --git a/tests/Unit/Telemetry/MessageAttributesTest.php b/tests/Unit/Telemetry/MessageAttributesTest.php new file mode 100644 index 000000000..e887feec8 --- /dev/null +++ b/tests/Unit/Telemetry/MessageAttributesTest.php @@ -0,0 +1,57 @@ +withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')) + ->withHeader(new CausationIdHeader('causation-1')) + ->withHeader(new StreamNameHeader('profile-1')); + + self::assertSame( + [ + TraceAttributes::EVENT_NAME => ProfileVisited::class, + TraceAttributes::MESSAGING_MESSAGE_ID => 'event-1', + TraceAttributes::MESSAGING_MESSAGE_CONVERSATION_ID => 'correlation-1', + TraceAttributes::CAUSATION_ID => 'causation-1', + TraceAttributes::MESSAGING_DESTINATION_NAME => 'profile-1', + ], + MessageAttributes::from($message), + ); + } + + public function testWithoutHeaders(): void + { + $message = Message::create(new ProfileVisited(ProfileId::fromString('1'))); + + self::assertSame( + [ + TraceAttributes::EVENT_NAME => ProfileVisited::class, + TraceAttributes::MESSAGING_MESSAGE_ID => null, + TraceAttributes::MESSAGING_MESSAGE_CONVERSATION_ID => null, + TraceAttributes::CAUSATION_ID => null, + TraceAttributes::MESSAGING_DESTINATION_NAME => null, + ], + MessageAttributes::from($message), + ); + } +} diff --git a/tests/Unit/Telemetry/SpanEventLoggerTest.php b/tests/Unit/Telemetry/SpanEventLoggerTest.php new file mode 100644 index 000000000..7f020e224 --- /dev/null +++ b/tests/Unit/Telemetry/SpanEventLoggerTest.php @@ -0,0 +1,61 @@ +createTracerProvider()); + $logger = new SpanEventLogger(); + + $instrumentation->span( + 'test.span', + static function () use ($logger): void { + $logger->debug('Repository: aggregate saved.'); + }, + ); + + $events = $this->span()->getEvents(); + + self::assertCount(1, $events); + self::assertSame('Repository: aggregate saved.', $events[0]->getName()); + self::assertSame(LogLevel::DEBUG, $events[0]->getAttributes()->get('log.level')); + } + + public function testDelegatesToInnerLogger(): void + { + $this->createTracerProvider(); + + $inner = $this->createMock(LoggerInterface::class); + $inner + ->expects($this->once()) + ->method('log') + ->with(LogLevel::INFO, 'message', ['foo' => 'bar']); + + $logger = new SpanEventLogger($inner); + $logger->info('message', ['foo' => 'bar']); + } + + public function testNoSpanEventWithoutActiveSpan(): void + { + $this->createTracerProvider(); + + $logger = new SpanEventLogger(); + $logger->error('message'); + + self::assertCount(0, $this->spans()); + } +} diff --git a/tests/Unit/Telemetry/TraceDecoratorTest.php b/tests/Unit/Telemetry/TraceDecoratorTest.php new file mode 100644 index 000000000..33140ea23 --- /dev/null +++ b/tests/Unit/Telemetry/TraceDecoratorTest.php @@ -0,0 +1,70 @@ +createTracerProvider()); + $decorator = new TraceDecorator(); + + $message = $instrumentation->span( + 'test.span', + fn (): Message => $decorator(Message::create($this->event())), + ); + + self::assertTrue($message->hasHeader(TraceHeader::class)); + + $span = $this->span(); + $traceparent = $message->header(TraceHeader::class)->traceparent; + + self::assertTrue(str_contains($traceparent, $span->getContext()->getTraceId())); + self::assertTrue(str_contains($traceparent, $span->getContext()->getSpanId())); + } + + public function testNoTraceHeaderWithoutActiveSpan(): void + { + $decorator = new TraceDecorator(); + + $message = $decorator(Message::create($this->event())); + + self::assertFalse($message->hasHeader(TraceHeader::class)); + } + + public function testKeepsExistingTraceHeader(): void + { + $instrumentation = new Instrumentation($this->createTracerProvider()); + $decorator = new TraceDecorator(); + + $message = $instrumentation->span( + 'test.span', + fn (): Message => $decorator( + Message::create($this->event())->withHeader(new TraceHeader('explicit')), + ), + ); + + self::assertSame('explicit', $message->header(TraceHeader::class)->traceparent); + } + + private function event(): ProfileVisited + { + return new ProfileVisited(ProfileId::fromString('1')); + } +} diff --git a/tests/Unit/Telemetry/TraceableCommandBusTest.php b/tests/Unit/Telemetry/TraceableCommandBusTest.php new file mode 100644 index 000000000..e5eb96691 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableCommandBusTest.php @@ -0,0 +1,37 @@ +createMock(CommandBus::class); + $commandBus + ->expects($this->once()) + ->method('dispatch') + ->with($command); + + $traceableCommandBus = new TraceableCommandBus($commandBus, $this->createTracerProvider()); + $traceableCommandBus->dispatch($command); + + $span = $this->span(); + + self::assertSame('event_sourcing.command_bus.dispatch', $span->getName()); + self::assertSame($command::class, $span->getAttributes()->get(TraceAttributes::COMMAND_NAME)); + } +} diff --git a/tests/Unit/Telemetry/TraceableConsumerTest.php b/tests/Unit/Telemetry/TraceableConsumerTest.php new file mode 100644 index 000000000..06b284db5 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableConsumerTest.php @@ -0,0 +1,52 @@ +withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')); + + $consumer = $this->createMock(Consumer::class); + $consumer + ->expects($this->once()) + ->method('consume') + ->with($message); + + $traceableConsumer = new TraceableConsumer($consumer, $this->createTracerProvider()); + $traceableConsumer->consume($message); + + $span = $this->span(); + $attributes = $span->getAttributes(); + + self::assertSame('event_sourcing.event_bus.consume', $span->getName()); + self::assertSame(SpanKind::KIND_CONSUMER, $span->getKind()); + self::assertSame(ProfileVisited::class, $attributes->get(TraceAttributes::EVENT_NAME)); + self::assertSame('event-1', $attributes->get(TraceAttributes::MESSAGING_MESSAGE_ID)); + self::assertSame( + 'correlation-1', + $attributes->get(TraceAttributes::MESSAGING_MESSAGE_CONVERSATION_ID), + ); + self::assertFalse($attributes->has(TraceAttributes::CAUSATION_ID)); + } +} diff --git a/tests/Unit/Telemetry/TraceableEventBusTest.php b/tests/Unit/Telemetry/TraceableEventBusTest.php new file mode 100644 index 000000000..a9f2039f1 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableEventBusTest.php @@ -0,0 +1,42 @@ +createMock(EventBus::class); + $eventBus + ->expects($this->once()) + ->method('dispatch') + ->with($first, $second); + + $traceableEventBus = new TraceableEventBus($eventBus, $this->createTracerProvider()); + $traceableEventBus->dispatch($first, $second); + + $span = $this->span(); + + self::assertSame('event_sourcing.event_bus.dispatch', $span->getName()); + self::assertSame(SpanKind::KIND_PRODUCER, $span->getKind()); + self::assertSame(2, $span->getAttributes()->get(TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT)); + } +} diff --git a/tests/Unit/Telemetry/TraceableQueryBusTest.php b/tests/Unit/Telemetry/TraceableQueryBusTest.php new file mode 100644 index 000000000..526fc9ab8 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableQueryBusTest.php @@ -0,0 +1,39 @@ +createMock(QueryBus::class); + $queryBus + ->expects($this->once()) + ->method('dispatch') + ->with($query) + ->willReturn('result'); + + $traceableQueryBus = new TraceableQueryBus($queryBus, $this->createTracerProvider()); + + self::assertSame('result', $traceableQueryBus->dispatch($query)); + + $span = $this->span(); + + self::assertSame('event_sourcing.query_bus.dispatch', $span->getName()); + self::assertSame($query::class, $span->getAttributes()->get(TraceAttributes::QUERY_NAME)); + } +} diff --git a/tests/Unit/Telemetry/TraceableRepositoryManagerTest.php b/tests/Unit/Telemetry/TraceableRepositoryManagerTest.php new file mode 100644 index 000000000..5738c4b25 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableRepositoryManagerTest.php @@ -0,0 +1,43 @@ +createMock(RepositoryManager::class); + $repositoryManager + ->expects($this->once()) + ->method('get') + ->with(Profile::class) + ->willReturn($this->createMock(Repository::class)); + + $manager = new TraceableRepositoryManager( + $repositoryManager, + new AggregateRootRegistry(['profile' => Profile::class]), + $this->createTracerProvider(), + ); + + $repository = $manager->get(Profile::class); + + self::assertInstanceOf(TraceableRepository::class, $repository); + + // the inner manager must only be asked once + self::assertSame($repository, $manager->get(Profile::class)); + } +} diff --git a/tests/Unit/Telemetry/TraceableRepositoryTest.php b/tests/Unit/Telemetry/TraceableRepositoryTest.php new file mode 100644 index 000000000..71401db29 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableRepositoryTest.php @@ -0,0 +1,100 @@ +createMock(Repository::class); + $repository + ->expects($this->once()) + ->method('load') + ->with($id) + ->willReturn($profile); + + $traceableRepository = new TraceableRepository($repository, 'profile', $this->createTracerProvider()); + + self::assertSame($profile, $traceableRepository->load($id)); + + $span = $this->span(); + + self::assertSame('event_sourcing.repository.load', $span->getName()); + self::assertSame('profile', $span->getAttributes()->get(TraceAttributes::AGGREGATE_NAME)); + self::assertSame('1', $span->getAttributes()->get(TraceAttributes::AGGREGATE_ID)); + } + + public function testHas(): void + { + $id = ProfileId::fromString('1'); + + $repository = $this->createMock(Repository::class); + $repository + ->expects($this->once()) + ->method('has') + ->with($id) + ->willReturn(true); + + $traceableRepository = new TraceableRepository($repository, 'profile', $this->createTracerProvider()); + + self::assertTrue($traceableRepository->has($id)); + self::assertSame('event_sourcing.repository.has', $this->span()->getName()); + } + + public function testSave(): void + { + $profile = Profile::createProfile(ProfileId::fromString('1'), Email::fromString('info@patchlevel.de')); + + $repository = $this->createMock(Repository::class); + $repository + ->expects($this->once()) + ->method('save') + ->with($profile); + + $traceableRepository = new TraceableRepository($repository, 'profile', $this->createTracerProvider()); + $traceableRepository->save($profile); + + self::assertSame('event_sourcing.repository.save', $this->span()->getName()); + } + + public function testRecordsExceptionOnSpan(): void + { + $id = ProfileId::fromString('1'); + + $repository = $this->createMock(Repository::class); + $repository + ->expects($this->once()) + ->method('load') + ->with($id) + ->willThrowException(new AggregateNotFound(Profile::class, $id)); + + $traceableRepository = new TraceableRepository($repository, 'profile', $this->createTracerProvider()); + + $this->expectException(AggregateNotFound::class); + + try { + $traceableRepository->load($id); + } finally { + self::assertSame(StatusCode::STATUS_ERROR, $this->span()->getStatus()->getCode()); + } + } +} diff --git a/tests/Unit/Telemetry/TraceableStoreTest.php b/tests/Unit/Telemetry/TraceableStoreTest.php new file mode 100644 index 000000000..8575c3ae9 --- /dev/null +++ b/tests/Unit/Telemetry/TraceableStoreTest.php @@ -0,0 +1,224 @@ +createMock(Store::class); + $store + ->expects($this->once()) + ->method('load') + ->with(null, null, null, false) + ->willReturn($stream); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + self::assertSame($stream, $traceableStore->load()); + self::assertSame('event_sourcing.store.load', $this->span()->getName()); + } + + public function testCount(): void + { + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('count') + ->with(null) + ->willReturn(3); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + self::assertSame(3, $traceableStore->count()); + self::assertSame('event_sourcing.store.count', $this->span()->getName()); + } + + public function testSave(): void + { + $message = Message::create(new ProfileVisited(ProfileId::fromString('1'))); + + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('save') + ->with($message); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + $traceableStore->save($message); + + $span = $this->span(); + + self::assertSame('event_sourcing.store.save', $span->getName()); + self::assertSame(SpanKind::KIND_PRODUCER, $span->getKind()); + self::assertSame(1, $span->getAttributes()->get(TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT)); + self::assertSame( + TraceAttributes::SYSTEM, + $span->getAttributes()->get(TraceAttributes::MESSAGING_SYSTEM), + ); + } + + public function testTransactional(): void + { + $function = static fn (): null => null; + + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('transactional') + ->with($function); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + $traceableStore->transactional($function); + + self::assertSame('event_sourcing.store.transactional', $this->span()->getName()); + } + + public function testStreams(): void + { + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('streams') + ->willReturn(['profile-1']); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + self::assertSame(['profile-1'], $traceableStore->streams()); + self::assertSame('event_sourcing.store.streams', $this->span()->getName()); + } + + public function testRemove(): void + { + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('remove') + ->with(null); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + $traceableStore->remove(); + + self::assertSame('event_sourcing.store.remove', $this->span()->getName()); + } + + public function testArchive(): void + { + $store = $this->createMock(Store::class); + $store + ->expects($this->once()) + ->method('archive') + ->with(null); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + $traceableStore->archive(); + + self::assertSame('event_sourcing.store.archive', $this->span()->getName()); + } + + public function testAppend(): void + { + $message = Message::create(new ProfileVisited(ProfileId::fromString('1'))); + $appendCondition = new AppendCondition(new Query()); + + $store = $this->createMockForIntersectionOfInterfaces([Store::class, AppendStore::class]); + $store + ->expects($this->once()) + ->method('append') + ->with([$message], $appendCondition); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + $traceableStore->append((static fn () => yield $message)(), $appendCondition); + + $span = $this->span(); + + self::assertSame('event_sourcing.store.append', $span->getName()); + self::assertSame(SpanKind::KIND_PRODUCER, $span->getKind()); + self::assertSame(1, $span->getAttributes()->get(TraceAttributes::MESSAGING_BATCH_MESSAGE_COUNT)); + } + + public function testAppendNotSupported(): void + { + $store = $this->createMock(Store::class); + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + $this->expectException(StoreDoesNotSupport::class); + $this->expectExceptionMessage(AppendStore::class); + + $traceableStore->append([]); + } + + public function testQuery(): void + { + $stream = new Stream(); + $query = new Query(); + + $store = $this->createMockForIntersectionOfInterfaces([Store::class, AppendStore::class]); + $store + ->expects($this->once()) + ->method('query') + ->with($query, 5) + ->willReturn($stream); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + self::assertSame($stream, $traceableStore->query($query, 5)); + self::assertSame('event_sourcing.store.query', $this->span()->getName()); + } + + public function testQueryNotSupported(): void + { + $store = $this->createMock(Store::class); + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + $this->expectException(StoreDoesNotSupport::class); + + $traceableStore->query(new Query()); + } + + public function testHead(): void + { + $store = $this->createMockForIntersectionOfInterfaces([Store::class, AppendStore::class]); + $store + ->expects($this->once()) + ->method('head') + ->willReturn(42); + + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + self::assertSame(42, $traceableStore->head()); + self::assertSame('event_sourcing.store.head', $this->span()->getName()); + } + + public function testHeadNotSupported(): void + { + $store = $this->createMock(Store::class); + $traceableStore = new TraceableStore($store, $this->createTracerProvider()); + + $this->expectException(StoreDoesNotSupport::class); + + $traceableStore->head(); + } +} diff --git a/tests/Unit/Telemetry/TraceableSubscriptionEngineTest.php b/tests/Unit/Telemetry/TraceableSubscriptionEngineTest.php new file mode 100644 index 000000000..a1e6be2fb --- /dev/null +++ b/tests/Unit/Telemetry/TraceableSubscriptionEngineTest.php @@ -0,0 +1,111 @@ +createMock(SubscriptionEngine::class); + $engine + ->expects($this->once()) + ->method('execute') + ->with($command) + ->willReturn($result); + + $traceableEngine = new TraceableSubscriptionEngine($engine, $this->createTracerProvider()); + + self::assertSame($result, $traceableEngine->execute($command)); + + $span = $this->span(); + $attributes = $span->getAttributes(); + + self::assertSame('event_sourcing.subscription.run', $span->getName()); + self::assertSame('profile_projection', $attributes->get(TraceAttributes::SUBSCRIPTION_ID)); + self::assertSame('reporting', $attributes->get(TraceAttributes::SUBSCRIPTION_GROUP)); + self::assertSame(5, $attributes->get(TraceAttributes::SUBSCRIPTION_PROCESSED_MESSAGES)); + self::assertTrue($attributes->get(TraceAttributes::SUBSCRIPTION_FINISHED)); + self::assertSame(0, $attributes->get(TraceAttributes::ERROR_COUNT)); + } + + public function testExecuteBootCountsErrors(): void + { + $command = new Boot(); + $result = new Result([new Error('profile_projection', 'ERROR', new RuntimeException('ERROR'))]); + + $engine = $this->createMock(SubscriptionEngine::class); + $engine + ->expects($this->once()) + ->method('execute') + ->with($command) + ->willReturn($result); + + $traceableEngine = new TraceableSubscriptionEngine($engine, $this->createTracerProvider()); + $traceableEngine->execute($command); + + $span = $this->span(); + + self::assertSame('event_sourcing.subscription.boot', $span->getName()); + self::assertSame(1, $span->getAttributes()->get(TraceAttributes::ERROR_COUNT)); + self::assertFalse($span->getAttributes()->has(TraceAttributes::SUBSCRIPTION_PROCESSED_MESSAGES)); + } + + public function testSubscriptions(): void + { + $criteria = new SubscriptionEngineCriteria(); + $subscriptions = [new Subscription('profile_projection')]; + + $engine = $this->createMock(SubscriptionEngine::class); + $engine + ->expects($this->once()) + ->method('subscriptions') + ->with($criteria) + ->willReturn($subscriptions); + + $traceableEngine = new TraceableSubscriptionEngine($engine, $this->createTracerProvider()); + + self::assertSame($subscriptions, $traceableEngine->subscriptions($criteria)); + self::assertSame('event_sourcing.subscription.subscriptions', $this->span()->getName()); + } + + public function testStats(): void + { + $criteria = new SubscriptionEngineCriteria(); + $stats = new SubscriptionStats(['active' => 1]); + + $engine = $this->createMock(SubscriptionEngine::class); + $engine + ->expects($this->once()) + ->method('stats') + ->with($criteria) + ->willReturn($stats); + + $traceableEngine = new TraceableSubscriptionEngine($engine, $this->createTracerProvider()); + + self::assertSame($stats, $traceableEngine->stats($criteria)); + self::assertSame('event_sourcing.subscription.stats', $this->span()->getName()); + } +} diff --git a/tests/Unit/Telemetry/TracingSubscriberTest.php b/tests/Unit/Telemetry/TracingSubscriberTest.php new file mode 100644 index 000000000..f5c2692fd --- /dev/null +++ b/tests/Unit/Telemetry/TracingSubscriberTest.php @@ -0,0 +1,316 @@ +createTracerProvider()); + + $subscription = new Subscription('profile_projection', 'reporting'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + + self::assertCount(1, $this->spans()); + + $span = $this->span(); + $attributes = $span->getAttributes(); + + self::assertSame(TracingSubscriber::SPAN_NAME, $span->getName()); + self::assertSame(SpanKind::KIND_CONSUMER, $span->getKind()); + self::assertSame(StatusCode::STATUS_OK, $span->getStatus()->getCode()); + self::assertSame('profile_projection', $attributes->get(TraceAttributes::SUBSCRIPTION_ID)); + self::assertSame('reporting', $attributes->get(TraceAttributes::SUBSCRIPTION_GROUP)); + self::assertSame(ProfileVisited::class, $attributes->get(TraceAttributes::EVENT_NAME)); + self::assertSame('event-1', $attributes->get(TraceAttributes::MESSAGING_MESSAGE_ID)); + self::assertSame( + 'correlation-1', + $attributes->get(TraceAttributes::MESSAGING_MESSAGE_CONVERSATION_ID), + ); + self::assertSame('causation-1', $attributes->get(TraceAttributes::CAUSATION_ID)); + } + + public function testLinksToTheTraceWhichRecordedTheMessage(): void + { + $tracerProvider = $this->createTracerProvider(); + $instrumentation = new Instrumentation($tracerProvider); + $decorator = new TraceDecorator(); + + // the message is recorded inside the producing trace + $message = $instrumentation->span( + 'producer', + fn (): Message => $decorator($this->message()), + ); + + $listener = new TracingSubscriber($tracerProvider); + + $subscription = new Subscription('profile_projection'); + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + + [$producerSpan, $consumerSpan] = $this->spans(); + + $links = $consumerSpan->getLinks(); + + self::assertCount(1, $links); + self::assertSame( + $producerSpan->getContext()->getTraceId(), + $links[0]->getSpanContext()->getTraceId(), + ); + self::assertSame( + $producerSpan->getContext()->getSpanId(), + $links[0]->getSpanContext()->getSpanId(), + ); + + // a link, not a parent: the consumer span starts its own trace + self::assertNotSame( + $producerSpan->getContext()->getTraceId(), + $consumerSpan->getContext()->getTraceId(), + ); + } + + public function testNoLinkWithoutTraceHeader(): void + { + $listener = new TracingSubscriber($this->createTracerProvider()); + + $subscription = new Subscription('profile_projection'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + + self::assertCount(0, $this->span()->getLinks()); + } + + public function testInvalidTraceHeaderIsIgnored(): void + { + $listener = new TracingSubscriber($this->createTracerProvider()); + + $subscription = new Subscription('profile_projection'); + $message = $this->message()->withHeader(new TraceHeader('not-a-traceparent')); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + + self::assertCount(0, $this->span()->getLinks()); + } + + public function testInvalidTraceHeaderDoesNotLinkToTheActiveSpan(): void + { + $tracerProvider = $this->createTracerProvider(); + $listener = new TracingSubscriber($tracerProvider); + + $subscription = new Subscription('profile_projection'); + $message = $this->message()->withHeader(new TraceHeader('not-a-traceparent')); + + // the engine run span is active while the message is handled + (new Instrumentation($tracerProvider))->span( + 'event_sourcing.subscription.run', + static function () use ($listener, $subscription, $message): void { + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess($subscription, $message, 1)); + }, + ); + + [$consumerSpan, $runSpan] = $this->spans(); + + self::assertSame(TracingSubscriber::SPAN_NAME, $consumerSpan->getName()); + self::assertSame($runSpan->getContext()->getSpanId(), $consumerSpan->getParentContext()->getSpanId()); + self::assertCount(0, $consumerSpan->getLinks()); + } + + public function testRecordsError(): void + { + $listener = new TracingSubscriber($this->createTracerProvider()); + + $subscription = new Subscription('profile_projection'); + $message = $this->message(); + + $listener->onHandleMessage(new OnHandleMessage($subscription, $message)); + $listener->onHandleMessageError(new OnHandleMessageError( + $subscription, + new RuntimeException('ERROR'), + $message, + 1, + )); + + $span = $this->span(); + + self::assertSame(StatusCode::STATUS_ERROR, $span->getStatus()->getCode()); + self::assertSame('ERROR', $span->getStatus()->getDescription()); + self::assertCount(1, $span->getEvents()); + } + + public function testSuccessWithoutHandleMessageCreatesNoSpan(): void + { + $listener = new TracingSubscriber($this->createTracerProvider()); + + // a subscriber without a matching subscribe method is reported as + // success without a preceding OnHandleMessage + $listener->onHandleMessageSuccess(new OnHandleMessageSuccess( + new Subscription('profile_projection'), + $this->message(), + 1, + )); + + self::assertCount(0, $this->spans()); + } + + public function testSpanIsNotLeakedWhenTerminalListenerFails(): void + { + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addSubscriber(new TracingSubscriber($this->createTracerProvider())); + + // a batch flush runs on the terminal event and can fail + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static fn (): never => throw new RuntimeException('FLUSH FAILED'), + ); + + $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] + class { + #[Subscribe(ProfileVisited::class)] + public function onProfileVisited(ProfileVisited $event): void + { + } + }; + + $processor = new MessageProcessor( + new MetadataSubscriberAccessorRepository([$subscriber]), + $eventDispatcher, + [], + new NullLogger(), + ); + + $error = $processor->process(1, $this->message(), new Subscription('test')); + + self::assertNotNull($error); + + // the span must be ended and exported, and must not stay active as the parent + // of everything the application does afterwards + self::assertCount(1, $this->spans()); + self::assertFalse(Span::getCurrent()->getContext()->isValid()); + + // and it must report the failure: a message which ended in an error must not + // leave an Ok span behind + $span = $this->span(); + + self::assertSame(StatusCode::STATUS_ERROR, $span->getStatus()->getCode()); + self::assertSame('FLUSH FAILED', $span->getStatus()->getDescription()); + self::assertCount(1, $span->getEvents()); + self::assertSame('exception', $span->getEvents()[0]->getName()); + } + + public function testSpanMeasuresWorkOfOtherTerminalListeners(): void + { + $eventDispatcher = new EventDispatcher(); + $eventDispatcher->addSubscriber(new TracingSubscriber($this->createTracerProvider())); + + $spanDuringFlush = null; + + // a batch flush runs on the terminal event, its work belongs inside the span + $eventDispatcher->addListener( + OnHandleMessageSuccess::class, + static function () use (&$spanDuringFlush): void { + $spanDuringFlush = Span::getCurrent()->getContext()->getSpanId(); + }, + ); + + $subscriber = new #[Subscriber('test', RunMode::FromBeginning)] + class { + #[Subscribe(ProfileVisited::class)] + public function onProfileVisited(ProfileVisited $event): void + { + } + }; + + $processor = new MessageProcessor( + new MetadataSubscriberAccessorRepository([$subscriber]), + $eventDispatcher, + [], + new NullLogger(), + ); + + $processor->process(1, $this->message(), new Subscription('test')); + + self::assertSame($this->span()->getContext()->getSpanId(), $spanDuringFlush); + } + + public function testCommandClosesLeakedSpan(): void + { + $listener = new TracingSubscriber($this->createTracerProvider()); + + $listener->onHandleMessage(new OnHandleMessage( + new Subscription('profile_projection'), + $this->message(), + )); + + self::assertCount(0, $this->spans()); + + $listener->onCommand(new OnCommand(new Run())); + + self::assertCount(1, $this->spans()); + } + + public function testSubscribedEvents(): void + { + self::assertSame( + [ + OnCommand::class, + OnHandleMessage::class, + OnHandleMessageSuccess::class, + OnHandleMessageError::class, + ], + array_keys(TracingSubscriber::getSubscribedEvents()), + ); + } + + private function message(): Message + { + return Message::create(new ProfileVisited(ProfileId::fromString('1'))) + ->withHeader(new EventIdHeader('event-1')) + ->withHeader(new CorrelationIdHeader('correlation-1')) + ->withHeader(new CausationIdHeader('causation-1')); + } +}