komodo_client 2.1.1

Client for the Komodo build and deployment system
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
use std::{collections::HashMap, sync::OnceLock};

use anyhow::Context;
use bson::{Document, doc};
use derive_builder::Builder;
use derive_default_builder::DefaultBuilder;
use indexmap::IndexSet;
use partial_derive2::Partial;
use serde::{
  Deserialize, Serialize,
  de::{IntoDeserializer, Visitor, value::MapAccessDeserializer},
};
use strum::Display;
use typeshare::typeshare;

use crate::{
  deserializers::{
    env_vars_deserializer, file_contents_deserializer,
    option_env_vars_deserializer, option_file_contents_deserializer,
    option_maybe_string_i64_deserializer,
    option_string_list_deserializer, string_list_deserializer,
  },
  entities::{
    EnvironmentVar, ImageDigest,
    docker::service::SwarmServiceListItem, environment_vars_from_str,
  },
};

use super::{
  FileContents, SystemCommand,
  docker::container::ContainerListItem,
  resource::{Resource, ResourceListItem, ResourceQuery},
};

#[cfg(feature = "utoipa")]
#[derive(utoipa::ToSchema)]
#[schema(as = Stack)]
pub struct StackSchema(
  #[schema(inline)] pub Resource<StackConfig, StackInfo>,
);

#[typeshare]
pub type Stack = Resource<StackConfig, StackInfo>;

impl Stack {
  /// If fresh is passed, it will bypass the deployed project name.
  /// and get the most up to date one from just project_name field falling back to stack name.
  pub fn project_name(&self, fresh: bool) -> String {
    if !fresh
      && let Some(project_name) = &self.info.deployed_project_name
    {
      return project_name.clone();
    }
    if self.config.project_name.is_empty() {
      self.name.clone()
    } else {
      self.config.project_name.clone()
    }
  }

  pub fn compose_file_paths(&self) -> &[String] {
    if self.config.file_paths.is_empty() {
      default_stack_file_paths()
    } else {
      &self.config.file_paths
    }
  }

  pub fn is_compose_file(&self, path: &str) -> bool {
    // First make sure its not a config file, which *could* also include
    // other compose files not directly treated as compose.
    if self.is_config_file(path) {
      return false;
    }
    for compose_path in self.compose_file_paths() {
      if path.ends_with(compose_path) {
        return true;
      }
    }
    false
  }

  pub fn is_config_file(&self, path: &str) -> bool {
    for file in &self.config.config_files {
      if path.ends_with(&file.path) {
        return true;
      }
    }
    false
  }

  /// Get tracked additional env files (those that Komodo should manage)
  fn tracked_env_files(&self) -> impl Iterator<Item = &str> {
    self
      .config
      .additional_env_files
      .iter()
      .filter(|f| f.track)
      .map(|f| f.path.as_str())
  }

  pub fn all_tracked_file_paths(&self) -> Vec<String> {
    let mut res = self
      .compose_file_paths()
      .iter()
      .cloned()
      // Makes sure to dedup them, while maintaining ordering
      .collect::<IndexSet<_>>();
    res.extend(self.tracked_env_files().map(str::to_string));
    res.extend(
      self.config.config_files.iter().map(|f| f.path.clone()),
    );
    res.into_iter().collect()
  }

  pub fn all_file_dependencies(&self) -> Vec<StackFileDependency> {
    let mut res = self
      .compose_file_paths()
      .iter()
      .cloned()
      .map(StackFileDependency::full_redeploy)
      // Makes sure to dedup them, while maintaining ordering
      .collect::<IndexSet<_>>();
    res.extend(
      self
        .tracked_env_files()
        .map(|p| StackFileDependency::full_redeploy(p.to_string())),
    );
    res.extend(self.config.config_files.clone());
    res.into_iter().collect()
  }
}

fn default_stack_file_paths() -> &'static [String] {
  static DEFAULT_FILE_PATHS: OnceLock<Vec<String>> = OnceLock::new();
  DEFAULT_FILE_PATHS
    .get_or_init(|| vec![String::from("compose.yaml")])
}

#[typeshare]
pub type StackListItem = ResourceListItem<StackListItemInfo>;

#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackListItemInfo {
  /// The swarm that stack is deployed on, when in Swarm mode.
  pub swarm_id: String,
  /// The server that stack is deployed on, when in Server mode.
  pub server_id: String,
  /// Whether stack is using files on host mode
  pub files_on_host: bool,
  /// Whether stack has file contents defined.
  pub file_contents: bool,
  /// Linked repo, if one is attached.
  pub linked_repo: String,
  /// The git provider domain
  pub git_provider: String,
  /// The configured repo
  pub repo: String,
  /// The configured branch
  pub branch: String,
  /// Full link to the repo.
  pub repo_link: String,
  /// The stack state
  pub state: StackState,
  /// A string given by docker conveying the status of the stack.
  pub status: Option<String>,
  /// The services that are part of the stack.
  /// If deployed, will be `deployed_services`.
  /// Otherwise, its `latest_services`
  pub services: Vec<StackServiceWithUpdate>,
  /// Whether the compose project is missing on the host.
  /// Ie, it does not show up in `docker compose ls`.
  /// If true, and the stack is not Down, this is an unhealthy state.
  pub project_missing: bool,
  /// If any compose files are missing in the repo, the path will be here.
  /// If there are paths here, this is an unhealthy state, and deploying will fail.
  pub missing_files: Vec<String>,
  /// Deployed short commit hash, or null. Only for repo based stacks.
  pub deployed_hash: Option<String>,
  /// Latest short commit hash, or null. Only for repo based stacks
  pub latest_hash: Option<String>,
}

#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackServiceWithUpdate {
  pub service: String,
  /// The service's image
  pub image: String,
  /// Whether there is a newer image available for this service
  pub update_available: bool,
}

#[typeshare]
#[derive(
  Debug,
  Clone,
  Copy,
  Default,
  PartialEq,
  Eq,
  PartialOrd,
  Ord,
  Serialize,
  Deserialize,
  Display,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
// Do this one snake_case in line with DeploymentState.
// Also in line with docker terminology.
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum StackState {
  /// The stack is currently re/deploying
  Deploying,
  /// All containers are running.
  Running,
  /// All containers are paused
  Paused,
  /// All contianers are stopped
  Stopped,
  /// All containers are created
  Created,
  /// All containers are restarting
  Restarting,
  /// All containers are dead
  Dead,
  /// All containers are removing
  Removing,
  /// The containers are in a mix of states
  Unhealthy,
  /// The stack is not deployed
  Down,
  /// Server not reachable for status
  #[default]
  Unknown,
}

#[typeshare]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackInfo {
  /// If any of the expected compose / additional files are missing in the repo,
  /// they will be stored here.
  #[serde(default)]
  pub missing_files: Vec<String>,

  /// The deployed project name.
  /// This is updated whenever Komodo successfully deploys the stack.
  /// If it is present, Komodo will use it for actions over other options,
  /// to ensure control is maintained after changing the project name (there is no rename compose project api).
  pub deployed_project_name: Option<String>,

  /// Deployed short commit hash, or null. Only for repo based stacks.
  pub deployed_hash: Option<String>,
  /// Deployed commit message, or null. Only for repo based stacks
  pub deployed_message: Option<String>,
  /// The deployed compose / additional file contents.
  /// This is updated whenever Komodo successfully deploys the stack.
  pub deployed_contents: Option<Vec<FileContents>>,
  /// The deployed service names.
  /// This is updated whenever it is empty, or deployed contents is updated.
  pub deployed_services: Option<Vec<StackServiceNames>>,
  /// The output of `docker compose config`.
  /// This is updated whenever Komodo successfully deploys the stack.
  pub deployed_config: Option<String>,
  /// The latest service names.
  /// This is updated whenever the stack cache refreshes, using the latest file contents (either db defined or remote).
  #[serde(default)]
  pub latest_services: Vec<StackServiceNames>,

  /// The remote compose / additional file contents, whether on host or in repo.
  /// This is updated whenever Komodo refreshes the stack cache.
  /// It will be empty if the file is defined directly in the stack config.
  pub remote_contents: Option<Vec<StackRemoteFileContents>>,
  /// If there was an error in getting the remote contents, it will be here.
  pub remote_errors: Option<Vec<FileContents>>,

  /// Latest commit hash, or null
  pub latest_hash: Option<String>,
  /// Latest commit message, or null
  pub latest_message: Option<String>,
}

#[typeshare(serialized_as = "Partial<StackConfig>")]
pub type _PartialStackConfig = PartialStackConfig;

/// The compose file configuration.
#[typeshare]
#[derive(Debug, Clone, Serialize, Deserialize, Builder, Partial)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[partial_derive(Debug, Clone, Default, Serialize, Deserialize)]
#[diff_derive(Debug, Clone, Default, Serialize, Deserialize)]
#[partial(skip_serializing_none, from, diff)]
pub struct StackConfig {
  /// The Swarm to deploy the Stack on, setting the Stack into Swarm mode.
  ///
  /// Note. If both swarm_id and server_id are set,
  /// swarm_id overrides server_id and the Stack will be in Swarm mode.
  #[serde(default, alias = "swarm")]
  #[partial_attr(serde(alias = "swarm"))]
  #[builder(default)]
  pub swarm_id: String,

  /// The Server to deploy the Stack on, setting the Stack into Compose mode.
  ///
  /// Note. If both swarm_id and server_id are set,
  /// swarm_id overrides server_id and the Stack will be in Swarm mode.
  #[serde(default, alias = "server")]
  #[partial_attr(serde(alias = "server"))]
  #[builder(default)]
  pub server_id: String,

  /// Configure quick links that are displayed in the resource header
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub links: Vec<String>,

  /// Optionally specify a custom project name for the stack.
  /// If this is empty string, it will default to the stack name.
  /// Used with `docker compose -p {project_name}` / `docker stack deploy {project_name}`.
  ///
  /// Note. Can be used to import pre-existing stacks with names that do not match Stack name.
  #[serde(default)]
  #[builder(default)]
  pub project_name: String,

  /// Whether to automatically `compose pull` before redeploying stack.
  /// Ensured latest images are deployed.
  /// Will fail if the compose file specifies a locally build image.
  ///
  /// Note. Not used in Swarm mode.
  #[serde(default = "default_auto_pull")]
  #[builder(default = "default_auto_pull()")]
  #[partial_default(default_auto_pull())]
  pub auto_pull: bool,

  /// Whether to `docker compose build` before `compose down` / `compose up`.
  /// Combine with build_extra_args for custom behaviors.
  ///
  /// Note. Not used in Swarm mode.
  #[serde(default)]
  #[builder(default)]
  pub run_build: bool,

  /// Whether to poll for any updates to the images.
  #[serde(default)]
  #[builder(default)]
  pub poll_for_updates: bool,

  /// Whether to automatically redeploy when
  /// newer images are found. Will implicitly
  /// enable `poll_for_updates`, you don't need to
  /// enable both.
  #[serde(default)]
  #[builder(default)]
  pub auto_update: bool,

  /// If auto update is enabled, Komodo will
  /// by default only update the specific services
  /// with image updates. If this parameter is set to true,
  /// Komodo will redeploy the whole Stack (all services).
  #[serde(default)]
  #[builder(default)]
  pub auto_update_all_services: bool,

  /// Whether to run `docker compose down` before `compose up`.
  #[serde(default)]
  #[builder(default)]
  pub destroy_before_deploy: bool,

  /// Whether to skip secret interpolation into the stack environment variables.
  #[serde(default)]
  #[builder(default)]
  pub skip_secret_interp: bool,

  /// Choose a Komodo Repo (Resource) to source the compose files.
  #[serde(default)]
  #[builder(default)]
  pub linked_repo: String,

  /// The git provider domain. Default: github.com
  #[serde(default = "default_git_provider")]
  #[builder(default = "default_git_provider()")]
  #[partial_default(default_git_provider())]
  pub git_provider: String,

  /// Whether to use https to clone the repo (versus http). Default: true
  ///
  /// Note. Komodo does not currently support cloning repos via ssh.
  #[serde(default = "default_git_https")]
  #[builder(default = "default_git_https()")]
  #[partial_default(default_git_https())]
  pub git_https: bool,

  /// The git account used to access private repos.
  /// Passing empty string can only clone public repos.
  ///
  /// Note. A token for the account must be available in the core config or the builder server's periphery config
  /// for the configured git provider.
  #[serde(default)]
  #[builder(default)]
  pub git_account: String,

  /// The repo used as the source of the build.
  /// {namespace}/{repo_name}
  #[serde(default)]
  #[builder(default)]
  pub repo: String,

  /// The branch of the repo.
  #[serde(default = "default_branch")]
  #[builder(default = "default_branch()")]
  #[partial_default(default_branch())]
  pub branch: String,

  /// Optionally set a specific commit hash.
  #[serde(default)]
  #[builder(default)]
  pub commit: String,

  /// Optionally set a specific clone path
  #[serde(default)]
  #[builder(default)]
  pub clone_path: String,

  /// By default, the Stack will `git pull` the repo after it is first cloned.
  /// If this option is enabled, the repo folder will be deleted and recloned instead.
  #[serde(default)]
  #[builder(default)]
  pub reclone: bool,

  /// Whether incoming webhooks actually trigger action.
  #[serde(default = "default_webhook_enabled")]
  #[builder(default = "default_webhook_enabled()")]
  #[partial_default(default_webhook_enabled())]
  pub webhook_enabled: bool,

  /// Optionally provide an alternate webhook secret for this stack.
  /// If its an empty string, use the default secret from the config.
  #[serde(default)]
  #[builder(default)]
  pub webhook_secret: String,

  /// By default, the Stack will `DeployStackIfChanged`.
  /// If this option is enabled, will always run `DeployStack` without diffing.
  #[serde(default)]
  #[builder(default)]
  pub webhook_force_deploy: bool,

  /// If this is checked, the stack will source the files on the host.
  /// Use `run_directory` and `file_paths` to specify the path on the host.
  /// This is useful for those who wish to setup their files on the host,
  /// rather than defining the contents in UI or in a git repo.
  #[serde(default)]
  #[builder(default)]
  pub files_on_host: bool,

  /// Directory to change to (`cd`) before running `docker compose up -d`.
  #[serde(default)]
  #[builder(default)]
  pub run_directory: String,

  /// Add paths to compose files, relative to the run path.
  /// If this is empty, will use file `compose.yaml`.
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub file_paths: Vec<String>,

  /// The name of the written environment file before `docker compose up`.
  /// Relative to the run directory root.
  /// Default: .env
  ///
  /// Note. Not used in Swarm mode.
  #[serde(default = "default_env_file_path")]
  #[builder(default = "default_env_file_path()")]
  #[partial_default(default_env_file_path())]
  pub env_file_path: String,

  /// Add additional env files to attach with `--env-file`.
  /// Relative to the run directory root.
  ///
  /// Note. It is already included as an `additional_file`.
  /// Don't add it again there.
  #[serde(default)]
  #[partial_attr(serde(default))]
  #[builder(default)]
  pub additional_env_files: Vec<AdditionalEnvFile>,

  /// Add additional config files either in repo or on host to track.
  /// Can add any files associated with the stack to enable editing them in the UI.
  /// Doing so will also include diffing these when deciding to deploy in `DeployStackIfChanged`.
  /// Relative to the run directory.
  ///
  /// Note. If the config file is .env and should be included in compose command
  /// using `--env-file`, add it to `additional_env_files` instead.
  #[serde(default)]
  #[partial_attr(serde(default))]
  #[builder(default)]
  pub config_files: Vec<StackFileDependency>,

  /// Whether to send StackStateChange alerts for this stack.
  #[serde(default = "default_send_alerts")]
  #[builder(default = "default_send_alerts()")]
  #[partial_default(default_send_alerts())]
  pub send_alerts: bool,

  /// Used with `registry_account` to login to a registry before docker compose up.
  #[serde(default)]
  #[builder(default)]
  pub registry_provider: String,

  /// Used with `registry_provider` to login to a registry before docker compose up.
  #[serde(default)]
  #[builder(default)]
  pub registry_account: String,

  /// The optional command to run before the Stack is deployed.
  #[serde(default)]
  #[builder(default)]
  pub pre_deploy: SystemCommand,

  /// The optional command to run after the Stack is deployed.
  #[serde(default)]
  #[builder(default)]
  pub post_deploy: SystemCommand,

  /// The extra arguments to pass to the deploy command.
  ///
  /// - For Compose stack, uses `docker compose up -d [EXTRA_ARGS]`.
  /// - For Swarm mode. `docker stack deploy [EXTRA_ARGS] STACK_NAME`
  ///
  /// If empty, no extra arguments will be passed.
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub extra_args: Vec<String>,

  /// The extra arguments to pass after `docker compose build`.
  /// If empty, no extra build arguments will be passed.
  /// Only used if `run_build: true`
  ///
  /// Note. Not used in Swarm mode.
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub build_extra_args: Vec<String>,

  /// Optional command wrapper for secrets management tools.
  /// Wraps the docker compose up command with a prefix command.
  /// Use [[COMPOSE_COMMAND]] as placeholder for the full compose command.
  ///
  /// Examples:
  /// - "op run -- [[COMPOSE_COMMAND]]" (1password CLI)
  /// - "sops exec-file --no-fifo /path/to/secret.env '[[COMPOSE_COMMAND]]'" (sops)
  #[serde(default)]
  #[builder(default)]
  pub compose_cmd_wrapper: String,

  /// Which compose subcommands should use the wrapper.
  /// Valid values for Compose: "config", "build", "pull", "up", "run"
  /// Valid values for Swarm: "config", "deploy"
  /// Default: [] (empty). If empty and wrapper is set, defaults to ["up"] (Compose) or ["deploy"] (Swarm).
  /// Set to ["config", "build", "pull", "up"] for sops exec-file with {} placeholder.
  #[serde(
    default = "default_wrapper_include",
    deserialize_with = "string_list_deserializer"
  )]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default = "default_wrapper_include()")]
  pub compose_cmd_wrapper_include: Vec<String>,

  /// Ignore certain services declared in the compose file when checking
  /// the stack status. For example, an init service might be exited, but the
  /// stack should be healthy. This init service should be in `ignore_services`
  #[serde(default, deserialize_with = "string_list_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_string_list_deserializer"
  ))]
  #[builder(default)]
  pub ignore_services: Vec<String>,

  /// The contents of the file directly, for management in the UI.
  /// If this is empty, it will fall back to checking git config for
  /// repo based compose file.
  /// Supports variable / secret interpolation.
  #[serde(default, deserialize_with = "file_contents_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_file_contents_deserializer"
  ))]
  #[builder(default)]
  pub file_contents: String,

  /// The environment variables passed to the compose file.
  /// They will be written to path defined in env_file_path,
  /// which is given relative to the run directory.
  ///
  /// If it is empty, no file will be written.
  ///
  /// Note. Not used in Swarm mode.
  #[serde(default, deserialize_with = "env_vars_deserializer")]
  #[partial_attr(serde(
    default,
    deserialize_with = "option_env_vars_deserializer"
  ))]
  #[builder(default)]
  pub environment: String,
}

impl StackConfig {
  pub fn builder() -> StackConfigBuilder {
    StackConfigBuilder::default()
  }

  pub fn env_vars(&self) -> anyhow::Result<Vec<EnvironmentVar>> {
    environment_vars_from_str(&self.environment)
      .context("Invalid environment")
  }
}

fn default_env_file_path() -> String {
  String::from(".env")
}

fn default_auto_pull() -> bool {
  true
}

fn default_git_provider() -> String {
  String::from("github.com")
}

fn default_git_https() -> bool {
  true
}

fn default_branch() -> String {
  String::from("main")
}

fn default_webhook_enabled() -> bool {
  true
}

fn default_send_alerts() -> bool {
  true
}

fn default_wrapper_include() -> Vec<String> {
  vec![]
}

impl Default for StackConfig {
  fn default() -> Self {
    Self {
      swarm_id: Default::default(),
      server_id: Default::default(),
      project_name: Default::default(),
      run_directory: Default::default(),
      file_paths: Default::default(),
      files_on_host: Default::default(),
      registry_provider: Default::default(),
      registry_account: Default::default(),
      file_contents: Default::default(),
      auto_pull: default_auto_pull(),
      poll_for_updates: Default::default(),
      auto_update: Default::default(),
      auto_update_all_services: Default::default(),
      ignore_services: Default::default(),
      pre_deploy: Default::default(),
      post_deploy: Default::default(),
      extra_args: Default::default(),
      environment: Default::default(),
      env_file_path: default_env_file_path(),
      additional_env_files: Default::default(),
      config_files: Default::default(),
      run_build: Default::default(),
      destroy_before_deploy: Default::default(),
      build_extra_args: Default::default(),
      compose_cmd_wrapper: Default::default(),
      compose_cmd_wrapper_include: default_wrapper_include(),
      skip_secret_interp: Default::default(),
      linked_repo: Default::default(),
      git_provider: default_git_provider(),
      git_https: default_git_https(),
      repo: Default::default(),
      branch: default_branch(),
      commit: Default::default(),
      clone_path: Default::default(),
      reclone: Default::default(),
      git_account: Default::default(),
      webhook_enabled: default_webhook_enabled(),
      webhook_secret: Default::default(),
      webhook_force_deploy: Default::default(),
      send_alerts: default_send_alerts(),
      links: Default::default(),
    }
  }
}

#[cfg(feature = "utoipa")]
impl utoipa::PartialSchema for PartialStackConfig {
  fn schema()
  -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
    utoipa::schema!(#[inline] std::collections::HashMap<String, serde_json::Value>).into()
  }
}

#[cfg(feature = "utoipa")]
impl utoipa::ToSchema for PartialStackConfig {}

#[typeshare]
#[derive(
  Debug, Clone, Default, PartialEq, Serialize, Deserialize,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ComposeProject {
  /// The compose project name.
  pub name: String,
  /// The status of the project, as returned by docker.
  pub status: Option<String>,
  /// The compose files included in the project.
  pub compose_files: Vec<String>,
}

#[typeshare]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackServiceNames {
  /// The name of the service
  pub service_name: String,
  /// Will either be the declared container_name in the compose file,
  /// or a pattern to match auto named containers.
  ///
  /// Auto named containers are composed of three parts:
  ///
  /// 1. The name of the compose project (top level name field of compose file).
  ///    This defaults to the name of the parent folder of the compose file.
  ///    Komodo will always set it to be the name of the stack, but imported stacks
  ///    will have a different name.
  /// 2. The service name
  /// 3. The replica number
  ///
  /// Example: stacko-mongo-1.
  ///
  /// This stores only 1. and 2., ie stacko-mongo.
  /// Containers will be matched via regex like `^container_name-?[0-9]*$``
  ///
  /// Note. Setting container_name is not supported by Swarm,
  /// so will always be 1. and 2. in Swarm mode.
  pub container_name: String,
  /// The services image.
  #[serde(default)]
  pub image: String,
  /// Store the associated image digest.
  /// This includes both the image name / tag, and the specific digest hash.
  pub image_digest: Option<ImageDigest>,
}

#[typeshare]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackService {
  /// The service name
  pub service: String,
  /// The service image
  pub image: String,
  /// The container (Server mode)
  pub container: Option<ContainerListItem>,
  /// The service (Swarm mode)
  pub swarm_service: Option<SwarmServiceListItem>,
  /// The service image digests
  pub image_digests: Option<Vec<ImageDigest>>,
}

#[typeshare]
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackActionState {
  pub pulling: bool,
  pub deploying: bool,
  pub starting: bool,
  pub restarting: bool,
  pub pausing: bool,
  pub unpausing: bool,
  pub stopping: bool,
  pub destroying: bool,
}

#[typeshare]
pub type StackQuery = ResourceQuery<StackQuerySpecifics>;

#[typeshare]
#[derive(
  Serialize, Deserialize, Debug, Clone, Default, DefaultBuilder,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackQuerySpecifics {
  /// Query only for Stacks on these Servers.
  /// If empty, does not filter by Server.
  /// Only accepts Server id (not name).
  #[serde(default)]
  pub server_ids: Vec<String>,
  /// Query only for Stacks with these linked repos.
  /// Only accepts Repo id (not name).
  #[serde(default)]
  pub linked_repos: Vec<String>,
  /// Filter syncs by their repo.
  #[serde(default)]
  pub repos: Vec<String>,
  /// Query only for Stack with available image updates.
  #[serde(default)]
  pub update_available: bool,
}

impl super::resource::AddFilters for StackQuerySpecifics {
  fn add_filters(&self, filters: &mut Document) {
    if !self.server_ids.is_empty() {
      filters
        .insert("config.server_id", doc! { "$in": &self.server_ids });
    }
    if !self.linked_repos.is_empty() {
      filters.insert(
        "config.linked_repo",
        doc! { "$in": &self.linked_repos },
      );
    }
    if !self.repos.is_empty() {
      filters.insert("config.repo", doc! { "$in": &self.repos });
    }
  }
}

/// Keeping this minimal for now as its only needed to parse the service names / container names,
/// and replica count. Not a typeshared type.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ComposeFile {
  /// If not provided, will default to the parent folder holding the compose file.
  pub name: Option<String>,
  #[serde(default)]
  pub services: HashMap<String, ComposeService>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ComposeService {
  pub image: Option<String>,
  pub container_name: Option<String>,
  pub deploy: Option<ComposeServiceDeploy>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ComposeServiceDeploy {
  #[serde(
    default,
    deserialize_with = "option_maybe_string_i64_deserializer"
  )]
  pub replicas: Option<i64>,
}

// PRE-1.19.1 BACKWARD COMPAT NOTE
// This was split from general FileContents in 1.19.1,
// and must maintain 2 way de/ser backward compatibility
// with the mentioned struct.
/// Same as [FileContents] with some extra
/// info specific to Stacks.
#[typeshare]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackRemoteFileContents {
  /// The path to the file
  pub path: String,
  /// The contents of the file
  pub contents: String,
  /// The services depending on this file,
  /// or empty for global requirement (eg all compose files and env files).
  #[serde(default)]
  pub services: Vec<String>,
  /// Whether diff requires Redeploy / Restart / None
  #[serde(default)]
  pub requires: StackFileRequires,
}

#[typeshare]
#[derive(
  Debug,
  Clone,
  Copy,
  PartialEq,
  Eq,
  Hash,
  Default,
  Serialize,
  Deserialize,
)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum StackFileRequires {
  /// Diff requires service redeploy.
  #[serde(alias = "redeploy")]
  Redeploy,
  /// Diff requires service restart
  #[serde(alias = "restart")]
  Restart,
  /// Diff requires no action. Default.
  #[default]
  #[serde(alias = "none")]
  None,
}

/// Additional env file configuration for Stack.
/// Supports backward compatibility with string-only format.
#[typeshare]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct AdditionalEnvFile {
  /// File path relative to run directory
  pub path: String,
  /// Whether Komodo should track this file's contents.
  /// If true (default), Komodo will read, display, diff, and validate.
  /// If false, only passed to docker compose via --env-file.
  /// Useful for externally managed files (e.g., sops decrypted files).
  #[serde(default = "default_true")]
  pub track: bool,
}

fn default_true() -> bool {
  true
}

/// Used with custom de/serializer for [AdditionalEnvFile]
#[derive(Deserialize)]
struct __AdditionalEnvFile {
  path: String,
  #[serde(default = "default_true")]
  track: bool,
}

impl<'de> Deserialize<'de> for AdditionalEnvFile {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    struct AdditionalEnvFileVisitor;

    impl<'de> Visitor<'de> for AdditionalEnvFileVisitor {
      type Value = AdditionalEnvFile;

      fn expecting(
        &self,
        formatter: &mut std::fmt::Formatter,
      ) -> std::fmt::Result {
        write!(formatter, "string or AdditionalEnvFile (object)")
      }

      fn visit_string<E>(self, path: String) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Ok(AdditionalEnvFile {
          path,
          track: default_true(),
        })
      }

      fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Self::visit_string(self, v.to_string())
      }

      fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
      where
        A: serde::de::MapAccess<'de>,
      {
        __AdditionalEnvFile::deserialize(
          MapAccessDeserializer::new(map).into_deserializer(),
        )
        .map(|v| AdditionalEnvFile {
          path: v.path,
          track: v.track,
        })
      }
    }

    deserializer.deserialize_any(AdditionalEnvFileVisitor)
  }
}

/// Configure additional file dependencies of the Stack.
#[typeshare]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct StackFileDependency {
  /// Specify the file
  pub path: String,
  /// Specify specific service/s
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub services: Vec<String>,
  /// Specify
  #[serde(default, skip_serializing_if = "is_none")]
  pub requires: StackFileRequires,
}

impl StackFileDependency {
  pub fn full_redeploy(path: String) -> StackFileDependency {
    StackFileDependency {
      path,
      services: Vec::new(),
      requires: StackFileRequires::Redeploy,
    }
  }
}

fn is_none(requires: &StackFileRequires) -> bool {
  matches!(requires, StackFileRequires::None)
}

/// Used with custom de/serializer for [StackFileDependency]
#[derive(Deserialize)]
struct __StackFileDependency {
  path: String,
  #[serde(
    default,
    alias = "service",
    deserialize_with = "string_list_deserializer"
  )]
  services: Vec<String>,
  #[serde(default, alias = "req")]
  requires: StackFileRequires,
}

impl<'de> Deserialize<'de> for StackFileDependency {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: serde::Deserializer<'de>,
  {
    struct StackFileDependencyVisitor;

    impl<'de> Visitor<'de> for StackFileDependencyVisitor {
      type Value = StackFileDependency;

      fn expecting(
        &self,
        formatter: &mut std::fmt::Formatter,
      ) -> std::fmt::Result {
        write!(formatter, "string or StackFileDependency (object)")
      }

      fn visit_string<E>(self, path: String) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Ok(StackFileDependency {
          path,
          services: Vec::new(),
          requires: StackFileRequires::None,
        })
      }

      fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
      where
        E: serde::de::Error,
      {
        Self::visit_string(self, v.to_string())
      }

      fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
      where
        A: serde::de::MapAccess<'de>,
      {
        __StackFileDependency::deserialize(
          MapAccessDeserializer::new(map).into_deserializer(),
        )
        .map(|v| StackFileDependency {
          path: v.path,
          services: v.services,
          requires: v.requires,
        })
      }
    }

    deserializer.deserialize_any(StackFileDependencyVisitor)
  }
}

// // This one is nice for TOML, but annoying to use in UI
// impl Serialize for StackFileDependency {
//   fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
//   where
//     S: serde::Serializer,
//   {
//     // Serialize to string in default case
//     if is_redeploy(&self.requires) && self.services.is_empty() {
//       return serializer.serialize_str(&self.path);
//     }
//     __StackFileDependency {
//       path: self.path.clone(),
//       services: self.services.clone(),
//       requires: self.requires,
//     }
//     .serialize(serializer)
//   }
// }