orthogonal design

This commit is contained in:
Infendro committed 2026-11-21 10:44:38 +01:00
1 parent 6467c79eac
commit 387f9d6b8c
12 files changed
+266 -161

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
use std::error::Error;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use crate::{config::AuthConfig, model::dns_record::DnsRecord};
const API: &str = "https://api.porkbun.com/api/json/v3";
#[derive(Clone)]
pub struct DnsClient {
auth_config: AuthConfig,
client: Client,
}
impl DnsClient {
pub fn new(auth_config: AuthConfig, client: Client) -> Self {
Self { auth_config, client }
}
pub async fn get_records(&self, domain: &str) -> Result<Vec<DnsRecord>, Box<dyn Error>> {
let body = GetRecordsRequest {
apikey: self.auth_config.key.clone(),
secretapikey: self.auth_config.secret_key.clone(),
};
let response = self.client.post(format!("{API}/dns/retrieve/{domain}"))
.json(&body)
.send().await?
.error_for_status()?;
let response_body = response.json::<GetRecordsResponse>().await?;
let records = response_body.records.iter()
.map(|it| {
let subdomain = it.name
.strip_suffix(domain).unwrap()
.strip_suffix(".").unwrap_or("");
DnsRecord::new(
it.id.clone(),
it.type_.clone(),
domain.to_string(),
subdomain.to_string(),
it.content.clone(),
it.ttl.parse().unwrap(),
)
})
.collect();
Ok(records)
}
pub async fn update_record(&self, record: &DnsRecord, value: &str) -> Result<(), Box<dyn Error>> {
let body = UpdateRecordRequest {
apikey: self.auth_config.key.clone(),
secretapikey: self.auth_config.secret_key.clone(),
type_: record.type_.clone(),
name: record.subdomain.clone(),
content: value.to_string(),
ttl: record.ttl,
};
self.client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id))
.json(&body)
.send().await?
.error_for_status()?;
Ok(())
}
}
#[derive(Serialize)]
struct GetRecordsRequest {
pub apikey: String,
pub secretapikey: String,
}
#[derive(Deserialize)]
struct GetRecordsResponse {
pub records: Vec<GetRecordsResponseRecord>,
}
#[derive(Deserialize)]
struct GetRecordsResponseRecord {
pub id: String,
#[serde(rename = "type")]
pub type_: String,
pub name: String,
pub content: String,
pub ttl: String,
}
#[derive(Serialize)]
struct UpdateRecordRequest {
pub apikey: String,
pub secretapikey: String,
#[serde(rename = "type")]
pub type_: String,
pub name: String,
pub content: String,
pub ttl: i32,
}
+48
View File
@@ -0,0 +1,48 @@
use std::error::Error;
use reqwest::Client;
use crate::model::ip_address::IpAddress;
const API4: &str = "https://api4.ipify.org";
const API6: &str = "https://api6.ipify.org";
#[derive(Clone)]
pub struct IpClient {
client: Client,
}
impl IpClient {
pub fn new(client: Client) -> Self {
Self { client: client.clone() }
}
pub async fn get_ip(&self) -> Result<IpAddress, Box<dyn Error>> {
let ipv4 = self.get_ipv4().await?;
let ipv6 = self.get_ipv6().await?;
let ip = IpAddress::new(ipv4, ipv6);
Ok(ip)
}
async fn get_ipv4(&self) -> Result<Option<String>, Box<dyn Error>> {
let response = self.client.get(API4)
.send().await;
let response = match response {
Ok(x) => x,
Err(_) => return Ok(None),
};
let ipv4 = response.text().await?;
Ok(Some(ipv4))
}
async fn get_ipv6(&self) -> Result<Option<String>, Box<dyn Error>> {
let response = self.client.get(API6)
.send().await;
let response = match response {
Ok(x) => x,
Err(_) => return Ok(None),
};
let ipv6 = response.text().await?;
Ok(Some(ipv6))
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod dns_client;
pub mod ip_client;
+20 -12
View File
@@ -1,27 +1,35 @@
use serde::Deserialize;
use std::{error::Error, fs};
#[derive(Deserialize)]
use serde::Deserialize;
#[derive(Clone, Deserialize)]
pub struct Config {
pub auth: Auth,
#[serde(rename = "entry")]
pub entries: Vec<Entry>,
pub auth: AuthConfig,
pub dns: DnsConfig,
}
#[derive(Deserialize)]
pub struct Auth {
#[derive(Clone, Deserialize)]
pub struct AuthConfig {
pub key: String,
pub secret_key: String,
}
#[derive(Deserialize)]
#[derive(Clone, Deserialize)]
pub struct DnsConfig {
pub entries: Vec<Entry>,
}
#[derive(Clone, Deserialize)]
pub struct Entry {
pub domain: String,
pub subdomains: Vec<String>,
}
pub fn load(path: &str) -> Result<Config, Box<dyn Error>> {
let raw = fs::read_to_string(&path)?;
let config = toml::from_str(&raw)?;
Ok(config)
impl Config {
pub fn load(path: &str) -> Result<Self, Box<dyn Error>> {
let raw = fs::read_to_string(&path)?;
let config = toml::from_str(&raw)?;
Ok(config)
}
}
-93
View File
@@ -1,93 +0,0 @@
use std::error::Error;
use reqwest::Client;
use serde::Deserialize;
use serde_json::json;
use crate::config::Auth;
pub struct Record {
pub id: String,
pub record_type: String,
pub domain: String,
pub subdomain: String,
pub value: String,
pub ttl: String,
}
const API: &str = "https://api.porkbun.com/api/json/v3";
#[derive(Deserialize)]
struct RecordsResponse {
records: Vec<RecordResponse>,
}
#[derive(Deserialize)]
struct RecordResponse {
id: String,
#[serde(rename = "type")]
record_type: String,
name: String,
content: String,
ttl: String,
}
impl RecordResponse {
fn into_model(self, domain: &str) -> Record {
let subdomain = self.name
.strip_suffix(domain).unwrap()
.strip_suffix(".").unwrap_or("");
Record {
id: self.id,
record_type: self.record_type,
domain: domain.to_string(),
subdomain: subdomain.to_string(),
value: self.content,
ttl: self.ttl,
}
}
}
pub async fn get_records(
client: &Client,
auth: &Auth,
domain: &str,
) -> Result<Vec<Record>, Box<dyn Error>> {
let body = json!({
"apikey": auth.key,
"secretapikey": auth.secret_key,
});
let request = client.post(format!("{API}/dns/retrieve/{domain}"))
.json(&body)
.send().await?;
let response = request.json::<RecordsResponse>().await?;
let records = response.records
.into_iter()
.map(|it| it.into_model(domain))
.collect();
Ok(records)
}
pub async fn update_record(
client: &Client,
auth: &Auth,
record: &Record,
value: &str,
) -> Result<(), Box<dyn Error>> {
let body = json!({
"apikey": auth.key,
"secretapikey": auth.secret_key,
"type": record.record_type,
"name": record.subdomain,
"content": value,
"ttl": record.ttl,
});
client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id))
.json(&body)
.send().await?;
Ok(())
}
-18
View File
@@ -1,18 +0,0 @@
use reqwest::Client;
use std::error::Error;
pub async fn get_ipv4(client: &Client) -> Result<String, Box<dyn Error>> {
get_ip(client, "https://api4.ipify.org").await
}
pub async fn get_ipv6(client: &Client) -> Result<String, Box<dyn Error>> {
get_ip(client, "https://api6.ipify.org").await
}
async fn get_ip(client: &Client, url: &str) -> Result<String, Box<dyn Error>> {
let request = client.get(url)
.send().await?
.error_for_status()?;
let ip = request.text().await?;
Ok(ip)
}
+11 -38
View File
@@ -1,52 +1,25 @@
pub mod client;
pub mod config;
pub mod model;
pub mod service;
use std::error::Error;
use reqwest::Client;
use crate::dns::Record;
mod config;
mod dns;
mod ip;
use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::Config, service::dns_service::DnsService};
const CONFIG: &str = "/etc/ddns.conf";
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = Config::load(CONFIG)?;
let client = Client::new();
let ip_client = IpClient::new(client.clone());
let dns_client = DnsClient::new(config.auth.clone(), client.clone());
let dns_service = DnsService::new(config.dns.clone(), ip_client, dns_client);
let config = config::load(CONFIG)?;
let ipv4 = ip::get_ipv4(&client).await.ok();
let ipv6 = ip::get_ipv6(&client).await.ok();
for entry in &config.entries {
let records = dns::get_records(&client, &config.auth, &entry.domain).await?;
if let Some(ip) = &ipv4 {
let a_records = find_records(&records, "A", &entry.subdomains, ip);
for record in a_records {
dns::update_record(&client, &config.auth, &record, ip).await?;
}
}
if let Some(ip) = &ipv6 {
let aaaa_records = find_records(&records, "AAAA", &entry.subdomains, ip);
for record in aaaa_records {
dns::update_record(&client, &config.auth, &record, ip).await?;
}
}
}
dns_service.update_records().await?;
Ok(())
}
fn find_records<'a>(
records: &'a [Record],
record_type: &str,
subdomains: &[String],
value: &str
) -> Vec<&'a Record> {
records.iter()
.filter(|it| it.record_type == record_type && subdomains.contains(&it.subdomain) && it.value != value)
.collect()
}
+21
View File
@@ -0,0 +1,21 @@
pub struct DnsRecord {
pub id: String,
pub type_: String,
pub domain: String,
pub subdomain: String,
pub value: String,
pub ttl: i32,
}
impl DnsRecord {
pub fn new(
id: String,
type_: String,
domain: String,
subdomain: String,
value: String,
ttl: i32,
) -> Self {
Self { id, type_, domain, subdomain, value, ttl }
}
}
+13
View File
@@ -0,0 +1,13 @@
pub struct IpAddress {
pub ipv4: Option<String>,
pub ipv6: Option<String>,
}
impl IpAddress {
pub fn new(
ipv4: Option<String>,
ipv6: Option<String>
) -> Self {
Self { ipv4, ipv6 }
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod dns_record;
pub mod ip_address;
+51
View File
@@ -0,0 +1,51 @@
use std::error::Error;
use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::{DnsConfig}, model::{dns_record::DnsRecord, ip_address::IpAddress}};
#[derive(Clone)]
pub struct DnsService {
dns_config: DnsConfig,
ip_client: IpClient,
dns_client: DnsClient,
}
impl DnsService {
pub fn new(dns_config: DnsConfig, ip_client: IpClient, dns_client: DnsClient) -> Self {
Self { dns_config, ip_client, dns_client }
}
pub async fn update_records(&self) -> Result<(), Box<dyn Error>> {
let ip = self.ip_client.get_ip().await?;
for entry in &self.dns_config.entries {
self.update_ip_records(&entry.domain, &entry.subdomains, &ip).await?;
}
Ok(())
}
async fn update_ip_records(&self, domain: &str, subdomains: &[String], ip: &IpAddress) -> Result<(), Box<dyn Error>> {
let records = self.dns_client.get_records(domain).await?;
if let Some(ipv4) = &ip.ipv4 {
let ipv4_records: Vec<&DnsRecord> = records.iter()
.filter(|it| it.type_ == "A" && subdomains.contains(&it.subdomain) && it.value != *ipv4)
.collect();
for ipv4_record in ipv4_records {
self.dns_client.update_record(&ipv4_record, ipv4).await?;
}
}
if let Some(ipv6) = &ip.ipv6 {
let ipv6_records: Vec<&DnsRecord> = records.iter()
.filter(|it| it.type_ == "AAAA" && subdomains.contains(&it.subdomain) && it.value != *ipv6)
.collect();
for ipv6_record in ipv6_records {
self.dns_client.update_record(&ipv6_record, ipv6).await?;
}
}
Ok(())
}
}
+1
View File
@@ -0,0 +1 @@
pub mod dns_service;