stac 0.10.0

Rust library for the SpatioTemporal Asset Catalog (STAC) specification
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
//! Rust implementation of the [SpatioTemporal Asset Catalog (STAC)](https://stacspec.org/) specification.
//!
//! The SpatioTemporal Asset Catalog (STAC) specification provides a common language to describe a range of geospatial information, so it can more easily be indexed and discovered.
//! A 'spatiotemporal asset' is any file that represents information about the earth captured in a certain space and time.
//!
//! This is a Rust implementation of the specification.
//! Similar projects in other languages include:
//!
//! - Python: [PySTAC](https://pystac.readthedocs.io/en/1.0/)
//! - Go: [go-stac](https://github.com/planetlabs/go-stac)
//! - .NET: [DotNetStac](https://github.com/Terradue/DotNetStac)
//! - PHP: [resto](https://github.com/jjrom/resto)
//!
//! # Data structures
//!
//! STAC has three core data structures:
//!
//! - [Item] is a [GeoJSON](http://geojson.org/) [Feature](https://tools.ietf.org/html/rfc7946#section-3.2) augmented with [foreign members](https://tools.ietf.org/html/rfc7946#section-6)
//! - [Catalog] represents a logical group of other [Catalogs](Catalog), [Collections](Collection), and [Items](Item)
//! - [Collection] shares all fields with the `Catalog` (with different allowed values for `type` and `stac_extensions`) and adds fields to describe the whole dataset and the included set of `Items`
//!
//! All three are provided as [serde](https://serde.rs/) (de)serializable structures with public attributes.
//! Each structure provides a `new` method that fills most of the object's attributes with sensible defaults:
//!
//! ```
//! use stac::{Item, Catalog, Collection};
//! let item = Item::new("id");
//! let catalog = Catalog::new("id", "description");
//! let collection = Catalog::new("id", "description");
//! ```
//!
//! All attributes of STAC objects are accessible as public members:
//!
//! ```
//! use stac::{Item, Link};
//! let mut item = Item::new("id");
//! assert_eq!(item.id, "id");
//! assert!(item.geometry.is_none());
//! assert!(item.links.is_empty());
//! item.links.push(Link::new("an/href", "a-rel-type"));
//! ```
//!
//! # [Value]
//!
//! A [Value] can represent any of the three core data structures, as well as an [ItemCollection], akin to [serde_json::Value]:
//!
//! ```
//! use stac::{Value, Item};
//!
//! let value = Value::Item(Item::new("an-id"));
//! ```
//!
//! [Value] implements most traits that are shared between the data structures, so users of this library can do work (e.g. [migration](Migrate)) without needing to know what type of object the value represents:
//!
//! ```
//! use stac::{Value, Migrate, Version};
//!
//! let value: Value = stac::read("examples/simple-item.json").unwrap();
//! let value = value.migrate(&Version::v1_1_0).unwrap();
//! ```
//!
//! # Input and output
//!
//! Synchronous reads from the filesystem are supported via [read]:
//!
//! ```
//! let value: stac::Item = stac::read("examples/simple-item.json").unwrap();
//! ```
//!
//! If the [reqwest](https://docs.rs/reqwest/latest/reqwest/) feature is enabled, synchronous reads from urls are also supported:
//!
//! ```
//! #[cfg(feature = "reqwest")]
//! {
//!     let url = "https://raw.githubusercontent.com/radiantearth/stac-spec/master/examples/simple-item.json";
//!     let item: stac::Item = stac::read(url).unwrap();
//! }
//! ```
//!
//! To write, use [write()]:
//!
//! ```no_run
//! use stac::Format;
//!
//! stac::write("an-id.json", stac::Item::new("an-id")).unwrap();
//! ```
//!
//! Enable the `object-store` feature to get and put objects from e.g. AWS s3 (with the `object-store-aws` feature) or from other backends (see [features](#features) for a complete listing):
//!
//! ```no_run
//! use stac::Item;
//!
//! #[cfg(feature = "object-store")]
//! {
//!     # tokio_test::block_on(async {
//!     stac::io::put_opts("s3://bucket/item.json", Item::new("an-id"), [("foo", "bar")]).await.unwrap();
//!     let item: Item = stac::io::get_opts("s3://bucket/item.json", [("foo", "bar")]).await.unwrap();
//!     # })
//! }
//! ```
//!
//! For more, see the documentation in the [io] module.
//!
//! # Features
//!
//! - `gdal`: read raster assets, see [gdal]
//! - `geo`: add some geo-enabled methods, see [geo]
//! - `geoarrow`: read and write [geoarrow](https://geoarrow.org/), see [geoarrow]
//! - `geoparquet`: read and write [geoparquet](https://geoparquet.org/), see [geoparquet]
//!     - `geoparquet-compression`: enable parquet compression
//! - `object-store`: get and put from object stores. Sub-features enable specific protocols:
//!     - `object-store-aws`
//!     - `object-store-azure`
//!     - `object-store-gcp`
//!     - `object-store-http`
//!     - `object-store-all` (enable them all)
//! - `reqwest`: get from `http` and `https` urls when using [read]

#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![deny(
    elided_lifetimes_in_paths,
    explicit_outlives_requirements,
    keyword_idents,
    macro_use_extern_crate,
    meta_variable_misuse,
    missing_abi,
    missing_debug_implementations,
    missing_docs,
    non_ascii_idents,
    noop_method_call,
    rust_2021_incompatible_closure_captures,
    rust_2021_incompatible_or_patterns,
    rust_2021_prefixes_incompatible_syntax,
    rust_2021_prelude_collisions,
    single_use_lifetimes,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unsafe_code,
    unsafe_op_in_unsafe_fn,
    unused_crate_dependencies,
    unused_extern_crates,
    unused_import_braces,
    unused_lifetimes,
    unused_qualifications,
    unused_results,
    warnings
)]

mod asset;
mod band;
mod bbox;
mod catalog;
mod collection;
mod data_type;
pub mod datetime;
mod error;
pub mod extensions;
mod fields;
mod format;
#[cfg(feature = "gdal")]
pub mod gdal;
#[cfg(feature = "geo")]
pub mod geo;
#[cfg(feature = "geoarrow")]
pub mod geoarrow;
pub mod geoparquet;
mod href;
pub mod io;
pub mod item;
mod item_asset;
mod item_collection;
mod json;
pub mod link;
mod migrate;
pub mod mime;
mod ndjson;
mod statistics;
mod value;
mod version;

pub use {
    asset::{Asset, Assets},
    band::Band,
    bbox::Bbox,
    catalog::{Catalog, CATALOG_TYPE},
    collection::{Collection, Extent, Provider, SpatialExtent, TemporalExtent, COLLECTION_TYPE},
    data_type::DataType,
    error::Error,
    extensions::{Extension, Extensions},
    fields::Fields,
    format::Format,
    geoparquet::{FromGeoparquet, IntoGeoparquet},
    href::Href,
    io::{read, write},
    item::{FlatItem, Item, Properties, ITEM_TYPE},
    item_asset::ItemAsset,
    item_collection::{ItemCollection, ITEM_COLLECTION_TYPE},
    json::{FromJson, ToJson},
    link::{Link, Links},
    migrate::Migrate,
    ndjson::{FromNdjson, ToNdjson},
    statistics::Statistics,
    value::Value,
    version::Version,
};

/// The default STAC version of this library.
pub const STAC_VERSION: Version = Version::v1_1_0;

/// Custom [Result](std::result::Result) type for this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// Enum for the four "types" of STAC values.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Type {
    /// An item.
    Item,

    /// A collection.
    Collection,

    /// A catalog.
    Catalog,

    /// An item collection.
    ///
    /// While not technically part of the STAC specification, it's used all over the place.
    ItemCollection,
}

impl Type {
    /// Returns this type as a str.
    ///
    /// # Examples
    ///
    /// ```
    /// use stac::Type;
    ///
    /// assert_eq!(Type::Item.as_str(), "Feature");
    /// ```
    pub fn as_str(&self) -> &'static str {
        match self {
            Type::Item => "Feature",
            Type::Catalog => "Catalog",
            Type::Collection => "Collection",
            Type::ItemCollection => "FeatureCollection",
        }
    }

    /// Returns the schema path for this type.
    ///
    /// # Examples
    ///
    /// ```
    /// use stac::{Type, Version};
    ///
    /// assert_eq!(Type::Item.spec_path(&Version::v1_0_0).unwrap(), "/v1.0.0/item-spec/json-schema/item.json");
    /// ```
    pub fn spec_path(&self, version: &Version) -> Option<String> {
        match self {
            Type::Item => Some(format!("/v{}/item-spec/json-schema/item.json", version)),
            Type::Catalog => Some(format!(
                "/v{}/catalog-spec/json-schema/catalog.json",
                version
            )),
            Type::Collection => Some(format!(
                "/v{}/collection-spec/json-schema/collection.json",
                version
            )),
            Type::ItemCollection => None,
        }
    }
}

impl std::str::FromStr for Type {
    type Err = Error;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "Feature" => Ok(Type::Item),
            "Catalog" => Ok(Type::Catalog),
            "Collection" => Ok(Type::Collection),
            "FeatureCollection" => Ok(Type::ItemCollection),
            _ => Err(Error::UnknownType(s.to_string())),
        }
    }
}

impl<T> PartialEq<T> for Type
where
    T: AsRef<str>,
{
    fn eq(&self, other: &T) -> bool {
        self.as_str() == other.as_ref()
    }
}

/// Utility function to deserialize the type field on an object.
///
/// Use this, via a wrapper function, for `#[serde(deserialize_with)]`.
///
/// # Examples
///
/// ```
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Foo {
///     #[serde(deserialize_with = "deserialize_type")]
///     r#type: String,     
/// }
///
/// fn deserialize_type<'de, D>(deserializer: D) -> Result<String, D::Error>
/// where
///     D: serde::de::Deserializer<'de>
/// {
///     stac::deserialize_type(deserializer, "Foo")
/// }
/// ```
pub fn deserialize_type<'de, D>(
    deserializer: D,
    expected: &str,
) -> std::result::Result<String, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    use serde::Deserialize;
    let r#type = String::deserialize(deserializer)?;
    if r#type != expected {
        Err(serde::de::Error::invalid_value(
            serde::de::Unexpected::Str(&r#type),
            &expected,
        ))
    } else {
        Ok(r#type)
    }
}

/// Utility function to serialize the type field on an object.
///
/// Use this, via a wrapper function, in `#[serde(serialize_with)]`.
///
/// # Examples
///
/// ```
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Foo {
///     #[serde(serialize_with = "serialize_type")]
///     r#type: String,     
/// }
///
/// fn serialize_type<S>(r#type: &String, serializer: S) -> Result<S::Ok, S::Error>
/// where
///     S: serde::ser::Serializer
/// {
///     stac::serialize_type(r#type, serializer, "Foo")
/// }
/// ```
pub fn serialize_type<S>(
    r#type: &String,
    serializer: S,
    expected: &str,
) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::ser::Serializer,
{
    use serde::Serialize;
    if r#type != expected {
        Err(serde::ser::Error::custom(format!(
            "type field must be '{}', got: '{}'",
            expected, r#type
        )))
    } else {
        r#type.serialize(serializer)
    }
}

#[cfg(test)]
mod tests {
    use rstest as _;
    use tokio as _;
    use tokio_test as _;

    macro_rules! roundtrip {
        ($function:ident, $filename:expr, $object:ident) => {
            #[test]
            fn $function() {
                use assert_json_diff::{assert_json_matches, CompareMode, Config, NumericMode};
                use chrono::{DateTime, Utc};
                use serde_json::Value;
                use std::{fs::File, io::BufReader};

                let file = File::open($filename).unwrap();
                let buf_reader = BufReader::new(file);
                let mut before: Value = serde_json::from_reader(buf_reader).unwrap();
                if let Some(object) = before.as_object_mut() {
                    if object
                        .get("stac_extensions")
                        .and_then(|value| value.as_array())
                        .map(|array| array.is_empty())
                        .unwrap_or_default()
                    {
                        let _ = object.remove("stac_extensions");
                    }
                    if let Some(properties) =
                        object.get_mut("properties").and_then(|v| v.as_object_mut())
                    {
                        if let Some(datetime) = properties.get("datetime") {
                            if !datetime.is_null() {
                                let datetime: DateTime<Utc> =
                                    serde_json::from_value(datetime.clone()).unwrap();
                                let _ = properties.insert(
                                    "datetime".to_string(),
                                    serde_json::to_value(datetime).unwrap(),
                                );
                            }
                        }
                    }
                    if let Some(intervals) = object
                        .get_mut("extent")
                        .and_then(|v| v.as_object_mut())
                        .and_then(|o| o.get_mut("temporal"))
                        .and_then(|v| v.as_object_mut())
                        .and_then(|o| o.get_mut("interval"))
                        .and_then(|v| v.as_array_mut())
                    {
                        for interval in intervals {
                            if let Some(interval) = interval.as_array_mut() {
                                for datetime in interval {
                                    if !datetime.is_null() {
                                        let dt: DateTime<Utc> =
                                            serde_json::from_value(datetime.clone()).unwrap();
                                        *datetime = serde_json::to_value(dt).unwrap();
                                    }
                                }
                            }
                        }
                    }
                }
                let object: $object = serde_json::from_value(before.clone()).unwrap();
                let after = serde_json::to_value(object).unwrap();
                assert_json_matches!(
                    before,
                    after,
                    Config::new(CompareMode::Strict).numeric_mode(NumericMode::AssumeFloat)
                );
            }
        };
    }
    pub(crate) use roundtrip;
}

// From https://github.com/rust-lang/cargo/issues/383#issuecomment-720873790,
// may they be forever blessed.
#[cfg(doctest)]
mod readme {
    macro_rules! external_doc_test {
        ($x:expr) => {
            #[doc = $x]
            extern "C" {}
        };
    }

    external_doc_test!(include_str!("../README.md"));
}

/// We only use gdal-sys for the build script.
#[cfg(feature = "gdal")]
use gdal_sys as _;