brahe 1.4.0

Brahe is a modern satellite dynamics library for research and engineering applications designed to be easy-to-learn, high-performance, and quick-to-deploy. The north-star of the development is enabling users to solve meaningful problems and answer questions quickly, easily, and correctly.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/*!
 * SpaceTrack query builder.
 *
 * Provides a fluent builder API for constructing Space-Track.org API queries.
 * The builder produces URL path strings that are appended to the base URL
 * by the client.
 *
 * The Space-Track API uses a path-based query format:
 * `/<controller>/query/class/<class>/FIELD/value/.../format/<format>`
 */

use crate::spacetrack::types::{OutputFormat, RequestClass, RequestController, SortOrder};

/// Percent-encode characters that are invalid in URI path segments.
///
/// Encodes `>`, `<`, and `^` which are used by SpaceTrack filter operators
/// but are not valid URI path characters per RFC 3986.
fn encode_path_value(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '>' => result.push_str("%3E"),
            '<' => result.push_str("%3C"),
            '^' => result.push_str("%5E"),
            _ => result.push(c),
        }
    }
    result
}

/// A filter predicate for a SpaceTrack query.
#[derive(Debug, Clone)]
struct Filter {
    field: String,
    value: String,
}

/// An ordering clause for a SpaceTrack query.
#[derive(Debug, Clone)]
struct OrderBy {
    field: String,
    order: SortOrder,
}

/// Builder for constructing SpaceTrack API queries.
///
/// Uses a fluent API where each method returns `Self` to allow method chaining.
/// Call `build()` to produce the URL path string.
///
/// # Examples
///
/// ```
/// use brahe::spacetrack::{SpaceTrackQuery, RequestClass, SortOrder, OutputFormat};
///
/// // Query latest GP data for ISS
/// let query = SpaceTrackQuery::new(RequestClass::GP)
///     .filter("NORAD_CAT_ID", "25544")
///     .order_by("EPOCH", SortOrder::Desc)
///     .limit(1);
///
/// let url_path = query.build();
/// assert!(url_path.contains("/class/gp/"));
/// assert!(url_path.contains("/NORAD_CAT_ID/25544/"));
///
/// // Query with custom format
/// let query = SpaceTrackQuery::new(RequestClass::GP)
///     .filter("NORAD_CAT_ID", "25544")
///     .format(OutputFormat::TLE);
///
/// let url_path = query.build();
/// assert!(url_path.contains("/format/tle"));
/// ```
#[derive(Debug, Clone)]
pub struct SpaceTrackQuery {
    controller: RequestController,
    class: RequestClass,
    filters: Vec<Filter>,
    order_by: Vec<OrderBy>,
    limit_count: Option<u32>,
    limit_offset: Option<u32>,
    output_format: Option<OutputFormat>,
    predicates: Vec<String>,
    metadata: bool,
    distinct: bool,
    empty_result: bool,
    favorites: Option<String>,
}

impl SpaceTrackQuery {
    /// Create a new query builder for the specified request class.
    ///
    /// Uses the default controller for the request class.
    ///
    /// # Arguments
    ///
    /// * `class` - The request class to query
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::spacetrack::{SpaceTrackQuery, RequestClass};
    ///
    /// let query = SpaceTrackQuery::new(RequestClass::GP);
    /// ```
    pub fn new(class: RequestClass) -> Self {
        SpaceTrackQuery {
            controller: class.default_controller(),
            class,
            filters: Vec::new(),
            order_by: Vec::new(),
            limit_count: None,
            limit_offset: None,
            output_format: None,
            predicates: Vec::new(),
            metadata: false,
            distinct: false,
            empty_result: false,
            favorites: None,
        }
    }

    /// Override the default controller for this query.
    ///
    /// Most users will not need to call this method, as each request class
    /// has an appropriate default controller.
    ///
    /// # Arguments
    ///
    /// * `controller` - The controller to use
    pub fn controller(mut self, controller: RequestController) -> Self {
        self.controller = controller;
        self
    }

    /// Add a filter predicate to the query.
    ///
    /// Filters restrict the results to records where the specified field matches
    /// the given value. Use operator functions from the `operators` module to
    /// construct comparison values (e.g., `operators::greater_than("25544")`).
    ///
    /// # Arguments
    ///
    /// * `field` - The field name (e.g., "NORAD_CAT_ID", "EPOCH")
    /// * `value` - The filter value, optionally with operator prefix
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::spacetrack::{SpaceTrackQuery, RequestClass, operators};
    ///
    /// let query = SpaceTrackQuery::new(RequestClass::GP)
    ///     .filter("NORAD_CAT_ID", "25544")
    ///     .filter("EPOCH", &operators::greater_than("2024-01-01"));
    /// ```
    pub fn filter(mut self, field: &str, value: &str) -> Self {
        self.filters.push(Filter {
            field: field.to_string(),
            value: value.to_string(),
        });
        self
    }

    /// Add an ordering clause to the query.
    ///
    /// Multiple order_by calls are cumulative - records are sorted by the
    /// first field, then by subsequent fields for ties.
    ///
    /// # Arguments
    ///
    /// * `field` - The field to sort by
    /// * `order` - The sort direction (ascending or descending)
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::spacetrack::{SpaceTrackQuery, RequestClass, SortOrder};
    ///
    /// let query = SpaceTrackQuery::new(RequestClass::GP)
    ///     .order_by("EPOCH", SortOrder::Desc);
    /// ```
    pub fn order_by(mut self, field: &str, order: SortOrder) -> Self {
        self.order_by.push(OrderBy {
            field: field.to_string(),
            order,
        });
        self
    }

    /// Set the maximum number of results to return.
    ///
    /// # Arguments
    ///
    /// * `count` - Maximum number of records
    pub fn limit(mut self, count: u32) -> Self {
        self.limit_count = Some(count);
        self
    }

    /// Set the maximum number of results and an offset.
    ///
    /// # Arguments
    ///
    /// * `count` - Maximum number of records
    /// * `offset` - Number of records to skip
    pub fn limit_offset(mut self, count: u32, offset: u32) -> Self {
        self.limit_count = Some(count);
        self.limit_offset = Some(offset);
        self
    }

    /// Set the output format for query results.
    ///
    /// If not specified, defaults to JSON.
    ///
    /// # Arguments
    ///
    /// * `format` - The desired output format
    pub fn format(mut self, format: OutputFormat) -> Self {
        self.output_format = Some(format);
        self
    }

    /// Specify which fields to include in the response.
    ///
    /// This is a predicates filter that limits which fields are returned
    /// for each record. Useful for reducing response size.
    ///
    /// # Arguments
    ///
    /// * `fields` - Slice of field names to include
    pub fn predicates_filter(mut self, fields: &[&str]) -> Self {
        self.predicates = fields.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Enable or disable metadata in the response.
    ///
    /// When enabled, the response includes query metadata (e.g., total count).
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to include metadata
    pub fn metadata(mut self, enabled: bool) -> Self {
        self.metadata = enabled;
        self
    }

    /// Enable or disable distinct results.
    ///
    /// When enabled, duplicate records are removed from the results.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to return distinct results
    pub fn distinct(mut self, enabled: bool) -> Self {
        self.distinct = enabled;
        self
    }

    /// Enable or disable empty result return.
    ///
    /// When enabled, an empty query (no results) returns an empty array/set
    /// instead of an error response.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to allow empty results
    pub fn empty_result(mut self, enabled: bool) -> Self {
        self.empty_result = enabled;
        self
    }

    /// Set a favorites filter for the query.
    ///
    /// # Arguments
    ///
    /// * `favorites` - The favorites identifier
    pub fn favorites(mut self, favorites: &str) -> Self {
        self.favorites = Some(favorites.to_string());
        self
    }

    /// Build the URL path string for this query.
    ///
    /// Produces the path portion of the Space-Track API URL, which should
    /// be appended to the base URL and authentication endpoint.
    ///
    /// # Returns
    ///
    /// * `String` - The URL path string for this query
    ///
    /// # Examples
    ///
    /// ```
    /// use brahe::spacetrack::{SpaceTrackQuery, RequestClass, SortOrder};
    ///
    /// let query = SpaceTrackQuery::new(RequestClass::GP)
    ///     .filter("NORAD_CAT_ID", "25544")
    ///     .order_by("EPOCH", SortOrder::Desc)
    ///     .limit(1);
    ///
    /// let path = query.build();
    /// assert_eq!(
    ///     path,
    ///     "/basicspacedata/query/class/gp/NORAD_CAT_ID/25544/orderby/EPOCH%20desc/limit/1/format/json"
    /// );
    /// ```
    pub fn build(&self) -> String {
        let mut parts = Vec::new();

        // Controller and query prefix
        parts.push(format!(
            "/{}/query/class/{}",
            self.controller.as_str(),
            self.class.as_str()
        ));

        // Filters (percent-encode operator characters in values)
        for filter in &self.filters {
            parts.push(format!(
                "/{}/{}",
                filter.field,
                encode_path_value(&filter.value)
            ));
        }

        // Order by
        if !self.order_by.is_empty() {
            let order_str: Vec<String> = self
                .order_by
                .iter()
                .map(|o| format!("{}%20{}", o.field, o.order.as_str()))
                .collect();
            parts.push(format!("/orderby/{}", order_str.join(",")));
        }

        // Limit
        if let Some(count) = self.limit_count {
            if let Some(offset) = self.limit_offset {
                parts.push(format!("/limit/{},{}", count, offset));
            } else {
                parts.push(format!("/limit/{}", count));
            }
        }

        // Predicates filter
        if !self.predicates.is_empty() {
            parts.push(format!("/predicates/{}", self.predicates.join(",")));
        }

        // Metadata
        if self.metadata {
            parts.push("/metadata/true".to_string());
        }

        // Distinct
        if self.distinct {
            parts.push("/distinct/true".to_string());
        }

        // Empty result
        if self.empty_result {
            parts.push("/emptyresult/show".to_string());
        }

        // Favorites
        if let Some(ref fav) = self.favorites {
            parts.push(format!("/favorites/{}", fav));
        }

        // Format (default to JSON)
        let format = self.output_format.unwrap_or(OutputFormat::JSON);
        parts.push(format!("/format/{}", format.as_str()));

        parts.concat()
    }

    /// Returns the output format for this query.
    ///
    /// Returns `OutputFormat::JSON` if no format has been explicitly set.
    pub fn output_format(&self) -> OutputFormat {
        self.output_format.unwrap_or(OutputFormat::JSON)
    }

    /// Returns the request class for this query.
    pub fn request_class(&self) -> RequestClass {
        self.class
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use crate::spacetrack::operators;

    #[test]
    fn test_basic_query() {
        let query = SpaceTrackQuery::new(RequestClass::GP);
        let path = query.build();
        assert_eq!(path, "/basicspacedata/query/class/gp/format/json");
    }

    #[test]
    fn test_query_with_filter() {
        let query = SpaceTrackQuery::new(RequestClass::GP).filter("NORAD_CAT_ID", "25544");

        let path = query.build();
        assert_eq!(
            path,
            "/basicspacedata/query/class/gp/NORAD_CAT_ID/25544/format/json"
        );
    }

    #[test]
    fn test_query_with_multiple_filters() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .filter("EPOCH", &operators::greater_than("2024-01-01"));

        let path = query.build();
        assert!(path.contains("/NORAD_CAT_ID/25544/"));
        assert!(path.contains("/EPOCH/%3E2024-01-01/"));
    }

    #[test]
    fn test_query_with_order_by() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .order_by("EPOCH", SortOrder::Desc);

        let path = query.build();
        assert!(path.contains("/orderby/EPOCH%20desc/"));
    }

    #[test]
    fn test_query_with_multiple_order_by() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .order_by("EPOCH", SortOrder::Desc)
            .order_by("NORAD_CAT_ID", SortOrder::Asc);

        let path = query.build();
        assert!(path.contains("/orderby/EPOCH%20desc,NORAD_CAT_ID%20asc/"));
    }

    #[test]
    fn test_query_with_limit() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .limit(5);

        let path = query.build();
        assert!(path.contains("/limit/5/"));
    }

    #[test]
    fn test_query_with_limit_offset() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .limit_offset(10, 20);

        let path = query.build();
        assert!(path.contains("/limit/10,20/"));
    }

    #[test]
    fn test_query_with_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .format(OutputFormat::TLE);

        let path = query.build();
        assert!(path.ends_with("/format/tle"));
    }

    #[test]
    fn test_query_with_3le_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .format(OutputFormat::ThreeLe);

        let path = query.build();
        assert!(path.ends_with("/format/3le"));
    }

    #[test]
    fn test_query_with_predicates() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .predicates_filter(&["NORAD_CAT_ID", "OBJECT_NAME", "EPOCH"]);

        let path = query.build();
        assert!(path.contains("/predicates/NORAD_CAT_ID,OBJECT_NAME,EPOCH/"));
    }

    #[test]
    fn test_query_with_metadata() {
        let query = SpaceTrackQuery::new(RequestClass::GP).metadata(true);

        let path = query.build();
        assert!(path.contains("/metadata/true"));
    }

    #[test]
    fn test_query_with_distinct() {
        let query = SpaceTrackQuery::new(RequestClass::GP).distinct(true);

        let path = query.build();
        assert!(path.contains("/distinct/true"));
    }

    #[test]
    fn test_query_with_empty_result() {
        let query = SpaceTrackQuery::new(RequestClass::GP).empty_result(true);

        let path = query.build();
        assert!(path.contains("/emptyresult/show"));
    }

    #[test]
    fn test_query_with_favorites() {
        let query = SpaceTrackQuery::new(RequestClass::GP).favorites("my_favorites");

        let path = query.build();
        assert!(path.contains("/favorites/my_favorites/"));
    }

    #[test]
    fn test_query_with_custom_controller() {
        let query =
            SpaceTrackQuery::new(RequestClass::GP).controller(RequestController::ExpandedSpaceData);

        let path = query.build();
        assert!(path.starts_with("/expandedspacedata/"));
    }

    #[test]
    fn test_query_cdm_public_default_controller() {
        let query = SpaceTrackQuery::new(RequestClass::CDMPublic);

        let path = query.build();
        assert!(path.starts_with("/basicspacedata/"));
    }

    #[test]
    fn test_query_satcat() {
        let query = SpaceTrackQuery::new(RequestClass::SATCAT)
            .filter("NORAD_CAT_ID", "25544")
            .limit(1);

        let path = query.build();
        assert_eq!(
            path,
            "/basicspacedata/query/class/satcat/NORAD_CAT_ID/25544/limit/1/format/json"
        );
    }

    #[test]
    fn test_full_query() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .order_by("EPOCH", SortOrder::Desc)
            .limit(1);

        let path = query.build();
        assert_eq!(
            path,
            "/basicspacedata/query/class/gp/NORAD_CAT_ID/25544/orderby/EPOCH%20desc/limit/1/format/json"
        );
    }

    #[test]
    fn test_query_with_operators() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("EPOCH", &operators::greater_than(operators::now_offset(-7)))
            .filter("ECCENTRICITY", &operators::less_than("0.01"))
            .filter("OBJECT_TYPE", &operators::not_equal("DEBRIS"))
            .filter("NORAD_CAT_ID", &operators::inclusive_range(25544, 25600))
            .format(OutputFormat::JSON);

        let path = query.build();
        assert!(path.contains("/EPOCH/%3Enow-7/"));
        assert!(path.contains("/ECCENTRICITY/%3C0.01/"));
        assert!(path.contains("/OBJECT_TYPE/%3C%3EDEBRIS/"));
        assert!(path.contains("/NORAD_CAT_ID/25544--25600/"));
    }

    #[test]
    fn test_query_output_format_accessor() {
        let query = SpaceTrackQuery::new(RequestClass::GP);
        assert_eq!(query.output_format(), OutputFormat::JSON);

        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::TLE);
        assert_eq!(query.output_format(), OutputFormat::TLE);
    }

    #[test]
    fn test_query_request_class_accessor() {
        let query = SpaceTrackQuery::new(RequestClass::GP);
        assert_eq!(query.request_class(), RequestClass::GP);

        let query = SpaceTrackQuery::new(RequestClass::SATCAT);
        assert_eq!(query.request_class(), RequestClass::SATCAT);
    }

    #[test]
    fn test_query_clone() {
        let query = SpaceTrackQuery::new(RequestClass::GP)
            .filter("NORAD_CAT_ID", "25544")
            .limit(1);

        let cloned = query.clone();
        assert_eq!(query.build(), cloned.build());
    }

    #[test]
    fn test_query_metadata_false_not_in_url() {
        let query = SpaceTrackQuery::new(RequestClass::GP).metadata(false);

        let path = query.build();
        assert!(!path.contains("metadata"));
    }

    #[test]
    fn test_query_distinct_false_not_in_url() {
        let query = SpaceTrackQuery::new(RequestClass::GP).distinct(false);

        let path = query.build();
        assert!(!path.contains("distinct"));
    }

    #[test]
    fn test_query_empty_result_false_not_in_url() {
        let query = SpaceTrackQuery::new(RequestClass::GP).empty_result(false);

        let path = query.build();
        assert!(!path.contains("emptyresult"));
    }

    #[test]
    fn test_all_request_classes() {
        let classes = vec![
            RequestClass::GP,
            RequestClass::GPHistory,
            RequestClass::SATCAT,
            RequestClass::SATCATChange,
            RequestClass::SATCATDebut,
            RequestClass::Decay,
            RequestClass::TIP,
            RequestClass::CDMPublic,
            RequestClass::Boxscore,
            RequestClass::Announcement,
            RequestClass::LaunchSite,
        ];

        for class in classes {
            let query = SpaceTrackQuery::new(class);
            let path = query.build();
            assert!(path.contains(&format!("/class/{}/", class.as_str())));
        }
    }

    #[test]
    fn test_query_with_xml_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::XML);
        let path = query.build();
        assert!(path.ends_with("/format/xml"));
    }

    #[test]
    fn test_query_with_html_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::HTML);
        let path = query.build();
        assert!(path.ends_with("/format/html"));
    }

    #[test]
    fn test_query_with_csv_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::CSV);
        let path = query.build();
        assert!(path.ends_with("/format/csv"));
    }

    #[test]
    fn test_query_with_kvn_format() {
        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::KVN);
        let path = query.build();
        assert!(path.ends_with("/format/kvn"));
    }

    #[test]
    fn test_query_with_json_format_explicit() {
        let query = SpaceTrackQuery::new(RequestClass::GP).format(OutputFormat::JSON);
        let path = query.build();
        assert!(path.ends_with("/format/json"));
    }

    #[test]
    fn test_query_with_all_controllers() {
        let controllers = vec![
            (RequestController::BasicSpaceData, "basicspacedata"),
            (RequestController::ExpandedSpaceData, "expandedspacedata"),
            (RequestController::FileShare, "fileshare"),
            (RequestController::PublicFiles, "publicfiles"),
        ];

        for (controller, expected) in controllers {
            let query = SpaceTrackQuery::new(RequestClass::GP).controller(controller);
            let path = query.build();
            assert!(
                path.starts_with(&format!("/{}/", expected)),
                "Expected path to start with /{expected}/, got: {path}"
            );
        }
    }
}