Skip to main content

sidereon_core/
data.rs

1//! Data product filename, cache path, and archive URL catalog.
2//!
3//! This module is sans-IO: it performs no network access, reads no files, and
4//! writes no cache entries. It only turns cataloged product inputs into
5//! canonical archive filenames, URLs, cache relative paths, and deterministic
6//! converted bytes for pure terrain ingestion.
7
8use core::fmt;
9use core::str::FromStr;
10use std::collections::{HashMap, HashSet};
11
12use crate::astro::time::civil::{civil_from_julian_day_number, day_of_year_int, days_in_month};
13use crate::astro::time::gnss::{week_epoch_julian_day_number, week_from_calendar};
14use crate::astro::time::model::TimeScale;
15use crate::astro::time::scales::julian_day_number;
16use crate::terrain;
17
18/// Analysis-center code supported by the data-product catalog.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum AnalysisCenter {
21    /// `igs`.
22    Igs,
23    /// `cod_rap`.
24    CodRap,
25    /// `cod_prd1`.
26    CodPrd1,
27    /// `cod_prd2`.
28    CodPrd2,
29    /// `esa`.
30    Esa,
31    /// `cod`.
32    Cod,
33    /// `gfz`.
34    Gfz,
35    /// `igs_ult`.
36    IgsUlt,
37    /// `cod_ult`.
38    CodUlt,
39    /// `esa_ult`.
40    EsaUlt,
41    /// `gfz_ult`.
42    GfzUlt,
43}
44
45impl AnalysisCenter {
46    /// The lower-case catalog code.
47    #[must_use]
48    pub const fn code(self) -> &'static str {
49        match self {
50            Self::Igs => "igs",
51            Self::CodRap => "cod_rap",
52            Self::CodPrd1 => "cod_prd1",
53            Self::CodPrd2 => "cod_prd2",
54            Self::Esa => "esa",
55            Self::Cod => "cod",
56            Self::Gfz => "gfz",
57            Self::IgsUlt => "igs_ult",
58            Self::CodUlt => "cod_ult",
59            Self::EsaUlt => "esa_ult",
60            Self::GfzUlt => "gfz_ult",
61        }
62    }
63
64    /// Parse a lower-case catalog code.
65    #[must_use]
66    pub fn from_code(code: &str) -> Option<Self> {
67        match code {
68            "igs" => Some(Self::Igs),
69            "cod_rap" => Some(Self::CodRap),
70            "cod_prd1" => Some(Self::CodPrd1),
71            "cod_prd2" => Some(Self::CodPrd2),
72            "esa" => Some(Self::Esa),
73            "cod" => Some(Self::Cod),
74            "gfz" => Some(Self::Gfz),
75            "igs_ult" => Some(Self::IgsUlt),
76            "cod_ult" => Some(Self::CodUlt),
77            "esa_ult" => Some(Self::EsaUlt),
78            "gfz_ult" => Some(Self::GfzUlt),
79            _ => None,
80        }
81    }
82
83    /// Public publisher represented by this catalog product line.
84    #[must_use]
85    pub const fn publisher(self) -> ProductPublisher {
86        match self {
87            Self::Igs | Self::IgsUlt => ProductPublisher::Igs,
88            Self::CodRap | Self::CodPrd1 | Self::CodPrd2 | Self::Cod | Self::CodUlt => {
89                ProductPublisher::Code
90            }
91            Self::Esa | Self::EsaUlt => ProductPublisher::Esa,
92            Self::Gfz | Self::GfzUlt => ProductPublisher::Gfz,
93        }
94    }
95
96    /// Public solution class represented by this catalog product line.
97    #[must_use]
98    pub const fn solution_class(self) -> SolutionClass {
99        match self {
100            Self::Igs => SolutionClass::Broadcast,
101            Self::CodRap | Self::Gfz => SolutionClass::Rapid,
102            Self::CodPrd1 | Self::CodPrd2 => SolutionClass::Predicted,
103            Self::Esa | Self::Cod => SolutionClass::Final,
104            Self::IgsUlt | Self::CodUlt | Self::EsaUlt | Self::GfzUlt => SolutionClass::UltraRapid,
105        }
106    }
107
108    /// Prediction horizon associated with a predicted product alias.
109    #[must_use]
110    pub const fn prediction_horizon_days(self) -> Option<u8> {
111        match self {
112            Self::CodPrd1 => Some(1),
113            Self::CodPrd2 => Some(2),
114            _ => None,
115        }
116    }
117}
118
119impl fmt::Display for AnalysisCenter {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(self.code())
122    }
123}
124
125impl FromStr for AnalysisCenter {
126    type Err = DataCatalogError;
127
128    fn from_str(s: &str) -> Result<Self, Self::Err> {
129        Self::from_code(s).ok_or_else(|| DataCatalogError::UnknownCenter(s.to_string()))
130    }
131}
132
133/// Product type supported by the data-product catalog.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
135pub enum ProductType {
136    /// Precise orbit SP3.
137    Sp3,
138    /// RINEX clock.
139    Clk,
140    /// Merged broadcast navigation.
141    Nav,
142    /// IONEX global ionosphere map.
143    Ionex,
144}
145
146impl ProductType {
147    /// The lower-case product code.
148    #[must_use]
149    pub const fn code(self) -> &'static str {
150        match self {
151            Self::Sp3 => "sp3",
152            Self::Clk => "clk",
153            Self::Nav => "nav",
154            Self::Ionex => "ionex",
155        }
156    }
157
158    /// Parse a lower-case product code.
159    #[must_use]
160    pub fn from_code(code: &str) -> Option<Self> {
161        match code {
162            "sp3" => Some(Self::Sp3),
163            "clk" => Some(Self::Clk),
164            "nav" => Some(Self::Nav),
165            "ionex" => Some(Self::Ionex),
166            _ => None,
167        }
168    }
169}
170
171impl fmt::Display for ProductType {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.write_str(self.code())
174    }
175}
176
177impl FromStr for ProductType {
178    type Err = DataCatalogError;
179
180    fn from_str(s: &str) -> Result<Self, Self::Err> {
181        Self::from_code(s).ok_or_else(|| DataCatalogError::UnknownProductType(s.to_string()))
182    }
183}
184
185/// Public organization that produced or combined a GNSS product.
186///
187/// This is intentionally separate from [`AnalysisCenter`]. Catalog center
188/// codes such as `cod`, `cod_rap`, and `cod_ult` select different product
189/// lines, but all three have the same publisher.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
191pub enum ProductPublisher {
192    /// International GNSS Service combination product.
193    Igs,
194    /// Center for Orbit Determination in Europe (CODE).
195    Code,
196    /// European Space Agency.
197    Esa,
198    /// GFZ German Research Centre for Geosciences.
199    Gfz,
200}
201
202impl ProductPublisher {
203    /// IGS long-filename publisher token.
204    #[must_use]
205    pub const fn code(self) -> &'static str {
206        match self {
207            Self::Igs => "IGS",
208            Self::Code => "COD",
209            Self::Esa => "ESA",
210            Self::Gfz => "GFZ",
211        }
212    }
213}
214
215impl fmt::Display for ProductPublisher {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        f.write_str(self.code())
218    }
219}
220
221/// Public solution class encoded in a GNSS product name.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
223pub enum SolutionClass {
224    /// Final product.
225    Final,
226    /// Rapid product.
227    Rapid,
228    /// Ultra-rapid product, which may contain observed and predicted segments.
229    UltraRapid,
230    /// Predicted product.
231    Predicted,
232    /// Broadcast navigation product.
233    Broadcast,
234}
235
236impl SolutionClass {
237    /// Stable public code used in Sidereon provenance and cache paths.
238    #[must_use]
239    pub const fn code(self) -> &'static str {
240        match self {
241            Self::Final => "final",
242            Self::Rapid => "rapid",
243            Self::UltraRapid => "ultra_rapid",
244            Self::Predicted => "predicted",
245            Self::Broadcast => "broadcast",
246        }
247    }
248
249    /// IGS long-filename solution token where one exists.
250    #[must_use]
251    pub const fn filename_token(self) -> Option<&'static str> {
252        match self {
253            Self::Final => Some("FIN"),
254            Self::Rapid => Some("RAP"),
255            Self::UltraRapid => Some("ULT"),
256            Self::Predicted => Some("PRD"),
257            Self::Broadcast => None,
258        }
259    }
260}
261
262impl fmt::Display for SolutionClass {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        f.write_str(self.code())
265    }
266}
267
268/// Public campaign or project encoded in a GNSS product name.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
270pub enum ProductCampaign {
271    /// Operational IGS product line.
272    Operational,
273    /// Multi-GNSS product line (`MGN`).
274    MultiGnss,
275    /// Multi-GNSS Experiment product line (`MGX`).
276    MultiGnssExperiment,
277    /// Broadcast navigation archive product.
278    Broadcast,
279}
280
281impl ProductCampaign {
282    /// Stable public code.
283    #[must_use]
284    pub const fn code(self) -> &'static str {
285        match self {
286            Self::Operational => "OPS",
287            Self::MultiGnss => "MGN",
288            Self::MultiGnssExperiment => "MGX",
289            Self::Broadcast => "BRD",
290        }
291    }
292}
293
294/// Public serialization format carried by a catalog product.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
296pub enum ProductFormat {
297    /// Standard Product 3 orbit format.
298    Sp3,
299    /// IONosphere map EXchange format.
300    Ionex,
301    /// RINEX clock format.
302    RinexClock,
303    /// RINEX navigation format.
304    RinexNavigation,
305}
306
307impl ProductFormat {
308    /// Stable public format code.
309    #[must_use]
310    pub const fn code(self) -> &'static str {
311        match self {
312            Self::Sp3 => "SP3",
313            Self::Ionex => "IONEX",
314            Self::RinexClock => "RINEX_CLK",
315            Self::RinexNavigation => "RINEX_NAV",
316        }
317    }
318}
319
320/// Explicit distributor used to obtain an exact public product.
321///
322/// Distributor selection never changes product publisher, solution class,
323/// issue, cadence, date, or family.
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
325pub enum DistributionSource {
326    /// The cataloged analysis-center or IGS direct archive.
327    Direct,
328    /// NASA CDDIS over HTTPS, optionally authenticated with Earthdata Login.
329    NasaCddis,
330    /// Bytes read from a caller-provided local file.
331    LocalFile,
332    /// Bytes supplied directly by the caller.
333    InMemory,
334}
335
336impl DistributionSource {
337    /// Stable public code used in provenance and cache paths.
338    #[must_use]
339    pub const fn code(self) -> &'static str {
340        match self {
341            Self::Direct => "direct",
342            Self::NasaCddis => "nasa_cddis",
343            Self::LocalFile => "local_file",
344            Self::InMemory => "in_memory",
345        }
346    }
347}
348
349/// CelesTrak space-weather product served by the data catalog.
350#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
351pub enum SpaceWeatherProduct {
352    /// `SW-All.csv`: full history plus daily and monthly predictions.
353    All,
354    /// `SW-Last5Years.csv`: observed rolling window.
355    Last5Years,
356}
357
358impl SpaceWeatherProduct {
359    /// The lower-case catalog code.
360    #[must_use]
361    pub const fn code(self) -> &'static str {
362        match self {
363            Self::All => "sw_all",
364            Self::Last5Years => "sw_last5",
365        }
366    }
367
368    /// Parse a lower-case catalog code.
369    #[must_use]
370    pub fn from_code(code: &str) -> Option<Self> {
371        match code {
372            "sw_all" => Some(Self::All),
373            "sw_last5" => Some(Self::Last5Years),
374            _ => None,
375        }
376    }
377}
378
379impl fmt::Display for SpaceWeatherProduct {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.write_str(self.code())
382    }
383}
384
385impl FromStr for SpaceWeatherProduct {
386    type Err = DataCatalogError;
387
388    fn from_str(s: &str) -> Result<Self, Self::Err> {
389        Self::from_code(s).ok_or_else(|| DataCatalogError::UnknownProductType(s.to_string()))
390    }
391}
392
393/// Archive transport protocol recorded by the catalog.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
395pub enum ArchiveProtocol {
396    /// HTTP.
397    Http,
398    /// HTTPS.
399    Https,
400}
401
402impl ArchiveProtocol {
403    /// URI scheme text.
404    #[must_use]
405    pub const fn as_str(self) -> &'static str {
406        match self {
407            Self::Http => "http",
408            Self::Https => "https",
409        }
410    }
411}
412
413/// Archive compression for a cataloged product.
414#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
415pub enum ArchiveCompression {
416    /// Archive URL has a `.gz` suffix.
417    Gzip,
418    /// Archive URL is the plain product filename.
419    None,
420}
421
422impl ArchiveCompression {
423    /// Catalog text for the compression format.
424    #[must_use]
425    pub const fn as_str(self) -> &'static str {
426        match self {
427            Self::Gzip => "gzip",
428            Self::None => "none",
429        }
430    }
431
432    const fn suffix(self) -> &'static str {
433        match self {
434            Self::Gzip => ".gz",
435            Self::None => "",
436        }
437    }
438}
439
440/// Directory layout used below an archive root.
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
442pub enum ArchiveLayout {
443    /// `rapid/w<gps-week>`.
444    GfzRapidWeek,
445    /// `ultra/w<gps-week>`.
446    GfzUltraWeek,
447    /// `<gps-week>`.
448    GpsWeek,
449    /// `products/<gps-week>`.
450    BkgProductsWeek,
451    /// `BRDC/<year>/<day-of-year>`.
452    BkgBrdcYearDoy,
453    /// `obs/<year>/<day-of-year>`.
454    BkgObsYearDoy,
455    /// `CODE_MGEX/CODE/<year>`.
456    AiubCodeMgexYear,
457    /// `CODE/<year>`.
458    AiubCodeYear,
459    /// `CODE`.
460    AiubCodeRoot,
461}
462
463/// Product filename convention.
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum ProductFilenameKind {
466    /// `TOKEN_DATE_LEN_SAMPLE_CODE.EXT`.
467    Sampled,
468    /// `TOKEN_R_DATE_LEN_CODE.ext`.
469    Nav,
470}
471
472/// Product-type filename convention.
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474pub struct ProductTypeConvention {
475    /// Product type.
476    pub product_type: ProductType,
477    /// Filename content code, for example `ORB`.
478    pub content_code: &'static str,
479    /// Filename extension, preserving archive case.
480    pub extension: &'static str,
481    /// Filename convention.
482    pub kind: ProductFilenameKind,
483}
484
485/// Per-center convention for one product type.
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub struct CenterProductConvention {
488    /// Product type.
489    pub product_type: ProductType,
490    /// IGS long-name token prefix.
491    pub token: &'static str,
492    /// Directory layout under the archive root.
493    pub layout: ArchiveLayout,
494    /// Product span token.
495    pub span: &'static str,
496    /// Default sampling token.
497    pub default_sample: &'static str,
498    /// Archive compression.
499    pub compression: ArchiveCompression,
500}
501
502/// Static catalog entry for one analysis-center code.
503#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504pub struct CenterCatalogEntry {
505    /// Analysis-center code.
506    pub center: AnalysisCenter,
507    /// Lower-case catalog code.
508    pub code: &'static str,
509    /// Archive URI scheme.
510    pub protocol: ArchiveProtocol,
511    /// Archive host.
512    pub host: &'static str,
513    /// Archive root URL without trailing slash.
514    pub root_url: &'static str,
515    /// Product conventions served by this center.
516    pub products: &'static [CenterProductConvention],
517    /// Valid issue times for sub-daily products.
518    pub issues: &'static [&'static str],
519}
520
521/// Static catalog entry for one terrain source.
522#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523pub struct TerrainSourceEntry {
524    /// Archive URI scheme.
525    pub protocol: ArchiveProtocol,
526    /// Archive host.
527    pub host: &'static str,
528    /// Archive compression.
529    pub compression: ArchiveCompression,
530    /// Archive root URL without trailing slash.
531    pub root_url: &'static str,
532}
533
534/// Static catalog entry for the CelesTrak space-weather source.
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub struct SpaceWeatherSourceEntry {
537    /// Archive URI scheme.
538    pub protocol: ArchiveProtocol,
539    /// Archive host.
540    pub host: &'static str,
541    /// Archive compression.
542    pub compression: ArchiveCompression,
543    /// Archive root URL without trailing slash.
544    pub root_url: &'static str,
545}
546
547/// Product pair that is intentionally not offered because no open mirror exists.
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
549pub struct NoOpenMirrorProduct {
550    /// Analysis-center code.
551    pub center: &'static str,
552    /// Product type code.
553    pub product_type: &'static str,
554}
555
556const PRODUCT_TYPE_CONVENTIONS: [ProductTypeConvention; 4] = [
557    ProductTypeConvention {
558        product_type: ProductType::Sp3,
559        content_code: "ORB",
560        extension: "SP3",
561        kind: ProductFilenameKind::Sampled,
562    },
563    ProductTypeConvention {
564        product_type: ProductType::Clk,
565        content_code: "CLK",
566        extension: "CLK",
567        kind: ProductFilenameKind::Sampled,
568    },
569    ProductTypeConvention {
570        product_type: ProductType::Nav,
571        content_code: "MN",
572        extension: "rnx",
573        kind: ProductFilenameKind::Nav,
574    },
575    ProductTypeConvention {
576        product_type: ProductType::Ionex,
577        content_code: "GIM",
578        extension: "INX",
579        kind: ProductFilenameKind::Sampled,
580    },
581];
582
583const COD_RAP_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
584    product_type: ProductType::Ionex,
585    token: "COD0OPSRAP",
586    layout: ArchiveLayout::AiubCodeRoot,
587    span: "01D",
588    default_sample: "01H",
589    compression: ArchiveCompression::Gzip,
590}];
591
592const COD_PRD_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
593    product_type: ProductType::Ionex,
594    token: "COD0OPSPRD",
595    layout: ArchiveLayout::AiubCodeRoot,
596    span: "01D",
597    default_sample: "01H",
598    compression: ArchiveCompression::Gzip,
599}];
600
601const ESA_PRODUCTS: [CenterProductConvention; 3] = [
602    CenterProductConvention {
603        product_type: ProductType::Sp3,
604        token: "ESA0MGNFIN",
605        layout: ArchiveLayout::GpsWeek,
606        span: "01D",
607        default_sample: "05M",
608        compression: ArchiveCompression::Gzip,
609    },
610    CenterProductConvention {
611        product_type: ProductType::Clk,
612        token: "ESA0MGNFIN",
613        layout: ArchiveLayout::GpsWeek,
614        span: "01D",
615        default_sample: "30S",
616        compression: ArchiveCompression::Gzip,
617    },
618    CenterProductConvention {
619        product_type: ProductType::Ionex,
620        token: "ESA0OPSFIN",
621        layout: ArchiveLayout::GpsWeek,
622        span: "01D",
623        default_sample: "02H",
624        compression: ArchiveCompression::Gzip,
625    },
626];
627
628const COD_PRODUCTS: [CenterProductConvention; 3] = [
629    CenterProductConvention {
630        product_type: ProductType::Sp3,
631        token: "COD0MGXFIN",
632        layout: ArchiveLayout::AiubCodeMgexYear,
633        span: "01D",
634        default_sample: "05M",
635        compression: ArchiveCompression::Gzip,
636    },
637    CenterProductConvention {
638        product_type: ProductType::Clk,
639        token: "COD0MGXFIN",
640        layout: ArchiveLayout::AiubCodeMgexYear,
641        span: "01D",
642        default_sample: "30S",
643        compression: ArchiveCompression::Gzip,
644    },
645    CenterProductConvention {
646        product_type: ProductType::Ionex,
647        token: "COD0OPSFIN",
648        layout: ArchiveLayout::AiubCodeYear,
649        span: "01D",
650        default_sample: "01H",
651        compression: ArchiveCompression::Gzip,
652    },
653];
654
655const GFZ_PRODUCTS: [CenterProductConvention; 2] = [
656    CenterProductConvention {
657        product_type: ProductType::Sp3,
658        token: "GFZ0OPSRAP",
659        layout: ArchiveLayout::GfzRapidWeek,
660        span: "01D",
661        default_sample: "15M",
662        compression: ArchiveCompression::Gzip,
663    },
664    CenterProductConvention {
665        product_type: ProductType::Clk,
666        token: "GFZ0OPSRAP",
667        layout: ArchiveLayout::GfzRapidWeek,
668        span: "01D",
669        default_sample: "30S",
670        compression: ArchiveCompression::Gzip,
671    },
672];
673
674const IGS_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
675    product_type: ProductType::Nav,
676    token: "BRDC00WRD",
677    layout: ArchiveLayout::BkgBrdcYearDoy,
678    span: "01D",
679    default_sample: "01D",
680    compression: ArchiveCompression::Gzip,
681}];
682
683const IGS_ULT_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
684    product_type: ProductType::Sp3,
685    token: "IGS0OPSULT",
686    layout: ArchiveLayout::BkgProductsWeek,
687    span: "02D",
688    default_sample: "15M",
689    compression: ArchiveCompression::Gzip,
690}];
691
692const COD_ULT_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
693    product_type: ProductType::Sp3,
694    token: "COD0OPSULT",
695    layout: ArchiveLayout::AiubCodeRoot,
696    span: "01D",
697    default_sample: "05M",
698    compression: ArchiveCompression::None,
699}];
700
701const ESA_ULT_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
702    product_type: ProductType::Sp3,
703    token: "ESA0OPSULT",
704    layout: ArchiveLayout::GpsWeek,
705    span: "02D",
706    default_sample: "05M",
707    compression: ArchiveCompression::Gzip,
708}];
709
710const GFZ_ULT_PRODUCTS: [CenterProductConvention; 1] = [CenterProductConvention {
711    product_type: ProductType::Sp3,
712    token: "GFZ0OPSULT",
713    layout: ArchiveLayout::GfzUltraWeek,
714    span: "02D",
715    default_sample: "05M",
716    compression: ArchiveCompression::Gzip,
717}];
718
719const OPSULT_ISSUES: [&str; 4] = ["0000", "0600", "1200", "1800"];
720const COD_ULT_ISSUES: [&str; 1] = ["0000"];
721const GFZ_ULT_ISSUES: [&str; 8] = [
722    "0000", "0300", "0600", "0900", "1200", "1500", "1800", "2100",
723];
724
725const CENTER_ORDER: [AnalysisCenter; 11] = [
726    AnalysisCenter::CodRap,
727    AnalysisCenter::CodPrd1,
728    AnalysisCenter::CodPrd2,
729    AnalysisCenter::Igs,
730    AnalysisCenter::Esa,
731    AnalysisCenter::Cod,
732    AnalysisCenter::Gfz,
733    AnalysisCenter::IgsUlt,
734    AnalysisCenter::CodUlt,
735    AnalysisCenter::EsaUlt,
736    AnalysisCenter::GfzUlt,
737];
738
739const CATALOG: [CenterCatalogEntry; 11] = [
740    CenterCatalogEntry {
741        center: AnalysisCenter::CodRap,
742        code: "cod_rap",
743        protocol: ArchiveProtocol::Http,
744        host: "ftp.aiub.unibe.ch",
745        root_url: "http://ftp.aiub.unibe.ch",
746        products: &COD_RAP_PRODUCTS,
747        issues: &[],
748    },
749    CenterCatalogEntry {
750        center: AnalysisCenter::CodPrd1,
751        code: "cod_prd1",
752        protocol: ArchiveProtocol::Https,
753        host: "www.aiub.unibe.ch",
754        root_url: "https://www.aiub.unibe.ch/download",
755        products: &COD_PRD_PRODUCTS,
756        issues: &[],
757    },
758    CenterCatalogEntry {
759        center: AnalysisCenter::CodPrd2,
760        code: "cod_prd2",
761        protocol: ArchiveProtocol::Https,
762        host: "www.aiub.unibe.ch",
763        root_url: "https://www.aiub.unibe.ch/download",
764        products: &COD_PRD_PRODUCTS,
765        issues: &[],
766    },
767    CenterCatalogEntry {
768        center: AnalysisCenter::Igs,
769        code: "igs",
770        protocol: ArchiveProtocol::Https,
771        host: "igs.bkg.bund.de",
772        root_url: "https://igs.bkg.bund.de/root_ftp/IGS",
773        products: &IGS_PRODUCTS,
774        issues: &[],
775    },
776    CenterCatalogEntry {
777        center: AnalysisCenter::Esa,
778        code: "esa",
779        protocol: ArchiveProtocol::Https,
780        host: "navigation-office.esa.int",
781        root_url: "https://navigation-office.esa.int/products/gnss-products",
782        products: &ESA_PRODUCTS,
783        issues: &[],
784    },
785    CenterCatalogEntry {
786        center: AnalysisCenter::Cod,
787        code: "cod",
788        protocol: ArchiveProtocol::Http,
789        host: "ftp.aiub.unibe.ch",
790        root_url: "http://ftp.aiub.unibe.ch",
791        products: &COD_PRODUCTS,
792        issues: &[],
793    },
794    CenterCatalogEntry {
795        center: AnalysisCenter::Gfz,
796        code: "gfz",
797        protocol: ArchiveProtocol::Https,
798        host: "isdc-data.gfz.de",
799        root_url: "https://isdc-data.gfz.de/gnss/products",
800        products: &GFZ_PRODUCTS,
801        issues: &[],
802    },
803    CenterCatalogEntry {
804        center: AnalysisCenter::IgsUlt,
805        code: "igs_ult",
806        protocol: ArchiveProtocol::Https,
807        host: "igs.bkg.bund.de",
808        root_url: "https://igs.bkg.bund.de/root_ftp/IGS",
809        products: &IGS_ULT_PRODUCTS,
810        issues: &OPSULT_ISSUES,
811    },
812    CenterCatalogEntry {
813        center: AnalysisCenter::CodUlt,
814        code: "cod_ult",
815        protocol: ArchiveProtocol::Https,
816        host: "www.aiub.unibe.ch",
817        // AIUB retired the old ftp.aiub.unibe.ch HTTP tree. Its public file
818        // browser links products through this stable HTTPS download surface,
819        // which redirects to the current object store.
820        root_url: "https://www.aiub.unibe.ch/download",
821        products: &COD_ULT_PRODUCTS,
822        issues: &COD_ULT_ISSUES,
823    },
824    CenterCatalogEntry {
825        center: AnalysisCenter::EsaUlt,
826        code: "esa_ult",
827        protocol: ArchiveProtocol::Https,
828        host: "navigation-office.esa.int",
829        root_url: "https://navigation-office.esa.int/products/gnss-products",
830        products: &ESA_ULT_PRODUCTS,
831        issues: &OPSULT_ISSUES,
832    },
833    CenterCatalogEntry {
834        center: AnalysisCenter::GfzUlt,
835        code: "gfz_ult",
836        protocol: ArchiveProtocol::Https,
837        host: "isdc-data.gfz.de",
838        root_url: "https://isdc-data.gfz.de/gnss/products",
839        products: &GFZ_ULT_PRODUCTS,
840        issues: &GFZ_ULT_ISSUES,
841    },
842];
843
844const SKADI_SOURCE: TerrainSourceEntry = TerrainSourceEntry {
845    protocol: ArchiveProtocol::Https,
846    host: "s3.amazonaws.com",
847    compression: ArchiveCompression::Gzip,
848    root_url: "https://s3.amazonaws.com/elevation-tiles-prod",
849};
850
851const CELESTRAK_SPACE_WEATHER_SOURCE: SpaceWeatherSourceEntry = SpaceWeatherSourceEntry {
852    protocol: ArchiveProtocol::Https,
853    host: "celestrak.org",
854    compression: ArchiveCompression::None,
855    root_url: "https://celestrak.org/SpaceData",
856};
857
858const ALLOWED_HOSTS: [&str; 11] = [
859    "ftp.aiub.unibe.ch",
860    "www.aiub.unibe.ch",
861    "download.aiub.unibe.ch",
862    "zhw-b.s3.cloud.switch.ch",
863    "navigation-office.esa.int",
864    "isdc-data.gfz.de",
865    "igs.bkg.bund.de",
866    "s3.amazonaws.com",
867    "celestrak.org",
868    "cddis.nasa.gov",
869    "urs.earthdata.nasa.gov",
870];
871
872const NO_OPEN_MIRRORS: [NoOpenMirrorProduct; 7] = [
873    NoOpenMirrorProduct {
874        center: "grg",
875        product_type: "sp3",
876    },
877    NoOpenMirrorProduct {
878        center: "grg",
879        product_type: "clk",
880    },
881    NoOpenMirrorProduct {
882        center: "wum",
883        product_type: "sp3",
884    },
885    NoOpenMirrorProduct {
886        center: "wum",
887        product_type: "clk",
888    },
889    NoOpenMirrorProduct {
890        center: "grg_ult",
891        product_type: "sp3",
892    },
893    NoOpenMirrorProduct {
894        center: "grg_ult",
895        product_type: "clk",
896    },
897    NoOpenMirrorProduct {
898        center: "igs",
899        product_type: "ionex",
900    },
901];
902
903/// Error returned by the pure data-product catalog.
904#[derive(Debug, Clone, PartialEq, Eq)]
905pub enum DataCatalogError {
906    /// Unknown analysis-center code.
907    UnknownCenter(String),
908    /// Unknown product type code.
909    UnknownProductType(String),
910    /// The center does not serve the requested product type.
911    UnsupportedProduct {
912        /// Analysis center.
913        center: AnalysisCenter,
914        /// Product type.
915        product_type: ProductType,
916    },
917    /// A distributor does not carry the requested product family.
918    UnsupportedDistribution {
919        /// Explicit distributor.
920        source: DistributionSource,
921        /// Requested product family.
922        product_type: ProductType,
923    },
924    /// An exact request did not include any acceptable distributor.
925    NoDistributionSources,
926    /// A caller-constructed identity contained an unsafe official filename.
927    InvalidOfficialFilename(String),
928    /// A caller-constructed identity disagrees with its official filename.
929    InconsistentProductIdentity {
930        /// Identity field that did not agree with the filename or catalog convention.
931        field: &'static str,
932    },
933    /// The product has no verified anonymous HTTP(S) mirror.
934    NoOpenMirror {
935        /// Analysis-center code.
936        center: String,
937        /// Product type code.
938        product_type: String,
939    },
940    /// Bad civil date.
941    InvalidDate {
942        /// Year.
943        year: i32,
944        /// Month.
945        month: u8,
946        /// Day.
947        day: u8,
948    },
949    /// Date cannot be represented by this API.
950    DateOutOfRange,
951    /// Date precedes the GPS week epoch.
952    DateBeforeGpsEpoch(ProductDate),
953    /// GPS day-of-week must be `0..=6`.
954    InvalidGpsDayOfWeek(u8),
955    /// Sampling token is not `NNX` with an upper-case unit.
956    InvalidSample(String),
957    /// Issue time is malformed.
958    InvalidIssue(String),
959    /// The center requires an issue time.
960    MissingIssue {
961        /// Analysis center.
962        center: AnalysisCenter,
963    },
964    /// The center does not use issue times.
965    UnexpectedIssue {
966        /// Analysis center.
967        center: AnalysisCenter,
968    },
969    /// Issue time is valid text but not published by this center.
970    UnsupportedIssue {
971        /// Analysis center.
972        center: AnalysisCenter,
973        /// Issue time.
974        issue: String,
975    },
976    /// The target datetime was invalid.
977    InvalidDateTime {
978        /// Hour.
979        hour: u8,
980        /// Minute.
981        minute: u8,
982        /// Second.
983        second: u8,
984    },
985    /// No ultra-rapid issue exists at or before the requested target.
986    NoUltraIssue,
987    /// No available ultra-rapid issue exists at or before the requested target.
988    NoAvailableUltraIssue,
989    /// Station identifier is not a 9-character upper-case alphanumeric token.
990    InvalidStation(String),
991    /// Terrain lookup coordinate is non-finite or outside the reader range.
992    InvalidCoordinate {
993        /// Latitude as `f64::to_bits()`.
994        lat_deg_bits: u64,
995        /// Longitude as `f64::to_bits()`.
996        lon_deg_bits: u64,
997    },
998    /// Terrain tile index is outside the valid one-degree cell range.
999    InvalidTileIndex {
1000        /// Latitude index.
1001        lat_index: i32,
1002        /// Longitude index.
1003        lon_index: i32,
1004    },
1005    /// Skadi tile identifier is malformed.
1006    InvalidTileId(String),
1007}
1008
1009impl fmt::Display for DataCatalogError {
1010    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011        match self {
1012            Self::UnknownCenter(center) => write!(f, "unknown analysis center {center:?}"),
1013            Self::UnknownProductType(product_type) => {
1014                write!(f, "unknown product type {product_type:?}")
1015            }
1016            Self::UnsupportedProduct {
1017                center,
1018                product_type,
1019            } => write!(f, "{center} does not serve {product_type}"),
1020            Self::UnsupportedDistribution {
1021                source,
1022                product_type,
1023            } => write!(
1024                f,
1025                "distributor {} does not serve {product_type}",
1026                source.code()
1027            ),
1028            Self::NoDistributionSources => {
1029                write!(f, "exact product request has no distributors")
1030            }
1031            Self::InvalidOfficialFilename(filename) => {
1032                write!(f, "invalid official product filename {filename:?}")
1033            }
1034            Self::InconsistentProductIdentity { field } => {
1035                write!(
1036                    f,
1037                    "product identity field {field:?} disagrees with its official filename"
1038                )
1039            }
1040            Self::NoOpenMirror {
1041                center,
1042                product_type,
1043            } => write!(f, "{center}/{product_type} has no open mirror"),
1044            Self::InvalidDate { year, month, day } => {
1045                write!(f, "invalid product date {year:04}-{month:02}-{day:02}")
1046            }
1047            Self::DateOutOfRange => write!(f, "product date is out of range"),
1048            Self::DateBeforeGpsEpoch(date) => {
1049                write!(f, "product date {date} is before the GPS week epoch")
1050            }
1051            Self::InvalidGpsDayOfWeek(day) => {
1052                write!(f, "invalid GPS day-of-week {day}")
1053            }
1054            Self::InvalidSample(sample) => write!(f, "invalid sample code {sample:?}"),
1055            Self::InvalidIssue(issue) => write!(f, "invalid issue time {issue:?}"),
1056            Self::MissingIssue { center } => write!(f, "{center} requires an issue time"),
1057            Self::UnexpectedIssue { center } => write!(f, "{center} does not take an issue time"),
1058            Self::UnsupportedIssue { center, issue } => {
1059                write!(f, "{center} does not publish issue {issue:?}")
1060            }
1061            Self::InvalidDateTime {
1062                hour,
1063                minute,
1064                second,
1065            } => write!(f, "invalid product time {hour:02}:{minute:02}:{second:02}"),
1066            Self::NoUltraIssue => write!(f, "no ultra-rapid issue at or before target"),
1067            Self::NoAvailableUltraIssue => {
1068                write!(f, "no available ultra-rapid issue at or before target")
1069            }
1070            Self::InvalidStation(station) => write!(f, "invalid station code {station:?}"),
1071            Self::InvalidCoordinate {
1072                lat_deg_bits,
1073                lon_deg_bits,
1074            } => write!(
1075                f,
1076                "invalid terrain coordinate lat={} lon={}",
1077                f64::from_bits(*lat_deg_bits),
1078                f64::from_bits(*lon_deg_bits)
1079            ),
1080            Self::InvalidTileIndex {
1081                lat_index,
1082                lon_index,
1083            } => write!(
1084                f,
1085                "invalid terrain tile index lat={lat_index} lon={lon_index}"
1086            ),
1087            Self::InvalidTileId(id) => write!(f, "invalid skadi tile id {id:?}"),
1088        }
1089    }
1090}
1091
1092impl std::error::Error for DataCatalogError {}
1093
1094/// Error returned by SRTM HGT to DTED conversion.
1095#[derive(Debug, Clone, PartialEq, Eq)]
1096pub enum HgtConversionError {
1097    /// The decompressed HGT payload is not the SRTM1 byte length.
1098    BadLength {
1099        /// Expected byte length.
1100        expected: usize,
1101        /// Actual byte length.
1102        got: usize,
1103    },
1104    /// Terrain tile index is outside the valid one-degree cell range.
1105    InvalidTileIndex {
1106        /// Latitude index.
1107        lat_index: i32,
1108        /// Longitude index.
1109        lon_index: i32,
1110    },
1111}
1112
1113impl fmt::Display for HgtConversionError {
1114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1115        match self {
1116            Self::BadLength { expected, got } => {
1117                write!(
1118                    f,
1119                    "invalid SRTM1 HGT length: expected {expected}, got {got}"
1120                )
1121            }
1122            Self::InvalidTileIndex {
1123                lat_index,
1124                lon_index,
1125            } => write!(
1126                f,
1127                "invalid terrain tile index lat={lat_index} lon={lon_index}"
1128            ),
1129        }
1130    }
1131}
1132
1133impl std::error::Error for HgtConversionError {}
1134
1135const MIN_TERRAIN_LAT_INDEX: i32 = -90;
1136const MAX_TERRAIN_LAT_INDEX: i32 = 89;
1137const MIN_TERRAIN_LON_INDEX: i32 = -180;
1138const MAX_TERRAIN_LON_INDEX: i32 = 179;
1139const MIN_TERRAIN_LAT_DEG: f64 = -90.0;
1140const MAX_TERRAIN_LAT_DEG: f64 = 90.0;
1141const MIN_TERRAIN_LON_DEG: f64 = -180.0;
1142const MAX_TERRAIN_LON_DEG: f64 = 180.0;
1143const SRTM1_POSTINGS_PER_AXIS: usize = 3601;
1144const SRTM1_HGT_LEN: usize = SRTM1_POSTINGS_PER_AXIS * SRTM1_POSTINGS_PER_AXIS * 2;
1145const DTED_SRTM1_DATA_BLOCK_LEN: usize = 12 + 2 * SRTM1_POSTINGS_PER_AXIS;
1146const DTED_SRTM1_LEN: usize =
1147    terrain::DATA_OFFSET + SRTM1_POSTINGS_PER_AXIS * DTED_SRTM1_DATA_BLOCK_LEN;
1148
1149/// Civil UTC date used by product archive names.
1150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1151pub struct ProductDate {
1152    /// Year.
1153    pub year: i32,
1154    /// Month in `1..=12`.
1155    pub month: u8,
1156    /// Day of month.
1157    pub day: u8,
1158}
1159
1160impl ProductDate {
1161    /// Build and validate a civil date.
1162    pub fn new(year: i32, month: u8, day: u8) -> Result<Self, DataCatalogError> {
1163        let days = days_in_month(i64::from(year), i64::from(month));
1164        if !(1..=9999).contains(&year) || days == 0 || day == 0 || i64::from(day) > days {
1165            return Err(DataCatalogError::InvalidDate { year, month, day });
1166        }
1167        Ok(Self { year, month, day })
1168    }
1169
1170    /// Build a date from GPS week and day-of-week (`0` = Sunday).
1171    pub fn from_gps_week_day(week: u32, day_of_week: u8) -> Result<Self, DataCatalogError> {
1172        if day_of_week > 6 {
1173            return Err(DataCatalogError::InvalidGpsDayOfWeek(day_of_week));
1174        }
1175        let epoch_jdn =
1176            week_epoch_julian_day_number(TimeScale::Gpst).expect("GPST has a week-numbering epoch");
1177        let offset_days = i64::from(week)
1178            .checked_mul(7)
1179            .and_then(|days| days.checked_add(i64::from(day_of_week)))
1180            .ok_or(DataCatalogError::DateOutOfRange)?;
1181        product_date_from_jdn(
1182            epoch_jdn
1183                .checked_add(offset_days)
1184                .ok_or(DataCatalogError::DateOutOfRange)?,
1185        )
1186    }
1187
1188    /// GPS week for this date.
1189    pub fn gps_week(self) -> Result<u32, DataCatalogError> {
1190        week_from_calendar(
1191            TimeScale::Gpst,
1192            i64::from(self.year),
1193            i64::from(self.month),
1194            i64::from(self.day),
1195        )
1196        .ok_or(DataCatalogError::DateBeforeGpsEpoch(self))
1197    }
1198
1199    /// Day-of-year in `1..=366`.
1200    #[must_use]
1201    pub fn day_of_year(self) -> u16 {
1202        day_of_year_int(self.year, i32::from(self.month), i32::from(self.day)) as u16
1203    }
1204
1205    fn add_days(self, days: i64) -> Result<Self, DataCatalogError> {
1206        product_date_from_jdn(
1207            self.julian_day_number()
1208                .checked_add(days)
1209                .ok_or(DataCatalogError::DateOutOfRange)?,
1210        )
1211    }
1212
1213    fn julian_day_number(self) -> i64 {
1214        julian_day_number(self.year, i32::from(self.month), i32::from(self.day))
1215    }
1216}
1217
1218impl fmt::Display for ProductDate {
1219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1220        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
1221    }
1222}
1223
1224/// Civil UTC date and time used for ultra-rapid issue selection.
1225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1226pub struct ProductDateTime {
1227    /// Date.
1228    pub date: ProductDate,
1229    /// Hour in `0..=23`.
1230    pub hour: u8,
1231    /// Minute in `0..=59`.
1232    pub minute: u8,
1233    /// Second in `0..=59`.
1234    pub second: u8,
1235}
1236
1237impl ProductDateTime {
1238    /// Build and validate a civil date and time.
1239    pub fn new(
1240        date: ProductDate,
1241        hour: u8,
1242        minute: u8,
1243        second: u8,
1244    ) -> Result<Self, DataCatalogError> {
1245        if hour > 23 || minute > 59 || second > 59 {
1246            return Err(DataCatalogError::InvalidDateTime {
1247                hour,
1248                minute,
1249                second,
1250            });
1251        }
1252        Ok(Self {
1253            date,
1254            hour,
1255            minute,
1256            second,
1257        })
1258    }
1259
1260    fn ordering_minutes(self) -> i64 {
1261        self.date.julian_day_number() * 1_440 + i64::from(self.hour) * 60 + i64::from(self.minute)
1262    }
1263}
1264
1265/// Ultra-rapid issue date and `HHMM` issue time.
1266#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1267pub struct UltraIssue {
1268    /// Product date.
1269    pub date: ProductDate,
1270    /// Issue time.
1271    pub issue: String,
1272}
1273
1274impl UltraIssue {
1275    /// Build and validate an ultra-rapid issue.
1276    pub fn new(date: ProductDate, issue: &str) -> Result<Self, DataCatalogError> {
1277        validate_issue(issue)?;
1278        Ok(Self {
1279            date,
1280            issue: issue.to_string(),
1281        })
1282    }
1283}
1284
1285/// One generated ultra-rapid SP3 archive candidate.
1286#[derive(Debug, Clone, PartialEq, Eq)]
1287pub struct UltraSp3Location {
1288    /// Stable catalog label identifying the primary, alternate, or alias rule.
1289    pub pattern: String,
1290    /// Product span token used by the candidate.
1291    pub span: String,
1292    /// Sampling token used by the candidate.
1293    pub sample: String,
1294    /// Archive filename without a transport compression suffix.
1295    pub filename: String,
1296    /// Full archive URL, including its compression suffix when applicable.
1297    pub url: String,
1298    /// Archive compression for this candidate.
1299    pub compression: ArchiveCompression,
1300}
1301
1302#[derive(Debug, Clone, Copy)]
1303struct UltraSp3Pattern {
1304    label: &'static str,
1305    span: &'static str,
1306    sample: &'static str,
1307    alias_filename: Option<&'static str>,
1308}
1309
1310const IGS_ULT_SP3_PATTERNS: [UltraSp3Pattern; 3] = [
1311    UltraSp3Pattern {
1312        label: "primary_02D_15M",
1313        span: "02D",
1314        sample: "15M",
1315        alias_filename: None,
1316    },
1317    UltraSp3Pattern {
1318        label: "alternate_02D_05M",
1319        span: "02D",
1320        sample: "05M",
1321        alias_filename: None,
1322    },
1323    UltraSp3Pattern {
1324        label: "alternate_01D_15M",
1325        span: "01D",
1326        sample: "15M",
1327        alias_filename: None,
1328    },
1329];
1330
1331const COD_ULT_SP3_PATTERNS: [UltraSp3Pattern; 3] = [
1332    UltraSp3Pattern {
1333        label: "primary_01D_05M",
1334        span: "01D",
1335        sample: "05M",
1336        alias_filename: None,
1337    },
1338    UltraSp3Pattern {
1339        label: "alternate_02D_05M",
1340        span: "02D",
1341        sample: "05M",
1342        alias_filename: None,
1343    },
1344    UltraSp3Pattern {
1345        label: "alias_latest",
1346        span: "01D",
1347        sample: "05M",
1348        alias_filename: Some("COD0OPSULT.SP3"),
1349    },
1350];
1351
1352const ESA_ULT_SP3_PATTERNS: [UltraSp3Pattern; 3] = [
1353    UltraSp3Pattern {
1354        label: "primary_02D_05M",
1355        span: "02D",
1356        sample: "05M",
1357        alias_filename: None,
1358    },
1359    UltraSp3Pattern {
1360        label: "alternate_02D_15M",
1361        span: "02D",
1362        sample: "15M",
1363        alias_filename: None,
1364    },
1365    UltraSp3Pattern {
1366        label: "alternate_01D_05M",
1367        span: "01D",
1368        sample: "05M",
1369        alias_filename: None,
1370    },
1371];
1372
1373const GFZ_ULT_SP3_PATTERNS: [UltraSp3Pattern; 3] = [
1374    UltraSp3Pattern {
1375        label: "primary_02D_05M",
1376        span: "02D",
1377        sample: "05M",
1378        alias_filename: None,
1379    },
1380    UltraSp3Pattern {
1381        label: "alternate_02D_15M",
1382        span: "02D",
1383        sample: "15M",
1384        alias_filename: None,
1385    },
1386    UltraSp3Pattern {
1387        label: "alternate_01D_05M",
1388        span: "01D",
1389        sample: "05M",
1390        alias_filename: None,
1391    },
1392];
1393
1394/// Exact identity of one public GNSS product, independent of distributor.
1395///
1396/// The official filename is part of the identity. Transport compression and
1397/// URL belong to [`DistributionLocation`] because two distributors may package
1398/// the same decompressed product differently.
1399#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1400pub struct ProductIdentity {
1401    /// Product family.
1402    pub family: ProductType,
1403    /// Producing or combining organization.
1404    pub publisher: ProductPublisher,
1405    /// Solution class or tier.
1406    pub solution: SolutionClass,
1407    /// Campaign or project.
1408    pub campaign: ProductCampaign,
1409    /// Product-line version encoded by the long filename.
1410    pub version: u8,
1411    /// Nominal product start date.
1412    pub date: ProductDate,
1413    /// Optional `HHMM` issue/start time.
1414    pub issue: Option<String>,
1415    /// Intended coverage period token, for example `01D`.
1416    pub span: String,
1417    /// Sampling interval token, for example `05M`.
1418    pub sample: String,
1419    /// Official filename without transport compression suffix.
1420    pub official_filename: String,
1421    /// Public serialization format.
1422    pub format: ProductFormat,
1423    /// Prediction horizon when the product line encodes one.
1424    pub prediction_horizon_days: Option<u8>,
1425}
1426
1427impl ProductIdentity {
1428    /// Validate that every identity field agrees with the official filename.
1429    ///
1430    /// This is required for caller-constructed values before using them in a
1431    /// request, URL, or cache path. Catalog-produced identities are validated
1432    /// before they are returned.
1433    pub fn validate(&self) -> Result<(), DataCatalogError> {
1434        validate_official_filename(&self.official_filename)?;
1435        ProductDate::new(self.date.year, self.date.month, self.date.day)?;
1436        validate_sample(&self.sample)?;
1437        if let Some(issue) = self.issue.as_deref() {
1438            validate_issue(issue)?;
1439        }
1440
1441        if self.format != product_format(self.family) {
1442            return Err(DataCatalogError::InconsistentProductIdentity { field: "format" });
1443        }
1444
1445        let horizon_valid = match (self.publisher, self.solution, self.prediction_horizon_days) {
1446            (ProductPublisher::Code, SolutionClass::Predicted, Some(1 | 2)) => true,
1447            (_, SolutionClass::Predicted, _) => false,
1448            (_, _, None) => true,
1449            (_, _, Some(_)) => false,
1450        };
1451        if !horizon_valid {
1452            return Err(DataCatalogError::InconsistentProductIdentity {
1453                field: "prediction_horizon_days",
1454            });
1455        }
1456
1457        let descriptor = product_type_convention(self.family);
1458        let expected = match descriptor.kind {
1459            ProductFilenameKind::Sampled => {
1460                let solution_token = self
1461                    .solution
1462                    .filename_token()
1463                    .ok_or(DataCatalogError::InconsistentProductIdentity { field: "solution" })?;
1464                format!(
1465                    "{}{}{}{}_{}_{}_{}_{}.{}",
1466                    self.publisher.code(),
1467                    self.version,
1468                    self.campaign.code(),
1469                    solution_token,
1470                    date_block(self.date, self.issue.as_deref()),
1471                    self.span,
1472                    self.sample,
1473                    descriptor.content_code,
1474                    descriptor.extension
1475                )
1476            }
1477            ProductFilenameKind::Nav => {
1478                let nav_fields_valid = self.publisher == ProductPublisher::Igs
1479                    && self.solution == SolutionClass::Broadcast
1480                    && self.campaign == ProductCampaign::Broadcast
1481                    && self.version == 0
1482                    && self.issue.is_none()
1483                    && self.span == "01D"
1484                    && self.sample == "01D";
1485                if !nav_fields_valid {
1486                    return Err(DataCatalogError::InconsistentProductIdentity {
1487                        field: "broadcast_navigation",
1488                    });
1489                }
1490                format!(
1491                    "BRDC00WRD_R_{}_{}_{}.{}",
1492                    date_block(self.date, None),
1493                    self.span,
1494                    descriptor.content_code,
1495                    descriptor.extension
1496                )
1497            }
1498        };
1499        if expected != self.official_filename {
1500            return Err(DataCatalogError::InconsistentProductIdentity {
1501                field: "official_filename",
1502            });
1503        }
1504        Ok(())
1505    }
1506
1507    /// Deterministic identity key suitable for a portable cache layout.
1508    pub fn key(&self) -> Result<String, DataCatalogError> {
1509        self.validate()?;
1510        let prediction = self.prediction_horizon_days.map_or_else(
1511            || "observed".to_string(),
1512            |days| format!("prediction_{days}d"),
1513        );
1514        Ok(format!(
1515            "{}/{}/{}/{}/{}/{}",
1516            self.family.code(),
1517            self.publisher.code().to_ascii_lowercase(),
1518            self.solution.code(),
1519            self.campaign.code().to_ascii_lowercase(),
1520            prediction,
1521            self.official_filename
1522        ))
1523    }
1524
1525    /// Deterministic cache path for this identity and distributor.
1526    pub fn cache_relpath(&self, source: DistributionSource) -> Result<String, DataCatalogError> {
1527        Ok(format!("products/v1/{}/{}", source.code(), self.key()?))
1528    }
1529}
1530
1531/// Distribution metadata for an exact product identity.
1532#[derive(Debug, Clone, PartialEq, Eq)]
1533pub struct DistributionLocation {
1534    /// Selected distributor.
1535    pub source: DistributionSource,
1536    /// Original public URL. Local and in-memory sources have no URL.
1537    pub original_url: Option<String>,
1538    /// Archive filename as served, including transport compression suffix.
1539    pub archive_filename: String,
1540    /// Compression applied by this distributor.
1541    pub compression: ArchiveCompression,
1542}
1543
1544/// Exact product request with an ordered, caller-controlled distributor list.
1545#[derive(Debug, Clone, PartialEq, Eq)]
1546pub struct ProductRequest {
1547    /// Exact requested identity.
1548    pub identity: ProductIdentity,
1549    /// Ordered acceptable distributors for that identity only.
1550    pub distributors: Vec<DistributionSource>,
1551}
1552
1553/// Complete-set validation failure for exact product identities.
1554#[derive(Debug, Clone, PartialEq, Eq)]
1555pub enum ExactProductSetError {
1556    /// A complete set must declare at least one expected product.
1557    EmptyExpected,
1558    /// One expected identity was not internally consistent.
1559    InvalidExpected {
1560        /// Zero-based position in the expected identity list.
1561        index: usize,
1562        /// Identity validation failure.
1563        source: DataCatalogError,
1564    },
1565    /// One available identity was not internally consistent.
1566    InvalidAvailable {
1567        /// Zero-based position in the available identity list.
1568        index: usize,
1569        /// Identity validation failure.
1570        source: DataCatalogError,
1571    },
1572    /// The available identities were not exactly the expected set.
1573    Mismatch {
1574        /// Expected identities that were not available.
1575        missing: Vec<ProductIdentity>,
1576        /// Available identities that were not expected.
1577        unexpected: Vec<ProductIdentity>,
1578        /// Identities declared more than once in the expected list.
1579        duplicate_expected: Vec<ProductIdentity>,
1580        /// Identities declared more than once in the available list.
1581        duplicate_available: Vec<ProductIdentity>,
1582    },
1583}
1584
1585impl fmt::Display for ExactProductSetError {
1586    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1587        match self {
1588            Self::EmptyExpected => write!(f, "exact product set has no expected products"),
1589            Self::InvalidExpected { index, source } => {
1590                write!(f, "expected product {index} is invalid: {source}")
1591            }
1592            Self::InvalidAvailable { index, source } => {
1593                write!(f, "available product {index} is invalid: {source}")
1594            }
1595            Self::Mismatch {
1596                missing,
1597                unexpected,
1598                duplicate_expected,
1599                duplicate_available,
1600            } => write!(
1601                f,
1602                "exact product set mismatch (missing: {}; unexpected: {}; duplicate expected: {}; duplicate available: {})",
1603                identity_list(missing),
1604                identity_list(unexpected),
1605                identity_list(duplicate_expected),
1606                identity_list(duplicate_available),
1607            ),
1608        }
1609    }
1610}
1611
1612impl std::error::Error for ExactProductSetError {}
1613
1614/// Require an available product inventory to match an expected exact set.
1615///
1616/// Every identity is validated before comparison. The expected list must be
1617/// non-empty, neither list may contain duplicates, every expected identity must
1618/// be available, and no undeclared identity may be present. Comparison uses the
1619/// complete [`ProductIdentity`], not only its filename, so metadata that
1620/// distinguishes otherwise identical archive names remains authoritative.
1621///
1622/// This function is a sans-IO completion gate: pass only identities from
1623/// successfully validated acquisitions, and do not start dependent processing
1624/// unless it returns `Ok(())`. For SP3 observed/predicted timing, use
1625/// [`crate::sp3::Sp3::prediction_summary`]; issue times and catalog fields are
1626/// not substitutes for the record flags in the product itself.
1627pub fn validate_exact_product_set(
1628    expected: &[ProductIdentity],
1629    available: &[ProductIdentity],
1630) -> Result<(), ExactProductSetError> {
1631    if expected.is_empty() {
1632        return Err(ExactProductSetError::EmptyExpected);
1633    }
1634    for (index, identity) in expected.iter().enumerate() {
1635        identity
1636            .validate()
1637            .map_err(|source| ExactProductSetError::InvalidExpected { index, source })?;
1638    }
1639    for (index, identity) in available.iter().enumerate() {
1640        identity
1641            .validate()
1642            .map_err(|source| ExactProductSetError::InvalidAvailable { index, source })?;
1643    }
1644
1645    let expected_counts = identity_counts(expected);
1646    let available_counts = identity_counts(available);
1647    let missing = unique_matching(expected, |identity| {
1648        !available_counts.contains_key(identity)
1649    });
1650    let unexpected = unique_matching(available, |identity| {
1651        !expected_counts.contains_key(identity)
1652    });
1653    let duplicate_expected = unique_matching(expected, |identity| expected_counts[identity] > 1);
1654    let duplicate_available = unique_matching(available, |identity| available_counts[identity] > 1);
1655
1656    if missing.is_empty()
1657        && unexpected.is_empty()
1658        && duplicate_expected.is_empty()
1659        && duplicate_available.is_empty()
1660    {
1661        Ok(())
1662    } else {
1663        Err(ExactProductSetError::Mismatch {
1664            missing,
1665            unexpected,
1666            duplicate_expected,
1667            duplicate_available,
1668        })
1669    }
1670}
1671
1672fn identity_counts(identities: &[ProductIdentity]) -> HashMap<&ProductIdentity, usize> {
1673    let mut counts = HashMap::with_capacity(identities.len());
1674    for identity in identities {
1675        *counts.entry(identity).or_insert(0) += 1;
1676    }
1677    counts
1678}
1679
1680fn unique_matching(
1681    identities: &[ProductIdentity],
1682    mut predicate: impl FnMut(&ProductIdentity) -> bool,
1683) -> Vec<ProductIdentity> {
1684    let mut seen = HashSet::with_capacity(identities.len());
1685    identities
1686        .iter()
1687        .filter(|identity| predicate(identity) && seen.insert((*identity).clone()))
1688        .cloned()
1689        .collect()
1690}
1691
1692fn identity_list(identities: &[ProductIdentity]) -> String {
1693    if identities.is_empty() {
1694        return "none".to_string();
1695    }
1696    identities
1697        .iter()
1698        .map(|identity| {
1699            identity
1700                .key()
1701                .unwrap_or_else(|_| identity.official_filename.clone())
1702        })
1703        .collect::<Vec<_>>()
1704        .join(", ")
1705}
1706
1707impl ProductRequest {
1708    /// Build an exact request. At least one distributor is required.
1709    pub fn new(
1710        identity: ProductIdentity,
1711        distributors: Vec<DistributionSource>,
1712    ) -> Result<Self, DataCatalogError> {
1713        if distributors.is_empty() {
1714            return Err(DataCatalogError::NoDistributionSources);
1715        }
1716        identity.validate()?;
1717        Ok(Self {
1718            identity,
1719            distributors,
1720        })
1721    }
1722}
1723
1724/// A pure product specification that resolves to one archive filename and URL.
1725#[derive(Debug, Clone, PartialEq, Eq)]
1726pub struct ProductSpec {
1727    /// Analysis center.
1728    pub center: AnalysisCenter,
1729    /// Product type.
1730    pub product_type: ProductType,
1731    /// Product date.
1732    pub date: ProductDate,
1733    /// Sampling token.
1734    pub sample: String,
1735    /// Optional issue time for ultra-rapid products.
1736    pub issue: Option<String>,
1737}
1738
1739impl ProductSpec {
1740    /// Build a product specification and validate it against the catalog.
1741    pub fn new(
1742        center: AnalysisCenter,
1743        product_type: ProductType,
1744        date: ProductDate,
1745        sample: &str,
1746        issue: Option<&str>,
1747    ) -> Result<Self, DataCatalogError> {
1748        validate_product(center, product_type, sample, issue)?;
1749        Ok(Self {
1750            center,
1751            product_type,
1752            date,
1753            sample: sample.to_string(),
1754            issue: issue.map(ToOwned::to_owned),
1755        })
1756    }
1757
1758    /// GPS week for the product date.
1759    pub fn gps_week(&self) -> Result<u32, DataCatalogError> {
1760        self.date.gps_week()
1761    }
1762
1763    /// Day-of-year for the product date.
1764    #[must_use]
1765    pub fn day_of_year(&self) -> u16 {
1766        self.date.day_of_year()
1767    }
1768
1769    /// Canonical IGS long-name filename without archive compression suffix.
1770    pub fn canonical_filename(&self) -> Result<String, DataCatalogError> {
1771        let convention = validate_product(
1772            self.center,
1773            self.product_type,
1774            &self.sample,
1775            self.issue.as_deref(),
1776        )?;
1777        let descriptor = product_type_convention(self.product_type);
1778        Ok(match descriptor.kind {
1779            ProductFilenameKind::Sampled => format!(
1780                "{}_{}_{}_{}_{}.{}",
1781                convention.token,
1782                date_block(self.date, self.issue.as_deref()),
1783                convention.span,
1784                self.sample,
1785                descriptor.content_code,
1786                descriptor.extension
1787            ),
1788            ProductFilenameKind::Nav => format!(
1789                "{}_R_{}_{}_{}.{}",
1790                convention.token,
1791                date_block(self.date, None),
1792                convention.span,
1793                descriptor.content_code,
1794                descriptor.extension
1795            ),
1796        })
1797    }
1798
1799    /// Full archive URL, including `.gz` when the cataloged archive is gzipped.
1800    pub fn archive_url(&self) -> Result<String, DataCatalogError> {
1801        let convention = validate_product(
1802            self.center,
1803            self.product_type,
1804            &self.sample,
1805            self.issue.as_deref(),
1806        )?;
1807        let entry = center_catalog(self.center).expect("catalog entry exists for enum variant");
1808        let filename = self.canonical_filename()?;
1809        Ok(format!(
1810            "{}/{}/{}{}",
1811            entry.root_url,
1812            product_dir_path(self.center, convention.layout, self.date)?,
1813            filename,
1814            convention.compression.suffix()
1815        ))
1816    }
1817
1818    /// Exact product identity, independent of distributor.
1819    pub fn identity(&self) -> Result<ProductIdentity, DataCatalogError> {
1820        let convention = validate_product(
1821            self.center,
1822            self.product_type,
1823            &self.sample,
1824            self.issue.as_deref(),
1825        )?;
1826        let descriptor = product_type_convention(self.product_type);
1827        let campaign = match descriptor.kind {
1828            ProductFilenameKind::Nav => ProductCampaign::Broadcast,
1829            ProductFilenameKind::Sampled => match convention.token.get(4..7) {
1830                Some("OPS") => ProductCampaign::Operational,
1831                Some("MGN") => ProductCampaign::MultiGnss,
1832                Some("MGX") => ProductCampaign::MultiGnssExperiment,
1833                _ => {
1834                    return Err(DataCatalogError::InconsistentProductIdentity {
1835                        field: "campaign",
1836                    });
1837                }
1838            },
1839        };
1840        let identity = ProductIdentity {
1841            family: self.product_type,
1842            publisher: self.center.publisher(),
1843            solution: self.center.solution_class(),
1844            campaign,
1845            version: 0,
1846            date: self.date,
1847            issue: self.issue.clone(),
1848            span: convention.span.to_string(),
1849            sample: self.sample.clone(),
1850            official_filename: self.canonical_filename()?,
1851            format: product_format(self.product_type),
1852            prediction_horizon_days: self.center.prediction_horizon_days(),
1853        };
1854        identity.validate()?;
1855        Ok(identity)
1856    }
1857
1858    /// Resolve one explicit distributor without changing product identity.
1859    pub fn distribution_location(
1860        &self,
1861        source: DistributionSource,
1862    ) -> Result<DistributionLocation, DataCatalogError> {
1863        let identity = self.identity()?;
1864        match source {
1865            DistributionSource::Direct => {
1866                let compression = product_convention(self.center, self.product_type)?.compression;
1867                Ok(DistributionLocation {
1868                    source,
1869                    original_url: Some(self.archive_url()?),
1870                    archive_filename: format!(
1871                        "{}{}",
1872                        identity.official_filename,
1873                        compression.suffix()
1874                    ),
1875                    compression,
1876                })
1877            }
1878            DistributionSource::NasaCddis => {
1879                let url = cddis_archive_url(&identity)?;
1880                Ok(DistributionLocation {
1881                    source,
1882                    original_url: Some(url),
1883                    archive_filename: format!("{}.gz", identity.official_filename),
1884                    compression: ArchiveCompression::Gzip,
1885                })
1886            }
1887            DistributionSource::LocalFile | DistributionSource::InMemory => {
1888                Ok(DistributionLocation {
1889                    source,
1890                    original_url: None,
1891                    archive_filename: identity.official_filename,
1892                    compression: ArchiveCompression::None,
1893                })
1894            }
1895        }
1896    }
1897}
1898
1899/// A pure station observation specification.
1900#[derive(Debug, Clone, PartialEq, Eq)]
1901pub struct StationObservationSpec {
1902    /// 9-character RINEX 3 site identifier.
1903    pub station: String,
1904    /// Observation date.
1905    pub date: ProductDate,
1906    /// Sampling token.
1907    pub sample: String,
1908}
1909
1910impl StationObservationSpec {
1911    /// Build and validate a daily station observation product.
1912    pub fn new(station: &str, date: ProductDate, sample: &str) -> Result<Self, DataCatalogError> {
1913        validate_station(station)?;
1914        validate_sample(sample)?;
1915        Ok(Self {
1916            station: station.to_string(),
1917            date,
1918            sample: sample.to_string(),
1919        })
1920    }
1921
1922    /// Canonical RINEX 3 CRINEX filename without archive compression suffix.
1923    pub fn canonical_filename(&self) -> Result<String, DataCatalogError> {
1924        station_obs_filename(&self.station, self.date, &self.sample)
1925    }
1926
1927    /// Full archive URL, including `.gz`.
1928    pub fn archive_url(&self) -> Result<String, DataCatalogError> {
1929        station_obs_url(&self.station, self.date, &self.sample)
1930    }
1931}
1932
1933/// Static catalog entries, in the same order as the binding data catalog.
1934#[must_use]
1935pub const fn catalog() -> &'static [CenterCatalogEntry] {
1936    &CATALOG
1937}
1938
1939/// Supported center codes, in catalog order.
1940#[must_use]
1941pub const fn centers() -> &'static [AnalysisCenter] {
1942    &CENTER_ORDER
1943}
1944
1945/// Supported product types.
1946#[must_use]
1947pub const fn product_types() -> &'static [ProductTypeConvention] {
1948    &PRODUCT_TYPE_CONVENTIONS
1949}
1950
1951/// Archive hosts present in the catalog.
1952#[must_use]
1953pub const fn allowed_hosts() -> &'static [&'static str] {
1954    &ALLOWED_HOSTS
1955}
1956
1957/// Catalog entry for the Skadi SRTM terrain source.
1958#[must_use]
1959pub const fn skadi_source_entry() -> TerrainSourceEntry {
1960    SKADI_SOURCE
1961}
1962
1963/// Catalog entry for the CelesTrak CSSI space-weather source.
1964#[must_use]
1965pub const fn space_weather_source_entry() -> SpaceWeatherSourceEntry {
1966    CELESTRAK_SPACE_WEATHER_SOURCE
1967}
1968
1969/// Filename for a CelesTrak space-weather product.
1970#[must_use]
1971pub const fn space_weather_filename(product: SpaceWeatherProduct) -> &'static str {
1972    match product {
1973        SpaceWeatherProduct::All => "SW-All.csv",
1974        SpaceWeatherProduct::Last5Years => "SW-Last5Years.csv",
1975    }
1976}
1977
1978/// Build the CelesTrak archive URL for a space-weather product.
1979#[must_use]
1980pub fn space_weather_archive_url(product: SpaceWeatherProduct) -> String {
1981    format!(
1982        "{}/{}",
1983        CELESTRAK_SPACE_WEATHER_SOURCE.root_url,
1984        space_weather_filename(product)
1985    )
1986}
1987
1988/// Build the cache relative path for a space-weather product.
1989#[must_use]
1990pub fn space_weather_cache_relpath(product: SpaceWeatherProduct) -> String {
1991    format!("space-weather/{}", space_weather_filename(product))
1992}
1993
1994/// Build the Skadi SRTM tile id, for example `N36W107`.
1995pub fn skadi_tile_id(lat_index: i32, lon_index: i32) -> Result<String, DataCatalogError> {
1996    validate_terrain_tile_index(lat_index, lon_index)?;
1997    let lat_hemi = if lat_index >= 0 { 'N' } else { 'S' };
1998    let lon_hemi = if lon_index >= 0 { 'E' } else { 'W' };
1999    Ok(format!(
2000        "{lat_hemi}{:02}{lon_hemi}{:03}",
2001        lat_index.abs(),
2002        lon_index.abs()
2003    ))
2004}
2005
2006/// Build the Skadi latitude band directory, for example `N36`.
2007pub fn skadi_band(lat_index: i32) -> Result<String, DataCatalogError> {
2008    validate_terrain_lat_index(lat_index)?;
2009    let lat_hemi = if lat_index >= 0 { 'N' } else { 'S' };
2010    Ok(format!("{lat_hemi}{:02}", lat_index.abs()))
2011}
2012
2013/// Build the Skadi SRTM archive URL for a tile.
2014pub fn skadi_archive_url(lat_index: i32, lon_index: i32) -> Result<String, DataCatalogError> {
2015    let band = skadi_band(lat_index)?;
2016    let tile_id = skadi_tile_id(lat_index, lon_index)?;
2017    Ok(format!(
2018        "{}/skadi/{}/{}.hgt{}",
2019        SKADI_SOURCE.root_url,
2020        band,
2021        tile_id,
2022        SKADI_SOURCE.compression.suffix()
2023    ))
2024}
2025
2026/// Build the DTED tile filename read by the terrain module.
2027pub fn dted_tile_filename(lat_index: i32, lon_index: i32) -> Result<String, DataCatalogError> {
2028    validate_terrain_tile_index(lat_index, lon_index)?;
2029    Ok(format!(
2030        "{}_{}{}",
2031        terrain::format_lat(lat_index),
2032        terrain::format_lon(lon_index),
2033        terrain::DTED_SUFFIX
2034    ))
2035}
2036
2037/// Build the DTED ten-degree cache block directory read by the terrain module.
2038pub fn dted_block_dir(lat_index: i32, lon_index: i32) -> Result<String, DataCatalogError> {
2039    validate_terrain_tile_index(lat_index, lon_index)?;
2040    Ok(terrain::terrain_block_dir(lat_index, lon_index))
2041}
2042
2043/// Build the DTED cache relative path read by the terrain module.
2044pub fn dted_cache_relpath(lat_index: i32, lon_index: i32) -> Result<String, DataCatalogError> {
2045    Ok(format!(
2046        "{}/{}",
2047        dted_block_dir(lat_index, lon_index)?,
2048        dted_tile_filename(lat_index, lon_index)?
2049    ))
2050}
2051
2052/// Parse a Skadi SRTM tile id into `(lat_index, lon_index)`.
2053pub fn parse_skadi_tile_id(id: &str) -> Result<(i32, i32), DataCatalogError> {
2054    let bytes = id.as_bytes();
2055    if bytes.len() != 7
2056        || !matches!(bytes[0], b'N' | b'S')
2057        || !matches!(bytes[3], b'E' | b'W')
2058        || !bytes[1..3].iter().all(u8::is_ascii_digit)
2059        || !bytes[4..7].iter().all(u8::is_ascii_digit)
2060    {
2061        return Err(DataCatalogError::InvalidTileId(id.to_string()));
2062    }
2063
2064    let lat_abs = id[1..3]
2065        .parse::<i32>()
2066        .map_err(|_| DataCatalogError::InvalidTileId(id.to_string()))?;
2067    let lon_abs = id[4..7]
2068        .parse::<i32>()
2069        .map_err(|_| DataCatalogError::InvalidTileId(id.to_string()))?;
2070    if (bytes[0] == b'S' && lat_abs == 0) || (bytes[3] == b'W' && lon_abs == 0) {
2071        return Err(DataCatalogError::InvalidTileId(id.to_string()));
2072    }
2073
2074    let lat_index = if bytes[0] == b'N' { lat_abs } else { -lat_abs };
2075    let lon_index = if bytes[3] == b'E' { lon_abs } else { -lon_abs };
2076    validate_terrain_tile_index(lat_index, lon_index)?;
2077    Ok((lat_index, lon_index))
2078}
2079
2080/// Derive the terrain tile index covering a latitude/longitude coordinate.
2081pub fn terrain_tile_index(lat_deg: f64, lon_deg: f64) -> Result<(i32, i32), DataCatalogError> {
2082    if !lat_deg.is_finite()
2083        || !lon_deg.is_finite()
2084        || !(MIN_TERRAIN_LAT_DEG..=MAX_TERRAIN_LAT_DEG).contains(&lat_deg)
2085        || !(MIN_TERRAIN_LON_DEG..=MAX_TERRAIN_LON_DEG).contains(&lon_deg)
2086    {
2087        return Err(DataCatalogError::InvalidCoordinate {
2088            lat_deg_bits: lat_deg.to_bits(),
2089            lon_deg_bits: lon_deg.to_bits(),
2090        });
2091    }
2092
2093    let (mut lat_index, mut lon_index) = terrain::terrain_grid(lon_deg, lat_deg);
2094    if lat_index == MAX_TERRAIN_LAT_DEG as i32 {
2095        lat_index = MAX_TERRAIN_LAT_INDEX;
2096    }
2097    if lon_index == MAX_TERRAIN_LON_DEG as i32 {
2098        lon_index = MAX_TERRAIN_LON_INDEX;
2099    }
2100    validate_terrain_tile_index(lat_index, lon_index)?;
2101    Ok((lat_index, lon_index))
2102}
2103
2104/// Convert decompressed SRTM1 HGT bytes into deterministic DTED `.dt2` bytes.
2105///
2106/// The HGT payload must be 3601 by 3601 big-endian `i16` samples in row-major
2107/// order. HGT rows run north to south; DTED data records are longitude columns
2108/// with postings south to north, so output posting `(i, j)` reads source sample
2109/// `hgt[r = 3600 - i][c = j]`. SRTM void samples (`-32768`) are written as sea
2110/// level (`0`) so the existing terrain reader returns `0` for those postings.
2111pub fn hgt_to_dted(
2112    lat_index: i32,
2113    lon_index: i32,
2114    hgt: &[u8],
2115) -> Result<Vec<u8>, HgtConversionError> {
2116    validate_hgt_tile_index(lat_index, lon_index)?;
2117    if hgt.len() != SRTM1_HGT_LEN {
2118        return Err(HgtConversionError::BadLength {
2119            expected: SRTM1_HGT_LEN,
2120            got: hgt.len(),
2121        });
2122    }
2123
2124    let mut out = vec![b' '; DTED_SRTM1_LEN];
2125    out[0..4].copy_from_slice(b"UHL1");
2126    out[4..12].copy_from_slice(dted_coord_field(lon_index, true).as_bytes());
2127    out[12..20].copy_from_slice(dted_coord_field(lat_index, false).as_bytes());
2128    out[47..51].copy_from_slice(b"3601");
2129    out[51..55].copy_from_slice(b"3601");
2130
2131    for lon_posting in 0..SRTM1_POSTINGS_PER_AXIS {
2132        let block_start = terrain::DATA_OFFSET + lon_posting * DTED_SRTM1_DATA_BLOCK_LEN;
2133        let checksum_start = block_start + DTED_SRTM1_DATA_BLOCK_LEN - 4;
2134        out[block_start] = terrain::DATA_SENTINEL;
2135
2136        let count = (lon_posting as u32).to_be_bytes();
2137        out[block_start + 1..block_start + 4].copy_from_slice(&count[1..4]);
2138        out[block_start + 4..block_start + 6].copy_from_slice(&(lon_posting as u16).to_be_bytes());
2139        out[block_start + 6..block_start + 8].copy_from_slice(&0u16.to_be_bytes());
2140
2141        for lat_posting in 0..SRTM1_POSTINGS_PER_AXIS {
2142            let hgt_row = SRTM1_POSTINGS_PER_AXIS - 1 - lat_posting;
2143            let hgt_sample_start = 2 * (hgt_row * SRTM1_POSTINGS_PER_AXIS + lon_posting);
2144            let sample = i16::from_be_bytes([hgt[hgt_sample_start], hgt[hgt_sample_start + 1]]);
2145            let encoded = encode_dted_signed_magnitude(sample).to_be_bytes();
2146            let dted_sample_start = block_start + 8 + 2 * lat_posting;
2147            out[dted_sample_start..dted_sample_start + 2].copy_from_slice(&encoded);
2148        }
2149
2150        let checksum = out[block_start..checksum_start]
2151            .iter()
2152            .fold(0i32, |acc, byte| acc + i32::from(*byte));
2153        out[checksum_start..checksum_start + 4].copy_from_slice(&checksum.to_be_bytes());
2154    }
2155
2156    debug_assert_eq!(out.len(), 25_981_042);
2157    Ok(out)
2158}
2159
2160/// Product pairs intentionally withheld because no open mirror is known.
2161#[must_use]
2162pub const fn no_open_mirrors() -> &'static [NoOpenMirrorProduct] {
2163    &NO_OPEN_MIRRORS
2164}
2165
2166/// Confirm that a center/product pair has an open catalog mirror.
2167pub fn open_mirror(
2168    center: AnalysisCenter,
2169    product_type: ProductType,
2170) -> Result<(), DataCatalogError> {
2171    open_mirror_code(center.code(), product_type.code())
2172}
2173
2174/// Confirm that a center/product code pair is not in the no-open-mirror list.
2175pub fn open_mirror_code(center: &str, product_type: &str) -> Result<(), DataCatalogError> {
2176    if NO_OPEN_MIRRORS
2177        .iter()
2178        .any(|entry| entry.center == center && entry.product_type == product_type)
2179    {
2180        Err(DataCatalogError::NoOpenMirror {
2181            center: center.to_string(),
2182            product_type: product_type.to_string(),
2183        })
2184    } else {
2185        Ok(())
2186    }
2187}
2188
2189/// Look up a center's static catalog entry.
2190#[must_use]
2191pub fn center_catalog(center: AnalysisCenter) -> Option<&'static CenterCatalogEntry> {
2192    CATALOG.iter().find(|entry| entry.center == center)
2193}
2194
2195/// Look up the convention for one center and product type.
2196pub fn product_convention(
2197    center: AnalysisCenter,
2198    product_type: ProductType,
2199) -> Result<&'static CenterProductConvention, DataCatalogError> {
2200    open_mirror(center, product_type)?;
2201    let entry = center_catalog(center).expect("catalog entry exists for enum variant");
2202    entry
2203        .products
2204        .iter()
2205        .find(|product| product.product_type == product_type)
2206        .ok_or(DataCatalogError::UnsupportedProduct {
2207            center,
2208            product_type,
2209        })
2210}
2211
2212/// Default sampling token for a center/product pair.
2213pub fn default_sample(
2214    center: AnalysisCenter,
2215    product_type: ProductType,
2216) -> Result<&'static str, DataCatalogError> {
2217    Ok(product_convention(center, product_type)?.default_sample)
2218}
2219
2220/// GPS week number for a product date.
2221pub fn gps_week(date: ProductDate) -> Result<u32, DataCatalogError> {
2222    date.gps_week()
2223}
2224
2225/// Day-of-year in `1..=366` for a product date.
2226#[must_use]
2227pub fn day_of_year(date: ProductDate) -> u16 {
2228    date.day_of_year()
2229}
2230
2231/// Build a product specification for any center/product/date combination.
2232pub fn product(
2233    center: AnalysisCenter,
2234    product_type: ProductType,
2235    date: ProductDate,
2236    sample: Option<&str>,
2237    issue: Option<&str>,
2238) -> Result<ProductSpec, DataCatalogError> {
2239    let sample = match sample {
2240        Some(sample) => sample,
2241        None => default_sample(center, product_type)?,
2242    };
2243    ProductSpec::new(center, product_type, date, sample, issue)
2244}
2245
2246/// Build the canonical IGS long-name filename for a product.
2247pub fn canonical_filename(
2248    center: AnalysisCenter,
2249    product_type: ProductType,
2250    date: ProductDate,
2251    sample: Option<&str>,
2252    issue: Option<&str>,
2253) -> Result<String, DataCatalogError> {
2254    product(center, product_type, date, sample, issue)?.canonical_filename()
2255}
2256
2257/// Build the full archive URL for a product.
2258pub fn archive_url(
2259    center: AnalysisCenter,
2260    product_type: ProductType,
2261    date: ProductDate,
2262    sample: Option<&str>,
2263    issue: Option<&str>,
2264) -> Result<String, DataCatalogError> {
2265    product(center, product_type, date, sample, issue)?.archive_url()
2266}
2267
2268/// Build the exact identity for a catalog product.
2269pub fn product_identity(
2270    center: AnalysisCenter,
2271    product_type: ProductType,
2272    date: ProductDate,
2273    sample: Option<&str>,
2274    issue: Option<&str>,
2275) -> Result<ProductIdentity, DataCatalogError> {
2276    product(center, product_type, date, sample, issue)?.identity()
2277}
2278
2279/// Resolve an explicit distributor for a catalog product.
2280pub fn distribution_location(
2281    center: AnalysisCenter,
2282    product_type: ProductType,
2283    date: ProductDate,
2284    sample: Option<&str>,
2285    issue: Option<&str>,
2286    source: DistributionSource,
2287) -> Result<DistributionLocation, DataCatalogError> {
2288    product(center, product_type, date, sample, issue)?.distribution_location(source)
2289}
2290
2291/// Build the official NASA CDDIS HTTPS URL for an exact SP3 or IONEX identity.
2292///
2293/// CDDIS stores current SP3 products by GPS week and current IONEX products by
2294/// year/day-of-year. The decompressed official filename is unchanged.
2295pub fn cddis_archive_url(identity: &ProductIdentity) -> Result<String, DataCatalogError> {
2296    identity.validate()?;
2297    match identity.family {
2298        ProductType::Sp3 => Ok(format!(
2299            "https://cddis.nasa.gov/archive/gnss/products/{}/{}.gz",
2300            identity.date.gps_week()?,
2301            identity.official_filename
2302        )),
2303        ProductType::Ionex => Ok(format!(
2304            "https://cddis.nasa.gov/archive/gnss/products/ionex/{}/{:03}/{}.gz",
2305            identity.date.year,
2306            identity.date.day_of_year(),
2307            identity.official_filename
2308        )),
2309        product_type => Err(DataCatalogError::UnsupportedDistribution {
2310            source: DistributionSource::NasaCddis,
2311            product_type,
2312        }),
2313    }
2314}
2315
2316/// Build a clock product for a center and date.
2317pub fn mgex_clk(
2318    center: AnalysisCenter,
2319    date: ProductDate,
2320    sample: Option<&str>,
2321) -> Result<ProductSpec, DataCatalogError> {
2322    product(center, ProductType::Clk, date, sample, None)
2323}
2324
2325/// Build a merged broadcast-navigation product for a center and date.
2326pub fn mgex_nav(
2327    center: AnalysisCenter,
2328    date: ProductDate,
2329    sample: Option<&str>,
2330) -> Result<ProductSpec, DataCatalogError> {
2331    product(center, ProductType::Nav, date, sample, None)
2332}
2333
2334/// Build an IONEX product for a center and date.
2335pub fn mgex_ionex(
2336    center: AnalysisCenter,
2337    date: ProductDate,
2338    sample: Option<&str>,
2339) -> Result<ProductSpec, DataCatalogError> {
2340    product(center, ProductType::Ionex, date, sample, None)
2341}
2342
2343/// Build the CODE rapid IONEX product for a date.
2344pub fn rapid_ionex(
2345    date: ProductDate,
2346    sample: Option<&str>,
2347) -> Result<ProductSpec, DataCatalogError> {
2348    product(
2349        AnalysisCenter::CodRap,
2350        ProductType::Ionex,
2351        date,
2352        sample,
2353        None,
2354    )
2355}
2356
2357/// Day offset for predicted IONEX aliases.
2358#[must_use]
2359pub const fn predicted_day_offset(center: AnalysisCenter) -> i64 {
2360    match center {
2361        AnalysisCenter::CodPrd2 => 1,
2362        _ => 0,
2363    }
2364}
2365
2366/// Build a CODE predicted IONEX product for a target date.
2367pub fn predicted_ionex(
2368    center: AnalysisCenter,
2369    date: ProductDate,
2370    sample: Option<&str>,
2371) -> Result<ProductSpec, DataCatalogError> {
2372    match center {
2373        AnalysisCenter::CodPrd1 | AnalysisCenter::CodPrd2 => {
2374            let target = date.add_days(predicted_day_offset(center))?;
2375            product(center, ProductType::Ionex, target, sample, None)
2376        }
2377        other => Err(DataCatalogError::UnsupportedProduct {
2378            center: other,
2379            product_type: ProductType::Ionex,
2380        }),
2381    }
2382}
2383
2384/// Build an SP3 product for a center and date.
2385pub fn mgex_sp3(
2386    center: AnalysisCenter,
2387    date: ProductDate,
2388    sample: Option<&str>,
2389) -> Result<ProductSpec, DataCatalogError> {
2390    product(center, ProductType::Sp3, date, sample, None)
2391}
2392
2393/// Build an ultra-rapid OPS SP3 product for a date and issue time.
2394pub fn ops_ultra_sp3(
2395    center: AnalysisCenter,
2396    date: ProductDate,
2397    sample: Option<&str>,
2398    issue: Option<&str>,
2399) -> Result<ProductSpec, DataCatalogError> {
2400    let issue = issue.unwrap_or("0000");
2401    product(center, ProductType::Sp3, date, sample, Some(issue))
2402}
2403
2404/// Generate the current primary ultra-rapid SP3 location followed by known
2405/// duration/sampling alternates and documented latest-product aliases.
2406///
2407/// Candidate order is deterministic and center-specific. Callers should try
2408/// the next location only when the prior archive URL is absent; transport and
2409/// retry policy remain outside the pure core catalog.
2410pub fn ultra_sp3_locations(
2411    center: AnalysisCenter,
2412    date: ProductDate,
2413    issue: &str,
2414) -> Result<Vec<UltraSp3Location>, DataCatalogError> {
2415    validate_issue_for_center(center, Some(issue))?;
2416    let patterns: &[UltraSp3Pattern] = match center {
2417        AnalysisCenter::IgsUlt => &IGS_ULT_SP3_PATTERNS,
2418        AnalysisCenter::CodUlt => &COD_ULT_SP3_PATTERNS,
2419        AnalysisCenter::EsaUlt => &ESA_ULT_SP3_PATTERNS,
2420        AnalysisCenter::GfzUlt => &GFZ_ULT_SP3_PATTERNS,
2421        other => {
2422            return Err(DataCatalogError::UnsupportedProduct {
2423                center: other,
2424                product_type: ProductType::Sp3,
2425            })
2426        }
2427    };
2428    let convention = product_convention(center, ProductType::Sp3)?;
2429    let entry = center_catalog(center).expect("catalog entry exists for enum variant");
2430    let directory = dir_path(convention.layout, date)?;
2431    let date = date_block(date, Some(issue));
2432
2433    Ok(patterns
2434        .iter()
2435        .map(|pattern| {
2436            let filename = pattern.alias_filename.map_or_else(
2437                || {
2438                    format!(
2439                        "{}_{}_{}_{}_ORB.SP3",
2440                        convention.token, date, pattern.span, pattern.sample
2441                    )
2442                },
2443                ToOwned::to_owned,
2444            );
2445            UltraSp3Location {
2446                pattern: pattern.label.to_string(),
2447                span: pattern.span.to_string(),
2448                sample: pattern.sample.to_string(),
2449                url: format!(
2450                    "{}/{}/{}{}",
2451                    entry.root_url,
2452                    directory,
2453                    filename,
2454                    convention.compression.suffix()
2455                ),
2456                filename,
2457                compression: convention.compression,
2458            }
2459        })
2460        .collect())
2461}
2462
2463/// Build an ultra-rapid OPS clock product for a date and issue time.
2464pub fn ops_ultra_clk(
2465    center: AnalysisCenter,
2466    date: ProductDate,
2467    sample: Option<&str>,
2468    issue: Option<&str>,
2469) -> Result<ProductSpec, DataCatalogError> {
2470    let issue = issue.unwrap_or("0000");
2471    product(center, ProductType::Clk, date, sample, Some(issue))
2472}
2473
2474/// Select the latest ultra-rapid OPS SP3 issue at or before a target time.
2475pub fn latest_ops_ultra_sp3(
2476    center: AnalysisCenter,
2477    target: ProductDateTime,
2478    sample: Option<&str>,
2479    available_issues: Option<&[UltraIssue]>,
2480) -> Result<ProductSpec, DataCatalogError> {
2481    let selected = latest_ultra_issue(center, target, available_issues)?;
2482    ops_ultra_sp3(center, selected.date, sample, Some(&selected.issue))
2483}
2484
2485/// Candidate ultra-rapid issues at or before a target time, newest first.
2486pub fn ultra_issue_candidates(
2487    center: AnalysisCenter,
2488    target: ProductDateTime,
2489) -> Result<Vec<UltraIssue>, DataCatalogError> {
2490    let entry = center_catalog(center).expect("catalog entry exists for enum variant");
2491    let _ = product_convention(center, ProductType::Sp3)?;
2492    if entry.issues.is_empty() {
2493        return Err(DataCatalogError::UnsupportedProduct {
2494            center,
2495            product_type: ProductType::Sp3,
2496        });
2497    }
2498
2499    let mut candidates = Vec::new();
2500    for date in [target.date, target.date.add_days(-1)?] {
2501        for issue in entry.issues.iter().rev() {
2502            if issue_ordering_minutes(date, issue)? <= target.ordering_minutes() {
2503                candidates.push(UltraIssue::new(date, issue)?);
2504            }
2505        }
2506    }
2507    Ok(candidates)
2508}
2509
2510/// Latest ultra-rapid issue at or before a target time.
2511pub fn latest_ultra_issue(
2512    center: AnalysisCenter,
2513    target: ProductDateTime,
2514    available_issues: Option<&[UltraIssue]>,
2515) -> Result<UltraIssue, DataCatalogError> {
2516    let candidates = ultra_issue_candidates(center, target)?;
2517    if candidates.is_empty() {
2518        return Err(DataCatalogError::NoUltraIssue);
2519    }
2520    if let Some(available) = available_issues {
2521        candidates
2522            .into_iter()
2523            .find(|candidate| {
2524                available
2525                    .iter()
2526                    .any(|issue| issue.date == candidate.date && issue.issue == candidate.issue)
2527            })
2528            .ok_or(DataCatalogError::NoAvailableUltraIssue)
2529    } else {
2530        Ok(candidates[0].clone())
2531    }
2532}
2533
2534/// Candidate IONEX dates at or before a target date, newest first.
2535pub fn gim_date_candidates(
2536    center: AnalysisCenter,
2537    target: ProductDate,
2538    lookback: u32,
2539) -> Result<Vec<ProductDate>, DataCatalogError> {
2540    let _ = product_convention(center, ProductType::Ionex)?;
2541    let base = target.add_days(predicted_day_offset(center))?;
2542    let mut out = Vec::with_capacity(usize::try_from(lookback).unwrap_or(usize::MAX));
2543    for back in 0..=lookback {
2544        out.push(base.add_days(-i64::from(back))?);
2545    }
2546    Ok(out)
2547}
2548
2549/// Build a daily station observation product.
2550pub fn station_obs(
2551    station: &str,
2552    date: ProductDate,
2553    sample: Option<&str>,
2554) -> Result<StationObservationSpec, DataCatalogError> {
2555    StationObservationSpec::new(station, date, sample.unwrap_or("30S"))
2556}
2557
2558/// Build the canonical RINEX 3 CRINEX filename for a daily station observation.
2559pub fn station_obs_filename(
2560    station: &str,
2561    date: ProductDate,
2562    sample: &str,
2563) -> Result<String, DataCatalogError> {
2564    validate_station(station)?;
2565    validate_sample(sample)?;
2566    Ok(format!(
2567        "{}_R_{}_01D_{}_MO.crx",
2568        station,
2569        date_block(date, None),
2570        sample
2571    ))
2572}
2573
2574/// Build the full BKG IGS archive URL for a daily station observation.
2575pub fn station_obs_url(
2576    station: &str,
2577    date: ProductDate,
2578    sample: &str,
2579) -> Result<String, DataCatalogError> {
2580    let filename = station_obs_filename(station, date, sample)?;
2581    Ok(format!(
2582        "https://igs.bkg.bund.de/root_ftp/IGS/{}/{}.gz",
2583        dir_path(ArchiveLayout::BkgObsYearDoy, date)?,
2584        filename
2585    ))
2586}
2587
2588/// The transfer protocol for the daily station observation archive.
2589#[must_use]
2590pub const fn station_obs_protocol() -> ArchiveProtocol {
2591    ArchiveProtocol::Https
2592}
2593
2594fn validate_terrain_lat_index(lat_index: i32) -> Result<(), DataCatalogError> {
2595    if (MIN_TERRAIN_LAT_INDEX..=MAX_TERRAIN_LAT_INDEX).contains(&lat_index) {
2596        Ok(())
2597    } else {
2598        Err(DataCatalogError::InvalidTileIndex {
2599            lat_index,
2600            lon_index: 0,
2601        })
2602    }
2603}
2604
2605fn validate_terrain_tile_index(lat_index: i32, lon_index: i32) -> Result<(), DataCatalogError> {
2606    if (MIN_TERRAIN_LAT_INDEX..=MAX_TERRAIN_LAT_INDEX).contains(&lat_index)
2607        && (MIN_TERRAIN_LON_INDEX..=MAX_TERRAIN_LON_INDEX).contains(&lon_index)
2608    {
2609        Ok(())
2610    } else {
2611        Err(DataCatalogError::InvalidTileIndex {
2612            lat_index,
2613            lon_index,
2614        })
2615    }
2616}
2617
2618fn validate_hgt_tile_index(lat_index: i32, lon_index: i32) -> Result<(), HgtConversionError> {
2619    if (MIN_TERRAIN_LAT_INDEX..=MAX_TERRAIN_LAT_INDEX).contains(&lat_index)
2620        && (MIN_TERRAIN_LON_INDEX..=MAX_TERRAIN_LON_INDEX).contains(&lon_index)
2621    {
2622        Ok(())
2623    } else {
2624        Err(HgtConversionError::InvalidTileIndex {
2625            lat_index,
2626            lon_index,
2627        })
2628    }
2629}
2630
2631fn dted_coord_field(index: i32, is_longitude: bool) -> String {
2632    let hemi = match (is_longitude, index >= 0) {
2633        (true, true) => 'E',
2634        (true, false) => 'W',
2635        (false, true) => 'N',
2636        (false, false) => 'S',
2637    };
2638    format!("{:03}0000{hemi}", index.abs())
2639}
2640
2641fn encode_dted_signed_magnitude(sample: i16) -> u16 {
2642    if sample == i16::MIN {
2643        0
2644    } else if sample >= 0 {
2645        sample as u16
2646    } else {
2647        0x8000 | (-i32::from(sample) as u16)
2648    }
2649}
2650
2651fn product_type_convention(product_type: ProductType) -> &'static ProductTypeConvention {
2652    PRODUCT_TYPE_CONVENTIONS
2653        .iter()
2654        .find(|descriptor| descriptor.product_type == product_type)
2655        .expect("product descriptor exists for enum variant")
2656}
2657
2658const fn product_format(product_type: ProductType) -> ProductFormat {
2659    match product_type {
2660        ProductType::Sp3 => ProductFormat::Sp3,
2661        ProductType::Ionex => ProductFormat::Ionex,
2662        ProductType::Clk => ProductFormat::RinexClock,
2663        ProductType::Nav => ProductFormat::RinexNavigation,
2664    }
2665}
2666
2667fn validate_official_filename(filename: &str) -> Result<(), DataCatalogError> {
2668    if filename.is_empty()
2669        || filename == "."
2670        || filename == ".."
2671        || filename.contains('/')
2672        || filename.contains('\\')
2673        || filename.contains('\0')
2674        || filename.contains("..")
2675    {
2676        Err(DataCatalogError::InvalidOfficialFilename(
2677            filename.to_string(),
2678        ))
2679    } else {
2680        Ok(())
2681    }
2682}
2683
2684fn validate_product(
2685    center: AnalysisCenter,
2686    product_type: ProductType,
2687    sample: &str,
2688    issue: Option<&str>,
2689) -> Result<&'static CenterProductConvention, DataCatalogError> {
2690    let convention = product_convention(center, product_type)?;
2691    validate_sample(sample)?;
2692    validate_issue_for_center(center, issue)?;
2693    Ok(convention)
2694}
2695
2696fn validate_issue_for_center(
2697    center: AnalysisCenter,
2698    issue: Option<&str>,
2699) -> Result<(), DataCatalogError> {
2700    let entry = center_catalog(center).expect("catalog entry exists for enum variant");
2701    match (entry.issues.is_empty(), issue) {
2702        (true, None) => Ok(()),
2703        (true, Some(_)) => Err(DataCatalogError::UnexpectedIssue { center }),
2704        (false, None) => Err(DataCatalogError::MissingIssue { center }),
2705        (false, Some(issue)) => {
2706            validate_issue(issue)?;
2707            if entry.issues.contains(&issue) {
2708                Ok(())
2709            } else {
2710                Err(DataCatalogError::UnsupportedIssue {
2711                    center,
2712                    issue: issue.to_string(),
2713                })
2714            }
2715        }
2716    }
2717}
2718
2719fn validate_sample(sample: &str) -> Result<(), DataCatalogError> {
2720    let bytes = sample.as_bytes();
2721    let valid = bytes.len() == 3
2722        && bytes[0].is_ascii_digit()
2723        && bytes[1].is_ascii_digit()
2724        && bytes[2].is_ascii_uppercase();
2725    if valid {
2726        Ok(())
2727    } else {
2728        Err(DataCatalogError::InvalidSample(sample.to_string()))
2729    }
2730}
2731
2732fn validate_issue(issue: &str) -> Result<(), DataCatalogError> {
2733    let bytes = issue.as_bytes();
2734    let valid_digits = bytes.len() == 4 && bytes.iter().all(u8::is_ascii_digit);
2735    if !valid_digits {
2736        return Err(DataCatalogError::InvalidIssue(issue.to_string()));
2737    }
2738    let hour = issue[0..2]
2739        .parse::<u8>()
2740        .map_err(|_| DataCatalogError::InvalidIssue(issue.to_string()))?;
2741    let minute = issue[2..4]
2742        .parse::<u8>()
2743        .map_err(|_| DataCatalogError::InvalidIssue(issue.to_string()))?;
2744    if hour <= 23 && minute <= 59 {
2745        Ok(())
2746    } else {
2747        Err(DataCatalogError::InvalidIssue(issue.to_string()))
2748    }
2749}
2750
2751fn validate_station(station: &str) -> Result<(), DataCatalogError> {
2752    let bytes = station.as_bytes();
2753    let valid = bytes.len() == 9
2754        && bytes
2755            .iter()
2756            .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit());
2757    if valid {
2758        Ok(())
2759    } else {
2760        Err(DataCatalogError::InvalidStation(station.to_string()))
2761    }
2762}
2763
2764fn issue_minutes(issue: &str) -> Result<u16, DataCatalogError> {
2765    validate_issue(issue)?;
2766    let hour = issue[0..2]
2767        .parse::<u16>()
2768        .map_err(|_| DataCatalogError::InvalidIssue(issue.to_string()))?;
2769    let minute = issue[2..4]
2770        .parse::<u16>()
2771        .map_err(|_| DataCatalogError::InvalidIssue(issue.to_string()))?;
2772    Ok(hour * 60 + minute)
2773}
2774
2775fn issue_ordering_minutes(date: ProductDate, issue: &str) -> Result<i64, DataCatalogError> {
2776    Ok(date.julian_day_number() * 1_440 + i64::from(issue_minutes(issue)?))
2777}
2778
2779fn date_block(date: ProductDate, issue: Option<&str>) -> String {
2780    format!(
2781        "{}{:03}{}",
2782        date.year,
2783        date.day_of_year(),
2784        issue.unwrap_or("0000")
2785    )
2786}
2787
2788fn dir_path(layout: ArchiveLayout, date: ProductDate) -> Result<String, DataCatalogError> {
2789    Ok(match layout {
2790        ArchiveLayout::GfzRapidWeek => format!("rapid/w{}", date.gps_week()?),
2791        ArchiveLayout::GfzUltraWeek => format!("ultra/w{}", date.gps_week()?),
2792        ArchiveLayout::GpsWeek => date.gps_week()?.to_string(),
2793        ArchiveLayout::BkgProductsWeek => format!("products/{}", date.gps_week()?),
2794        ArchiveLayout::BkgBrdcYearDoy => {
2795            format!("BRDC/{}/{:03}", date.year, date.day_of_year())
2796        }
2797        ArchiveLayout::BkgObsYearDoy => format!("obs/{}/{:03}", date.year, date.day_of_year()),
2798        ArchiveLayout::AiubCodeMgexYear => format!("CODE_MGEX/CODE/{}", date.year),
2799        ArchiveLayout::AiubCodeYear => format!("CODE/{}", date.year),
2800        ArchiveLayout::AiubCodeRoot => "CODE".to_string(),
2801    })
2802}
2803
2804fn product_dir_path(
2805    center: AnalysisCenter,
2806    layout: ArchiveLayout,
2807    date: ProductDate,
2808) -> Result<String, DataCatalogError> {
2809    match center {
2810        AnalysisCenter::CodPrd1 => Ok(format!("CODE/IONO/P1/{}", date.year)),
2811        AnalysisCenter::CodPrd2 => Ok(format!("CODE/IONO/P2/{}", date.year)),
2812        _ => dir_path(layout, date),
2813    }
2814}
2815
2816fn product_date_from_jdn(jdn: i64) -> Result<ProductDate, DataCatalogError> {
2817    let (year, month, day) = civil_from_julian_day_number(jdn);
2818    let year = i32::try_from(year).map_err(|_| DataCatalogError::DateOutOfRange)?;
2819    let month = u8::try_from(month).map_err(|_| DataCatalogError::DateOutOfRange)?;
2820    let day = u8::try_from(day).map_err(|_| DataCatalogError::DateOutOfRange)?;
2821    ProductDate::new(year, month, day).map_err(|_| DataCatalogError::DateOutOfRange)
2822}