Merge pull request #5 from bernard-ng/codex/implement-sse-with-mercure-for-updates

Introduce Point value object and toast-driven error handling
This commit is contained in:
Bernard Ngandu
2025-10-10 14:56:09 +02:00
committed by GitHub
46 changed files with 3691 additions and 229 deletions
+58
View File
@@ -13,6 +13,7 @@
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toast": "^1.2.15",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"i18next": "^25.5.3",
@@ -1156,6 +1157,40 @@
}
}
},
"node_modules/@radix-ui/react-toast": {
"version": "1.2.15",
"resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.15.tgz",
"integrity": "sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-collection": "1.1.7",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-dismissable-layer": "1.1.11",
"@radix-ui/react-portal": "1.1.9",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-controllable-state": "1.2.2",
"@radix-ui/react-use-layout-effect": "1.1.1",
"@radix-ui/react-visually-hidden": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
@@ -1241,6 +1276,29 @@
}
}
},
"node_modules/@radix-ui/react-visually-hidden": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.3.tgz",
"integrity": "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-primitive": "2.1.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.0-beta.41",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-beta.41.tgz",
+1
View File
@@ -15,6 +15,7 @@
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toast": "^1.2.15",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"i18next": "^25.5.3",
+87 -28
View File
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useState } from 'react'
import { Layers, Menu, PanelRightClose, PanelRightOpen } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Layers, Loader2, Menu, PanelRightClose, PanelRightOpen } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { AppHeader } from '@/components/layout/AppHeader'
@@ -23,12 +23,39 @@ import { useHotspotFeed } from '@/hooks/useHotspotFeed'
import { useLeafletHeatmap, type TileProvider } from '@/hooks/useLeafletHeatmap'
import { useUserLocation } from '@/hooks/useUserLocation'
import { cn, distanceInKm, formatCoordinate, formatRelativeTime, formatTimestamp } from '@/lib/utils'
import type { LatLng } from '@/types/api'
import type { Point } from '@/types/api'
import { Toaster } from '@/components/ui/toaster'
import { useToast } from '@/components/ui/use-toast'
const RADIUS_KM = 1
interface LocationGateProps {
title: string
message: string
actionLabel: string
onRetry: () => void
isLoading: boolean
}
function LocationGate({ title, message, actionLabel, onRetry, isLoading }: LocationGateProps) {
return (
<div className="flex min-h-screen flex-col items-center justify-center bg-background px-6 text-center">
<div className="max-w-md space-y-6">
<div className="space-y-2">
<h1 className="text-2xl font-semibold tracking-tight text-foreground">{title}</h1>
<p className="text-sm text-muted-foreground">{message}</p>
</div>
<Button onClick={onRetry} disabled={isLoading} className="inline-flex items-center gap-2">
{isLoading && <Loader2 className="h-4 w-4 animate-spin" />}
<span>{actionLabel}</span>
</Button>
</div>
</div>
)
}
export default function App() {
const [pendingSpot, setPendingSpot] = useState<LatLng | null>(null)
const [pendingSpot, setPendingSpot] = useState<Point | null>(null)
const [isConfirmOpen, setIsConfirmOpen] = useState(false)
const [isConfirming, setIsConfirming] = useState(false)
const [tileProvider, setTileProvider] = useState<TileProvider>('openstreetmap')
@@ -44,6 +71,7 @@ export default function App() {
}
return window.innerWidth < 768
})
const { t, i18n } = useTranslation()
const locale = i18n.language === 'fr' ? 'fr-FR' : 'en-US'
const distanceFormatter = useMemo(
@@ -63,6 +91,13 @@ export default function App() {
[t],
)
const {
location: userLocation,
error: locationError,
isRequesting: isRequestingLocation,
refresh: refreshLocation,
} = useUserLocation()
const {
status,
error,
@@ -73,9 +108,7 @@ export default function App() {
selectVisibleLatestByUser,
myLatestPoint,
lastUpdated,
} = useHotspotFeed()
const { location: userLocation, error: locationError, isRequesting: isRequestingLocation } = useUserLocation()
} = useHotspotFeed({ userLocation: userLocation ?? null })
const visibleDensity = useMemo(
() => selectVisibleDensity(userLocation ?? null),
@@ -102,7 +135,7 @@ export default function App() {
if (!myLatestPoint) {
return null
}
if (userLocation && distanceInKm(userLocation, myLatestPoint) > RADIUS_KM) {
if (userLocation && distanceInKm(userLocation, myLatestPoint.signalLocation) > RADIUS_KM) {
return null
}
return myLatestPoint
@@ -135,12 +168,27 @@ export default function App() {
tileProvider,
})
const { toast } = useToast()
useEffect(() => {
if (!error) {
return
}
const description = error.detail ?? t(error.key, error.values ?? {})
toast({
variant: 'destructive',
title: t('errors.title'),
description,
duration: 6000,
})
}, [error, t, toast])
const handleConfirmSignal = useCallback(async () => {
if (!pendingSpot) {
return
}
setIsConfirming(true)
const result = await submitPoint(pendingSpot.lat, pendingSpot.lng)
const result = await submitPoint(pendingSpot)
setIsConfirming(false)
if (result.success) {
setIsConfirmOpen(false)
@@ -164,7 +212,7 @@ export default function App() {
const handleFocusMySignal = useCallback(() => {
if (myVisibleSignal) {
focusOn({ lat: myVisibleSignal.lat, lng: myVisibleSignal.lng }, 15)
focusOn({ lat: myVisibleSignal.signalLocation.lat, lng: myVisibleSignal.signalLocation.lng }, 15)
}
}, [focusOn, myVisibleSignal])
@@ -209,12 +257,12 @@ export default function App() {
.slice(0, 8)
.map((point) => {
const coordinates = t('common.coordinates', {
lat: formatCoordinate(point.lat, locale),
lng: formatCoordinate(point.lng, locale),
lat: formatCoordinate(point.signalLocation.lat, locale),
lng: formatCoordinate(point.signalLocation.lng, locale),
})
const distanceLabel = userLocation
? t('activityItem.distance', {
distance: `${distanceFormatter.format(distanceInKm(userLocation, point))} km`,
distance: `${distanceFormatter.format(distanceInKm(userLocation, point.signalLocation))} km`,
})
: formatTimestamp(point.createdAt, locale)
return {
@@ -223,7 +271,7 @@ export default function App() {
subtitle: t('activityItem.user', { id: point.userKey.slice(0, 4).toUpperCase() }),
timestampLabel: formatRelativeTime(point.createdAt, locale),
distanceLabel,
onFocus: () => focusOn({ lat: point.lat, lng: point.lng }, 15),
onFocus: () => focusOn({ lat: point.signalLocation.lat, lng: point.signalLocation.lng }, 15),
}
}),
[visiblePoints, userLocation, focusOn, distanceFormatter, t, locale],
@@ -240,10 +288,27 @@ export default function App() {
: 'translate-y-[calc(100%+1rem)] sm:translate-x-[calc(100%+2rem)]',
)
if (!userLocation) {
const gateTitle = t('location.gate.title')
const gateMessage = locationError ? t(locationError) : t('location.gate.description')
const gateAction = isRequestingLocation ? t('location.gate.loading') : t('location.gate.action')
return (
<LocationGate
title={gateTitle}
message={gateMessage}
actionLabel={gateAction}
onRetry={refreshLocation}
isLoading={isRequestingLocation}
/>
)
}
return (
<div className="relative min-h-screen w-full overflow-hidden bg-background text-foreground">
<MapViewport
containerRef={mapContainerRef}
<>
<div className="relative min-h-screen w-full overflow-hidden bg-background text-foreground">
<MapViewport
containerRef={mapContainerRef}
isPosting={isPosting || isConfirming}
isLoading={isLoading}
confirmationHint={isConfirmOpen ? t('map.confirmationHint') : null}
@@ -401,24 +466,18 @@ export default function App() {
<span className="text-muted-foreground">{t('dialog.confirmSignal.longitude')}</span>
<span className="font-medium text-foreground">{confirmationLng}°</span>
</div>
<p className="mt-4 text-xs text-muted-foreground">{t('dialog.confirmSignal.reach', { radius: RADIUS_KM })}</p>
</div>
<p className="text-xs text-muted-foreground">
{t('dialog.confirmSignal.reach', { radius: RADIUS_KM })}
</p>
<AlertDialogFooter>
<AlertDialogCancel disabled={isConfirming}>{t('dialog.confirmSignal.cancel')}</AlertDialogCancel>
<AlertDialogAction
disabled={isDialogDisabled}
onClick={(event) => {
event.preventDefault()
handleConfirmSignal().catch(() => undefined)
}}
>
<AlertDialogAction onClick={handleConfirmSignal} disabled={isDialogDisabled}>
{isConfirming ? t('dialog.confirmSignal.sending') : t('dialog.confirmSignal.confirm')}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
<Toaster />
</>
)
}
+116
View File
@@ -0,0 +1,116 @@
import * as React from 'react'
import * as ToastPrimitives from '@radix-ui/react-toast'
import { cva, type VariantProps } from 'class-variance-authority'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
'fixed inset-x-0 top-4 z-[1000] mx-auto flex w-full max-w-sm flex-col gap-2 px-4 sm:right-4 sm:left-auto sm:mx-0 sm:w-96',
className,
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
'group pointer-events-auto relative flex w-full items-start gap-3 overflow-hidden rounded-2xl border border-border bg-background p-4 shadow-lg transition-all',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive: 'border-destructive/60 bg-destructive text-destructive-foreground',
},
},
defaultVariants: {
variant: 'default',
},
},
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props}>
{props.children}
</ToastPrimitives.Root>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
'inline-flex h-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-background px-3 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
className,
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
'absolute right-3 top-3 rounded-full p-1 text-foreground/70 transition-colors hover:bg-foreground/10 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
className,
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title ref={ref} className={cn('text-sm font-semibold leading-none tracking-tight', className)} {...props} />
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
export type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
export type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}
+37
View File
@@ -0,0 +1,37 @@
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from '@/components/ui/toast'
import { useToast } from '@/components/ui/use-toast'
export function Toaster() {
const { toasts, dismiss } = useToast()
return (
<ToastProvider>
{toasts.map(({ id, title, description, action, ...props }) => (
<Toast
key={id}
{...props}
onOpenChange={(open) => {
if (!open) {
dismiss(id)
}
}}
>
<div className="flex flex-1 flex-col gap-1">
{title ? <ToastTitle>{title}</ToastTitle> : null}
{description ? <ToastDescription>{description}</ToastDescription> : null}
</div>
{action}
<ToastClose />
</Toast>
))}
<ToastViewport />
</ToastProvider>
)
}
+129
View File
@@ -0,0 +1,129 @@
import * as React from 'react'
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
type ToastState = {
toasts: ToasterToast[]
}
type ToastAction =
| { type: 'ADD_TOAST'; toast: ToasterToast }
| { type: 'UPDATE_TOAST'; toast: Partial<ToasterToast> & { id: string } }
| { type: 'DISMISS_TOAST'; toastId?: string }
| { type: 'REMOVE_TOAST'; toastId?: string }
const TOAST_LIMIT = 5
const TOAST_REMOVE_DELAY = 1000
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const listeners = new Set<(state: ToastState) => void>()
let memoryState: ToastState = { toasts: [] }
function dispatch(action: ToastAction) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
function reducer(state: ToastState, action: ToastAction): ToastState {
switch (action.type) {
case 'ADD_TOAST': {
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
}
case 'UPDATE_TOAST': {
return {
...state,
toasts: state.toasts.map((toast) =>
toast.id === action.toast.id ? { ...toast, ...action.toast } : toast,
),
}
}
case 'DISMISS_TOAST': {
const { toastId } = action
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((toast) =>
toast.id === toastId || toastId === undefined
? { ...toast, open: false }
: toast,
),
}
}
case 'REMOVE_TOAST': {
if (action.toastId === undefined) {
return { ...state, toasts: [] }
}
return {
...state,
toasts: state.toasts.filter((toast) => toast.id !== action.toastId),
}
}
default:
return state
}
}
function addToRemoveQueue(toastId: string) {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({ type: 'REMOVE_TOAST', toastId })
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
function genId() {
return Math.random().toString(36).slice(2, 10)
}
export function useToast() {
const [state, setState] = React.useState<ToastState>(memoryState)
React.useEffect(() => {
listeners.add(setState)
return () => {
listeners.delete(setState)
}
}, [])
return {
...state,
toast: (props: Omit<ToasterToast, 'id'>) => {
const id = genId()
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
return id
},
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),
}
}
export const toast = (props: Omit<ToasterToast, 'id'>) => {
const id = genId()
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
return id
}
+174 -46
View File
@@ -1,15 +1,40 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { distanceInKm } from '@/lib/utils'
import type { ApiDensityCell, ApiPoint, ApiSnapshot, FeedStatus, LatLng } from '@/types/api'
import type {
ApiDensityCell,
ApiPoint,
ApiSnapshot,
FeedStatus,
Point,
SnapshotEventPayload,
} from '@/types/api'
const API_BASE = import.meta.env.VITE_API_BASE ?? 'http://localhost:8000/api/signals'
const SNAPSHOT_LIMIT = 750
const DEFAULT_REFRESH_MS = 7000
const MERCURE_HUB = import.meta.env.VITE_MERCURE_HUB ?? 'http://localhost:3000/.well-known/mercure'
const MERCURE_TOPIC = import.meta.env.VITE_MERCURE_TOPIC ?? 'https://points-of-interest.local/signals'
const VISIBLE_RADIUS_KM = 1
type ProblemDetails = {
detail?: unknown
}
function extractProblemDetail(payload: unknown): string | null {
if (payload && typeof payload === 'object') {
const { detail } = payload as ProblemDetails
if (typeof detail === 'string' && detail.trim().length > 0) {
return detail
}
}
return null
}
interface UseHotspotFeedOptions {
autoRefreshMs?: number
userLocation: Point | null
snapshotLimit?: number
mercureHub?: string
mercureTopic?: string
}
interface SubmitResult {
@@ -19,9 +44,15 @@ interface SubmitResult {
export interface FeedError {
key: string
values?: Record<string, unknown>
detail?: string
}
export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspotFeedOptions = {}) {
export function useHotspotFeed({
userLocation,
snapshotLimit = SNAPSHOT_LIMIT,
mercureHub = MERCURE_HUB,
mercureTopic = MERCURE_TOPIC,
}: UseHotspotFeedOptions) {
const [status, setStatus] = useState<FeedStatus>('loading')
const [error, setError] = useState<FeedError | null>(null)
const [rawPoints, setRawPoints] = useState<ApiPoint[]>([])
@@ -32,14 +63,51 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
const statusRef = useRef<FeedStatus>('loading')
const initialLoadRef = useRef(true)
const eventSourceRef = useRef<EventSource | null>(null)
const setStatusSafe = useCallback((next: FeedStatus) => {
statusRef.current = next
setStatus(next)
}, [])
const resetState = useCallback(() => {
setRawPoints([])
setRawDensity([])
setRawLatestByUser([])
setLastUpdated(null)
setClientKey(null)
setError(null)
eventSourceRef.current?.close()
eventSourceRef.current = null
initialLoadRef.current = true
setStatusSafe('loading')
}, [setStatusSafe])
const applySnapshot = useCallback(
(snapshot: ApiSnapshot, options?: { preserveClientKey?: boolean }) => {
setRawPoints(snapshot.points)
setRawDensity(snapshot.density)
setRawLatestByUser(snapshot.latestByUser)
if (!options?.preserveClientKey) {
setClientKey(snapshot.clientKey ?? null)
}
setLastUpdated(snapshot.updatedAt ?? new Date().toISOString())
setError(null)
initialLoadRef.current = false
if (statusRef.current !== 'posting') {
setStatusSafe('idle')
}
},
[setStatusSafe],
)
const fetchSnapshot = useCallback(
async (options?: { silent?: boolean }) => {
if (!userLocation) {
resetState()
return
}
const silent = options?.silent ?? false
const previousStatus = statusRef.current
const isInitial = initialLoadRef.current
@@ -53,26 +121,24 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
}
try {
const response = await fetch(`${API_BASE}?limit=${SNAPSHOT_LIMIT}`, { cache: 'no-store' })
const response = await fetch(`${API_BASE}?limit=${snapshotLimit}`, { cache: 'no-store' })
if (!response.ok) {
throw new Error('feed-unavailable')
const payload = await response.json().catch(() => null)
const detail = extractProblemDetail(payload)
setError({ key: 'errors.feedUnavailable', detail: detail ?? undefined })
if (initialLoadRef.current) {
setStatusSafe('error')
} else if (previousStatus !== 'posting') {
setStatusSafe('idle')
}
return
}
const data: ApiSnapshot = await response.json()
setRawPoints(data.points ?? [])
setRawDensity(data.density ?? [])
setRawLatestByUser(data.latestByUser ?? [])
setClientKey(data.clientKey ?? null)
setLastUpdated(data.updatedAt ?? new Date().toISOString())
setError(null)
initialLoadRef.current = false
const nextStatus = previousStatus === 'posting' ? 'posting' : 'idle'
setStatusSafe(nextStatus)
applySnapshot(data)
} catch (error) {
const message = error instanceof Error ? error.message : null
const key = message === 'feed-unavailable' ? 'errors.feedUnavailable' : 'errors.feedUnknown'
setError({ key })
const detail = error instanceof Error && error.message ? error.message : null
setError({ key: 'errors.feedUnknown', detail: detail ?? undefined })
if (initialLoadRef.current) {
setStatusSafe('error')
} else if (previousStatus !== 'posting') {
@@ -80,39 +146,92 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
}
}
},
[setStatusSafe],
[userLocation, snapshotLimit, resetState, setStatusSafe, applySnapshot],
)
useEffect(() => {
fetchSnapshot().catch(() => undefined)
if (!autoRefreshMs) {
const connectToStream = useCallback(() => {
if (!userLocation) {
return
}
const interval = window.setInterval(() => {
fetchSnapshot({ silent: true }).catch(() => undefined)
}, autoRefreshMs)
try {
const url = new URL(mercureHub)
url.searchParams.append('topic', mercureTopic)
const eventSource = new EventSource(url.toString())
eventSource.onmessage = (event) => {
try {
const payload: SnapshotEventPayload = JSON.parse(event.data)
if (payload?.type === 'snapshot' && payload.payload) {
applySnapshot(payload.payload, { preserveClientKey: true })
}
} catch (parseError) {
console.error('Failed to parse stream payload', parseError)
}
}
eventSource.onerror = () => {
if (statusRef.current !== 'loading') {
setError({ key: 'errors.feedUnknown' })
setStatusSafe('error')
}
}
eventSourceRef.current = eventSource
} catch (connectionError) {
console.error('Unable to subscribe to live updates', connectionError)
setError({ key: 'errors.feedUnavailable' })
setStatusSafe('error')
}
}, [applySnapshot, mercureHub, mercureTopic, setStatusSafe, userLocation])
useEffect(() => {
if (!userLocation) {
resetState()
return undefined
}
fetchSnapshot().catch(() => undefined)
connectToStream()
return () => {
window.clearInterval(interval)
eventSourceRef.current?.close()
eventSourceRef.current = null
}
}, [autoRefreshMs, fetchSnapshot])
}, [connectToStream, fetchSnapshot, resetState, userLocation])
const submitPoint = useCallback(
async (lat: number, lng: number): Promise<SubmitResult> => {
async (target: Point): Promise<SubmitResult> => {
if (!userLocation) {
setError({
key: 'errors.submitWithReason',
values: { message: 'Location required before submitting.' },
detail: 'Location required before submitting.',
})
setStatusSafe('error')
return { success: false }
}
setStatusSafe('posting')
try {
const response = await fetch(API_BASE, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ lat, lng }),
body: JSON.stringify({
signalLocation: target,
userLocation,
}),
})
if (!response.ok) {
const payload = await response.json().catch(() => null)
const message = payload?.message as string | undefined
if (message) {
setError({ key: 'errors.submitWithReason', values: { message } })
const detail = extractProblemDetail(payload)
if (detail) {
setError({
key: 'errors.submitWithReason',
values: { message: detail },
detail,
})
} else {
setError({ key: 'errors.submitUnavailable' })
}
@@ -120,14 +239,13 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
return { success: false }
}
await fetchSnapshot({ silent: true })
setError(null)
setStatusSafe('idle')
return { success: true }
} catch (error) {
const message = error instanceof Error ? error.message : null
if (message) {
setError({ key: 'errors.submitWithReason', values: { message } })
const detail = error instanceof Error && error.message ? error.message : null
if (detail) {
setError({ key: 'errors.submitWithReason', values: { message: detail }, detail })
} else {
setError({ key: 'errors.submitUnknown' })
}
@@ -135,13 +253,13 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
return { success: false }
}
},
[fetchSnapshot, setStatusSafe],
[setStatusSafe, userLocation],
)
const hasClientKey = Boolean(clientKey)
const filterWithinRadius = useCallback(
<T extends LatLng>(collection: T[], origin: LatLng | null) => {
const filterDensityWithinRadius = useCallback(
(collection: ApiDensityCell[], origin: Point | null) => {
if (!origin) {
return []
}
@@ -150,19 +268,29 @@ export function useHotspotFeed({ autoRefreshMs = DEFAULT_REFRESH_MS }: UseHotspo
[],
)
const filterPointsWithinRadius = useCallback(
(collection: ApiPoint[], origin: Point | null) => {
if (!origin) {
return []
}
return collection.filter((item) => distanceInKm(origin, item.signalLocation) <= VISIBLE_RADIUS_KM)
},
[],
)
const selectVisibleDensity = useCallback(
(origin: LatLng | null) => filterWithinRadius(rawDensity, origin),
[filterWithinRadius, rawDensity],
(origin: Point | null) => filterDensityWithinRadius(rawDensity, origin),
[filterDensityWithinRadius, rawDensity],
)
const selectVisiblePoints = useCallback(
(origin: LatLng | null) => filterWithinRadius(rawPoints, origin),
[filterWithinRadius, rawPoints],
(origin: Point | null) => filterPointsWithinRadius(rawPoints, origin),
[filterPointsWithinRadius, rawPoints],
)
const selectVisibleLatestByUser = useCallback(
(origin: LatLng | null) => filterWithinRadius(rawLatestByUser, origin),
[filterWithinRadius, rawLatestByUser],
(origin: Point | null) => filterPointsWithinRadius(rawLatestByUser, origin),
[filterPointsWithinRadius, rawLatestByUser],
)
const myLatestPoint = useMemo(() => {
+16 -9
View File
@@ -9,7 +9,7 @@ import L, {
} from 'leaflet'
import 'leaflet.heat'
import type { ApiDensityCell, LatLng } from '@/types/api'
import type { ApiDensityCell, Point } from '@/types/api'
type HeatPoint = [number, number, number?]
@@ -24,18 +24,24 @@ type LeafletWithHeat = typeof L & {
interface UseLeafletHeatmapParams {
heatCells: ApiDensityCell[]
userLocation: LatLng | null
onRequestSpot?: (position: LatLng) => void
userLocation: Point | null
onRequestSpot?: (position: Point) => void
tileProvider: TileProvider
}
interface UseLeafletHeatmapResult {
mapContainerRef: MutableRefObject<HTMLDivElement | null>
focusOn: (position: LatLng, zoom?: number) => void
focusOn: (position: Point, zoom?: number) => void
fitToHeat: () => void
map: LeafletMap | null
}
type TileSource = {
readonly url: string
readonly attribution: string
readonly options?: TileLayerOptions
}
const TILE_SOURCES = {
openstreetmap: {
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
@@ -49,11 +55,11 @@ const TILE_SOURCES = {
zoomOffset: -1,
} satisfies TileLayerOptions,
},
} as const
} as const satisfies Record<string, TileSource>
export type TileProvider = keyof typeof TILE_SOURCES
const INITIAL_VIEW: LatLng = { lat: 20, lng: 0 }
const INITIAL_VIEW: Point = { lat: 20, lng: 0 }
const DEFAULT_ZOOM = 3
export function useLeafletHeatmap({
@@ -74,12 +80,13 @@ export function useLeafletHeatmap({
const createTileLayer = useCallback(
(provider: TileProvider) => {
const leaflet = L as LeafletWithHeat
const source = TILE_SOURCES[provider]
const source: TileSource = TILE_SOURCES[provider]
const options = source.options ?? {}
return leaflet.tileLayer(source.url, {
attribution: source.attribution,
crossOrigin: true,
maxZoom: 19,
...(source.options ?? {}),
...options,
})
},
[],
@@ -248,7 +255,7 @@ export function useLeafletHeatmap({
}
}, [userLocation])
const focusOn = useCallback((position: LatLng, zoom = 14) => {
const focusOn = useCallback((position: Point, zoom = 14) => {
const map = mapRef.current
if (!map) {
return
+2 -2
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { LatLng } from '@/types/api'
import type { Point } from '@/types/api'
function geolocationErrorMessage(error: GeolocationPositionError): string {
switch (error.code) {
@@ -16,7 +16,7 @@ function geolocationErrorMessage(error: GeolocationPositionError): string {
}
export function useUserLocation() {
const [location, setLocation] = useState<LatLng | null>(null)
const [location, setLocation] = useState<Point | null>(null)
const [error, setError] = useState<string | null>(null)
const [isRequesting, setIsRequesting] = useState<boolean>(false)
const watchIdRef = useRef<number | null>(null)
+7
View File
@@ -99,6 +99,12 @@
"timeout": "Timed out while fetching your location.",
"generic": "Failed to retrieve your location.",
"unsupported": "Geolocation is not supported in this browser."
},
"gate": {
"title": "Share your location to continue",
"description": "We need your location to personalise the live map feed.",
"action": "Try location again",
"loading": "Requesting location…"
}
},
"activityItem": {
@@ -128,6 +134,7 @@
"french": "Français"
},
"errors": {
"title": "Something went wrong",
"feedUnavailable": "Unable to reach the hotspot feed.",
"feedUnknown": "Unknown error while loading hotspots.",
"submitUnavailable": "Unable to store your signal.",
+7
View File
@@ -99,6 +99,12 @@
"timeout": "Délai dépassé lors de la récupération de votre localisation.",
"generic": "Échec de la récupération de votre localisation.",
"unsupported": "La géolocalisation n'est pas prise en charge par ce navigateur."
},
"gate": {
"title": "Partagez votre position pour continuer",
"description": "Nous avons besoin de votre localisation pour personnaliser la carte en direct.",
"action": "Relancer la localisation",
"loading": "Demande de localisation…"
}
},
"activityItem": {
@@ -128,6 +134,7 @@
"french": "Français"
},
"errors": {
"title": "Une erreur est survenue",
"feedUnavailable": "Impossible d'atteindre le flux de signaux.",
"feedUnknown": "Erreur inconnue lors du chargement des signaux.",
"submitUnavailable": "Impossible d'enregistrer votre signal.",
+15 -10
View File
@@ -1,9 +1,14 @@
export type FeedStatus = 'loading' | 'idle' | 'error' | 'posting' | 'refreshing'
export interface Point {
lat: number
lng: number
}
export interface ApiPoint {
id: number
lat: number
lng: number
signalLocation: Point
userLocation: Point
createdAt: string
userKey: string
}
@@ -16,17 +21,17 @@ export interface ApiDensityCell {
export interface ApiSnapshot {
clientKey?: string
points?: ApiPoint[]
density?: ApiDensityCell[]
latestByUser?: ApiPoint[]
totals?: {
points: ApiPoint[]
density: ApiDensityCell[]
latestByUser: ApiPoint[]
totals: {
points: number
contributors: number
}
updatedAt?: string
updatedAt: string
}
export type LatLng = {
lat: number
lng: number
export interface SnapshotEventPayload {
type: 'snapshot'
payload: ApiSnapshot
}
+24
View File
@@ -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 ###
+7
View File
@@ -0,0 +1,7 @@
services:
###> symfony/mercure-bundle ###
mercure:
ports:
- "3000:80"
###< symfony/mercure-bundle ###
+30
View File
@@ -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 ###
+7
View File
@@ -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": {
+2077 -1
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -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],
];
+6
View File
@@ -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
+8
View File
@@ -0,0 +1,8 @@
mercure:
hubs:
default:
url: '%env(MERCURE_URL)%'
public_url: '%env(MERCURE_PUBLIC_URL)%'
jwt:
secret: '%env(MERCURE_JWT_SECRET)%'
publish: '*'
+18
View File
@@ -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://'
+79
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
sentry:
dsn: '%env(SENTRY_DSN)%'
register_error_listener: true
options:
environment: '%kernel.environment%'
traces_sample_rate: 0.0
+8
View File
@@ -0,0 +1,8 @@
framework:
rate_limiter:
signal_submission:
policy: 'token_bucket'
limit: 5
rate:
interval: '1 minute'
amount: 1
+11
View File
@@ -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
View File
@@ -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)');
}
}
+25 -84
View File
@@ -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);
}
}
+5 -2
View File
@@ -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);
-14
View File
@@ -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,
) {
}
}
+13 -12
View File
@@ -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,
]);
}
}
}
+16
View File
@@ -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,
) {
}
}
+59
View File
@@ -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;
}
}
+27 -6
View File
@@ -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(),
]);
}
}
+66
View File
@@ -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);
}
}
}
+57
View File
@@ -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);
}
}