use bytes::Bytes;
use krab_store::{Event, MemStore};
use serde_json::{Map, Value, json};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::broadcast::{self, error::RecvError, error::TryRecvError};
pub const ALPHABET: &[u8] = b"bcdfghjklmnpqrstvwxz2456789";
const MAX_EVENTS: usize = 256;
pub fn now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
pub fn rfc3339(secs: i64) -> String {
let days = secs.div_euclid(86400);
let rem = secs.rem_euclid(86400);
let z = days + 719468;
let era = z.div_euclid(146097);
let doe = z.rem_euclid(146097);
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
y,
m,
d,
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
pub fn parse_rfc3339(s: &str) -> Option<i64> {
let b = s.as_bytes();
if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' {
return None;
}
let n = |r: std::ops::Range<usize>| s.get(r)?.parse::<i64>().ok();
let (y, m, d) = (n(0..4)?, n(5..7)?, n(8..10)?);
let (hh, mm, ss) = (n(11..13)?, n(14..16)?, n(17..19)?);
let y2 = if m <= 2 { y - 1 } else { y };
let era = y2.div_euclid(400);
let yoe = y2.rem_euclid(400);
let mp = if m > 2 { m - 3 } else { m + 9 };
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some((era * 146097 + doe - 719468) * 86400 + hh * 3600 + mm * 60 + ss)
}
pub fn now_rfc() -> String {
rfc3339(now_secs())
}
pub fn now_micro() -> String {
let d = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let s = rfc3339(d.as_secs() as i64);
format!("{}.{:06}Z", &s[..19], d.subsec_micros())
}
pub fn rand_u64() -> u64 {
static STATE: AtomicU64 = AtomicU64::new(0);
let seed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
let mut z = STATE
.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
.wrapping_add(seed);
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
pub fn rand_suffix(n: usize) -> String {
(0..n)
.map(|_| ALPHABET[(rand_u64() % ALPHABET.len() as u64) as usize] as char)
.collect()
}
pub fn new_uid() -> String {
let a = rand_u64();
let b = rand_u64();
let h = format!("{a:016x}{b:016x}");
format!(
"{}-{}-4{}-a{}-{}",
&h[0..8],
&h[8..12],
&h[13..16],
&h[17..20],
&h[20..32]
)
}
pub fn fnv32a(data: &[u8]) -> u32 {
let mut h: u32 = 0x811c_9dc5;
for b in data {
h ^= *b as u32;
h = h.wrapping_mul(0x0100_0193);
}
h
}
pub fn safe_encode(s: &str) -> String {
s.bytes()
.map(|b| ALPHABET[b as usize % ALPHABET.len()] as char)
.collect()
}
pub fn template_hash(template: &Value) -> String {
let data = serde_json::to_vec(template).unwrap_or_default();
safe_encode(&fnv32a(&data).to_string())
}
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() * 3 / 4);
let mut acc = 0u32;
let mut bits = 0;
for c in s.bytes() {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' | b'-' => 62,
b'/' | b'_' => 63,
b'=' | b'\n' | b'\r' | b' ' => continue,
_ => return None,
} as u32;
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
Some(out)
}
pub fn quantity(s: &str) -> Option<f64> {
let s = s.trim();
let split = s
.find(|c: char| c.is_ascii_alphabetic() && c != 'e' && c != 'E')
.unwrap_or(s.len());
let (num, suf) = s.split_at(split);
let n: f64 = num.parse().ok()?;
let mul = match suf {
"" => 1.0,
"n" => 1e-9,
"u" => 1e-6,
"m" => 1e-3,
"k" => 1e3,
"M" => 1e6,
"G" => 1e9,
"T" => 1e12,
"P" => 1e15,
"E" => 1e18,
"Ki" => 1024.0,
"Mi" => 1024.0 * 1024.0,
"Gi" => 1024.0 * 1024.0 * 1024.0,
"Ti" => 1024f64.powi(4),
"Pi" => 1024f64.powi(5),
"Ei" => 1024f64.powi(6),
_ => return None,
};
Some(n * mul)
}
pub fn int_or_percent(v: &Value, total: i64, round_up: bool, default: &str) -> i64 {
let v = if v.is_null() { &json!(default) } else { v };
if let Some(n) = v.as_i64() {
return n.max(0);
}
let s = v.as_str().unwrap_or("0");
match s.strip_suffix('%').and_then(|p| p.parse::<f64>().ok()) {
Some(p) => {
let x = p * total as f64 / 100.0;
(if round_up { x.ceil() } else { x.floor() }) as i64
}
None => s.parse().unwrap_or(0),
}
}
pub fn parse(b: &Bytes) -> Option<Value> {
serde_json::from_slice(b).ok()
}
pub fn get(store: &MemStore, key: &str) -> Option<Value> {
store.get(key).as_ref().and_then(parse)
}
pub fn list(store: &MemStore, prefix: &str) -> Vec<(String, Value)> {
store
.list(prefix)
.items
.into_iter()
.filter_map(|(k, v)| parse(&v).map(|v| (k.to_string(), v)))
.collect()
}
pub fn to_bytes(v: &Value, rev: u64) -> Bytes {
let mut v = v.clone();
v["metadata"]["resourceVersion"] = json!(rev.to_string());
Bytes::from(serde_json::to_vec(&v).unwrap_or_default())
}
pub fn create(store: &MemStore, key: &str, mut v: Value) -> Option<Value> {
if store.get(key).is_some() {
return None;
}
let m = &mut v["metadata"];
if m["uid"].as_str().is_none_or(str::is_empty) {
m["uid"] = json!(new_uid());
}
if m["creationTimestamp"].is_null() {
m["creationTimestamp"] = json!(now_rfc());
}
if m["generation"].is_null() && !key.starts_with("pods/") && !key.starts_with("events/") {
m["generation"] = json!(1);
}
let rev = store.put(key, |rev| to_bytes(&v, rev));
v["metadata"]["resourceVersion"] = json!(rev.to_string());
Some(v)
}
pub fn fix_object(v: &mut Value, ptr: &str) {
if let Some(x) = v.pointer_mut(ptr)
&& !x.is_null()
&& !x.is_object()
{
*x = json!({});
}
}
pub fn update(store: &MemStore, key: &str, mut f: impl FnMut(&mut Value) -> bool) -> Option<Value> {
for _ in 0..8 {
let cur = store.get(key)?;
let mut v = parse(&cur)?;
if !v.is_object() {
return None;
}
for p in [
"/metadata",
"/metadata/labels",
"/metadata/annotations",
"/spec",
"/status",
] {
fix_object(&mut v, p);
}
let spec_before = v["spec"].clone();
if !f(&mut v) {
return None;
}
if v["spec"] != spec_before && !key.starts_with("pods/") {
let g = v["metadata"]["generation"].as_i64().unwrap_or(1);
v["metadata"]["generation"] = json!(g + 1);
}
if store.get(key).as_ref() != Some(&cur) {
continue;
}
let rev = store.put(key, |rev| to_bytes(&v, rev));
v["metadata"]["resourceVersion"] = json!(rev.to_string());
return Some(v);
}
None
}
pub fn delete(store: &MemStore, key: &str) -> bool {
store
.delete(key, |rev, old| {
parse(old)
.map(|v| to_bytes(&v, rev))
.unwrap_or_else(|| old.clone())
})
.is_some()
}
pub fn delete_pod(store: &MemStore, key: &str) {
let Some(pod) = get(store, key) else { return };
if pod["spec"]["nodeName"].as_str().is_none_or(str::is_empty) {
delete(store, key);
return;
}
update(store, key, |p| {
if !p["metadata"]["deletionTimestamp"].is_null() {
return false;
}
let grace = p["spec"]["terminationGracePeriodSeconds"]
.as_i64()
.unwrap_or(30);
p["metadata"]["deletionTimestamp"] = json!(rfc3339(now_secs() + grace));
p["metadata"]["deletionGracePeriodSeconds"] = json!(grace);
true
});
}
pub fn s<'a>(v: &'a Value, ptr: &str) -> &'a str {
v.pointer(ptr).and_then(Value::as_str).unwrap_or("")
}
pub fn name(v: &Value) -> &str {
s(v, "/metadata/name")
}
pub fn ns(v: &Value) -> &str {
s(v, "/metadata/namespace")
}
pub fn uid(v: &Value) -> &str {
s(v, "/metadata/uid")
}
pub fn terminating(v: &Value) -> bool {
!v["metadata"]["deletionTimestamp"].is_null()
}
pub fn created(v: &Value) -> i64 {
parse_rfc3339(s(v, "/metadata/creationTimestamp")).unwrap_or(0)
}
pub fn controller_uid(v: &Value) -> Option<&str> {
v["metadata"]["ownerReferences"]
.as_array()?
.iter()
.find(|r| r["controller"].as_bool() == Some(true))
.and_then(|r| r["uid"].as_str())
}
pub fn controller_kind(v: &Value) -> Option<&str> {
v["metadata"]["ownerReferences"]
.as_array()?
.iter()
.find(|r| r["controller"].as_bool() == Some(true))
.and_then(|r| r["kind"].as_str())
}
pub fn owner_ref(api: &str, kind: &str, owner: &Value) -> Value {
json!({
"apiVersion": api,
"kind": kind,
"name": name(owner),
"uid": uid(owner),
"controller": true,
"blockOwnerDeletion": true
})
}
pub fn map_matches(sel: &Value, labels: &Value) -> bool {
match sel.as_object() {
None => true,
Some(m) => m
.iter()
.all(|(k, v)| labels.get(k).and_then(Value::as_str) == v.as_str()),
}
}
pub fn selector_matches(sel: &Value, labels: &Value) -> bool {
if !map_matches(&sel["matchLabels"], labels) {
return false;
}
let Some(exprs) = sel["matchExpressions"].as_array() else {
return true;
};
exprs.iter().all(|e| {
let val = labels.get(s(e, "/key")).and_then(Value::as_str);
let vals: Vec<&str> = e["values"]
.as_array()
.map(|a| a.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
match s(e, "/operator") {
"In" => val.is_some_and(|v| vals.contains(&v)),
"NotIn" => val.is_none_or(|v| !vals.contains(&v)),
"Exists" => val.is_some(),
"DoesNotExist" => val.is_none(),
_ => false,
}
})
}
pub fn pod_active(p: &Value) -> bool {
!terminating(p) && !matches!(s(p, "/status/phase"), "Succeeded" | "Failed")
}
pub fn condition<'a>(v: &'a Value, ty: &str) -> Option<&'a Value> {
v["status"]["conditions"]
.as_array()?
.iter()
.find(|c| c["type"].as_str() == Some(ty))
}
pub fn pod_ready(p: &Value) -> bool {
condition(p, "Ready").and_then(|c| c["status"].as_str()) == Some("True")
}
pub fn pod_available(p: &Value, min_ready: i64, now: i64) -> bool {
if !pod_ready(p) {
return false;
}
if min_ready <= 0 {
return true;
}
let since = condition(p, "Ready")
.and_then(|c| c["lastTransitionTime"].as_str())
.and_then(parse_rfc3339)
.unwrap_or(now);
since + min_ready <= now
}
pub fn set_condition(v: &mut Value, ty: &str, status: bool, reason: &str, msg: &str) -> bool {
let st = if status { "True" } else { "False" };
if !v["status"].is_object() {
v["status"] = json!({});
}
if !v["status"]["conditions"].is_array() {
v["status"]["conditions"] = json!([]);
}
let conds = v["status"]["conditions"].as_array_mut().unwrap();
let now = now_rfc();
if let Some(c) = conds.iter_mut().find(|c| c["type"].as_str() == Some(ty)) {
if c["status"].as_str() == Some(st)
&& c["reason"].as_str().unwrap_or("") == reason
&& c["message"].as_str().unwrap_or("") == msg
{
return false;
}
if c["status"].as_str() != Some(st) {
c["lastTransitionTime"] = json!(now);
}
c["status"] = json!(st);
set_opt(c, "reason", reason);
set_opt(c, "message", msg);
if c.get("lastUpdateTime").is_some() {
c["lastUpdateTime"] = json!(now);
}
return true;
}
let mut c = json!({"type": ty, "status": st, "lastTransitionTime": now});
set_opt(&mut c, "reason", reason);
set_opt(&mut c, "message", msg);
conds.push(c);
true
}
fn set_opt(c: &mut Value, k: &str, v: &str) {
match c.as_object_mut() {
Some(o) if v.is_empty() => {
o.remove(k);
}
Some(o) => {
o.insert(k.into(), json!(v));
}
None => {}
}
}
pub fn subscribe(store: &MemStore) -> broadcast::Receiver<Event> {
match store.watch("\u{10FFFF}", Some(store.rev())) {
Ok(w) => w.rx,
Err(_) => store.watch("\u{10FFFF}", None).ok().map(|w| w.rx).unwrap(),
}
}
pub async fn wait_event(rx: &mut broadcast::Receiver<Event>, prefixes: &[&str]) -> bool {
loop {
match rx.recv().await {
Ok(e) if prefixes.iter().any(|p| e.key.starts_with(p)) => return true,
Ok(_) => {}
Err(RecvError::Lagged(_)) => return true,
Err(RecvError::Closed) => return false,
}
}
}
pub fn drain(rx: &mut broadcast::Receiver<Event>) {
loop {
match rx.try_recv() {
Ok(_) | Err(TryRecvError::Lagged(_)) => {}
Err(_) => return,
}
}
}
pub async fn level_loop(
store: &MemStore,
prefixes: &[&str],
resync: Duration,
mut f: impl FnMut(),
) {
let mut rx = subscribe(store);
let mut tick = tokio::time::interval(resync);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
drain(&mut rx);
f();
tokio::select! {
_ = tick.tick() => {}
ok = wait_event(&mut rx, prefixes) => if !ok { return },
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
struct RecState {
keys: VecDeque<String>,
index: HashMap<String, String>,
}
pub struct Recorder {
component: &'static str,
state: Mutex<RecState>,
}
impl Default for Recorder {
fn default() -> Self {
Self::new("krab")
}
}
impl Recorder {
pub fn new(component: &'static str) -> Self {
Self {
component,
state: Mutex::new(RecState {
keys: VecDeque::new(),
index: HashMap::new(),
}),
}
}
pub fn event(&self, store: &MemStore, obj: &Value, reason: &str, msg: &str, warn: bool) {
let namespace = match ns(obj) {
"" => "default",
n => n,
};
let ident = format!("{}|{reason}|{msg}", uid(obj));
let now = now_rfc();
let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(key) = st.index.get(&ident).cloned() {
let bumped = update(store, &key, |e| {
let c = e["count"].as_i64().unwrap_or(1);
e["count"] = json!(c + 1);
e["lastTimestamp"] = json!(now);
true
});
if bumped.is_some() {
return;
}
st.index.remove(&ident);
}
let ev_name = format!("{}.{:016x}", name(obj), rand_u64());
let key = format!("events/{namespace}/{ev_name}");
let mut involved = Map::new();
for (k, p) in [
("apiVersion", "/apiVersion"),
("kind", "/kind"),
("name", "/metadata/name"),
("namespace", "/metadata/namespace"),
("uid", "/metadata/uid"),
("resourceVersion", "/metadata/resourceVersion"),
] {
let v = s(obj, p);
if !v.is_empty() {
involved.insert(k.into(), json!(v));
}
}
let ev = json!({
"apiVersion": "v1",
"kind": "Event",
"metadata": {"name": ev_name, "namespace": namespace, "uid": new_uid(), "creationTimestamp": now},
"involvedObject": involved,
"reason": reason,
"message": msg,
"type": if warn { "Warning" } else { "Normal" },
"source": {"component": self.component},
"firstTimestamp": now,
"lastTimestamp": now,
"count": 1,
"reportingComponent": self.component,
"reportingInstance": self.component
});
create(store, &key, ev);
st.keys.push_back(key.clone());
st.index.insert(ident, key);
while st.keys.len() > MAX_EVENTS {
if let Some(old) = st.keys.pop_front() {
delete(store, &old);
st.index.retain(|_, k| k != &old);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn update_survives_garbage_shapes() {
let st = MemStore::new(1 << 20, 16);
st.put("replicasets/d/r", |_| {
Bytes::from_static(br#"{"metadata":{"name":"r","annotations":"x","labels":[1]},"spec":"x","status":"x"}"#)
});
let v = update(&st, "replicasets/d/r", |r| {
r["status"]["replicas"] = json!(1);
r["spec"]["replicas"] = json!(1);
r["metadata"]["annotations"]["a"] = json!("b");
r["metadata"]["labels"]["l"] = json!("v");
true
})
.unwrap();
assert_eq!(v["status"]["replicas"], 1);
assert_eq!(v["metadata"]["annotations"]["a"], "b");
st.put("leases/n/x", |_| Bytes::from_static(b"[1]"));
assert!(update(&st, "leases/n/x", |_| true).is_none());
}
#[test]
fn helpers() {
assert_eq!(parse_rfc3339(&rfc3339(1_795_000_000)), Some(1_795_000_000));
assert_eq!(base64_decode("aGVsbG8=").unwrap(), b"hello");
assert_eq!(quantity("128Mi"), Some(134217728.0));
assert_eq!(quantity("500m"), Some(0.5));
assert_eq!(quantity("1e3"), Some(1000.0));
assert_eq!(int_or_percent(&Value::Null, 4, true, "25%"), 1);
assert_eq!(int_or_percent(&json!("50%"), 3, false, "25%"), 1);
assert_eq!(new_uid().len(), 36);
let sel = json!({"matchLabels": {"a": "1"}, "matchExpressions": [{"key": "b", "operator": "In", "values": ["x"]}]});
assert!(selector_matches(&sel, &json!({"a": "1", "b": "x"})));
assert!(!selector_matches(&sel, &json!({"a": "1"})));
}
#[test]
fn update_bumps_generation_and_rv() {
let st = MemStore::new(1 << 20, 16);
create(
&st,
"deployments/d/x",
json!({"metadata": {"name": "x"}, "spec": {"replicas": 1}}),
);
let v = update(&st, "deployments/d/x", |v| {
v["spec"]["replicas"] = json!(2);
true
})
.unwrap();
assert_eq!(v["metadata"]["generation"], 2);
assert_eq!(
get(&st, "deployments/d/x").unwrap()["metadata"]["resourceVersion"],
json!(st.rev().to_string())
);
assert!(update(&st, "deployments/d/x", |_| false).is_none());
}
}