dsh_api 0.10.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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! # Defines DSH platforms and their properties

use crate::error::{DshApiError, DshApiResult};
use crate::{DEFAULT_PLATFORMS, ENV_VAR_PLATFORM, ENV_VAR_PLATFORMS_FILE_NAME};
use itertools::Itertools;
use log::{debug, error, info};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
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.
///
/// # Example
///
/// ```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,
}

/// Selects the vhost zone
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum VhostZone {
  #[serde(rename = "private")]
  Private,
  #[serde(rename = "public")]
  Public,
}

#[rustfmt::skip]
/// Custom serializer serializes to platform name.
///
/// Custom serializer for `DshPlatform`. If you include a `DshPlatform` in an enum, struct or
/// tuple that implements `Serialize`, the serialized output will include the complete
/// serialized `DshPlatform` struct with all its fields. If all you want or need is the `name` of
/// the platform, you can set the `serialize_with`[^ser] and `deserialize_with`[^des]
/// attributes to this function and its companion function [`deserialize_platform`].
///
/// If you prefer to use the `alias` instead of the `name`, see [`serialize_platform_alias`].
///
/// # Example
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// use dsh_api::platform::{deserialize_platform, serialize_platform, DshPlatform};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// pub struct StructUnderTest {
///   #[serde(deserialize_with = "deserialize_platform",
///           serialize_with = "serialize_platform")]
///   pub platform: DshPlatform,
/// }
///
/// let sut = StructUnderTest { platform: DshPlatform::new("nplz") };
/// let serialized_sut = serde_json::to_string(&sut)?;
/// assert_eq!(serialized_sut, r#"{"platform":"np-aws-lz-dsh"}"#);
/// let deserialized_sut = serde_json::from_str(&serialized_sut)?;
/// assert_eq!(sut, deserialized_sut);
/// # Ok(())
/// # }
/// ```
///
/// [^des]: <https://serde.rs/field-attrs.html#deserialize_with>
/// [^ser]: <https://serde.rs/field-attrs.html#serialize_with>
pub fn serialize_platform<S>(platform: &DshPlatform, serialize: S) -> Result<S::Ok, S::Error>
where
  S: Serializer,
{
  serialize.serialize_str(platform.name())
}

#[rustfmt::skip]
/// Custom serializer serializes to platform alias.
///
/// Custom serializer for `DshPlatform`. If you include a `DshPlatform` in an enum, struct or
/// tuple that implements `Serialize`, the serialized output will include the complete
/// serialized `DshPlatform` struct with all its fields. If all you want or need is the `alias` of
/// the platform, you can set the `serialize_with`[^ser] and `deserialize_with`[^des]
/// attributes to this function and its companion function [`deserialize_platform`].
///
/// If you prefer to use the `name` instead of the `alias`, see [`serialize_platform`].
///
/// # Example
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// use dsh_api::platform::{
///   deserialize_platform,
///   serialize_platform_alias,
///   DshPlatform
/// };
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// pub struct StructUnderTest {
///   #[serde(deserialize_with = "deserialize_platform",
///           serialize_with = "serialize_platform_alias")]
///   pub platform: DshPlatform,
/// }
///
/// let sut = StructUnderTest { platform: DshPlatform::new("np-aws-lz-dsh") };
/// let serialized_sut = serde_json::to_string(&sut)?;
/// assert_eq!(serialized_sut, r#"{"platform":"nplz"}"#);
/// let deserialized_sut = serde_json::from_str(&serialized_sut)?;
/// assert_eq!(sut, deserialized_sut);
/// # Ok(())
/// # }
/// ```
///
/// [^des]: <https://serde.rs/field-attrs.html#deserialize_with>
/// [^ser]: <https://serde.rs/field-attrs.html#serialize_with>
pub fn serialize_platform_alias<S>(platform: &DshPlatform, serialize: S) -> Result<S::Ok, S::Error>
where
  S: Serializer,
{
  serialize.serialize_str(platform.alias())
}

#[rustfmt::skip]
/// Custom deserializer deserializes from platform name or alias.
///
/// Custom deserializer for `DshPlatform`. If you include a `DshPlatform` in an enum, struct or
/// tuple that implements `Deserialize`, this custom deserializer will expect just the `name`
/// or `alias` for the value of the field, instead of the entire `DshPlatform` struct. To
/// accomplish this, set the `serialize_with`[^ser] and `deserialize_with`[^des] attributes
/// to this function and its companion function [`serialize_platform`].
///
/// # Examples
///
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// use dsh_api::platform::{deserialize_platform, serialize_platform, DshPlatform};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
///
/// #[derive(Debug, Deserialize, PartialEq, Serialize)]
/// pub struct StructUnderTest {
///   #[serde(deserialize_with = "deserialize_platform",
///           serialize_with = "serialize_platform")]
///   pub platform: DshPlatform,
/// }
///
/// let sut_json = r#"{"platform":"np-aws-lz-dsh"}"#;
/// let sut = serde_json::from_str::<StructUnderTest>(sut_json)?;
/// assert_eq!(sut, StructUnderTest { platform: DshPlatform::new("nplz") });
/// let serialized_sut = serde_json::to_string(&sut)?;
/// assert_eq!(serialized_sut, sut_json);
/// # Ok(())
/// # }
/// ```
///
/// [^des]: <https://serde.rs/field-attrs.html#deserialize_with>
/// [^ser]: <https://serde.rs/field-attrs.html#serialize_with>
pub fn deserialize_platform<'de, D>(deserializer: D) -> Result<DshPlatform, D::Error>
where
  D: Deserializer<'de>,
{
  DshPlatform::from_str(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}

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"
  /// );
  /// ```
  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 list of 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"
  /// );
  /// 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"
  /// );
  /// # 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.
  ///
  /// This method is deprecated, use [`DshPlatform::robot_client_id`] instead.
  #[deprecated]
  pub fn client_id(&self) -> String {
    self.robot_client_id()
  }

  /// 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");
  /// ```
  pub fn console_domain(&self) -> String {
    format!("console.{}", self.public_domain())
  }

  #[rustfmt::skip]
  /// 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"
  /// );
  /// ```
  pub fn console_url(&self) -> String {
    format!("https://{}", self.console_domain())
  }

  /// Returns the consumer group for a service.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `service_name` - Name/id of the service.
  /// * `index` - Proxy consumer group index.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz").consumer_group("my-tenant", "my-service", 2),
  ///   "my-tenant_my-service_2"
  /// );
  /// ```
  pub fn consumer_group(&self, tenant_name: impl Display, service_name: impl Display, index: usize) -> String {
    format!("{}_{}_{}", tenant_name, service_name, index)
  }

  #[rustfmt::skip]
  /// 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
  }

  #[rustfmt::skip]
  /// Returns the private or public domain.
  ///
  /// The private domain for a platform is optional.
  ///
  /// # Parameters
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// assert_eq!(
  ///   DshPlatform::new("nplz").domain(VhostZone::Private),
  ///   Ok("dsh-dev.dsh.np.aws.kpn.org")
  /// );
  /// ```
  pub fn domain(&self, vhost_zone: VhostZone) -> DshApiResult<&str> {
    match vhost_zone {
      VhostZone::Private => match self.private_domain() {
        Some(private_domain) => Ok(private_domain),
        None => Err(DshApiError::parameter(format!("platform '{}' does not support private vhosts", self))),
      },
      VhostZone::Public => Ok(self.public_domain()),
    }
  }

  #[rustfmt::skip]
  /// Finds a platform from a domain name.
  ///
  /// Tries to find a platform that matches the provided private or public domain name.
  ///
  /// # Parameters
  /// * `domain_name` - Domain to match against.
  ///
  /// # Example
  /// ```rust
  /// # use std::str::FromStr;
  /// use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// use dsh_api::platform::VhostZone;
  /// let (platform, vhost_zone) = DshPlatform::from_domain("dsh.np.aws.kpn.com")?.unwrap();
  /// assert_eq!(platform, DshPlatform::new("nplz"));
  /// assert_eq!(vhost_zone, VhostZone::Public);
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// # Returns
  /// * `Ok(Some((DshPlatform, VhostZone::Public)))` - When a single platform with a matching
  ///   public vhost domain was found.
  /// * `Ok(Some((DshPlatform, VhostZone::Private)))` - When a single platform with a matching
  ///   private vhost domain was found.
  /// * `Ok(None)` - When no match was found.
  /// * `Err()` - When multiple matches were found.
  pub fn from_domain(domain_name: &str) -> DshApiResult<Option<(Self, VhostZone)>> {
    let matching_platforms: Vec<(DshPlatform, VhostZone)> = DSH_PLATFORMS
      .iter()
      .filter_map(|platform| {
        match (
          platform.public_domain.ends_with(domain_name),
          platform.private_domain.as_ref().is_some_and(|private_domain| private_domain.ends_with(domain_name)),
        ) {
          (false, false) => None,
          (false, true) => Some((platform.clone(), VhostZone::Private)),
          (true, false) => Some((platform.clone(), VhostZone::Public)),
          (true, true) => None,
        }
      })
      .collect_vec();
    match matching_platforms.len() {
      0 => Ok(None),
      1 => Ok(matching_platforms.first().cloned()),
      _ => Err(DshApiError::parameter("")),
    }
  }

  /// 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"
  /// );
  /// ```
  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"
  /// );
  /// ```
  pub fn http_messaging_api_url_single(&self, mqtt_topic: impl Display) -> String {
    format!("https://{}/data/v0/single/{}", self.rest_api_domain(), mqtt_topic)
  }

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

  /// Returns the internal domain name for a service.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `service_name` - Name/id of the 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"
  /// );
  /// ```
  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"
  /// );
  /// ```
  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"
  /// );
  /// ```
  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 or alias.
  ///
  /// # Parameters
  /// * `platform_name` - Platform name or alias.
  ///
  /// # 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()
  }

  #[rustfmt::skip]
  /// Returns the proxy common name.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .proxy_common_name("my-proxy", "my-tenant", VhostZone::Public)?,
  ///   "my-proxy.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com"
  /// );
  /// #   Ok(())
  /// # }
  /// ```
  pub fn proxy_common_name(&self, proxy_name: impl Display, tenant_name: impl Display, vhost_zone: VhostZone) -> DshApiResult<String> {
    Ok(format!("{}.{}", proxy_name, self.proxy_vhost_domain(tenant_name, vhost_zone)?))
  }

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

  #[rustfmt::skip]
  /// Returns the proxy consumer group for acl groups.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `acl_group_id` - Acl group id.
  /// * `index` - Proxy consumer group index.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .proxy_consumer_group_acl("my-tenant", "my-proxy", "my-acl-group", 2),
  ///   "my-tenant.my-acl-group_my-proxy_2"
  /// );
  /// ```
  pub fn proxy_consumer_group_acl(&self, tenant_name: impl Display, proxy_name: impl Display, acl_group_id: impl Display, index: usize) -> String {
    format!("{}.{}_{}_{}", tenant_name, acl_group_id, proxy_name, index)
  }

  /// Returns the proxy schema store vhost.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_schema_store_vhost(
  ///     "my-tenant",
  ///     "my-proxy",
  ///     VhostZone::Public
  ///   )?,
  ///   "my-proxy-schema-store.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com"
  /// );
  /// #   Ok(())
  /// # }
  /// ```
  pub fn proxy_schema_store_vhost(&self, tenant_name: impl Display, proxy_name: impl Display, vhost_zone: VhostZone) -> DshApiResult<String> {
    Ok(format!("{}-schema-store.{}", proxy_name, self.proxy_vhost_domain(tenant_name, vhost_zone)?))
  }

  #[rustfmt::skip]
  /// Returns the proxy vhost.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `vhost_zone` - Vhost zone.
  /// * `index` - Proxy vhost index.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .proxy_vhost("my-tenant", "my-proxy", VhostZone::Public, 2)?,
  ///   "my-proxy-2.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com"
  /// );
  /// #   Ok(())
  /// # }
  /// ```
  pub fn proxy_vhost(&self, tenant_name: impl Display, proxy_name: impl Display, vhost_zone: VhostZone, index: usize) -> DshApiResult<String> {
    Ok(format!("{}-{}.{}", proxy_name, index, self.proxy_vhost_domain(tenant_name, vhost_zone)?))
  }

  /// Returns the proxy vhost domain.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").proxy_vhost_domain("my-tenant", VhostZone::Public)?,
  ///   "kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com"
  /// );
  /// #   Ok(())
  /// # }
  /// ```
  pub fn proxy_vhost_domain(&self, tenant_name: impl Display, vhost_zone: VhostZone) -> DshApiResult<String> {
    Ok(format!("kafka.{}.{}", tenant_name, self.domain(vhost_zone)?))
  }

  /// 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");
  /// ```
  pub fn public_domain(&self) -> &str {
    &self.public_domain
  }

  /// Returns the public domain for a vhost.
  ///
  /// # Parameters
  /// * `vhost_name` - Public vhost name.
  ///
  /// # 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"
  /// );
  /// ```
  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");
  /// ```
  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"
  /// );
  /// ```
  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"
  /// );
  /// ```
  pub fn rest_token_endpoint(&self) -> String {
    format!("https://{}/auth/v0/token", self.rest_api_domain())
  }

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

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

  /// 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"
  /// );
  /// ```
  pub fn swagger_url(&self) -> String {
    format!("https://{}/tenant-api/spec?url=/tenant-api/assets/openapi.json", self.console_domain())
  }

  #[rustfmt::skip]
  /// 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`.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `vendor_name` - Vendor name.
  /// * `app_name` - App name.
  ///
  /// # 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"
  /// );
  /// ```
  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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # 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"
  /// );
  /// ```
  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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `app_name` - App name.
  ///
  /// # 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"
  /// );
  /// ```
  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)
  }

  #[rustfmt::skip]
  /// Returns properly formatted robot client_id for tenant.
  ///
  /// This method is deprecated, use [`DshPlatform::robot_tenant_client_id`] instead.
  #[deprecated]
  pub fn tenant_client_id(&self, tenant_name: impl Display) -> String {
    format!("{}{}{}", self.robot_client_id(), CLIENT_ID_SEPARATOR, tenant_name)
  }

  /// Returns the url of the platform console for a tenant.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # 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"
  /// );
  /// ```
  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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # 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"
  /// );
  /// ```
  pub fn tenant_data_catalog_url(&self, tenant_name: impl Display) -> String {
    format!("https://{}/#/profiles/{}/data-catalog", self.console_domain(), tenant_name)
  }

  /// Returns the domain for a tenant.
  ///
  /// Returns the private or public 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz").tenant_domain("my-tenant", VhostZone::Private)?,
  ///   "my-tenant.dsh-dev.dsh.np.aws.kpn.org"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_domain(&self, tenant_name: impl Display, vhost_zone: VhostZone) -> Result<String, String> {
    Ok(format!("{}.{}", tenant_name, self.domain(vhost_zone)?))
  }

  /// Returns the url of the platform monitoring page for a tenant.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # 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"
  /// );
  /// ```
  pub fn tenant_monitoring_url(&self, tenant_name: impl Display) -> String {
    format!("https://monitoring-{}.{}", tenant_name, self.public_domain)
  }

  /// 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_domain`] instead.
  ///
  /// # 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"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  #[deprecated]
  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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `vhost_name` - Name of the vhost.
  ///
  /// # 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"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_private_vhost_domain(&self, tenant_name: impl Display, vhost_name: impl Display) -> Result<String, String> {
    self
      .tenant_domain(tenant_name, VhostZone::Private)
      .map(|tenant_private_domain| format!("{}.{}", vhost_name, tenant_private_domain))
  }

  #[rustfmt::skip]
  /// Returns the bootstrap server 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `vhost_zone` - Vhost zone.
  /// * `port` - Port number.
  /// * `index` - Number of proxy servers.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::{DshPlatform, VhostZone};
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .tenant_proxy_bootstrap_server(
  ///       "my-tenant",
  ///       "my-proxy",
  ///       VhostZone::Private,
  ///       Some(19091),
  ///       2
  ///     )?,
  ///   "my-proxy-2.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.org:19091"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_proxy_bootstrap_server(
    &self,
    tenant_name: impl Display,
    proxy_name: impl Display,
    vhost_zone: VhostZone,
    port: Option<usize>,
    index: usize,
  ) -> Result<String, String> {
    match port {
      Some(port) => Ok(format!("{}-{}.kafka.{}:{}", proxy_name, index, self.tenant_domain(tenant_name, vhost_zone)?, port)),
      None => Ok(format!("{}-{}.kafka.{}:9091", proxy_name, index, self.tenant_domain(tenant_name, vhost_zone)?)),
    }
  }

  #[rustfmt::skip]
  /// Returns the 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `vhost_zone` - Vhost zone.
  /// * `number_of_servers` - Number of proxy servers.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
  /// use dsh_api::platform::VhostZone;
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .tenant_proxy_bootstrap_servers(
  ///       "my-tenant",
  ///       "my-proxy",
  ///       VhostZone::Private,
  ///       3
  ///     )?
  ///     .first()
  ///     .unwrap(),
  ///   "my-proxy-0.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.org:9091"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_proxy_bootstrap_servers(
    &self,
    tenant_name: impl Display,
    proxy_name: impl Display,
    vhost_zone: VhostZone,
    number_of_servers: usize,
  ) -> Result<Vec<String>, String> {
    (0..number_of_servers)
      .map(|index| self.tenant_proxy_bootstrap_server(&tenant_name, &proxy_name, vhost_zone.clone(), None, index))
      .collect::<Result<Vec<_>, _>>()
  }

  /// 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.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_proxy_bootstrap_servers`] instead.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `number_of_servers` - Number of proxy servers.
  ///
  /// # 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", 3)?
  ///     .first()
  ///     .unwrap(),
  ///   "my-proxy-0.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.org:9091"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  #[deprecated]
  pub fn tenant_proxy_private_bootstrap_servers(&self, tenant_name: impl Display, proxy_name: impl Display, number_of_servers: usize) -> Result<Vec<String>, String> {
    self.tenant_domain(tenant_name, VhostZone::Private).map(|tenant_private_domain| {
      (0..number_of_servers)
        .map(|index| format!("{}-{}.kafka.{}:9091", proxy_name, index, tenant_private_domain))
        .collect_vec()
    })
  }

  #[rustfmt::skip]
  /// 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_proxy_schema_store_host`] instead.
  ///
  /// # 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"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  #[deprecated]
  pub fn tenant_proxy_private_schema_store_host(&self, tenant_name: impl Display, proxy_name: impl Display) -> Result<String, String> {
    self
      .tenant_domain(tenant_name, VhostZone::Private)
      .map(|tenant_private_domain| format!("{}-schema-store.kafka.{}", proxy_name, tenant_private_domain))
  }

  /// Returns the public bootstrap servers for a configured proxy.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_proxy_bootstrap_servers`] instead.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `number_of_servers` - Bootstrap server index.
  ///
  /// # Examples
  /// ```rust
  /// # use dsh_api::platform::DshPlatform;
  /// assert_eq!(
  ///   DshPlatform::new("nplz")
  ///     .tenant_proxy_public_bootstrap_servers("my-tenant", "my-proxy", 3)
  ///     .first()
  ///     .unwrap(),
  ///   "my-proxy-0.kafka.my-tenant.dsh-dev.dsh.np.aws.kpn.com:9091"
  /// );
  /// ```
  #[deprecated]
  pub fn tenant_proxy_public_bootstrap_servers(&self, tenant_name: impl Display, proxy_name: impl Display, number_of_servers: usize) -> Vec<String> {
    (0..number_of_servers)
      .map(|index| format!("{}-{}.kafka.{}.{}:9091", proxy_name, index, tenant_name, self.public_domain))
      .collect_vec()
  }

  /// Returns the public schema store host for a configured proxy.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_proxy_schema_store_host`] instead.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  ///
  /// # 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"
  /// );
  /// ```
  #[deprecated]
  pub fn tenant_proxy_public_schema_store_host(&self, tenant_name: impl Display, proxy_name: impl Display) -> String {
    format!("{}-schema-store.kafka.{}.{}", proxy_name, tenant_name, self.public_domain)
  }

  /// 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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `proxy_name` - Proxy name.
  /// * `vhost_zone` - Vhost zone.
  ///
  /// # 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"
  /// );
  /// # Ok(())
  /// # }
  /// ```
  pub fn tenant_proxy_schema_store_host(&self, tenant_name: impl Display, proxy_name: impl Display, vhost_zone: VhostZone) -> Result<String, String> {
    self
      .tenant_domain(tenant_name, vhost_zone)
      .map(|tenant_private_domain| format!("{}-schema-store.kafka.{}", proxy_name, tenant_private_domain))
  }

  /// Returns the public domain for an app.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `app_name` - App name.
  ///
  /// # 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"
  /// );
  /// ```
  pub fn tenant_public_app_domain(&self, tenant_name: impl Display, app_name: impl Display) -> String {
    format!("{}.{}.{}", app_name, tenant_name, self.public_domain)
  }

  /// Returns the public domain for a tenant.
  ///
  /// This method is deprecated, use [`DshPlatform::tenant_domain`] instead.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  ///
  /// # 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"
  /// );
  /// ```
  #[deprecated]
  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.
  ///
  /// # Parameters
  /// * `tenant_name` - Tenant name.
  /// * `service_name` - Name/id of the 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"
  /// );
  /// ```
  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)
  }

  #[rustfmt::skip]
  /// 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"
  /// );
  /// ```
  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 Display for VhostZone {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      Self::Private => f.write_str("private"),
      Self::Public => f.write_str("public"),
    }
  }
}

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(", ")
      )),
    }
  }
}

impl FromStr for VhostZone {
  type Err = DshApiError;

  fn from_str(representation: &str) -> DshApiResult<Self> {
    match representation {
      "private" => Ok(Self::Private),
      "public" => Ok(Self::Public),
      _ => Err(DshApiError::parameter(format!("invalid vhost zone '{}'", representation))),
    }
  }
}

impl FromStr for CloudProvider {
  type Err = DshApiError;

  fn from_str(representation: &str) -> DshApiResult<Self> {
    match representation {
      "aws" => Ok(Self::AWS),
      "azure" => Ok(Self::Azure),
      _ => Err(DshApiError::parameter(format!("invalid cloud provider '{}'", representation))),
    }
  }
}

// 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(())
  }
}