horizon-sdk 9.0.0

Canonical Rust data access layer for the Horizon platform
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
//! Domain model types for the Horizon platform.
//!
//! Each struct maps to a table in the `horizon_public` `PostgreSQL` schema.
//! Fields use `Option` where the database column is nullable or has a server-side default.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::error::BoxDynError;
use sqlx::postgres::{PgTypeInfo, PgValueRef};
use uuid::Uuid;

use crate::types::error::{HorizonError, Result as HorizonResult};

/// Minimum byte length for a `PostgreSQL` `POINT` binary value.
const POINT_BYTE_LEN: usize = 16;

/// A geographic position as (longitude, latitude).
///
/// Maps to `PostgreSQL` `POINT` type with native sqlx decode support.
/// The binary wire format is two big-endian `f64` values (x, y).
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Position(pub f64, pub f64);

impl sqlx::Type<sqlx::Postgres> for Position {
    fn compatible(ty: &PgTypeInfo) -> bool {
        *ty == Self::type_info()
    }

    fn type_info() -> PgTypeInfo {
        PgTypeInfo::with_name("POINT")
    }
}

#[allow(
    clippy::as_conversions,
    clippy::indexing_slicing,
    clippy::std_instead_of_core,
    clippy::big_endian_bytes,
    clippy::float_arithmetic,
    reason = "byte slicing, Box cast, and BE f64 decode required for PostgreSQL POINT wire format"
)]
impl<'de> sqlx::Decode<'de, sqlx::Postgres> for Position {
    fn decode(value: PgValueRef<'de>) -> Result<Self, BoxDynError> {
        let buf = <&[u8] as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
        if buf.len() < POINT_BYTE_LEN {
            return Err("POINT requires 16 bytes".into());
        }
        let (x_bytes, rest) = buf.split_at(8_usize);
        let x = f64::from_be_bytes(
            x_bytes
                .try_into()
                .map_err(|err| Box::new(err) as BoxDynError)?,
        );
        let y = f64::from_be_bytes(
            rest[..8]
                .try_into()
                .map_err(|err| Box::new(err) as BoxDynError)?,
        );
        Ok(Self(x, y))
    }
}

/// A label/annotation on a platform.
///
/// Time and value coordinates describe the labeled region. `time_coordinates`
/// pairs with `value_coordinates` element-wise (a point, line, or polygon
/// depending on length). `bearing_time_record_specification_id` and
/// `spectrogram_specification_id` are mutually exclusive — only one may be
/// set. `data_stream_id` is `None` for legacy platform-wide rows; inserts
/// require `Some(...)`. User attribution is managed by database triggers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Annotation {
    pub bearing_time_record_specification_id: Option<Uuid>,
    pub confidence: Option<f64>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub data_stream_id: Option<Uuid>,
    pub duration_seconds: Option<i32>,
    pub feed_context: Option<serde_json::Value>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub notes: Option<String>,
    pub ontology_class_id: Option<Uuid>,
    pub organization_id: Option<Uuid>,
    pub parent_annotation_id: Option<Uuid>,
    pub platform_id: Uuid,
    pub spectrogram_specification_id: Option<Uuid>,
    pub time_coordinates: Vec<DateTime<Utc>>,
    pub value_coordinates: Vec<f64>,
}

/// A specification for audio data processing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AudioSpecification {
    pub bit_depth: i64,
    pub channel_count: i64,
    pub channel_index: i64,
    pub created_datetime: Option<DateTime<Utc>>,
    pub encoding: String,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub sample_rate: i64,
}

/// A specification for beamgram data processing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BeamgramSpecification {
    pub center_bearing: Option<f64>,
    pub center_bin_width: Option<f64>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub elevation_increment: Option<f64>,
    pub fft_sample_count: Option<i32>,
    pub id: Option<Uuid>,
    pub lower_elevation: Option<f64>,
    pub max_frequency: Option<f64>,
    pub min_frequency: Option<f64>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub normalizer: Option<String>,
    pub organization_id: Option<Uuid>,
    pub update_rate_ms: Option<i64>,
    pub upper_elevation: Option<f64>,
}

/// A user-defined alias for a bearing resolution, naming a bearing bin count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BearingResolutionAlias {
    pub bearing_bin_count: Option<i32>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// A specification for bearing-time record data processing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BearingTimeRecordSpecification {
    pub amplitude_unit_mode: Option<String>,
    pub baffle_bearing_list: Option<Vec<f64>>,
    pub bearing_bin_count: Option<i32>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub elevation_increment: Option<f64>,
    pub fft_sample_count: Option<i32>,
    pub focus_range: Option<String>,
    pub frequency_spacing: Option<f64>,
    pub heading_data_type: Option<String>,
    pub heading_vector_index: Option<i32>,
    pub id: Option<Uuid>,
    pub lower_elevation: Option<f64>,
    pub max_frequency: Option<f64>,
    pub max_pixel: Option<i32>,
    pub min_frequency: Option<f64>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub normalizer: Option<String>,
    pub organization_id: Option<Uuid>,
    pub update_rate_ms: Option<i64>,
    pub upper_elevation: Option<f64>,
}

/// Discriminator for a [`VariantDataRow`] payload arm.
///
/// Stored as text in Postgres/Iceberg. Legacy rows may have `variant = NULL`
/// and still carry a vector payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum DataRowVariant {
    Float32,
    Float32Array,
    Float64,
    Float64Array,
    Int,
    IntArray,
    String,
    Struct,
    Vector,
}

impl DataRowVariant {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Float32 => "float32",
            Self::Float32Array => "float32_array",
            Self::Float64 => "float64",
            Self::Float64Array => "float64_array",
            Self::Int => "int",
            Self::IntArray => "int_array",
            Self::String => "string",
            Self::Struct => "struct",
            Self::Vector => "vector",
        }
    }

    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "float32" => Some(Self::Float32),
            "float32_array" => Some(Self::Float32Array),
            "float64" => Some(Self::Float64),
            "float64_array" => Some(Self::Float64Array),
            "int" => Some(Self::Int),
            "int_array" => Some(Self::IntArray),
            "string" => Some(Self::String),
            "struct" => Some(Self::Struct),
            "vector" => Some(Self::Vector),
            _ => None,
        }
    }

    /// Column name for the payload arm this variant selects.
    #[must_use]
    pub const fn payload_arm(self) -> &'static str {
        match self {
            Self::Float32 => "payload_float32",
            Self::Float32Array => "payload_float32_array",
            Self::Float64 => "payload_float64",
            Self::Float64Array => "payload_float64_array",
            Self::Int => "payload_int",
            Self::IntArray => "payload_int_array",
            Self::String => "payload_string",
            Self::Struct => "payload_struct",
            Self::Vector => "vector",
        }
    }
}

/// Typed payload carried by a [`VariantDataRow`].
///
/// Exactly one arm is active. Unstructured data uses [`DataRowPayload::Struct`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum DataRowPayload {
    Float32(f32),
    Float32Array(Vec<f32>),
    Float64(f64),
    Float64Array(Vec<f64>),
    Int(i32),
    IntArray(Vec<i32>),
    String(String),
    /// Unstructured JSON. Serialized as `jsonb` in Postgres and JSON text in Iceberg.
    Struct(serde_json::Value),
    Vector {
        vector: Vec<f64>,
        vector_end_bound: f64,
        vector_start_bound: f64,
    },
}

impl DataRowPayload {
    #[must_use]
    pub const fn variant(&self) -> DataRowVariant {
        match self {
            Self::Float32(_) => DataRowVariant::Float32,
            Self::Float32Array(_) => DataRowVariant::Float32Array,
            Self::Float64(_) => DataRowVariant::Float64,
            Self::Float64Array(_) => DataRowVariant::Float64Array,
            Self::Int(_) => DataRowVariant::Int,
            Self::IntArray(_) => DataRowVariant::IntArray,
            Self::String(_) => DataRowVariant::String,
            Self::Struct(_) => DataRowVariant::Struct,
            Self::Vector { .. } => DataRowVariant::Vector,
        }
    }
}

/// A vector row of data in the `data_row` table.
///
/// This preserves the original Rust SDK model used by existing stream
/// producers. Convert it to [`VariantDataRow`] at storage boundaries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataRow {
    pub created_datetime: Option<DateTime<Utc>>,
    pub data_stream_id: Uuid,
    pub data_type: String,
    pub datetime: DateTime<Utc>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub specification_id: Uuid,
    pub vector: Vec<f64>,
    pub vector_end_bound: f64,
    pub vector_start_bound: f64,
}

/// A row with any supported payload variant in the `data_row` table.
///
/// This type is used for both Postgres inserts and Arrow IPC serialization.
/// Payload columns are flat `Option` fields so `sqlx` can map them directly;
/// use [`VariantDataRow::from_payload`] / [`VariantDataRow::payload`] for the typed union.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VariantDataRow {
    pub created_datetime: Option<DateTime<Utc>>,
    pub data_stream_id: Uuid,
    pub data_type: String,
    pub datetime: DateTime<Utc>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub payload_float32: Option<f32>,
    pub payload_float32_array: Option<Vec<f32>>,
    pub payload_float64: Option<f64>,
    pub payload_float64_array: Option<Vec<f64>>,
    pub payload_int: Option<i32>,
    pub payload_int_array: Option<Vec<i32>>,
    pub payload_string: Option<String>,
    pub payload_struct: Option<serde_json::Value>,
    pub specification_id: Uuid,
    pub variant: Option<String>,
    pub vector: Option<Vec<f64>>,
    pub vector_end_bound: Option<f64>,
    pub vector_start_bound: Option<f64>,
}

impl VariantDataRow {
    /// Build a row from a typed payload, setting `variant` and clearing unused columns.
    #[must_use]
    pub fn from_payload(
        data_stream_id: Uuid,
        datetime: DateTime<Utc>,
        data_type: String,
        specification_id: Uuid,
        payload: DataRowPayload,
    ) -> Self {
        let mut row = Self {
            created_datetime: None,
            data_stream_id,
            data_type,
            datetime,
            modified_datetime: None,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id,
            variant: Some(payload.variant().as_str().to_owned()),
            vector: None,
            vector_end_bound: None,
            vector_start_bound: None,
        };
        match payload {
            DataRowPayload::Float32(value) => row.payload_float32 = Some(value),
            DataRowPayload::Float32Array(value_list) => {
                row.payload_float32_array = Some(value_list);
            }
            DataRowPayload::Float64(value) => row.payload_float64 = Some(value),
            DataRowPayload::Float64Array(value_list) => {
                row.payload_float64_array = Some(value_list);
            }
            DataRowPayload::Int(value) => row.payload_int = Some(value),
            DataRowPayload::IntArray(value_list) => row.payload_int_array = Some(value_list),
            DataRowPayload::String(value) => row.payload_string = Some(value),
            DataRowPayload::Struct(value) => row.payload_struct = Some(value),
            DataRowPayload::Vector {
                vector,
                vector_end_bound,
                vector_start_bound,
            } => {
                row.vector = Some(vector);
                row.vector_end_bound = Some(vector_end_bound);
                row.vector_start_bound = Some(vector_start_bound);
            }
        }
        row
    }

    /// Resolve the active payload arm.
    ///
    /// Legacy rows (`variant` null with a vector present) map to
    /// [`DataRowPayload::Vector`]. An unrecognized non-null `variant` fails
    /// even when `vector` is populated.
    pub fn payload(&self) -> Option<DataRowPayload> {
        let variant = match self.variant.as_deref() {
            None if self.vector.is_some() => DataRowVariant::Vector,
            None => return None,
            Some(variant_text) => DataRowVariant::parse(variant_text)?,
        };

        match variant {
            DataRowVariant::Float32 => self.payload_float32.map(DataRowPayload::Float32),
            DataRowVariant::Float32Array => self
                .payload_float32_array
                .clone()
                .map(DataRowPayload::Float32Array),
            DataRowVariant::Float64 => self.payload_float64.map(DataRowPayload::Float64),
            DataRowVariant::Float64Array => self
                .payload_float64_array
                .clone()
                .map(DataRowPayload::Float64Array),
            DataRowVariant::Int => self.payload_int.map(DataRowPayload::Int),
            DataRowVariant::IntArray => {
                self.payload_int_array.clone().map(DataRowPayload::IntArray)
            }
            DataRowVariant::String => self.payload_string.clone().map(DataRowPayload::String),
            DataRowVariant::Struct => self.payload_struct.clone().map(DataRowPayload::Struct),
            DataRowVariant::Vector => {
                let vector = self.vector.clone()?;
                let vector_end_bound = self.vector_end_bound?;
                let vector_start_bound = self.vector_start_bound?;
                Some(DataRowPayload::Vector {
                    vector,
                    vector_end_bound,
                    vector_start_bound,
                })
            }
        }
    }

    /// Require exactly one of `vector` / `payload_*` and a matching `variant`.
    ///
    /// Legacy rows may omit `variant` when only `vector` is set. A `vector` arm
    /// also requires both `vector_start_bound` and `vector_end_bound` so
    /// [`Self::payload`] can resolve it. Call this before Postgres writes and
    /// Arrow serialization so rows built outside [`Self::from_payload`] cannot
    /// persist mixed, mismatched, or incomplete payloads.
    ///
    /// # Errors
    ///
    /// Returns [`HorizonError::InvalidDataRowPayload`] when the invariant does not hold.
    pub fn validate_payload(&self) -> HorizonResult<()> {
        let populated_arm_list: Vec<&'static str> = [
            ("payload_float32", self.payload_float32.is_some()),
            (
                "payload_float32_array",
                self.payload_float32_array.is_some(),
            ),
            ("payload_float64", self.payload_float64.is_some()),
            (
                "payload_float64_array",
                self.payload_float64_array.is_some(),
            ),
            ("payload_int", self.payload_int.is_some()),
            ("payload_int_array", self.payload_int_array.is_some()),
            ("payload_string", self.payload_string.is_some()),
            ("payload_struct", self.payload_struct.is_some()),
            ("vector", self.vector.is_some()),
        ]
        .into_iter()
        .filter_map(|(field_name, is_set)| is_set.then_some(field_name))
        .collect();

        let active_arm = if let [arm] = populated_arm_list.as_slice() {
            *arm
        } else {
            let message = "exactly one of vector or payload_* must be set".to_owned();
            return Err(HorizonError::InvalidDataRowPayload { message });
        };
        if active_arm == "vector"
            && (self.vector_start_bound.is_none() || self.vector_end_bound.is_none())
        {
            let message =
                "vector payload requires vector_start_bound and vector_end_bound".to_owned();
            return Err(HorizonError::InvalidDataRowPayload { message });
        }

        match self.variant.as_deref() {
            None => {
                if active_arm != "vector" {
                    let message =
                        "variant is required when the payload is not a legacy vector".to_owned();
                    return Err(HorizonError::InvalidDataRowPayload { message });
                }
            }
            Some(variant_text) => {
                let Some(variant) = DataRowVariant::parse(variant_text) else {
                    let message = format!("unknown variant: {variant_text}");
                    return Err(HorizonError::InvalidDataRowPayload { message });
                };
                let expected_arm = variant.payload_arm();
                if expected_arm != active_arm {
                    let message = format!(
                        "variant '{variant_text}' does not match populated payload arm '{active_arm}'"
                    );
                    return Err(HorizonError::InvalidDataRowPayload { message });
                }
            }
        }
        Ok(())
    }
}

impl From<&DataRow> for VariantDataRow {
    fn from(row: &DataRow) -> Self {
        Self {
            created_datetime: row.created_datetime,
            data_stream_id: row.data_stream_id,
            data_type: row.data_type.clone(),
            datetime: row.datetime,
            modified_datetime: row.modified_datetime,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id: row.specification_id,
            variant: Some(DataRowVariant::Vector.as_str().to_owned()),
            vector: Some(row.vector.clone()),
            vector_end_bound: Some(row.vector_end_bound),
            vector_start_bound: Some(row.vector_start_bound),
        }
    }
}

impl TryFrom<VariantDataRow> for DataRow {
    type Error = HorizonError;

    fn try_from(row: VariantDataRow) -> Result<Self, Self::Error> {
        let Some(DataRowPayload::Vector {
            vector,
            vector_end_bound,
            vector_start_bound,
        }) = row.payload()
        else {
            let message = "a non-vector variant cannot be converted to DataRow".to_owned();
            return Err(HorizonError::InvalidDataRowPayload { message });
        };

        Ok(Self {
            created_datetime: row.created_datetime,
            data_stream_id: row.data_stream_id,
            data_type: row.data_type,
            datetime: row.datetime,
            modified_datetime: row.modified_datetime,
            specification_id: row.specification_id,
            vector,
            vector_end_bound,
            vector_start_bound,
        })
    }
}

/// Backend that powers tile queries for a data stream.
///
/// Maps to the `horizon_public.data_stream_query_source` Postgres ENUM.
#[allow(
    clippy::exhaustive_enums,
    reason = "variants mirror a closed Postgres ENUM, so exhaustive matching downstream is desirable"
)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]
#[sqlx(
    type_name = "horizon_public.data_stream_query_source",
    rename_all = "lowercase"
)]
#[serde(rename_all = "lowercase")]
pub enum DataStreamQuerySource {
    /// Query the row-store `data_row` table directly.
    #[default]
    Postgres,
    /// Query Iceberg through Trino.
    Trino,
}

/// A data stream belonging to a platform.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DataStream {
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Option<Uuid>,
    #[serde(default)]
    pub query_source: DataStreamQuerySource,
}

impl DataStream {
    /// Create a `DataStream` with a deterministic UUID derived from the platform ID and name.
    ///
    /// Defaults `query_source` to [`DataStreamQuerySource::Postgres`]; override the
    /// field after construction if the stream should be served from Trino.
    #[must_use]
    pub fn from_platform_and_name(platform_id: Uuid, data_stream_name: &str) -> Self {
        let name = capitalize(data_stream_name);
        Self {
            created_datetime: None,
            id: Some(data_stream_uuid(platform_id, data_stream_name)),
            modified_datetime: None,
            name: Some(name),
            organization_id: None,
            platform_id: Some(platform_id),
            query_source: DataStreamQuerySource::Postgres,
        }
    }
}

/// A user-defined alias for an elevation range (lower/upper elevation and increment).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ElevationAlias {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub elevation_increment: Option<f64>,
    pub id: Option<Uuid>,
    pub lower_elevation: Option<f64>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub upper_elevation: Option<f64>,
}

/// A user-defined focus range label for categorizing acoustic conditions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FocusRange {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// A user-defined alias for a frequency band (lower/upper frequency pair).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrequencyBandAlias {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub lower_frequency: Option<f64>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub upper_frequency: Option<f64>,
}

/// A user-defined alias for a frequency resolution, naming a frequency bin count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrequencyResolutionAlias {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub frequency_bin_count: Option<i32>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// A row of metadata in the Iceberg `metadata_row` table.
///
/// This type is used for both Postgres inserts and Arrow IPC serialization.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MetadataRow {
    pub altitude: Option<f64>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub data_stream_id: Uuid,
    pub datetime: DateTime<Utc>,
    pub heading: Option<f64>,
    pub latitude: Option<f64>,
    pub longitude: Option<f64>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub pitch: Option<f64>,
    pub roll: Option<f64>,
    pub speed: Option<f64>,
    pub speed_over_ground: Option<f64>,
}

/// A group that can group platforms around some bounded time or purpose.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mission {
    pub created_datetime: Option<DateTime<Utc>>,
    pub end_datetime: Option<DateTime<Utc>>,
    pub free_text: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub position: Option<Position>,
    pub start_datetime: Option<DateTime<Utc>>,
}

/// A relationship that associates a platform with a mission.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MissionPlatform {
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub mission_id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Option<Uuid>,
}

/// A named normalization algorithm referenced by feed specifications.
///
/// Uses a soft delete: `is_archived` frees the name for reuse because the
/// unique constraint is partial (`WHERE NOT is_archived`). There is no hard
/// delete; use `archive_normalizer` instead.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Normalizer {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub is_archived: Option<bool>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// An ontology for organizing platforms.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ontology {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// A class within an ontology.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OntologyClass {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub ontology_id: Uuid,
    pub order: Option<i32>,
    pub organization_id: Option<Uuid>,
    pub parent_id: Option<Uuid>,
    pub relationship_type: Option<String>,
}

/// An instance of a platform.
///
/// The `position` field maps to `PostgreSQL`'s `POINT` type as `(longitude, latitude)`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Platform {
    pub created_datetime: Option<DateTime<Utc>>,
    pub end_datetime: Option<DateTime<Utc>>,
    pub free_text: Option<String>,
    pub id: Option<Uuid>,
    pub kind_id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub position: Option<Position>,
    pub start_datetime: Option<DateTime<Utc>>,
}

/// A relationship that associates a platform with an audio specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformAudioSpecification {
    pub audio_specification_id: Uuid,
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Uuid,
}

/// A relationship that associates a platform with a beamgram specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformBeamgramSpecification {
    pub beamgram_specification_id: Option<Uuid>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Option<Uuid>,
}

/// A relationship that associates a platform with a bearing-time record specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformBearingTimeRecordSpecification {
    pub bearing_time_record_specification_id: Option<Uuid>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Option<Uuid>,
}

/// Key-value information stored for a platform (append-only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformInformation {
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Uuid,
    pub properties: serde_json::Value,
}

/// A kind of platform (e.g. buoy, vessel, aircraft).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformKind {
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub image_url: Option<String>,
    pub long_description: Option<String>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub short_description: Option<String>,
}

/// A relationship that associates a platform with a spectrogram specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformSpectrogramSpecification {
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub platform_id: Option<Uuid>,
    pub spectrogram_specification_id: Option<Uuid>,
}

/// A directional spectrogram specification: leading/lagging bearing row offsets
/// used to derive directional hue on top of a spectrogram.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DirectionalSpectrogramSpecification {
    pub bearing_lagging_rows: Option<i64>,
    pub bearing_leading_rows: Option<i64>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub organization_id: Option<Uuid>,
    pub spectrogram_specification_id: Option<Uuid>,
}

/// A specification for spectrogram data processing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpectrogramSpecification {
    pub amplitude_unit_mode: Option<String>,
    pub channel: Option<i32>,
    pub channel_role: Option<String>,
    pub created_datetime: Option<DateTime<Utc>>,
    pub fft_sample_count: Option<i32>,
    pub fft_sample_overlap_count: Option<i32>,
    pub frequency_bin_count: Option<i32>,
    pub frequency_spacing: Option<f64>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub normalizer: Option<String>,
    pub organization_id: Option<Uuid>,
}

/// A user-defined alias for an update rate, naming an interval.
///
/// `update_rate_ms` maps the `PostgreSQL` `interval` column to whole
/// milliseconds, mirroring the beamgram/bearing-time-record specifications.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateRateAlias {
    pub created_datetime: Option<DateTime<Utc>>,
    pub description: Option<String>,
    pub id: Option<Uuid>,
    pub modified_datetime: Option<DateTime<Utc>>,
    pub name: Option<String>,
    pub organization_id: Option<Uuid>,
    pub update_rate_ms: Option<i64>,
}

/// Capitalize a string: uppercase first character, lowercase rest.
///
/// Matches Python's `str.capitalize()` for cross-SDK parity.
#[must_use]
pub fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    chars.next().map_or_else(String::new, |first| {
        let upper: String = first.to_uppercase().collect();
        format!("{upper}{}", chars.as_str().to_lowercase())
    })
}

/// Compute the deterministic UUID for a data stream from its platform and name.
///
/// Applies [`capitalize`] to the name for Python SDK parity, then hashes
/// the `"{platform_id}:{capitalized_name}"` string via [`name_to_uuid`].
#[must_use]
pub fn data_stream_uuid(platform_id: Uuid, data_stream_name: &str) -> Uuid {
    let name = capitalize(data_stream_name);
    name_to_uuid(&format!("{platform_id}:{name}"))
}

/// Deterministic UUID generation for data idempotency.
///
/// Uses UUID v5 (SHA-1 namespace) with a fixed namespace to produce
/// the same UUID for the same input string across invocations.
#[must_use]
pub fn name_to_uuid(name: &str) -> Uuid {
    const NAMESPACE: Uuid = Uuid::from_bytes([
        0x13, 0xdb, 0x1b, 0xb5, 0x27, 0xac, 0x4b, 0xf7, 0x81, 0x86, 0x10, 0x43, 0x34, 0x7c, 0x42,
        0x47,
    ]);
    let normalized = name.trim().to_lowercase();
    Uuid::new_v5(&NAMESPACE, normalized.as_bytes())
}

#[cfg(test)]
#[allow(
    clippy::default_numeric_fallback,
    clippy::unwrap_used,
    reason = "tests use numeric literals and unwrap for brevity"
)]
mod tests {
    use super::*;

    #[test]
    fn capitalize_matches_python() {
        assert_eq!(capitalize("hydrophone"), "Hydrophone");
        assert_eq!(capitalize("Hydrophone"), "Hydrophone");
        assert_eq!(capitalize("hYDROPHONE"), "Hydrophone");
        assert_eq!(capitalize("HYDROPHONE"), "Hydrophone");
        assert_eq!(capitalize(""), "");
        assert_eq!(capitalize("a"), "A");
    }

    #[test]
    fn data_stream_from_platform_and_name() {
        let platform_id = Uuid::new_v4();
        let ds = DataStream::from_platform_and_name(platform_id, "audio");
        assert_eq!(ds.platform_id, Some(platform_id));
        assert_eq!(ds.name.as_deref(), Some("Audio"));
        assert!(ds.id.is_some());

        let ds2 = DataStream::from_platform_and_name(platform_id, "audio");
        assert_eq!(ds.id, ds2.id);
    }

    #[test]
    fn data_stream_uuid_is_deterministic() {
        let platform_id = Uuid::new_v4();
        let a = data_stream_uuid(platform_id, "audio");
        let b = data_stream_uuid(platform_id, "audio");
        assert_eq!(a, b);
    }

    #[test]
    fn data_stream_uuid_matches_from_platform_and_name() {
        let platform_id = Uuid::new_v4();
        let ds = DataStream::from_platform_and_name(platform_id, "audio");
        assert_eq!(ds.id, Some(data_stream_uuid(platform_id, "audio")));
    }

    #[test]
    fn mission_serde_round_trip() {
        let mission = Mission {
            created_datetime: None,
            end_datetime: None,
            free_text: None,
            id: Some(Uuid::new_v4()),
            modified_datetime: None,
            name: Some("Test Mission".to_owned()),
            organization_id: None,
            position: Some(Position(1.5_f64, 2.5_f64)),
            start_datetime: Some(Utc::now()),
        };
        let json = serde_json::to_string(&mission).unwrap();
        let deserialized: Mission = serde_json::from_str(&json).unwrap();
        assert_eq!(mission, deserialized);
    }

    #[test]
    fn name_to_uuid_is_deterministic() {
        let a = name_to_uuid("test");
        let b = name_to_uuid("test");
        assert_eq!(a, b);
    }

    #[test]
    fn name_to_uuid_matches_python_sdk() {
        let expected = Uuid::parse_str("e32be881-c656-5b8e-8dd7-889066ac1c83").unwrap();
        assert_eq!(name_to_uuid("Test Platform"), expected);

        let expected2 = Uuid::parse_str("eaeebe45-0eaa-59e4-9b79-7ceda69789e2").unwrap();
        assert_eq!(name_to_uuid("hello world"), expected2);
    }

    #[test]
    fn name_to_uuid_normalizes_whitespace_and_case() {
        let a = name_to_uuid("  Hello World  ");
        let b = name_to_uuid("hello world");
        assert_eq!(a, b);
    }

    #[test]
    fn platform_information_serde_with_json_properties() {
        let info = PlatformInformation {
            created_datetime: None,
            id: None,
            modified_datetime: None,
            organization_id: None,
            platform_id: Uuid::new_v4(),
            properties: serde_json::json!({"key": "value", "nested": {"a": 1_i32}}),
        };
        let json = serde_json::to_string(&info).unwrap();
        let deserialized: PlatformInformation = serde_json::from_str(&json).unwrap();
        assert_eq!(info, deserialized);
    }

    #[test]
    fn data_row_from_payload_passes_validation() {
        let row = VariantDataRow::from_payload(
            Uuid::nil(),
            Utc::now(),
            "cot".to_owned(),
            Uuid::nil(),
            DataRowPayload::Struct(serde_json::json!({"callsign": "ALPHA"})),
        );
        row.validate_payload().unwrap();
    }

    #[test]
    fn data_row_allows_legacy_vector_without_variant() {
        let row = VariantDataRow {
            created_datetime: None,
            data_stream_id: Uuid::nil(),
            data_type: "audio".to_owned(),
            datetime: Utc::now(),
            modified_datetime: None,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id: Uuid::nil(),
            variant: None,
            vector: Some(vec![1.0, 2.0]),
            vector_end_bound: Some(1.0),
            vector_start_bound: Some(0.0),
        };
        row.validate_payload().unwrap();
    }

    #[test]
    fn data_row_rejects_vector_without_bounds() {
        let row = VariantDataRow {
            created_datetime: None,
            data_stream_id: Uuid::nil(),
            data_type: "audio".to_owned(),
            datetime: Utc::now(),
            modified_datetime: None,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id: Uuid::nil(),
            variant: None,
            vector: Some(vec![1.0, 2.0]),
            vector_end_bound: None,
            vector_start_bound: Some(0.0),
        };
        let error = row.validate_payload().unwrap_err();
        assert!(
            error
                .to_string()
                .contains("vector payload requires vector_start_bound and vector_end_bound"),
            "got: {error}"
        );
        assert!(row.payload().is_none());
    }

    #[test]
    fn data_row_rejects_mixed_payload_fields() {
        let mut row = VariantDataRow::from_payload(
            Uuid::nil(),
            Utc::now(),
            "cot".to_owned(),
            Uuid::nil(),
            DataRowPayload::Struct(serde_json::json!({})),
        );
        row.payload_float64 = Some(22.5);
        let error = row.validate_payload().unwrap_err();
        assert!(
            error
                .to_string()
                .contains("exactly one of vector or payload_* must be set"),
            "got: {error}"
        );
    }

    #[test]
    fn data_row_rejects_mismatched_variant() {
        let mut row = VariantDataRow::from_payload(
            Uuid::nil(),
            Utc::now(),
            "cot".to_owned(),
            Uuid::nil(),
            DataRowPayload::Struct(serde_json::json!({})),
        );
        row.variant = Some("float64".to_owned());
        let error = row.validate_payload().unwrap_err();
        assert!(
            error
                .to_string()
                .contains("does not match populated payload arm"),
            "got: {error}"
        );
    }

    #[test]
    fn data_row_payload_resolves_legacy_vector() {
        let row = VariantDataRow {
            created_datetime: None,
            data_stream_id: Uuid::nil(),
            data_type: "audio".to_owned(),
            datetime: Utc::now(),
            modified_datetime: None,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id: Uuid::nil(),
            variant: None,
            vector: Some(vec![1.0, 2.0]),
            vector_end_bound: Some(1.0),
            vector_start_bound: Some(0.0),
        };
        assert!(matches!(row.payload(), Some(DataRowPayload::Vector { .. })));
    }

    #[test]
    fn data_row_payload_rejects_unknown_variant_even_with_vector() {
        let row = VariantDataRow {
            created_datetime: None,
            data_stream_id: Uuid::nil(),
            data_type: "audio".to_owned(),
            datetime: Utc::now(),
            modified_datetime: None,
            payload_float32: None,
            payload_float32_array: None,
            payload_float64: None,
            payload_float64_array: None,
            payload_int: None,
            payload_int_array: None,
            payload_string: None,
            payload_struct: None,
            specification_id: Uuid::nil(),
            variant: Some("not-a-variant".to_owned()),
            vector: Some(vec![1.0, 2.0]),
            vector_end_bound: Some(1.0),
            vector_start_bound: Some(0.0),
        };
        assert!(row.payload().is_none());
    }
}