CTWeb Maps

Denmark data lifecycle

The ASP.NET application owns this subsystem under server/CTWebMaps.Server/Data/. AddMapData(configuration) registers the catalogue, validator, official Protomaps source, notifications and one scheduled worker. It does not expose a static PMTiles directory. The authorized API must resolve a catalogue version before returning its immutable physical file with Range support.

Storage and activation

Set Data__Root (or MapData__Root) to a writable private data volume outside static web roots. Production Compose uses /data by default, configurable through MAPS_DATA_PATH. The ASP.NET host supplies its own private map-data directory under the content root when no data root is configured; the standalone catalogue/maintenance options default to state/map-data. Never place this directory under a web server static root. Data__Root wins if both are supplied. The application rejects linked/reparse-point data paths; the volume should be owned by the application account, with no other writers.

Layout:

catalog.json
update.lock
staging/<operation-guid>/denmark.pmtiles
versions/<YYYYMMDD>-<full-sha256>/denmark.pmtiles

Each operation holds an in-process semaphore and an OS-exclusive file handle on update.lock. A concurrent update, import or rollback is rejected, including another application/maintenance process sharing the volume. There is no distributed lock for independent volumes: all instances must share the same supported local volume, or run only one writer. Network filesystem locking/atomic rename semantics require installation-specific testing.

An update extracts into a unique staging directory, validates the archive, moves the directory into its immutable version path, then writes and flushes a new catalogue and atomically renames it over catalog.json. HTTP readers resolve the catalogue on every request. Readers see either the old complete pointer or the new complete pointer. A crash before catalogue replacement leaves the previous version active and may leave an unreferenced archive. Never overwrite an existing version file. Reusing an existing content-addressed version rechecks its full hash and size.

Staging and version directories are on the same volume so directory renames are atomic. File contents/catalogue are flushed before activation. Filesystem directory-entry durability after sudden power loss still depends on the volume/filesystem; exercise backup recovery on the target installation. An external writer modifying immutable files violates the storage ownership boundary.

Validation and sources

The updater reads only the official Protomaps build feed, with redirects disabled, a 60-second timeout and a bounded response. The feed is an array containing key, uploaded, size, and version. Selection requires an actual YYYYMMDD.pmtiles date, positive source size, compatible schema major 4, no future dates and the configured upload stability delay. The newest eligible date wins. Feed values cannot introduce a URL or command argument.

The binary path is explicit and executed directly with an argument list, never through a shell. Only the selected date enters this fixed official source URL:

pmtiles extract https://build.protomaps.com/YYYYMMDD.pmtiles STAGING/denmark.pmtiles --bbox=7.8,54.4,15.3,57.9 --maxzoom=15 --download-threads=4

This is a server-side Range extraction, not a planet download. Extraction has a four-hour deadline; cancellation kills its process tree. Use the pinned official binary provided by the project installation, not an arbitrary executable from an upload. Official CLI documentation describes geographic extraction and verification.

Before extraction the application requires 3 GiB available space by default. Import additionally reserves the source size beyond that minimum. During extraction/import a guard checks the actual data filesystem every 100 ms. Crossing the configured reserve cancels the writer; CLI cancellation kills its process tree before staging cleanup. A final check runs before validation/activation, and reserve failures retain the current pointer with sanitized insufficient_disk_space status. Sampling and concurrent unrelated writers can briefly overshoot the threshold, so this is not a filesystem quota or an absolute reservation against every process. Capacity monitoring/quotas should protect shared storage and allow room for retained archives and backups, not only the staging minimum.

Every imported/extracted archive must pass:

The local subset SHA256 is computed from extracted bytes; the feed's planet hash is not a subset hash. An archive failing validation cannot replace the active pointer. Rollback rechecks the full archive hash/size, header/schema, CLI structure and sample tiles before changing the pointer.

Configuration

ASP.NET configuration uses the MapData section, or double underscores in environment variables:

Setting Default Meaning
Data__Root / MapData__Root /data in Compose; host private map-data; standalone options state/map-data Private writable archive/catalogue volume
MapData__PmTilesPath tools/pmtiles/pmtiles.exe Fixed trusted CLI path; Linux installation uses /usr/local/bin/pmtiles
MapData__Enabled true Scheduled updates; manual operations remain available
MapData__DailyTimeUtc 10:00 Daily UTC schedule
MapData__Interval 1.00:00:00 A non-24-hour interval overrides daily scheduling
MapData__BuildStabilityDelay 01:00:00 Minimum time since upload before selecting a build
MapData__MinimumFreeBytes 3221225472 Free-space floor before and during extraction/import
MapData__RetainVersions 3 Minimum most-recently-activated archive count
MapData__RetentionGrace 7.00:00:00 Extra retention after deactivation
MapData__MaximumSessionLifetime 1.00:00:00 Full supported browser session duration, including token renewal
MapData__BootstrapPath unset Explicit one-time import if no active archive exists
MapData__BootstrapBuild 20261130 Official build date of bootstrap file

Use .NET TimeSpan formats shown above. The worker imports bootstrap data independently of the scheduled update switch. Import copies once into the private data volume; it leaves the phase 1 archive intact. No bootstrap import occurs when there is already an active archive. A failed bootstrap is logged with a fixed message; administration/maintenance can fix and import it without changing unrelated services.

The worker waits until its next configured schedule rather than downloading immediately at startup. Manual updates and scheduled updates share all locking and validation. Attempts, successful checks/activations and sanitized error codes persist in the catalogue. Status reports current version, last attempt/success, next attempt, running/locked state, enabled state and disk availability. It does not retain external command stderr, credential values, visitor addresses or exception details.

Retention and cleanup

Deactivating a version sets RetainUntil to the current time plus RetentionGrace + MaximumSessionLifetime. Rollback starts a fresh window for the version being deactivated. Activation keeps the active archive and at least RetainVersions archives by activation date regardless of age. Older inactive archives may be removed only after their retention window. Cleanup failures defer deletion and do not break a valid activation. Set maximum session lifetime to the actual maximum supported complete browser session, not merely one short-lived access-token lifetime; the SDK/session policy must bound sessions accordingly.

Staging cleanup only considers operation directories with 32-character GUID names older than 24 hours, while holding the same exclusive lock. It refuses linked paths and nested unexpected directories. It never follows links or recursively deletes arbitrary directory trees. A crash leaving an immutable archive without a catalogue entry is deliberately retained for operator inspection; it is not guessed safe to delete. Back up catalog.json and all retained version directories together while holding the writer lock or stopping the app. Restore to a private volume and verify before allowing traffic; physical paths are recomputed from version identifiers so restored volumes may use a different absolute root.

Administration and maintenance

The server uses IMapDataCatalog:

Task<MapDataVersion?> ActiveAsync(CancellationToken ct = default);
Task<MapDataVersion?> ResolveVersionAsync(string version, CancellationToken ct = default);
Task<MapDataStatus> StatusAsync(CancellationToken ct = default);
Task<MapDataVersion?> UpdateAsync(CancellationToken ct = default);
Task<MapDataVersion> RollbackAsync(string version, CancellationToken ct = default);

MapDataVersion includes Version, private FilePath, Sha256, SizeBytes, ActivatedAt, source Build, and RetainUntil. MapDataCatalog.ImportAsync(path, build, ct) explicitly imports a local archive. Expose manual mutations only behind admin authorization and antiforgery; never publish FilePath in public APIs.

The package-free maintenance CLI compiles the same production sources. From the repository root:

dotnet restore scripts/data/CTWebMaps.Data.Tool.csproj --configfile scripts/data/NuGet.Config
$env:Data__Root = 'C:\private\ctweb-maps-data'
$env:MapData__PmTilesPath = 'C:\trusted\pmtiles.exe'
dotnet run --no-restore --project scripts/data/CTWebMaps.Data.Tool.csproj -- status
dotnet run --no-restore --project scripts/data/CTWebMaps.Data.Tool.csproj -- verify public/data/denmark.pmtiles
dotnet run --no-restore --project scripts/data/CTWebMaps.Data.Tool.csproj -- import public/data/denmark.pmtiles 20261130
dotnet run --no-restore --project scripts/data/CTWebMaps.Data.Tool.csproj -- update
dotnet run --no-restore --project scripts/data/CTWebMaps.Data.Tool.csproj -- rollback VERSION

CTWEB_DATA_CONFIG optionally names an existing JSON configuration file; environment variables override it. The CLI starts no web server or background worker. It exits nonzero with a sanitized error on failure. Do not copy secret-bearing configuration into source control or command arguments.

Notifications

MapData__Notifications__WebhookUrl enables webhook notifications, with exact DNS host allowlisting via MapData__Notifications__AllowedWebhookHosts__0, __1, etc. Only HTTPS port 443, no userinfo, no fragments, no literal IPs. DNS is resolved at connection time; all answers must be public unicast addresses and the validated address is used directly, preventing a second DNS lookup/rebinding. Private, local, link-local, mapped private, reserved/documentation and transition addresses are rejected. Redirects, system proxies and cookies are disabled. Keep the host allowlist tightly scoped to a trusted notification provider. Egress firewall policy remains useful installation defense.

Email uses framework System.Net.Mail.SmtpClient, STARTTLS required, with SmtpHost, SmtpPort (587), SmtpUser, SmtpPassword, MailFrom, and MailTo under MapData:Notifications. SMTP endpoints are operator configuration and may intentionally be internal relays. Supply credentials with environment/secret mounts, never checked-in settings. Delivery compatibility with the organization's relay requires installation testing.

Update success/failure notifications apply to manual and scheduled updates; bootstrap failures also notify. Payloads contain only service, outcome, fixed event code and timestamp. Notifications have deadlines and failure never stops the worker or reverses a successful activation. Logs retain fixed notification-failure messages, no destination, query token, SMTP password, exception or IP.

Verification evidence

dotnet restore tests/data/CTWebMaps.Data.Tests.csproj --configfile tests/data/NuGet.Config
dotnet run --no-restore --project tests/data/CTWebMaps.Data.Tests.csproj
dotnet run --no-restore --project tests/data/CTWebMaps.Data.Tests.csproj -- --verify public/data/denmark.pmtiles

The normal suite uses tiny handcrafted headers, real files, the real catalogue and deterministic source fixtures. It covers corruption/overflow, required layers, Bornholm bounds, insufficient zoom, size/hash, initial and in-flight disk guards, cancellation before activation, immutable activation, retained old paths, rollback/restart, locking, failed extraction/import preserving current state, strict feed selection, expired-version cleanup, abandoned staging, malformed sample tiles and notification safety. It never copies the 968 MB phase 1 archive. A separate 32 MiB Linux tmpfs regression starts a real controlled writer through the production process runner, crosses a 16 MiB reserve, and verifies its PID is dead before staging cleanup returns, reserve space recovers, and the active archive remains intact.

On 2026-11-30 the optional real-archive command passed production validation, CLI structure verification and eight sampled MVT reads for the existing archive: 968353286 bytes, SHA256 d6ff7c30576e5908d04e325c208e694aaa1fff3c032448bf697f462351248ea3. The official build feed was read successfully. A fresh full remote extraction, live email/webhook delivery, storage power-loss simulation and production installation are not claimed by these local tests.