Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Add tracing Feature #25

Merged
merged 5 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions snapr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ default = ["rayon", "svg"]
rayon = ["dep:rayon"]
svg = ["dep:resvg"]
tokio = ["dep:async-trait", "dep:tokio"]
tracing = ["dep:tracing"]

[dependencies]
anyhow.workspace = true
Expand All @@ -28,3 +29,4 @@ resvg = { workspace = true, optional = true }
thiserror.workspace = true
tiny-skia = { workspace = true }
tokio = { version = "1.41.0", optional = true, features = ["rt"] }
tracing = { version = "0.1.40", optional = true }
10 changes: 10 additions & 0 deletions snapr/src/drawing/geometry/line.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ impl_styled_geo!(
.inner
.map_coords(|coord| context.epsg_4326_to_pixel(&coord));

#[cfg(feature = "tracing")]
{
tracing::trace!(start = ?line.start, end = ?line.end, "rendering `Line` to `pixmap`");
}

let mut path_builder = PathBuilder::new();
path_builder.move_to(line.start.x as f32, line.start.y as f32);
path_builder.line_to(line.end.x as f32, line.end.y as f32);
Expand Down Expand Up @@ -157,6 +162,11 @@ impl_styled_geo!(
.inner
.map_coords(|coord| context.epsg_4326_to_pixel(&coord));

#[cfg(feature = "tracing")]
{
tracing::trace!("rendering `LineString` to `pixmap`");
}

for (index, point) in line_string.points().enumerate() {
if index == 0 {
path_builder.move_to(point.x() as f32, point.y() as f32);
Expand Down
4 changes: 4 additions & 0 deletions snapr/src/drawing/geometry/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ pub(crate) mod macros {
impl Styleable<$style> for geo::$type<f64> {}

impl Drawable for Styled<'_, geo::$type<f64>, $style> {
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self, pixmap), err)
)]
$draw

fn as_geometry(&self) -> Option<geo::Geometry<f64>> {
Expand Down
5 changes: 5 additions & 0 deletions snapr/src/drawing/geometry/point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ impl_styled_geo!(
}
};

#[cfg(feature = "tracing")]
{
tracing::trace!(position = ?point, "rendering `Point` to `pixmap`");
}

let shape = shape.to_path(point.x() as f32, point.y() as f32)?;

pixmap.fill_path(
Expand Down
5 changes: 5 additions & 0 deletions snapr/src/drawing/geometry/polygon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ impl_styled_geo!(
.inner
.map_coords(|coord| context.epsg_4326_to_pixel(&coord));

#[cfg(feature = "tracing")]
{
tracing::trace!("rendering `Polygon` to `pixmap`");
}

let mut path_builder = PathBuilder::new();

for (index, point) in pixel_polygon.exterior().points().enumerate() {
Expand Down
9 changes: 9 additions & 0 deletions snapr/src/drawing/svg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,21 @@ pub(crate) struct SpatialSvg {
}

impl Drawable for SpatialSvg {
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self, pixmap), err)
)]
fn draw(&self, pixmap: &mut Pixmap, _: &Context) -> Result<(), crate::Error> {
let SpatialSvg { pixel, tree } = self;

let svg_size = tree.size();
let (x, y) = *pixel;

#[cfg(feature = "tracing")]
{
tracing::trace!("rendering `SpatialSvg` to `pixmap`");
}

render(
tree,
Transform::from_translate(
Expand Down
39 changes: 39 additions & 0 deletions snapr/src/fetchers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ impl<'a> TileFetcher<'a> {
Self::Batch(Box::new(tile_fetcher))
}
}

/// Types that represent objects that can fetch map tiles one-by-one with the tile's [`EPSG:3857`](https://epsg.io/3857) position.
///
/// ## Example
Expand Down Expand Up @@ -316,6 +317,10 @@ impl<'a> AsyncTileFetcher<'a> {
#[cfg(feature = "tokio")]
impl<'a> AsyncTileFetcher<'a> {
/// Retrieves tiles from the [`AsyncTileFetcher`] with an [`AsyncBatchTileFetcher`] executor.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self), err)
)]
pub(crate) async fn fetch_tiles_in_batch(
&self,
coordinate_matrix: &[(i32, i32)],
Expand All @@ -325,6 +330,14 @@ impl<'a> AsyncTileFetcher<'a> {

let expected_tile_count = coordinate_matrix.len();

#[cfg(feature = "tracing")]
{
tracing::trace!(
expected_tile_count,
"executing inner `AsyncTileFetcher` variant"
);
}

match self {
AsyncTileFetcher::Individual(tile_fetcher) => {
let mut tiles = Vec::with_capacity(expected_tile_count);
Expand All @@ -333,14 +346,40 @@ impl<'a> AsyncTileFetcher<'a> {
for &(x, y) in coordinate_matrix {
let tile_fetcher = tile_fetcher.clone();

#[cfg(feature = "tracing")]
{
tracing::trace!(
x,
y,
"spawning task for `AsyncIndividualTileFetcher.fetch_tile` call"
);
}

tasks.spawn(async move {
let tile = tile_fetcher.fetch_tile(x, y, zoom).await;
tile.map(|tile| (x, y, tile))
});
}

#[cfg(feature = "tracing")]
{
tracing::trace!(
tasks = tasks.len(),
"awaiting `JoinSet` of `AsyncIndividualTileFetcher.fetch_tile` tasks"
);
}

while let Some(task) = tasks.join_next().await {
let tile = task.map_err(|_| Error::AsynchronousTaskPanic)??;

#[cfg(feature = "tracing")]
{
tracing::trace!(
tile = ?(tile.0, tile.1),
"successfully retrieved tile from `AsyncIndividualTileFetcher.fetch_tile` task"
);
}

tiles.push(tile);
}

Expand Down
79 changes: 78 additions & 1 deletion snapr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ pub struct Snapr<'a> {

impl<'a> Snapr<'a> {
/// Attempts to generate a snapshot from the [`Drawable`] object.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "DEBUG", skip(self, drawable), err)
)]
pub fn snapshot_from_drawable(
&self,
drawable: &dyn Drawable,
Expand All @@ -142,6 +146,10 @@ impl<'a> Snapr<'a> {
}

/// Attempts to generate a snapshot from the [`Drawable`] objects.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "DEBUG", skip(self, drawables), err)
)]
pub fn snapshot_from_drawables(
&self,
drawables: Vec<&dyn Drawable>,
Expand All @@ -167,10 +175,21 @@ impl<'a> Snapr<'a> {
Zoom::Constant(level) => level,
Zoom::Automatic(max_level) => match geometries.bounding_rect() {
Some(bounding_box) => self.zoom_from_geometries(bounding_box, max_level),
None => todo!("Return an `Err` or find a suitable default for `bounding_box`"),
None => return Err(Error::BoundingBoxCalculation),
},
};

#[cfg(feature = "tracing")]
{
tracing::trace!(
zoom,
?center,
geometries = geometries.len(),
drawables = drawables.len(),
"calculated variables required for overlaying and rendering. overlaying backing tiles..."
);
}

self.overlay_backing_tiles(&mut output_image, center, zoom)?;

drawables
Expand All @@ -184,9 +203,22 @@ impl<'a> Snapr<'a> {
index,
};

#[cfg(feature = "tracing")]
{
tracing::trace!(
?context,
"rendering `Drawable` with the `Drawable.draw` method"
);
}

drawable.draw(&mut pixmap, &context)
})?;

#[cfg(feature = "tracing")]
{
tracing::trace!("merging the tiles and `Drawables` render images together");
}

let pixmap_image = image::ImageBuffer::from_fn(self.width, self.height, |x, y| {
let pixel = pixmap.pixel(x, y)
.expect("pixel coordinates should exactly match across `image::ImageBuffer` and `tiny_skia::Pixmap` instances");
Expand All @@ -199,6 +231,10 @@ impl<'a> Snapr<'a> {
}

/// Attempts to generate a snapshot from the given [`Geometry`](geo::Geometry).
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "DEBUG", skip(self, geometry), err)
)]
pub fn snapshot_from_geometry<G>(&self, geometry: G) -> Result<image::RgbaImage, Error>
where
G: Into<geo::Geometry>,
Expand All @@ -208,6 +244,10 @@ impl<'a> Snapr<'a> {
}

/// Attempts to generate a snapshot from the given [`Geometries`](geo::Geometry).
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "DEBUG", skip(self), err)
)]
pub fn snapshot_from_geometries(
&self,
geometries: Vec<geo::Geometry>,
Expand Down Expand Up @@ -235,6 +275,10 @@ impl<'a> Snapr<'a> {

impl<'a> Snapr<'a> {
/// Calculates the [`zoom`](Self::zoom) level to use when [`zoom`](Self::zoom) itself is [`None`].
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self), ret)
)]
fn zoom_from_geometries(&self, bounding_box: geo::Rect, max_zoom: u8) -> u8 {
let mut zoom = 1;

Expand Down Expand Up @@ -265,6 +309,10 @@ impl<'a> Snapr<'a> {
}

/// Fills the given `image` with tiles centered around the given `epsg_3857_center` point.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self, image), err)
)]
fn overlay_backing_tiles(
&self,
image: &mut image::RgbaImage,
Expand All @@ -282,6 +330,18 @@ impl<'a> Snapr<'a> {
let max_x = (epsg_3857_center.x() + required_columns).ceil() as i32;
let max_y = (epsg_3857_center.y() + required_rows).ceil() as i32;

#[cfg(feature = "tracing")]
{
tracing::trace!(
required_rows,
required_columns,
?epsg_3857_center,
min = ?(min_x, min_y),
max = ?(max_x, max_y),
"calculated bounds and required variables"
);
}

let coordinate_matrix = (min_x..max_x)
.map(|x| (x, min_y..max_y))
.flat_map(|(x, y)| y.map(move |y| (x, y)));
Expand Down Expand Up @@ -310,6 +370,13 @@ impl<'a> Snapr<'a> {

#[cfg(feature = "rayon")]
{
#[cfg(feature = "tracing")]
{
tracing::trace!(
"executing `TileFetcher::Individual` in parallel with `rayon` crate"
);
}

coordinate_matrix
.par_bridge()
.flat_map(x_y_to_tile)
Expand All @@ -320,6 +387,11 @@ impl<'a> Snapr<'a> {

#[cfg(not(feature = "rayon"))]
{
#[cfg(feature = "tracing")]
{
tracing::trace!("executing `TileFetcher::Individual` sequentially");
}

for (x, y) in coordinate_matrix {
let (tile, x, y) = x_y_to_tile((x, y))?;
overlay(image, &tile, x, y);
Expand All @@ -330,6 +402,11 @@ impl<'a> Snapr<'a> {
TileFetcher::Batch(ref tile_fetcher) => {
let coordinate_matrix = coordinate_matrix.collect::<Vec<_>>();

#[cfg(feature = "tracing")]
{
tracing::trace!("executing `TileFetcher::Batch`");
}

for (x, y, tile) in tile_fetcher.fetch_tiles(&coordinate_matrix, zoom)? {
let tile_coords = (geo::Point::from((x as f64, y as f64)) - epsg_3857_center)
.map_coords(|coord| geo::Coord {
Expand Down
26 changes: 26 additions & 0 deletions snapr/src/tokio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ impl<'a> SnaprBuilder<'a> {
/// assert!(snapr.is_ok());
/// }
/// ```
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self), err)
)]
pub async fn build(self) -> Result<Snapr<'a>, Error> {
let Some(tile_fetcher) = self.tile_fetcher else {
return Err(Error::Builder {
Expand All @@ -62,6 +66,14 @@ impl<'a> SnaprBuilder<'a> {
inner: tile_fetcher,
};

#[cfg(feature = "tracing")]
{
tracing::trace!(
handle = ?tokio_tile_fetcher.handle,
"built internal `TokioTileFetcher`"
);
}

TileFetcher::batch(tokio_tile_fetcher)
};

Expand Down Expand Up @@ -100,14 +112,28 @@ struct TokioTileFetcher<'a> {
}

impl<'a> BatchTileFetcher for TokioTileFetcher<'a> {
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "TRACE", skip(self), err)
)]
fn fetch_tiles(
&self,
coordinate_matrix: &[(i32, i32)],
zoom: u8,
) -> Result<Vec<(i32, i32, image::DynamicImage)>, Error> {
thread::scope(move |scope| {
let spawned = scope.spawn(move || {
#[cfg(feature = "tracing")]
{
tracing::trace!("spawned `std::thread` to execute future on");
}

self.handle.block_on(async move {
#[cfg(feature = "tracing")]
{
tracing::trace!("running `Handle::block_on` on `AsyncTileFetcher.fetch_tiles_in_batch` future");
}

self.inner
.fetch_tiles_in_batch(coordinate_matrix, zoom)
.await
Expand Down
Loading