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
//! # Additional methods to manage vhosts
//!
//! Module that contains methods and functions to manage vhosts.
//!
//! _Since the DSH resource management API does not support vhosts, there are no generated methods
//! to manage them. All derived methods act only on vhosts that are configured in either
//! applications or app resources._
//!
//! # Generated methods
//!
//! Not supported by the DSH resource management API.
//!
//! # Derived methods
//!
//! [`DshApiClient`] methods that add extra capabilities but do not directly call the
//! DSH resource management API. These derived methods depend on the API methods for this.
//!
//! * [`vhosts_with_dependant_applications() -> [vhost id, [(application id, instances, [injection])]]`](DshApiClient::vhosts_with_dependant_applications)
//! * [`vhosts_with_dependant_apps() -> [vhost id, [(app id, [resource])]]`](DshApiClient::vhosts_with_dependant_apps)
//! * [`vhosts_with_dependants() -> [vhost id, [injection]]`](DshApiClient::vhosts_with_dependants)

use crate::app::app_resources;
use crate::application_types::ApplicationValues;
/// # Additional method to manage vhosts
///
/// Module that contains methods and functions to manage vhosts.
/// * Derived methods - DshApiClient methods that add extra capabilities
///   but depend on the API methods.
///
/// # Derived methods
/// * [`list_vhosts_with_usage() -> [id, [usage]]`](DshApiClient::list_vhosts_with_usage)
use crate::dsh_api_client::DshApiClient;
use crate::error::DshApiResult;
use crate::parse::parse_function;
use crate::types::{AppCatalogApp, AppCatalogAppResourcesValue, Application, PortMapping, Vhost};
use crate::{Dependant, DependantApp, DependantApplication};
use futures::try_join;
use itertools::Itertools;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::str::FromStr;
use std::sync::LazyLock;

/// # Describes an injection of a resource in an application
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum VhostInjection {
  /// Environment variable injection, where the value is the name of the environment variable.
  #[serde(rename = "env")]
  EnvVar { env_var_name: String },
  /// Variable function, where the values are the name of the function and the parameter.
  #[serde(rename = "variable")]
  Variable { variable_name: String },
  /// Vhost injection, where the values are the exposed port and the zone
  #[serde(rename = "vhost")]
  Vhost { exposed_port: String, zone: Option<String> },
}

impl VhostInjection {
  pub(crate) fn vhost<S, T>(exposed_port: S, zone: Option<T>) -> Self
  where
    S: Into<String>,
    T: Into<String>,
  {
    Self::Vhost { exposed_port: exposed_port.into(), zone: zone.map(|zone| zone.into()) }
  }
}

impl Display for VhostInjection {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    match self {
      VhostInjection::EnvVar { env_var_name } => write!(f, "{}", env_var_name),
      VhostInjection::Variable { variable_name } => write!(f, "{{ vhost('{}') }}", variable_name),
      VhostInjection::Vhost { exposed_port, zone } => match zone {
        Some(a_zone) => write!(f, "vhost({}:{})", exposed_port, a_zone),
        None => write!(f, "{}", exposed_port),
      },
    }
  }
}

impl DshApiClient {
  /// # Returns all vhosts with dependant applications
  ///
  /// Returns a sorted list of all vhosts together with the applications use them.
  /// Note that only vhosts that are actually referenced in the applications will be included.
  pub async fn vhosts_with_dependant_applications(&self) -> DshApiResult<Vec<(String, Vec<DependantApplication<VhostInjection>>)>> {
    let applications = self.get_application_configuration_map().await?;
    let mut vhosts_map = HashMap::<String, Vec<DependantApplication<VhostInjection>>>::new();
    for ApplicationValues { id, application, values } in vhosts_from_applications(&applications) {
      for (vhost, port, _) in values {
        let dependant_applications = vhosts_map.entry(vhost.clone()).or_default();
        dependant_applications.push(DependantApplication::new(
          id.to_string(),
          application.instances,
          vec![VhostInjection::Vhost { exposed_port: port.to_string(), zone: None }],
        ));
      }
    }
    let mut vhosts: Vec<(String, Vec<DependantApplication<VhostInjection>>)> = Vec::from_iter(vhosts_map.into_iter());
    vhosts.sort_by(|(vhost_id_a, _), (vhost_id_b, _)| vhost_id_a.cmp(vhost_id_b));
    Ok(vhosts)
  }

  /// # Returns all vhosts with dependant apps
  ///
  /// Returns a sorted list of all vhosts together with the apps that use them.
  /// Note that only vhosts that are actually referenced in the apps will be included.
  pub async fn vhosts_with_dependant_apps(&self) -> DshApiResult<Vec<(String, Vec<DependantApp>)>> {
    let apps = self.get_appcatalogapp_configuration_map().await?;
    let mut vhosts_map = HashMap::<String, Vec<DependantApp>>::new();
    let mut app_ids = apps.keys().collect_vec();
    app_ids.sort();
    for app_id in app_ids {
      let app = apps.get(app_id).unwrap();
      for (_, vhost_string) in vhost_strings_from_app(app) {
        let dependant_apps = vhosts_map.entry(vhost_string.vhost_name.clone()).or_default();
        dependant_apps.push(DependantApp::new(app_id.clone(), vec![vhost_string.to_string()]));
      }
    }
    let mut vhosts: Vec<(String, Vec<DependantApp>)> = Vec::from_iter(vhosts_map);
    vhosts.sort_by(|(vhost_id_a, _), (vhost_id_b, _)| vhost_id_a.cmp(vhost_id_b));
    Ok(vhosts)
  }

  /// # Returns all vhosts with dependant applications and apps
  ///
  /// Returns a sorted list of all vhosts together with the applications and apps that use them.
  /// Note that only vhosts that are actually referenced in the applications and apps
  /// will be included.
  pub async fn vhosts_with_dependants(&self) -> DshApiResult<Vec<(String, Vec<Dependant<VhostInjection>>)>> {
    let (application_configuration_map, appcatalogapp_configuration_map) = try_join!(self.get_application_configuration_map(), self.get_appcatalogapp_configuration_map())?;
    let mut vhosts_with_dependants_map = HashMap::<String, Vec<Dependant<VhostInjection>>>::new();
    for ApplicationValues { id, application, values } in vhosts_from_applications(&application_configuration_map) {
      for (vhost, port, _) in values {
        let dependants = vhosts_with_dependants_map.entry(vhost.clone()).or_default();
        dependants.push(Dependant::service(
          id,
          application.instances,
          vec![VhostInjection::Vhost { exposed_port: port.to_string(), zone: None }],
        ));
      }
    }
    let mut app_ids = appcatalogapp_configuration_map.keys().collect_vec();
    app_ids.sort();
    for app_id in app_ids {
      let app = appcatalogapp_configuration_map.get(app_id).unwrap();
      for (_, vhost_string) in vhost_strings_from_app(app) {
        let dependants = vhosts_with_dependants_map.entry(vhost_string.vhost_name.clone()).or_default();
        dependants.push(Dependant::app(app_id.clone(), vec![vhost_string.to_string()]));
      }
    }
    let mut vhosts: Vec<(String, Vec<Dependant<VhostInjection>>)> = Vec::from_iter(vhosts_with_dependants_map.into_iter());
    vhosts.sort_by(|(vhost_id_a, _), (vhost_id_b, _)| vhost_id_a.cmp(vhost_id_b));
    Ok(vhosts)
  }
}

/// # Get application port mappings for vhost id
///
/// Get all port mappings from an `Application` that use a vhost with `vhost_id`.
/// When `vhost_id` is not used in `application`, an empty list will be returned.
///
/// # Parameters
/// * `vhost_id` - id of the vhost to look for
/// * `application` - reference to the `Application`
///
/// # Returns
/// `Vec<(&str, &PortMapping)>` - list of tuples containing:
/// * port number
/// * reference to port mapping
///
/// The list is sorted by port number.
pub fn vhost_port_mappings_from_application<'a>(vhost_id: &str, application: &'a Application) -> Vec<(&'a str, &'a PortMapping)> {
  let mut port_mappings: Vec<(&'a str, &'a PortMapping)> = application
    .exposed_ports
    .iter()
    .filter_map(|(port, port_mapping)| {
      port_mapping.vhost.clone().and_then(|vhost_string| {
        VhostString::from_str(vhost_string.as_str())
          .ok()
          .and_then(|vhost| if vhost.vhost_name == vhost_id { Some((port.as_str(), port_mapping)) } else { None })
      })
    })
    .collect_vec();
  port_mappings.sort_by(|(port_a, _), (port_b, _)| port_a.cmp(port_b));
  port_mappings
}

/// # Get applications port mappings for vhost id
///
/// Get all port mappings from multiple `Application`s that use a vhost with `vhost_id`.
/// Applications are only included if they reference `vhost_id` at least once.
///
/// # Parameters
/// * `vhost_id` - id of the vhost to look for
/// * `applications` - hashmap containing id/application pairs
///
/// # Returns
/// `Vec<ApplicationTuple<(&str, &PortMapping)>>` - list of tuples containing:
/// * application id
/// * reference to application
/// * list of pairs of port number and port mapping, sorted by port number
///
/// The list is sorted by application id.
pub fn vhost_port_mappings_from_applications<'a>(vhost_id: &str, applications: &'a HashMap<String, Application>) -> Vec<ApplicationValues<'a, (&'a str, &'a PortMapping)>> {
  let mut application_tuples: Vec<ApplicationValues<(&str, &PortMapping)>> = applications
    .iter()
    .filter_map(|(application_id, application)| {
      let port_mappings: Vec<(&str, &PortMapping)> = vhost_port_mappings_from_application(vhost_id, application);
      if port_mappings.is_empty() {
        None
      } else {
        Some(ApplicationValues::new(application_id, application, port_mappings))
      }
    })
    .collect_vec();
  application_tuples.sort();
  application_tuples
}

/// Get vhost resources from `AppCatalogApp`
///
/// # Parameters
/// * `app` - app to get the vhost resources from
///
/// # Returns
/// Either `None` when the `app` does not have any vhost resources,
/// or a `Some` that contains tuples describing the vhost resources:
/// * resource id
/// * reference to the `Vhost`
pub fn vhost_resources_from_app(app: &AppCatalogApp) -> Vec<(&str, &Vhost)> {
  app_resources(app, &|resource_value| match resource_value {
    AppCatalogAppResourcesValue::Vhost(vhost) => Some(vhost),
    _ => None,
  })
}

/// Get parsed vhost strings from `AppCatalogApp`
///
/// # Parameters
/// * `app` - app to get the vhost strings from
///
/// # Returns
/// `Vec` that contains tuples describing the resource ids and vhost strings:
/// * resource id
/// * [VhostString]
pub(crate) fn vhost_strings_from_app(app: &AppCatalogApp) -> Vec<(&str, VhostString)> {
  let mut resources: Vec<(&str, VhostString)> = vec![];
  for (resource_id, resource) in &app.resources {
    if let AppCatalogAppResourcesValue::Vhost(vhost) = resource {
      if let Ok(vhost_string) = VhostString::from_resource_str(&vhost.value) {
        resources.push((resource_id, vhost_string))
      }
    }
  }
  resources.sort_by(|(resource_id_a, _), (resource_id_b, _)| resource_id_a.cmp(resource_id_b));
  resources
}

/// # Get vhosts from application
///
/// Get all vhosts used in `Application`.
///
/// # Parameters
/// * `application` - reference to the `Application`
///
/// # Returns
/// `Vec<(String, &PortMapping)>` - list of tuples containing:
/// * vhost id
/// * port
/// * port mapping
///
/// The list is sorted by vhost id.
pub fn vhosts_from_application(application: &Application) -> Vec<(String, &str, &PortMapping)> {
  let mut vhosts: Vec<(String, &str, &PortMapping)> = application
    .exposed_ports
    .iter()
    .filter_map(|(port, port_mapping)| {
      port_mapping.vhost.clone().and_then(|vhost_string| {
        VhostString::from_str(vhost_string.as_str())
          .ok()
          .map(|vhost| (vhost.vhost_name, port.as_str(), port_mapping))
      })
    })
    .collect_vec();
  vhosts.sort_by(|(vhost_name_a, _, _), (vhost_name_b, _, _)| vhost_name_a.cmp(vhost_name_b));
  vhosts
}

/// # Get all vhosts from applications
///
/// Get all vhosts from all `Application`s.
/// Applications without configured vhosts will be contained in the list
/// with an empty list of topics.
///
/// # Parameters
/// * `applications` - hashmap containing id/application pairs
///
/// # Returns
/// `Vec<ApplicationValues<(String, &str, &PortMapping)>>` - sorted list of tuples containing:
/// * application id
/// * application reference
/// * lists of vhost ids, ports and port mappings used in the application
pub fn vhosts_from_applications(applications: &HashMap<String, Application>) -> Vec<ApplicationValues<(String, &str, &PortMapping)>> {
  let mut vhosts: Vec<ApplicationValues<(String, &str, &PortMapping)>> = vec![];
  for (application_id, application) in applications {
    for (port, port_mapping) in &application.exposed_ports {
      if let Some(vhost_string) = port_mapping.vhost.clone() {
        if let Ok(vhost) = VhostString::from_str(vhost_string.as_str()) {
          vhosts.push(ApplicationValues::new(application_id, application, vec![(vhost.vhost_name, port, port_mapping)]));
        }
      }
    }
  }
  vhosts.sort();
  // vhosts.sort_by(|application_tuple_a, application_tuple_b| application_tuple_a.cmp(application_tuple_b));
  vhosts
}

/// Structure that describes a vhost string. Vhost strings are used in the `exposedPorts` section
/// of a service definition file and are deserialized into the `vhost` field of the
/// [`PortMapping`] data structure.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct VhostString {
  /// Domain name of the vhost
  pub vhost_name: String,
  /// Indicates whether the vhost name contains the substring `.kafka`
  pub kafka: bool,
  /// Optional tenant name
  pub tenant_name: Option<String>,
  /// Optional zone
  pub zone: Option<String>,
}

impl VhostString {
  /// # Create a `VhostString`
  ///
  /// # Parameters
  /// * `vhost_name` - mandatory identifier of the vhost
  /// * `kafka` - whether the vhost name contains the substring `.kafka`
  /// * `tenant_name` - optional tenant name
  /// * `zone` - optional zone, typically `private` or `public`
  pub fn new<T, U, V>(vhost_name: T, kafka: bool, tenant_name: Option<U>, zone: Option<V>) -> Self
  where
    T: Into<String>,
    U: Into<String>,
    V: Into<String>,
  {
    Self { vhost_name: vhost_name.into(), kafka, tenant_name: tenant_name.map(Into::<String>::into), zone: zone.map(Into::<String>::into) }
  }

  /// # Parse vhost resource string
  ///
  /// Multiple vhosts using the `join` function are not supported.
  ///
  /// # Example
  ///
  /// ```
  /// # use dsh_api::vhost::VhostString;
  /// assert_eq!(
  ///   VhostString::from_resource_str("my-vhost.my-tenant@private"),
  ///   Ok(VhostString::new(
  ///     "my-vhost".to_string(),
  ///     false,
  ///     Some("my-tenant".to_string()),
  ///     Some("private".to_string())
  ///   ))
  /// );
  /// ```
  ///
  /// # Parameters
  /// * `vhost_string` - the vhost string to be parsed
  ///
  /// # Returns
  /// When the provided string is valid, the method returns an instance of the `VhostString`
  /// struct, describing the auth string.
  pub fn from_resource_str(vhost_resource_string: &str) -> Result<Self, String> {
    static VHOST_RESOURCE_STRING_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)@([a-zA-Z0-9_-]+)$").unwrap());

    VHOST_RESOURCE_STRING_REGEX
      .captures(vhost_resource_string)
      .map(|captures| {
        VhostString::new(
          captures.get(1).map(|vhost_match| vhost_match.as_str()).unwrap_or_default(),
          false,
          captures.get(2).map(|tenant_match| Some(tenant_match.as_str())).unwrap_or_default(),
          captures.get(3).map(|zone_match| zone_match.as_str()),
        )
      })
      .ok_or(format!("invalid value in vhost string (\"{}\")", vhost_resource_string))
  }
}

impl FromStr for VhostString {
  type Err = String;

  /// # Parse vhost string
  ///
  /// Multiple vhosts using the `join` function are not supported.
  ///
  /// # Example
  ///
  /// ```
  /// # use std::str::FromStr;
  /// # use dsh_api::vhost::VhostString;
  /// assert_eq!(
  ///   VhostString::from_str("{ vhost('my-vhost-name') }"),
  ///   Ok(VhostString::new("my-vhost-name".to_string(), false, None::<String>, None::<String>))
  /// );
  /// assert_eq!(
  ///   VhostString::from_str("{ vhost('my-vhost-name.kafka.my-tenant','public') }"),
  ///   Ok(VhostString::new(
  ///     "my-vhost-name".to_string(),
  ///     true,
  ///     Some("my-tenant".to_string()),
  ///     Some("public".to_string())
  ///   ))
  /// );
  /// ```
  ///
  /// # Parameters
  /// * `vhost_string` - the vhost string to be parsed
  ///
  /// # Returns
  /// When the provided string is valid, the method returns an instance of the `VhostString`
  /// struct, describing the auth string.
  fn from_str(vhost_string: &str) -> Result<Self, Self::Err> {
    static VALUE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"([a-zA-Z0-9_-]+)(\.kafka)?(?:\.([a-zA-Z0-9_-]+))?").unwrap());
    let (value_string, zone) = parse_function(vhost_string, "vhost")?;
    VALUE_REGEX
      .captures(value_string)
      .map(|captures| {
        VhostString::new(
          captures.get(1).map(|vhost_match| vhost_match.as_str()).unwrap_or_default(),
          captures.get(2).is_some(),
          captures.get(3).map(|tenant_match| tenant_match.as_str()),
          zone,
        )
      })
      .ok_or(format!("invalid value in vhost string (\"{}\")", vhost_string))
  }
}

impl TryFrom<&PortMapping> for VhostString {
  type Error = String;

  fn try_from(port_mapping: &PortMapping) -> Result<Self, Self::Error> {
    match &port_mapping.vhost {
      Some(vhost) => VhostString::from_str(vhost),
      None => Err("port mapping has no vhost".to_string()),
    }
  }
}

impl Display for VhostString {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.vhost_name)?;
    if self.kafka {
      write!(f, ".kafka")?;
    }
    if let Some(tenant_name) = &self.tenant_name {
      write!(f, ".{}", tenant_name)?;
    }
    if let Some(zone) = &self.zone {
      write!(f, ".{}", zone)?;
    }
    Ok(())
  }
}