geolith 0.1.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Output format trait for writing tiles to different archive formats.
//!
//! The [`OutputFormat`] trait abstracts over `PMTiles`, `MBTiles`, and future
//! output formats. The pipeline calls [`write_tile()`](OutputFormat::write_tile)
//! for each encoded tile and [`finalize()`](OutputFormat::finalize) at the end.

use crate::error::{GeolithError, Result};
use crate::geometry::mercator::TileCoord;
use crate::output::hilbert::tile_to_pmtiles_id;
use crate::output::writer::{Compression, PmtilesWriter, TileType};

/// Trait for writing encoded tiles to an output archive.
///
/// Implementations include [`PmtilesOutput`] (`PMTiles` v3) and
/// `MbtilesOutput` (`MBTiles` SQLite, added in Task 6).
///
/// # Thread Safety
///
/// Implementations must be `Send` to allow the writer to be moved across
/// thread boundaries. `Sync` is not required — tile writing is single-threaded.
pub trait OutputFormat: Send {
    /// Returns the format name (e.g., `"pmtiles"`, `"mbtiles"`).
    #[must_use]
    fn name(&self) -> &str;

    /// Writes a single encoded tile.
    ///
    /// `tile` identifies the tile coordinate. `data` is the encoded tile
    /// content (typically gzip-compressed MVT bytes).
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails (I/O error, database error, etc.).
    fn write_tile(&mut self, tile: TileCoord, data: &[u8]) -> Result<()>;

    /// Finalizes the output archive.
    ///
    /// Called once after all tiles have been written. Implementations should
    /// flush buffers, write headers/footers, and close file handles.
    ///
    /// `metadata` is a JSON value containing archive metadata (name, bounds,
    /// minzoom, maxzoom, etc.).
    ///
    /// # Errors
    ///
    /// Returns an error if finalization fails.
    fn finalize(&mut self, metadata: &serde_json::Value) -> Result<()>;
}

/// [`OutputFormat`] adapter wrapping the existing [`PmtilesWriter`].
///
/// Translates [`write_tile(TileCoord, data)`](OutputFormat::write_tile) calls
/// into the `PMTiles` Hilbert-ordered tile ID format used by [`PmtilesWriter`].
///
/// Uses `Option<PmtilesWriter>` internally so that [`finalize()`](Self::finalize)
/// can take ownership of the writer (required by [`PmtilesWriter::finalize`]).
pub struct PmtilesOutput {
    /// The underlying writer. `None` after `finalize()` has been called.
    writer: Option<PmtilesWriter>,
    /// Cached tile count for post-finalize queries.
    tiles_written: u64,
    /// Cached unique tile count for post-finalize queries.
    unique_tiles: usize,
}

impl PmtilesOutput {
    /// Creates a new `PmtilesOutput` writing to the given path.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created.
    pub fn create(path: &std::path::Path) -> Result<Self> {
        Self::create_with(path, TileType::Mvt, Compression::Gzip)
    }

    /// Creates a new `PmtilesOutput` with explicit tile type and compression.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created.
    pub fn create_with(
        path: &std::path::Path,
        tile_type: TileType,
        tile_compression: Compression,
    ) -> Result<Self> {
        let writer = PmtilesWriter::create(path, tile_compression, tile_type, 0, 15)?;
        Ok(Self {
            writer: Some(writer),
            tiles_written: 0,
            unique_tiles: 0,
        })
    }

    /// Returns the number of tiles written so far.
    #[must_use]
    pub const fn tiles_written(&self) -> u64 {
        match &self.writer {
            Some(w) => w.tiles_written(),
            None => self.tiles_written,
        }
    }

    /// Returns the number of unique tile contents (after deduplication).
    #[must_use]
    pub fn unique_tiles(&self) -> usize {
        match &self.writer {
            Some(w) => w.unique_tiles(),
            None => self.unique_tiles,
        }
    }
}

impl OutputFormat for PmtilesOutput {
    fn name(&self) -> &str {
        "pmtiles"
    }

    fn write_tile(&mut self, tile: TileCoord, data: &[u8]) -> Result<()> {
        let writer = self
            .writer
            .as_mut()
            .ok_or_else(|| GeolithError::PmtilesWrite("write_tile called after finalize".into()))?;
        let tile_id = tile_to_pmtiles_id(tile);
        writer.write_tile(tile_id, data)?;
        Ok(())
    }

    fn finalize(&mut self, metadata: &serde_json::Value) -> Result<()> {
        let writer = self
            .writer
            .take()
            .ok_or_else(|| GeolithError::PmtilesWrite("finalize called more than once".into()))?;
        // Cache stats before consuming the writer
        self.tiles_written = writer.tiles_written();
        self.unique_tiles = writer.unique_tiles();

        let metadata_bytes = serde_json::to_vec(metadata).map_err(GeolithError::Json)?;
        writer.finalize(&metadata_bytes)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::mercator::TileCoord;
    use tempfile::tempdir;

    #[test]
    fn pmtiles_output_name() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("test.pmtiles");
        let output = PmtilesOutput::create(&path).expect("create");
        assert_eq!(output.name(), "pmtiles");
    }

    #[test]
    fn pmtiles_output_write_and_finalize() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("test.pmtiles");
        let mut output = PmtilesOutput::create(&path).expect("create");

        // Write 3 test tiles
        let tile_data = b"fake-mvt-data";
        output
            .write_tile(TileCoord::new(0, 0, 0), tile_data)
            .expect("write tile 0/0/0");
        output
            .write_tile(TileCoord::new(1, 0, 0), tile_data)
            .expect("write tile 1/0/0");
        output
            .write_tile(TileCoord::new(1, 1, 0), tile_data)
            .expect("write tile 1/1/0");

        assert_eq!(output.tiles_written(), 3);

        let metadata = serde_json::json!({
            "name": "test",
            "format": "pbf",
            "minzoom": 0,
            "maxzoom": 1,
        });
        output.finalize(&metadata).expect("finalize");

        // Verify the file was created and has content
        let file_size = std::fs::metadata(&path).expect("metadata").len();
        assert!(file_size > 127, "PMTiles file should be larger than header");
    }

    #[test]
    fn write_after_finalize_returns_error() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("test.pmtiles");
        let mut output = PmtilesOutput::create(&path).expect("create");

        let metadata = serde_json::json!({});
        output.finalize(&metadata).expect("finalize");

        let result = output.write_tile(TileCoord::new(0, 0, 0), b"data");
        assert!(result.is_err());
    }

    #[test]
    fn double_finalize_returns_error() {
        let dir = tempdir().expect("tempdir");
        let path = dir.path().join("test.pmtiles");
        let mut output = PmtilesOutput::create(&path).expect("create");

        let metadata = serde_json::json!({});
        output.finalize(&metadata).expect("first finalize");
        let result = output.finalize(&metadata);
        assert!(result.is_err());
    }
}