Skip to main content

oxigeo_stac/
lib.rs

1//! STAC (SpatioTemporal Asset Catalog) support for OxiGeo.
2//!
3//! This crate provides Pure Rust implementation of the STAC specification,
4//! enabling cloud-native geospatial workflows with catalogs, collections,
5//! and items.
6//!
7//! # Features
8//!
9//! - **STAC 1.0.0 Specification**: Full compliance with STAC 1.0.0
10//! - **Core Models**: Catalog, Collection, Item, and Asset
11//! - **Extensions**: EO (Electro-Optical) and Projection extensions
12//! - **STAC API Client**: Async HTTP client for searching STAC APIs
13//! - **Builder Patterns**: Fluent APIs for easy object creation
14//! - **Validation**: Comprehensive validation of STAC objects
15//! - **Pure Rust**: No C/Fortran dependencies
16//!
17//! # Example
18//!
19//! ```rust
20//! use oxigeo_stac::{ItemBuilder, Asset};
21//! use chrono::Utc;
22//!
23//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
24//! // Create a STAC Item
25//! let item = ItemBuilder::new("my-item")
26//!     .datetime(Utc::now())
27//!     .bbox(-122.5, 37.5, -122.0, 38.0)
28//!     .simple_asset("visual", "https://example.com/image.tif")
29//!     .build()?;
30//!
31//! // Serialize to JSON
32//! let json = serde_json::to_string_pretty(&item)?;
33//! println!("{}", json);
34//! # Ok(())
35//! # }
36//! ```
37//!
38//! # STAC API Search
39//!
40//! ```rust,no_run
41//! # #[cfg(feature = "async")]
42//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
43//! use oxigeo_stac::StacClient;
44//!
45//! // Create a STAC API client
46//! let client = StacClient::new("https://earth-search.aws.element84.com/v1")?;
47//!
48//! // Search for items
49//! let results = client.search()
50//!     .collections(vec!["sentinel-2-l2a"])
51//!     .bbox([-122.5, 37.5, -122.0, 38.0])
52//!     .limit(10)
53//!     .execute()
54//!     .await?;
55//!
56//! println!("Found {} items", results.features.len());
57//! # Ok(())
58//! # }
59//! ```
60
61#![deny(missing_docs)]
62#![cfg_attr(not(feature = "std"), no_std)]
63// Allow collapsible matches for clear STAC field handling
64#![allow(clippy::collapsible_match)]
65#![allow(clippy::collapsible_if)]
66// Allow dead code for future STAC extensions
67#![allow(dead_code)]
68// Allow stripping prefix manually for URL handling
69#![allow(clippy::manual_strip)]
70// Allow method name conflicts for builder patterns
71#![allow(clippy::should_implement_trait)]
72
73// Re-export common types
74pub use chrono;
75pub use geojson;
76pub use serde_json;
77
78// Core modules
79pub mod aggregation;
80pub mod api;
81pub mod asset;
82pub mod builder;
83pub mod catalog;
84pub mod client;
85pub mod collection;
86pub mod collection_aggregation;
87pub mod cql2;
88pub mod error;
89pub mod extensions;
90pub mod item;
91pub mod transaction;
92pub mod version;
93
94#[cfg(feature = "async")]
95pub mod pagination;
96
97#[cfg(feature = "async")]
98pub mod search;
99
100// Public exports
101pub use aggregation::{
102    Aggregation, AggregationRequest, AggregationResponse, AggregationResult, Bucket,
103};
104pub use api::{
105    CollectionSummary, CollectionsList, ConformanceDeclaration, FieldsSpec, ItemCollection,
106    LandingPage, SearchContext as ApiSearchContext, SearchRequest as ApiSearchRequest,
107    SortDirection as ApiSortDirection, SortField,
108};
109pub use asset::{Asset, media_types, roles};
110pub use builder::{CatalogBuilder, CollectionBuilder, ItemBuilder};
111pub use catalog::Catalog;
112pub use collection::{Collection, Extent, Provider, SpatialExtent, TemporalExtent};
113pub use collection_aggregation::{CollectionAggregator, CollectionStats, NumericStats};
114pub use cql2::{Cql2Filter, Cql2Operand};
115pub use error::{Result, StacError};
116pub use extensions::{
117    eo::{Band, CommonBandName, EoExtension},
118    projection::{ProjectionExtension, epsg_codes},
119    sar::{FrequencyBand, ObservationDirection, Polarization, SarExtension},
120    scientific::{Publication, ScientificExtension},
121    timestamps::TimestampsExtension,
122    version::VersionExtension,
123    view::ViewExtension,
124};
125pub use item::{Item, ItemProperties, Link, link_rel};
126pub use transaction::{StacItemStore, TransactionOp, TransactionResult};
127pub use version::StacVersion;
128
129#[cfg(feature = "async")]
130pub use pagination::{CursorPagination, PagePagination, Paginator, TokenPagination};
131
132#[cfg(feature = "async")]
133pub use search::{SearchContext, SearchParams, SearchResults, SortBy, SortDirection, StacClient};
134
135/// STAC version supported by this crate.
136pub const STAC_VERSION: &str = "1.0.0";
137
138/// Helper function to create a bounding box from coordinates.
139///
140/// # Arguments
141///
142/// * `west` - Western longitude
143/// * `south` - Southern latitude
144/// * `east` - Eastern longitude
145/// * `north` - Northern latitude
146///
147/// # Returns
148///
149/// Bounding box vector [west, south, east, north]
150///
151/// # Example
152///
153/// ```
154/// use oxigeo_stac::bbox;
155///
156/// let bbox = bbox(-122.5, 37.5, -122.0, 38.0);
157/// assert_eq!(bbox, vec![-122.5, 37.5, -122.0, 38.0]);
158/// ```
159pub fn bbox(west: f64, south: f64, east: f64, north: f64) -> Vec<f64> {
160    vec![west, south, east, north]
161}
162
163/// Helper function to create a GeoJSON Point geometry.
164///
165/// # Arguments
166///
167/// * `lon` - Longitude
168/// * `lat` - Latitude
169///
170/// # Returns
171///
172/// GeoJSON Point geometry
173///
174/// # Example
175///
176/// ```
177/// use oxigeo_stac::point_geometry;
178///
179/// let geometry = point_geometry(-122.0, 37.0);
180/// assert_eq!(geometry.value, geojson::GeometryValue::new_point([-122.0, 37.0]));
181/// ```
182pub fn point_geometry(lon: f64, lat: f64) -> geojson::Geometry {
183    geojson::Geometry::new_point([lon, lat])
184}
185
186/// Helper function to create a GeoJSON Polygon geometry from a bounding box.
187///
188/// # Arguments
189///
190/// * `west` - Western longitude
191/// * `south` - Southern latitude
192/// * `east` - Eastern longitude
193/// * `north` - Northern latitude
194///
195/// # Returns
196///
197/// GeoJSON Polygon geometry
198///
199/// # Example
200///
201/// ```
202/// use oxigeo_stac::bbox_to_polygon;
203///
204/// let geometry = bbox_to_polygon(-122.5, 37.5, -122.0, 38.0);
205/// match geometry.value {
206///     geojson::GeometryValue::Polygon { coordinates: _ } => (),
207///     _ => panic!("Expected Polygon"),
208/// }
209/// ```
210pub fn bbox_to_polygon(west: f64, south: f64, east: f64, north: f64) -> geojson::Geometry {
211    let polygon = vec![vec![
212        vec![west, south],
213        vec![east, south],
214        vec![east, north],
215        vec![west, north],
216        vec![west, south], // Close the ring
217    ]];
218    geojson::Geometry::new_polygon(polygon)
219}
220
221#[cfg(test)]
222#[allow(clippy::panic)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn test_bbox_helper() {
228        let bbox = bbox(-122.5, 37.5, -122.0, 38.0);
229        assert_eq!(bbox, vec![-122.5, 37.5, -122.0, 38.0]);
230    }
231
232    #[test]
233    fn test_point_geometry() {
234        let geometry = point_geometry(-122.0, 37.0);
235        assert_eq!(
236            geometry.value,
237            geojson::GeometryValue::new_point([-122.0, 37.0])
238        );
239    }
240
241    #[test]
242    fn test_bbox_to_polygon() {
243        let geometry = bbox_to_polygon(-122.5, 37.5, -122.0, 38.0);
244        match geometry.value {
245            geojson::GeometryValue::Polygon {
246                coordinates: coords,
247            } => {
248                assert_eq!(coords.len(), 1);
249                assert_eq!(coords[0].len(), 5); // 4 corners + close
250            }
251            _ => panic!("Expected Polygon"),
252        }
253    }
254
255    #[test]
256    fn test_stac_version() {
257        assert_eq!(STAC_VERSION, "1.0.0");
258    }
259}