Skip to main content

geolith/output/
format.rs

1//! Output format trait for writing tiles to different archive formats.
2//!
3//! The [`OutputFormat`] trait abstracts over `PMTiles`, `MBTiles`, and future
4//! output formats. The pipeline calls [`write_tile()`](OutputFormat::write_tile)
5//! for each encoded tile and [`finalize()`](OutputFormat::finalize) at the end.
6
7use crate::error::{GeolithError, Result};
8use crate::geometry::mercator::TileCoord;
9use crate::output::hilbert::tile_to_pmtiles_id;
10use crate::output::writer::{Compression, PmtilesWriter, TileType};
11
12/// Trait for writing encoded tiles to an output archive.
13///
14/// Implementations include [`PmtilesOutput`] (`PMTiles` v3) and
15/// `MbtilesOutput` (`MBTiles` SQLite, added in Task 6).
16///
17/// # Thread Safety
18///
19/// Implementations must be `Send` to allow the writer to be moved across
20/// thread boundaries. `Sync` is not required — tile writing is single-threaded.
21pub trait OutputFormat: Send {
22    /// Returns the format name (e.g., `"pmtiles"`, `"mbtiles"`).
23    #[must_use]
24    fn name(&self) -> &str;
25
26    /// Writes a single encoded tile.
27    ///
28    /// `tile` identifies the tile coordinate. `data` is the encoded tile
29    /// content (typically gzip-compressed MVT bytes).
30    ///
31    /// # Errors
32    ///
33    /// Returns an error if the write fails (I/O error, database error, etc.).
34    fn write_tile(&mut self, tile: TileCoord, data: &[u8]) -> Result<()>;
35
36    /// Finalizes the output archive.
37    ///
38    /// Called once after all tiles have been written. Implementations should
39    /// flush buffers, write headers/footers, and close file handles.
40    ///
41    /// `metadata` is a JSON value containing archive metadata (name, bounds,
42    /// minzoom, maxzoom, etc.).
43    ///
44    /// # Errors
45    ///
46    /// Returns an error if finalization fails.
47    fn finalize(&mut self, metadata: &serde_json::Value) -> Result<()>;
48}
49
50/// [`OutputFormat`] adapter wrapping the existing [`PmtilesWriter`].
51///
52/// Translates [`write_tile(TileCoord, data)`](OutputFormat::write_tile) calls
53/// into the `PMTiles` Hilbert-ordered tile ID format used by [`PmtilesWriter`].
54///
55/// Uses `Option<PmtilesWriter>` internally so that [`finalize()`](Self::finalize)
56/// can take ownership of the writer (required by [`PmtilesWriter::finalize`]).
57pub struct PmtilesOutput {
58    /// The underlying writer. `None` after `finalize()` has been called.
59    writer: Option<PmtilesWriter>,
60    /// Cached tile count for post-finalize queries.
61    tiles_written: u64,
62    /// Cached unique tile count for post-finalize queries.
63    unique_tiles: usize,
64}
65
66impl PmtilesOutput {
67    /// Creates a new `PmtilesOutput` writing to the given path.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if the file cannot be created.
72    pub fn create(path: &std::path::Path) -> Result<Self> {
73        Self::create_with(path, TileType::Mvt, Compression::Gzip)
74    }
75
76    /// Creates a new `PmtilesOutput` with explicit tile type and compression.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if the file cannot be created.
81    pub fn create_with(
82        path: &std::path::Path,
83        tile_type: TileType,
84        tile_compression: Compression,
85    ) -> Result<Self> {
86        let writer = PmtilesWriter::create(path, tile_compression, tile_type, 0, 15)?;
87        Ok(Self {
88            writer: Some(writer),
89            tiles_written: 0,
90            unique_tiles: 0,
91        })
92    }
93
94    /// Returns the number of tiles written so far.
95    #[must_use]
96    pub const fn tiles_written(&self) -> u64 {
97        match &self.writer {
98            Some(w) => w.tiles_written(),
99            None => self.tiles_written,
100        }
101    }
102
103    /// Returns the number of unique tile contents (after deduplication).
104    #[must_use]
105    pub fn unique_tiles(&self) -> usize {
106        match &self.writer {
107            Some(w) => w.unique_tiles(),
108            None => self.unique_tiles,
109        }
110    }
111}
112
113impl OutputFormat for PmtilesOutput {
114    fn name(&self) -> &str {
115        "pmtiles"
116    }
117
118    fn write_tile(&mut self, tile: TileCoord, data: &[u8]) -> Result<()> {
119        let writer = self
120            .writer
121            .as_mut()
122            .ok_or_else(|| GeolithError::PmtilesWrite("write_tile called after finalize".into()))?;
123        let tile_id = tile_to_pmtiles_id(tile);
124        writer.write_tile(tile_id, data)?;
125        Ok(())
126    }
127
128    fn finalize(&mut self, metadata: &serde_json::Value) -> Result<()> {
129        let writer = self
130            .writer
131            .take()
132            .ok_or_else(|| GeolithError::PmtilesWrite("finalize called more than once".into()))?;
133        // Cache stats before consuming the writer
134        self.tiles_written = writer.tiles_written();
135        self.unique_tiles = writer.unique_tiles();
136
137        let metadata_bytes = serde_json::to_vec(metadata).map_err(GeolithError::Json)?;
138        writer.finalize(&metadata_bytes)?;
139        Ok(())
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::geometry::mercator::TileCoord;
147    use tempfile::tempdir;
148
149    #[test]
150    fn pmtiles_output_name() {
151        let dir = tempdir().expect("tempdir");
152        let path = dir.path().join("test.pmtiles");
153        let output = PmtilesOutput::create(&path).expect("create");
154        assert_eq!(output.name(), "pmtiles");
155    }
156
157    #[test]
158    fn pmtiles_output_write_and_finalize() {
159        let dir = tempdir().expect("tempdir");
160        let path = dir.path().join("test.pmtiles");
161        let mut output = PmtilesOutput::create(&path).expect("create");
162
163        // Write 3 test tiles
164        let tile_data = b"fake-mvt-data";
165        output
166            .write_tile(TileCoord::new(0, 0, 0), tile_data)
167            .expect("write tile 0/0/0");
168        output
169            .write_tile(TileCoord::new(1, 0, 0), tile_data)
170            .expect("write tile 1/0/0");
171        output
172            .write_tile(TileCoord::new(1, 1, 0), tile_data)
173            .expect("write tile 1/1/0");
174
175        assert_eq!(output.tiles_written(), 3);
176
177        let metadata = serde_json::json!({
178            "name": "test",
179            "format": "pbf",
180            "minzoom": 0,
181            "maxzoom": 1,
182        });
183        output.finalize(&metadata).expect("finalize");
184
185        // Verify the file was created and has content
186        let file_size = std::fs::metadata(&path).expect("metadata").len();
187        assert!(file_size > 127, "PMTiles file should be larger than header");
188    }
189
190    #[test]
191    fn write_after_finalize_returns_error() {
192        let dir = tempdir().expect("tempdir");
193        let path = dir.path().join("test.pmtiles");
194        let mut output = PmtilesOutput::create(&path).expect("create");
195
196        let metadata = serde_json::json!({});
197        output.finalize(&metadata).expect("finalize");
198
199        let result = output.write_tile(TileCoord::new(0, 0, 0), b"data");
200        assert!(result.is_err());
201    }
202
203    #[test]
204    fn double_finalize_returns_error() {
205        let dir = tempdir().expect("tempdir");
206        let path = dir.path().join("test.pmtiles");
207        let mut output = PmtilesOutput::create(&path).expect("create");
208
209        let metadata = serde_json::json!({});
210        output.finalize(&metadata).expect("first finalize");
211        let result = output.finalize(&metadata);
212        assert!(result.is_err());
213    }
214}