use crate::util::{now_secs, rfc3339};
use bytes::Bytes;
use krab_store::MemStore;
use serde_json::{Value, json};
use std::hash::{BuildHasher, Hasher};
use std::sync::atomic::{AtomicU64, Ordering};
pub const SOURCE_ANNOTATION: &str = "krab.io/source";
pub fn rand_u64() -> u64 {
static C: AtomicU64 = AtomicU64::new(0);
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(C.fetch_add(1, Ordering::Relaxed));
h.write_u128(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0),
);
h.finish()
}
pub fn new_uid() -> String {
let (a, b) = (rand_u64(), rand_u64());
format!(
"{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
a >> 32,
(a >> 16) & 0xffff,
a & 0xfff,
(b >> 48) & 0x3fff | 0x8000,
b & 0xffff_ffff_ffff
)
}
pub fn random_suffix(n: usize) -> String {
const ALPHA: &[u8] = b"bcdfghjklmnpqrstvwxz2456789";
let mut x = rand_u64();
(0..n)
.map(|_| {
let c = ALPHA[(x % ALPHA.len() as u64) as usize] as char;
x /= ALPHA.len() as u64;
c
})
.collect()
}
pub fn now_rfc3339() -> String {
rfc3339(now_secs())
}
pub fn store_key(plural: &str, ns: Option<&str>, name: &str) -> String {
match ns {
Some(ns) => format!("{plural}/{ns}/{name}"),
None => format!("{plural}/{name}"),
}
}
pub fn owner_ref(owner: &Value) -> Value {
json!({
"apiVersion": owner["apiVersion"],
"kind": owner["kind"],
"name": owner["metadata"]["name"],
"uid": owner["metadata"]["uid"],
"controller": true,
"blockOwnerDeletion": true
})
}
pub fn new_object(
api_version: &str,
kind: &str,
ns: Option<&str>,
name: &str,
owner: Option<&Value>,
) -> Value {
let mut meta = json!({"name": name, "uid": new_uid(), "creationTimestamp": now_rfc3339()});
if let Some(ns) = ns {
meta["namespace"] = json!(ns);
}
if let Some(o) = owner {
meta["ownerReferences"] = json!([owner_ref(o)]);
}
json!({"apiVersion": api_version, "kind": kind, "metadata": meta})
}
pub fn set_rv(obj: &mut Value, rev: u64) {
if let Some(m) = obj.get_mut("metadata").and_then(Value::as_object_mut) {
m.insert("resourceVersion".into(), json!(rev.to_string()));
}
}
pub fn to_bytes(obj: &Value) -> Bytes {
Bytes::from(serde_json::to_vec(obj).unwrap_or_default())
}
pub fn with_rv(obj: &Bytes, rev: u64) -> Bytes {
match serde_json::from_slice::<Value>(obj) {
Ok(mut v) => {
set_rv(&mut v, rev);
to_bytes(&v)
}
Err(_) => obj.clone(),
}
}
pub fn is_docker(obj: &Value) -> bool {
obj.pointer("/metadata/annotations")
.and_then(|a| a.get(SOURCE_ANNOTATION))
.and_then(Value::as_str)
== Some("docker")
}
pub fn is_docker_bytes(obj: &Bytes) -> bool {
serde_json::from_slice::<Value>(obj).is_ok_and(|v| is_docker(&v))
}
pub fn apply_defaults(kind: &str, obj: &mut Value) {
crate::defaults::apply(kind, obj);
}
pub fn create(store: &MemStore, key: &str, mut obj: Value) -> Option<Bytes> {
store
.put_checked(key, |cur, rev| {
if cur.is_some() {
return Err(());
}
set_rv(&mut obj, rev);
Ok(to_bytes(&obj))
})
.ok()
.map(|(_, b)| b)
}
pub fn update(store: &MemStore, key: &str, f: impl FnOnce(&mut Value)) -> Option<Bytes> {
store
.put_checked(key, |cur, rev| {
let mut v: Value = serde_json::from_slice(cur.ok_or(())?).map_err(|_| ())?;
let before = v.clone();
f(&mut v);
if v == before {
return Err(());
}
set_rv(&mut v, rev);
Ok(to_bytes(&v))
})
.ok()
.map(|(_, b)| b)
}
pub fn delete(store: &MemStore, key: &str) -> Option<Bytes> {
store
.delete_checked(key, |old, rev| Ok::<_, ()>(with_rv(old, rev)))
.ok()
.flatten()
.map(|(_, b)| b)
}
pub fn base64(data: &[u8]) -> String {
const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for c in data.chunks(3) {
let n = (c[0] as u32) << 16
| (*c.get(1).unwrap_or(&0) as u32) << 8
| *c.get(2).unwrap_or(&0) as u32;
out.push(T[(n >> 18) as usize & 63] as char);
out.push(T[(n >> 12) as usize & 63] as char);
out.push(if c.len() > 1 {
T[(n >> 6) as usize & 63] as char
} else {
'='
});
out.push(if c.len() > 2 {
T[n as usize & 63] as char
} else {
'='
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uid_and_suffix() {
let u = new_uid();
assert_eq!(u.len(), 36);
assert_ne!(u, new_uid());
assert_eq!(random_suffix(5).len(), 5);
}
#[test]
fn b64() {
assert_eq!(base64(b"hello"), "aGVsbG8=");
assert_eq!(base64(b"ab"), "YWI=");
assert_eq!(base64(b"abc"), "YWJj");
}
#[test]
fn create_update_delete() {
let s = MemStore::new(1 << 20, 16);
let o = new_object("v1", "ConfigMap", Some("d"), "x", None);
let k = store_key("configmaps", Some("d"), "x");
assert!(create(&s, &k, o.clone()).is_some());
assert!(create(&s, &k, o).is_none());
assert!(update(&s, &k, |v| v["data"] = json!({"a": "b"})).is_some());
assert!(update(&s, &k, |v| v["data"] = json!({"a": "b"})).is_none());
let d = delete(&s, &k).unwrap();
assert!(String::from_utf8_lossy(&d).contains(&format!("\"{}\"", s.rev())));
}
}