Refactor point value object and add observability
This commit is contained in:
+24
@@ -35,3 +35,27 @@ DATABASE_URL="sqlite:///%kernel.project_dir%/var/points.sqlite"
|
||||
###> nelmio/cors-bundle ###
|
||||
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
|
||||
###< nelmio/cors-bundle ###
|
||||
|
||||
###> symfony/mercure-bundle ###
|
||||
# See https://symfony.com/doc/current/mercure.html#configuration
|
||||
# The URL of the Mercure hub, used by the app to publish updates (can be a local URL)
|
||||
MERCURE_URL=http://mercure:3000/.well-known/mercure
|
||||
# The public URL of the Mercure hub, used by the browser to connect
|
||||
MERCURE_PUBLIC_URL=http://localhost:3000/.well-known/mercure
|
||||
# The secret used to sign the JWTs
|
||||
MERCURE_JWT_SECRET="!ChangeThisMercureHubJWTSecretKey!"
|
||||
# Topic used for live signal updates
|
||||
MERCURE_SIGNALS_TOPIC=https://points-of-interest.local/signals
|
||||
###< symfony/mercure-bundle ###
|
||||
|
||||
###> symfony/messenger ###
|
||||
# Choose one of the transports below
|
||||
# MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
|
||||
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
|
||||
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
|
||||
###< symfony/messenger ###
|
||||
|
||||
###> sentry/sentry-symfony ###
|
||||
# Provide the DSN when deploying to production to enable error tracking
|
||||
SENTRY_DSN=
|
||||
###< sentry/sentry-symfony ###
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
|
||||
services:
|
||||
###> symfony/mercure-bundle ###
|
||||
mercure:
|
||||
ports:
|
||||
- "3000:80"
|
||||
###< symfony/mercure-bundle ###
|
||||
@@ -0,0 +1,30 @@
|
||||
|
||||
services:
|
||||
###> symfony/mercure-bundle ###
|
||||
mercure:
|
||||
image: dunglas/mercure
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
SERVER_NAME: ':80'
|
||||
MERCURE_PUBLISHER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
|
||||
MERCURE_SUBSCRIBER_JWT_KEY: '!ChangeThisMercureHubJWTSecretKey!'
|
||||
# Set the URL of your Symfony project (without trailing slash!) as value of the cors_origins directive
|
||||
MERCURE_EXTRA_DIRECTIVES: |
|
||||
cors_origins http://127.0.0.1:8000 http://localhost:8000 http://localhost:5173 http://127.0.0.1:5173
|
||||
# Comment the following line to disable the development mode
|
||||
command: /usr/bin/caddy run --config /etc/caddy/dev.Caddyfile
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "https://localhost/healthz"]
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 60s
|
||||
volumes:
|
||||
- mercure_data:/data
|
||||
- mercure_config:/config
|
||||
###< symfony/mercure-bundle ###
|
||||
|
||||
volumes:
|
||||
###> symfony/mercure-bundle ###
|
||||
mercure_data:
|
||||
mercure_config:
|
||||
###< symfony/mercure-bundle ###
|
||||
@@ -13,14 +13,21 @@
|
||||
"doctrine/doctrine-migrations-bundle": "^3.4",
|
||||
"doctrine/orm": "^3.5",
|
||||
"nelmio/cors-bundle": "^2.5",
|
||||
"sentry/sentry-symfony": "^5.6",
|
||||
"symfony/console": "7.3.*",
|
||||
"symfony/dotenv": "7.3.*",
|
||||
"symfony/flex": "^2",
|
||||
"symfony/framework-bundle": "7.3.*",
|
||||
"symfony/http-client": "^7.3",
|
||||
"symfony/mercure-bundle": "^0.3.9",
|
||||
"symfony/messenger": "^7.3",
|
||||
"symfony/monolog-bundle": "^3.10",
|
||||
"symfony/property-access": "7.3.*",
|
||||
"symfony/property-info": "7.3.*",
|
||||
"symfony/rate-limiter": "^7.3",
|
||||
"symfony/runtime": "7.3.*",
|
||||
"symfony/serializer": "^7.3",
|
||||
"symfony/validator": "^7.3",
|
||||
"symfony/yaml": "7.3.*"
|
||||
},
|
||||
"config": {
|
||||
|
||||
Generated
+2077
-1
File diff suppressed because it is too large
Load Diff
@@ -6,4 +6,7 @@ return [
|
||||
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
|
||||
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
|
||||
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
|
||||
Symfony\Bundle\MercureBundle\MercureBundle::class => ['all' => true],
|
||||
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
|
||||
Sentry\SentryBundle\SentryBundle::class => ['prod' => true],
|
||||
];
|
||||
|
||||
@@ -24,6 +24,12 @@ doctrine:
|
||||
dir: '%kernel.project_dir%/src/Entity'
|
||||
prefix: 'App\Entity'
|
||||
alias: App
|
||||
AppValueObject:
|
||||
type: attribute
|
||||
is_bundle: false
|
||||
dir: '%kernel.project_dir%/src/ValueObject'
|
||||
prefix: 'App\ValueObject'
|
||||
alias: AppValueObject
|
||||
controller_resolver:
|
||||
auto_mapping: false
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
mercure:
|
||||
hubs:
|
||||
default:
|
||||
url: '%env(MERCURE_URL)%'
|
||||
public_url: '%env(MERCURE_PUBLIC_URL)%'
|
||||
jwt:
|
||||
secret: '%env(MERCURE_JWT_SECRET)%'
|
||||
publish: '*'
|
||||
@@ -0,0 +1,18 @@
|
||||
framework:
|
||||
messenger:
|
||||
# Uncomment this (and the failed transport below) to send failed messages to this transport for later handling.
|
||||
# failure_transport: failed
|
||||
|
||||
transports:
|
||||
sync: 'sync://'
|
||||
|
||||
routing:
|
||||
App\Message\SignalCreatedMessage: sync
|
||||
|
||||
# when@test:
|
||||
# framework:
|
||||
# messenger:
|
||||
# transports:
|
||||
# # replace with your transport name here (e.g., my_transport: 'in-memory://')
|
||||
# # For more Messenger testing tools, see https://github.com/zenstruck/messenger-test
|
||||
# async: 'in-memory://'
|
||||
@@ -0,0 +1,79 @@
|
||||
monolog:
|
||||
channels:
|
||||
- deprecation # Deprecations are logged in the dedicated "deprecation" channel when it exists
|
||||
- signals
|
||||
|
||||
when@dev:
|
||||
monolog:
|
||||
handlers:
|
||||
main:
|
||||
type: stream
|
||||
path: "%kernel.logs_dir%/%kernel.environment%.log"
|
||||
level: debug
|
||||
channels: ["!event"]
|
||||
signals:
|
||||
type: stream
|
||||
path: "%kernel.logs_dir%/signals_%kernel.environment%.log"
|
||||
level: debug
|
||||
channels: [signals]
|
||||
# uncomment to get logging in your browser
|
||||
# you may have to allow bigger header sizes in your Web server configuration
|
||||
#firephp:
|
||||
# type: firephp
|
||||
# level: info
|
||||
#chromephp:
|
||||
# type: chromephp
|
||||
# level: info
|
||||
console:
|
||||
type: console
|
||||
process_psr_3_messages: false
|
||||
channels: ["!event", "!doctrine", "!console"]
|
||||
|
||||
when@test:
|
||||
monolog:
|
||||
handlers:
|
||||
main:
|
||||
type: fingers_crossed
|
||||
action_level: error
|
||||
handler: nested
|
||||
excluded_http_codes: [404, 405]
|
||||
channels: ["!event"]
|
||||
nested:
|
||||
type: stream
|
||||
path: "%kernel.logs_dir%/%kernel.environment%.log"
|
||||
level: debug
|
||||
signals:
|
||||
type: stream
|
||||
path: "%kernel.logs_dir%/signals_%kernel.environment%.log"
|
||||
level: debug
|
||||
channels: [signals]
|
||||
|
||||
when@prod:
|
||||
monolog:
|
||||
handlers:
|
||||
main:
|
||||
type: stream
|
||||
path: php://stderr
|
||||
level: info
|
||||
formatter: monolog.formatter.json
|
||||
channels: ["!event"]
|
||||
signals:
|
||||
type: stream
|
||||
path: php://stderr
|
||||
level: info
|
||||
formatter: monolog.formatter.json
|
||||
channels: [signals]
|
||||
sentry:
|
||||
type: sentry
|
||||
level: error
|
||||
hub_id: sentry
|
||||
channels: ["!event", "!doctrine", "!console"]
|
||||
console:
|
||||
type: console
|
||||
process_psr_3_messages: false
|
||||
channels: ["!event", "!doctrine"]
|
||||
deprecation:
|
||||
type: stream
|
||||
channels: [deprecation]
|
||||
path: php://stderr
|
||||
formatter: monolog.formatter.json
|
||||
@@ -0,0 +1,6 @@
|
||||
sentry:
|
||||
dsn: '%env(SENTRY_DSN)%'
|
||||
register_error_listener: true
|
||||
options:
|
||||
environment: '%kernel.environment%'
|
||||
traces_sample_rate: 0.0
|
||||
@@ -0,0 +1,8 @@
|
||||
framework:
|
||||
rate_limiter:
|
||||
signal_submission:
|
||||
policy: 'token_bucket'
|
||||
limit: 5
|
||||
rate:
|
||||
interval: '1 minute'
|
||||
amount: 1
|
||||
@@ -0,0 +1,11 @@
|
||||
framework:
|
||||
validation:
|
||||
# Enables validator auto-mapping support.
|
||||
# For instance, basic validation constraints will be inferred from Doctrine's metadata.
|
||||
#auto_mapping:
|
||||
# App\Entity\: []
|
||||
|
||||
when@test:
|
||||
framework:
|
||||
validation:
|
||||
not_compromised_password: false
|
||||
@@ -4,6 +4,9 @@
|
||||
# Put parameters here that don't need to change on each machine where the app is deployed
|
||||
# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration
|
||||
parameters:
|
||||
app.signal_snapshot_limit: 750
|
||||
app.max_signal_distance_km: 1
|
||||
app.signal_stream_topic: '%env(string:MERCURE_SIGNALS_TOPIC)%'
|
||||
|
||||
services:
|
||||
# default configuration for services in *this* file
|
||||
@@ -23,3 +26,4 @@ services:
|
||||
|
||||
# add more service definitions when explicit configuration is needed
|
||||
# please note that last definitions always *replace* previous ones
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20251010102708 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Split signal coordinates into user and signal embeddables';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE __temp__signals (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_key VARCHAR(64) NOT NULL, created_at DATETIME NOT NULL, user_lat DOUBLE PRECISION NOT NULL, user_lng DOUBLE PRECISION NOT NULL, signal_lat DOUBLE PRECISION NOT NULL, signal_lng DOUBLE PRECISION NOT NULL)');
|
||||
$this->addSql('INSERT INTO __temp__signals (id, user_key, created_at, user_lat, user_lng, signal_lat, signal_lng) SELECT id, user_key, created_at, lat, lng, lat, lng FROM signals');
|
||||
$this->addSql('DROP TABLE signals');
|
||||
$this->addSql('ALTER TABLE __temp__signals RENAME TO signals');
|
||||
$this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
|
||||
$this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE __temp__signals (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_key VARCHAR(64) NOT NULL, lat DOUBLE PRECISION NOT NULL, lng DOUBLE PRECISION NOT NULL, created_at DATETIME NOT NULL)');
|
||||
$this->addSql('INSERT INTO __temp__signals (id, user_key, lat, lng, created_at) SELECT id, user_key, signal_lat, signal_lng, created_at FROM signals');
|
||||
$this->addSql('DROP TABLE signals');
|
||||
$this->addSql('ALTER TABLE __temp__signals RENAME TO signals');
|
||||
$this->addSql('CREATE INDEX idx_signals_created_at ON signals (created_at)');
|
||||
$this->addSql('CREATE INDEX idx_signals_user_key ON signals (user_key)');
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,13 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Dto\SignalPayload;
|
||||
use App\Entity\Signal;
|
||||
use App\Repository\SignalRepository;
|
||||
use App\Service\SignalSnapshotBuilder;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use App\Payload\SignalPayload;
|
||||
use App\Service\ClientKeyProvider;
|
||||
use App\Service\SignalSnapshotService;
|
||||
use App\Service\SignalSubmissionService;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
|
||||
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
@@ -20,104 +19,46 @@ use Symfony\Component\Routing\Annotation\Route;
|
||||
class SignalController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SignalRepository $signals,
|
||||
private readonly SignalSnapshotBuilder $snapshotBuilder,
|
||||
private readonly SignalSnapshotService $snapshotService,
|
||||
private readonly SignalSubmissionService $submissionService,
|
||||
private readonly ClientKeyProvider $clientKeyProvider,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route(path: '', name: 'api_signals_index', methods: ['GET'])]
|
||||
public function index(Request $request, #[MapQueryParameter('limit', flags: FILTER_NULL_ON_FAILURE)] ?int $limit = null): JsonResponse
|
||||
{
|
||||
$limit = $this->normalizeLimit($limit);
|
||||
$clientKey = $this->clientKeyProvider->fromRequest($request);
|
||||
$snapshot = $this->snapshotService->buildSnapshot($limit, $clientKey);
|
||||
|
||||
$clientKey = $this->hashIp($this->extractClientIp($request));
|
||||
|
||||
$signals = $this->signals->findRecent($limit);
|
||||
$snapshot = $this->snapshotBuilder->build($signals);
|
||||
|
||||
$payload = [
|
||||
'clientKey' => $clientKey,
|
||||
'points' => $snapshot['points'],
|
||||
'density' => $snapshot['density'],
|
||||
'latestByUser' => $snapshot['latestByUser'],
|
||||
'totals' => $snapshot['totals'],
|
||||
'updatedAt' => new DateTimeImmutable('now', new DateTimeZone('UTC'))->format(DATE_ATOM),
|
||||
];
|
||||
|
||||
return new JsonResponse($payload);
|
||||
return new JsonResponse($snapshot);
|
||||
}
|
||||
|
||||
#[Route(path: '', name: 'api_signals_store', methods: ['POST'])]
|
||||
public function store(#[MapRequestPayload(validationFailedStatusCode: JsonResponse::HTTP_UNPROCESSABLE_ENTITY)] SignalPayload $payload, Request $request): JsonResponse
|
||||
public function store(Request $request, #[MapRequestPayload] SignalPayload $payload): JsonResponse
|
||||
{
|
||||
$lat = $payload->lat;
|
||||
$lng = $payload->lng;
|
||||
$clientKey = $this->clientKeyProvider->fromRequest($request);
|
||||
$signal = $this->submissionService->submit($clientKey, $payload);
|
||||
|
||||
if (! is_finite($lat) || ! is_finite($lng)) {
|
||||
return $this->errorResponse('invalid_coordinates', 'Latitude and longitude must be numbers.', JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
|
||||
return $this->errorResponse('out_of_bounds', 'Latitude or longitude out of range.', JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
$clientIp = $this->extractClientIp($request);
|
||||
$clientKey = $this->hashIp($clientIp);
|
||||
|
||||
$signal = new Signal()
|
||||
->setUserKey($clientKey)
|
||||
->setLat($lat)
|
||||
->setLng($lng)
|
||||
->setCreatedAt(new DateTimeImmutable('now', new DateTimeZone('UTC')));
|
||||
|
||||
$this->signals->save($signal);
|
||||
$signalLocation = $signal->getSignalLocation();
|
||||
$userLocation = $signal->getUserLocation();
|
||||
|
||||
return new JsonResponse([
|
||||
'status' => 'stored',
|
||||
'clientKey' => $clientKey,
|
||||
'point' => [
|
||||
'id' => $signal->getId(),
|
||||
'lat' => $signal->getLat(),
|
||||
'lng' => $signal->getLng(),
|
||||
'signalLocation' => [
|
||||
'lat' => $signalLocation->getLat(),
|
||||
'lng' => $signalLocation->getLng(),
|
||||
],
|
||||
'userLocation' => [
|
||||
'lat' => $userLocation->getLat(),
|
||||
'lng' => $userLocation->getLng(),
|
||||
],
|
||||
'createdAt' => $signal->getCreatedAt()->format(DATE_ATOM),
|
||||
'userKey' => $signal->getUserKey(),
|
||||
],
|
||||
], JsonResponse::HTTP_CREATED);
|
||||
}
|
||||
|
||||
private function errorResponse(string $error, string $message, int $statusCode): JsonResponse
|
||||
{
|
||||
return new JsonResponse([
|
||||
'error' => $error,
|
||||
'message' => $message,
|
||||
], $statusCode);
|
||||
}
|
||||
|
||||
private function normalizeLimit(?int $limit): int
|
||||
{
|
||||
$limit ??= 750;
|
||||
if ($limit < 1 || $limit > 5000) {
|
||||
return 750;
|
||||
}
|
||||
|
||||
return $limit;
|
||||
}
|
||||
|
||||
private function extractClientIp(Request $request): string
|
||||
{
|
||||
$forwarded = $request->headers->get('X-Forwarded-For');
|
||||
if ($forwarded !== null && $forwarded !== '') {
|
||||
$parts = array_filter(array_map('trim', explode(',', $forwarded)));
|
||||
if ($parts !== []) {
|
||||
return $parts[0];
|
||||
}
|
||||
}
|
||||
|
||||
return $request->getClientIp() ?? '0.0.0.0';
|
||||
}
|
||||
|
||||
private function hashIp(string $ip): string
|
||||
{
|
||||
return substr(hash('sha256', $ip), 0, 12);
|
||||
], Response::HTTP_CREATED);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\DataFixtures;
|
||||
|
||||
use App\ValueObject\Point;
|
||||
use App\Entity\Signal;
|
||||
use DateInterval;
|
||||
use DateTimeImmutable;
|
||||
@@ -38,10 +39,12 @@ class SignalFixtures extends Fixture
|
||||
];
|
||||
|
||||
foreach ($coordinates as $config) {
|
||||
$signalLocation = Point::fromLatLng($config['lat'], $config['lng']);
|
||||
|
||||
$signal = new Signal()
|
||||
->setUserKey($config['user'])
|
||||
->setLat($config['lat'])
|
||||
->setLng($config['lng'])
|
||||
->setUserLocation(Point::fromLatLng($config['lat'], $config['lng']))
|
||||
->setSignalLocation($signalLocation)
|
||||
->setCreatedAt($baseTime->add(new DateInterval(sprintf('PT%dM', $config['offset']))));
|
||||
|
||||
$manager->persist($signal);
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Dto;
|
||||
|
||||
final readonly class SignalPayload
|
||||
{
|
||||
public function __construct(
|
||||
public float $lat,
|
||||
public float $lng,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Repository\SignalRepository;
|
||||
use App\ValueObject\Point;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
@@ -23,11 +24,11 @@ class Signal
|
||||
#[ORM\Column(type: Types::STRING, length: 64)]
|
||||
private string $userKey;
|
||||
|
||||
#[ORM\Column(type: Types::FLOAT)]
|
||||
private float $lat;
|
||||
#[ORM\Embedded(class: Point::class, columnPrefix: 'user_')]
|
||||
private Point $userLocation;
|
||||
|
||||
#[ORM\Column(type: Types::FLOAT)]
|
||||
private float $lng;
|
||||
#[ORM\Embedded(class: Point::class, columnPrefix: 'signal_')]
|
||||
private Point $signalLocation;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, name: 'created_at')]
|
||||
private DateTimeImmutable $createdAt;
|
||||
@@ -49,26 +50,26 @@ class Signal
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLat(): float
|
||||
public function getUserLocation(): Point
|
||||
{
|
||||
return $this->lat;
|
||||
return $this->userLocation;
|
||||
}
|
||||
|
||||
public function setLat(float $lat): self
|
||||
public function setUserLocation(Point $userLocation): self
|
||||
{
|
||||
$this->lat = $lat;
|
||||
$this->userLocation = $userLocation;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLng(): float
|
||||
public function getSignalLocation(): Point
|
||||
{
|
||||
return $this->lng;
|
||||
return $this->signalLocation;
|
||||
}
|
||||
|
||||
public function setLng(float $lng): self
|
||||
public function setSignalLocation(Point $signalLocation): self
|
||||
{
|
||||
$this->lng = $lng;
|
||||
$this->signalLocation = $signalLocation;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exception;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
|
||||
use function sprintf;
|
||||
|
||||
#[WithHttpStatus(Response::HTTP_UNPROCESSABLE_ENTITY, headers: ['x-error-code' => 'invalid_coordinates'])]
|
||||
final class InvalidPointException extends \RuntimeException
|
||||
{
|
||||
private function __construct(string $message)
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public static function invalidNumber(): self
|
||||
{
|
||||
return new self('Latitude and longitude must be finite numbers.');
|
||||
}
|
||||
|
||||
public static function latitudeOutOfRange(float $lat): self
|
||||
{
|
||||
return new self(sprintf('Latitude %.6f is out of bounds.', $lat));
|
||||
}
|
||||
|
||||
public static function longitudeOutOfRange(float $lng): self
|
||||
{
|
||||
return new self(sprintf('Longitude %.6f is out of bounds.', $lng));
|
||||
}
|
||||
|
||||
public static function missingCoordinates(): self
|
||||
{
|
||||
return new self('Missing latitude or longitude.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exception;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
|
||||
|
||||
#[WithHttpStatus(Response::HTTP_BAD_REQUEST, headers: ['x-error-code' => 'missing_client_key'])]
|
||||
final class MissingClientKeyException extends \RuntimeException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Unable to determine your network address.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exception;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
|
||||
use function sprintf;
|
||||
|
||||
#[WithHttpStatus(Response::HTTP_UNPROCESSABLE_ENTITY, headers: ['x-error-code' => 'point_too_far'])]
|
||||
final class PointTooFarException extends \RuntimeException
|
||||
{
|
||||
public function __construct(float $maximumDistanceKm)
|
||||
{
|
||||
parent::__construct(sprintf('The submitted point must be within %.2fkm of your location.', $maximumDistanceKm));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exception;
|
||||
|
||||
use DateTimeInterface;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
|
||||
use function sprintf;
|
||||
|
||||
#[WithHttpStatus(Response::HTTP_TOO_MANY_REQUESTS, headers: ['x-error-code' => 'submission_rate_limited'])]
|
||||
final class SubmissionRateLimitedException extends \RuntimeException
|
||||
{
|
||||
public function __construct(?DateTimeInterface $retryAfter)
|
||||
{
|
||||
$message = 'Too many submissions from your network. Please wait before trying again.';
|
||||
if ($retryAfter !== null) {
|
||||
$message .= sprintf(' You can retry after %s.', $retryAfter->format(DATE_ATOM));
|
||||
}
|
||||
|
||||
parent::__construct($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Message;
|
||||
|
||||
final class SignalCreatedMessage
|
||||
{
|
||||
public function __construct(public readonly int $signalId)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\MessageHandler;
|
||||
|
||||
use App\Message\SignalCreatedMessage;
|
||||
use App\Repository\SignalRepository;
|
||||
use App\Service\SignalSnapshotBuilder;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Symfony\Component\Mercure\HubInterface;
|
||||
use Symfony\Component\Mercure\Update;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
|
||||
use function json_encode;
|
||||
use const JSON_THROW_ON_ERROR;
|
||||
use Throwable;
|
||||
|
||||
#[AsMessageHandler]
|
||||
final class SignalCreatedMessageHandler
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SignalRepository $signals,
|
||||
private readonly SignalSnapshotBuilder $snapshotBuilder,
|
||||
private readonly HubInterface $hub,
|
||||
#[Autowire('%app.signal_stream_topic%')]
|
||||
private readonly string $topic,
|
||||
#[Autowire('%app.signal_snapshot_limit%')]
|
||||
private readonly int $snapshotLimit,
|
||||
private readonly ?LoggerInterface $logger = null,
|
||||
) {
|
||||
}
|
||||
|
||||
public function __invoke(SignalCreatedMessage $message): void
|
||||
{
|
||||
$recentSignals = $this->signals->findRecent($this->snapshotLimit);
|
||||
$snapshot = $this->snapshotBuilder->build($recentSignals);
|
||||
|
||||
$payload = [
|
||||
'type' => 'snapshot',
|
||||
'payload' => [
|
||||
'points' => $snapshot['points'],
|
||||
'density' => $snapshot['density'],
|
||||
'latestByUser' => $snapshot['latestByUser'],
|
||||
'totals' => $snapshot['totals'],
|
||||
'updatedAt' => (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format(DATE_ATOM),
|
||||
],
|
||||
];
|
||||
|
||||
$data = json_encode($payload, JSON_THROW_ON_ERROR);
|
||||
|
||||
$update = new Update(
|
||||
topics: $this->topic,
|
||||
data: $data,
|
||||
);
|
||||
|
||||
try {
|
||||
$this->hub->publish($update);
|
||||
} catch (Throwable $exception) {
|
||||
$this->logger?->error('Failed to publish signal update to Mercure.', [
|
||||
'exception' => $exception,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Payload;
|
||||
|
||||
use App\ValueObject\Point;
|
||||
|
||||
final readonly class SignalPayload
|
||||
{
|
||||
public function __construct(
|
||||
public Point $signalLocation,
|
||||
public Point $userLocation,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Exception\MissingClientKeyException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
final class ClientKeyProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function fromRequest(Request $request): string
|
||||
{
|
||||
$ip = $this->extractClientIp($request);
|
||||
|
||||
$clientKey = $this->hashIp($ip);
|
||||
$this->logger->debug('Generated client key for request.', [
|
||||
'client_key' => $clientKey,
|
||||
]);
|
||||
|
||||
return $clientKey;
|
||||
}
|
||||
|
||||
private function extractClientIp(Request $request): string
|
||||
{
|
||||
$forwarded = $request->headers->get('X-Forwarded-For');
|
||||
if ($forwarded !== null && $forwarded !== '') {
|
||||
$parts = array_filter(array_map('trim', explode(',', $forwarded)));
|
||||
if ($parts !== []) {
|
||||
$this->logger->info('Resolved client address from forwarded header.', [
|
||||
'resolution' => 'forwarded',
|
||||
]);
|
||||
return $parts[0];
|
||||
}
|
||||
}
|
||||
|
||||
$ip = $request->getClientIp();
|
||||
if (is_string($ip) && $ip !== '') {
|
||||
$this->logger->info('Resolved client address from remote address.', [
|
||||
'resolution' => 'remote',
|
||||
]);
|
||||
return $ip;
|
||||
}
|
||||
|
||||
$this->logger->critical('Failed to resolve client address for key generation.');
|
||||
throw new MissingClientKeyException();
|
||||
}
|
||||
|
||||
private function hashIp(string $ip): string
|
||||
{
|
||||
return substr(hash('sha256', $ip), 0, 12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\ValueObject\Point;
|
||||
use App\Exception\PointTooFarException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
final class PointProximityValidator
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire('%app.max_signal_distance_km%')]
|
||||
private readonly float $maximumDistanceKm,
|
||||
#[Autowire(service: 'monolog.logger.signals')]
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function assertWithinRange(Point $userLocation, Point $signalLocation): void
|
||||
{
|
||||
$distance = $this->distanceInKm($userLocation, $signalLocation);
|
||||
|
||||
$this->logger->debug('Calculated proximity between user and signal.', [
|
||||
'distance_km' => $distance,
|
||||
'max_distance_km' => $this->maximumDistanceKm,
|
||||
]);
|
||||
|
||||
if ($distance > $this->maximumDistanceKm) {
|
||||
$this->logger->warning('Rejected signal because it is beyond the allowed proximity.', [
|
||||
'distance_km' => $distance,
|
||||
'max_distance_km' => $this->maximumDistanceKm,
|
||||
]);
|
||||
throw new PointTooFarException($this->maximumDistanceKm);
|
||||
}
|
||||
}
|
||||
|
||||
private function distanceInKm(Point $a, Point $b): float
|
||||
{
|
||||
$lat1 = deg2rad($a->getLat());
|
||||
$lat2 = deg2rad($b->getLat());
|
||||
$deltaLat = deg2rad($b->getLat() - $a->getLat());
|
||||
$deltaLng = deg2rad($b->getLng() - $a->getLng());
|
||||
|
||||
$haversine = sin($deltaLat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($deltaLng / 2) ** 2;
|
||||
$c = 2 * atan2(sqrt($haversine), sqrt(1 - $haversine));
|
||||
|
||||
return 6371 * $c;
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,21 @@ class SignalSnapshotBuilder
|
||||
* @param list<Signal> $signals
|
||||
*
|
||||
* @return array{
|
||||
* points: list<array{id: int, lat: float, lng: float, createdAt: string, userKey: string}>,
|
||||
* points: list<array{
|
||||
* id: int,
|
||||
* signalLocation: array{lat: float, lng: float},
|
||||
* userLocation: array{lat: float, lng: float},
|
||||
* createdAt: string,
|
||||
* userKey: string,
|
||||
* }>,
|
||||
* density: list<array{lat: float, lng: float, intensity: int}>,
|
||||
* latestByUser: list<array{id: int, lat: float, lng: float, createdAt: string, userKey: string}>,
|
||||
* latestByUser: list<array{
|
||||
* id: int,
|
||||
* signalLocation: array{lat: float, lng: float},
|
||||
* userLocation: array{lat: float, lng: float},
|
||||
* createdAt: string,
|
||||
* userKey: string,
|
||||
* }>,
|
||||
* totals: array{points: int, contributors: int}
|
||||
* }
|
||||
*/
|
||||
@@ -25,18 +37,27 @@ class SignalSnapshotBuilder
|
||||
$latestByUser = [];
|
||||
|
||||
foreach ($signals as $signal) {
|
||||
$signalLocation = $signal->getSignalLocation();
|
||||
$userLocation = $signal->getUserLocation();
|
||||
|
||||
$point = [
|
||||
'id' => (int) $signal->getId(),
|
||||
'lat' => $signal->getLat(),
|
||||
'lng' => $signal->getLng(),
|
||||
'signalLocation' => [
|
||||
'lat' => $signalLocation->getLat(),
|
||||
'lng' => $signalLocation->getLng(),
|
||||
],
|
||||
'userLocation' => [
|
||||
'lat' => $userLocation->getLat(),
|
||||
'lng' => $userLocation->getLng(),
|
||||
],
|
||||
'createdAt' => $signal->getCreatedAt()->format(DATE_ATOM),
|
||||
'userKey' => $signal->getUserKey(),
|
||||
];
|
||||
|
||||
$points[] = $point;
|
||||
|
||||
$bucketLat = round($signal->getLat(), 3);
|
||||
$bucketLng = round($signal->getLng(), 3);
|
||||
$bucketLat = round($signalLocation->getLat(), 3);
|
||||
$bucketLng = round($signalLocation->getLng(), 3);
|
||||
$bucketKey = $bucketLat . ':' . $bucketLng;
|
||||
|
||||
if (! isset($densityBuckets[$bucketKey])) {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Repository\SignalRepository;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
|
||||
final class SignalSnapshotService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SignalRepository $signals,
|
||||
private readonly SignalSnapshotBuilder $snapshotBuilder,
|
||||
#[Autowire('%app.signal_snapshot_limit%')]
|
||||
private readonly int $snapshotLimit,
|
||||
#[Autowire(service: 'monolog.logger.signals')]
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function buildSnapshot(?int $limit, string $clientKey): array
|
||||
{
|
||||
$resolvedLimit = $this->normalizeLimit($limit);
|
||||
$signals = $this->signals->findRecent($resolvedLimit);
|
||||
$snapshot = $this->snapshotBuilder->build($signals);
|
||||
|
||||
$this->logger->info('Built signal snapshot for client.', [
|
||||
'client_key' => $clientKey,
|
||||
'requested_limit' => $limit,
|
||||
'applied_limit' => $resolvedLimit,
|
||||
'point_count' => count($snapshot['points']),
|
||||
]);
|
||||
|
||||
return [
|
||||
'clientKey' => $clientKey,
|
||||
'points' => $snapshot['points'],
|
||||
'density' => $snapshot['density'],
|
||||
'latestByUser' => $snapshot['latestByUser'],
|
||||
'totals' => $snapshot['totals'],
|
||||
'updatedAt' => new DateTimeImmutable('now', new DateTimeZone('UTC'))->format(DATE_ATOM),
|
||||
];
|
||||
}
|
||||
|
||||
private function normalizeLimit(?int $limit): int
|
||||
{
|
||||
if ($limit === null) {
|
||||
return $this->snapshotLimit;
|
||||
}
|
||||
|
||||
if ($limit < 1) {
|
||||
return $this->snapshotLimit;
|
||||
}
|
||||
|
||||
return min($limit, $this->snapshotLimit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Payload\SignalPayload;
|
||||
use App\Entity\Signal;
|
||||
use App\Exception\SubmissionRateLimitedException;
|
||||
use App\Message\SignalCreatedMessage;
|
||||
use App\Repository\SignalRepository;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
use Symfony\Component\RateLimiter\RateLimiterFactory;
|
||||
|
||||
final class SignalSubmissionService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SignalRepository $signals,
|
||||
#[Autowire(service: 'limiter.signal_submission')]
|
||||
private readonly RateLimiterFactory $submissionLimiter,
|
||||
private readonly PointProximityValidator $proximityValidator,
|
||||
private readonly MessageBusInterface $bus,
|
||||
#[Autowire(service: 'monolog.logger.signals')]
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
}
|
||||
|
||||
public function submit(string $clientKey, SignalPayload $payload): Signal
|
||||
{
|
||||
$this->enforceRateLimit($clientKey);
|
||||
$signalLocation = $payload->signalLocation;
|
||||
$userLocation = $payload->userLocation;
|
||||
|
||||
$this->proximityValidator->assertWithinRange($userLocation, $signalLocation);
|
||||
|
||||
$this->logger->info('Storing new signal submission.', [
|
||||
'client_key' => $clientKey,
|
||||
'signal_location' => [
|
||||
'lat' => round($signalLocation->getLat(), 5),
|
||||
'lng' => round($signalLocation->getLng(), 5),
|
||||
],
|
||||
'user_location' => [
|
||||
'lat' => round($userLocation->getLat(), 5),
|
||||
'lng' => round($userLocation->getLng(), 5),
|
||||
],
|
||||
]);
|
||||
|
||||
$signal = (new Signal())
|
||||
->setUserKey($clientKey)
|
||||
->setUserLocation($userLocation)
|
||||
->setSignalLocation($signalLocation)
|
||||
->setCreatedAt(new DateTimeImmutable('now', new DateTimeZone('UTC')));
|
||||
|
||||
$this->signals->save($signal);
|
||||
|
||||
$signalId = $signal->getId();
|
||||
if ($signalId !== null) {
|
||||
$this->logger->debug('Dispatching signal created message.', [
|
||||
'signal_id' => $signalId,
|
||||
]);
|
||||
$this->bus->dispatch(new SignalCreatedMessage($signalId));
|
||||
$this->logger->info('Signal stored successfully.', [
|
||||
'signal_id' => $signalId,
|
||||
'client_key' => $clientKey,
|
||||
]);
|
||||
}
|
||||
|
||||
return $signal;
|
||||
}
|
||||
|
||||
private function enforceRateLimit(string $clientKey): void
|
||||
{
|
||||
$rateLimiter = $this->submissionLimiter->create($clientKey);
|
||||
$limit = $rateLimiter->consume(1);
|
||||
|
||||
if (! $limit->isAccepted()) {
|
||||
$retryAfter = $limit->getRetryAfter();
|
||||
$this->logger->warning('Signal submission rejected due to rate limiting.', [
|
||||
'client_key' => $clientKey,
|
||||
'retry_after' => $retryAfter?->format(DATE_ATOM),
|
||||
]);
|
||||
throw new SubmissionRateLimitedException($limit->getRetryAfter());
|
||||
}
|
||||
|
||||
$this->logger->debug('Signal submission passed rate limiting.', [
|
||||
'client_key' => $clientKey,
|
||||
'remaining_tokens' => $limit->getRemainingTokens(),
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ValueObject;
|
||||
|
||||
use App\Exception\InvalidPointException;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
#[ORM\Embeddable]
|
||||
class Point
|
||||
{
|
||||
#[ORM\Column(name: 'lat', type: Types::FLOAT)]
|
||||
private float $lat;
|
||||
|
||||
#[ORM\Column(name: 'lng', type: Types::FLOAT)]
|
||||
private float $lng;
|
||||
|
||||
public function __construct(float $lat, float $lng)
|
||||
{
|
||||
$this->assertValid($lat, $lng);
|
||||
|
||||
$this->lat = $lat;
|
||||
$this->lng = $lng;
|
||||
}
|
||||
|
||||
public static function fromArray(array $coordinates): self
|
||||
{
|
||||
if (! isset($coordinates['lat'], $coordinates['lng'])) {
|
||||
throw InvalidPointException::missingCoordinates();
|
||||
}
|
||||
|
||||
return new self((float) $coordinates['lat'], (float) $coordinates['lng']);
|
||||
}
|
||||
|
||||
public static function fromLatLng(float $lat, float $lng): self
|
||||
{
|
||||
return new self($lat, $lng);
|
||||
}
|
||||
|
||||
public function getLat(): float
|
||||
{
|
||||
return $this->lat;
|
||||
}
|
||||
|
||||
public function getLng(): float
|
||||
{
|
||||
return $this->lng;
|
||||
}
|
||||
|
||||
private function assertValid(float $lat, float $lng): void
|
||||
{
|
||||
if (! is_finite($lat) || ! is_finite($lng)) {
|
||||
throw InvalidPointException::invalidNumber();
|
||||
}
|
||||
|
||||
if ($lat < -90 || $lat > 90) {
|
||||
throw InvalidPointException::latitudeOutOfRange($lat);
|
||||
}
|
||||
|
||||
if ($lng < -180 || $lng > 180) {
|
||||
throw InvalidPointException::longitudeOutOfRange($lng);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,15 @@
|
||||
"bin/phpunit"
|
||||
]
|
||||
},
|
||||
"sentry/sentry-symfony": {
|
||||
"version": "5.6",
|
||||
"recipe": {
|
||||
"repo": "github.com/symfony/recipes-contrib",
|
||||
"branch": "main",
|
||||
"version": "5.0",
|
||||
"ref": "b6cb4b34429dadecd7187852123be19d628fa37a"
|
||||
}
|
||||
},
|
||||
"symfony/console": {
|
||||
"version": "7.3",
|
||||
"recipe": {
|
||||
@@ -131,6 +140,42 @@
|
||||
".editorconfig"
|
||||
]
|
||||
},
|
||||
"symfony/mercure-bundle": {
|
||||
"version": "0.3",
|
||||
"recipe": {
|
||||
"repo": "github.com/symfony/recipes",
|
||||
"branch": "main",
|
||||
"version": "0.3",
|
||||
"ref": "528285147494380298f8f991ee8c47abebaf79db"
|
||||
},
|
||||
"files": [
|
||||
"config/packages/mercure.yaml"
|
||||
]
|
||||
},
|
||||
"symfony/messenger": {
|
||||
"version": "7.3",
|
||||
"recipe": {
|
||||
"repo": "github.com/symfony/recipes",
|
||||
"branch": "main",
|
||||
"version": "6.0",
|
||||
"ref": "ba1ac4e919baba5644d31b57a3284d6ba12d52ee"
|
||||
},
|
||||
"files": [
|
||||
"config/packages/messenger.yaml"
|
||||
]
|
||||
},
|
||||
"symfony/monolog-bundle": {
|
||||
"version": "3.10",
|
||||
"recipe": {
|
||||
"repo": "github.com/symfony/recipes",
|
||||
"branch": "main",
|
||||
"version": "3.7",
|
||||
"ref": "aff23899c4440dd995907613c1dd709b6f59503f"
|
||||
},
|
||||
"files": [
|
||||
"config/packages/monolog.yaml"
|
||||
]
|
||||
},
|
||||
"symfony/property-info": {
|
||||
"version": "7.3",
|
||||
"recipe": {
|
||||
@@ -155,5 +200,17 @@
|
||||
"config/packages/routing.yaml",
|
||||
"config/routes.yaml"
|
||||
]
|
||||
},
|
||||
"symfony/validator": {
|
||||
"version": "7.3",
|
||||
"recipe": {
|
||||
"repo": "github.com/symfony/recipes",
|
||||
"branch": "main",
|
||||
"version": "7.0",
|
||||
"ref": "8c1c4e28d26a124b0bb273f537ca8ce443472bfd"
|
||||
},
|
||||
"files": [
|
||||
"config/packages/validator.yaml"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,9 @@ class SignalControllerTest extends WebTestCase
|
||||
|
||||
public function testIndexReturnsRecentSignals(): void
|
||||
{
|
||||
$this->client->request('GET', '/api/signals');
|
||||
$this->client->request('GET', '/api/signals', server: [
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
]);
|
||||
|
||||
self::assertResponseIsSuccessful();
|
||||
|
||||
@@ -60,12 +62,14 @@ class SignalControllerTest extends WebTestCase
|
||||
self::assertCount(3, $payload['points']);
|
||||
self::assertSame(3, $payload['totals']['points']);
|
||||
self::assertSame(2, $payload['totals']['contributors']);
|
||||
self::assertSame(-11.6852, $payload['points'][0]['lat']);
|
||||
self::assertSame(-11.6852, $payload['points'][0]['signalLocation']['lat']);
|
||||
}
|
||||
|
||||
public function testIndexRespectsLimitQueryParameter(): void
|
||||
{
|
||||
$this->client->request('GET', '/api/signals?limit=1');
|
||||
$this->client->request('GET', '/api/signals?limit=1', server: [
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
]);
|
||||
|
||||
self::assertResponseIsSuccessful();
|
||||
|
||||
@@ -80,13 +84,20 @@ class SignalControllerTest extends WebTestCase
|
||||
public function testStorePersistsNewSignal(): void
|
||||
{
|
||||
$body = [
|
||||
'lat' => -11.6901,
|
||||
'lng' => 27.4959,
|
||||
'signalLocation' => [
|
||||
'lat' => -11.6901,
|
||||
'lng' => 27.4959,
|
||||
],
|
||||
'userLocation' => [
|
||||
'lat' => -11.6899,
|
||||
'lng' => 27.4962,
|
||||
],
|
||||
];
|
||||
|
||||
$this->client->request('POST', '/api/signals', [], [], [
|
||||
$this->client->request('POST', '/api/signals', server: [
|
||||
'CONTENT_TYPE' => 'application/json',
|
||||
], json_encode($body, JSON_THROW_ON_ERROR));
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
], content: json_encode($body, JSON_THROW_ON_ERROR));
|
||||
|
||||
self::assertResponseStatusCodeSame(Response::HTTP_CREATED);
|
||||
|
||||
@@ -94,8 +105,10 @@ class SignalControllerTest extends WebTestCase
|
||||
self::assertIsString($content);
|
||||
$payload = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
|
||||
self::assertSame('stored', $payload['status']);
|
||||
self::assertSame($body['lat'], $payload['point']['lat']);
|
||||
self::assertSame($body['lng'], $payload['point']['lng']);
|
||||
self::assertSame($body['signalLocation']['lat'], $payload['point']['signalLocation']['lat']);
|
||||
self::assertSame($body['signalLocation']['lng'], $payload['point']['signalLocation']['lng']);
|
||||
self::assertSame($body['userLocation']['lat'], $payload['point']['userLocation']['lat']);
|
||||
self::assertSame($body['userLocation']['lng'], $payload['point']['userLocation']['lng']);
|
||||
|
||||
$repository = $this->entityManager->getRepository(Signal::class);
|
||||
$signals = $repository->findAll();
|
||||
@@ -105,19 +118,58 @@ class SignalControllerTest extends WebTestCase
|
||||
public function testStoreRejectsInvalidCoordinates(): void
|
||||
{
|
||||
$body = [
|
||||
'lat' => 181,
|
||||
'lng' => 10,
|
||||
'signalLocation' => [
|
||||
'lat' => 181,
|
||||
'lng' => 10,
|
||||
],
|
||||
'userLocation' => [
|
||||
'lat' => 10,
|
||||
'lng' => 10,
|
||||
],
|
||||
];
|
||||
|
||||
$this->client->request('POST', '/api/signals', [], [], [
|
||||
$this->client->request('POST', '/api/signals', server: [
|
||||
'CONTENT_TYPE' => 'application/json',
|
||||
], json_encode($body, JSON_THROW_ON_ERROR));
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
], content: json_encode($body, JSON_THROW_ON_ERROR));
|
||||
|
||||
self::assertResponseStatusCodeSame(Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
|
||||
$content = $this->client->getResponse()->getContent();
|
||||
$response = $this->client->getResponse();
|
||||
self::assertSame('invalid_coordinates', $response->headers->get('x-error-code'));
|
||||
|
||||
$content = $response->getContent();
|
||||
self::assertIsString($content);
|
||||
$payload = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
|
||||
self::assertSame('out_of_bounds', $payload['error']);
|
||||
self::assertSame('Latitude 181.000000 is out of bounds.', $payload['detail'] ?? null);
|
||||
}
|
||||
|
||||
public function testStoreRejectsPointTooFar(): void
|
||||
{
|
||||
$body = [
|
||||
'signalLocation' => [
|
||||
'lat' => -11.6901,
|
||||
'lng' => 27.4959,
|
||||
],
|
||||
'userLocation' => [
|
||||
'lat' => -11.7005,
|
||||
'lng' => 27.4804,
|
||||
],
|
||||
];
|
||||
|
||||
$this->client->request('POST', '/api/signals', server: [
|
||||
'CONTENT_TYPE' => 'application/json',
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
], content: json_encode($body, JSON_THROW_ON_ERROR));
|
||||
|
||||
self::assertResponseStatusCodeSame(Response::HTTP_UNPROCESSABLE_ENTITY);
|
||||
|
||||
$response = $this->client->getResponse();
|
||||
self::assertSame('point_too_far', $response->headers->get('x-error-code'));
|
||||
|
||||
$content = $response->getContent();
|
||||
self::assertIsString($content);
|
||||
$payload = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
|
||||
self::assertSame('The submitted point must be within 1.00km of your location.', $payload['detail'] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user