Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] Add base for profiler #27

Merged
merged 19 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from 10 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
6 changes: 5 additions & 1 deletion .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
<?php

$finder = (new PhpCsFixer\Finder())
->in(__DIR__)
->in([
__DIR__ . '/config',
Neirda24 marked this conversation as resolved.
Show resolved Hide resolved
__DIR__ . '/src',
__DIR__ . '/tests',
])
;

return (new PhpCsFixer\Config())
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"phpstan/phpstan-symfony": "^1.3",
"phpunit/phpunit": "^10.4",
"symfony/framework-bundle": "^6.4 || ^7.0",
"symfony/twig-bundle": "^6.4 || ^7.0"
"symfony/twig-bundle": "^6.4 || ^7.0",
"symfony/stopwatch": "^6.4 || ^7.0"
},
"config": {
"allow-plugins": {
Expand Down
29 changes: 29 additions & 0 deletions config/debug.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

use Sensiolabs\GotenbergBundle\DataCollector\GotenbergDataCollector;
use Sensiolabs\GotenbergBundle\Debug\TraceableGotenberg;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Reference;
use function Symfony\Component\DependencyInjection\Loader\Configurator\abstract_arg;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
use function Symfony\Component\DependencyInjection\Loader\Configurator\tagged_locator;

return static function (ContainerConfigurator $container): void {
$services = $container->services();

$services->set('sensiolabs_gotenberg.traceable', TraceableGotenberg::class)
->decorate('sensiolabs_gotenberg')
->args([
new Reference('.inner'),
])
;

$services->set('sensiolabs_gotenberg.data_collector', GotenbergDataCollector::class)
->args([
service('sensiolabs_gotenberg'),
tagged_locator('sensiolabs_gotenberg.builder'),
abstract_arg('All default options will be set through the configuration.'),
])
->tag('data_collector', ['template' => '@SensiolabsGotenberg/Collector/sensiolabs_gotenberg.html.twig', 'id' => 'sensiolabs_gotenberg'])
;
};
2 changes: 1 addition & 1 deletion config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
use function Symfony\Component\DependencyInjection\Loader\Configurator\tagged_locator;

return function (ContainerConfigurator $container): void {
return static function (ContainerConfigurator $container): void {
$services = $container->services();

$services->set('sensiolabs_gotenberg.client', GotenbergClient::class)
Expand Down
2 changes: 1 addition & 1 deletion src/Builder/AbstractPdfBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ abstract class AbstractPdfBuilder implements PdfBuilderInterface
*/
protected array $formFields = [];

private string|null $fileName = null;
private ?string $fileName = null;
Jean-Beru marked this conversation as resolved.
Show resolved Hide resolved

private string $headerDisposition = HeaderUtils::DISPOSITION_INLINE;

Expand Down
116 changes: 116 additions & 0 deletions src/DataCollector/GotenbergDataCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?php

declare(strict_types=1);

namespace Sensiolabs\GotenbergBundle\DataCollector;

use Sensiolabs\GotenbergBundle\Builder\PdfBuilderInterface;
use Sensiolabs\GotenbergBundle\Debug\Builder\TraceablePdfBuilder;
use Sensiolabs\GotenbergBundle\Debug\TraceableGotenberg;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
use Symfony\Component\VarDumper\Cloner\Data;

final class GotenbergDataCollector extends DataCollector implements LateDataCollectorInterface
{
/**
* @param ServiceLocator<PdfBuilderInterface> $builders
*/
public function __construct(
private readonly TraceableGotenberg $traceableGotenberg,
private readonly ServiceLocator $builders,
private readonly array $defaultOptions,
) {
}

public function collect(Request $request, Response $response, ?\Throwable $exception = null): void
{
$this->data['request_total_memory'] = 0;
$this->data['request_total_time'] = 0;
$this->data['request_count'] = 0;
Neirda24 marked this conversation as resolved.
Show resolved Hide resolved
$this->data['builders'] = [];

foreach ($this->builders->getProvidedServices() as $id => $type) {
$builder = $this->builders->get($id);

if ($builder instanceof TraceablePdfBuilder) {
$builder = $builder->getInner();
}

if (\str_starts_with($id, '.sensiolabs_gotenberg.builder.')) {
[$id] = \sscanf($id, '.sensiolabs_gotenberg.builder.%s');
}

$this->data['builders'][$id] = [
'class' => $builder::class,
'default_options' => $this->defaultOptions[$id] ?? [],
'pdfs' => [],
];
}
}

public function getName(): string
{
return 'sensiolabs_gotenberg';
}

public function lateCollect(): void
{
/**
* @var string $id
* @var TraceablePdfBuilder $builder
*/
foreach ($this->traceableGotenberg->getBuilders() as [$id, $builder]) {
$this->data['builders'][$id]['pdfs'] = array_merge($this->data['builders'][$id]['pdfs'], array_map(function (array $request): array {
$request['calls'] = array_map(function (array $call): array {
return array_merge($call, ['stub' => $this->cloneVar($call['stub'])]);
}, $request['calls']);

$this->data['request_total_time'] += $request['time'];
$this->data['request_total_memory'] += $request['memory'];

return $request;
}, $builder->getPdfs()));

$this->data['request_count'] += \count($builder->getPdfs());
}
}

/**
* @return array<string, array{
* 'class': string,
* 'default_options': array<mixed>,
* 'pdfs': list<array{
* 'time': float,
* 'fileName': string,
* 'calls': list<array{
* 'method': string,
* 'arguments': array<mixed>,
Neirda24 marked this conversation as resolved.
Show resolved Hide resolved
* 'stub': Data
* }>
* }>
* }>
*/
public function getBuilders(): array
{
return $this->data['builders'] ?? [];
}

public function getRequestCount(): int
{
return $this->data['request_count'] ?? 0;
}

public function getRequestTotalTime(): int|float
{
return $this->data['request_total_time'] ?? 0.0;
}

public function getRequestTotalMemory(): int
{
return $this->data['request_total_memory'] ?? 0;
}
}
96 changes: 96 additions & 0 deletions src/Debug/Builder/TraceablePdfBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

namespace Sensiolabs\GotenbergBundle\Debug\Builder;

use Sensiolabs\GotenbergBundle\Builder\PdfBuilderInterface;
use Sensiolabs\GotenbergBundle\Client\PdfResponse;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\VarDumper\Caster\ArgsStub;
use Symfony\Component\VarDumper\Cloner\Stub;

final class TraceablePdfBuilder implements PdfBuilderInterface
{
/**
* @var list<array{'time': float, 'memory': int, 'fileName': string, 'calls': list<array{'method': string, 'arguments': array<mixed>, 'stub': Stub}>}>
*/
private array $pdfs = [];

/**
* @var list<array{'method': string, 'arguments': array<mixed>, 'stub': Stub}>
*/
private array $calls = [];

private int $totalGenerated = 0;

private static int $count = 0;

public function __construct(
private readonly PdfBuilderInterface $inner,
private readonly Stopwatch $stopwatch,
) {
}

public function generate(): PdfResponse
{
$name = self::$count.'.'.$this->inner::class.'::'.__FUNCTION__;
++self::$count;

$swEvent = $this->stopwatch->start($name, 'gotenberg.generate_pdf');
$response = $this->inner->generate();
$swEvent->stop();

$fileName = 'Unknown.pdf';
if ($response->headers->has('Content-Disposition')) {
$matches = [];

preg_match('#[^;]*;\sfilename="?(?P<fileName>[^"]*)"?#', $response->headers->get('Content-Disposition', ''), $matches);
Jean-Beru marked this conversation as resolved.
Show resolved Hide resolved
$fileName = $matches['fileName'];
}

$this->pdfs[] = [
'calls' => $this->calls,
'time' => $swEvent->getDuration(),
'memory' => $swEvent->getMemory(),
'fileName' => $fileName,
];

++$this->totalGenerated;

return $response;
}

/**
* @param array<mixed> $arguments
*/
public function __call(string $name, array $arguments): mixed
{
$result = $this->inner->$name(...$arguments);

$this->calls[] = [
'method' => $name,
'arguments' => $arguments,
'stub' => new ArgsStub($arguments, $name, $this->inner::class),
Neirda24 marked this conversation as resolved.
Show resolved Hide resolved
];

if ($result === $this->inner) {
return $this;
}

return $result;
}

/**
* @return list<array{'time': float, 'memory': int, 'fileName': string, 'calls': list<array{'method': string, 'arguments': array<mixed>, 'stub': Stub}>}>
*/
public function getPdfs(): array
{
return $this->pdfs;
}

public function getInner(): PdfBuilderInterface
{
return $this->inner;
}
}
Loading