flux-releaser/crates/flux-releaser/tests/publish_artifacts.rs
kjuulh 6cf1a23169
Some checks failed
continuous-integration/drone/push Build is failing
feat: with actual archive test
Signed-off-by: kjuulh <contact@kjuulh.io>
2024-02-18 13:38:16 +01:00

192 lines
4.7 KiB
Rust

use std::{
env::temp_dir,
net::{Ipv4Addr, SocketAddr},
time::Duration,
};
use anyhow::Context;
use flux_releaser::{
app::SharedApp, grpc::gen::HelloRequest, services::file_store::extensions::FileStoreExt,
};
use tokio::{net::TcpListener, runtime::Runtime, time::sleep};
use tonic::transport::Channel;
use uuid::Uuid;
struct Server {
endpoints: Endpoints,
app: SharedApp,
}
#[derive(Clone, Debug)]
struct Endpoints {
http: SocketAddr,
grpc: SocketAddr,
}
impl Server {
pub async fn new() -> anyhow::Result<Self> {
let http_socket = Self::find_free_port().await?;
let grpc_socket = Self::find_free_port().await?;
Ok(Self {
endpoints: Endpoints {
http: http_socket,
grpc: grpc_socket,
},
app: SharedApp::new(flux_releaser::app::App::new().await?),
})
}
pub async fn start(&self) -> anyhow::Result<()> {
flux_releaser::cli::server::run_server(self.endpoints.http, self.endpoints.grpc).await?;
Ok(())
}
pub async fn find_free_port() -> anyhow::Result<SocketAddr> {
let socket = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0);
let listener = TcpListener::bind(socket).await?;
listener.local_addr().context("failed to get local addr")
}
}
static INIT: std::sync::Once = std::sync::Once::new();
async fn perform_task_with_backoff<F, Fut, T, E>(
mut task: F,
max_retries: u32,
base_delay_ms: u64,
) -> Result<T, E>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T, E>>,
{
let mut retries = 0;
let mut delay = base_delay_ms;
loop {
match task().await {
Ok(result) => return Ok(result),
Err(e) if retries < max_retries => {
sleep(Duration::from_millis(delay)).await;
delay *= 2; // Exponential backoff
retries += 1;
}
Err(e) => return Err(e),
}
}
}
// Makes sure the setup is ready for execution
async fn is_ready() -> anyhow::Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
perform_task_with_backoff(
|| async {
let endpoints = unsafe {
if ENDPOINTS.is_none() {
anyhow::bail!("endpoints not set yet");
}
ENDPOINTS.clone().unwrap()
};
let resp = reqwest::get(format!("http://{}/ping", endpoints.http)).await?;
if !resp.status().is_success() {
anyhow::bail!("failed with status: {}", resp.status());
}
Ok::<(), anyhow::Error>(())
},
5,
500,
)
.await?;
Ok(())
}
static mut ENDPOINTS: Option<Endpoints> = None;
static mut APP: Option<SharedApp> = None;
async fn setup() -> anyhow::Result<(Endpoints, SharedApp)> {
INIT.call_once(|| {
std::thread::spawn(|| {
let rt = Runtime::new().unwrap();
rt.block_on(async move {
println!("once was created once");
let server = Server::new().await.unwrap();
unsafe {
ENDPOINTS = Some(server.endpoints.clone());
APP = Some(server.app.clone());
}
server.start().await.unwrap();
})
});
});
is_ready().await?;
Ok(unsafe { (ENDPOINTS.clone().unwrap(), APP.clone().unwrap()) })
}
#[tokio::test]
async fn can_create_artifact() -> anyhow::Result<()> {
setup().await?;
Ok(())
}
#[tokio::test]
async fn can_more_create_artifact() -> anyhow::Result<()> {
std::env::set_var("RUST_LOG", "flux_releaser=trace");
let (endpoints, app) = setup().await?;
let mut client = flux_releaser::grpc::gen::greeter_client::GreeterClient::connect(format!(
"http://{}",
endpoints.grpc
))
.await?;
let test_id = Uuid::new_v4();
let temp = temp_dir()
.join("flux_releaser")
.join("tests")
.join(test_id.to_string());
let file_path = temp
.join("clusters")
.join(Uuid::new_v4().to_string())
.join("some-file.yaml");
tokio::fs::create_dir_all(file_path.parent().unwrap()).await?;
let _ = tokio::fs::File::create(file_path).await?;
let resp = client
.say_hello(HelloRequest {
app: "some-app".into(),
branch: "some-branch".into(),
folder: temp.to_string_lossy().to_string(),
})
.await?;
let artifact = resp.into_inner();
let archive = app
.file_store()
.get_archive(artifact.artifact_id.try_into()?)
.await?;
assert!(archive.exists());
Ok(())
}
pub struct TestGreeter {}