Spaces:
Running
Download docs/architecture.md from climateexploer/meteogate: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/spaces/climateexploer/meteogate/resolve/main/docs/architecture.md
- Command line
-
hf download hf://spaces/climateexploer/meteogate/docs/architecture.md
-
curl -L -o architecture.md https://huggingface.co/spaces/climateexploer/meteogate/resolve/main/docs/architecture.md
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:
elevationcountryregionname(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:
Rscript misc/update_oscar_elevation_cache.R
How the script works:
- It queries the MeteoGate API for the current list of all available stations.
- It reads the existing
data/oscar_elevation_cache.csv. - It identifies any "missing" stations that are present in the MeteoGate API but not yet cached in the local CSV.
- It queries the WMO OSCAR API in parallel (with sleep intervals to prevent banning) to fetch the metadata strictly for those missing stations.
- 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 = FALSEis 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:
- Run
Rscript misc/update_oscar_elevation_cache.Rlocally. - Ensure the script finished successfully.
- Commit the updated
data/oscar_elevation_cache.csvfile (along with any other source code changes). - 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:
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:
- For the most recent ~24 hours, the app prefers the live MeteoGate REST API.
- For older requests, the app uses the Hugging Face archive.
- 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:
- If every needed day shard is already present in
data/parquet_cache/, query those local Parquet files with DuckDB. - Otherwise, try DuckDB directly against the remote Hugging Face Parquet URLs.
DuckDB loads the
httpfsextension lazily at runtime when needed. - If remote DuckDB is unavailable, download the missing day shards into
data/parquet_cache/and query the cached local files with DuckDB. - 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:
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 <dialog> 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:
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: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:
.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 nativepopover="hint"triggered viainterestforattributes, offloading light dismissals and screen reader associations (aria-describedbyoraria-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:.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 ofdisplay: noneor 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:
.dashboard-widget-wrapper { container-type: inline-size; } - Modular Styles: Internal widgets dynamically resize, wrap text, or format spacing using
@container (max-width: <length>)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:
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1"> - 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:
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.cssandapp_v1.1.js) utilizing a centralized constant defined inglobal.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 <iframe> element to match the app's content height.
- Conditional Activation: The auto-height emitter only runs when the app detects it is inside an iframe (
window.self !== window.top), having no effect when running standalone. - Efficient Emission: Height changes are debounced through
requestAnimationFrameto avoid flooding the parent with resize messages.// In app_v1.1.js var resizeObserver = new ResizeObserver(function() { requestAnimationFrame(sendHeight); });
7. Security Hardening
MeteoGate implements multiple defense-in-depth security layers for safe iframe embedding and data integrity.
7.1 Content Security Policy (CSP) — Frame Ancestors
To prevent clickjacking attacks (where an attacker frames the application inside a malicious page), the R backend injects a Content-Security-Policy header restricting which parent origins may embed the app:
# In global.R
shiny::shinyOptions(
httpHeaders = list(
"Content-Security-Policy" = "frame-ancestors 'self' https://*.quarto.pub https://*.climateexplorer.app https://climateexplorer.app https://*.climateexplorer.org https://climateexplorer.org"
)
)
7.2 postMessage Origin Validation
The eurometeo-navigate message listener in app_v1.1.js validates event.origin against a trusted allowlist before processing any incoming navigation commands. This prevents malicious pages from injecting station or parameter selection changes via crafted postMessage calls:
// In app_v1.2.js
var allowedOrigins = [
'https://climateexplorer.app',
'https://www.climateexplorer.app',
'https://climateexplorer.org',
'https://www.climateexplorer.org'
];
if (allowedOrigins.indexOf(event.origin) === -1) return;
7.3 Scoped SSL Verification
Global SSL certificate verification bypass (ssl_verifypeer = FALSE) was removed from global.R. Any endpoint-specific certificate issues are scoped to individual httr::GET() calls in funs/helpers.R rather than disabling verification for the entire application.
7.4 HTML Escaping (XSS Prevention)
All user-facing dynamic values injected into HTML label popups are sanitized using htmltools::htmlEscape(). This includes station name, country, id, label_name, unit, and missing_label fields in the generate_station_label() function in server.R, preventing Cross-Site Scripting attacks from malformed station metadata.
8. Performance: 31-Day Query Constraint
To ensure low-latency performance on Hugging Face Spaces Free Tier (2 vCPUs, 16 GB RAM), the maximum date range for data queries is constrained to 31 days. This eliminates the need for asynchronous background workers (which would cause CPU contention on 2 vCPUs) and keeps DuckDB Parquet shard reads fast and responsive.
- Interactive Clamping: The
date_rangeobserver inserver.Rautomatically adjusts the start or end date when a user manually selects a range exceeding 31 days. - URL Clamping: Incoming shared links with date spans exceeding 31 days are automatically truncated before processing.
- Default Alignment: The
default_start_dateinglobal.Ris already set toSys.Date() - 31, matching the constraint.
9. Accessibility (WCAG Compliance)
MeteoGate enhances keyboard navigation and screen reader support for its map overlay controls:
- Semantic Landmarks: The map layer control panel (
absolutePanel) usesrole="region"andaria-label="Map layer controls"to register as a named landmark for screen readers. - Keyboard Focus:
tabindex="0"enables keyboard navigation to the layer control. A:focus-visibleCSS rule renders a visible 3px outline ring for keyboard-only users:.map-layer-control:focus-visible { outline: 3px solid var(--bs-primary, #3498db); outline-offset: 2px; } - Icon Button Labels: The zoom-home icon button (
actionButton("zoom_home", ...)) includes an explicitaria-label("Zoom map to all European stations") since icon-only buttons contain no text content for screen readers.
10. Typography: Inter Font System
MeteoGate uses the Inter typeface (loaded from Google Fonts) as its primary font family, replacing browser-default serif/sans-serif stacks. Inter provides excellent readability at small sizes and a professional, modern aesthetic across all platforms:
html, body {
font-family: 'Inter', system-ui, -apple-system, sans-serif;
}
The font is loaded with display=swap to prevent invisible text during font loading, preserving Largest Contentful Paint (LCP) performance.