Add first test (#38)
* wip * wip implement test * complete test * add lint and test actions * fix bad format
This commit is contained in:
parent
80d8c8885b
commit
90c5485cce
|
@ -0,0 +1,17 @@
|
||||||
|
on: push
|
||||||
|
name: lint checks
|
||||||
|
jobs:
|
||||||
|
rust_lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- run: rustup component add clippy
|
||||||
|
- uses: actions-rs/clippy-check@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
args: --all-features
|
||||||
|
rust_format_check:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- run: cargo fmt --all --check
|
|
@ -0,0 +1,25 @@
|
||||||
|
name: test
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- "main"
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- "*"
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: run tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Install Rust
|
||||||
|
run: rustup toolchain install stable --component llvm-tools-preview
|
||||||
|
- name: Install cargo-llvm-cov
|
||||||
|
uses: taiki-e/install-action@cargo-llvm-cov
|
||||||
|
- name: Generate code coverage
|
||||||
|
run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info
|
||||||
|
- name: Upload coverage to Codecov
|
||||||
|
uses: codecov/codecov-action@v3
|
||||||
|
with:
|
||||||
|
files: lcov.info
|
||||||
|
fail_ci_if_error: true
|
|
@ -3,5 +3,6 @@
|
||||||
"gandi",
|
"gandi",
|
||||||
"rrset",
|
"rrset",
|
||||||
"structopt"
|
"structopt"
|
||||||
]
|
],
|
||||||
|
"editor.formatOnSave": true
|
||||||
}
|
}
|
File diff suppressed because it is too large
Load Diff
|
@ -9,7 +9,6 @@ strip = "symbols"
|
||||||
lto = true
|
lto = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|
||||||
reqwest = { version = "0.11", default-features= false, features = ["json", "rustls-tls"] }
|
reqwest = { version = "0.11", default-features= false, features = ["json", "rustls-tls"] }
|
||||||
toml = "0.5"
|
toml = "0.5"
|
||||||
json = "0.12"
|
json = "0.12"
|
||||||
|
@ -20,5 +19,9 @@ tokio = { version = "1.20", features = ["full"] }
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
governor = "0.4"
|
governor = "0.4"
|
||||||
|
async-trait = "0.1"
|
||||||
# TODO: Relies on a yet-unreleased interface. Switch to an actual crate release once available
|
# TODO: Relies on a yet-unreleased interface. Switch to an actual crate release once available
|
||||||
die-exit = { git = "https://github.com/Xavientois/die.git", rev = "31d3801f4e21654b0b28430987b1e21fc7728676" }
|
die-exit = { git = "https://github.com/Xavientois/die.git", rev = "31d3801f4e21654b0b28430987b1e21fc7728676" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
httpmock = "0.6"
|
||||||
|
|
|
@ -13,7 +13,9 @@ pub struct Entry {
|
||||||
ttl: Option<u32>,
|
ttl: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_ttl() -> u32 { return 300; }
|
fn default_ttl() -> u32 {
|
||||||
|
return 300;
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
|
|
|
@ -0,0 +1,15 @@
|
||||||
|
pub(crate) struct GandiAPI<'t> {
|
||||||
|
pub(crate) base_url: &'t str,
|
||||||
|
pub(crate) fqdn: &'t str,
|
||||||
|
pub(crate) rrset_name: &'t str,
|
||||||
|
pub(crate) rrset_type: &'t str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t> GandiAPI<'t> {
|
||||||
|
pub(crate) fn url(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"{}/v5/livedns/domains/{}/records/{}/{}",
|
||||||
|
self.base_url, self.fqdn, self.rrset_name, self.rrset_type
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
use anyhow;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait IPSource {
|
||||||
|
async fn get_ipv4() -> anyhow::Result<String>;
|
||||||
|
async fn get_ipv6() -> anyhow::Result<String>;
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
use anyhow;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use super::ip_source::IPSource;
|
||||||
|
|
||||||
|
pub(crate) struct IPSourceIpify {}
|
||||||
|
|
||||||
|
async fn get_ip(api_url: &str) -> anyhow::Result<String> {
|
||||||
|
let response = reqwest::get(api_url).await?;
|
||||||
|
let text = response.text().await?;
|
||||||
|
Ok(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl IPSource for IPSourceIpify {
|
||||||
|
async fn get_ipv4() -> anyhow::Result<String> {
|
||||||
|
get_ip("https://api.ipify.org").await
|
||||||
|
}
|
||||||
|
async fn get_ipv6() -> anyhow::Result<String> {
|
||||||
|
get_ip("https://api6.ipify.org").await
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
pub(crate) mod ip_source;
|
||||||
|
pub(crate) mod ipify;
|
108
src/main.rs
108
src/main.rs
|
@ -1,29 +1,26 @@
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
|
use crate::gandi::GandiAPI;
|
||||||
|
use crate::ip_source::{ip_source::IPSource, ipify::IPSourceIpify};
|
||||||
use anyhow;
|
use anyhow;
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use futures;
|
use futures;
|
||||||
|
use opts::Opts;
|
||||||
use reqwest::{header, Client, ClientBuilder, StatusCode};
|
use reqwest::{header, Client, ClientBuilder, StatusCode};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::{num::NonZeroU32, sync::Arc, time::Duration};
|
use std::{num::NonZeroU32, sync::Arc, time::Duration};
|
||||||
use tokio::{self, task::JoinHandle};
|
use tokio::{self, task::JoinHandle};
|
||||||
mod config;
|
mod config;
|
||||||
|
mod gandi;
|
||||||
|
mod ip_source;
|
||||||
mod opts;
|
mod opts;
|
||||||
use die_exit::*;
|
use die_exit::*;
|
||||||
use governor;
|
use governor;
|
||||||
|
|
||||||
|
|
||||||
/// 30 requests per minute, see https://api.gandi.net/docs/reference/
|
/// 30 requests per minute, see https://api.gandi.net/docs/reference/
|
||||||
const GANDI_RATE_LIMIT: u32 = 30;
|
const GANDI_RATE_LIMIT: u32 = 30;
|
||||||
/// If we hit the rate limit, wait up to this many seconds before next attempt
|
/// If we hit the rate limit, wait up to this many seconds before next attempt
|
||||||
const GANDI_DELAY_JITTER: u64 = 20;
|
const GANDI_DELAY_JITTER: u64 = 20;
|
||||||
|
|
||||||
fn gandi_api_url(fqdn: &str, rrset_name: &str, rrset_type: &str) -> String {
|
|
||||||
return format!(
|
|
||||||
" https://api.gandi.net/v5/livedns/domains/{}/records/{}/{}",
|
|
||||||
fqdn, rrset_name, rrset_type
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn api_client(api_key: &str) -> anyhow::Result<Client> {
|
fn api_client(api_key: &str) -> anyhow::Result<Client> {
|
||||||
let client_builder = ClientBuilder::new();
|
let client_builder = ClientBuilder::new();
|
||||||
|
|
||||||
|
@ -38,27 +35,19 @@ fn api_client(api_key: &str) -> anyhow::Result<Client> {
|
||||||
return Ok(client);
|
return Ok(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_ip(api_url: &str) -> anyhow::Result<String> {
|
|
||||||
let response = reqwest::get(api_url).await?;
|
|
||||||
let text = response.text().await?;
|
|
||||||
Ok(text)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct APIPayload {
|
pub struct APIPayload {
|
||||||
pub rrset_values: Vec<String>,
|
pub rrset_values: Vec<String>,
|
||||||
pub rrset_ttl: u32,
|
pub rrset_ttl: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main(flavor = "current_thread")]
|
async fn run<IP: IPSource>(base_url: &str, opts: Opts) -> anyhow::Result<()> {
|
||||||
async fn main() -> anyhow::Result<()> {
|
|
||||||
let opts = opts::Opts::parse();
|
|
||||||
let conf = config::load_config(&opts)
|
let conf = config::load_config(&opts)
|
||||||
.die_with(|error| format!("Failed to read config file: {}", error));
|
.die_with(|error| format!("Failed to read config file: {}", error));
|
||||||
config::validate_config(&conf).die_with(|error| format!("Invalid config: {}", error));
|
config::validate_config(&conf).die_with(|error| format!("Invalid config: {}", error));
|
||||||
println!("Finding out the IP address...");
|
println!("Finding out the IP address...");
|
||||||
let ipv4_result = get_ip("https://api.ipify.org").await;
|
let ipv4_result = IP::get_ipv4().await;
|
||||||
let ipv6_result = get_ip("https://api6.ipify.org").await;
|
let ipv6_result = IP::get_ipv6().await;
|
||||||
let ipv4 = ipv4_result.as_ref();
|
let ipv4 = ipv4_result.as_ref();
|
||||||
let ipv6 = ipv6_result.as_ref();
|
let ipv6 = ipv6_result.as_ref();
|
||||||
println!("Found these:");
|
println!("Found these:");
|
||||||
|
@ -84,10 +73,16 @@ async fn main() -> anyhow::Result<()> {
|
||||||
for entry in &conf.entry {
|
for entry in &conf.entry {
|
||||||
for entry_type in Config::types(entry) {
|
for entry_type in Config::types(entry) {
|
||||||
let fqdn = Config::fqdn(&entry, &conf).to_string();
|
let fqdn = Config::fqdn(&entry, &conf).to_string();
|
||||||
let url = gandi_api_url(&fqdn, entry.name.as_str(), entry_type);
|
let url = GandiAPI {
|
||||||
|
fqdn: &fqdn,
|
||||||
|
rrset_name: &entry.name,
|
||||||
|
rrset_type: &entry_type,
|
||||||
|
base_url,
|
||||||
|
}
|
||||||
|
.url();
|
||||||
let ip = match entry_type {
|
let ip = match entry_type {
|
||||||
"A" => ipv4.die_with(|error| format!("Needed IPv4 for {}: {}", fqdn, error)),
|
"A" => ipv4.die_with(|error| format!("Needed IPv4 for {fqdn}: {error}")),
|
||||||
"AAAA" => ipv6.die_with(|error| format!("Needed IPv6 for {}: {}", fqdn, error)),
|
"AAAA" => ipv6.die_with(|error| format!("Needed IPv6 for {fqdn}: {error}")),
|
||||||
bad_entry_type => die!("Unexpected type in config: {}", bad_entry_type),
|
bad_entry_type => die!("Unexpected type in config: {}", bad_entry_type),
|
||||||
};
|
};
|
||||||
let payload = APIPayload {
|
let payload = APIPayload {
|
||||||
|
@ -121,5 +116,72 @@ async fn main() -> anyhow::Result<()> {
|
||||||
println!("{} - {}", status, body);
|
println!("{} - {}", status, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(());
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main(flavor = "current_thread")]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
let opts = opts::Opts::parse();
|
||||||
|
run::<IPSourceIpify>("https://api.gandi.net", opts).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::env::temp_dir;
|
||||||
|
|
||||||
|
use crate::{ip_source::ip_source::IPSource, opts::Opts, run};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use httpmock::MockServer;
|
||||||
|
use tokio::fs;
|
||||||
|
|
||||||
|
struct IPSourceMock {}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl IPSource for IPSourceMock {
|
||||||
|
async fn get_ipv4() -> anyhow::Result<String> {
|
||||||
|
Ok("192.168.0.0".to_string())
|
||||||
|
}
|
||||||
|
async fn get_ipv6() -> anyhow::Result<String> {
|
||||||
|
Ok("fe80:0000:0208:74ff:feda:625c".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn create_repo_success_test() {
|
||||||
|
let mut temp = temp_dir().join("gandi-live-dns-test");
|
||||||
|
fs::create_dir_all(&temp)
|
||||||
|
.await
|
||||||
|
.expect("Failed to create test dir");
|
||||||
|
temp.push("test.toml");
|
||||||
|
fs::write(
|
||||||
|
&temp,
|
||||||
|
"fqdn = \"example.com\"\napi_key = \"xxx\"\nttl = 300\n[[entry]]\nname =\"@\"\n",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed to write test config file");
|
||||||
|
let fqdn = "example.com";
|
||||||
|
let rname = "@";
|
||||||
|
let rtype = "A";
|
||||||
|
let server = MockServer::start();
|
||||||
|
let mock = server.mock(|when, then| {
|
||||||
|
when.method("PUT")
|
||||||
|
.path(format!(
|
||||||
|
"/v5/livedns/domains/{fqdn}/records/{rname}/{rtype}"
|
||||||
|
))
|
||||||
|
.body_contains("192.168.0.0");
|
||||||
|
then.status(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
run::<IPSourceMock>(
|
||||||
|
server.base_url().as_str(),
|
||||||
|
Opts {
|
||||||
|
config: Some(temp.to_string_lossy().to_string()),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("Failed when running the update");
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
mock.assert();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,5 +7,4 @@ pub struct Opts {
|
||||||
/// The path to the configuration file.
|
/// The path to the configuration file.
|
||||||
#[clap(long)]
|
#[clap(long)]
|
||||||
pub config: Option<String>,
|
pub config: Option<String>,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue