Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ jobs:
name: PHPStan
strategy:
matrix:
php-version: ["8.4"]
# PHP 8.2 resolves to Symfony 7.4 (Symfony 8 requires PHP 8.4+); PHP 8.4 resolves to Symfony 8.
php-version: ["8.2", "8.4"]
fail-fast: false
runs-on: ubuntu-latest
steps:
Expand All @@ -33,7 +34,7 @@ jobs:
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ runner.os }}-composer-

# Analysis runs against the highest set (doctrine/dbal 4 + Symfony 8).
# Analysis runs against doctrine/dbal 4 (Symfony 8 on PHP 8.4, Symfony 7.4 on PHP 8.2).
# The doctrine/dbal 3 only DBAL3\Connection decorator is excluded in
# phpstan.neon (its bool transaction methods are not covariant with the
# dbal 4 parent); it is exercised on dbal 3 by the PHPUnit job below.
Expand Down Expand Up @@ -83,7 +84,7 @@ jobs:
name: PHPUnit
strategy:
matrix:
php-version: ["8.4"]
php-version: ["8.2", "8.4"]
dbal: ["^3.6", "^4.0"]
fail-fast: false
runs-on: ubuntu-latest
Expand Down Expand Up @@ -112,10 +113,10 @@ jobs:
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
restore-keys: ${{ runner.os }}-composer-

# Pin the doctrine/dbal major up front so the whole graph resolves
# consistently: dbal 4 pulls Symfony 8, dbal 3 keeps Symfony on 7.4
# (symfony/http-foundation 8 conflicts with dbal 3). This gives runtime
# coverage of both Symfony majors across the matrix.
# The PHP version selects the Symfony major: Symfony 8 requires PHP 8.4+,
# so PHP 8.2 resolves to Symfony 7.4 while PHP 8.4 resolves to Symfony 8.
# The doctrine/dbal major is pinned so both the DBAL 3 and DBAL 4 connection
# decorators are exercised on each Symfony major.
- name: Pin doctrine/dbal version
run: composer require --dev --no-update "doctrine/dbal:${{ matrix.dbal }}"

Expand Down
9 changes: 5 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
}
],
"require": {
"php": ">=8.2",
"open-telemetry/sdk": "^1.2",
"symfony/dependency-injection": "*"
"symfony/dependency-injection": "^7.4 || ^8.0"
},
"require-dev": {
"doctrine/dbal": "^3.6 || ^4.0",
Expand All @@ -33,7 +34,7 @@
"symfony/framework-bundle": "^7.4 || ^8.0",
"symfony/http-client": "^7.4 || ^8.0",
"symfony/messenger": "^7.4 || ^8.0",
"symfony/monolog-bundle": "^3.7",
"symfony/monolog-bundle": "^3.7 || ^4.0",
"symfony/security-core": "^7.4 || ^8.0",
"symfony/serializer": "^7.4 || ^8.0",
"symfony/twig-bundle": "^7.4 || ^8.0",
Expand Down Expand Up @@ -71,8 +72,8 @@
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev",
"dev-main": "1.0.x-dev"
"dev-master": "3.0.x-dev",
"dev-main": "3.0.x-dev"
}
}
}
6 changes: 5 additions & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false" colors="true" testdox="true" processIsolation="false" stopOnFailure="true" displayDetailsOnTestsThatTriggerWarnings="true" displayDetailsOnTestsThatTriggerDeprecations="true" displayDetailsOnTestsThatTriggerErrors="true" displayDetailsOnTestsThatTriggerNotices="true" displayDetailsOnPhpunitDeprecations="true" bootstrap="vendor/autoload.php">
<phpunit backupGlobals="false" colors="true" testdox="true" processIsolation="false" stopOnFailure="true" failOnWarning="true" failOnNotice="true" failOnDeprecation="true" failOnPhpunitDeprecation="true" displayDetailsOnTestsThatTriggerWarnings="true" displayDetailsOnTestsThatTriggerDeprecations="true" displayDetailsOnTestsThatTriggerErrors="true" displayDetailsOnTestsThatTriggerNotices="true" displayDetailsOnPhpunitDeprecations="true" bootstrap="vendor/autoload.php">
<php>
<env name="APP_SECRET" value="6310772b1fdc3" />
<env name="APP_ENV" value="test" force="true" />
<env name="APP_DEBUG" value="1" force="true" />
<env name="SHELL_VERBOSITY" value="-1"/>
<!-- Offline OTel exporters so the functional boot test never touches the network. -->
<env name="OTEL_TRACES_EXPORTER" value="memory" />
<env name="OTEL_METRICS_EXPORTER" value="none" />
<env name="OTEL_LOGS_EXPORTER" value="none" />
</php>
<testsuites>
<testsuite name="unit">
Expand Down
6 changes: 0 additions & 6 deletions src/Tracing/Request/EventListener/AddUserEventSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,6 @@ protected function getUsername(UserInterface $user): string

private function getUser(TokenInterface $token): UserInterface|null
{
if (method_exists($token, 'isAuthenticated') && !$token->isAuthenticated(false)) {
dump('it exists');

return null;
}

return $token->getUser();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ private function getSpanForRequest(Request $request): SpanInterface

private function closeRequestScope(Request $request): void
{
if ($this->scopes->contains($request)) {
if ($this->scopes->offsetExists($request)) {
$this->scopes[$request]->detach();
}
}
Expand Down
106 changes: 106 additions & 0 deletions tests/Functional/BootTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

declare(strict_types=1);

/*
* This file is part of the worldia/instrumentation-bundle package.
* (c) Worldia <developers@worldia.com>
*/

namespace Tests\Instrumentation\Functional;

use Instrumentation\Metrics\AI\Platform\MeteringPlatform;
use Instrumentation\Tracing\AI\Platform\TracingPlatform;
use OpenTelemetry\API\Metrics\MeterProviderInterface;
use OpenTelemetry\API\Trace\TracerProviderInterface;
use Symfony\AI\Platform\PlatformInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Filesystem\Filesystem;
use Tests\Instrumentation\Functional\Stub\DummyPlatform;

/**
* Confirms the bundle boots inside a real Symfony kernel (container compiles,
* services resolve, AI platform decoration is applied). Runs against whichever
* Symfony major is installed, so it validates both the 7.4 and 8.x legs.
*/
final class BootTest extends KernelTestCase
{
protected function setUp(): void
{
// Force a fresh compile so this genuinely exercises DI compilation.
(new Filesystem())->remove(sys_get_temp_dir().'/instrumentation-bundle-tests');
}

protected static function getKernelClass(): string
{
return TestKernel::class;
}

public function testKernelBootsAndCompilesContainer(): void
{
self::bootKernel();

$container = self::getContainer();

$this->assertInstanceOf(TracerProviderInterface::class, $container->get(TracerProviderInterface::class));
$this->assertInstanceOf(MeterProviderInterface::class, $container->get(MeterProviderInterface::class));
}

public function testAiPlatformServiceIsDecorated(): void
{
self::bootKernel();

$platform = self::getContainer()->get('app.platform.openai');

$this->assertInstanceOf(PlatformInterface::class, $platform);
$this->assertNotInstanceOf(DummyPlatform::class, $platform);
$this->assertTrue(
$platform instanceof TracingPlatform || $platform instanceof MeteringPlatform,
'The ai.platform service should be decorated by the bundle AI platform decorators.',
);
}

/**
* Booting + compiling + instantiating the bundle's services must not trigger
* any deprecation originating from this package's own source (PHP or Symfony,
* including @-silenced ones). Deprecations from third-party vendors are ignored.
*/
public function testBootTriggersNoDeprecationsFromThisPackage(): void
{
$srcDir = realpath(\dirname(__DIR__, 2).'/src');
$deprecations = [];

$previous = set_error_handler(
static function (int $type, string $message, string $file = '', int $line = 0) use (&$deprecations, &$previous, $srcDir) {
if (\E_USER_DEPRECATED === $type || \E_DEPRECATED === $type) {
foreach (debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) {
if (isset($frame['file']) && str_starts_with($frame['file'], $srcDir)) {
$deprecations[] = \sprintf('%s (via %s:%d)', $message, $frame['file'], $frame['line'] ?? 0);
break;
}
}

return true;
}

return null !== $previous && ($previous)($type, $message, $file, $line);
}
);

try {
self::bootKernel();
$container = self::getContainer();
$container->get(TracerProviderInterface::class);
$container->get(MeterProviderInterface::class);
$container->get('app.platform.openai');
} finally {
restore_error_handler();
}

$this->assertSame([], $deprecations, \sprintf(
"Booting the bundle triggered %d deprecation(s) from its own code:\n- %s",
\count($deprecations),
implode("\n- ", $deprecations),
));
}
}
33 changes: 33 additions & 0 deletions tests/Functional/Stub/DummyPlatform.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

/*
* This file is part of the worldia/instrumentation-bundle package.
* (c) Worldia <developers@worldia.com>
*/

namespace Tests\Instrumentation\Functional\Stub;

use Symfony\AI\Platform\Model;
use Symfony\AI\Platform\ModelCatalog\ModelCatalogInterface;
use Symfony\AI\Platform\PlatformInterface;
use Symfony\AI\Platform\Result\DeferredResult;

/**
* Minimal `ai.platform` service used by the boot test so the AI compiler passes
* have a tagged service to decorate. Its methods are never invoked during the
* boot test (we only assert the container compiles and the decoration applies).
*/
final class DummyPlatform implements PlatformInterface
{
public function invoke(string|Model $model, array|string|object $input, array $options = []): DeferredResult
{
throw new \LogicException('DummyPlatform::invoke() is not meant to be called.');
}

public function getModelCatalog(): ModelCatalogInterface
{
throw new \LogicException('DummyPlatform::getModelCatalog() is not meant to be called.');
}
}
121 changes: 121 additions & 0 deletions tests/Functional/TestKernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

declare(strict_types=1);

/*
* This file is part of the worldia/instrumentation-bundle package.
* (c) Worldia <developers@worldia.com>
*/

namespace Tests\Instrumentation\Functional;

use Instrumentation\InstrumentationBundle;
use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as ContractsEventDispatcherInterface;
use Tests\Instrumentation\Functional\Stub\DummyPlatform;

/**
* Minimal kernel that boots FrameworkBundle + InstrumentationBundle so we can
* prove the bundle's DI container compiles and boots under the installed Symfony
* (7.4 or 8.x, depending on the CI leg), including the AI platform decoration.
*/
final class TestKernel extends Kernel
{
use MicroKernelTrait;

public function registerBundles(): iterable
{
yield new FrameworkBundle();
yield new InstrumentationBundle();
}

public function build(ContainerBuilder $container): void
{
// On Symfony 8, the core `event_dispatcher` service is provided by
// dependency-injection's ServicesBundle, which drops it when
// symfony/event-dispatcher is only a *dev* dependency of the root package
// (as it is inside this bundle, where framework-bundle is require-dev).
// A real consuming app requires framework-bundle normally, so this never
// happens there. Re-add it here so the boot test reflects real usage.
// No-op on Symfony 7.4, where event_dispatcher is always registered.
$container->addCompilerPass(new class implements CompilerPassInterface {
public function process(ContainerBuilder $container): void
{
if ($container->has('event_dispatcher') || !class_exists(EventDispatcher::class)) {
return;
}

$container->register('event_dispatcher', EventDispatcher::class)
->setPublic(true)
->addTag('container.hot_path')
->addTag('event_dispatcher.dispatcher', ['name' => 'event_dispatcher']);

foreach ([EventDispatcherInterface::class, ContractsEventDispatcherInterface::class, PsrEventDispatcherInterface::class] as $alias) {
if (interface_exists($alias)) {
$container->setAlias($alias, 'event_dispatcher');
}
}
}
}, PassConfig::TYPE_BEFORE_OPTIMIZATION, 100);
}

public function getCacheDir(): string
{
return sys_get_temp_dir().'/instrumentation-bundle-tests/cache/'.$this->environment;
}

public function getLogDir(): string
{
return sys_get_temp_dir().'/instrumentation-bundle-tests/log';
}

protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'test',
'test' => true,
'http_method_override' => false,
'handle_all_throwables' => true,
'php_errors' => ['log' => true],
'router' => ['utf8' => true],
// Required: the bundle always decorates serializer.normalizer.problem
// and the HttpClientInterface service when tracing is enabled.
'serializer' => ['enabled' => true],
'http_client' => ['enabled' => true],
]);

$container->extension('instrumentation', [
// Keep the boot minimal: logging would pull in monolog wiring.
'logging' => ['enabled' => false],
'tracing' => [
'enabled' => true,
'ai' => ['enabled' => true],
],
'metrics' => [
'enabled' => true,
'ai' => ['enabled' => true],
],
]);

// A stub service tagged `ai.platform` so the AI tracing/metrics compiler
// passes have a real service to decorate during container compilation.
$container->services()
->set('app.platform.openai', DummyPlatform::class)
->public()
->tag('ai.platform', ['name' => 'openai']);
}

protected function configureRoutes(RoutingConfigurator $routes): void
{
}
}
Loading