use std::path::PathBuf;
use std::time::Duration;
use semver::Version;
use crate::util::managed_bin::{self, Release};
const REGISTRY_LATEST: &str = "https://registry.npmjs.org/hyperframes/latest";
const PACKAGE: &str = "hyperframes";
const ENTRY: &str = "hyperframes/bin/hyperframes.mjs";
const NO_ENTRY: &str = "the installed hyperframes package carries no entry point";
const NODE_MODULES: &str = "node_modules";
const RELEASE_TIMEOUT: Duration = Duration::from_secs(60);
static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static IN_USE: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
fn root() -> Result<PathBuf, String> {
crate::config::default_config_dir()
.map(|dir| dir.join(PACKAGE))
.map_err(|_| "the product's configuration directory is unavailable".to_string())
}
pub(super) fn dir() -> Result<PathBuf, String> {
let dir = root()?;
std::fs::create_dir_all(&dir).map_err(|e| {
format!(
"the product's hyperframes directory could not be created ({})",
e.kind()
)
})?;
Ok(dir)
}
pub(super) fn entry() -> Option<PathBuf> {
let entry = root().ok()?.join(NODE_MODULES).join(ENTRY);
entry.is_file().then_some(entry)
}
pub(super) async fn hold_for_run()
-> Result<(tokio::sync::RwLockReadGuard<'static, ()>, PathBuf), String> {
let held = IN_USE.read().await;
let entry = entry().ok_or_else(|| "the renderer is not installed".to_string())?;
Ok((held, entry))
}
async fn installed_version() -> Option<Version> {
let path = root()
.ok()?
.join(NODE_MODULES)
.join("hyperframes/package.json");
let body = tokio::fs::read_to_string(path).await.ok()?;
manifest_version(&body)
}
async fn start_probe() -> Option<Version> {
if let Ok(dir) = root() {
super::reclaim_scratch(&dir);
}
installed_version().await
}
fn manifest_version(body: &str) -> Option<Version> {
let value = serde_json::from_str::<serde_json::Value>(body).ok()?;
Version::parse(value.get("version")?.as_str()?).ok()
}
async fn newest_version() -> Result<Version, String> {
let client = crate::util::http::build_download_client(RELEASE_TIMEOUT)
.map_err(|_| "the release check's own client could not be built".to_string())?;
let response = client.get(REGISTRY_LATEST).send().await.map_err(|e| {
format!(
"the release check request failed: {}",
crate::util::managed_bin::request_reason(&e)
)
})?;
if !response.status().is_success() {
return Err(format!("the release check got HTTP {}", response.status()));
}
let body = response.text().await.map_err(|e| {
format!(
"the release check's answer could not be read: {}",
crate::util::managed_bin::request_reason(&e)
)
})?;
manifest_version(&body)
.ok_or_else(|| "the newest release's answer carries no version".to_string())
}
async fn newest_release() -> Result<Release, String> {
let version = newest_version().await?;
Ok(Release {
tag: version.to_string(),
version,
})
}
pub(super) async fn ensure_installed() -> Result<(), String> {
if entry().is_some() {
return Ok(());
}
let version = newest_version().await?;
install(&version).await.map(|_| ())
}
async fn install(version: &Version) -> Result<PathBuf, String> {
let _installing = INSTALLING.lock().await;
if installed_version().await.as_ref() == Some(version)
&& let Some(entry) = entry()
{
return Ok(entry);
}
let dir = dir()?;
super::reclaim_scratch(&dir);
super::reclaim_aside(&dir);
let bun = crate::tools::bun::bun_binary_path()
.ok_or_else(|| "the product's managed bun runtime is not installed".to_string())?;
let work = super::scratch(&dir)?;
let args = vec![
"add".to_string(),
"--exact".to_string(),
format!("{PACKAGE}@{version}"),
];
let outcome = crate::tools::shell::run_internal_program_outcome(
work.path(),
&bun,
&args,
&[],
Some(super::DOWNLOAD_TIMEOUT),
)
.await;
if !outcome.success {
return Err(super::run_failure(
&outcome,
"installing the hyperframes package",
Some(super::DOWNLOAD_TIMEOUT),
));
}
let staged = work.path().join(NODE_MODULES);
if !staged.join(ENTRY).is_file() {
return Err(NO_ENTRY.to_string());
}
let _swap = managed_bin::swap_when_idle(&IN_USE).await;
managed_bin::place_staged_tree(&staged, &dir.join(NODE_MODULES))?;
entry().ok_or_else(|| NO_ENTRY.to_string())
}
pub(super) async fn refresh_on_start() {
managed_bin::install_on_start(
PACKAGE,
|| entry().is_some(),
start_probe,
newest_release,
async |release| {
let release = managed_bin::release_or_reason(release)?;
install(&release.version).await
},
managed_bin::WhenMissing::Skip,
)
.await;
}