use crate::registry::{Client, Grade};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const DIR: &str = "offers";
const OPEN: &str = "open";
const HELD: &str = "held";
const DECLINED: &str = "declined";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Record {
pub name: String,
pub workspace: String,
pub grade: Grade,
pub code: String,
pub expires: i64,
pub word: Option<String>,
pub claimed: Option<i64>,
pub declined: bool,
}
impl Record {
fn encode(&self) -> String {
json!({
"name": self.name, "workspace": self.workspace, "grade": self.grade.word(),
"code": self.code, "expires": self.expires, "word": self.word,
"claimed": self.claimed, DECLINED: self.declined,
})
.to_string()
}
fn decode(text: &str) -> Option<Self> {
let v: Value = serde_json::from_str(text).ok()?;
let text_of = |key: &str| v.get(key).and_then(Value::as_str).map(str::to_owned);
Some(Self {
name: text_of("name")?,
workspace: text_of("workspace")?,
grade: Grade::of(&text_of("grade")?)?,
code: text_of("code")?,
expires: v.get("expires")?.as_i64()?,
word: text_of("word"),
claimed: v.get("claimed").and_then(Value::as_i64),
declined: v.get(DECLINED).and_then(Value::as_bool).unwrap_or(false),
})
}
}
fn half(state_root: &Path, half: &str) -> PathBuf {
state_root.join(DIR).join(half)
}
fn write(dir: &Path, record: &Record) -> Result<(), String> {
let path = dir.join(&record.name);
std::fs::create_dir_all(dir)
.and_then(|()| std::fs::write(&path, record.encode()))
.map_err(|e| format!("{}: {e}", path.display()))
}
fn read_all(dir: &Path) -> Vec<Record> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut records: Vec<Record> = entries
.flatten()
.filter_map(|entry| Record::decode(&std::fs::read_to_string(entry.path()).ok()?))
.collect();
records.sort_by(|a, b| a.name.cmp(&b.name));
records
}
pub fn mint(state_root: &Path, record: &Record) -> Result<(), String> {
write(&half(state_root, OPEN), record)
}
fn open(state_root: &Path, now: i64) -> Vec<Record> {
let dir = half(state_root, OPEN);
let mut live = Vec::new();
for record in read_all(&dir) {
if record.expires > now {
live.push(record);
} else {
let _ = std::fs::remove_file(dir.join(&record.name));
}
}
live
}
pub fn pending(state_root: &Path, now: i64) -> Vec<Record> {
let mut live = open(state_root, now);
live.extend(
read_all(&half(state_root, HELD))
.into_iter()
.filter(|record| !record.declined),
);
live
}
pub fn take(state_root: &Path, code: &str, now: i64) -> Option<Record> {
let record = open(state_root, now)
.into_iter()
.find(|record| record.code == code)?;
let held = half(state_root, HELD);
std::fs::create_dir_all(&held).ok()?;
std::fs::rename(
half(state_root, OPEN).join(&record.name),
held.join(&record.name),
)
.ok()?;
Some(record)
}
pub fn restore(state_root: &Path, record: &Record) {
let _ = std::fs::rename(
half(state_root, HELD).join(&record.name),
half(state_root, OPEN).join(&record.name),
);
}
pub fn settle(state_root: &Path, record: &Record) -> Result<(), String> {
write(&half(state_root, HELD), record)
}
pub fn remove(state_root: &Path, name: &str) {
for dir in [OPEN, HELD] {
let _ = std::fs::remove_file(half(state_root, dir).join(name));
}
}
pub fn held(state_root: &Path, client: &Client) -> bool {
half(state_root, HELD).join(client.name()).is_file()
}
pub fn refusal(client: &Client) -> String {
format!(
"{name} holds a certificate issued by an offer no operator has approved, so nothing it \
says is answered yet: show its confirmation word to an operator, who approves it from \
a seat with /approve {name}",
name = client.name()
)
}