#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
include!("../runtime/helix-db.rs");
use std::{
fs::{self, File},
io::{Read, Seek, SeekFrom},
path::Path,
};
use super::journal::private_options;
pub fn is_native(path: &Path) -> bool {
path.extension().is_some_and(|ext| ext == "hxdb")
}
fn access_lock(path: &Path, write: bool) -> Result<File, String> {
let mut name = path.as_os_str().to_owned();
name.push(".io.lock");
let file = if !write && Path::new(&name).exists() {
File::open(name)
} else {
private_options()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(name)
}
.map_err(|e| e.to_string())?;
if write {
file.lock().map_err(|e| e.to_string())?;
} else {
file.lock_shared().map_err(|e| e.to_string())?;
}
Ok(file)
}
fn key(offset: u64) -> String {
format!("event:{offset:016x}")
}
fn decode(records: &str) -> Result<String, String> {
let mut events = String::with_capacity(records.len());
let mut offset = 0u64;
for line in records.split_inclusive('\n') {
let error = || format!("invalid Helix DB event at byte {offset}; restore a verified copy");
let row = line.strip_suffix('\n').ok_or_else(error)?;
let (stored_key, rest) = row.split_once("\tV\t").ok_or_else(error)?;
let (sum, escaped) = rest.split_once(':').ok_or_else(error)?;
let event = db_unesc(escaped);
if stored_key != key(offset)
|| sum != format!("{:016x}", db_fnv(&event))
|| db_esc(&event) != escaped
|| event.contains('\n')
{
return Err(error());
}
events.push_str(&event);
events.push('\n');
offset += line.len() as u64;
}
Ok(events)
}
pub fn read(path: &Path) -> Result<String, String> {
if !path.try_exists().map_err(|e| e.to_string())? {
return Ok(String::new());
}
let _lock = access_lock(path, false)?;
let records =
fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
decode(&records)
}
fn put(file: &mut File, path: &Path, event: &str) -> Result<(), String> {
let offset = file.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
let id = key(offset);
db_putv(
path.to_str().ok_or("Helix DB requires a UTF-8 path")?,
&id,
event,
);
let expected = format!("{id}\tV\t{:016x}:{}\n", db_fnv(event), db_esc(event));
let mut actual = String::new();
file.read_to_string(&mut actual)
.map_err(|e| e.to_string())?;
if expected != actual {
return Err(format!(
"Helix DB write verification failed at byte {offset}"
));
}
Ok(())
}
pub fn append(path: &Path, event: &str) -> Result<(), String> {
append_many(path, &[event])
}
pub fn append_many(path: &Path, events: &[&str]) -> Result<(), String> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
let _lock = access_lock(path, true)?;
let mut file = private_options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.map_err(|e| e.to_string())?;
if file.metadata().map_err(|e| e.to_string())?.len() > 0 {
file.seek(SeekFrom::End(-1)).map_err(|e| e.to_string())?;
let mut last = [0u8];
file.read_exact(&mut last).map_err(|e| e.to_string())?;
if last != [b'\n'] {
return Err("incomplete final Helix DB record; restore a verified copy".into());
}
}
for event in events {
put(&mut file, path, event)?;
}
file.sync_data().map_err(|e| e.to_string())
}
pub fn import(path: &Path, events: &str) -> Result<usize, String> {
if !is_native(path) {
return Err("migration destination must end in .hxdb".into());
}
if let Some(dir) = path.parent() {
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
let _lock = access_lock(path, true)?;
if path.try_exists().map_err(|e| e.to_string())? {
return Err("migration destination already exists".into());
}
let mut staging_name = path.as_os_str().to_owned();
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_nanos();
staging_name.push(format!(".import-{}-{nonce}", std::process::id()));
let staging = std::path::PathBuf::from(staging_name);
let mut file = private_options()
.read(true)
.write(true)
.create_new(true)
.open(&staging)
.map_err(|e| e.to_string())?;
let result = (
|| -> Result<usize, String> {
let mut normalized = String::new();
let mut count = 0;
for event in events.lines().filter(|s| !s.trim().is_empty()) {
if super::parse_json(event)?
.get("kind")
.and_then(super::Json::as_str)
.is_none()
{
return Err("expected a bank event with a string kind".into());
}
put(&mut file, &staging, event)?;
normalized.push_str(event);
normalized.push('\n');
count += 1;
}
file.sync_all().map_err(|e| e.to_string())?;
let stored = fs::read_to_string(&staging).map_err(|e| e.to_string())?;
if decode(&stored)? != normalized {
return Err("Helix DB import replay differs from source".into());
}
fs::hard_link(&staging, path)
.map_err(|e| format!("cannot publish new Helix DB: {e}"))?;
Ok(count)
}
)();
drop(file);
let _ = fs::remove_file(staging);
result
}
pub fn cue_similarity(query: &[String], cue: &str) -> f64 {
let words = super::tokens(cue);
if query.len() < 2 || query.len() != words.len() {
return 0.0;
}
for (a, b) in query.iter().zip(&words) {
if a != b
&& (a.chars().count().min(b.chars().count()) < 4
|| a.chars().next() != b.chars().next()
|| a.chars().count().abs_diff(b.chars().count()) > 1
|| db_sim(&db_trigrams(a), &db_trigrams(b)) < 0.35)
{
return 0.0;
}
}
db_sim(
&db_trigrams(&query.join(" ")),
&db_trigrams(&words.join(" ")),
)
}