Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/openapi.rs

//! **The OpenAPI 3.1 description of the HTTP door** (`GET /openapi.json`), written by
//! hand. Its `paths` are exactly the router's [`ROUTES`](crate::http::ROUTES) (a test
//! holds the two equal); the refusal codes come from [`Code::ALL`].

use serde_json::{Value, json};

use crate::error::Code;

/// The public korp-map server.
pub const PUBLIC_SERVER: &str = "https://karta.gunnar.rs";

fn param(name: &str, at: &str, required: bool, description: &str, schema: Value) -> Value {
    json!({
        "name": name, "in": at, "required": required,
        "description": description, "schema": schema,
    })
}

fn region_param() -> Value {
    param(
        "region",
        "query",
        true,
        "A region name from `/v1/regions`.",
        json!({"type": "string"}),
    )
}

fn refusals(statuses: &[&str]) -> Value {
    let mut m = serde_json::Map::new();
    for s in statuses {
        m.insert(
            (*s).to_string(),
            json!({
                "description": "A refusal: `{\"error\": \"…\", \"code\": \"korp-map-<n>\"}`.",
                "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}},
            }),
        );
    }
    Value::Object(m)
}

/// Headers of a cacheable, encodable reply.
fn reply_headers() -> Value {
    json!({
        "ETag": {"$ref": "#/components/headers/ETag"},
        "Cache-Control": {"$ref": "#/components/headers/Cache-Control"},
        "Content-Encoding": {"$ref": "#/components/headers/Content-Encoding"},
        "Vary": {"$ref": "#/components/headers/Vary"},
    })
}

/// The request headers every cacheable route reads.
fn caching_params() -> Vec<Value> {
    vec![
        json!({"$ref": "#/components/parameters/Accept-Encoding"}),
        json!({"$ref": "#/components/parameters/If-None-Match"}),
    ]
}

fn json_get(summary: &str, description: &str, params: Vec<Value>, schema: Value) -> Value {
    let mut responses = json!({
        "200": {
            "description": "The answer, as JSON.",
            "headers": reply_headers(),
            "content": {"application/json": {"schema": schema}},
        },
        "304": {"description": "Not Modified: `If-None-Match` names this reply.", "headers": reply_headers()},
    });
    if let (Some(r), Value::Object(more)) =
        (responses.as_object_mut(), refusals(&["400", "404", "500"]))
    {
        r.extend(more);
    }
    let mut parameters = params;
    parameters.extend(caching_params());
    json!({"get": {"summary": summary, "description": description, "parameters": parameters, "responses": responses}})
}

fn html_get(summary: &str) -> Value {
    json!({"get": {
        "summary": summary,
        "description": "A page about this server: the regions it serves, an example of every endpoint (curl, Python, DuckDB) and the error codes. No external assets.",
        "responses": {"200": {"description": "The page.", "content": {"text/html": {"schema": {"type": "string"}}}}},
    }})
}

/// **The OpenAPI 3.1 document.**
#[must_use]
pub fn document() -> Value {
    let codes: Vec<String> = Code::ALL.iter().map(|c| c.tag()).collect();
    let code_list: Vec<String> = Code::ALL
        .iter()
        .map(|c| format!("`{}` ({}): {}", c.tag(), c.http_status(), c.summary()))
        .collect();
    let bbox = json!({
        "type": "string",
        "pattern": "^-?[0-9.]+,-?[0-9.]+,-?[0-9.]+,-?[0-9.]+$",
        "examples": ["17.9,59.2,18.2,59.4"],
    });
    let mut paths = serde_json::Map::new();
    paths.insert("/".into(), html_get("This page (the landing page)"));
    paths.insert(
        "/v1/".into(),
        html_get("The landing page under the /v1/ prefix"),
    );
    paths.insert(
        "/openapi.json".into(),
        json!({"get": {
            "summary": "This OpenAPI description",
            "responses": {"200": {"description": "OpenAPI 3.1, JSON.", "content": {"application/json": {"schema": {"type": "object"}}}}},
        }}),
    );
    paths.insert(
        "/v1/health".into(),
        json!({"get": {
            "summary": "Is the server up",
            "responses": {"200": {"description": "`ok`.", "content": {"text/plain": {"schema": {"type": "string", "const": "ok"}}}}},
        }}),
    );
    paths.insert(
        "/v1/regions".into(),
        json_get(
            "The regions served",
            "Each region's name, bounding box and `data_version` (which cut is served). Cached for a minute by default.",
            vec![],
            json!({"type": "array", "items": {"$ref": "#/components/schemas/Region"}}),
        ),
    );
    let mut map_responses = json!({
        "200": {
            "description": "An Arrow IPC stream: the schema (its metadata carries `data_version`, `truncated`, `row_groups_total`, `row_groups_scanned`, `status`, `geometry_source` and the GeoParquet `geo` document), then zero or more record batches of GeoParquet 1.1 native rows: `id`, `tags`, `min_zoom`, `geometry`.",
            "headers": reply_headers(),
            "content": {"application/vnd.apache.arrow.stream": {"schema": {"type": "string", "contentMediaType": "application/vnd.apache.arrow.stream"}}},
        },
        "304": {"description": "Not Modified: `If-None-Match` names this reply.", "headers": reply_headers()},
    });
    if let (Some(r), Value::Object(more)) = (
        map_responses.as_object_mut(),
        refusals(&["400", "404", "500"]),
    ) {
        r.extend(more);
    }
    let mut map_params = vec![
        param(
            "kind",
            "path",
            true,
            "`points` (tagged nodes), `lines` or `areas`.",
            json!({"type": "string", "enum": ["points", "lines", "areas"]}),
        ),
        region_param(),
        param(
            "bbox",
            "query",
            true,
            "`minlon,minlat,maxlon,maxlat` in degrees (WGS 84), min ≤ max.",
            bbox,
        ),
        param(
            "lod",
            "query",
            true,
            "Level of detail, a web-map zoom: the coarsest stored geometry exact enough for it, and only rows whose `min_zoom` ≤ lod.",
            json!({"type": "integer", "minimum": 0, "maximum": 30}),
        ),
        param(
            "max",
            "query",
            false,
            "At most this many rows (lowest `min_zoom` first); the server's default cap applies without it.",
            json!({"type": "integer", "minimum": 1}),
        ),
        param(
            "compress",
            "query",
            false,
            "`zstd`: Arrow IPC buffer compression inside the stream (then no HTTP content encoding).",
            json!({"type": "string", "enum": ["zstd", "none"]}),
        ),
    ];
    map_params.extend(caching_params());
    paths.insert(
        "/v1/map/{kind}".into(),
        json!({"get": {
            "summary": "The map rows in a bounding box",
            "description": "One map query. The same query is served over Arrow Flight on the same port (`DoGet`, the ticket is the query as JSON).",
            "parameters": map_params,
            "responses": map_responses,
        }}),
    );
    paths.insert(
        "/v1/geocode".into(),
        json_get(
            "An address text to ranked addresses",
            "Answered from the region cut's address index, best first.",
            vec![
                region_param(),
                param(
                    "q",
                    "query",
                    true,
                    "The address text, e.g. `Drottninggatan 53 Stockholm`.",
                    json!({"type": "string"}),
                ),
                param(
                    "max",
                    "query",
                    false,
                    "At most this many hits (default 10).",
                    json!({"type": "integer", "minimum": 1, "maximum": 1000}),
                ),
            ],
            json!({"$ref": "#/components/schemas/GeocodeReply"}),
        ),
    );
    paths.insert(
        "/v1/revgeocode".into(),
        json_get(
            "A point to the nearest address",
            "The nearest address in the region cut's address index and its distance in metres.",
            vec![
                region_param(),
                param(
                    "lon",
                    "query",
                    true,
                    "Longitude, degrees.",
                    json!({"type": "number", "minimum": -180, "maximum": 180}),
                ),
                param(
                    "lat",
                    "query",
                    true,
                    "Latitude, degrees.",
                    json!({"type": "number", "minimum": -90, "maximum": 90}),
                ),
            ],
            json!({"$ref": "#/components/schemas/RevGeocodeReply"}),
        ),
    );
    let listing = |summary: &str, params: Vec<Value>| {
        json!({"get": {
            "summary": summary,
            "description": "The files as JSON: name, format (`geoparquet-1.1-native`, `geoparquet-2.0`, `geoparquet-1.x` or `parquet`), size, sha256 (`null` while it is being computed at start), url, region, set and last_modified. `HEAD` answers the headers alone.",
            "parameters": params,
            "responses": {
                "200": {"description": "The files.", "content": {"application/json": {"schema": {"type": "array", "items": {"$ref": "#/components/schemas/FileInfo"}}}}},
                "404": refusals(&["404"])["404"],
            },
        }})
    };
    let file_param = |name: &str, d: &str| param(name, "path", true, d, json!({"type": "string"}));
    paths.insert(
        "/v1/files/".into(),
        listing("Every served file, of every region", vec![]),
    );
    paths.insert(
        "/v1/files/{region}/".into(),
        listing(
            "The region's files",
            vec![file_param("region", "A region with files here.")],
        ),
    );
    let file_headers = json!({
        "Accept-Ranges": {"description": "`bytes`.", "schema": {"type": "string"}},
        "Content-Length": {"schema": {"type": "integer"}},
        "ETag": {"description": "The file's sha256, quoted (once it has been computed at start).", "schema": {"type": "string"}},
        "Last-Modified": {"schema": {"type": "string"}},
        "Cache-Control": {"$ref": "#/components/headers/Cache-Control"},
    });
    let file_get = |summary: &str| {
        json!({
            "summary": summary,
            "description": "One Parquet file, sent as it is (never content-encoded) and read from disk as it is sent. Answers HTTP range requests, so DuckDB, pyarrow and GDAL (`/vsicurl/`) read only the parts a query needs. Only the listed files are served.",
            "parameters": [
                file_param("region", "The region."),
                file_param("set", "The set: `native` (GeoParquet 1.1 native encodings), `geoparquet2` (GeoParquet 2.0), or a name the server was given."),
                file_param("file", "The file name, e.g. `areas.parquet`."),
                {"name": "Range", "in": "header", "required": false, "description": "`bytes=a-b`, `bytes=a-`, `bytes=-n`, or several, comma separated.", "schema": {"type": "string"}},
                {"name": "If-Range", "in": "header", "required": false, "description": "The file's ETag or Last-Modified: the range holds only for that version of the file.", "schema": {"type": "string"}},
                {"$ref": "#/components/parameters/If-None-Match"},
            ],
            "responses": {
                "200": {"description": "The whole file.", "headers": file_headers.clone(), "content": {"application/vnd.apache.parquet": {"schema": {"type": "string", "contentMediaType": "application/vnd.apache.parquet"}}}},
                "206": {"description": "Partial content: one range (with `Content-Range`), or several as `multipart/byteranges`.", "headers": file_headers.clone(), "content": {"application/vnd.apache.parquet": {"schema": {"type": "string"}}, "multipart/byteranges": {"schema": {"type": "string"}}}},
                "304": {"description": "Not Modified: `If-None-Match` names the file's sha256."},
                "404": refusals(&["404"])["404"],
                "416": refusals(&["416"])["416"],
                "503": refusals(&["503"])["503"],
            },
        })
    };
    paths.insert(
        "/v1/files/{region}/{set}/{file}".into(),
        json!({
            "get": file_get("One file, or a range of it"),
            "head": file_get("One file's headers"),
        }),
    );
    let hit = json!({
        "type": "object",
        "required": ["street", "housenumber", "city", "postcode", "lon", "lat", "source", "score"],
        "properties": {
            "street": {"type": "string"}, "housenumber": {"type": "string"},
            "city": {"type": "string"}, "postcode": {"type": "string"},
            "lon": {"type": "number"}, "lat": {"type": "number"},
            "source": {"type": "integer", "description": "The OSM id of the node or way the address came from."},
            "score": {"type": "integer", "description": "How well the text matched; higher is better."},
        },
    });
    json!({
        "openapi": "3.1.0",
        "info": {
            "title": "korp-map map wire",
            "version": "1.2",
            "summary": "OpenStreetMap region cuts as Arrow, and address lookups",
            "description": format!(
                "The HTTP door of korp-map-server: map rows of a region cut as an Arrow IPC stream, \
                 and address lookups as JSON. Arrow Flight is served on the same port. Replies of \
                 1400 bytes or more are sent zstd, br or gzip encoded as `Accept-Encoding` allows; \
                 replies carry a strong `ETag` and `Cache-Control`.\n\nRefusal codes:\n\n- {}",
                code_list.join("\n- ")
            ),
            "license": {"name": "MIT OR Apache-2.0", "identifier": "MIT OR Apache-2.0"},
        },
        "servers": [
            {"url": PUBLIC_SERVER, "description": "The public server (Sweden)."},
            {"url": "/", "description": "The server this description came from."},
        ],
        "paths": paths,
        "components": {
            "schemas": {
                "Region": {
                    "type": "object",
                    "required": ["name", "bbox", "data_version"],
                    "properties": {
                        "name": {"type": "string"},
                        "bbox": {"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4, "description": "minlon, minlat, maxlon, maxlat"},
                        "data_version": {"type": "string", "description": "Which cut is served (opaque)."},
                    },
                },
                "GeocodeHit": hit,
                "GeocodeReply": {
                    "type": "object",
                    "required": ["region", "query", "indexed", "hits"],
                    "properties": {
                        "region": {"type": "string"}, "query": {"type": "string"},
                        "indexed": {"type": "integer", "description": "Addresses in the index."},
                        "hits": {"type": "array", "items": {"$ref": "#/components/schemas/GeocodeHit"}},
                    },
                },
                "RevGeocodeReply": {
                    "type": "object",
                    "required": ["region", "lon", "lat", "indexed", "hit", "distance_m"],
                    "properties": {
                        "region": {"type": "string"}, "lon": {"type": "number"}, "lat": {"type": "number"},
                        "indexed": {"type": "integer"},
                        "hit": {"oneOf": [{"$ref": "#/components/schemas/GeocodeHit"}, {"type": "null"}]},
                        "distance_m": {"type": "number"},
                    },
                },
                "FileInfo": {
                    "type": "object",
                    "required": ["name", "format", "size", "sha256", "url", "region", "set", "last_modified"],
                    "properties": {
                        "name": {"type": "string"},
                        "format": {"type": "string", "enum": ["geoparquet-1.1-native", "geoparquet-2.0", "geoparquet-1.x", "parquet"]},
                        "size": {"type": "integer"},
                        "sha256": {"type": ["string", "null"]},
                        "url": {"type": "string", "description": "The path to fetch it from on this server."},
                        "region": {"type": "string"},
                        "set": {"type": "string"},
                        "last_modified": {"type": "string"},
                    },
                },
                "Error": {
                    "type": "object",
                    "required": ["error", "code"],
                    "properties": {
                        "error": {"type": "string", "description": "What was wrong, for a person."},
                        "code": {"type": "string", "enum": codes},
                    },
                },
            },
            "headers": {
                "ETag": {"description": "A strong tag of the server build, the region's `data_version` and the query; an encoded reply's ends in `-zstd`, `-br` or `-gzip`.", "schema": {"type": "string"}},
                "Cache-Control": {"description": "`public, max-age=<s>`.", "schema": {"type": "string"}},
                "Content-Encoding": {"description": "`zstd`, `br` or `gzip` when the reply is encoded.", "schema": {"type": "string"}},
                "Vary": {"description": "`accept-encoding`.", "schema": {"type": "string"}},
            },
            "parameters": {
                "Accept-Encoding": {"name": "Accept-Encoding", "in": "header", "required": false, "description": "`zstd`, `br` and `gzip` are offered, in that order at equal q.", "schema": {"type": "string"}},
                "If-None-Match": {"name": "If-None-Match", "in": "header", "required": false, "description": "A tag from an earlier reply: `304` when it still names the reply.", "schema": {"type": "string"}},
            },
        },
    })
}