use std::collections::BTreeMap;
use std::fmt;
use std::time::SystemTime;
use async_trait::async_trait;
use olai_stack_state::{InstanceId, VarSet};
use crate::secrets::SecretValue;
#[derive(Clone, Default)]
pub struct Overlay {
pub vars: BTreeMap<String, String>,
pub endpoints: BTreeMap<String, String>,
pub credentials: BTreeMap<String, SecretValue>,
pub expires_at: Option<SystemTime>,
}
impl fmt::Debug for Overlay {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Overlay")
.field("vars", &self.vars)
.field("endpoints", &self.endpoints)
.field("credentials", &self.credentials.keys().collect::<Vec<_>>())
.field("expires_at", &self.expires_at)
.finish()
}
}
impl Overlay {
pub fn is_expired(&self, now: SystemTime) -> bool {
self.expires_at.is_some_and(|t| t <= now)
}
}
#[derive(Clone, Debug)]
pub struct SourceCtx {
pub instance: InstanceId,
pub workspace: String,
pub environment: String,
pub revision: u32,
pub config: serde_json::Value,
}
#[derive(Debug, thiserror::Error)]
#[error("source `{source_name}`: {reason}")]
pub struct SourceError {
pub source_name: String,
pub reason: String,
}
#[async_trait]
pub trait Source: Send + Sync {
fn name(&self) -> &str;
async fn overlay(&self, ctx: &SourceCtx) -> Result<Overlay, SourceError>;
async fn refresh(&self, ctx: &SourceCtx, current: &Overlay) -> Result<Overlay, SourceError> {
let _ = current;
self.overlay(ctx).await
}
}
#[derive(Clone, Debug, Default)]
pub struct UserVars {
vars: BTreeMap<String, String>,
}
impl UserVars {
pub fn new(vars: BTreeMap<String, String>) -> Self {
UserVars { vars }
}
pub fn from_var_set(set: &VarSet) -> Self {
UserVars::new(
set.0
.iter()
.filter_map(|(k, v)| match v {
olai_stack_state::VarValue::Literal(l) => Some((k.clone(), l.clone())),
olai_stack_state::VarValue::Secret(_) => None,
})
.collect(),
)
}
}
#[async_trait]
impl Source for UserVars {
fn name(&self) -> &str {
"user"
}
async fn overlay(&self, _ctx: &SourceCtx) -> Result<Overlay, SourceError> {
Ok(Overlay {
vars: self.vars.clone(),
..Overlay::default()
})
}
}