use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tokio::fs;
use crate::utils::now;
use crate::Error;
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Meta {
pub resource: String,
pub resource_path: PathBuf,
pub meta_path: PathBuf,
pub etag: Option<String>,
pub expires: Option<f64>,
pub creation_time: f64,
}
impl Meta {
pub(crate) fn new(
resource: String,
resource_path: PathBuf,
etag: Option<String>,
freshness_lifetime: Option<u64>,
) -> Meta {
let mut expires: Option<f64> = None;
let creation_time = now();
if let Some(lifetime) = freshness_lifetime {
expires = Some(creation_time + (lifetime as f64));
}
let meta_path = Meta::meta_path(&resource_path);
Meta {
resource,
resource_path,
meta_path,
etag,
expires,
creation_time,
}
}
pub(crate) fn meta_path(resource_path: &Path) -> PathBuf {
let mut meta_path = PathBuf::from(resource_path);
let resource_file_name = meta_path.file_name().unwrap().to_str().unwrap();
let meta_file_name = format!("{}.meta", resource_file_name);
meta_path.set_file_name(&meta_file_name[..]);
meta_path
}
pub(crate) async fn to_file(&self) -> Result<(), Error> {
let serialized = serde_json::to_string(self).unwrap();
fs::write(&self.meta_path, &serialized[..]).await?;
Ok(())
}
pub async fn from_cache(resource_path: &Path) -> Result<Self, Error> {
let meta_path = Meta::meta_path(resource_path);
Meta::from_path(&meta_path).await
}
pub(crate) async fn from_path(path: &Path) -> Result<Self, Error> {
let serialized = fs::read_to_string(path).await?;
let meta: Meta = serde_json::from_str(&serialized[..]).unwrap();
Ok(meta)
}
pub fn is_fresh(&self) -> bool {
if let Some(expiration_time) = self.expires {
expiration_time > now()
} else {
false
}
}
}