# MeteoGate Architecture ## Station Metadata Caching (OSCAR) MeteoGate retrieves real-time observation data for weather stations from its REST API (which syncs with the WIS2 global network). However, the API often lacks complete human-readable metadata for these stations—such as accurate elevations, proper country assignments, or human-readable station names (frequently defaulting to generic names like `"platform-0-208-0-06186"`). To resolve this without penalizing the application's runtime performance, MeteoGate enriches its station list using authoritative metadata from the WMO OSCAR (Observing Systems Capability Analysis and Review Tool) database. ### The OSCAR Cache Pre-generation Workflow Because the application is hosted on Hugging Face Spaces (Free Tier), its local disk storage is ephemeral and gets wiped every time the Space goes to sleep or restarts. If the app attempted to fetch missing metadata from OSCAR concurrently during startup, it would easily hit WMO's API rate limits and add significant minutes of startup delay. Instead, the OSCAR metadata is **pre-generated locally** and committed directly to the Git repository. #### 1. The Cache File The enriched metadata is stored persistently in the repository at: `data/oscar_elevation_cache.csv` This CSV file maps a station's `wigos_id` to its: - `elevation` - `country` - `region` - `name` (the official human-readable name, which overrides the API's "platform-" defaults) #### 2. The Updater Script Whenever new stations are added to the MeteoGate API (or if you simply want to refresh the metadata), a local developer must run the updater script before pushing changes to Hugging Face: ```bash Rscript misc/update_oscar_elevation_cache.R ``` **How the script works:** 1. It queries the MeteoGate API for the current list of all available stations. 2. It reads the existing `data/oscar_elevation_cache.csv`. 3. It identifies any "missing" stations that are present in the MeteoGate API but not yet cached in the local CSV. 4. It queries the WMO OSCAR API *in parallel* (with sleep intervals to prevent banning) to fetch the metadata strictly for those missing stations. 5. It appends the newly discovered metadata to the CSV file. #### 3. Application Runtime Behavior When the Shiny app boots up, it retrieves the station network by calling `get_meteogate_stations()` (located in `funs/helpers.R`). For OSCAR metadata, the app operates in a strictly **read-only** mode: - `fetch_missing = FALSE` is strictly enforced to block ad-hoc API calls. - The app instantly merges the live MeteoGate API station list with the locally shipped `data/oscar_elevation_cache.csv`. - If the MeteoGate API returns an empty name or a generic `"platform-"` name, the app seamlessly overrides it with the official human-readable name found in the CSV cache. - No HTTP requests are ever made to the WMO OSCAR API during the app's runtime lifecycle, guaranteeing stable and rapid station loading. #### 4. Deployment Checklist To ensure the app on Hugging Face is fully up to date: 1. Run `Rscript misc/update_oscar_elevation_cache.R` locally. 2. Ensure the script finished successfully. 3. Commit the updated `data/oscar_elevation_cache.csv` file (along with any other source code changes). 4. Push everything to the Hugging Face remote environment. ## Historical Archive Query Path Older observations are stored in the public Hugging Face dataset `alexdum/meteogate-archive` as daily Parquet files under a date-based layout: ```text data/YYYY/MM/YYYY-MM-DD.parquet ``` The Shiny app uses this archive for historical station charts and for older map observation lookups that fall outside the live MeteoGate API window. ### Archive Routing Rules The runtime data strategy is intentionally hybrid: 1. For the most recent ~24 hours, the app prefers the live MeteoGate REST API. 2. For older requests, the app uses the Hugging Face archive. 3. If a request spans both ranges, the app merges archive data and API data into one unified frame before plotting. This keeps the latest data fresh while still allowing large historical queries. ### DuckDB-First Archive Reads Archive reads are now **DuckDB-first** rather than Arrow-per-file-first. For station history requests, the archive logic follows this order: 1. If every needed day shard is already present in `data/parquet_cache/`, query those local Parquet files with DuckDB. 2. Otherwise, try DuckDB directly against the remote Hugging Face Parquet URLs. DuckDB loads the `httpfs` extension lazily at runtime when needed. 3. If remote DuckDB is unavailable, download the missing day shards into `data/parquet_cache/` and query the cached local files with DuckDB. 4. If all DuckDB paths fail, fall back to the older Arrow remote-read path. The area-observation archive path uses the same ordering for single-day historical map queries. ### Why DuckDB Is Preferred DuckDB performed substantially better than the previous Arrow-per-file loop when filtering large station history requests over multiple day shards. The current design keeps DuckDB as the fast path but preserves Arrow as a safety net for environments where `httpfs` cannot be installed or remote Parquet access fails. ### Ephemeral Parquet Shard Cache The app can temporarily download daily Hugging Face Parquet shards into: ```text data/parquet_cache/YYYY/MM/YYYY-MM-DD.parquet ``` This cache is **ephemeral** and exists only to speed up archive reads within a single running Space instance. It is not treated as durable storage. Important properties: - The cache is opportunistic: day shards are only downloaded when the remote DuckDB path is unavailable and the app needs a local fallback. - Cached day shards can be reused by later requests while the current Space instance is still running. - Because Hugging Face free-tier Space storage is ephemeral, the cache is not guaranteed to survive restarts or sleep cycles. ### Startup Cache Reset To keep disk usage bounded and prevent long-lived Spaces from accumulating too many downloaded archive shards, the app now clears `data/parquet_cache/` on startup. That means all three runtime caches are reset when the app boots: - `data/station_data/` - `data/map_cache/` - `data/parquet_cache/` This is the simplest safety mechanism against disk exhaustion in the free-tier deployment model. ### Failure Behavior When Disk or Remote Access Fails If the Space cannot write another Parquet shard locally, the shard download fails and the cache step is abandoned. The app then continues down the fallback chain rather than crashing immediately. In practice, that means: - If remote DuckDB works, the request can still succeed without writing to disk. - If remote DuckDB fails and local shard caching also fails, the app falls back to Arrow remote reads. - Performance may degrade, but the archive path remains operational whenever at least one of the supported backends can still read the data. ### Progress Bar Behavior The archive overlay uses two different kinds of progress reporting: - **Real percentage progress** is shown when the app is working through known per-file stages, such as downloading or caching a finite set of day shards. - **Indeterminate/simulated progress** is used during the single blocking DuckDB query stage. This distinction exists because the current R DuckDB client path uses blocking DBI calls and does not expose live query progress updates to the Shiny server in the same way that a manually chunked per-file loop can expose them. As a result, the UI can show the current phase (`Querying archive...`) but not a true intra-query percentage for that specific DuckDB call. --- ## Modern Web Guidance & Frontend Architecture To maintain high performance and code maintainability, MeteoGate minimizes heavy JavaScript/jQuery layout orchestration by delegating rendering states, overlays, and responsiveness directly to modern, native Web APIs. This guarantees superior Core Web Vitals (specifically Largest Contentful Paint (LCP) and Interaction to Next Paint (INP)) and simplifies frontend maintenance. ### 1. Native Overlays & Discrete Top-Layer Transitions MeteoGate implements its UI locking screen ("frozen overlay") using the native HTML `` element and the Popover API (`popover="manual"`), rather than custom z-indexed absolute containers toggled via jQuery. - **Native Top-Layer Stacking**: Natively projected elements bypass CSS stack context traps, ensuring they are rendered at the top of the browser viewport. - **Discrete Style Transitions**: Transitions are defined directly in CSS using discrete property behaviors to enable fade-in and fade-out timings on open/close: ```css dialog { transition: opacity 0.3s, transform 0.3s, display 0.3s allow-discrete, overlay 0.3s allow-discrete; } ``` - **Entry Animations with `@starting-style`**: Prevents unstyled rendering jumps by declaring entry styles directly in CSS, executing native performance-optimized hardware acceleration: ```css dialog[open] { opacity: 1; transform: scale(1); @starting-style { opacity: 0; transform: scale(0.95); } } ``` ### 2. Tethered Interfaces with CSS Anchor Positioning & Popover Hints For floating interfaces—such as the map layer selector panel (`.map-layer-control`) and weather station hover cards—MeteoGate eliminates JavaScript position calculations and manual listener attachments. - **CSS Anchor Positioning**: Target overlays are dynamically tethered to anchor elements natively via CSS: ```css .map-layer-control { position-anchor: --map-anchor-id; top: anchor(bottom); left: anchor(center); position-try: flip-block; } ``` - **Interest Invokers (`popover="hint"`)**: Hover tooltips and overlay cards use native `popover="hint"` triggered via `interestfor` attributes, offloading light dismissals and screen reader associations (`aria-describedby` or `aria-details`) entirely to the browser. ### 3. Rendering Deferral & State Caching MeteoGate coordinates complex, heavy dashboard elements (such as multiple Plotly wind roses/time series) and extensive data tables using rendering optimization features. - **`content-visibility: auto`**: Off-screen panels and bottom-heavy card lists are deferred until scrolled into viewport proximity, preventing unnecessary DOM paint pipelines during initialization: ```css .deferred-dashboard-card { content-visibility: auto; contain-intrinsic-size: auto 300px; } ``` - **`content-visibility: hidden`**: Inactive dashboard subtabs cache their layout rendering tree natively. This eliminates the CPU overhead of destroying and recreating DOM charts (typical of `display: none` or conditional reactive rendering) while keeping navigation transitions instantaneous. ### 4. Component-Driven Layouts via CSS Container Queries Instead of using global screen width media queries (`@media`), MeteoGate sizes responsive sidebar configurations, plots, and data panels based on their container container box sizes. - **Container Sizing**: Key dashboard elements are registered as layout contexts: ```css .dashboard-widget-wrapper { container-type: inline-size; } ``` - **Modular Styles**: Internal widgets dynamically resize, wrap text, or format spacing using `@container (max-width: )` queries, facilitating modular component design that fits beautifully regardless of split-pane or sidebar states. ### 5. Resilient Mobile Iframe & Asset Cache-Busting Integration When embedded inside a parent document iframe (like `climateexplorer`), MeteoGate secures mobile scaling stability and resource delivery using modern browser integration standards. - **Embedded Mobile Viewport Meta Tags**: Shiny pages force WebKit rendering engines inside mobile iframes to immediately adopt the host page's mobile scale by declaring an explicit viewport definition directly inside the iframe head: ```html ``` - **Iframe Width & Overflow Bounds**: Prevents browser-level auto-expansion (common in iOS mobile Safari where an iframe stretches to fit overflowing wide containers rather than clipping them) by enforcing strict root CSS bounds: ```css html, body { width: 100%; max-width: 100vw; overflow-x: hidden; } ``` - **Filename-Based Cache-Busting**: Guarantees that mobile browsers and CDNs immediately load fresh versions of assets following deployments (preventing broken layouts due to stale assets). The R backend dynamically maps assets to version-fingerprinted filenames (e.g. `styles_v1.1.css` and `app_v1.1.js`) utilizing a centralized constant defined in `global.R`: ```R # In global.R ASSETS_VERSION <- "v1.1" # In ui.R tags$link(rel = "stylesheet", type = "text/css", href = paste0("styles_", ASSETS_VERSION, ".css")) ``` ### 6. Iframe Auto-Height via ResizeObserver To eliminate double scrollbars when embedded in a Quarto parent page, MeteoGate continuously emits its document height to the parent window using `postMessage` driven by a `ResizeObserver`. This allows the parent to dynamically resize the `