Skip to main content

nomad_rs_api/
service.rs

1use crate::{ClientError, Nomad};
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Serialize, Deserialize)]
5#[serde(rename_all = "PascalCase")]
6pub struct ServiceRegistrationList {
7    pub namespace: String,
8    pub services: Vec<ServiceRegistrationStub>,
9}
10
11#[derive(Debug, Serialize, Deserialize)]
12#[serde(rename_all = "PascalCase")]
13pub struct ServiceRegistrationStub {
14    pub service_name: String,
15    pub tags: Vec<String>,
16}
17
18#[derive(Debug, Serialize, Deserialize)]
19#[serde(rename_all = "PascalCase")]
20pub struct ServiceRegistration {
21    pub id: String,
22    pub service_name: String,
23    pub namespace: String,
24    pub node_id: String,
25    pub datacenter: String,
26    pub job_id: String,
27    pub alloc_id: String,
28    pub tags: Vec<String>,
29    pub address: String,
30    pub port: u16,
31    pub create_index: u64,
32    pub modify_index: u64,
33}
34
35pub struct Endpoint<'a> {
36    client: &'a Nomad,
37}
38
39impl<'a> Endpoint<'a> {
40    /// Create a new `Endpoint` with the given `Nomad` client to interact with
41    /// the service registrations endpoint.
42    pub fn new(client: &'a Nomad) -> Self {
43        Self { client }
44    }
45
46    /// Delete a service registration by its name.
47    ///
48    /// # Arguments
49    /// * `name` - The name of the service to delete.
50    ///
51    /// # Returns
52    /// A `Result` indicating success or failure of the operation.
53    pub async fn delete(&self, name: &str) -> Result<(), ClientError> {
54        let req = self
55            .client
56            .build_request(reqwest::Method::DELETE, &format!("/v1/service/{}", name));
57        self.client.send_without_response(req).await
58    }
59
60    /// Get the details of a specific service by its ID.
61    ///
62    /// # Arguments
63    /// * `name` - The name of the service to retrieve.
64    ///
65    /// # Returns
66    /// A `Result` containing a vector of `ServiceRegistration` or an error if
67    /// the request fails.
68    pub async fn get(&self, name: &str) -> Result<Vec<ServiceRegistration>, ClientError> {
69        let req = self
70            .client
71            .build_request(reqwest::Method::GET, &format!("/v1/service/{}", name));
72        self.client
73            .send_with_response::<Vec<ServiceRegistration>>(req)
74            .await
75    }
76
77    /// Get the list of services registered in the Nomad cluster.
78    ///
79    /// # Returns
80    /// A `Result` containing a vector of `ServiceRegistrationList` or an error
81    /// if the request fails.
82    pub async fn list(&self) -> Result<Vec<ServiceRegistrationList>, ClientError> {
83        let req = self
84            .client
85            .build_request(reqwest::Method::GET, "/v1/services");
86        self.client
87            .send_with_response::<Vec<ServiceRegistrationList>>(req)
88            .await
89    }
90}