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

Code refactoring #100

Merged
merged 6 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
1. Adds feature tests for modules
2. Fixes some bugs with Sentry events
3. Fixes some bugs with inspector events
4. Updates RoadRunner version
5. Fixes some bugs with Ray events
  • Loading branch information
butschster committed Dec 1, 2023
commit 586c86c65f7ee6cb263055835bb82bef1aea4ed1
4 changes: 4 additions & 0 deletions app/config/broadcasting.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use App\Application\Broadcasting\InMemoryDriver;
use Spiral\Broadcasting\Driver\NullBroadcast;

return [
Expand All @@ -14,5 +15,8 @@
'null' => [
'driver' => NullBroadcast::class,
],
'in-memory' => [
'driver' => InMemoryDriver::class,
],
],
];
18 changes: 11 additions & 7 deletions app/config/cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,22 @@
declare(strict_types=1);

use Spiral\Cache\Storage\ArrayStorage;
use Spiral\Cache\Storage\FileStorage;

$defaultStorage = env('CACHE_DEFAULT_STORAGE', 'roadrunner');

return [
'default' => env('CACHE_STORAGE', 'local'),
'default' => env('CACHE_STORAGE', 'roadrunner'),
'aliases' => [
'events' => ['storage' => $defaultStorage, 'prefix' => 'events:'],
'local' => ['storage' => $defaultStorage, 'prefix' => 'local:'],
],
'storages' => [
'local' => [
'type' => 'roadrunner',
'driver' => 'local',
'array' => [
'type' => ArrayStorage::class,
],
'events' => [
'roadrunner' => [
'type' => 'roadrunner',
'driver' => 'events',
'driver' => 'local',
],
],
];
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,21 @@
namespace Modules\Events\Interfaces\Http\Controllers;

use App\Application\Commands\ClearEvents;
use App\Application\HTTP\Response\ResourceInterface;
use App\Application\HTTP\Response\SuccessResource;
use Modules\Events\Interfaces\Http\Request\ClearEventsRequest;
use Spiral\Cqrs\CommandBusInterface;
use Spiral\Router\Annotation\Route;

final class ClearEventsAction
final class ClearAction
{
#[Route(route: 'events', name: 'events.clear', methods: 'DELETE', group: 'api')]
public function __invoke(ClearEventsRequest $request, CommandBusInterface $bus): void
public function __invoke(ClearEventsRequest $request, CommandBusInterface $bus): ResourceInterface
{
$bus->dispatch(
new ClearEvents(type: $request->type)
new ClearEvents(type: $request->type),
);

return new SuccessResource();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,20 @@

use App\Application\Commands\DeleteEvent;
use App\Application\Domain\ValueObjects\Uuid;
use App\Application\HTTP\Response\ResourceInterface;
use App\Application\HTTP\Response\SuccessResource;
use Spiral\Cqrs\CommandBusInterface;
use Spiral\Router\Annotation\Route;

final class DeleteEventAction
final class DeleteAction
{
#[Route(route: 'event/<uuid>', name: 'event.delete', methods: 'DELETE', group: 'api')]
public function __invoke(CommandBusInterface $bus, Uuid $uuid): void
public function __invoke(CommandBusInterface $bus, Uuid $uuid): ResourceInterface
{
$bus->dispatch(
new DeleteEvent($uuid)
new DeleteEvent($uuid),
);

return new SuccessResource();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Application\Commands\FindEvents;
use Modules\Events\Interfaces\Http\Request\EventsRequest;
use Modules\Events\Interfaces\Http\Resources\EventCollection;
use Spiral\Cqrs\QueryBusInterface;
use Spiral\Router\Annotation\Route;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Application\Commands\FindEventByUuid;
use App\Application\Domain\ValueObjects\Uuid;
use App\Application\Exception\EntityNotFoundException;
use Modules\Events\Interfaces\Http\Resources\EventResource;
use Spiral\Cqrs\QueryBusInterface;
use Spiral\Http\Exception\ClientException\NotFoundException;
use Spiral\Router\Annotation\Route;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

namespace Modules\Events\Interfaces\Http\Request;

use Spiral\Filters\Attribute\Input\Post;
use Spiral\Filters\Attribute\Input\Data;
use Spiral\Filters\Model\Filter;
use Spiral\Filters\Model\FilterDefinitionInterface;
use Spiral\Filters\Model\HasFilterDefinition;
use Spiral\Validator\FilterDefinition;

final class ClearEventsRequest extends Filter implements HasFilterDefinition
{
#[Post]
#[Data]
public ?string $type = null;

public function filterDefinition(): FilterDefinitionInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Modules\Events\Interfaces\Http\Controllers;
namespace Modules\Events\Interfaces\Http\Resources;

use App\Application\HTTP\Response\ResourceCollection;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

declare(strict_types=1);

namespace Modules\Events\Interfaces\Http\Controllers;
namespace Modules\Events\Interfaces\Http\Resources;

use App\Application\HTTP\Response\JsonResource;
use Modules\Events\Domain\Event;
use Psr\Http\Message\ServerRequestInterface;

/**
* @property-read Event $data
Expand All @@ -18,7 +17,7 @@ public function __construct(Event $data)
parent::__construct($data);
}

protected function mapData(ServerRequestInterface $request): array|\JsonSerializable
protected function mapData(): array|\JsonSerializable
{
return [
'uuid' => (string)$this->data->getUuid(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function handle(ServerRequestInterface $request, \Closure $next): Respons
$event = $this->handler->handle($payload);

$this->commands->dispatch(
new HandleReceivedEvent(type: 'http-dump', payload: $event)
new HandleReceivedEvent(type: 'http-dump', payload: $event),
);

return $this->responseWrapper->create(200);
Expand All @@ -77,7 +77,7 @@ private function createPayload(ServerRequestInterface $request): array
function (UploadedFileInterface $attachment) use ($id) {
$this->bucket->write(
$filename = $id . '/' . $attachment->getClientFilename(),
$attachment->getStream()
$attachment->getStream(),
);

return [
Expand All @@ -88,9 +88,9 @@ function (UploadedFileInterface $attachment) use ($id) {
'mime' => $attachment->getClientMediaType(),
];
},
$request->getUploadedFiles()
$request->getUploadedFiles(),
),
]
],
];
}
}
13 changes: 9 additions & 4 deletions app/modules/Inspector/Interfaces/Http/Handler/EventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,17 @@ public function handle(ServerRequestInterface $request, \Closure $next): Respons
?? throw new ClientException\BadRequestException('Invalid data');

$type = $data[0]['type'] ?? 'unknown';
if ($type !== 'request') {
throw new ClientException\BadRequestException('Invalid data');
}

$data = match ($type) {
'process',
'request' => $data,
default => throw new ClientException\BadRequestException(
\sprintf('Invalid type "%s". [%s] expected.', $type, \implode(', ', ['process', 'request'])),
),
};

$this->commands->dispatch(
new HandleReceivedEvent(type: 'inspector', payload: $data)
new HandleReceivedEvent(type: 'inspector', payload: $data),
);

return $this->responseWrapper->create(200);
Expand Down
11 changes: 7 additions & 4 deletions app/modules/Ray/Interfaces/Http/Handler/EventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@ private function handleEvent(ServerRequestInterface $request): ResponseInterface
$this->cache->set($hash, 1, CarbonInterval::minute(5));
} elseif ($type === TypeEnum::ClearAll->value) {
$this->commands->dispatch(new ClearEvents(type: 'ray'));
return $this->responseWrapper->create(200);
}

$event = $this->handler->handle($event);

$this->commands->dispatch(
new HandleReceivedEvent(
type: 'ray', payload: $event, uuid: Uuid::fromString($event['uuid'])
)
type: 'ray', payload: $event, uuid: Uuid::fromString($event['uuid']),
),
);

return $this->responseWrapper->create(200);
Expand All @@ -86,9 +87,11 @@ private function handleLocks(ServerRequestInterface $request): ResponseInterface

private function isValidRequest(ServerRequestInterface $request): bool
{
$userAgent = $request->getServerParams()['HTTP_USER_AGENT'] ?? '';

return $request->getHeaderLine('X-Buggregator-Event') === 'ray'
|| $request->getAttribute('event-type') === 'ray'
|| \str_starts_with($request->getUri()->getPath(), 'Ray')
|| $request->getUri()->getUserInfo() === 'ray';
|| $request->getUri()->getUserInfo() === 'ray'
|| \str_starts_with($userAgent, 'Ray');
}
}
37 changes: 37 additions & 0 deletions app/modules/Sentry/Application/PayloadParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace Modules\Sentry\Application;

use App\Application\HTTP\GzippedStreamFactory;
use Psr\Http\Message\ServerRequestInterface;

final class PayloadParser
{
public function __construct(
private readonly GzippedStreamFactory $gzippedStreamFactory,
) {
}

public function parse(ServerRequestInterface $request): array
{
$isV4 = $request->getHeaderLine('Content-Type') === 'application/x-sentry-envelope' ||
\str_contains($request->getHeaderLine('X-Sentry-Auth'), 'sentry.php/4');

if ($isV4) {
if ($request->getHeaderLine('Content-Encoding') === 'gzip') {
return \iterator_to_array($this->gzippedStreamFactory->createFromRequest($request)->getPayload());
}

$payloads = \explode("\n", (string)$request->getBody());

return \array_map(
static fn(string $payload): array => \json_decode($payload, true),
\array_filter($payloads),
);
}

return [$request->getParsedBody()];
}
}
26 changes: 10 additions & 16 deletions app/modules/Sentry/Interfaces/Http/Handler/EventHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
namespace Modules\Sentry\Interfaces\Http\Handler;

use App\Application\Commands\HandleReceivedEvent;
use App\Application\HTTP\GzippedStreamFactory;
use App\Application\Service\HttpHandler\HandlerInterface;
use Modules\Sentry\Application\EventHandlerInterface;
use Modules\Sentry\Application\PayloadParser;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Cqrs\CommandBusInterface;
Expand All @@ -16,7 +16,7 @@
final class EventHandler implements HandlerInterface
{
public function __construct(
private readonly GzippedStreamFactory $gzippedStreamFactory,
private readonly PayloadParser $payloadParser,
private readonly ResponseWrapper $responseWrapper,
private readonly EventHandlerInterface $handler,
private readonly CommandBusInterface $commands,
Expand All @@ -35,7 +35,8 @@ public function handle(ServerRequestInterface $request, \Closure $next): Respons
}

$url = \rtrim($request->getUri()->getPath(), '/');
$payloads = $this->gzippedStreamFactory->createFromRequest($request)->getPayload();

$payloads = $this->payloadParser->parse($request);

match (true) {
\str_ends_with($url, '/envelope') => $this->handleEnvelope($payloads),
Expand All @@ -46,42 +47,35 @@ public function handle(ServerRequestInterface $request, \Closure $next): Respons
return $this->responseWrapper->create(200);
}

private function handleEvent(\Traversable $data): void
private function handleEvent(array $data): void
{
$data = \iterator_to_array($data);

$event = $this->handler->handle($data[0]);

$this->commands->dispatch(
new HandleReceivedEvent(type: 'sentry', payload: $event)
new HandleReceivedEvent(type: 'sentry', payload: $event),
);
}

/**
* TODO handle sentry transaction and session
*/
private function handleEnvelope(\Traversable $data): void
private function handleEnvelope(array $data): void
{
$data = \iterator_to_array($data);

if (\count($data) == 3) {
match ($data[1]['type']) {
'transaction' => null,
'session' => null,
'event' => $this->handleEvent([$data[2]]),
default => null,
};
}
}

private function isValidRequest(ServerRequestInterface $request): bool
{
if ($request->getHeaderLine('Content-Encoding') !== 'gzip') {
return false;
}

return $request->getHeaderLine('X-Buggregator-Event') === 'sentry'
|| $request->getAttribute('event-type') === 'sentry'
|| $request->hasHeader('X-Sentry-Auth')
|| $request->getUri()->getUserInfo() === 'sentry'
|| (string)$request->getUri() === 'profiler/store';
|| $request->getUri()->getUserInfo() === 'sentry';
}
}
6 changes: 2 additions & 4 deletions app/src/Application/Bootloader/RoutesBootloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@

namespace App\Application\Bootloader;

use App\Application\Service\HttpHandler\CoreHandlerInterface;
use App\Interfaces\Http\EventHandlerAction;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Bootloader\Http\RoutesBootloader as BaseRoutesBootloader;
use Spiral\Filter\ValidationHandlerMiddleware;
use Spiral\Http\Middleware\ErrorHandlerMiddleware;
use Spiral\Http\Middleware\JsonPayloadMiddleware;
use Spiral\Router\Bootloader\AnnotatedRoutesBootloader;
use Spiral\Router\GroupRegistry;
use Spiral\Router\Loader\Configurator\RoutingConfigurator;
Expand All @@ -25,6 +22,7 @@ final class RoutesBootloader extends BaseRoutesBootloader
protected function globalMiddleware(): array
{
return [
JsonPayloadMiddleware::class,
ErrorHandlerMiddleware::class,
ValidationHandlerMiddleware::class,
];
Expand Down
Loading