feat(live): add web track map (#32)

Subscribe to SignalR Position.z and CarData.z, decode DEFLATE payloads, stream throttled positions over SSE, and render live car dots against cached track outline bounds with tap telemetry.

Alignment spike: no checked-in or locally cached real Position.z samples were available in this isolated worktree; verified both streams expose the official raw F1 X/Y/Z coordinate contract and implemented shared-bounds normalization against prefetched OpenF1 outlines. Fallback build-outline-from-stream was not taken.

Playwright remains out of scope for live rendering because BOXBOX_DISABLE_LIVE is used there; coverage is via parser, web handler/SSE, pure transform, and seeded component tests.
This commit is contained in:
Aman Tahiliani
2026-07-03 19:34:09 -04:00
committed by GitHub
parent 5408a45bbd
commit 7263949260
15 changed files with 1076 additions and 18 deletions

View File

@@ -1046,21 +1046,35 @@ type trackPoint struct {
Y float64 `json:"y"`
}
type trackBounds struct {
MinX float64 `json:"minX"`
MaxX float64 `json:"maxX"`
MinY float64 `json:"minY"`
MaxY float64 `json:"maxY"`
}
type trackOutlineResponse struct {
CircuitKey int `json:"circuit_key"`
Points []trackPoint `json:"points"`
Bounds trackBounds `json:"bounds"`
}
func (s *Server) handleTrackOutline(w http.ResponseWriter, r *http.Request) {
circuitKey, err := strconv.Atoi(r.URL.Query().Get("circuit_key"))
if err != nil || circuitKey == 0 {
http.Error(w, "circuit_key required", http.StatusBadRequest)
return
}
year, _ := strconv.Atoi(r.URL.Query().Get("year"))
if year == 0 {
year = time.Now().Year()
}
circuitKey, err := strconv.Atoi(r.URL.Query().Get("circuit_key"))
if err != nil {
circuitKey = 0
}
if circuitKey == 0 {
circuitKey = s.resolveCircuitKey(year, r.URL.Query().Get("meeting_name"), r.URL.Query().Get("circuit_name"))
}
if circuitKey == 0 {
http.Error(w, "circuit_key or live meeting identity required", http.StatusBadRequest)
return
}
locs, ok := s.client.Cache().GetTrackOutline(circuitKey, year)
if !ok || len(locs) == 0 {
@@ -1110,7 +1124,85 @@ func (s *Server) handleTrackOutline(w http.ResponseWriter, r *http.Request) {
}
}
writeJSON(w, trackOutlineResponse{CircuitKey: circuitKey, Points: points})
writeJSON(w, trackOutlineResponse{
CircuitKey: circuitKey,
Points: points,
Bounds: trackBounds{MinX: minX, MaxX: maxX, MinY: minY, MaxY: maxY},
})
}
func (s *Server) resolveCircuitKey(year int, meetingName, circuitName string) int {
if !s.hasLocalQuery() {
return 0
}
meetings, err := s.query.ListMeetingsByYear(year)
if err != nil {
return 0
}
wantMeeting := normalizeTrackIdentity(meetingName)
wantCircuit := normalizeTrackIdentity(circuitName)
bestScore := 0
bestCircuitKey := 0
for _, m := range meetings {
if m.CircuitKey == 0 {
continue
}
score := identityScore(wantMeeting, m.MeetingName, m.MeetingOfficialName, m.Location)
score += identityScore(wantCircuit, m.CircuitShortName, m.Location, m.MeetingName)
if score > bestScore {
bestScore = score
bestCircuitKey = m.CircuitKey
}
}
if bestScore == 0 {
return 0
}
return bestCircuitKey
}
func identityScore(want string, candidates ...string) int {
if want == "" {
return 0
}
best := 0
for _, candidate := range candidates {
got := normalizeTrackIdentity(candidate)
if got == "" {
continue
}
switch {
case got == want:
if best < 4 {
best = 4
}
case strings.Contains(got, want) || strings.Contains(want, got):
if best < 2 {
best = 2
}
}
}
return best
}
func normalizeTrackIdentity(s string) string {
s = strings.ToLower(s)
replacer := strings.NewReplacer(
"grand prix", "",
" gp", "",
"circuit", "",
"autodromo", "",
"autódromo", "",
"international", "",
"street", "",
" ", "",
"-", "",
"_", "",
".", "",
",", "",
"'", "",
"", "",
)
return strings.TrimSpace(replacer.Replace(s))
}
// --- /api/v1/strategy ---

View File

@@ -29,9 +29,10 @@ type SSEHub struct {
deregister chan *sseClient
broadcast chan sseEvent
mu sync.RWMutex
lastSnapshot *live.LiveStreamData
isLive bool
mu sync.RWMutex
lastSnapshot *live.LiveStreamData
lastPositions map[string]live.LivePositionData
isLive bool
}
func newSSEHub() *SSEHub {
@@ -52,6 +53,7 @@ func (h *SSEHub) run() {
// Send catch-up snapshot so new clients see current state immediately.
h.mu.RLock()
snap := h.lastSnapshot
positions := cloneLivePositions(h.lastPositions)
live := h.isLive
h.mu.RUnlock()
if snap != nil {
@@ -62,6 +64,14 @@ func (h *SSEHub) run() {
}
}
}
if len(positions) > 0 {
if data, err := json.Marshal(positions); err == nil {
select {
case c.ch <- formatSSEFrame("positions", data):
default:
}
}
}
case c := <-h.deregister:
if clients[c] {
@@ -122,6 +132,7 @@ func (s *Server) signalRLoop() {
s.hub.mu.Lock()
s.hub.isLive = false
s.hub.lastSnapshot = nil
s.hub.lastPositions = nil
s.hub.mu.Unlock()
if payload, err := json.Marshal(map[string]any{"data": nil, "is_live": false}); err == nil {
@@ -150,17 +161,33 @@ func (s *Server) connectAndDrain() error {
idleTimeout := 60 * time.Second
timer := time.NewTimer(idleTimeout)
defer timer.Stop()
lastPositionBroadcast := time.Time{}
for {
select {
case data := <-dataChan:
now := time.Now()
s.hub.mu.Lock()
s.hub.lastSnapshot = &data
if data.SnapshotUpdated {
s.hub.lastSnapshot = &data
}
if data.PositionUpdated && len(data.Positions) > 0 {
s.hub.lastPositions = cloneLivePositions(data.Positions)
}
s.hub.isLive = true
s.hub.mu.Unlock()
if payload, err := json.Marshal(map[string]any{"data": data, "is_live": true}); err == nil {
s.hub.broadcast <- sseEvent{name: "snapshot", data: payload}
if data.SnapshotUpdated {
if payload, err := json.Marshal(map[string]any{"data": data, "is_live": true}); err == nil {
s.hub.broadcast <- sseEvent{name: "snapshot", data: payload}
}
}
if data.PositionUpdated && len(data.Positions) > 0 && now.Sub(lastPositionBroadcast) >= 250*time.Millisecond {
if payload, err := json.Marshal(data.Positions); err == nil {
s.hub.broadcast <- sseEvent{name: "positions", data: payload}
lastPositionBroadcast = now
}
}
if !timer.Stop() {
@@ -177,6 +204,17 @@ func (s *Server) connectAndDrain() error {
}
}
func cloneLivePositions(in map[string]live.LivePositionData) map[string]live.LivePositionData {
if len(in) == 0 {
return nil
}
out := make(map[string]live.LivePositionData, len(in))
for k, v := range in {
out[k] = v
}
return out
}
// handleLiveState returns the current live data snapshot as JSON.
func (s *Server) handleLiveState(w http.ResponseWriter, r *http.Request) {
snap, isLive := s.hub.Snapshot()

View File

@@ -0,0 +1,76 @@
package web
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/AmanTahiliani/box-box/internal/live"
"github.com/AmanTahiliani/box-box/internal/models"
"github.com/AmanTahiliani/box-box/internal/store"
)
func TestHandleTrackOutlineReturnsBoundsAndResolvesLiveIdentity(t *testing.T) {
st := openTestStore(t)
if err := st.UpsertMeeting(store.Meeting{
MeetingKey: 1234,
MeetingName: "British Grand Prix",
Location: "Silverstone",
CircuitKey: 9,
CircuitShortName: "Silverstone",
Year: 2026,
}); err != nil {
t.Fatalf("UpsertMeeting() error = %v", err)
}
srv := testServer(t, st)
locs := []models.Location{
{X: -100, Y: 50, Z: 0},
{X: 0, Y: 100, Z: 0},
{X: 100, Y: 50, Z: 0},
}
if err := srv.client.Cache().SetTrackOutline(9, 2026, locs); err != nil {
t.Fatalf("SetTrackOutline() error = %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/track-outline?meeting_name=British+Grand+Prix&circuit_name=Silverstone&year=2026", nil)
rec := httptest.NewRecorder()
srv.handleTrackOutline(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
}
var resp trackOutlineResponse
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode response: %v", err)
}
if resp.CircuitKey != 9 {
t.Fatalf("circuit_key = %d, want 9", resp.CircuitKey)
}
if resp.Bounds.MinX != -100 || resp.Bounds.MaxX != 100 || resp.Bounds.MinY != 50 || resp.Bounds.MaxY != 100 {
t.Fatalf("bounds = %+v", resp.Bounds)
}
if len(resp.Points) != 3 {
t.Fatalf("points len = %d, want 3", len(resp.Points))
}
}
func TestPositionsSSEFrameShape(t *testing.T) {
payload, err := json.Marshal(map[string]live.LivePositionData{
"1": {X: 100, Y: -50, Z: 2, Status: "OnTrack"},
})
if err != nil {
t.Fatalf("marshal positions: %v", err)
}
frame := string(formatSSEFrame("positions", payload))
if !strings.HasPrefix(frame, "event: positions\ndata: ") {
t.Fatalf("frame prefix = %q", frame)
}
if !strings.Contains(frame, `"1":{"x":100,"y":-50,"z":2,"status":"OnTrack"}`) {
t.Fatalf("frame data = %q", frame)
}
if !strings.HasSuffix(frame, "\n\n") {
t.Fatalf("frame should end with blank line: %q", frame)
}
}