1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum AnalysisCenter {
21 Igs,
23 CodRap,
25 CodPrd1,
27 CodPrd2,
29 Esa,
31 Cod,
33 Gfz,
35 IgsUlt,
37 CodUlt,
39 EsaUlt,
41 GfzUlt,
43}
44
45impl AnalysisCenter {
46 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
135pub enum ProductType {
136 Sp3,
138 Clk,
140 Nav,
142 Ionex,
144}
145
146impl ProductType {
147 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
191pub enum ProductPublisher {
192 Igs,
194 Code,
196 Esa,
198 Gfz,
200}
201
202impl ProductPublisher {
203 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
223pub enum SolutionClass {
224 Final,
226 Rapid,
228 UltraRapid,
230 Predicted,
232 Broadcast,
234}
235
236impl SolutionClass {
237 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
270pub enum ProductCampaign {
271 Operational,
273 MultiGnss,
275 MultiGnssExperiment,
277 Broadcast,
279}
280
281impl ProductCampaign {
282 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
296pub enum ProductFormat {
297 Sp3,
299 Ionex,
301 RinexClock,
303 RinexNavigation,
305}
306
307impl ProductFormat {
308 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
325pub enum DistributionSource {
326 Direct,
328 NasaCddis,
330 LocalFile,
332 InMemory,
334}
335
336impl DistributionSource {
337 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
351pub enum SpaceWeatherProduct {
352 All,
354 Last5Years,
356}
357
358impl SpaceWeatherProduct {
359 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
395pub enum ArchiveProtocol {
396 Http,
398 Https,
400}
401
402impl ArchiveProtocol {
403 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
415pub enum ArchiveCompression {
416 Gzip,
418 None,
420}
421
422impl ArchiveCompression {
423 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
442pub enum ArchiveLayout {
443 GfzRapidWeek,
445 GfzUltraWeek,
447 GpsWeek,
449 BkgProductsWeek,
451 BkgBrdcYearDoy,
453 BkgObsYearDoy,
455 AiubCodeMgexYear,
457 AiubCodeYear,
459 AiubCodeRoot,
461}
462
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum ProductFilenameKind {
466 Sampled,
468 Nav,
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474pub struct ProductTypeConvention {
475 pub product_type: ProductType,
477 pub content_code: &'static str,
479 pub extension: &'static str,
481 pub kind: ProductFilenameKind,
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub struct CenterProductConvention {
488 pub product_type: ProductType,
490 pub token: &'static str,
492 pub layout: ArchiveLayout,
494 pub span: &'static str,
496 pub default_sample: &'static str,
498 pub compression: ArchiveCompression,
500}
501
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
504pub struct CenterCatalogEntry {
505 pub center: AnalysisCenter,
507 pub code: &'static str,
509 pub protocol: ArchiveProtocol,
511 pub host: &'static str,
513 pub root_url: &'static str,
515 pub products: &'static [CenterProductConvention],
517 pub issues: &'static [&'static str],
519}
520
521#[derive(Debug, Clone, Copy, PartialEq, Eq)]
523pub struct TerrainSourceEntry {
524 pub protocol: ArchiveProtocol,
526 pub host: &'static str,
528 pub compression: ArchiveCompression,
530 pub root_url: &'static str,
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub struct SpaceWeatherSourceEntry {
537 pub protocol: ArchiveProtocol,
539 pub host: &'static str,
541 pub compression: ArchiveCompression,
543 pub root_url: &'static str,
545}
546
547#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
549pub struct NoOpenMirrorProduct {
550 pub center: &'static str,
552 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 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#[derive(Debug, Clone, PartialEq, Eq)]
905pub enum DataCatalogError {
906 UnknownCenter(String),
908 UnknownProductType(String),
910 UnsupportedProduct {
912 center: AnalysisCenter,
914 product_type: ProductType,
916 },
917 UnsupportedDistribution {
919 source: DistributionSource,
921 product_type: ProductType,
923 },
924 NoDistributionSources,
926 InvalidOfficialFilename(String),
928 InconsistentProductIdentity {
930 field: &'static str,
932 },
933 NoOpenMirror {
935 center: String,
937 product_type: String,
939 },
940 InvalidDate {
942 year: i32,
944 month: u8,
946 day: u8,
948 },
949 DateOutOfRange,
951 DateBeforeGpsEpoch(ProductDate),
953 InvalidGpsDayOfWeek(u8),
955 InvalidSample(String),
957 InvalidIssue(String),
959 MissingIssue {
961 center: AnalysisCenter,
963 },
964 UnexpectedIssue {
966 center: AnalysisCenter,
968 },
969 UnsupportedIssue {
971 center: AnalysisCenter,
973 issue: String,
975 },
976 InvalidDateTime {
978 hour: u8,
980 minute: u8,
982 second: u8,
984 },
985 NoUltraIssue,
987 NoAvailableUltraIssue,
989 InvalidStation(String),
991 InvalidCoordinate {
993 lat_deg_bits: u64,
995 lon_deg_bits: u64,
997 },
998 InvalidTileIndex {
1000 lat_index: i32,
1002 lon_index: i32,
1004 },
1005 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#[derive(Debug, Clone, PartialEq, Eq)]
1096pub enum HgtConversionError {
1097 BadLength {
1099 expected: usize,
1101 got: usize,
1103 },
1104 InvalidTileIndex {
1106 lat_index: i32,
1108 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1151pub struct ProductDate {
1152 pub year: i32,
1154 pub month: u8,
1156 pub day: u8,
1158}
1159
1160impl ProductDate {
1161 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 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 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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1226pub struct ProductDateTime {
1227 pub date: ProductDate,
1229 pub hour: u8,
1231 pub minute: u8,
1233 pub second: u8,
1235}
1236
1237impl ProductDateTime {
1238 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1267pub struct UltraIssue {
1268 pub date: ProductDate,
1270 pub issue: String,
1272}
1273
1274impl UltraIssue {
1275 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#[derive(Debug, Clone, PartialEq, Eq)]
1287pub struct UltraSp3Location {
1288 pub pattern: String,
1290 pub span: String,
1292 pub sample: String,
1294 pub filename: String,
1296 pub url: String,
1298 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1400pub struct ProductIdentity {
1401 pub family: ProductType,
1403 pub publisher: ProductPublisher,
1405 pub solution: SolutionClass,
1407 pub campaign: ProductCampaign,
1409 pub version: u8,
1411 pub date: ProductDate,
1413 pub issue: Option<String>,
1415 pub span: String,
1417 pub sample: String,
1419 pub official_filename: String,
1421 pub format: ProductFormat,
1423 pub prediction_horizon_days: Option<u8>,
1425}
1426
1427impl ProductIdentity {
1428 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 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 pub fn cache_relpath(&self, source: DistributionSource) -> Result<String, DataCatalogError> {
1527 Ok(format!("products/v1/{}/{}", source.code(), self.key()?))
1528 }
1529}
1530
1531#[derive(Debug, Clone, PartialEq, Eq)]
1533pub struct DistributionLocation {
1534 pub source: DistributionSource,
1536 pub original_url: Option<String>,
1538 pub archive_filename: String,
1540 pub compression: ArchiveCompression,
1542}
1543
1544#[derive(Debug, Clone, PartialEq, Eq)]
1546pub struct ProductRequest {
1547 pub identity: ProductIdentity,
1549 pub distributors: Vec<DistributionSource>,
1551}
1552
1553#[derive(Debug, Clone, PartialEq, Eq)]
1555pub enum ExactProductSetError {
1556 EmptyExpected,
1558 InvalidExpected {
1560 index: usize,
1562 source: DataCatalogError,
1564 },
1565 InvalidAvailable {
1567 index: usize,
1569 source: DataCatalogError,
1571 },
1572 Mismatch {
1574 missing: Vec<ProductIdentity>,
1576 unexpected: Vec<ProductIdentity>,
1578 duplicate_expected: Vec<ProductIdentity>,
1580 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
1614pub 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 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#[derive(Debug, Clone, PartialEq, Eq)]
1726pub struct ProductSpec {
1727 pub center: AnalysisCenter,
1729 pub product_type: ProductType,
1731 pub date: ProductDate,
1733 pub sample: String,
1735 pub issue: Option<String>,
1737}
1738
1739impl ProductSpec {
1740 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 pub fn gps_week(&self) -> Result<u32, DataCatalogError> {
1760 self.date.gps_week()
1761 }
1762
1763 #[must_use]
1765 pub fn day_of_year(&self) -> u16 {
1766 self.date.day_of_year()
1767 }
1768
1769 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
1901pub struct StationObservationSpec {
1902 pub station: String,
1904 pub date: ProductDate,
1906 pub sample: String,
1908}
1909
1910impl StationObservationSpec {
1911 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 pub fn canonical_filename(&self) -> Result<String, DataCatalogError> {
1924 station_obs_filename(&self.station, self.date, &self.sample)
1925 }
1926
1927 pub fn archive_url(&self) -> Result<String, DataCatalogError> {
1929 station_obs_url(&self.station, self.date, &self.sample)
1930 }
1931}
1932
1933#[must_use]
1935pub const fn catalog() -> &'static [CenterCatalogEntry] {
1936 &CATALOG
1937}
1938
1939#[must_use]
1941pub const fn centers() -> &'static [AnalysisCenter] {
1942 &CENTER_ORDER
1943}
1944
1945#[must_use]
1947pub const fn product_types() -> &'static [ProductTypeConvention] {
1948 &PRODUCT_TYPE_CONVENTIONS
1949}
1950
1951#[must_use]
1953pub const fn allowed_hosts() -> &'static [&'static str] {
1954 &ALLOWED_HOSTS
1955}
1956
1957#[must_use]
1959pub const fn skadi_source_entry() -> TerrainSourceEntry {
1960 SKADI_SOURCE
1961}
1962
1963#[must_use]
1965pub const fn space_weather_source_entry() -> SpaceWeatherSourceEntry {
1966 CELESTRAK_SPACE_WEATHER_SOURCE
1967}
1968
1969#[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#[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#[must_use]
1990pub fn space_weather_cache_relpath(product: SpaceWeatherProduct) -> String {
1991 format!("space-weather/{}", space_weather_filename(product))
1992}
1993
1994pub 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
2006pub 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
2013pub 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
2026pub 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
2037pub 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
2043pub 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
2052pub 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
2080pub 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
2104pub 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#[must_use]
2162pub const fn no_open_mirrors() -> &'static [NoOpenMirrorProduct] {
2163 &NO_OPEN_MIRRORS
2164}
2165
2166pub fn open_mirror(
2168 center: AnalysisCenter,
2169 product_type: ProductType,
2170) -> Result<(), DataCatalogError> {
2171 open_mirror_code(center.code(), product_type.code())
2172}
2173
2174pub 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#[must_use]
2191pub fn center_catalog(center: AnalysisCenter) -> Option<&'static CenterCatalogEntry> {
2192 CATALOG.iter().find(|entry| entry.center == center)
2193}
2194
2195pub 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
2212pub 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
2220pub fn gps_week(date: ProductDate) -> Result<u32, DataCatalogError> {
2222 date.gps_week()
2223}
2224
2225#[must_use]
2227pub fn day_of_year(date: ProductDate) -> u16 {
2228 date.day_of_year()
2229}
2230
2231pub 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
2246pub 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
2257pub 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
2268pub 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
2279pub 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
2291pub 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
2316pub 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
2325pub 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
2334pub 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
2343pub 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#[must_use]
2359pub const fn predicted_day_offset(center: AnalysisCenter) -> i64 {
2360 match center {
2361 AnalysisCenter::CodPrd2 => 1,
2362 _ => 0,
2363 }
2364}
2365
2366pub 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
2384pub 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
2393pub 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
2404pub 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
2463pub 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
2474pub 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
2485pub 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
2510pub 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
2534pub 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
2549pub 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
2558pub 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
2574pub 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#[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}