use dhat::{HeapStats, Profiler};
use osproxy_core::cursor::{self, CursorSigner};
use osproxy_core::{ClusterId, ErrorCode, PartitionId, RequestId, TraceContext};
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn allocs(f: impl FnOnce()) -> u64 {
let before = HeapStats::get().total_blocks;
f();
HeapStats::get().total_blocks - before
}
struct StubSigner;
impl CursorSigner for StubSigner {
fn tag(&self, _msg: &[u8]) -> Vec<u8> {
vec![0xab; 32]
}
}
#[test]
fn core_allocation_budgets() {
if std::env::var_os("LLVM_PROFILE_FILE").is_some() {
return;
}
let _profiler = Profiler::builder().testing().build();
let before = HeapStats::get().total_blocks;
let _ = std::hint::black_box(ErrorCode::StaleEpoch.as_slug());
assert_eq!(
HeapStats::get().total_blocks,
before,
"as_slug must not allocate"
);
let before = HeapStats::get().total_blocks;
let id = std::hint::black_box(PartitionId::from("tenant-42"));
assert_eq!(
HeapStats::get().total_blocks - before,
1,
"PartitionId::from should allocate exactly once"
);
assert_eq!(id.as_str(), "tenant-42");
let cluster = ClusterId::from("eu-west-1");
let cursor_id = "c2NhbjsxOzEyMzQ1Njc4OTA";
let n = allocs(|| {
let _ = std::hint::black_box(cursor::wrap(&StubSigner, &cluster, cursor_id));
});
assert_eq!(n, CURSOR_WRAP_ALLOCS, "cursor::wrap allocation budget");
let token = cursor::wrap(&StubSigner, &cluster, cursor_id);
let n = allocs(|| {
let _ = std::hint::black_box(cursor::unwrap(&StubSigner, &token));
});
assert_eq!(n, CURSOR_UNWRAP_ALLOCS, "cursor::unwrap allocation budget");
let n = allocs(|| {
let _ = std::hint::black_box(TraceContext::parse(
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
));
});
assert_eq!(n, 0, "TraceContext::parse must not allocate");
let rid = RequestId::from("req-1");
let n = allocs(|| {
let _ = std::hint::black_box(TraceContext::propagate(
Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"),
None,
&rid,
));
});
assert_eq!(
n, 0,
"TraceContext::propagate (no tracestate) must not allocate"
);
}
const CURSOR_WRAP_ALLOCS: u64 = 3;
const CURSOR_UNWRAP_ALLOCS: u64 = 4;