perfgate-api 0.15.1

Common API types and models for perfgate baseline service
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
//! Common API types and models for the perfgate baseline service.
//!
//! Defines request/response types, baseline records, project models, and verdict
//! history used by both the server and client crates.
//!
//! Part of the [perfgate](https://github.com/EffortlessMetrics/perfgate) workspace.
//!
//! # Example
//!
//! ```
//! use perfgate_api::BASELINE_SCHEMA_V1;
//!
//! assert_eq!(BASELINE_SCHEMA_V1, "perfgate.baseline.v1");
//! ```

use chrono::{DateTime, Utc};
use perfgate_types::{RunReceipt, VerdictCounts, VerdictStatus};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Schema identifier for baseline records.
pub const BASELINE_SCHEMA_V1: &str = "perfgate.baseline.v1";

/// Schema identifier for project records.
pub const PROJECT_SCHEMA_V1: &str = "perfgate.project.v1";

/// Schema identifier for verdict records.
pub const VERDICT_SCHEMA_V1: &str = "perfgate.verdict.v1";

/// Schema identifier for audit event records.
pub const AUDIT_SCHEMA_V1: &str = "perfgate.audit.v1";

/// Source of baseline creation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum BaselineSource {
    /// Uploaded directly via API
    #[default]
    Upload,
    /// Created via promote operation
    Promote,
    /// Migrated from external storage
    Migrate,
    /// Created via rollback operation
    Rollback,
}

/// The primary storage model for baselines.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct BaselineRecord {
    /// Schema identifier (perfgate.baseline.v1)
    pub schema: String,
    /// Unique baseline identifier (ULID format)
    pub id: String,
    /// Project/namespace identifier
    pub project: String,
    /// Benchmark name
    pub benchmark: String,
    /// Semantic version
    pub version: String,
    /// Git reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_ref: Option<String>,
    /// Git commit SHA
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_sha: Option<String>,
    /// Full run receipt
    pub receipt: RunReceipt,
    /// User-provided metadata
    #[serde(default)]
    pub metadata: BTreeMap<String, String>,
    /// Tags for filtering
    #[serde(default)]
    pub tags: Vec<String>,
    /// Creation timestamp (RFC 3339)
    pub created_at: DateTime<Utc>,
    /// Last modification timestamp
    pub updated_at: DateTime<Utc>,
    /// Content hash for ETag
    pub content_hash: String,
    /// Creation source
    pub source: BaselineSource,
    /// Soft delete flag
    #[serde(default)]
    pub deleted: bool,
}

impl BaselineRecord {
    /// Returns the ETag value for this baseline.
    pub fn etag(&self) -> String {
        format!("\"sha256:{}\"", self.content_hash)
    }
}

/// A record of a benchmark execution verdict.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct VerdictRecord {
    /// Schema identifier (perfgate.verdict.v1)
    pub schema: String,
    /// Unique verdict identifier
    pub id: String,
    /// Project identifier
    pub project: String,
    /// Benchmark name
    pub benchmark: String,
    /// Run identifier from receipt
    pub run_id: String,
    /// Overall status (pass/warn/fail/skip)
    pub status: VerdictStatus,
    /// Detailed counts
    pub counts: VerdictCounts,
    /// List of reasons for the verdict
    pub reasons: Vec<String>,
    /// Git reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_ref: Option<String>,
    /// Git commit SHA
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_sha: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
}

/// Request for submitting a verdict.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SubmitVerdictRequest {
    pub benchmark: String,
    pub run_id: String,
    pub status: VerdictStatus,
    pub counts: VerdictCounts,
    pub reasons: Vec<String>,
    pub git_ref: Option<String>,
    pub git_sha: Option<String>,
}

/// Request for verdict list operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListVerdictsQuery {
    /// Filter by exact benchmark name
    pub benchmark: Option<String>,
    /// Filter by status
    pub status: Option<VerdictStatus>,
    /// Filter by creation date (after)
    pub since: Option<DateTime<Utc>>,
    /// Filter by creation date (before)
    pub until: Option<DateTime<Utc>>,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
    /// Pagination offset
    #[serde(default)]
    pub offset: u64,
}

impl Default for ListVerdictsQuery {
    fn default() -> Self {
        Self {
            benchmark: None,
            status: None,
            since: None,
            until: None,
            limit: default_limit(),
            offset: 0,
        }
    }
}

impl ListVerdictsQuery {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn with_benchmark(mut self, b: impl Into<String>) -> Self {
        self.benchmark = Some(b.into());
        self
    }
    pub fn with_status(mut self, s: VerdictStatus) -> Self {
        self.status = Some(s);
        self
    }
    pub fn with_limit(mut self, l: u32) -> Self {
        self.limit = l;
        self
    }
    pub fn with_offset(mut self, o: u64) -> Self {
        self.offset = o;
        self
    }
}

/// Response for verdict list operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListVerdictsResponse {
    pub verdicts: Vec<VerdictRecord>,
    pub pagination: PaginationInfo,
}

/// Version history metadata (without full receipt).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct BaselineVersion {
    /// Version identifier
    pub version: String,
    /// Git reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_ref: Option<String>,
    /// Git commit SHA
    #[serde(skip_serializing_if = "Option::is_none")]
    pub git_sha: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Creator identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,
    /// Whether this is the current/promoted version
    pub is_current: bool,
    /// Source of this version
    pub source: BaselineSource,
}

/// Retention policy for a project.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct RetentionPolicy {
    /// Maximum number of versions to keep per benchmark.
    pub max_versions: Option<u32>,
    /// Maximum age of a version in days.
    pub max_age_days: Option<u32>,
    /// Tags that prevent a version from being deleted.
    pub preserve_tags: Vec<String>,
}

impl Default for RetentionPolicy {
    fn default() -> Self {
        Self {
            max_versions: Some(50),
            max_age_days: Some(365),
            preserve_tags: vec!["production".to_string(), "stable".to_string()],
        }
    }
}

/// Strategy for auto-generating versions.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum VersioningStrategy {
    /// Use run_id from receipt as version
    #[default]
    RunId,
    /// Use timestamp as version
    Timestamp,
    /// Use git_sha as version
    GitSha,
    /// Manual version required
    Manual,
}

/// Multi-tenancy namespace with retention policies.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct Project {
    /// Schema identifier (perfgate.project.v1)
    pub schema: String,
    /// Project identifier (URL-safe)
    pub id: String,
    /// Display name
    pub name: String,
    /// Project description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Retention policy
    pub retention: RetentionPolicy,
    /// Default baseline versioning strategy
    pub versioning: VersioningStrategy,
}

/// Request for baseline list operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListBaselinesQuery {
    /// Filter by exact benchmark name
    pub benchmark: Option<String>,
    /// Filter by benchmark name prefix
    pub benchmark_prefix: Option<String>,
    /// Filter by git reference
    pub git_ref: Option<String>,
    /// Filter by git SHA
    pub git_sha: Option<String>,
    /// Filter by tags (comma-separated)
    pub tags: Option<String>,
    /// Filter by creation date (after)
    pub since: Option<DateTime<Utc>>,
    /// Filter by creation date (before)
    pub until: Option<DateTime<Utc>>,
    /// Include full receipts in output
    #[serde(default)]
    pub include_receipt: bool,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
    /// Pagination offset
    #[serde(default)]
    pub offset: u64,
}

impl Default for ListBaselinesQuery {
    fn default() -> Self {
        Self {
            benchmark: None,
            benchmark_prefix: None,
            git_ref: None,
            git_sha: None,
            tags: None,
            since: None,
            until: None,
            include_receipt: false,
            limit: default_limit(),
            offset: 0,
        }
    }
}

fn default_limit() -> u32 {
    50
}

impl ListBaselinesQuery {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn with_benchmark(mut self, b: impl Into<String>) -> Self {
        self.benchmark = Some(b.into());
        self
    }
    pub fn with_benchmark_prefix(mut self, p: impl Into<String>) -> Self {
        self.benchmark_prefix = Some(p.into());
        self
    }
    pub fn with_offset(mut self, o: u64) -> Self {
        self.offset = o;
        self
    }
    pub fn with_limit(mut self, l: u32) -> Self {
        self.limit = l;
        self
    }
    pub fn with_receipts(mut self) -> Self {
        self.include_receipt = true;
        self
    }
    pub fn parsed_tags(&self) -> Vec<String> {
        self.tags
            .as_ref()
            .map(|t| {
                t.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            })
            .unwrap_or_default()
    }
    pub fn to_query_params(&self) -> Vec<(String, String)> {
        let mut params = Vec::new();
        if let Some(b) = &self.benchmark {
            params.push(("benchmark".to_string(), b.clone()));
        }
        if let Some(p) = &self.benchmark_prefix {
            params.push(("benchmark_prefix".to_string(), p.clone()));
        }
        if let Some(r) = &self.git_ref {
            params.push(("git_ref".to_string(), r.clone()));
        }
        if let Some(s) = &self.git_sha {
            params.push(("git_sha".to_string(), s.clone()));
        }
        if let Some(t) = &self.tags {
            params.push(("tags".to_string(), t.clone()));
        }
        if let Some(s) = &self.since {
            params.push(("since".to_string(), s.to_rfc3339()));
        }
        if let Some(u) = &self.until {
            params.push(("until".to_string(), u.to_rfc3339()));
        }
        params.push(("limit".to_string(), self.limit.to_string()));
        params.push(("offset".to_string(), self.offset.to_string()));
        if self.include_receipt {
            params.push(("include_receipt".to_string(), "true".to_string()));
        }
        params
    }
}

/// Pagination information for lists.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PaginationInfo {
    /// Total count of items (if known)
    pub total: u64,
    /// Offset of current page
    pub offset: u64,
    /// Limit of items per page
    pub limit: u32,
    /// Whether more items are available
    pub has_more: bool,
}

/// Response for baseline list operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListBaselinesResponse {
    /// List of baseline summaries or records
    pub baselines: Vec<BaselineSummary>,
    /// Pagination metadata
    pub pagination: PaginationInfo,
}

/// Summary of a baseline record (without full receipt).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct BaselineSummary {
    pub id: String,
    pub benchmark: String,
    pub version: String,
    pub created_at: DateTime<Utc>,
    pub git_ref: Option<String>,
    pub git_sha: Option<String>,
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub receipt: Option<RunReceipt>,
}

impl From<BaselineRecord> for BaselineSummary {
    fn from(record: BaselineRecord) -> Self {
        Self {
            id: record.id,
            benchmark: record.benchmark,
            version: record.version,
            created_at: record.created_at,
            git_ref: record.git_ref,
            git_sha: record.git_sha,
            tags: record.tags,
            receipt: Some(record.receipt),
        }
    }
}

/// Request for baseline upload.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct UploadBaselineRequest {
    pub benchmark: String,
    pub version: Option<String>,
    pub git_ref: Option<String>,
    pub git_sha: Option<String>,
    pub receipt: RunReceipt,
    pub metadata: BTreeMap<String, String>,
    pub tags: Vec<String>,
    pub normalize: bool,
}

/// Response for successful baseline upload.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct UploadBaselineResponse {
    pub id: String,
    pub benchmark: String,
    pub version: String,
    pub created_at: DateTime<Utc>,
    pub etag: String,
}

/// Request for baseline promotion.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PromoteBaselineRequest {
    pub from_version: String,
    pub to_version: String,
    pub git_ref: Option<String>,
    pub git_sha: Option<String>,
    pub tags: Vec<String>,
    #[serde(default)]
    pub normalize: bool,
}

/// Response for baseline promotion.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PromoteBaselineResponse {
    pub id: String,
    pub benchmark: String,
    pub version: String,
    pub promoted_from: String,
    pub promoted_at: DateTime<Utc>,
    pub created_at: DateTime<Utc>,
}

/// Response for baseline deletion.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DeleteBaselineResponse {
    pub deleted: bool,
    pub id: String,
    pub benchmark: String,
    pub version: String,
    pub deleted_at: DateTime<Utc>,
}

// =========================================================================
// Audit logging types
// =========================================================================

/// The action that was performed in an audit event.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AuditAction {
    /// A resource was created (e.g., baseline upload)
    Create,
    /// A resource was updated
    Update,
    /// A resource was deleted (soft or hard)
    Delete,
    /// A baseline was promoted
    Promote,
}

impl std::fmt::Display for AuditAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuditAction::Create => write!(f, "create"),
            AuditAction::Update => write!(f, "update"),
            AuditAction::Delete => write!(f, "delete"),
            AuditAction::Promote => write!(f, "promote"),
        }
    }
}

impl std::str::FromStr for AuditAction {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "create" => Ok(AuditAction::Create),
            "update" => Ok(AuditAction::Update),
            "delete" => Ok(AuditAction::Delete),
            "promote" => Ok(AuditAction::Promote),
            other => Err(format!("Unknown audit action: {}", other)),
        }
    }
}

/// The type of resource affected by an audit event.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AuditResourceType {
    /// A baseline record
    Baseline,
    /// An API key
    Key,
    /// A verdict record
    Verdict,
}

impl std::fmt::Display for AuditResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuditResourceType::Baseline => write!(f, "baseline"),
            AuditResourceType::Key => write!(f, "key"),
            AuditResourceType::Verdict => write!(f, "verdict"),
        }
    }
}

impl std::str::FromStr for AuditResourceType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "baseline" => Ok(AuditResourceType::Baseline),
            "key" => Ok(AuditResourceType::Key),
            "verdict" => Ok(AuditResourceType::Verdict),
            other => Err(format!("Unknown resource type: {}", other)),
        }
    }
}

/// An append-only audit event for tracking mutations and admin actions.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct AuditEvent {
    /// Unique event identifier
    pub id: String,
    /// Timestamp of the event (RFC 3339)
    pub timestamp: DateTime<Utc>,
    /// Actor identity (API key ID or OIDC subject)
    pub actor: String,
    /// The action performed
    pub action: AuditAction,
    /// Type of resource affected
    pub resource_type: AuditResourceType,
    /// Identifier for the affected resource
    pub resource_id: String,
    /// Project scope
    pub project: String,
    /// Additional structured metadata (endpoint-specific details)
    #[serde(default)]
    pub metadata: serde_json::Value,
}

/// Query parameters for listing audit events.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListAuditEventsQuery {
    /// Filter by project
    pub project: Option<String>,
    /// Filter by action
    pub action: Option<String>,
    /// Filter by resource type
    pub resource_type: Option<String>,
    /// Filter by actor
    pub actor: Option<String>,
    /// Filter by events after this time
    pub since: Option<DateTime<Utc>>,
    /// Filter by events before this time
    pub until: Option<DateTime<Utc>>,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
    /// Pagination offset
    #[serde(default)]
    pub offset: u64,
}

impl Default for ListAuditEventsQuery {
    fn default() -> Self {
        Self {
            project: None,
            action: None,
            resource_type: None,
            actor: None,
            since: None,
            until: None,
            limit: default_limit(),
            offset: 0,
        }
    }
}

/// Response for audit event list operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListAuditEventsResponse {
    /// The audit events matching the query
    pub events: Vec<AuditEvent>,
    /// Pagination metadata
    pub pagination: PaginationInfo,
}

/// Health status of a storage backend.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct StorageHealth {
    pub backend: String,
    pub status: String,
}

/// Connection pool metrics exposed via the health endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PoolMetrics {
    /// Number of idle connections in the pool.
    pub idle: u32,
    /// Number of active (in-use) connections.
    pub active: u32,
    /// Maximum number of connections the pool is configured for.
    pub max: u32,
}

/// Response for health check.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
    pub storage: StorageHealth,
    /// Connection pool metrics (present only for pooled backends such as PostgreSQL).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pool: Option<PoolMetrics>,
}

/// Generic error response for the API.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ApiError {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<serde_json::Value>,
}

impl ApiError {
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
            details: None,
        }
    }
    pub fn unauthorized(msg: &str) -> Self {
        Self::new("unauthorized", msg)
    }
    pub fn forbidden(msg: &str) -> Self {
        Self::new("forbidden", msg)
    }
    pub fn not_found(msg: &str) -> Self {
        Self::new("not_found", msg)
    }
    pub fn bad_request(msg: &str) -> Self {
        Self::new("bad_request", msg)
    }
    pub fn conflict(msg: &str) -> Self {
        Self::new("conflict", msg)
    }
    pub fn internal_error(msg: &str) -> Self {
        Self::new("internal_error", msg)
    }
    pub fn internal(msg: &str) -> Self {
        Self::internal_error(msg)
    }
    pub fn validation(msg: &str) -> Self {
        Self::new("invalid_input", msg)
    }
    pub fn already_exists(msg: &str) -> Self {
        Self::new("conflict", msg)
    }
}

// ── API Key Management Types ──────────────────────────────────────────

/// Request for creating a new API key.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CreateKeyRequest {
    /// Human-readable description
    pub description: String,
    /// Role to assign (viewer, contributor, promoter, admin)
    pub role: perfgate_auth::Role,
    /// Project this key is scoped to (use "*" for all projects)
    pub project: String,
    /// Optional glob pattern to restrict benchmark access
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Optional expiration timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
}

/// Response for creating a new API key (contains the plaintext key once).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CreateKeyResponse {
    /// Unique key identifier (for management)
    pub id: String,
    /// The plaintext API key (only returned once)
    pub key: String,
    /// Human-readable description
    pub description: String,
    /// Assigned role
    pub role: perfgate_auth::Role,
    /// Scoped project
    pub project: String,
    /// Optional benchmark pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Expiration timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
}

/// A redacted API key entry returned by list operations.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct KeyEntry {
    /// Unique key identifier
    pub id: String,
    /// Redacted key prefix (e.g., "pg_live_abc1...***")
    pub key_prefix: String,
    /// Human-readable description
    pub description: String,
    /// Assigned role
    pub role: perfgate_auth::Role,
    /// Scoped project
    pub project: String,
    /// Optional benchmark pattern
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    /// Creation timestamp
    pub created_at: DateTime<Utc>,
    /// Expiration timestamp
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    /// Revocation timestamp (if revoked)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoked_at: Option<DateTime<Utc>>,
}

/// Response for listing API keys.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListKeysResponse {
    /// List of key entries (redacted)
    pub keys: Vec<KeyEntry>,
}

/// Response for revoking an API key.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RevokeKeyResponse {
    /// The key ID that was revoked
    pub id: String,
    /// When the key was revoked
    pub revoked_at: DateTime<Utc>,
}

// ---------------------------------------------------------------------------
// Fleet-wide dependency regression detection types
// ---------------------------------------------------------------------------

/// Schema identifier for dependency event records.
pub const DEPENDENCY_EVENT_SCHEMA_V1: &str = "perfgate.dependency_event.v1";

/// Schema identifier for fleet alert records.
pub const FLEET_ALERT_SCHEMA_V1: &str = "perfgate.fleet_alert.v1";

/// A single dependency version change observed alongside a benchmark run.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct DependencyChange {
    /// Dependency name (e.g., crate name)
    pub name: String,
    /// Previous version (None if newly added)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_version: Option<String>,
    /// New version (None if removed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_version: Option<String>,
}

/// A recorded dependency change event with its performance impact.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct DependencyEvent {
    /// Schema identifier
    pub schema: String,
    /// Unique event identifier
    pub id: String,
    /// Project that reported the event
    pub project: String,
    /// Benchmark name
    pub benchmark: String,
    /// Dependency name
    pub dep_name: String,
    /// Previous version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_version: Option<String>,
    /// New version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_version: Option<String>,
    /// Primary metric name (e.g., "wall_ms")
    pub metric: String,
    /// Percentage change in that metric (positive = regression)
    pub delta_pct: f64,
    /// Timestamp of the event
    pub created_at: DateTime<Utc>,
}

/// Request to record a dependency change event.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordDependencyEventRequest {
    /// Project that observed the event
    pub project: String,
    /// Benchmark name
    pub benchmark: String,
    /// List of dependency changes observed
    pub dependency_changes: Vec<DependencyChange>,
    /// Primary metric name
    pub metric: String,
    /// Percentage change in the metric (positive = regression)
    pub delta_pct: f64,
}

/// Response after recording dependency events.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordDependencyEventResponse {
    /// Number of events recorded
    pub recorded: usize,
}

/// A project affected by a fleet-wide dependency regression.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct AffectedProject {
    /// Project identifier
    pub project: String,
    /// Benchmark name
    pub benchmark: String,
    /// Primary metric name
    pub metric: String,
    /// Percentage change
    pub delta_pct: f64,
}

/// A fleet-wide alert: multiple projects regressed after the same dependency update.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
pub struct FleetAlert {
    /// Schema identifier
    pub schema: String,
    /// Unique alert identifier
    pub id: String,
    /// Dependency name
    pub dependency: String,
    /// Previous version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_version: Option<String>,
    /// New version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_version: Option<String>,
    /// Projects affected by this dependency change
    pub affected_projects: Vec<AffectedProject>,
    /// Confidence score (0.0 - 1.0): higher means more projects affected
    pub confidence: f64,
    /// Average delta percentage across affected projects
    pub avg_delta_pct: f64,
    /// When the alert was first detected
    pub first_seen: DateTime<Utc>,
}

/// Query parameters for listing fleet alerts.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListFleetAlertsQuery {
    /// Minimum number of affected projects to include
    #[serde(default = "default_min_affected")]
    pub min_affected: usize,
    /// Only include alerts since this time
    pub since: Option<DateTime<Utc>>,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
}

impl Default for ListFleetAlertsQuery {
    fn default() -> Self {
        Self {
            min_affected: default_min_affected(),
            since: None,
            limit: default_limit(),
        }
    }
}

fn default_min_affected() -> usize {
    2
}

/// Response for listing fleet alerts.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListFleetAlertsResponse {
    pub alerts: Vec<FleetAlert>,
}

/// Query parameters for dependency impact lookup.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DependencyImpactQuery {
    /// Only include events since this time
    pub since: Option<DateTime<Utc>>,
    /// Pagination limit
    #[serde(default = "default_limit")]
    pub limit: u32,
}

impl Default for DependencyImpactQuery {
    fn default() -> Self {
        Self {
            since: None,
            limit: default_limit(),
        }
    }
}

/// Response for dependency impact lookup.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DependencyImpactResponse {
    /// Dependency name
    pub dependency: String,
    /// All recorded events for this dependency
    pub events: Vec<DependencyEvent>,
    /// Number of distinct projects affected
    pub project_count: usize,
    /// Average delta percentage
    pub avg_delta_pct: f64,
}

#[cfg(feature = "server")]
impl axum::response::IntoResponse for ApiError {
    fn into_response(self) -> axum::response::Response {
        let status = match self.code.as_str() {
            "bad_request" | "invalid_input" => http::StatusCode::BAD_REQUEST,
            "unauthorized" => http::StatusCode::UNAUTHORIZED,
            "forbidden" => http::StatusCode::FORBIDDEN,
            "not_found" => http::StatusCode::NOT_FOUND,
            "conflict" => http::StatusCode::CONFLICT,
            _ => http::StatusCode::INTERNAL_SERVER_ERROR,
        };
        (status, axum::Json(self)).into_response()
    }
}