use std::borrow::Cow;
use std::path::Path;
use secrecy::{ExposeSecret, SecretBox};
use testcontainers::core::{ContainerPort, ContainerRequest, Mount, WaitFor};
use testcontainers::runners::AsyncRunner;
use testcontainers::{ContainerAsync, Image, ImageExt};
use tracing::Level;
use url::Url;
use crate::containers::{ContainerConfig, ContainerLogConsumer, ImageConfig};
use crate::helpers::{self, TempPathWithString};
const DATABASE_URL_KEY: &str = "FLORA_DATABASE_URL";
const READY_MESSAGE_KEY: &str = "FLORA_READY_MESSAGE";
const TRACING_LEVEL_KEY: &str = "FLORA_TRACING_LEVEL";
const TYPESENSE_API_KEY_KEY: &str = "FLORA_TYPESENSE_API_KEY";
const TYPESENSE_URL_KEY: &str = "FLORA_TYPESENSE_URL";
const DATA_PATH_CONTAINER: &str = "/usr/local/etc/flora";
const IMAGE_NAME: &str = "localhost:8777/omry-server";
const IMAGE_TAG: &str = "latest";
const CONTAINER_PORT: u16 = 37373;
const READY_MESSAGE: &str = "flora is ready!";
#[derive(Debug)]
pub enum EnvVar {
Plain {
key: String,
value: String,
},
Secret {
key: String,
value: SecretBox<str>,
},
}
impl EnvVar {
fn as_key_value_pair(&self) -> (&str, &str) {
match self {
Self::Plain { key, value } => (key, value),
Self::Secret { key, value } => (key, value.expose_secret()),
}
}
}
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Debug)]
pub struct FloraConfig {
database_url: EnvVar,
ready_message: EnvVar,
tracing_level: Option<EnvVar>,
typesense_api_key: EnvVar,
typesense_url: EnvVar,
}
impl FloraConfig {
#[must_use]
pub fn new(typesense_url: &Url, typesense_api_key: SecretBox<str>) -> Self {
let typesense_api_key = EnvVar::Secret {
key: TYPESENSE_API_KEY_KEY.to_string(),
value: typesense_api_key,
};
let typesense_url = EnvVar::Plain {
key: TYPESENSE_URL_KEY.to_string(),
value: typesense_url.to_string(),
};
let ready_message = EnvVar::Plain {
key: READY_MESSAGE_KEY.to_string(),
value: READY_MESSAGE.to_string(),
};
let db_path = Path::new(DATA_PATH_CONTAINER)
.join("flora.db")
.display()
.to_string();
let database_url = EnvVar::Plain {
key: DATABASE_URL_KEY.into(),
value: db_path,
};
Self {
typesense_api_key,
typesense_url,
ready_message,
database_url,
tracing_level: None,
}
}
#[must_use]
pub fn with_tracing_level(mut self, tracing_level: Level) -> Self {
let tracing_level = EnvVar::Plain {
key: TRACING_LEVEL_KEY.into(),
value: tracing_level.to_string(),
};
self.tracing_level = Some(tracing_level);
self
}
fn into_vec(self) -> Vec<EnvVar> {
let mut vars = vec![
self.database_url,
self.ready_message,
self.typesense_url,
self.typesense_api_key,
];
if let Some(tracing_level) = self.tracing_level {
vars.push(tracing_level);
}
vars
}
}
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Debug)]
pub struct FloraImage {
name: String,
tag: String,
env: Vec<EnvVar>,
mounts: Vec<Mount>,
container_ports: Vec<ContainerPort>,
ready_message: String,
host_port: Option<u16>,
#[allow(dead_code)]
data_temp_path: TempPathWithString,
}
impl FloraImage {
pub fn new(flora_config: FloraConfig, image_config: ImageConfig) -> anyhow::Result<Self> {
let data_temp_path = TempPathWithString::new()?;
let mount = Mount::bind_mount(data_temp_path.as_str(), DATA_PATH_CONTAINER);
let container_ports = if image_config.should_expose_ports {
vec![ContainerPort::Tcp(CONTAINER_PORT)]
} else {
vec![]
};
let (_, ready_message) = flora_config.ready_message.as_key_value_pair();
let ready_message = ready_message.into();
Ok(Self {
name: IMAGE_NAME.to_string(),
tag: IMAGE_TAG.to_string(),
env: flora_config.into_vec(),
data_temp_path,
mounts: vec![mount],
container_ports,
ready_message,
host_port: None,
})
}
fn with_auto_host_port(mut self) -> ContainerRequest<Self> {
let (_, host_port) = helpers::free_port_ipv6();
self.host_port = Some(host_port);
self.with_mapped_port(host_port, CONTAINER_PORT.into())
}
#[must_use]
pub fn host_port(&self) -> Option<u16> {
self.host_port
}
}
impl Image for FloraImage {
fn name(&self) -> &str {
&self.name
}
fn tag(&self) -> &str {
&self.tag
}
fn ready_conditions(&self) -> Vec<WaitFor> {
vec![WaitFor::message_on_stdout(&self.ready_message)]
}
fn env_vars(
&self,
) -> impl IntoIterator<Item = (impl Into<Cow<'_, str>>, impl Into<Cow<'_, str>>)> {
self.env.iter().map(EnvVar::as_key_value_pair)
}
fn mounts(&self) -> impl IntoIterator<Item = &Mount> {
&self.mounts
}
fn expose_ports(&self) -> &[ContainerPort] {
&self.container_ports
}
}
pub type FloraContainer = ContainerAsync<FloraImage>;
pub async fn start_flora_container<L>(
flora_config: FloraConfig,
container_config: ContainerConfig<L>,
) -> anyhow::Result<FloraContainer>
where
L: ContainerLogConsumer,
{
let flora_container =
FloraImage::new(flora_config, container_config.image_config)?.with_auto_host_port();
let flora_container = container_config.configure_container(flora_container);
Ok(flora_container.start().await?)
}