open-geocode 0.1.0

Lightweight geocoding engine: build a binary Pack from OSM extracts and serve search, autocomplete, and reverse geocoding from a single Rust runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
use std::{fs::File, net::SocketAddr, path::PathBuf};

use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand};
use serde_json::Value;

use open_geocode::{
    batch::{BatchGeocodeOptions, CoordinateJoinOptions, parse_field_groups, run_batch_geocode},
    bench::{PackBenchmarkOptions, benchmark_pack},
    builder::{BuildOsmOptions, DEFAULT_MEMORY_BUDGET_BYTES, build_osm_pack},
    pack::{PackReader, RecordId},
    reverse::{PackReverseGeocoder, ReverseGeocodeOptions},
    runtime::{ServeOptions, serve},
    search::{PackTextSearcher, TextSearchOptions},
};

#[derive(Debug, Parser)]
#[command(name = "open-geocode")]
#[command(about = "Build and serve lightweight geocoding data packs")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Build a Pack from an OSM .pbf extract, from a city up to the planet.
    Build {
        /// Input .osm.pbf file, sorted by type and id (the standard layout).
        #[arg(long)]
        input: PathBuf,

        /// Output Pack directory. The new build is published atomically.
        #[arg(long)]
        pack: PathBuf,

        /// Memory for build sort buffers, in MiB (64 to 1048576). Larger inputs
        /// spill to scratch files on disk instead of using more memory.
        #[arg(
            long,
            default_value_t = (DEFAULT_MEMORY_BUDGET_BYTES >> 20) as u64,
            value_parser = clap::value_parser!(u64).range(MIN_MEMORY_BUDGET_MB..=MAX_MEMORY_BUDGET_MB),
        )]
        memory_budget_mb: u64,

        /// Directory for scratch files. Defaults to inside the Pack directory.
        #[arg(long)]
        scratch_dir: Option<PathBuf>,
    },

    /// Inspect Pack records as readable JSON.
    #[command(name = "inspect-pack")]
    InspectPack {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,

        /// Read one Pack record by numeric row id.
        #[arg(long)]
        row: Option<RecordId>,

        /// Read one Pack record by source id, for example osm:node:123.
        #[arg(long)]
        id: Option<String>,

        /// List records from one layer.
        #[arg(long)]
        layer: Option<String>,

        /// Number of records or rejections to print. Use 0 for no limit.
        #[arg(long, default_value_t = 20)]
        limit: usize,

        /// Print rejected evidence instead of accepted records.
        #[arg(long)]
        rejections: bool,

        /// Include Boundary-Derived Context for --row or --id.
        #[arg(long)]
        context: bool,
    },

    /// Check a Pack file against its section checksums, for example after
    /// copying or downloading it.
    #[command(name = "verify-pack")]
    VerifyPack {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,
    },

    /// Search a Pack text index and hydrate matching records.
    #[command(name = "search-pack")]
    SearchPack {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,

        /// Text query to search.
        #[arg(long)]
        query: String,

        /// Restrict hits to one record layer.
        #[arg(long)]
        layer: Option<String>,

        /// Number of search hits to print. Use 0 for the default.
        #[arg(long, default_value_t = 10)]
        limit: usize,
    },

    /// Reverse geocode one coordinate from a Pack spatial index.
    #[command(name = "reverse-pack")]
    ReversePack {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,

        /// Longitude in WGS84 decimal degrees.
        #[arg(long)]
        lon: f64,

        /// Latitude in WGS84 decimal degrees.
        #[arg(long)]
        lat: f64,
    },

    /// Benchmark Pack size, open time, and query latency.
    #[command(name = "bench-pack")]
    BenchPack {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,

        /// Optional JSON fixture with search, autocomplete, and reverse cases.
        #[arg(long)]
        queries: Option<PathBuf>,

        /// Measured runs per query case.
        #[arg(long, default_value_t = 5)]
        iterations: usize,

        /// Warmup runs per query case, excluded from latency stats.
        #[arg(long, default_value_t = 1)]
        warmup: usize,

        /// Optional output path for the JSON benchmark report.
        #[arg(long)]
        output: Option<PathBuf>,
    },

    /// Geocode CSV rows into lat/lon columns using a Pack text index.
    #[command(name = "batch-geocode")]
    BatchGeocode(Box<BatchGeocodeArgs>),

    /// Serve the Runtime HTTP API and static demo files.
    Serve {
        /// Pack directory or Pack file.
        #[arg(long)]
        pack: PathBuf,

        /// Static demo directory to serve.
        #[arg(long, default_value = "demo")]
        demo: PathBuf,

        /// Address and port to bind.
        #[arg(long, default_value = "127.0.0.1:8080")]
        bind: SocketAddr,

        /// Basemap PMTiles archive to serve at /basemap.pmtiles. Skipped if the
        /// file is absent, so the demo still runs without a local basemap.
        #[arg(long, default_value = "data/ontario.pmtiles")]
        basemap: PathBuf,
    },
}

#[derive(Debug, Args)]
struct BatchGeocodeArgs {
    /// Pack directory or Pack file. Required with --address-fields.
    #[arg(long)]
    pack: Option<PathBuf>,

    /// Input CSV path.
    #[arg(long)]
    input: PathBuf,

    /// Clean output CSV path. Input columns are preserved and lat/lon are added or filled.
    #[arg(long)]
    output: PathBuf,

    /// Audit CSV path.
    #[arg(long)]
    audit: PathBuf,

    /// Comma-separated address columns to try as one query candidate. Repeat for fallbacks.
    #[arg(long = "address-fields")]
    address_fields: Vec<String>,

    /// Optional locality/city column used for engine context validation.
    #[arg(long)]
    locality_field: Option<String>,

    /// Optional region/province/state column used for engine context validation.
    #[arg(long)]
    region_field: Option<String>,

    /// Optional postal-code column used for engine context validation.
    #[arg(long)]
    postcode_field: Option<String>,

    /// Optional layer filter passed to the engine searcher.
    #[arg(long)]
    layer: Option<String>,

    /// Number of engine candidates to inspect per query. Use 0 for the engine default.
    #[arg(long, default_value_t = 10)]
    limit: usize,

    /// Latitude output column name.
    #[arg(long, default_value = "lat")]
    lat_column: String,

    /// Longitude output column name.
    #[arg(long, default_value = "lon")]
    lon_column: String,

    /// Copy coordinates from another CSV instead of geocoding address fields.
    #[arg(long)]
    join_coordinates_from: Option<PathBuf>,

    /// Key column used with --join-coordinates-from.
    #[arg(long)]
    join_key: Option<String>,

    /// Latitude column in the joined CSV.
    #[arg(long, default_value = "lat")]
    join_lat_column: String,

    /// Longitude column in the joined CSV.
    #[arg(long, default_value = "lon")]
    join_lon_column: String,
}

/// Below this, sorters spill so often that the build drowns in tiny run files.
const MIN_MEMORY_BUDGET_MB: u64 = 64;
/// 1 TiB; keeps the conversion to bytes far from overflow.
const MAX_MEMORY_BUDGET_MB: u64 = 1 << 20;

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Build {
            input,
            pack,
            memory_budget_mb,
            scratch_dir,
        } => {
            let report = build_osm_pack(BuildOsmOptions {
                input,
                pack,
                memory_budget_bytes: usize::try_from(memory_budget_mb << 20)
                    .context("--memory-budget-mb is larger than this machine can address")?,
                scratch_dir,
            })?;
            write_json(serde_json::json!({
                "records": report.output.record_count,
                "rejections": report.output.rejection_count,
                "pack_bytes": report.output.pack_bytes,
                "scratch_spilled_bytes": report.scratch.spilled_bytes,
                "seconds": report.phases.total_ms as f64 / 1000.0,
            }))
        }
        Commands::InspectPack {
            pack,
            row,
            id,
            layer,
            limit,
            rejections,
            context,
        } => inspect_pack(pack, row, id, layer, limit, rejections, context),
        Commands::VerifyPack { pack } => {
            let reader = PackReader::open(pack)?;
            reader.verify()?;
            write_json(serde_json::json!({
                "path": reader.path().display().to_string(),
                "sections": reader.container().sections().len(),
                "bytes": reader.container().file_size(),
                "verified": true,
            }))
        }
        Commands::SearchPack {
            pack,
            query,
            layer,
            limit,
        } => search_pack(pack, query, layer, limit),
        Commands::ReversePack { pack, lon, lat } => reverse_pack(pack, lon, lat),
        Commands::BenchPack {
            pack,
            queries,
            iterations,
            warmup,
            output,
        } => bench_pack(pack, queries, iterations, warmup, output),
        Commands::BatchGeocode(args) => batch_geocode(*args),
        Commands::Serve {
            pack,
            demo,
            bind,
            basemap,
        } => {
            serve(ServeOptions {
                pack,
                demo,
                bind,
                basemap,
            })
            .await
        }
    }
}

fn inspect_pack(
    pack: PathBuf,
    row: Option<RecordId>,
    id: Option<String>,
    layer: Option<String>,
    limit: usize,
    rejections: bool,
    include_context: bool,
) -> Result<()> {
    let reader = PackReader::open(pack)?;
    let output = if rejections {
        serde_json::to_value(reader.rejections(limit)?)?
    } else if let Some(row) = row {
        inspect_record_json(&reader, row, include_context)?
    } else if let Some(id) = id {
        inspect_record_by_source_id_json(&reader, &id, include_context)?
    } else if let Some(layer) = layer {
        serde_json::to_value(reader.records_json_by_layer(&layer, limit)?)?
    } else {
        serde_json::json!({
            "path": reader.path().display().to_string(),
            "manifest": reader.manifest(),
            "sections": reader.section_sizes(),
        })
    };

    write_json(output)
}

fn inspect_record_by_source_id_json(
    reader: &PackReader,
    source_id: &str,
    include_context: bool,
) -> Result<Value> {
    match reader.find_by_source_id(source_id)? {
        Some(record_id) => inspect_record_json(reader, record_id, include_context),
        None => bail!("record not found: {source_id}"),
    }
}

fn inspect_record_json(
    reader: &PackReader,
    record_id: RecordId,
    include_context: bool,
) -> Result<Value> {
    let mut value = reader.record_json(record_id)?;
    if !include_context {
        return Ok(value);
    }

    let boundary_context = boundary_context_json(reader, record_id)?;
    let Some(object) = value.as_object_mut() else {
        bail!("record JSON must be an object");
    };
    object.insert("boundary_context".to_string(), boundary_context);
    Ok(value)
}

fn boundary_context_json(reader: &PackReader, record_id: RecordId) -> Result<Value> {
    let Some(context) = reader.boundary_context(record_id)? else {
        return Ok(serde_json::json!(null));
    };
    let mut object = serde_json::Map::new();
    object.insert("flags".to_string(), serde_json::json!(context.flags));

    {
        let tuple = context.admin_context;
        for (key, value) in [
            ("country", tuple.country_record_id),
            ("region", tuple.region_record_id),
            ("district", tuple.district_record_id),
            ("locality", tuple.locality_record_id),
            ("neighbourhood", tuple.neighbourhood_record_id),
            ("place", tuple.place_record_id),
        ] {
            if let Some(parent_id) = value
                && let Some(record) = reader.context_record(parent_id)?
            {
                object.insert(
                    key.to_string(),
                    serde_json::json!({
                        "record_id": parent_id,
                        "id": record.id,
                        "label": record.label,
                        "name": record.name,
                        "layer": record.layer,
                    }),
                );
            }
        }
    }

    Ok(Value::Object(object))
}

fn write_json(value: Value) -> Result<()> {
    let stdout = std::io::stdout();
    let mut lock = stdout.lock();
    serde_json::to_writer_pretty(&mut lock, &value)?;
    use std::io::Write;
    writeln!(lock)?;
    Ok(())
}

fn write_json_to_path(value: &Value, output: PathBuf) -> Result<()> {
    if let Some(parent) = output.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    let file = File::create(&output)?;
    serde_json::to_writer_pretty(file, value)?;
    Ok(())
}

fn search_pack(pack: PathBuf, query: String, layer: Option<String>, limit: usize) -> Result<()> {
    let searcher = PackTextSearcher::open(pack)?;
    let hits = searcher.search(TextSearchOptions {
        query,
        limit,
        layer,
    })?;
    write_json(serde_json::to_value(hits)?)
}

fn reverse_pack(pack: PathBuf, lon: f64, lat: f64) -> Result<()> {
    let geocoder = PackReverseGeocoder::open(pack)?;
    let response = geocoder.reverse(ReverseGeocodeOptions { lon, lat })?;
    write_json(serde_json::to_value(response)?)
}

fn bench_pack(
    pack: PathBuf,
    queries: Option<PathBuf>,
    iterations: usize,
    warmup: usize,
    output: Option<PathBuf>,
) -> Result<()> {
    let report = benchmark_pack(PackBenchmarkOptions {
        pack,
        queries,
        iterations,
        warmup,
    })?;
    let value = serde_json::to_value(report)?;
    if let Some(output) = output {
        write_json_to_path(&value, output)
    } else {
        write_json(value)
    }
}

fn batch_geocode(args: BatchGeocodeArgs) -> Result<()> {
    let BatchGeocodeArgs {
        pack,
        input,
        output,
        audit,
        address_fields,
        locality_field,
        region_field,
        postcode_field,
        layer,
        limit,
        lat_column,
        lon_column,
        join_coordinates_from,
        join_key,
        join_lat_column,
        join_lon_column,
    } = args;
    let address_field_groups = parse_field_groups(&address_fields)?;
    let join = if let Some(path) = join_coordinates_from {
        let key_column = join_key.context("--join-key is required with --join-coordinates-from")?;
        Some(CoordinateJoinOptions {
            path,
            key_column,
            lat_column: join_lat_column,
            lon_column: join_lon_column,
        })
    } else {
        None
    };
    let report = run_batch_geocode(BatchGeocodeOptions {
        pack,
        input,
        output: output.clone(),
        audit: audit.clone(),
        address_field_groups,
        locality_field,
        region_field,
        postcode_field,
        layer,
        limit,
        lat_column,
        lon_column,
        join,
    })?;
    write_json(serde_json::json!({
        "rows": report.rows,
        "resolved": report.resolved,
        "output": output.display().to_string(),
        "audit": audit.display().to_string(),
    }))
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    fn build_budget(value: &str) -> Result<usize, clap::Error> {
        let cli = Cli::try_parse_from([
            "open-geocode",
            "build",
            "--input",
            "in.osm.pbf",
            "--pack",
            "pack",
            "--memory-budget-mb",
            value,
        ])?;
        match cli.command {
            Commands::Build {
                memory_budget_mb, ..
            } => Ok(memory_budget_mb as usize),
            _ => unreachable!("parsed a build command"),
        }
    }

    #[test]
    fn memory_budget_must_be_usable() {
        assert!(build_budget("0").is_err());
        assert!(build_budget("63").is_err());
        assert!(build_budget("99999999999999999").is_err());
        assert_eq!(build_budget("64").expect("minimum"), 64);
        assert_eq!(build_budget("16384").expect("planet"), 16_384);
    }
}