mirror of
https://github.com/AmanTahiliani/box-box.git
synced 2026-08-07 19:56:18 -04:00
Compare commits
1 Commits
feat/issue
...
feat/issue
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0fd252096 |
46
cmd/main.go
46
cmd/main.go
@@ -27,6 +27,7 @@ func main() {
|
|||||||
ingestMeeting := flag.Int("ingest-meeting", 0, "Ingest meeting metadata and Race Hub datasets for all sessions")
|
ingestMeeting := flag.Int("ingest-meeting", 0, "Ingest meeting metadata and Race Hub datasets for all sessions")
|
||||||
ingestSession := flag.Int("ingest-session", 0, "Ingest Race Hub datasets for a session key")
|
ingestSession := flag.Int("ingest-session", 0, "Ingest Race Hub datasets for a session key")
|
||||||
ingestNews := flag.Bool("ingest-news", false, "Refresh RSS/Atom paddock briefing feeds")
|
ingestNews := flag.Bool("ingest-news", false, "Refresh RSS/Atom paddock briefing feeds")
|
||||||
|
prefetchTrackOutlines := flag.Int("prefetch-track-outlines", 0, "Warm the web track-outline cache for a season year (for web-only hosts, run before --web so /api/v1/track-outline can serve live maps)")
|
||||||
dryRun := flag.Bool("dry-run", false, "Preview ingestion without writing domain rows")
|
dryRun := flag.Bool("dry-run", false, "Preview ingestion without writing domain rows")
|
||||||
force := flag.Bool("force", false, "Re-ingest datasets even if already tracked in the session_coverage table as completed")
|
force := flag.Bool("force", false, "Re-ingest datasets even if already tracked in the session_coverage table as completed")
|
||||||
coverageYear := flag.Int("coverage", 0, "Show season coverage report for the given year")
|
coverageYear := flag.Int("coverage", 0, "Show season coverage report for the given year")
|
||||||
@@ -76,11 +77,21 @@ func main() {
|
|||||||
if *ingestNews {
|
if *ingestNews {
|
||||||
ingestFlags++
|
ingestFlags++
|
||||||
}
|
}
|
||||||
|
if *prefetchTrackOutlines != 0 {
|
||||||
|
ingestFlags++
|
||||||
|
}
|
||||||
if ingestFlags > 0 {
|
if ingestFlags > 0 {
|
||||||
if ingestFlags > 1 {
|
if ingestFlags > 1 {
|
||||||
fmt.Fprintln(os.Stderr, "box-box: only one of --ingest-year, --backfill-season, --ingest-meeting, --ingest-session, or --ingest-news may be set")
|
fmt.Fprintln(os.Stderr, "box-box: only one of --ingest-year, --backfill-season, --ingest-meeting, --ingest-session, --ingest-news, or --prefetch-track-outlines may be set")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
if *prefetchTrackOutlines != 0 {
|
||||||
|
if err := runTrackOutlinePrefetch(client, *prefetchTrackOutlines); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "box-box track outline prefetch error: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
if *ingestNews {
|
if *ingestNews {
|
||||||
if err := runNewsIngestion(*dryRun, *dbPath); err != nil {
|
if err := runNewsIngestion(*dryRun, *dbPath); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "box-box ingest error: %v\n", err)
|
fmt.Fprintf(os.Stderr, "box-box ingest error: %v\n", err)
|
||||||
@@ -88,7 +99,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
yearVal := *ingestYear
|
yearVal := *ingestYear
|
||||||
if *backfillSeason != 0 {
|
if *backfillSeason != 0 {
|
||||||
yearVal = *backfillSeason
|
yearVal = *backfillSeason
|
||||||
@@ -174,6 +185,35 @@ func runIngestion(client *api.OpenF1Client, year, meetingKey, sessionKey int, fo
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func runTrackOutlinePrefetch(client *api.OpenF1Client, year int) error {
|
||||||
|
log.SetOutput(os.Stderr)
|
||||||
|
|
||||||
|
fmt.Fprintf(os.Stderr, "track outlines: warming HTTP cache %s for %d\n", api.DefaultCacheDBPath(), year)
|
||||||
|
|
||||||
|
meetings, err := client.GetMeetingsForYear(year)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("fetch meetings for %d: %w", year, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := client.PrefetchTrackOutlinesForYear(year, meetings)
|
||||||
|
fmt.Printf(
|
||||||
|
"track outlines %d: cached %d/%d unique circuit(s) before, %d/%d after; %d skipped, %d fetched, %d failed\n",
|
||||||
|
result.Year,
|
||||||
|
result.CachedBefore,
|
||||||
|
result.UniqueCircuits,
|
||||||
|
result.CachedAfter,
|
||||||
|
result.UniqueCircuits,
|
||||||
|
result.Skipped,
|
||||||
|
result.Fetched,
|
||||||
|
result.Failed,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.CachedAfter == 0 {
|
||||||
|
return fmt.Errorf("cached zero track outlines for %d", year)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func runNewsIngestion(dryRun bool, dbPath string) error {
|
func runNewsIngestion(dryRun bool, dbPath string) error {
|
||||||
log.SetOutput(os.Stderr)
|
log.SetOutput(os.Stderr)
|
||||||
|
|
||||||
@@ -275,7 +315,7 @@ func runCoverageReport(year int, dbPath string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("\n--- Season %d Coverage Report ---\n\n", year)
|
fmt.Printf("\n--- Season %d Coverage Report ---\n\n", year)
|
||||||
fmt.Printf("%-35s | %-5s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s\n",
|
fmt.Printf("%-35s | %-5s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s | %-2s\n",
|
||||||
"Meeting / Session (Key)", "ID", "DR", "SR", "SG", "ST", "PS", "PO", "RC", "WE", "LA")
|
"Meeting / Session (Key)", "ID", "DR", "SR", "SG", "ST", "PS", "PO", "RC", "WE", "LA")
|
||||||
fmt.Println(strings.Repeat("-", 82))
|
fmt.Println(strings.Repeat("-", 82))
|
||||||
|
|
||||||
|
|||||||
@@ -229,9 +229,7 @@ export function CompareView({ sessionKey, results, drivers }: Props) {
|
|||||||
<div>
|
<div>
|
||||||
<div className="compare-section-title">Race pace</div>
|
<div className="compare-section-title">Race pace</div>
|
||||||
<div className="compare-section-meta">
|
<div className="compare-section-meta">
|
||||||
Cumulative lap-time delta vs {referenceLabel ?? 'reference'}. Deltas are plotted
|
Cumulative lap-time delta vs {referenceLabel ?? 'reference'}
|
||||||
only where the reference lap is valid; gaps appear when the reference has no lap
|
|
||||||
time.
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<SectionState
|
<SectionState
|
||||||
|
|||||||
@@ -21,31 +21,15 @@ export function formatDeltaSeconds(delta: number): string {
|
|||||||
return `${sign}${delta.toFixed(1)}s`
|
return `${sign}${delta.toFixed(1)}s`
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function buildCumulative(lapTimes: ReadonlyArray<number | null>): number[] {
|
||||||
* Cumulative lap time aligned to reference-valid laps only.
|
|
||||||
* Laps where the reference is null are skipped for every series so later deltas
|
|
||||||
* do not compare against a frozen baseline while challengers keep accumulating.
|
|
||||||
*/
|
|
||||||
function buildAlignedCumulative(
|
|
||||||
lapTimes: ReadonlyArray<number | null>,
|
|
||||||
referenceLapTimes: ReadonlyArray<number | null>,
|
|
||||||
): number[] {
|
|
||||||
const cumulative: number[] = []
|
const cumulative: number[] = []
|
||||||
let running = 0
|
let running = 0
|
||||||
const length = Math.max(lapTimes.length, referenceLapTimes.length)
|
for (const lap of lapTimes) {
|
||||||
|
if (lap !== null) {
|
||||||
for (let i = 0; i < length; i++) {
|
|
||||||
if (referenceLapTimes[i] == null) {
|
|
||||||
cumulative.push(running)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const lap = lapTimes[i]
|
|
||||||
if (lap != null) {
|
|
||||||
running += lap
|
running += lap
|
||||||
}
|
}
|
||||||
cumulative.push(running)
|
cumulative.push(running)
|
||||||
}
|
}
|
||||||
|
|
||||||
return cumulative
|
return cumulative
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,8 +47,7 @@ function resolveReference(
|
|||||||
/**
|
/**
|
||||||
* Compute per-lap cumulative time delta for each non-reference driver.
|
* Compute per-lap cumulative time delta for each non-reference driver.
|
||||||
* Positive = behind reference; negative = ahead.
|
* Positive = behind reference; negative = ahead.
|
||||||
* Deltas are only emitted where the reference lap is valid; reference-null laps
|
* Null laps carry cumulative forward but emit null in deltas (skip when plotting).
|
||||||
* gap every series. Challenger-null laps gap only that driver's line.
|
|
||||||
*/
|
*/
|
||||||
export function computeCumulativeDeltas(
|
export function computeCumulativeDeltas(
|
||||||
series: ReadonlyArray<DeltaSeries>,
|
series: ReadonlyArray<DeltaSeries>,
|
||||||
@@ -73,22 +56,24 @@ export function computeCumulativeDeltas(
|
|||||||
const reference = resolveReference(series, referenceLabel)
|
const reference = resolveReference(series, referenceLabel)
|
||||||
if (!reference) return []
|
if (!reference) return []
|
||||||
|
|
||||||
const refLapTimes = reference.lapTimes
|
const refCumulative = buildCumulative(reference.lapTimes)
|
||||||
const refCumulative = buildAlignedCumulative(refLapTimes, refLapTimes)
|
|
||||||
|
|
||||||
return series
|
return series
|
||||||
.filter((s) => s.label !== reference.label)
|
.filter((s) => s.label !== reference.label)
|
||||||
.map((driver) => {
|
.map((driver) => {
|
||||||
const driverCumulative = buildAlignedCumulative(driver.lapTimes, refLapTimes)
|
const driverCumulative = buildCumulative(driver.lapTimes)
|
||||||
const lapCount = Math.max(driver.lapTimes.length, refCumulative.length)
|
const lapCount = Math.max(driver.lapTimes.length, refCumulative.length)
|
||||||
const deltas: (number | null)[] = []
|
const deltas: (number | null)[] = []
|
||||||
|
|
||||||
for (let i = 0; i < lapCount; i++) {
|
for (let i = 0; i < lapCount; i++) {
|
||||||
if (refLapTimes[i] == null || driver.lapTimes[i] == null) {
|
if (driver.lapTimes[i] === null) {
|
||||||
deltas.push(null)
|
deltas.push(null)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
deltas.push(driverCumulative[i] - refCumulative[i])
|
const refValue = refCumulative[i] ?? refCumulative[refCumulative.length - 1] ?? 0
|
||||||
|
const driverValue =
|
||||||
|
driverCumulative[i] ?? driverCumulative[driverCumulative.length - 1] ?? 0
|
||||||
|
deltas.push(driverValue - refValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ describe('computeCumulativeDeltas', () => {
|
|||||||
expect(result[0].deltas[2]).toBeCloseTo(2)
|
expect(result[0].deltas[2]).toBeCloseTo(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('emits null for challenger missing lap times while carrying cumulative forward', () => {
|
it('emits null for missing lap times while carrying cumulative forward', () => {
|
||||||
const withNull: DeltaSeries = {
|
const withNull: DeltaSeries = {
|
||||||
label: 'NOR',
|
label: 'NOR',
|
||||||
color: '#FF8000',
|
color: '#FF8000',
|
||||||
@@ -60,41 +60,6 @@ describe('computeCumulativeDeltas', () => {
|
|||||||
expect(result[0].deltas[2]).toBeCloseTo(-92)
|
expect(result[0].deltas[2]).toBeCloseTo(-92)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('gaps all drivers when the reference lap is null and resumes without that window', () => {
|
|
||||||
const refWithNull: DeltaSeries = {
|
|
||||||
label: 'VER',
|
|
||||||
color: '#3671C6',
|
|
||||||
lapTimes: [90, null, 92],
|
|
||||||
}
|
|
||||||
const validChallenger: DeltaSeries = {
|
|
||||||
label: 'HAM',
|
|
||||||
color: '#E8002D',
|
|
||||||
lapTimes: [89, 91, 90],
|
|
||||||
}
|
|
||||||
const result = computeCumulativeDeltas([refWithNull, validChallenger])
|
|
||||||
expect(result[0].deltas[0]).toBeCloseTo(-1)
|
|
||||||
expect(result[0].deltas[1]).toBeNull()
|
|
||||||
// Lap 3 excludes the reference-null window for both: (89+90) - (90+92) = -3
|
|
||||||
expect(result[0].deltas[2]).toBeCloseTo(-3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('gaps challenger laps beyond a shorter reference series', () => {
|
|
||||||
const shortReference: DeltaSeries = {
|
|
||||||
label: 'VER',
|
|
||||||
color: '#3671C6',
|
|
||||||
lapTimes: [90, 91],
|
|
||||||
}
|
|
||||||
const longerChallenger: DeltaSeries = {
|
|
||||||
label: 'HAM',
|
|
||||||
color: '#E8002D',
|
|
||||||
lapTimes: [89, 92, 90],
|
|
||||||
}
|
|
||||||
const result = computeCumulativeDeltas([shortReference, longerChallenger])
|
|
||||||
expect(result[0].deltas[0]).toBeCloseTo(-1)
|
|
||||||
expect(result[0].deltas[1]).toBeCloseTo(0)
|
|
||||||
expect(result[0].deltas[2]).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns an empty array when only one series is provided', () => {
|
it('returns an empty array when only one series is provided', () => {
|
||||||
expect(computeCumulativeDeltas([reference])).toEqual([])
|
expect(computeCumulativeDeltas([reference])).toEqual([])
|
||||||
})
|
})
|
||||||
@@ -132,19 +97,6 @@ describe('DeltaTimeGraph', () => {
|
|||||||
expect(screen.queryByTestId('delta-line-VER')).not.toBeInTheDocument()
|
expect(screen.queryByTestId('delta-line-VER')).not.toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('splits polylines at reference-null laps', () => {
|
|
||||||
const refWithNull: DeltaSeries = {
|
|
||||||
label: 'VER',
|
|
||||||
color: '#3671C6',
|
|
||||||
lapTimes: [90, null, 92],
|
|
||||||
}
|
|
||||||
const { container } = render(
|
|
||||||
<DeltaTimeGraph series={[refWithNull, challenger]} />,
|
|
||||||
)
|
|
||||||
const lines = container.querySelectorAll('.delta-graph-driver-line')
|
|
||||||
expect(lines.length).toBeGreaterThan(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('shows a crosshair tooltip on hover', () => {
|
it('shows a crosshair tooltip on hover', () => {
|
||||||
vi.spyOn(SVGSVGElement.prototype, 'getBoundingClientRect').mockReturnValue({
|
vi.spyOn(SVGSVGElement.prototype, 'getBoundingClientRect').mockReturnValue({
|
||||||
x: 0,
|
x: 0,
|
||||||
@@ -166,31 +118,4 @@ describe('DeltaTimeGraph', () => {
|
|||||||
expect(screen.getByText(/Lap 1/)).toBeInTheDocument()
|
expect(screen.getByText(/Lap 1/)).toBeInTheDocument()
|
||||||
vi.restoreAllMocks()
|
vi.restoreAllMocks()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('omits tooltip rows on reference-null laps', () => {
|
|
||||||
vi.spyOn(SVGSVGElement.prototype, 'getBoundingClientRect').mockReturnValue({
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
left: 0,
|
|
||||||
top: 0,
|
|
||||||
width: 640,
|
|
||||||
height: 220,
|
|
||||||
right: 640,
|
|
||||||
bottom: 220,
|
|
||||||
toJSON: () => ({}),
|
|
||||||
})
|
|
||||||
const refWithNull: DeltaSeries = {
|
|
||||||
label: 'VER',
|
|
||||||
color: '#3671C6',
|
|
||||||
lapTimes: [90, null, 92],
|
|
||||||
}
|
|
||||||
const { container } = render(
|
|
||||||
<DeltaTimeGraph series={[refWithNull, challenger]} />,
|
|
||||||
)
|
|
||||||
const hoverLayer = container.querySelector('.delta-graph-hover-layer')
|
|
||||||
fireEvent.mouseMove(hoverLayer!, { clientX: 352, clientY: 100 })
|
|
||||||
expect(screen.getByTestId('delta-crosshair')).toBeInTheDocument()
|
|
||||||
expect(screen.queryByTestId('delta-tooltip')).not.toBeInTheDocument()
|
|
||||||
vi.restoreAllMocks()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -94,6 +94,12 @@ func cacheDBPath() string {
|
|||||||
return filepath.Join(".cache", "box-box", "cache.db")
|
return filepath.Join(".cache", "box-box", "cache.db")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DefaultCacheDBPath returns the HTTP cache database path used by the OpenF1
|
||||||
|
// client in both TUI and web modes.
|
||||||
|
func DefaultCacheDBPath() string {
|
||||||
|
return cacheDBPath()
|
||||||
|
}
|
||||||
|
|
||||||
// ttlForURL determines the appropriate TTL based on the URL pattern.
|
// ttlForURL determines the appropriate TTL based on the URL pattern.
|
||||||
// Returns 0 (CacheTTLForever) for historical data that will never change.
|
// Returns 0 (CacheTTLForever) for historical data that will never change.
|
||||||
func ttlForURL(url string) time.Duration {
|
func ttlForURL(url string) time.Duration {
|
||||||
|
|||||||
@@ -623,6 +623,19 @@ func (c *OpenF1Client) GetTeamRadio(sessionKey, driverNumber int) ([]models.Team
|
|||||||
// to maximise the chance of finding data quickly.
|
// to maximise the chance of finding data quickly.
|
||||||
var candidateDrivers = []int{1, 11, 44, 16, 55, 4, 14, 63, 81, 24}
|
var candidateDrivers = []int{1, 11, 44, 16, 55, 4, 14, 63, 81, 24}
|
||||||
|
|
||||||
|
// TrackOutlinePrefetchResult summarizes a season track-outline cache warming
|
||||||
|
// run. Counts are scoped to the unique non-zero circuit keys in the provided
|
||||||
|
// meeting list.
|
||||||
|
type TrackOutlinePrefetchResult struct {
|
||||||
|
Year int
|
||||||
|
UniqueCircuits int
|
||||||
|
CachedBefore int
|
||||||
|
CachedAfter int
|
||||||
|
Skipped int
|
||||||
|
Fetched int
|
||||||
|
Failed int
|
||||||
|
}
|
||||||
|
|
||||||
// PrefetchTrackOutlines fetches GPS location data for every circuit in the
|
// PrefetchTrackOutlines fetches GPS location data for every circuit in the
|
||||||
// provided meeting list and stores it in the cache so the track map tab can
|
// provided meeting list and stores it in the cache so the track map tab can
|
||||||
// render during live sessions when the free-tier API is locked.
|
// render during live sessions when the free-tier API is locked.
|
||||||
@@ -632,28 +645,58 @@ var candidateDrivers = []int{1, 11, 44, 16, 55, 4, 14, 63, 81, 24}
|
|||||||
// Errors per-circuit are silently ignored — this is a best-effort operation
|
// Errors per-circuit are silently ignored — this is a best-effort operation
|
||||||
// and must never block or crash the main UI.
|
// and must never block or crash the main UI.
|
||||||
func (c *OpenF1Client) PrefetchTrackOutlines(meetings []models.Meeting) {
|
func (c *OpenF1Client) PrefetchTrackOutlines(meetings []models.Meeting) {
|
||||||
|
year := time.Now().Year()
|
||||||
|
for _, m := range meetings {
|
||||||
|
if m.Year != 0 {
|
||||||
|
year = m.Year
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = c.PrefetchTrackOutlinesForYear(year, meetings)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrefetchTrackOutlinesForYear fetches and caches track outlines for unique
|
||||||
|
// circuits in the provided meeting list, storing them under the explicit season
|
||||||
|
// year. Unlike PrefetchTrackOutlines, it returns accounting suitable for CLI
|
||||||
|
// cache-warming workflows.
|
||||||
|
func (c *OpenF1Client) PrefetchTrackOutlinesForYear(year int, meetings []models.Meeting) TrackOutlinePrefetchResult {
|
||||||
const maxWorkers = 3
|
const maxWorkers = 3
|
||||||
|
|
||||||
year := time.Now().Year()
|
result := TrackOutlinePrefetchResult{Year: year}
|
||||||
|
uniqueByCircuit := make(map[int]models.Meeting)
|
||||||
// Filter to meetings that need fetching.
|
var unique []models.Meeting
|
||||||
var pending []models.Meeting
|
|
||||||
for _, m := range meetings {
|
for _, m := range meetings {
|
||||||
if m.CircuitKey == 0 {
|
if m.CircuitKey == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if _, exists := uniqueByCircuit[m.CircuitKey]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
uniqueByCircuit[m.CircuitKey] = m
|
||||||
|
unique = append(unique, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.UniqueCircuits = len(unique)
|
||||||
|
|
||||||
|
// Filter to meetings that need fetching.
|
||||||
|
var pending []models.Meeting
|
||||||
|
for _, m := range unique {
|
||||||
if _, ok := c.cache.GetTrackOutline(m.CircuitKey, year); ok {
|
if _, ok := c.cache.GetTrackOutline(m.CircuitKey, year); ok {
|
||||||
|
result.CachedBefore++
|
||||||
|
result.Skipped++
|
||||||
continue // already cached for this season
|
continue // already cached for this season
|
||||||
}
|
}
|
||||||
pending = append(pending, m)
|
pending = append(pending, m)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(pending) == 0 {
|
if len(pending) == 0 {
|
||||||
return
|
result.CachedAfter = result.CachedBefore
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
sem := make(chan struct{}, maxWorkers)
|
sem := make(chan struct{}, maxWorkers)
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
|
var mu sync.Mutex
|
||||||
|
|
||||||
for _, mtg := range pending {
|
for _, mtg := range pending {
|
||||||
mtg := mtg // capture
|
mtg := mtg // capture
|
||||||
@@ -662,19 +705,34 @@ func (c *OpenF1Client) PrefetchTrackOutlines(meetings []models.Meeting) {
|
|||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() { <-sem }()
|
defer func() { <-sem }()
|
||||||
c.prefetchCircuit(mtg, year)
|
ok := c.prefetchCircuit(mtg, year)
|
||||||
|
mu.Lock()
|
||||||
|
if ok {
|
||||||
|
result.Fetched++
|
||||||
|
} else {
|
||||||
|
result.Failed++
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|
||||||
|
for _, m := range unique {
|
||||||
|
if _, ok := c.cache.GetTrackOutline(m.CircuitKey, year); ok {
|
||||||
|
result.CachedAfter++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// prefetchCircuit fetches the track outline for a single meeting and stores it.
|
// prefetchCircuit fetches the track outline for a single meeting and stores it.
|
||||||
// It prefers completed sessions (past date_end) so the data is full and stable.
|
// It prefers completed sessions (past date_end) so the data is full and stable.
|
||||||
func (c *OpenF1Client) prefetchCircuit(mtg models.Meeting, year int) {
|
func (c *OpenF1Client) prefetchCircuit(mtg models.Meeting, year int) bool {
|
||||||
sessions, err := c.GetSessionsForMeeting(int(mtg.MeetingKey))
|
sessions, err := c.GetSessionsForMeeting(int(mtg.MeetingKey))
|
||||||
if err != nil || len(sessions) == 0 {
|
if err != nil || len(sessions) == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pick the best session: prefer a completed race, then any session with
|
// Pick the best session: prefer a completed race, then any session with
|
||||||
@@ -696,7 +754,7 @@ func (c *OpenF1Client) prefetchCircuit(mtg models.Meeting, year int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if bestSession == nil {
|
if bestSession == nil {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try candidate drivers in order until we find one with enough points.
|
// Try candidate drivers in order until we find one with enough points.
|
||||||
@@ -706,7 +764,7 @@ func (c *OpenF1Client) prefetchCircuit(mtg models.Meeting, year int) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Store under the circuit key for this year and stop.
|
// Store under the circuit key for this year and stop.
|
||||||
_ = c.cache.SetTrackOutline(mtg.CircuitKey, year, locs)
|
return c.cache.SetTrackOutline(mtg.CircuitKey, year, locs) == nil
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
109
internal/api/track_outline_prefetch_test.go
Normal file
109
internal/api/track_outline_prefetch_test.go
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/AmanTahiliani/box-box/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTrackOutlineTestClient(t *testing.T, srvURL string) *OpenF1Client {
|
||||||
|
t.Helper()
|
||||||
|
t.Setenv("HOME", t.TempDir())
|
||||||
|
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||||
|
|
||||||
|
c := NewOpenF1Client(srvURL, 5*time.Second)
|
||||||
|
c.pacer = &requestPacer{}
|
||||||
|
t.Cleanup(func() { _ = c.Close() })
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrefetchTrackOutlinesForYearSkipsCachedAndWritesLocations(t *testing.T) {
|
||||||
|
var sessionsByMeeting = map[string][]models.Session{
|
||||||
|
"202": {
|
||||||
|
{
|
||||||
|
SessionKey: 9002,
|
||||||
|
SessionName: "Race",
|
||||||
|
MeetingKey: 202,
|
||||||
|
CircuitKey: 2,
|
||||||
|
DateEnd: "2026-01-01T12:00:00+00:00",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
var sessionsRequested []string
|
||||||
|
var locationsRequested []string
|
||||||
|
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/v1/sessions":
|
||||||
|
meetingKey := r.URL.Query().Get("meeting_key")
|
||||||
|
sessionsRequested = append(sessionsRequested, meetingKey)
|
||||||
|
_ = json.NewEncoder(w).Encode(sessionsByMeeting[meetingKey])
|
||||||
|
case "/v1/location":
|
||||||
|
sessionKey := r.URL.Query().Get("session_key")
|
||||||
|
driverNumber := r.URL.Query().Get("driver_number")
|
||||||
|
locationsRequested = append(locationsRequested, sessionKey+"/"+driverNumber)
|
||||||
|
_ = json.NewEncoder(w).Encode(testLocations(9002, 1, 51))
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected request path %s", r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
client := newTrackOutlineTestClient(t, srv.URL)
|
||||||
|
if err := client.Cache().SetTrackOutline(1, 2026, testLocations(9001, 1, 51)); err != nil {
|
||||||
|
t.Fatalf("SetTrackOutline() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := client.PrefetchTrackOutlinesForYear(2026, []models.Meeting{
|
||||||
|
{MeetingKey: 101, Year: 2026, Circuit: models.Circuit{CircuitKey: 1}},
|
||||||
|
{MeetingKey: 202, Year: 2026, Circuit: models.Circuit{CircuitKey: 2}},
|
||||||
|
{MeetingKey: 303, Year: 2026, Circuit: models.Circuit{CircuitKey: 2}},
|
||||||
|
})
|
||||||
|
|
||||||
|
if result.UniqueCircuits != 2 {
|
||||||
|
t.Fatalf("UniqueCircuits = %d, want 2", result.UniqueCircuits)
|
||||||
|
}
|
||||||
|
if result.CachedBefore != 1 || result.Skipped != 1 || result.Fetched != 1 || result.Failed != 0 || result.CachedAfter != 2 {
|
||||||
|
t.Fatalf("unexpected result: %+v", result)
|
||||||
|
}
|
||||||
|
if got, want := len(sessionsRequested), 1; got != want {
|
||||||
|
t.Fatalf("sessions requested %d time(s), want %d: %v", got, want, sessionsRequested)
|
||||||
|
}
|
||||||
|
if sessionsRequested[0] != "202" {
|
||||||
|
t.Fatalf("requested meeting %s, want 202", sessionsRequested[0])
|
||||||
|
}
|
||||||
|
if got, want := len(locationsRequested), 1; got != want {
|
||||||
|
t.Fatalf("locations requested %d time(s), want %d: %v", got, want, locationsRequested)
|
||||||
|
}
|
||||||
|
if locationsRequested[0] != "9002/1" {
|
||||||
|
t.Fatalf("requested location %s, want 9002/1", locationsRequested[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
locs, ok := client.Cache().GetTrackOutline(2, 2026)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("expected circuit 2 outline to be cached")
|
||||||
|
}
|
||||||
|
if len(locs) != 51 {
|
||||||
|
t.Fatalf("cached %d locations, want 51", len(locs))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testLocations(sessionKey, driverNumber, count int) []models.Location {
|
||||||
|
locs := make([]models.Location, count)
|
||||||
|
for i := range locs {
|
||||||
|
locs[i] = models.Location{
|
||||||
|
Date: "2026-01-01T12:00:" + strconv.Itoa(i%60) + "+00:00",
|
||||||
|
DriverNumber: driverNumber,
|
||||||
|
MeetingKey: 202,
|
||||||
|
SessionKey: sessionKey,
|
||||||
|
X: float64(i),
|
||||||
|
Y: float64(i * 2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return locs
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user