Martin server runtime
Martin is a tile and map resource server. It turns user configuration into a live source catalog, builds one HTTP service around that catalog, and exposes the configured map capabilities to clients. The runtime also coordinates readiness, reload work, request policies, offline tile workflows, and graceful shutdown.
Runtime model
Application entry point
The martin binary is the runtime entry point. It parses command arguments, starts logging, reads command-line and file settings, resolves configured sources, creates the HTTP server, and keeps the process alive until the server or an operator stops it. Optional command modes can finish before the HTTP server starts.
References: crates/…/martin.rs• L225-336
Command modes
Martin has a server mode and offline command modes. The martin cp command uses configured sources to copy tiles into an output tileset. The martin test command either creates a reviewed specification of table-layer results or checks an existing specification against current data. These modes do not start the long-lived HTTP service.
The test specification records representative source rows, the features that the configured layers produce, and per-tile operation counts. Generation finds rows on layer paths, renders them with bulk-mode behavior, and compares them with the prior specification. A check re-renders every recorded case and reports whether the row or its output changed. This gives offline work a stable review point without changing the public server catalog.
References: crates/…/martin.rs• L259-291 crates/…/mod.rs• L35-90 crates/…/mod.rs• L168-226 crates/…/mod.rs• L302-355
Configuration assembly
Configuration assembly turns a file, command-line input, and environment into one validated runtime plan. Martin can use an explicit file or detect sources from command-line connections, then applies server and source settings before it resolves live sources.
Source settings support both fixed entries and source discovery. PostgreSQL connections can publish configured or discovered tables and functions. DuckDB entries can publish database tables, table macros, or GeoParquet files. PMTiles and other remote sources share object-store settings, while credentials remain separate from saved public configuration.
Unknown settings are retained long enough to report their full configuration paths. This gives operators a warning instead of silently treating a misspelled setting as active. See Configuration and reload behavior for setting precedence and the effect of a change after startup.
References: crates/…/root.rs• L81-225 crates/…/connections.rs• L3-91 crates/…/collect_unrecognized.rs• L31-103 crates/…/object_store.rs• L38-71 crates/…/object_store.rs• L222-231 crates/…/config.rs• L41-75 crates/…/config.rs• L57-157 crates/…/pmtiles.rs• L31-105
Startup sequence
Startup moves from user intent to public service in a fixed order. Configuration is read or auto-detected, command-line values are merged, values are checked and completed, sources and resources are resolved, and the server is then bound to its listening address.
The following flow shows the main runtime hand-off:
flowchart TD
A[Command line and environment] --> B[Read or auto-detect configuration]
B --> C[Merge and validate settings]
C --> D[Resolve sources and map resources]
D --> E[Build live catalog and shared state]
E --> F[Create routes and middleware]
F --> G[Bind HTTP service]
G --> H[Serve public capabilities]
D --> I[Load or reload sources]
I --> E
Source loading may run beside server startup. The process waits for the initial loading task before it reports the service as active, while requests that need not-yet-published sources can wait for the catalog to become ready. A save-config run loads enough source state to write a complete configuration before it exits.
References: crates/…/martin.rs• L52-123 crates/…/martin.rs• L125-150 crates/…/martin.rs• L193-223
Server composition
Live source catalog
The live source catalog is the shared state behind tile requests and catalog responses. It holds tile sources, named aliases that combine sources, source processing rules, and cache access. Reload work changes this catalog without replacing the HTTP service.
The catalog accepts additions, updates, and removals. It publishes successful sources, removes stale entries, clears affected cache data, and applies the configured policy when a source cannot be built. An alias expands to its member sources for a request and appears as a catalog entry. See Source catalog and lifecycle for the source lifecycle and reload model.
References: crates/…/lifecycle.rs• L187-268 crates/…/tile_source_manager.rs• L16-34 crates/…/tile_source_manager.rs• L159-248 martin/…/source.rs• L73-150 martin/…/source.rs• L159-317
Route surface
The server composes a route surface from the capabilities enabled by the build and the active configuration. The common surface includes health and catalog endpoints. Tile routes, OGC API routes, styles, sprites, fonts, rendered resources, cache controls, and the Web UI are added when their capabilities are available. OGC map routes add dataset, collection, and style map images plus tiled map metadata and image tiles when server-side rendering is enabled. The generated OpenAPI description follows the same feature groups so clients can discover the public contract.
Route order is part of the public behavior. Specific protocol routes, canonical format redirects, and static image redirects are registered before broad tile or image paths so that a general source path does not capture them. See HTTP APIs and map resources for the public endpoint groups.
References: crates/…/server.rs• L148-263 crates/…/admin.rs• L15-119 crates/…/map.rs• L520-688 crates/…/map_tiles.rs• L115-335 martin/…/schemas.rs• L20-143
Request context
Each server worker receives shared runtime state for the catalog, server settings, tile manager, and enabled map resources. Middleware then applies cross-cutting request behavior such as path normalization, CORS, cache headers, request tracing, metrics, and optional dashboard observation.
This composition keeps endpoint handlers focused on one public capability. The handlers read the shared state and return a response that follows the server-wide policies unless that endpoint defines a more specific rule.
References: crates/…/server.rs• L275-383
Capability contracts
Martin groups its public runtime capabilities behind the library's configuration, server, logging, source, generation, and optional resource modules. Build features decide which capability groups exist, while the running configuration decides which enabled groups are exposed to clients.
Martin also defines machine-readable contracts for configuration and HTTP capabilities. The configuration schema describes the settings users can provide. The OpenAPI document describes the core routes and adds resource, rendering, and OGC API routes when the related capabilities are present. These contracts help clients and tools use the same public shape as the running server.
References: martin/…/lib.rs• L7-45 martin/…/schemas.rs• L11-38 martin/…/schemas.rs• L40-143
Public serving behavior
Readiness boundary
The health endpoint is both a liveness and readiness signal. When tile sources are enabled, it waits until the source manager finishes its current initial load before returning success. The catalog endpoint follows the same boundary so clients see a complete initial source view rather than a partial one.
A request for a named source can also wait while startup or reload publishes that source. This lets the HTTP service exist while source discovery continues without exposing a false missing-source result during the loading window.
References: crates/…/server.rs• L128-146 crates/…/admin.rs• L84-99 crates/…/tile_source_manager.rs• L74-99
Public path model
Martin supports deployment behind a reverse proxy or under a URL subpath. A route prefix moves the service routes under a configured path, while the health route remains available at /health. A base path describes the public path used when Martin builds URLs in responses, with the explicit base path taking priority over the route prefix. See Configuration and reload behavior for the settings and their reload impact.
The runtime also derives a public prefix from proxy information when an explicit prefix is not configured. This keeps generated resource links aligned with the URL that clients use to reach Martin.
References: crates/…/srv.rs• L76-100 crates/…/srv.rs• L176-186 crates/…/server.rs• L77-97 crates/…/server.rs• L148-165
Web UI access
The optional Web UI is a presentation layer over the same server. It can be available to all clients, limited to loopback clients, or disabled. When it is not available, the root response directs clients to the catalog instead.
The Web UI setting changes access to the interface only. It does not remove the configured public APIs or the catalog.
References: crates/…/server.rs• L247-278 crates/…/admin.rs• L101-119
Tile response handling
Tile serving turns a source or source group into one response for a requested tile coordinate. It waits for the named sources, applies source processing, reads or fills the tile cache, merges composite tiles when needed, and negotiates the response format and compression with the client.
The response can include an ETag, cache policy, and content-encoding. A client can request MVT or MLT when the sources and configured conversions support it. Empty tiles return no content, while incompatible formats or coordinates return a client error. See HTTP APIs and map resources for the endpoint contract.
References: crates/…/content.rs• L92-119 crates/…/content.rs• L323-425 crates/…/content.rs• L435-546
Terrain-derived tiles
Terrain processing provides derived tile products from elevation or normal tiles. A request gathers the requested tile's local neighbourhood, respects the source grid at world edges, and then produces either contour lines or a hillshade image. The shared gather step limits concurrent reads across the process so these products do not overload their source.
The processors treat the centre tile as the coverage boundary. If it has no data, they return no content instead of a blank result that could be cached as real terrain. A missing neighbour only affects the nearby seam because the centre edge is used in its place. Contours can use the nearest available ancestor when elevation coverage stops at a higher zoom. CPU-heavy tracing and baking run under separate process-wide limits, and a response gets an entity tag only when its input tiles and settings can identify the result.
This flow shows how source coverage becomes a cache-aware derived tile response:
flowchart TD
A[Terrain tile request] --> B[Gather centre and neighbours]
B --> C{Centre data exists?}
C -- No --> D[Return no content]
C -- Yes --> E[Trace contours or bake hillshade]
E --> F[Return derived tile with input-based cache identity]
References: crates/…/neighbourhood.rs• L16-179 crates/…/contour.rs• L56-140 crates/…/hillshade.rs• L58-145
Rendered map resources
Configured styles can produce rendered image tiles and static map images instead of vector or raster source tiles. The tile path renders a style at a tile coordinate. The static path renders a style for a center and zoom or for a bounding box, and it can accept a GeoJSON overlay for one request. Both paths return PNG, JPEG, or WebP output when rendering is enabled.
OGC API Maps exposes the same rendering capability as dataset, collection, and style maps. It accepts supported map formats and map views, and it exposes map tiles on the WebMercatorQuad tile matrix set. OGC map requests report invalid views, unsupported coordinate systems, missing collections or styles, and out-of-grid tiles as typed HTTP errors.
Image work runs outside the request worker and is limited across the process. This keeps CPU-heavy encoding from blocking unrelated HTTP requests. OGC tileset metadata describes the source grid, map bounds, and layer limits for clients that use the standard tile model.
References: crates/…/styles_rendering.rs• L64-153 crates/…/styles_rendering.rs• L184-319 crates/…/styles_static.rs• L218-317 crates/…/styles_static.rs• L355-516 crates/…/map.rs• L391-517 crates/…/map.rs• L520-688 crates/…/map_tiles.rs• L72-112 crates/…/map_tiles.rs• L115-335 crates/…/error.rs• L1-77 crates/…/tilesets.rs• L184-225
Runtime operations
Source resolution
Source resolution changes user-facing source definitions into live tile sources and processing rules. It may inspect a database catalog, derive metadata, compute bounds, prepare remote access, or report a warning for one source while keeping valid sibling sources available.
PostgreSQL discovery can publish tables and tile-serving functions. It merges database facts with explicit settings before building a source. DuckDB discovery can publish tables and macros from a database or expose local and remote GeoParquet data. Remote S3 settings can provide credentials and endpoint behavior to both object-store readers and DuckDB remote reads.
References: crates/…/builder.rs• L141-211 crates/…/builder.rs• L231-288 crates/…/query_tables.rs• L34-136 crates/…/resolve.rs• L32-71 crates/…/resolve.rs• L127-158 crates/…/geoparquet.rs• L20-53 crates/…/secret.rs• L15-46
Observability
The runtime reports startup, source changes, request activity, and failures through tracing. Operators can select log filters and output formats before the server starts. When metrics are enabled, the HTTP service also publishes request metrics under its metrics endpoint.
Observability is part of the runtime boundary because startup errors must be reported before a server exists, while request and source events use the server's shared tracing context.
References: crates/…/martin.rs• L252-335 martin/…/mod.rs• L270-319 crates/…/server.rs• L282-305
Offline tile workflows
Offline tile workflows turn configured sources into persistent tilesets or checked layer results without keeping an HTTP server open. Tile mode requests tiles through the normal source interface and writes them to MBTiles. Bulk mode scans supported Postgres table and view sources, applies their layer rules, and renders the result to MBTiles or PMTiles. The test specification path renders selected rows with the same bulk behavior and stores the expected feature results for later comparison.
The tile-copy path resolves configuration and sources once, then fetches the requested tile ranges while a writer stores them in the output. Bulk mode instead selects table sources from one database, lowers their layer settings into a render plan, and renders features across a continuous zoom range. A failed or interrupted bulk run removes the output it created, so a partial tileset is not presented as complete. A test specification records each case as source input, layer output, zoom range, attributes, and per-tile operation counts, including groups that a merge operation could not make valid.
References: martin/…/cp.rs• L286-337 martin/…/cp.rs• L737-878 crates/…/mod.rs• L317-401 crates/…/mod.rs• L468-480 crates/…/mod.rs• L515-603 crates/…/layers.rs• L37-100 crates/…/file.rs• L13-39 crates/…/file.rs• L87-109 crates/…/render.rs• L51-116
Shutdown behavior
The server stops accepting new work when the process receives its shutdown signal and allows in-flight requests to finish within the configured timeout. The runtime also supports a Lambda execution path and a terminal dashboard path when those capabilities are enabled.
The shutdown contract matters to source reloads and cache work because those tasks share the same process lifetime as the HTTP service.
References: crates/…/server.rs• L311-423 crates/…/martin.rs• L176-190 crates/…/srv.rs• L76-87
Change checklist
When these files or sections are changed, remember to consider these:
- Keep route registration order aligned with route specificity. A broad source route can hide protocol, format redirect, or static image routes if it moves ahead of them.
- Keep the readiness wait in sync with the source manager's load state. A health or catalog response must not claim readiness before the initial catalog boundary is complete.
- Keep
route_prefix,base_path, proxy prefix handling, generated public URLs, and generated style tile URLs consistent. A change in one can produce links that do not match the route surface. - Keep feature-gated route groups aligned with the shared state passed into each worker. An endpoint must not be registered without the resource state that serves it.
- Keep source update handling aligned with cache invalidation. Replacing or removing a source without clearing its cached tiles can return stale data.
- Keep source aliases within the request source limit and prevent aliases from referring to other aliases. Catalog entries and request expansion must describe the same source set.
- Keep PostgreSQL discovery, DuckDB discovery, and object-store credential hand-off aligned with the saved configuration shape. A source can resolve at startup but fail when a remote reader receives different settings.
- Keep tile response negotiation aligned with the advertised source format and enabled MVT/MLT conversions. A route must not advertise a format that a composite source cannot produce.
- Keep terrain neighbourhood gathering aligned with each tile grid's wrapping and edge rules. A change can alter seams or cause requests at world edges to read invalid tiles.
- Keep terrain centre-coverage handling aligned with cache behavior. A missing centre must remain no content, while a missing neighbour must remain a local seam degradation.
- Keep terrain processing limits aligned with CPU cost and shutdown behavior. Gathering and derived-tile work must stop cleanly without starting new work after shutdown.
- Keep terrain entity tags based on all identifiable input tiles and processing settings. Do not create an authoritative tag when an input has no identity.
- Keep rendered image routes aligned with the process-wide encoding limit and platform capability. A route that is described but not registered must remain absent from the public contract.
- Keep OGC map views, supported CRSs, map formats, and WebMercatorQuad tile limits aligned with the renderer and the advertised OGC links.
- Keep static map overlay parsing aligned with the documented GeoJSON contract. Invalid overlay input must remain a client error and must not reach the renderer as partial state.
- Keep bulk layer lowering aligned with the generator's supported layer features. A setting accepted by configuration can still stop an offline bulk run if the generator cannot render it.
- Keep the two offline modes' option contracts separate. Tile-copy options such as concurrent fetches and duplicate handling do not apply to bulk generation, which uses worker threads and writes only a new or empty output.
- Keep output format and compression choices aligned with what Martin can serve. A generated PMTiles or MBTiles file must not advertise an encoding that the server cannot detect or return.
- Keep the test specification format aligned with the bulk renderer. Row identity, layer output, zoom ranges, attributes, and per-tile counts must describe the same result that
martin test runchecks. This includes the count of merge groups that could not be made valid. - Keep test generation and test execution aligned on change status. A changed input row must remain distinct from a changed rendered output so review does not accept stale results by accident.
- Keep the OpenAPI feature groups aligned with route registration. A route added to the server but omitted from the contract is invisible to clients that use the generated description.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A configured source fails and on_invalid is abort | Startup or a reload stops instead of publishing the affected catalog change. | Use the configured invalid-source policy and inspect the startup or reload error. |
| A health check runs while initial sources are still loading | The check waits instead of returning a false healthy result. | Treat the health endpoint as a readiness check when sources are enabled. |
| A broad tile route is registered before a specific protocol or redirect route | Requests can reach the wrong handler. | Preserve the registration order in the server route composition. |
| A route prefix differs from the public URL prefix | Generated links can point outside the reachable deployment path. | Set the public path settings to match the reverse proxy path and keep prefix resolution consistent. |
| A source update does not invalidate its cache | Old tiles can remain visible after the source changes. | Apply source updates through the source manager's update path. |
| A request combines too many sources or mixes source formats or grids | The composite request is rejected instead of producing an invalid tile. | Keep aliases and composite requests within the source limit and use matching source formats and grids. |
| An OGC map request uses an unsupported CRS, conflicting view parameters, or an unsupported image format | The request returns a client error instead of a map. | Use CRS84, EPSG:4326, or EPSG:3857 with one valid view and a supported Accept format. |
| An OGC map tile uses a non-WebMercatorQuad set or falls outside the grid | The tile request is rejected as an unknown or invalid map tile. | Use the advertised WebMercatorQuad links and valid row, column, and zoom values. |
| Rendering is disabled, unavailable on the platform, or a style is missing | Rendered tile, static image, or OGC map requests return a forbidden or not-found response. | Enable rendering on a supported platform and use a configured style. |
| A static map has an inverted bounding box, invalid size, unserved pixel ratio, or malformed overlay | The request returns a client error before or during rendering. | Use valid camera and size values, configured pixel ratios, and a valid GeoJSON FeatureCollection. |
| Image rendering or encoding fails | The rendered response returns a server error and no image is published. | Check the style, renderer, image format, and process capacity. |
| A terrain request has no centre tile at the requested coverage | Martin could return a blank derived tile that looks like real flat or contour-free terrain and remains cached. | Return no content for the missing centre and use ancestor coverage only where the terrain product supports it. |
| A terrain neighbour is missing or outside the grid | The derived tile can lose detail at one seam or fail if the grid edge is treated as a real tile. | Follow the source grid's wrap rules and clamp over unavailable neighbours. |
| A terrain source tile has no usable identity | A derived response can carry an ETag that does not prove its inputs are unchanged. | Omit the entity tag unless all required input identities and processing settings are known. |
| Terrain gathering or CPU work starts after shutdown or exceeds its process limit | The request is rejected or waits behind other terrain work instead of consuming unbounded resources. | Use the shared gather limit and bounded contour or hillshade work. |
| A remote GeoParquet source has an invalid S3 endpoint or missing required credentials | Source resolution or the first remote read fails. | Use object-store settings accepted by the remote source and allow plain HTTP only for trusted endpoints. |
| A PostgreSQL source cannot connect, discover its table, or transform its grid | The source is warned or rejected and is absent from the live catalog. | Check the database, source schema, SRID, and tile-grid contract before publishing. |
| A DuckDB source has no valid database or GeoParquet location | Configuration finalization fails before the server can start. | Provide one supported source kind and an existing local file or supported remote URL. |
| A client requests a format that a source group cannot produce | The tile request returns an unacceptable-format error. | Advertise and request only source-native formats or conversions enabled for every member. |
| Tile-copy mode has no explicit zoom range or has more than one source without a source name | The copy is rejected before it fetches tiles. | Set a maximum zoom or explicit levels and name the source when the catalog has multiple sources. |
| Bulk mode receives a function source, multiple databases, an unsupported grid, or a layer feature it cannot lower | The offline generation run fails before it can produce a valid tileset. | Use table or view sources from one database with Web Mercator and supported layer settings. |
| Bulk generation is interrupted or fails while writing | The output and its write sidecars are removed rather than left as a usable-looking tileset. | Treat the run as atomic and check the final output after the command completes. |
| Bulk mode receives a gapped zoom list or an encoding the serving path cannot detect | The generation run is rejected instead of producing a file with an unsafe serving contract. | Use a continuous zoom range and a format and encoding supported by the target MBTiles or PMTiles path. |
| A test case's source row changed | martin test run reports ROW CHANGED even when the new output may look valid. | Review the input change before accepting a regenerated specification. |
| A test case's rendered output or per-tile counts changed | The case fails and the specification is not silently updated. This includes a change in merge groups that could not be made valid. | Compare the reported diff and use martin test generate with an explicit acceptance decision. |
| A generated case would require more tiles than the review path can hold | The test run fails instead of producing an incomplete case. | Use a smaller case or a suitable zoom range for the specification. |
Key files
| File | Why to read it |
|---|---|
| crates/…/martin.rs | Shows the process entry point and the startup-to-serving sequence. |
| martin/…/lib.rs | Shows the public runtime capability groups and their feature boundaries. |
| crates/…/server.rs | Shows how shared state, middleware, route order, binding, public paths, and shutdown form the HTTP service. |
| crates/…/lifecycle.rs | Shows how configuration becomes a live server state and source catalog. |
| crates/…/root.rs | Shows how file settings and command-line source inputs are combined. |
| crates/…/object_store.rs | Shows the shared remote access and credential boundary. |
| crates/…/tile_source_manager.rs | Shows the live catalog boundary used by requests and reloads. |
| martin/…/source.rs | Shows source aliases, composite source resolution, and catalog metadata. |
| crates/…/admin.rs | Shows the catalog, capability flags, readiness boundary, and root-facing runtime responses. |
| crates/…/content.rs | Shows tile request negotiation, caching, composition, and response behavior. |
| crates/…/neighbourhood.rs | Shows how terrain products gather source coverage and follow tile-grid edges. |
| crates/…/contour.rs | Shows the contour tile capability and its coverage, cache identity, and CPU-work boundary. |
| crates/…/hillshade.rs | Shows the hillshade tile capability and its coverage, cache identity, and CPU-work boundary. |
| crates/…/map.rs | Shows OGC dataset, collection, and style map capabilities and view handling. |
| crates/…/map_tiles.rs | Shows OGC map tileset metadata and rendered map tile access. |
| crates/…/error.rs | Shows how OGC map input and resource failures become public error classes. |
| crates/…/tilesets.rs | Shows how source metadata becomes OGC tileset descriptions. |
| crates/…/styles_rendering.rs | Shows rendered style tile access, image formats, and encoding behavior. |
| crates/…/styles_static.rs | Shows static map images, camera and size inputs, and request overlays. |
| martin/…/schemas.rs | Shows the machine-readable configuration and HTTP capability contracts. |
| crates/…/builder.rs | Shows how PostgreSQL catalogs become published sources. |
| crates/…/resolve.rs | Shows how DuckDB database and GeoParquet entries become live sources. |
| martin/…/cp.rs | Shows tile-copy mode and its shared source resolution path. |
| crates/…/mod.rs | Shows the bulk generation lifecycle from source selection to persistent output. |
| crates/…/mod.rs | Shows the martin test generate and run flows. |
| crates/…/file.rs | Defines the saved case and rendered-result contract used by test specifications. |
| crates/…/render.rs | Shows how one source row becomes tile features and per-tile counts for comparison. |
| crates/…/review.rs | Shows how generated cases become accepted, rejected, changed, or gone specification entries. |
| crates/…/report.rs | Shows how offline review and check results are presented to operators. |
| crates/…/layers.rs | Shows how table and layer settings become a bulk render plan. |
| crates/…/srv.rs | Defines the server settings that affect listening, public paths, and shutdown. |
| martin/…/reload.rs | Defines the change model passed from source discovery to the live catalog. |