Skip to content
punkouter27Public

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

PoTraffic - Empirical Commute Volatility Engine

PoTraffic is a Blazor WebAssembly + ASP.NET Core application that measures commute route volatility using Google Maps travel times (TomTom supplies traffic incidents only). It records travel-time samples on a schedule, computes route baselines, and flags congestion or reroute anomalies in real time.

Architecture

Layer Technology
Front-end Blazor WebAssembly (.NET 10) + Radzen Blazor
Back-end ASP.NET Core Minimal API (.NET 10); feature-folder handlers called from minimal-API endpoints
Persistence Azure Table Storage, Azurite locally
Background Jobs Table Storage-backed scheduler
Auth Microsoft OAuth in dev/prod, Testing-only auth bypasses
Logging Serilog + WASM client log forwarding
Observability OpenTelemetry + Azure Monitor / Application Insights; app spans (PoTraffic.Api source: jobs, Google Maps / TomTom / Open-Meteo calls, Table Storage writes) export only when App Insights or OTEL_EXPORTER_OTLP_ENDPOINT is configured
Testing xUnit + NSubstitute, integration tests, Playwright .NET E2E

The API and Blazor WASM static files are hosted together on Azure App Service. CORS is intentionally not configured.

Project Structure

src/
  PoTraffic.Api/             # ASP.NET Core host, Features/ slices, Infrastructure/
  PoTraffic.Client/          # Blazor WASM front-end
  PoTraffic.Shared/          # DTOs shared by API and client
  PoTraffic.Mobile/          # .NET MAUI phone app (Android/iOS) — not in the .slnx; CI's `mobile` job builds Android
tests/
  PoTraffic.Unit/
  PoTraffic.Integration/
  PoTraffic.E2EUI/

Prerequisites

  • .NET 10 SDK
  • Docker Desktop for Azurite
  • Azure CLI for local Key Vault access

Quick Start

dotnet restore
dotnet build
./scripts/start-dev.ps1

The startup script stops a stale PoTraffic host, starts PoTraffic's own Azurite (host port 10012, so it never collides with another project's Azurite on 10002), and launches the hosted API/client. If another app already holds 5001/5000 it uses 5011/5010 (then 5021/5020) and prints the URL.

URL Purpose
https://localhost:5001 Hosted API + Blazor client
https://localhost:5001/scalar/v1 Scalar API reference in Development
https://localhost:5001/diag System status page, no sign-in needed; data from GET /api/diag
https://localhost:5001/health Readiness (503 when a dependency is Unhealthy)
https://localhost:5001/health/live Liveness, with the deployed commit in X-Commit
https://localhost:5001/health/json Machine-readable dependency status
https://localhost:5001/api/diag/keyvault Admin-only Key Vault diagnostics API

Running Tests

./scripts/run-tests.ps1

The script fails fast if a tier holds more test cases than its cap — 100 unit, 50 integration, 25 E2E API, 25 E2E UI (theory rows count individually). Merge or trim tests rather than raising a cap. Real counts (2026-11-21): Unit 87, Integration 36, E2E API 13, E2E UI 17. CI runs Unit and Integration; the E2E tiers skip with one clear message when no app is running. pwsh scripts/run-e2eui.ps1 -Tier All runs both E2E tiers against the Release publish (the build that deploys).

Or run individual suites:

dotnet test tests/PoTraffic.Unit
dotnet test tests/PoTraffic.Integration
dotnet test tests/PoTraffic.E2EUI

Test caps: at most 100 unit, 50 integration, 25 API (E2ETests/Api) and 25 UI tests — counted as test cases, so each [Theory] row counts. Merge overlapping tests before adding new ones. [ApiSkipUnlessReady] probes E2E_BASE_URL when it is set.

Key Concepts

Routes have monitoring windows. When a window is active, the scheduler records traffic samples at configured intervals until the window closes. Samples are stored in Table Storage and used to build baseline travel-time bands per route and time slot.

On a route's Schedule tab a user can edit the schedule (swapped in one save, so a rejected edit keeps the old one), change the addresses (only a changed address is geocoded again; history is kept), and pause or resume monitoring (paused keeps the schedule and history but stops the poll chain; Stop only ends today's session). The sample commute's history is generated, so it never counts toward spend, admin usage or the fleet volatility chart. With mock providers on, address suggestions are canned and free.

Cost controls and feature flags, all editable at runtime by administrators on the Admin page (Config tab, or PUT /api/admin/configuration/{key}). Every key, default and validator lives in one catalogue, Features/Config/SystemSettings.cs:

Config key Default Effect
quota.daily.default 10 Monitoring sessions per user per local day. A per-user override (PUT /api/admin/users/{userId}/daily-quota, null to clear) takes precedence.
cost.perpoll.googlemaps 0.005 USD per Distance Matrix call: each recorded poll and each Check now.
cost.pergeocode.googlemaps 0.005 USD per address geocode (two per route created).
cost.perdirections.googlemaps 0.005 USD per Directions call (a route map's road shape, fetched once per route).
cost.perautocomplete.googlemaps 0.00283 USD per Places Autocomplete request (address suggestions while typing).
cost.monthly.cap.usd 100 Monthly provider budget. Spend is this UTC month's polls plus the Check now, geocode, directions and autocomplete calls (counted in the ProviderUsage table), each at its rate. Once it reaches the cap, scheduled polls and Check now pause until the next month or until the cap is raised; route creation and suggestions keep working. 0 disables the cap. Breakdown: GET /api/admin/spending.
feature.mockproviders.enabled false Use the mock traffic/places providers instead of Google. Takes effect on the next request. The Testing environment or Features:UseMockProviders=true forces mocks regardless.
feature.weather.enabled true Fetch Open-Meteo weather for the route Weather tab.

Development and Production require Microsoft OAuth. Testing exposes isolated auth bypass endpoints for integration and E2E tests; these are not available when running the app normally.

Client experience

  • Dashboard: one toolbar for search, status filter and sort; Select opens a drawer to pause, resume or delete several commutes at once. First load shows skeletons the same size as the final cards, so nothing jumps.
  • Graphics: route cards and panels use frosted glass (pt-glass.css) with a solid fallback; map pins pulse faster as delay grows; the trend chart morphs between ranges. Chart data crosses to JS as typed arrays via [JSImport] (FxInterop.cs). Everything respects the Motion setting and prefers-reduced-motion.
  • Keyboard: / search, n new commute, c Check now, ? shortcut help, Esc closes.
  • Settings: common options on top; density, motion, locale, quota and extra panels sit in a collapsible Advanced section.

Phone app (src/PoTraffic.Mobile)

A native .NET MAUI client (XAML-free C# pages) for Android and iOS that calls the same API — every web screen: commutes dashboard (search/filter/sort, select → pause/resume/delete, swipe for Check now / Delete, sample commute), new commute (autocomplete, Use my location via GPS + reverse geocoding, arrive-by, schedule), commute page (answer, latest sample, today's trend, map with route line and incident, rename / arrive-by / addresses / pause / return trip / delete, schedule edit and stop, heatmap, weather), alerts, settings (usage, locale, time zone, extra panels, export via the share sheet, delete account), admin, and system status. The dashboard snapshot and alerts are kept on the phone for offline starts.

Phone-only features:

  • Leave-by alerts. Per commute (needs an arrive-by time): a local notification at LeaveBy − lead (lead set in Settings, default 10 min) for each scheduled day of the next week, from the same /departure plan the dashboard shows. Armed with the OS so they fire with the app closed — Android AlarmManager (exact when the user allows exact alarms, else inexact; re-armed after reboot), iOS Time Sensitive notifications (entitlement com.apple.developer.usernotifications.time-sensitive). Re-armed on every dashboard refresh. Not server push: the API's push is Web Push (VAPID), which native apps can't receive.
  • Leaving-home detection. Per commute: leaving a 150 m circle round the start point calls POST /windows/{id}/start and one check-now, then notifies with the live time; optionally reaching the end point stops the day's session. Android uses the platform LocationManager proximity alerts (no Play Services; in the background Android checks a few times an hour), iOS uses CoreLocation region monitoring. Needs location "Allow all the time".

Sign-in: Microsoft (Entra PKCE in the system browser → bearer token, validated by the API's AddJwtBearer; the Entra app registration needs the public-client redirect potraffic://auth and the client id entered under Settings → Server) or, in Debug builds against a Development/Test API, the guest session cookie. Release builds call https://potraffic-api-win2.azurewebsites.net. The Android route map needs a Google Maps key at build time (POTRAFFIC_ANDROID_MAPS_KEY); without one the map panel is hidden on Android.

Dev loop: start an API (e.g. dotnet run --project src/PoTraffic.Api --launch-profile Test — mock traffic, guest sign-in, port 5150), then pwsh scripts/mobile-dev.ps1 -ApiPort 5150 -Run (USB phone or emulator: adb reverse maps the device's localhost:5000 to that port, then build, install, launch).

Development Guidelines

  • Keep features as vertical slices under Features/<FeatureName>/.
  • Do not add root-level Services/, Repositories/, or DTOs/ folders.
  • Keep NuGet versions in Directory.Packages.props.
  • Do not enable AOT or trimming.
  • Remove dead code and stale docs before merge.

See AGENTS.md for the full coding-agent contract.

Documentation

  • AGENTS.md — the Po web app standard this repo follows, plus the working rules.
  • docs/development.md — commands, test tiers, architecture and conventions.
  • infra/README.md — Azure resources and how they are applied.
  • SCREENSHOTS/ — before/after pages of UI changes ({YYMMDD}-{feature}.html + one annotated .png), made by pwsh scripts/screenshots.ps1 -Feature <name>. Git-ignored: local review aids, not committed.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages