batata-consul-client 0.0.2

Rust client for HashiCorp Consul or batata
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
use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::client::HttpClient;
use crate::error::Result;
use crate::types::{AgentService, HealthCheck, WriteMeta};

/// Agent member information
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AgentMember {
    /// Member name
    pub name: String,
    /// Member address
    pub addr: String,
    /// Member port
    pub port: u16,
    /// Member tags
    #[serde(default)]
    pub tags: HashMap<String, String>,
    /// Member status (alive, leaving, left, failed)
    pub status: i32,
    /// Protocol version (min)
    pub protocol_min: u8,
    /// Protocol version (max)
    pub protocol_max: u8,
    /// Protocol version (current)
    pub protocol_cur: u8,
    /// Delegate version (min)
    pub delegate_min: u8,
    /// Delegate version (max)
    pub delegate_max: u8,
    /// Delegate version (current)
    pub delegate_cur: u8,
}

/// Agent self information
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AgentSelf {
    /// Configuration
    pub config: HashMap<String, serde_json::Value>,
    /// Coordinator
    #[serde(default)]
    pub coord: Option<serde_json::Value>,
    /// Member information
    pub member: AgentMember,
    /// Statistics
    #[serde(default)]
    pub stats: HashMap<String, HashMap<String, String>>,
    /// Metadata
    #[serde(default)]
    pub meta: HashMap<String, String>,
}

/// Service registration request
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AgentServiceRegistration {
    /// Service ID (defaults to Name if not provided)
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Service name
    pub name: String,
    /// Service tags
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    /// Service port
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// Service address
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<String>,
    /// Enable tag override
    #[serde(default)]
    pub enable_tag_override: bool,
    /// Service metadata
    #[serde(default)]
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    pub meta: HashMap<String, String>,
    /// Health check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub check: Option<AgentServiceCheck>,
    /// Multiple health checks
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub checks: Vec<AgentServiceCheck>,
}

impl AgentServiceRegistration {
    pub fn new(name: &str) -> Self {
        Self {
            id: None,
            name: name.to_string(),
            tags: Vec::new(),
            port: None,
            address: None,
            enable_tag_override: false,
            meta: HashMap::new(),
            check: None,
            checks: Vec::new(),
        }
    }

    pub fn with_id(mut self, id: &str) -> Self {
        self.id = Some(id.to_string());
        self
    }

    pub fn with_address(mut self, address: &str) -> Self {
        self.address = Some(address.to_string());
        self
    }

    pub fn with_port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    pub fn with_meta(mut self, key: &str, value: &str) -> Self {
        self.meta.insert(key.to_string(), value.to_string());
        self
    }

    pub fn with_check(mut self, check: AgentServiceCheck) -> Self {
        self.check = Some(check);
        self
    }

    pub fn add_check(mut self, check: AgentServiceCheck) -> Self {
        self.checks.push(check);
        self
    }
}

/// Service health check definition
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AgentServiceCheck {
    /// Check ID
    #[serde(rename = "CheckID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub check_id: Option<String>,
    /// Check name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Script to run (deprecated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub script: Option<String>,
    /// Args for script
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    /// Docker container ID
    #[serde(rename = "DockerContainerID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub docker_container_id: Option<String>,
    /// Shell for docker exec
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shell: Option<String>,
    /// Interval between checks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<String>,
    /// Timeout for check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<String>,
    /// TTL for passive checks
    #[serde(rename = "TTL")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
    /// HTTP endpoint to check
    #[serde(rename = "HTTP")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http: Option<String>,
    /// HTTP method
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
    /// HTTP headers
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header: Option<HashMap<String, Vec<String>>>,
    /// TCP endpoint to check
    #[serde(rename = "TCP")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tcp: Option<String>,
    /// gRPC endpoint to check
    #[serde(rename = "GRPC")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grpc: Option<String>,
    /// Use TLS for gRPC
    #[serde(rename = "GRPCUseTLS")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grpc_use_tls: Option<bool>,
    /// Initial status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Notes about the check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    /// Skip TLS verification
    #[serde(rename = "TLSSkipVerify")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_skip_verify: Option<bool>,
    /// Deregister after critical for duration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deregister_critical_service_after: Option<String>,
}

impl AgentServiceCheck {
    /// Create a new HTTP check
    pub fn http(url: &str, interval: &str) -> Self {
        Self {
            check_id: None,
            name: None,
            script: None,
            args: None,
            docker_container_id: None,
            shell: None,
            interval: Some(interval.to_string()),
            timeout: None,
            ttl: None,
            http: Some(url.to_string()),
            method: None,
            header: None,
            tcp: None,
            grpc: None,
            grpc_use_tls: None,
            status: None,
            notes: None,
            tls_skip_verify: None,
            deregister_critical_service_after: None,
        }
    }

    /// Create a new TCP check
    pub fn tcp(address: &str, interval: &str) -> Self {
        Self {
            check_id: None,
            name: None,
            script: None,
            args: None,
            docker_container_id: None,
            shell: None,
            interval: Some(interval.to_string()),
            timeout: None,
            ttl: None,
            http: None,
            method: None,
            header: None,
            tcp: Some(address.to_string()),
            grpc: None,
            grpc_use_tls: None,
            status: None,
            notes: None,
            tls_skip_verify: None,
            deregister_critical_service_after: None,
        }
    }

    /// Create a new TTL check
    pub fn ttl(ttl: &str) -> Self {
        Self {
            check_id: None,
            name: None,
            script: None,
            args: None,
            docker_container_id: None,
            shell: None,
            interval: None,
            timeout: None,
            ttl: Some(ttl.to_string()),
            http: None,
            method: None,
            header: None,
            tcp: None,
            grpc: None,
            grpc_use_tls: None,
            status: None,
            notes: None,
            tls_skip_verify: None,
            deregister_critical_service_after: None,
        }
    }

    /// Create a new gRPC check
    pub fn grpc(address: &str, interval: &str) -> Self {
        Self {
            check_id: None,
            name: None,
            script: None,
            args: None,
            docker_container_id: None,
            shell: None,
            interval: Some(interval.to_string()),
            timeout: None,
            ttl: None,
            http: None,
            method: None,
            header: None,
            tcp: None,
            grpc: Some(address.to_string()),
            grpc_use_tls: None,
            status: None,
            notes: None,
            tls_skip_verify: None,
            deregister_critical_service_after: None,
        }
    }

    pub fn with_name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }

    pub fn with_timeout(mut self, timeout: &str) -> Self {
        self.timeout = Some(timeout.to_string());
        self
    }

    pub fn with_deregister_after(mut self, duration: &str) -> Self {
        self.deregister_critical_service_after = Some(duration.to_string());
        self
    }
}

/// Check registration request
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct AgentCheckRegistration {
    /// Check ID
    #[serde(rename = "ID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// Check name
    pub name: String,
    /// Notes about the check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    /// Service ID this check is for
    #[serde(rename = "ServiceID")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_id: Option<String>,
    /// Check definition
    #[serde(flatten)]
    pub check: AgentServiceCheck,
}

/// Agent API client
pub struct Agent {
    client: Arc<HttpClient>,
}

impl Agent {
    /// Create a new Agent client
    pub fn new(client: Arc<HttpClient>) -> Self {
        Self { client }
    }

    /// Get information about the agent
    pub async fn self_info(&self) -> Result<AgentSelf> {
        let builder = self.client.get("/v1/agent/self");
        self.client.execute_json(builder).await
    }

    /// Get the agent's node name
    pub async fn node_name(&self) -> Result<String> {
        let info = self.self_info().await?;
        Ok(info.member.name)
    }

    /// List all services registered with the agent
    pub async fn services(&self) -> Result<HashMap<String, AgentService>> {
        let builder = self.client.get("/v1/agent/services");
        self.client.execute_json(builder).await
    }

    /// Get a single service by ID
    pub async fn service(&self, service_id: &str) -> Result<AgentService> {
        let path = format!("/v1/agent/service/{}", service_id);
        let builder = self.client.get(&path);
        self.client.execute_json(builder).await
    }

    /// List all checks registered with the agent
    pub async fn checks(&self) -> Result<HashMap<String, HealthCheck>> {
        let builder = self.client.get("/v1/agent/checks");
        self.client.execute_json(builder).await
    }

    /// List cluster members
    pub async fn members(&self, wan: bool) -> Result<Vec<AgentMember>> {
        let path = if wan {
            "/v1/agent/members?wan=1"
        } else {
            "/v1/agent/members"
        };
        let builder = self.client.get(path);
        self.client.execute_json(builder).await
    }

    /// Register a service
    pub async fn service_register(&self, registration: &AgentServiceRegistration) -> Result<WriteMeta> {
        let builder = self.client.put("/v1/agent/service/register").json(registration);
        self.client.write_empty(builder).await
    }

    /// Deregister a service
    pub async fn service_deregister(&self, service_id: &str) -> Result<WriteMeta> {
        let path = format!("/v1/agent/service/deregister/{}", service_id);
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Register a check
    pub async fn check_register(&self, registration: &AgentCheckRegistration) -> Result<WriteMeta> {
        let builder = self.client.put("/v1/agent/check/register").json(registration);
        self.client.write_empty(builder).await
    }

    /// Deregister a check
    pub async fn check_deregister(&self, check_id: &str) -> Result<WriteMeta> {
        let path = format!("/v1/agent/check/deregister/{}", check_id);
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Mark a TTL check as passing
    pub async fn pass_ttl(&self, check_id: &str, note: Option<&str>) -> Result<WriteMeta> {
        let mut path = format!("/v1/agent/check/pass/{}", check_id);
        if let Some(n) = note {
            path.push_str(&format!("?note={}", urlencoding::encode(n)));
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Mark a TTL check as warning
    pub async fn warn_ttl(&self, check_id: &str, note: Option<&str>) -> Result<WriteMeta> {
        let mut path = format!("/v1/agent/check/warn/{}", check_id);
        if let Some(n) = note {
            path.push_str(&format!("?note={}", urlencoding::encode(n)));
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Mark a TTL check as failing
    pub async fn fail_ttl(&self, check_id: &str, note: Option<&str>) -> Result<WriteMeta> {
        let mut path = format!("/v1/agent/check/fail/{}", check_id);
        if let Some(n) = note {
            path.push_str(&format!("?note={}", urlencoding::encode(n)));
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Update a TTL check with custom status
    pub async fn update_ttl(&self, check_id: &str, output: &str, status: &str) -> Result<WriteMeta> {
        let path = format!("/v1/agent/check/update/{}", check_id);
        let body = serde_json::json!({
            "Output": output,
            "Status": status
        });
        let builder = self.client.put(&path).json(&body);
        self.client.write_empty(builder).await
    }

    /// Enable service maintenance mode
    pub async fn enable_service_maintenance(&self, service_id: &str, reason: Option<&str>) -> Result<WriteMeta> {
        let mut path = format!("/v1/agent/service/maintenance/{}?enable=true", service_id);
        if let Some(r) = reason {
            path.push_str(&format!("&reason={}", urlencoding::encode(r)));
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Disable service maintenance mode
    pub async fn disable_service_maintenance(&self, service_id: &str) -> Result<WriteMeta> {
        let path = format!("/v1/agent/service/maintenance/{}?enable=false", service_id);
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Enable node maintenance mode
    pub async fn enable_node_maintenance(&self, reason: Option<&str>) -> Result<WriteMeta> {
        let mut path = "/v1/agent/maintenance?enable=true".to_string();
        if let Some(r) = reason {
            path.push_str(&format!("&reason={}", urlencoding::encode(r)));
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Disable node maintenance mode
    pub async fn disable_node_maintenance(&self) -> Result<WriteMeta> {
        let builder = self.client.put("/v1/agent/maintenance?enable=false");
        self.client.write_empty(builder).await
    }

    /// Force leave a node
    pub async fn force_leave(&self, node: &str) -> Result<WriteMeta> {
        let path = format!("/v1/agent/force-leave/{}", node);
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Join a cluster
    pub async fn join(&self, address: &str, wan: bool) -> Result<WriteMeta> {
        let mut path = format!("/v1/agent/join/{}", address);
        if wan {
            path.push_str("?wan=1");
        }
        let builder = self.client.put(&path);
        self.client.write_empty(builder).await
    }

    /// Leave the cluster gracefully
    pub async fn leave(&self) -> Result<WriteMeta> {
        let builder = self.client.put("/v1/agent/leave");
        self.client.write_empty(builder).await
    }
}