manydns 1.1.1

Provider-agnostic DNS zone and record management, inspired by the Go libdns project
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
//! Low-level Hetzner Cloud DNS API client.
//!
//! This module provides direct access to the Hetzner Cloud DNS API endpoints.
//! For most use cases, prefer using [`HetznerProvider`](super::HetznerProvider) instead.
//!
//! # API Reference
//!
//! - [Hetzner Cloud API Documentation](https://docs.hetzner.cloud/)
//! - [DNS Zones API](https://docs.hetzner.cloud/reference/cloud#zones)
//! - [DNS RRSets API](https://docs.hetzner.cloud/reference/cloud#zone-rrsets)
//!
//! # Example
//!
//! ```rust,no_run
//! use manydns::hetzner::api::Client;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let client = Client::new("your-api-token")?;
//!
//! // List zones
//! let response = client.retrieve_zones(1, 100).await?;
//! for zone in &response.zones {
//!     println!("Zone: {} (ID: {})", zone.name, zone.id);
//! }
//! # Ok(())
//! # }
//! ```

use std::error::Error;

use reqwest::{
    header::{HeaderMap, HeaderValue, AUTHORIZATION},
    Client as HttpClient,
};
use serde::{Deserialize, Serialize};

use crate::HttpClientConfig;

const HETZNER_API_URL: &str = "https://api.hetzner.cloud/v1";

/// Low-level Hetzner Cloud DNS API client.
///
/// Provides direct access to Hetzner Cloud DNS API endpoints.
/// For most use cases, prefer [`HetznerProvider`](super::HetznerProvider).
#[derive(Debug, Clone)]
pub struct Client {
    http_client: HttpClient,
    base_url: String,
}

impl Client {
    /// Creates a new Hetzner Cloud DNS API client.
    ///
    /// # Arguments
    ///
    /// * `api_key` - Hetzner Cloud API token (Bearer token)
    pub fn new(api_key: &str) -> Result<Self, Box<dyn Error>> {
        Self::with_base_url_and_config(api_key, HETZNER_API_URL, HttpClientConfig::default())
    }

    /// Creates a new client with custom HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `api_key` - Hetzner Cloud API token
    /// * `config` - HTTP client configuration for network binding
    pub fn with_config(api_key: &str, config: HttpClientConfig) -> Result<Self, Box<dyn Error>> {
        Self::with_base_url_and_config(api_key, HETZNER_API_URL, config)
    }

    /// Creates a new client with a custom base URL.
    ///
    /// Primarily used for testing with mock servers.
    ///
    /// # Arguments
    ///
    /// * `api_key` - Hetzner Cloud API token
    /// * `base_url` - Base URL for API requests
    pub fn with_base_url(api_key: &str, base_url: &str) -> Result<Self, Box<dyn Error>> {
        Self::with_base_url_and_config(api_key, base_url, HttpClientConfig::default())
    }

    /// Creates a new client with a custom base URL and HTTP configuration.
    ///
    /// # Arguments
    ///
    /// * `api_key` - Hetzner Cloud API token
    /// * `base_url` - Base URL for API requests
    /// * `config` - HTTP client configuration for network binding
    pub fn with_base_url_and_config(
        api_key: &str,
        base_url: &str,
        config: HttpClientConfig,
    ) -> Result<Self, Box<dyn Error>> {
        let mut headers = HeaderMap::new();
        let mut auth_value = HeaderValue::from_str(&format!("Bearer {}", api_key))?;
        auth_value.set_sensitive(true);
        headers.append(AUTHORIZATION, auth_value);

        let mut builder = HttpClient::builder().default_headers(headers);

        if let Some(timeout) = config.timeout {
            builder = builder.timeout(timeout);
        }

        if let Some(addr) = config.local_address {
            builder = builder.local_address(addr);
        }

        #[cfg(any(
            target_os = "android",
            target_os = "fuchsia",
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "tvos",
            target_os = "watchos",
            target_os = "illumos",
            target_os = "solaris",
        ))]
        if let Some(ref iface) = config.interface {
            builder = builder.interface(iface);
        }

        let http_client = builder.build()?;
        Ok(Self {
            http_client,
            base_url: base_url.to_string(),
        })
    }

    /// Retrieves a paginated list of zones.
    ///
    /// # Arguments
    ///
    /// * `page` - Page number (1-indexed)
    /// * `per_page` - Number of items per page
    pub async fn retrieve_zones(
        &self,
        page: u32,
        per_page: u32,
    ) -> Result<ZonesResponse, reqwest::Error> {
        self.http_client
            .get(format!(
                "{}/zones?page={}&per_page={}",
                self.base_url, page, per_page
            ))
            .send()
            .await?
            .json::<ZonesResponse>()
            .await
    }

    /// Retrieves a zone by ID or name.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier (numeric ID) or domain name
    pub async fn retrieve_zone(
        &self,
        zone_id_or_name: &str,
    ) -> Result<ZoneResponse, reqwest::Error> {
        self.http_client
            .get(format!("{}/zones/{}", self.base_url, zone_id_or_name))
            .send()
            .await?
            .json()
            .await
    }

    /// Creates a new zone.
    ///
    /// # Arguments
    ///
    /// * `domain` - Domain name for the zone
    /// * `ttl` - Default TTL for the zone (default: 3600)
    pub async fn create_zone(
        &self,
        domain: &str,
        ttl: Option<u64>,
    ) -> Result<CreateZoneResponse, reqwest::Error> {
        let request_body = CreateZoneRequest {
            name: domain.to_string(),
            mode: "primary".to_string(),
            ttl: ttl.unwrap_or(3600),
        };

        self.http_client
            .post(format!("{}/zones", self.base_url))
            .json(&request_body)
            .send()
            .await?
            .json()
            .await
    }

    /// Deletes a zone by ID or name.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    pub async fn delete_zone(&self, zone_id_or_name: &str) -> Result<(), reqwest::Error> {
        self.http_client
            .delete(format!("{}/zones/{}", self.base_url, zone_id_or_name))
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Retrieves a paginated list of RRSets in a zone.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `page` - Page number (1-indexed)
    /// * `per_page` - Number of items per page (max 100)
    pub async fn retrieve_rrsets(
        &self,
        zone_id_or_name: &str,
        page: u32,
        per_page: u32,
    ) -> Result<RRSetsResponse, reqwest::Error> {
        self.http_client
            .get(format!(
                "{}/zones/{}/rrsets?page={}&per_page={}",
                self.base_url, zone_id_or_name, page, per_page
            ))
            .send()
            .await?
            .json()
            .await
    }

    /// Retrieves a specific RRSet by name and type.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `rr_name` - Record name (e.g., "www" or "@" for apex)
    /// * `rr_type` - Record type (A, AAAA, CNAME, etc.)
    pub async fn retrieve_rrset(
        &self,
        zone_id_or_name: &str,
        rr_name: &str,
        rr_type: &str,
    ) -> Result<RRSetResponse, reqwest::Error> {
        self.http_client
            .get(format!(
                "{}/zones/{}/rrsets/{}/{}",
                self.base_url, zone_id_or_name, rr_name, rr_type
            ))
            .send()
            .await?
            .json()
            .await
    }

    /// Creates a new RRSet in a zone.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `name` - Record name (e.g., "www" or "@" for apex)
    /// * `typ` - Record type (A, AAAA, CNAME, etc.)
    /// * `records` - List of record values
    /// * `ttl` - TTL in seconds (None uses zone default)
    pub async fn create_rrset(
        &self,
        zone_id_or_name: &str,
        name: &str,
        typ: &str,
        records: Vec<RecordValue>,
        ttl: Option<u64>,
    ) -> Result<CreateRRSetResponse, reqwest::Error> {
        let request_body = CreateRRSetRequest {
            name: name.to_string(),
            typ: typ.to_string(),
            records,
            ttl,
        };

        self.http_client
            .post(format!(
                "{}/zones/{}/rrsets",
                self.base_url, zone_id_or_name
            ))
            .json(&request_body)
            .send()
            .await?
            .json()
            .await
    }

    /// Adds records to an existing RRSet (creates it if it doesn't exist).
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `rr_name` - Record name (e.g., "www" or "@" for apex)
    /// * `rr_type` - Record type (A, AAAA, CNAME, etc.)
    /// * `records` - List of record values to add
    /// * `ttl` - TTL in seconds (must match existing RRSet TTL if updating)
    pub async fn add_records_to_rrset(
        &self,
        zone_id_or_name: &str,
        rr_name: &str,
        rr_type: &str,
        records: Vec<RecordValue>,
        ttl: Option<u64>,
    ) -> Result<ActionResponse, reqwest::Error> {
        let request_body = AddRecordsRequest { records, ttl };

        self.http_client
            .post(format!(
                "{}/zones/{}/rrsets/{}/{}/actions/add_records",
                self.base_url, zone_id_or_name, rr_name, rr_type
            ))
            .json(&request_body)
            .send()
            .await?
            .json()
            .await
    }

    /// Removes records from an RRSet.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `rr_name` - Record name (e.g., "www" or "@" for apex)
    /// * `rr_type` - Record type (A, AAAA, CNAME, etc.)
    /// * `records` - List of record values to remove
    pub async fn remove_records_from_rrset(
        &self,
        zone_id_or_name: &str,
        rr_name: &str,
        rr_type: &str,
        records: Vec<RecordValue>,
    ) -> Result<ActionResponse, reqwest::Error> {
        let request_body = RemoveRecordsRequest { records };

        self.http_client
            .post(format!(
                "{}/zones/{}/rrsets/{}/{}/actions/remove_records",
                self.base_url, zone_id_or_name, rr_name, rr_type
            ))
            .json(&request_body)
            .send()
            .await?
            .json()
            .await
    }

    /// Deletes an entire RRSet.
    ///
    /// # Arguments
    ///
    /// * `zone_id_or_name` - Zone identifier or domain name
    /// * `rr_name` - Record name (e.g., "www" or "@" for apex)
    /// * `rr_type` - Record type (A, AAAA, CNAME, etc.)
    pub async fn delete_rrset(
        &self,
        zone_id_or_name: &str,
        rr_name: &str,
        rr_type: &str,
    ) -> Result<ActionResponse, reqwest::Error> {
        self.http_client
            .delete(format!(
                "{}/zones/{}/rrsets/{}/{}",
                self.base_url, zone_id_or_name, rr_name, rr_type
            ))
            .send()
            .await?
            .json()
            .await
    }
}

// ============================================================================
// Request Types
// ============================================================================

/// Request body for creating a zone.
#[derive(Debug, Serialize)]
struct CreateZoneRequest {
    name: String,
    mode: String,
    ttl: u64,
}

/// Request body for creating an RRSet.
#[derive(Debug, Serialize)]
struct CreateRRSetRequest {
    name: String,
    #[serde(rename = "type")]
    typ: String,
    records: Vec<RecordValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ttl: Option<u64>,
}

/// Request body for adding records to an RRSet.
#[derive(Debug, Serialize)]
struct AddRecordsRequest {
    records: Vec<RecordValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ttl: Option<u64>,
}

/// Request body for removing records from an RRSet.
#[derive(Debug, Serialize)]
struct RemoveRecordsRequest {
    records: Vec<RecordValue>,
}

// ============================================================================
// Response Types
// ============================================================================

/// A DNS zone in Hetzner Cloud.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct Zone {
    /// Unique zone identifier (numeric).
    pub id: u64,
    /// Domain name (e.g., "example.com").
    pub name: String,
    /// Zone mode (primary or secondary).
    pub mode: String,
    /// Zone status.
    pub status: ZoneStatus,
    /// Default TTL for records in this zone.
    pub ttl: u64,
    /// Number of records in the zone.
    #[serde(default)]
    pub record_count: u32,
}

/// Zone status in Hetzner Cloud DNS.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZoneStatus {
    /// Zone is active and working.
    Ok,
    /// Zone is pending setup.
    Pending,
    /// Zone verification failed.
    Failed,
}

/// Response wrapper for a single zone.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct ZoneResponse {
    /// The zone data.
    pub zone: Zone,
}

/// Response wrapper for creating a zone.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct CreateZoneResponse {
    /// The created zone.
    pub zone: Zone,
    /// The action tracking the creation.
    pub action: Action,
}

/// Response wrapper for listing zones.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct ZonesResponse {
    /// Pagination metadata.
    pub meta: Meta,
    /// List of zones.
    pub zones: Vec<Zone>,
}

/// A DNS RRSet (Resource Record Set) in Hetzner Cloud.
///
/// An RRSet is a collection of DNS records with the same name and type.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct RRSet {
    /// Unique RRSet identifier (format: "name/type").
    pub id: String,
    /// Record name (e.g., "www" or "@" for apex).
    pub name: String,
    /// Record type (A, AAAA, CNAME, etc.).
    #[serde(rename = "type")]
    pub typ: String,
    /// TTL in seconds (None uses zone default).
    pub ttl: Option<u64>,
    /// List of record values.
    pub records: Vec<RecordValue>,
    /// Zone ID this RRSet belongs to.
    pub zone: u64,
}

/// A single record value within an RRSet.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Serialize, Deserialize)]
pub struct RecordValue {
    /// The record value (e.g., IP address for A records).
    pub value: String,
    /// Optional comment for this record.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

impl RecordValue {
    /// Creates a new record value without a comment.
    pub fn new(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            comment: None,
        }
    }

    /// Creates a new record value with a comment.
    pub fn with_comment(value: impl Into<String>, comment: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            comment: Some(comment.into()),
        }
    }
}

/// Response wrapper for a single RRSet.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct RRSetResponse {
    /// The RRSet data.
    pub rrset: RRSet,
}

/// Response wrapper for creating an RRSet.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct CreateRRSetResponse {
    /// The created RRSet.
    pub rrset: RRSet,
    /// The action tracking the creation.
    pub action: Action,
}

/// Response wrapper for listing RRSets.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct RRSetsResponse {
    /// Pagination metadata.
    pub meta: Meta,
    /// List of RRSets.
    pub rrsets: Vec<RRSet>,
}

/// Response wrapper for actions.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct ActionResponse {
    /// The action data.
    pub action: Action,
}

/// An async action in Hetzner Cloud.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct Action {
    /// Unique action identifier.
    pub id: u64,
    /// Command that was executed.
    pub command: String,
    /// Current status.
    pub status: ActionStatus,
    /// Progress percentage (0-100).
    pub progress: u32,
}

/// Status of an action in Hetzner Cloud.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ActionStatus {
    /// Action is currently running.
    Running,
    /// Action completed successfully.
    Success,
    /// Action failed.
    Error,
}

/// Pagination metadata for list responses.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct Meta {
    /// Pagination details.
    pub pagination: Pagination,
}

/// Pagination details for list responses.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Deserialize)]
pub struct Pagination {
    /// Last page number (1-indexed).
    pub last_page: u32,
    /// Current page number (1-indexed).
    pub page: u32,
    /// Items per page.
    pub per_page: u32,
    /// Total number of entries across all pages.
    pub total_entries: u32,
}