use std::time::Duration;
use dynamic_config::{dynamic_config, RemoteSource, RemoteWatch};
use dynamic_config_git::{Credential, GitSource};
use serde::Deserialize;
#[dynamic_config]
#[derive(Debug, Deserialize)]
struct DbConfig {
host: String,
port: u16,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = std::env::var("GIT_URL").unwrap_or_else(|_| "file:///tmp/config-repo".to_owned());
let credential = match std::env::var("GIT_TOKEN") {
Ok(token) => Credential::token(token),
Err(_) => Credential::anonymous(),
};
let source = GitSource::builder(&url)
.branch("main")
.path("db.yaml")
.credential(credential)
.build()?;
println!("built a source for {}\n", source.describe());
DbConfig::set_remote(source);
DbConfig::refresh_remote()?;
DbConfig::builder("db").env("APP_").init()?;
let started = DbConfig::current();
println!("at start: {}:{}", started.host, started.port);
let sink = DbConfig::remote_sink();
let watch = RemoteWatch::new();
let watching = watch.watching();
let watcher = std::thread::spawn(move || {
let source = GitSource::builder(&url)
.branch("main")
.path("db.yaml")
.build()
.expect("the same source, for the watch loop's own working directory");
source.watch(&watching, Duration::from_secs(5), move |document| {
sink.apply(document)
})
});
for _ in 0..24 {
std::thread::sleep(Duration::from_secs(5));
let now = DbConfig::current();
println!("now: {}:{}", now.host, now.port);
}
watch.stop();
let _ = watcher.join();
Ok(())
}