dsh_api 0.9.0

DSH resource management API client
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
//! # Defines DSH platforms and their properties

use crate::{DEFAULT_PLATFORMS, ENV_VAR_PLATFORM, ENV_VAR_PLATFORMS_FILE_NAME};
use itertools::Itertools;
use log::{debug, error, info};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use std::sync::LazyLock;
use std::{env, fs};

/// # Describes the DSH platforms and their properties
///
/// The `DshPlatform` enum has variants for all supported DSH platforms and can be used
/// to identify a platform when invoking a function,
/// to get platform related parameters, like domain names and endpoints or to construct
/// urls related to the platform.
///
/// # Examples
/// ```rust
/// # use std::convert::Infallible;
/// use dsh_api::platform::DshPlatform;
/// println!("start the 'my_app' app for tenant 'my-tenant' at platform 'my-platform'");
/// match DshPlatform::try_from("my-platform") {
///   Ok(platform) => {
///     println!(
///       "open the url {} in your browser",
///       platform.tenant_public_app_domain("my-tenant", "my_app")
///     )
///   }
///   Err(_) => println!("platform 'my-platform' is not recognized"),
/// }
/// ```
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DshPlatform {
  name: String,
  description: String,
  alias: String,
  #[serde(rename = "is-production")]
  is_production: bool,
  #[serde(rename = "cloud-provider")]
  cloud_provider: CloudProvider,
  region: Option<String>,
  #[serde(alias = "issuer-endpoint")]
  issuer_endpoint: String,
  realm: String,
  #[serde(rename = "public-domain")]
  public_domain: String,
  #[serde(rename = "private-domain")]
  private_domain: Option<String>,
}

/// # Cloud service provider that hosts a platform
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum CloudProvider {
  /// Amazon Web Services
  #[serde(rename = "aws")]
  AWS,
  /// Microsoft Azure
  #[serde(rename = "azure")]
  Azure,
}

const CLIENT_ID_SEPARATOR: &str = ":";

impl DshPlatform {
  /// Returns the endpoint for the DSH Rest API access token
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").access_token_endpoint(),
  ///   "https://auth.prod.cp-prod.dsh.prod.aws.kpn.com/auth/realms/dev-lz-dsh/protocol/openid-connect/token".to_string()
  /// );
  /// ```
  pub fn access_token_endpoint(&self) -> String {
    format!("{}/protocol/openid-connect/token", self.issuer_endpoint())
  }

  /// # Returns the optional short/alias platform name
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("np-aws-lz-dsh").alias(), "nplz");
  /// ```
  pub fn alias(&self) -> &str {
    self.alias.as_str()
  }

  /// # Returns all platforms
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// for platform in DshPlatform::all() {
  ///   println!("{} / {} -> {}", platform.name(), platform.alias(), platform.description());
  /// }
  /// ```
  pub fn all() -> &'static [DshPlatform] {
    &DSH_PLATFORMS
  }

  /// # Returns properly formatted bucket name
  ///
  /// Creates a bucket name from the bucket identifier for this platform and the provided tenant.
  /// For Azure this method requires the object store access key (stored as
  /// `system/objectstore/access_key_id` in the secret store).
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `bucket_id` - Bucket identifier.
  /// * `access_key` - Bucket access key. This value is mandatory for the Azure platform. For
  ///   AWS this parameter is not used (you can provide `None`).
  ///
  /// # Example
  /// ```
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").bucket_name("my-tenant", "my-bucket", None::<String>)?,
  ///   "dev-lz-dsh-my-tenant-my-bucket".to_string()
  /// );
  /// assert_eq!(
  ///   DshPlatform::new("prodaz").bucket_name("my-tenant", "my-bucket", Some("my-access-key"))?,
  ///   "prod-azure-dsh-my-tenant-my-bucket@my-access-key".to_string()
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn bucket_name(&self, tenant_name: impl Display, bucket_id: impl Display, access_key: Option<impl Display>) -> Result<String, String> {
    match self.cloud_provider {
      CloudProvider::AWS => Ok(format!("{}-{}-{}", self.realm, tenant_name, bucket_id)),
      CloudProvider::Azure => match access_key {
        Some(access_key) => Ok(format!("{}-{}-{}@{}", self.realm, tenant_name, bucket_id, access_key)),
        None => Err("bucket name for azure requires the bucket access secret system/objectstore/access_key_id".to_string()),
      },
    }
  }

  /// # Returns properly formatted client_id
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").client_id(), "robot:dev-lz-dsh".to_string());
  /// ```
  pub fn client_id(&self) -> String {
    format!("robot{}{}", CLIENT_ID_SEPARATOR, self.realm())
  }

  /// # Returns the cloud provider for the platform
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{CloudProvider, DshPlatform};
  /// assert_eq!(DshPlatform::new("nplz").cloud_provider(), &CloudProvider::AWS);
  /// ```
  pub fn cloud_provider(&self) -> &CloudProvider {
    &self.cloud_provider
  }

  /// # Returns the domain of the platform console
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").console_domain(),
  ///   "console.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn console_domain(&self) -> String {
    format!("console.{}", self.public_domain())
  }

  /// # Returns the url of the platform console
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").console_url(),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn console_url(&self) -> String {
    format!("https://{}", self.console_domain())
  }

  /// # Returns a description of the platform
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").description(), "Staging platform for KPN internal tenants");
  /// ```
  pub fn description(&self) -> &str {
    &self.description
  }

  /// Returns the endpoint for the http messaging api (multi)
  ///
  /// # Parameters
  /// * `mqtt_topic` - Mqtt topic name.
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").http_messaging_api_url_multi("my-topic"),
  ///   "https://api.dsh-dev.dsh.np.aws.kpn.com/data/v0/multi/my-topic".to_string()
  /// );
  /// ```
  pub fn http_messaging_api_url_multi(&self, mqtt_topic: impl Display) -> String {
    format!("https://{}/data/v0/multi/{}", self.rest_api_domain(), mqtt_topic)
  }

  /// Returns the endpoint for the http messaging api (single)
  ///
  /// # Parameters
  /// * `mqtt_topic` - Mqtt topic name.
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").http_messaging_api_url_single("my-topic"),
  ///   "https://api.dsh-dev.dsh.np.aws.kpn.com/data/v0/single/my-topic".to_string()
  /// );
  /// ```
  pub fn http_messaging_api_url_single(&self, mqtt_topic: impl Display) -> String {
    format!("https://{}/data/v0/single/{}", self.rest_api_domain(), mqtt_topic)
  }

  /// # Returns the internal domain name for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").internal_domain("my-tenant"),
  ///   "my-tenant.marathon.mesos".to_string()
  /// );
  /// ```
  pub fn internal_domain(&self, tenant_name: impl Display) -> String {
    format!("{}.marathon.mesos", tenant_name)
  }

  /// # Returns the internal domain name for a service
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").internal_service_domain("my-tenant", "my-service"),
  ///   "my-service.my-tenant.marathon.mesos".to_string()
  /// );
  /// ```
  pub fn internal_service_domain(&self, tenant_name: impl Display, service_name: impl Display) -> String {
    format!("{}.{}", service_name, self.internal_domain(tenant_name))
  }

  /// Returns the base issuer endpoint for openid connect
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").issuer_endpoint(),
  ///   "https://auth.prod.cp-prod.dsh.prod.aws.kpn.com/auth/realms/dev-lz-dsh"
  /// );
  /// ```
  pub fn issuer_endpoint(&self) -> &str {
    self.issuer_endpoint.as_str()
  }

  /// # Returns whether the platform is production
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("np-aws-lz-dsh").is_production(), false);
  /// ```
  pub fn is_production(&self) -> bool {
    self.is_production
  }

  /// Returns the endpoint for the mqtt messaging api
  ///
  /// It is preferred to use the endpoint in the mqtt token.
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").mqtt_messaging_api_endpoint(),
  ///   "mqtt.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn mqtt_messaging_api_endpoint(&self) -> String {
    format!("mqtt.{}", self.public_domain())
  }

  /// Returns the port for the mqtt messaging api
  ///
  /// It is preferred to use the endpoint in the mqtt token.
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").mqtt_messaging_api_port(), 8883);
  /// ```
  pub fn mqtt_messaging_api_port(&self) -> usize {
    8883
  }

  /// Returns the endpoint for fetching an MQTT token
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").mqtt_token_endpoint(),
  ///   "https://api.dsh-dev.dsh.np.aws.kpn.com/datastreams/v0/mqtt/token".to_string()
  /// );
  /// ```
  pub fn mqtt_token_endpoint(&self) -> String {
    format!("https://{}/datastreams/v0/mqtt/token", self.rest_api_domain())
  }

  /// # Returns the full platform name
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").name(), "np-aws-lz-dsh");
  /// ```
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Create platform from platform name
  ///
  /// # Panics
  /// This method will panic if the provided platform name is not valid.
  /// Use [`DshPlatform::try_from`] if you need to catch this situation.
  ///
  /// # Example
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("np-aws-lz-dsh").alias(), "nplz");
  /// assert_eq!(DshPlatform::new("nplz").name(), "np-aws-lz-dsh");
  /// ```
  ///
  /// The following example will panic.
  ///
  /// ```should_panic
  /// # use dsh_api::platform::DshPlatform;
  /// DshPlatform::new("illegal-platform-name");
  /// ```
  pub fn new(platform_name: &str) -> Self {
    match DshPlatform::try_from(platform_name) {
      Ok(dsh_platform) => dsh_platform,
      Err(error) => panic!("{}", error),
    }
  }

  /// # Returns the private domain
  ///
  /// The private domain for a platform is optional.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").private_domain(), Some("dsh-dev.dsh.np.aws.kpn.org"));
  /// ```
  pub fn private_domain(&self) -> Option<&str> {
    self.private_domain.as_deref()
  }

  /// # Returns the proxy broker vhost
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `number` - Proxy broker number.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_broker_vhost("my-tenant", "my-proxy", 2),
  ///   "my-proxy-2.my-tenant.np-aws-lz-dsh.kpn-dsh.com".to_string()
  /// );
  /// ```
  pub fn proxy_broker_vhost(&self, tenant_name: impl Display, proxy_name: impl Display, number: usize) -> String {
    format!("{}-{}.{}", proxy_name, number, self.proxy_vhost_domain(tenant_name))
  }

  /// # Returns the proxy common name
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_common_name("my-tenant"),
  ///   "brokers.kafka.my-tenant.np-aws-lz-dsh.kpn-dsh.com".to_string()
  /// );
  /// ```
  pub fn proxy_common_name(&self, tenant_name: impl Display) -> String {
    format!("brokers.kafka.{}", self.proxy_vhost_domain(tenant_name))
  }

  /// # Returns the proxy consumer name
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `number` - Proxy broker number.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_consumer_name("my-tenant", "my-proxy", 2),
  ///   "my-tenant_my-proxy_2".to_string()
  /// );
  /// ```
  pub fn proxy_consumer_name(&self, tenant_name: impl Display, proxy_name: impl Display, number: usize) -> String {
    format!("{}_{}_{}", tenant_name, proxy_name, number)
  }

  /// # Returns the proxy consumer name with acl groups
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `acl_group_name` - Acl group name.
  /// * `number` - Proxy broker number.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_consumer_name_acl_group("my-tenant", "my-acl-group", "my-proxy", 2),
  ///   "my-tenant.my-acl-group_my-proxy_2".to_string()
  /// );
  /// ```
  pub fn proxy_consumer_name_acl_group(&self, tenant_name: impl Display, acl_group_name: impl Display, proxy_name: impl Display, number: usize) -> String {
    format!("{}.{}_{}_{}", tenant_name, acl_group_name, proxy_name, number)
  }

  /// # Returns the proxy schema store vhost
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_schema_store_vhost("my-tenant", "my-proxy"),
  ///   "my-proxy-schema-store.kafka.my-tenant.np-aws-lz-dsh.kpn-dsh.com".to_string()
  /// );
  /// ```
  pub fn proxy_schema_store_vhost(&self, tenant_name: impl Display, proxy_name: impl Display) -> String {
    format!("{}-schema-store.kafka.{}", proxy_name, self.proxy_vhost_domain(tenant_name))
  }

  /// # Returns the proxy vhost domain
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_vhost_domain("my-tenant"),
  ///   "my-tenant.np-aws-lz-dsh.kpn-dsh.com".to_string()
  /// );
  /// ```
  pub fn proxy_vhost_domain(&self, tenant_name: impl Display) -> String {
    format!("{}.{}.kpn-dsh.com", tenant_name, &self.name)
  }

  /// # Returns the domain used for public vhosts
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").public_domain(), "dsh-dev.dsh.np.aws.kpn.com".to_string());
  /// ```
  pub fn public_domain(&self) -> &str {
    &self.public_domain
  }

  /// # Returns the public domain for a vhost
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").public_vhost_domain("my-vhost"),
  ///   "my-vhost.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn public_vhost_domain(&self, vhost_name: impl Display) -> String {
    format!("{}.{}", vhost_name, self.public_domain())
  }

  /// # Returns the realm for the platform
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").realm(), "dev-lz-dsh");
  /// ```
  pub fn realm(&self) -> &str {
    &self.realm
  }

  /// # Returns the cloud provider region for the platform
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::new("nplz").region().unwrap(), "eu-west-1");
  /// ```
  pub fn region(&self) -> Option<&str> {
    self.region.as_deref()
  }

  /// # Returns the domain for the DSH Rest API
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").rest_api_domain(),
  ///   "api.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn rest_api_domain(&self) -> String {
    format!("api.{}", self.public_domain())
  }

  /// # Returns the endpoint for the DSH Rest API
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").rest_api_endpoint(),
  ///   "https://api.dsh-dev.dsh.np.aws.kpn.com/resources/v0".to_string()
  /// );
  /// ```
  pub fn rest_api_endpoint(&self) -> String {
    format!("https://{}/resources/v0", self.rest_api_domain())
  }

  /// Returns the endpoint for fetching a rest token
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").rest_token_endpoint(),
  ///   "https://api.dsh-dev.dsh.np.aws.kpn.com/auth/v0/token".to_string()
  /// );
  /// ```
  pub fn rest_token_endpoint(&self) -> String {
    format!("https://{}/auth/v0/token", self.rest_api_domain())
  }

  /// # Returns the url of the platform swagger page
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").swagger_url(),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/tenant-api/spec?url=/tenant-api/assets/openapi.json".to_string()
  /// );
  /// ```
  pub fn swagger_url(&self) -> String {
    format!("https://{}/tenant-api/spec?url=/tenant-api/assets/openapi.json", self.console_domain())
  }

  /// # Returns the url of the app in the app catalog for a tenant
  ///
  /// Note that this method also requires the `vendor` to be specified.
  /// This will most likely be `kpn`.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_app_catalog_app_url("my-tenant", "kpn", "my-app"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant/app-catalog/app/kpn%2Fmy-app"
  ///     .to_string()
  /// );
  /// ```
  pub fn tenant_app_catalog_app_url(&self, tenant_name: impl Display, vendor_name: impl Display, app_name: impl Display) -> String {
    format!(
      "https://{}/#/profiles/{}/app-catalog/app/{}%2F{}",
      self.console_domain(),
      tenant_name,
      vendor_name,
      app_name
    )
  }

  /// # Returns the url of the app catalog for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_app_catalog_url("my-tenant"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant/app-catalog".to_string()
  /// );
  /// ```
  pub fn tenant_app_catalog_url(&self, tenant_name: impl Display) -> String {
    format!("https://{}/#/profiles/{}/app-catalog", self.console_domain(), tenant_name)
  }

  /// # Returns the url of the platform console for a tenant app
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_app_console_url("my-tenant", "my-app"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant/services/my-app/app"
  ///     .to_string()
  /// );
  /// ```
  pub fn tenant_app_console_url(&self, tenant_name: impl Display, app_name: impl Display) -> String {
    format!("{}/services/{}/app", self.tenant_console_url(tenant_name), app_name)
  }

  /// # Returns properly formatted client_id for tenant
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_client_id("my-tenant"),
  ///   "robot:dev-lz-dsh:my-tenant".to_string()
  /// );
  /// ```
  pub fn tenant_client_id(&self, tenant_name: impl Display) -> String {
    format!("{}{}{}", self.client_id(), CLIENT_ID_SEPARATOR, tenant_name)
  }

  /// # Returns the url of the platform console for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_console_url("my-tenant"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant".to_string()
  /// );
  /// ```
  pub fn tenant_console_url(&self, tenant_name: impl Display) -> String {
    format!("{}/#/profiles/{}", self.console_url(), tenant_name)
  }

  /// # Returns the url of the data catalog for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_app_catalog_url("my-tenant"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant/app-catalog".to_string()
  /// );
  /// ```
  pub fn tenant_data_catalog_url(&self, tenant_name: impl Display) -> String {
    format!("https://{}/#/profiles/{}/data-catalog", self.console_domain(), tenant_name)
  }

  /// # Returns the url of the platform monitoring page for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_monitoring_url("my-tenant"),
  ///   "https://monitoring-my-tenant.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn tenant_monitoring_url(&self, tenant_name: impl Display) -> String {
    format!("https://monitoring-{}", self.tenant_public_domain(tenant_name))
  }

  /// # Returns the private domain for a tenant
  ///
  /// The private domain for a tenant can only be constructed if the optional private domain
  /// for the platform is defined. If it is not, an `Err` will be returned.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_private_domain("my-tenant")?,
  ///   "my-tenant.dsh-dev.dsh.np.aws.kpn.org".to_string()
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_private_domain(&self, tenant_name: impl Display) -> Result<String, String> {
    match self.private_domain() {
      Some(private_domain) => Ok(format!("{}.{}", tenant_name, private_domain)),
      None => Err(format!("private domain is not set for platform {}", self.name())),
    }
  }

  /// # Returns the private domain for a vhost
  ///
  /// The private domain for a vhost can only be constructed if the optional private domain
  /// for the platform is defined. If it is not, an `Err` will be returned.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_private_vhost_domain("my-tenant", "my-vhost")?,
  ///   "my-vhost.my-tenant.dsh-dev.dsh.np.aws.kpn.org".to_string()
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_private_vhost_domain(&self, tenant_name: impl Display, vhost_name: impl Display) -> Result<String, String> {
    self
      .tenant_private_domain(tenant_name)
      .map(|tenant_private_domain| format!("{}.{}", vhost_name, tenant_private_domain))
  }

  /// # Returns the private bootstrap servers for a configured proxy
  ///
  /// The private bootstrap server can only be constructed if the optional private domain
  /// for the platform is defined. If it is not, an `Err` will be returned.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .tenant_proxy_private_bootstrap_servers("my-tenant", "my-proxy")?
  ///     .first()
  ///     .unwrap(),
  ///   "my-proxy-0.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.org:9091"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_proxy_private_bootstrap_servers(&self, tenant_name: impl Display, proxy_name: impl Display) -> Result<Vec<String>, String> {
    self.tenant_private_domain(tenant_name).map(|tenant_private_domain| {
      [0, 1, 2]
        .iter()
        .map(|n| format!("{}-{}.kafka.{}:9091", proxy_name, n, tenant_private_domain))
        .collect_vec()
    })
  }

  /// # Returns the private schema store host for a configured proxy
  ///
  /// The private schema store host can only be constructed if the optional private domain
  /// for the platform is defined. If it is not, an `Err` will be returned.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_proxy_private_schema_store_host("my-tenant", "my-proxy")?,
  ///   "my-proxy-schema-store.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.org:9091"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_proxy_private_schema_store_host(&self, tenant_name: impl Display, proxy_name: impl Display) -> Result<String, String> {
    self
      .tenant_private_domain(tenant_name)
      .map(|tenant_private_domain| format!("{}-schema-store.kafka.{}:9091", proxy_name, tenant_private_domain))
  }

  /// # Returns the public bootstrap servers for a configured proxy
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .tenant_proxy_public_bootstrap_servers("my-tenant", "my-proxy")
  ///     .first()
  ///     .unwrap(),
  ///   "my-proxy-0.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com:9091"
  /// );
  /// ```
  pub fn tenant_proxy_public_bootstrap_servers(&self, tenant_name: impl Display, proxy_name: impl Display) -> Vec<String> {
    let tenant_string = tenant_name.to_string();
    [0, 1, 2]
      .iter()
      .map(|n| format!("{}-{}.kafka.{}:9091", proxy_name, n, self.tenant_public_domain(&tenant_string)))
      .collect_vec()
  }

  /// # Returns the public schema store host for a configured proxy
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_proxy_public_schema_store_host("my-tenant", "my-proxy"),
  ///   "my-proxy-schema-store.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com:9091"
  /// );
  /// ```
  pub fn tenant_proxy_public_schema_store_host(&self, tenant_name: impl Display, proxy_name: impl Display) -> String {
    format!("{}-schema-store.kafka.{}:9091", proxy_name, self.tenant_public_domain(tenant_name))
  }

  /// # Returns the public domain for an app
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_public_app_domain("my-tenant", "my-app-vhost"),
  ///   "my-app-vhost.my-tenant.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn tenant_public_app_domain(&self, tenant_name: impl Display, app_name: impl Display) -> String {
    format!("{}.{}", app_name, self.tenant_public_domain(tenant_name))
  }

  /// # Returns the public domain for apps
  ///
  /// This method is deprecated. Use [`tenant_public_domain`](self.tenant_public_domain) instead.
  #[deprecated]
  pub fn tenant_public_apps_domain(&self, tenant_name: impl Display) -> String {
    self.tenant_public_domain(tenant_name)
  }

  /// # Returns the public domain for a tenant
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_public_domain("my-tenant"),
  ///   "my-tenant.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn tenant_public_domain(&self, tenant_name: impl Display) -> String {
    format!("{}.{}", tenant_name, self.public_domain)
  }

  /// # Returns the url of the platform console for a tenant and service
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_service_console_url("my-tenant", "cmd"),
  ///   "https://console.dsh-dev.dsh.np.aws.kpn.com/#/profiles/my-tenant/services/cmd/service"
  ///     .to_string()
  /// );
  /// ```
  pub fn tenant_service_console_url(&self, tenant_name: impl Display, service_name: impl Display) -> String {
    format!("{}/services/{}/service", self.tenant_console_url(tenant_name), service_name)
  }

  /// # Returns the url of the tracing application
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tracing_url(),
  ///   "https://tracing.dsh-dev.dsh.np.aws.kpn.com".to_string()
  /// );
  /// ```
  pub fn tracing_url(&self) -> String {
    format!("https://tracing.{}", self.public_domain())
  }

  /// # Returns the default platform
  ///
  /// This method will read the value of the environment variable `DSH_API_PLATFORM` and
  /// will select the platform from this value. It will return an `Err<String>`
  /// when the environment variable is not set or contains an undefined value.
  ///
  /// # Example
  /// ```
  /// # use dsh_api::platform::DshPlatform;
  /// match DshPlatform::try_default() {
  ///   Ok(default_platform) => println!("default platform is {}", default_platform),
  ///   Err(error) => println!("no default platform: {}", error),
  /// }
  /// ```
  pub fn try_default() -> Result<Self, String> {
    match env::var(ENV_VAR_PLATFORM) {
      Ok(platform_name_from_env_var) => match DshPlatform::try_from(platform_name_from_env_var.as_str()) {
        Ok(platform) => {
          debug!("platform '{}' (environment variable '{}')", platform, ENV_VAR_PLATFORM);
          Ok(platform)
        }
        Err(_) => Err(format!(
          "environment variable {} contains invalid platform name '{}' (possible values: {})",
          ENV_VAR_PLATFORM,
          platform_name_from_env_var,
          DSH_PLATFORMS
            .iter()
            .map(|dsh_platform| format!("{}/{}", dsh_platform.name(), dsh_platform.alias()))
            .collect_vec()
            .join(", ")
        )),
      },
      Err(_) => Err(format!("environment variable '{}' not set", ENV_VAR_PLATFORM)),
    }
  }
}

impl Default for DshPlatform {
  /// Returns the default platform
  ///
  /// This method will read the value of the environment variable `DSH_API_PLATFORM` and
  /// will select the platform from this value.
  ///
  /// # Panics
  /// This method will panic if the environment variable is not set or
  /// if it contains an invalid platform name.
  ///
  /// # Example
  /// ```ignore
  /// # use dsh_api::platform::DshPlatform;
  /// println!("default platform is {}", DshPlatform::default());
  /// ```
  fn default() -> Self {
    match DshPlatform::try_default() {
      Ok(dsh_platform) => {
        info!("default dsh platform {} created", dsh_platform);
        dsh_platform
      }
      Err(error) => panic!("{}", error),
    }
  }
}

impl Display for DshPlatform {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.name())
  }
}

impl Display for CloudProvider {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      CloudProvider::AWS => write!(f, "aws"),
      CloudProvider::Azure => write!(f, "azure"),
    }
  }
}

impl TryFrom<&str> for DshPlatform {
  type Error = String;

  /// # Converts a platform name to a `DshPlatform`
  ///
  /// Both a full name and an alias are accepted.
  ///
  /// Use [from_str()](Self::from_str) instead.
  ///
  /// # Example
  /// ```rust
  /// use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::try_from("np-aws-lz-dsh").unwrap().alias(), "nplz");
  /// assert_eq!(DshPlatform::try_from("nplz").unwrap().name(), "np-aws-lz-dsh");
  /// assert!(DshPlatform::try_from("illegal-platform-name").is_err());
  /// ```
  fn try_from(platform_name: &str) -> Result<Self, Self::Error> {
    Self::from_str(platform_name)
  }
}

impl FromStr for DshPlatform {
  type Err = String;

  /// # Converts a platform name to a `DshPlatform`
  ///
  /// Both a full name and an alias are accepted.
  ///
  /// # Example
  /// ```rust
  /// # use std::str::FromStr;
  /// use dsh_api::platform::DshPlatform;
  /// assert_eq!(DshPlatform::from_str("np-aws-lz-dsh").unwrap().alias(), "nplz");
  /// assert_eq!(DshPlatform::from_str("nplz").unwrap().name(), "np-aws-lz-dsh");
  /// assert!(DshPlatform::from_str("illegal-platform-name").is_err());
  /// ```
  fn from_str(platform_name: &str) -> Result<Self, Self::Err> {
    match DSH_PLATFORMS
      .iter()
      .find(|dsh_platform| dsh_platform.name() == platform_name || dsh_platform.alias() == platform_name)
    {
      Some(platform) => Ok(platform.clone()),
      None => Err(format!(
        "invalid platform name '{}' (possible values: {})",
        platform_name,
        DSH_PLATFORMS
          .iter()
          .map(|dsh_platform| format!("{}/{}", dsh_platform.name(), dsh_platform.alias()))
          .collect_vec()
          .join(", ")
      )),
    }
  }
}

// Static list of all recognized DSH platforms, lazily initialized
static DSH_PLATFORMS: LazyLock<Vec<DshPlatform>> = LazyLock::new(|| match env::var(ENV_VAR_PLATFORMS_FILE_NAME) {
  Ok(platform_file_name_from_env_var) => match fs::read_to_string(&platform_file_name_from_env_var) {
    Ok(platform_list_from_file) => match serde_json::from_str(platform_list_from_file.as_str()) {
      Ok(mut dsh_platforms_from_file) => {
        if let Err(validation_error) = check_for_duplicate_names_or_aliases(&dsh_platforms_from_file) {
          error!("{}", validation_error);
          panic!("{}", validation_error)
        }
        dsh_platforms_from_file.sort_by(|platform_a, platform_b| platform_a.name.cmp(&platform_b.name));
        info!("dsh platform list read from '{}'", platform_file_name_from_env_var);
        dsh_platforms_from_file
      }
      Err(parse_error) => {
        let message = format!("invalid platforms file '{}' ({})", platform_file_name_from_env_var, parse_error);
        error!("{}", message);
        panic!("{}", message)
      }
    },
    Err(file_error) => {
      let message = format!("unable to read platforms file '{}' ({})", platform_file_name_from_env_var, file_error);
      error!("{}", message);
      panic!("{}", message)
    }
  },
  Err(_) => match serde_json::from_str::<Vec<DshPlatform>>(DEFAULT_PLATFORMS) {
    Ok(mut default_dsh_platforms) => {
      default_dsh_platforms.sort_by(|platform_a, platform_b| platform_a.name.cmp(&platform_b.name));
      debug!("default platform list");
      default_dsh_platforms
    }
    Err(_) => panic!(),
  },
});

// Check whether duplicate names or aliases exist
#[allow(suspicious_double_ref_op)]
fn check_for_duplicate_names_or_aliases(platforms: &Vec<DshPlatform>) -> Result<(), String> {
  let mut names_and_aliases: Vec<&str> = vec![];
  for platform in platforms {
    names_and_aliases.push(platform.name.as_str());
    names_and_aliases.push(platform.alias.as_str());
  }
  names_and_aliases.sort();
  let mut duplicates = Vec::new();
  for (name_or_alias, chunk) in &names_and_aliases.into_iter().chunk_by(|b| b.clone()) {
    if chunk.collect_vec().len() > 1 {
      duplicates.push(name_or_alias);
    }
  }
  if !duplicates.is_empty() {
    Err(format!(
      "platforms file contains duplicate names and/or aliases ({})",
      duplicates.into_iter().join(", ")
    ))
  } else {
    Ok(())
  }
}