zlayer-types 0.11.10

Shared wire types for the ZLayer platform — API DTOs, OCI image references, and related serde types.
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
//! Storage `Stored*` wire types.
//!
//! These are the serde-friendly DTOs persisted by the daemon's `SqlxStorage`
//! backends and surfaced over the REST API. They live here (not in
//! `zlayer-api`) so SDK consumers can deserialize them without pulling in
//! axum/sqlx/tokio.
//!
//! Convenience constructors that allocate fresh UUIDs, plus the
//! database-bound traits and concrete sqlx implementations, remain in
//! `zlayer-api::storage` — that's where the `uuid` dependency lives. This
//! crate only carries the wire shapes (structs, enums, and pure-data
//! `Display` impls).

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::spec::DeploymentSpec;

// =========================================================================
// Deployments
// =========================================================================

/// A stored deployment with metadata.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredDeployment {
    /// Deployment name (unique identifier)
    pub name: String,

    /// The deployment specification (complex nested structure, see spec docs)
    #[schema(value_type = Object)]
    pub spec: DeploymentSpec,

    /// Current deployment status
    pub status: DeploymentStatus,

    /// When the deployment was created
    #[schema(value_type = String, example = "2025-01-27T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the deployment was last updated
    #[schema(value_type = String, example = "2025-01-27T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredDeployment {
    /// Create a new stored deployment from a spec.
    #[must_use]
    pub fn new(spec: DeploymentSpec) -> Self {
        let now = Utc::now();
        Self {
            name: spec.deployment.clone(),
            spec,
            status: DeploymentStatus::Pending,
            created_at: now,
            updated_at: now,
        }
    }

    /// Update the deployment spec and timestamp.
    pub fn update_spec(&mut self, spec: DeploymentSpec) {
        self.spec = spec;
        self.updated_at = Utc::now();
    }

    /// Update the deployment status and timestamp.
    pub fn update_status(&mut self, status: DeploymentStatus) {
        self.status = status;
        self.updated_at = Utc::now();
    }
}

/// Deployment lifecycle status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DeploymentStatus {
    /// Deployment created but not yet started
    Pending,

    /// Deployment is being rolled out
    Deploying,

    /// All services are running
    Running,

    /// Deployment failed with an error message
    Failed {
        /// Error message describing the failure
        message: String,
    },

    /// Deployment has been stopped
    Stopped,
}

impl std::fmt::Display for DeploymentStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DeploymentStatus::Pending => write!(f, "pending"),
            DeploymentStatus::Deploying => write!(f, "deploying"),
            DeploymentStatus::Running => write!(f, "running"),
            DeploymentStatus::Failed { message } => write!(f, "failed: {message}"),
            DeploymentStatus::Stopped => write!(f, "stopped"),
        }
    }
}

// =========================================================================
// Users
// =========================================================================

/// A stored user account.
///
/// The password hash lives in `zlayer-secrets::CredentialStore` keyed by the
/// email address — NOT in this record. This type only carries user metadata.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredUser {
    /// Opaque user ID (`UUIDv4` string).
    pub id: String,

    /// Primary login identifier. Stored lower-cased.
    pub email: String,

    /// Human-readable display name.
    pub display_name: String,

    /// Role — "admin" or "user".
    pub role: UserRole,

    /// Whether the user can log in.
    pub is_active: bool,

    /// When the user was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the user was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,

    /// When the user last logged in (if ever).
    #[schema(value_type = Option<String>, example = "2026-04-15T12:00:00Z")]
    pub last_login_at: Option<DateTime<Utc>>,
}

impl StoredUser {
    /// Create a new user record with a fresh UUID and `is_active = true`.
    #[must_use]
    pub fn new(email: impl Into<String>, display_name: impl Into<String>, role: UserRole) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            email: email.into().to_lowercase(),
            display_name: display_name.into(),
            role,
            is_active: true,
            created_at: now,
            updated_at: now,
            last_login_at: None,
        }
    }

    /// Record a successful login, advancing `last_login_at` and `updated_at`.
    pub fn touch_login(&mut self) {
        let now = Utc::now();
        self.last_login_at = Some(now);
        self.updated_at = now;
    }
}

/// User role. Admins can do everything; regular users are constrained by
/// per-resource permissions (added in a later phase).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum UserRole {
    /// Full administrative access.
    Admin,
    /// Standard user constrained by per-resource permissions.
    User,
}

impl UserRole {
    /// Stable string form of this role.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            UserRole::Admin => "admin",
            UserRole::User => "user",
        }
    }
}

impl std::fmt::Display for UserRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

// =========================================================================
// Environments
// =========================================================================

/// A deployment/runtime environment (e.g. "dev", "staging", "prod").
///
/// Each environment is an isolated namespace for secrets and, later,
/// deployments. Optionally belongs to a `Project` (added in Phase 5) — when
/// `project_id` is `None`, the environment is global.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredEnvironment {
    /// UUID identifier.
    pub id: String,

    /// Display name (e.g. "dev"). Unique within a given `project_id`.
    pub name: String,

    /// Project id this environment belongs to. `None` = global.
    pub project_id: Option<String>,

    /// Free-form description shown in the UI.
    pub description: Option<String>,

    /// When the environment was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the environment was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredEnvironment {
    /// Create a new environment record with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>, project_id: Option<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            project_id,
            description: None,
            created_at: now,
            updated_at: now,
        }
    }
}

// =========================================================================
// Projects
// =========================================================================

/// A project bundles a git source, build configuration, registry credential
/// reference, linked deployments, and a default environment.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredProject {
    /// UUID identifier.
    pub id: String,

    /// Project name (globally unique).
    pub name: String,

    /// Free-form description shown in the UI.
    pub description: Option<String>,

    /// Git repository URL (e.g. `"https://github.com/user/repo"`).
    pub git_url: Option<String>,

    /// Git branch to build from (default: `"main"`).
    pub git_branch: Option<String>,

    /// Reference to a `GitCredential` (Phase 5.2).
    pub git_credential_id: Option<String>,

    /// How the project is built.
    pub build_kind: Option<BuildKind>,

    /// Relative path within the repo (e.g. `"./Dockerfile"`).
    pub build_path: Option<String>,

    /// Relative path (inside the cloned repo) to a `DeploymentSpec` YAML that
    /// the workflow `DeployProject` action should apply.
    ///
    /// When `None`, the workflow `DeployProject` action fails with a clear
    /// "no deploy spec configured" error rather than silently succeeding —
    /// callers are expected to set this explicitly via `project edit`.
    #[serde(default)]
    pub deploy_spec_path: Option<String>,

    /// Reference to a `RegistryCredential` (Phase 5.2).
    pub registry_credential_id: Option<String>,

    /// Reference to the default environment for this project.
    pub default_environment_id: Option<String>,

    /// Reference to the owning user.
    pub owner_id: Option<String>,

    /// Whether new commits on the tracked branch should automatically
    /// trigger a build + deploy cycle.
    #[serde(default)]
    pub auto_deploy: bool,

    /// If set, the daemon polls the remote for new commits every N seconds.
    /// `None` disables polling (the project is only updated via manual pull
    /// or webhook).
    #[serde(default)]
    pub poll_interval_secs: Option<u64>,

    /// When the project was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the project was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredProject {
    /// Create a new project record with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            description: None,
            git_url: None,
            git_branch: Some("main".to_string()),
            git_credential_id: None,
            build_kind: None,
            build_path: None,
            deploy_spec_path: None,
            registry_credential_id: None,
            default_environment_id: None,
            owner_id: None,
            auto_deploy: false,
            poll_interval_secs: None,
            created_at: now,
            updated_at: now,
        }
    }
}

/// How a project is built.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BuildKind {
    /// Standard Dockerfile build.
    Dockerfile,
    /// Docker Compose / Compose file.
    Compose,
    /// `ZLayer`-native `ZImagefile`.
    ZImagefile,
    /// `ZLayer` deployment spec.
    Spec,
}

impl std::fmt::Display for BuildKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuildKind::Dockerfile => f.write_str("dockerfile"),
            BuildKind::Compose => f.write_str("compose"),
            BuildKind::ZImagefile => f.write_str("zimagefile"),
            BuildKind::Spec => f.write_str("spec"),
        }
    }
}

// =========================================================================
// Variables
// =========================================================================

/// A stored variable — a plaintext key-value pair for template substitution
/// in deployment specs. Variables are NOT encrypted (unlike secrets). They
/// live in their own storage, separate from the encrypted secrets store.
///
/// Variables can be global (`scope = None`) or project-scoped
/// (`scope = Some(project_id)`).
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredVariable {
    /// UUID identifier.
    pub id: String,

    /// Variable name (e.g. `"APP_VERSION"`, `"LOG_LEVEL"`). Unique within a
    /// given scope.
    pub name: String,

    /// Plaintext variable value.
    pub value: String,

    /// Scope: project id or `None` for global.
    pub scope: Option<String>,

    /// When the variable was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the variable was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredVariable {
    /// Create a new variable record with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>, value: impl Into<String>, scope: Option<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            value: value.into(),
            scope,
            created_at: now,
            updated_at: now,
        }
    }
}

// =========================================================================
// Syncs
// =========================================================================

/// A stored sync resource (persistent record of a git-backed resource set).
///
/// A sync points at a directory within a project's checkout that contains
/// `ZLayer` resource YAMLs. On diff/apply the directory is scanned, compared
/// against current API state, and reconciled.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredSync {
    /// UUID identifier.
    pub id: String,

    /// Display name for this sync.
    pub name: String,

    /// Linked project id (the git checkout to scan).
    pub project_id: Option<String>,

    /// Path within the project's checkout to scan for resource YAMLs.
    pub git_path: String,

    /// Whether the sync should automatically apply on pull.
    #[serde(default)]
    pub auto_apply: bool,

    /// Whether the sync apply should delete resources that are present on the
    /// API but missing from the manifest directory. Defaults to `false` —
    /// the safer behaviour, which skips deletes and only creates/updates.
    #[serde(default)]
    pub delete_missing: bool,

    /// The commit SHA at which this sync was last applied.
    pub last_applied_sha: Option<String>,

    /// When the sync was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the sync was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredSync {
    /// Create a new sync record with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>, git_path: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            project_id: None,
            git_path: git_path.into(),
            auto_apply: false,
            delete_missing: false,
            last_applied_sha: None,
            created_at: now,
            updated_at: now,
        }
    }
}

// =========================================================================
// Tasks
// =========================================================================

/// A stored task — a named runnable script that can be executed on demand.
///
/// Tasks can be global (`project_id = None`) or project-scoped
/// (`project_id = Some(project_id)`).
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredTask {
    /// UUID identifier.
    pub id: String,

    /// Task name.
    pub name: String,

    /// Script type.
    pub kind: TaskKind,

    /// The script/command body.
    pub body: String,

    /// Project id this task belongs to. `None` = global.
    pub project_id: Option<String>,

    /// When the task was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the task was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredTask {
    /// Create a new task record with a fresh UUID.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        kind: TaskKind,
        body: impl Into<String>,
        project_id: Option<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            kind,
            body: body.into(),
            project_id,
            created_at: now,
            updated_at: now,
        }
    }
}

/// Script type for a task.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum TaskKind {
    /// A bash shell script executed via `sh -c`.
    Bash,
}

impl std::fmt::Display for TaskKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TaskKind::Bash => f.write_str("bash"),
        }
    }
}

/// A recorded execution of a task.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct TaskRun {
    /// UUID identifier of this run.
    pub id: String,

    /// The task that was executed.
    pub task_id: String,

    /// Process exit code (`None` if the task could not be started).
    pub exit_code: Option<i32>,

    /// Captured standard output.
    pub stdout: String,

    /// Captured standard error.
    pub stderr: String,

    /// When the run started.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub started_at: DateTime<Utc>,

    /// When the run finished (`None` if it has not finished yet).
    #[schema(value_type = Option<String>, example = "2026-04-15T12:00:01Z")]
    pub finished_at: Option<DateTime<Utc>>,
}

// =========================================================================
// Workflows
// =========================================================================

/// A stored workflow — a named sequence of steps forming a DAG that
/// composes tasks, project builds, deploys, and sync applies.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredWorkflow {
    /// UUID identifier.
    pub id: String,

    /// Workflow name.
    pub name: String,

    /// Ordered list of steps to execute sequentially.
    pub steps: Vec<WorkflowStep>,

    /// Optional project scope.
    pub project_id: Option<String>,

    /// When the workflow was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the workflow was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredWorkflow {
    /// Create a new workflow record with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>, steps: Vec<WorkflowStep>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            steps,
            project_id: None,
            created_at: now,
            updated_at: now,
        }
    }
}

/// A single step in a workflow.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct WorkflowStep {
    /// Step name (display label).
    pub name: String,

    /// The action to perform.
    pub action: WorkflowAction,

    /// Name of another step (or task id) to run on failure.
    #[serde(default)]
    pub on_failure: Option<String>,
}

/// The action a workflow step performs.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WorkflowAction {
    /// Execute a task by id.
    RunTask {
        /// The task id to run.
        task_id: String,
    },
    /// Build a project by id.
    BuildProject {
        /// The project id to build.
        project_id: String,
    },
    /// Deploy a project by id.
    DeployProject {
        /// The project id to deploy.
        project_id: String,
    },
    /// Apply a sync resource by id.
    ApplySync {
        /// The sync id to apply.
        sync_id: String,
    },
}

/// A recorded execution of a workflow.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct WorkflowRun {
    /// UUID identifier of this run.
    pub id: String,

    /// The workflow that was executed.
    pub workflow_id: String,

    /// Overall run status.
    pub status: WorkflowRunStatus,

    /// Per-step results.
    pub step_results: Vec<StepResult>,

    /// When the run started.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub started_at: DateTime<Utc>,

    /// When the run finished (`None` if still running).
    #[schema(value_type = Option<String>, example = "2026-04-15T12:00:01Z")]
    pub finished_at: Option<DateTime<Utc>>,
}

/// Overall status of a workflow run.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowRunStatus {
    /// Not yet started.
    Pending,
    /// Currently executing.
    Running,
    /// All steps completed successfully.
    Completed,
    /// A step failed.
    Failed,
}

impl std::fmt::Display for WorkflowRunStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorkflowRunStatus::Pending => f.write_str("pending"),
            WorkflowRunStatus::Running => f.write_str("running"),
            WorkflowRunStatus::Completed => f.write_str("completed"),
            WorkflowRunStatus::Failed => f.write_str("failed"),
        }
    }
}

/// Result of executing a single step in a workflow run.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StepResult {
    /// The step name.
    pub step_name: String,

    /// Step outcome: `"ok"`, `"failed"`, or `"skipped"`.
    pub status: String,

    /// Optional output or error message.
    pub output: Option<String>,
}

// =========================================================================
// Notifiers
// =========================================================================

/// A stored notifier — a named notification channel that fires alerts to
/// Slack, Discord, a generic webhook, or SMTP when triggered.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredNotifier {
    /// UUID identifier.
    pub id: String,

    /// Display name (e.g. `"deploy-alerts"`).
    pub name: String,

    /// Notification channel type.
    pub kind: NotifierKind,

    /// Channel-specific configuration (webhook URL, SMTP settings, etc.).
    pub config: NotifierConfig,

    /// Whether this notifier is active. Disabled notifiers are skipped.
    pub enabled: bool,

    /// When the notifier was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the notifier was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredNotifier {
    /// Create a new notifier record with a fresh UUID and `enabled = true`.
    #[must_use]
    pub fn new(name: impl Into<String>, kind: NotifierKind, config: NotifierConfig) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            kind,
            config,
            enabled: true,
            created_at: now,
            updated_at: now,
        }
    }
}

/// Notification channel type.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum NotifierKind {
    /// Slack incoming webhook.
    Slack,
    /// Discord webhook.
    Discord,
    /// Generic HTTP webhook.
    Webhook,
    /// SMTP email.
    Smtp,
}

impl std::fmt::Display for NotifierKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NotifierKind::Slack => f.write_str("slack"),
            NotifierKind::Discord => f.write_str("discord"),
            NotifierKind::Webhook => f.write_str("webhook"),
            NotifierKind::Smtp => f.write_str("smtp"),
        }
    }
}

/// Channel-specific configuration for a notifier.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NotifierConfig {
    /// Slack incoming webhook configuration.
    Slack {
        /// Slack webhook URL.
        webhook_url: String,
    },
    /// Discord webhook configuration.
    Discord {
        /// Discord webhook URL.
        webhook_url: String,
    },
    /// Generic HTTP webhook configuration.
    Webhook {
        /// Target URL.
        url: String,
        /// HTTP method (defaults to `"POST"`).
        #[serde(default)]
        method: Option<String>,
        /// Extra headers to send with the request.
        #[serde(default)]
        headers: Option<HashMap<String, String>>,
    },
    /// SMTP email configuration.
    Smtp {
        /// SMTP server host.
        host: String,
        /// SMTP server port.
        port: u16,
        /// SMTP username.
        username: String,
        /// SMTP password.
        password: String,
        /// Sender email address.
        from: String,
        /// Recipient email addresses.
        to: Vec<String>,
    },
}

// =========================================================================
// User groups
// =========================================================================

/// A stored user group for role-based access control.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredUserGroup {
    /// UUID identifier.
    pub id: String,

    /// Group name.
    pub name: String,

    /// Free-form description.
    pub description: Option<String>,

    /// When the group was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,

    /// When the group was last updated.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub updated_at: DateTime<Utc>,
}

impl StoredUserGroup {
    /// Create a new user group with a fresh UUID.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            name: name.into(),
            description: None,
            created_at: now,
            updated_at: now,
        }
    }
}

// =========================================================================
// Permissions
// =========================================================================

/// Whether a permission subject is a user or a group.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum SubjectKind {
    /// A single user.
    User,
    /// A user group.
    Group,
}

impl std::fmt::Display for SubjectKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubjectKind::User => f.write_str("user"),
            SubjectKind::Group => f.write_str("group"),
        }
    }
}

/// Access level for a resource permission, ordered from least to most
/// privilege.
#[derive(
    Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, utoipa::ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum PermissionLevel {
    /// No access.
    None,
    /// Read-only access.
    Read,
    /// Execute (e.g. deploy, run tasks) in addition to read.
    Execute,
    /// Full read/write/execute access.
    Write,
}

impl std::fmt::Display for PermissionLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PermissionLevel::None => f.write_str("none"),
            PermissionLevel::Read => f.write_str("read"),
            PermissionLevel::Execute => f.write_str("execute"),
            PermissionLevel::Write => f.write_str("write"),
        }
    }
}

/// A stored permission grant binding a subject (user or group) to a resource
/// with a specific access level.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct StoredPermission {
    /// UUID identifier of this permission grant.
    pub id: String,

    /// Whether the subject is a user or a group.
    pub subject_kind: SubjectKind,

    /// The user or group id.
    pub subject_id: String,

    /// The kind of resource (e.g. `"deployment"`, `"project"`, `"secret"`).
    pub resource_kind: String,

    /// A specific resource id, or `None` for a wildcard (all resources of
    /// that kind).
    pub resource_id: Option<String>,

    /// The granted access level.
    pub level: PermissionLevel,

    /// When the permission was created.
    #[schema(value_type = String, example = "2026-04-15T12:00:00Z")]
    pub created_at: DateTime<Utc>,
}

impl StoredPermission {
    /// Create a new permission grant with a fresh UUID.
    #[must_use]
    pub fn new(
        subject_kind: SubjectKind,
        subject_id: impl Into<String>,
        resource_kind: impl Into<String>,
        resource_id: Option<String>,
        level: PermissionLevel,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            subject_kind,
            subject_id: subject_id.into(),
            resource_kind: resource_kind.into(),
            resource_id,
            level,
            created_at: Utc::now(),
        }
    }
}

// =========================================================================
// OIDC identities
// =========================================================================

/// One OIDC identity link row.
///
/// One row is inserted the first time a user signs in via a given provider;
/// subsequent sign-ins look up the same row and reuse the linked `user_id`.
/// The uniqueness constraint on `(provider, subject)` enforces the
/// one-subject-one-user invariant.
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct OidcIdentity {
    /// Surrogate id (uuid).
    pub id: String,
    /// `ZLayer` user account this identity resolves to.
    pub user_id: String,
    /// Provider slug matching `OidcProviderConfig::name`.
    pub provider: String,
    /// The `sub` claim from the provider's ID token. Opaque.
    pub subject: String,
    /// Email returned by the provider at link time (informational only).
    pub email_at_link: Option<String>,
    #[schema(value_type = String, format = DateTime)]
    pub created_at: DateTime<Utc>,
    #[schema(value_type = String, format = DateTime)]
    pub updated_at: DateTime<Utc>,
}

impl OidcIdentity {
    /// Convenience constructor — fills `id`, `created_at`, `updated_at`.
    #[must_use]
    pub fn new(
        user_id: impl Into<String>,
        provider: impl Into<String>,
        subject: impl Into<String>,
        email_at_link: Option<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4().to_string(),
            user_id: user_id.into(),
            provider: provider.into(),
            subject: subject.into(),
            email_at_link,
            created_at: now,
            updated_at: now,
        }
    }
}

// =========================================================================
// Audit log
//
// `AuditEntry` is intentionally NOT moved here: it carries an
// `Option<serde_json::Value>` field, and `zlayer-types` does not depend on
// `serde_json`. Once a sibling migration adds the dep (or restructures the
// `details` field to a string), `AuditEntry` can move alongside the other
// `Stored*` types — it lives in `zlayer-api::storage` for now.
// =========================================================================