use core::time::Duration;
use std::sync::Arc;
use async_graphql::{Context, Enum, Error, Object, Result, SimpleObject};
use crate::drive::{
DynRegistry, Registries, RegistryCounts as FamilyCounts, RegistryOptions, RegistryOverride,
RetireOrigin, RootState,
};
#[cfg(test)]
mod tests;
const DEFAULT_RECENT: usize = 20;
#[inline]
fn recent_limit(n: Option<i32>) -> usize {
n.map_or(DEFAULT_RECENT, |n| {
usize::try_from(n.max(0)).unwrap_or(usize::MAX)
})
}
#[inline]
fn wire_count(n: usize) -> u32 {
u32::try_from(n).unwrap_or(u32::MAX)
}
fn parse_duration(field: &str, text: &str) -> Result<Duration> {
humantime::parse_duration(text)
.map_err(|error| Error::new(format!("{field}: not a duration: {text:?} ({error})")))
}
fn format_duration(duration: Duration) -> String {
humantime::format_duration(duration).to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)]
#[graphql(rename_items = "lowercase")]
pub enum RegistryState {
Idle,
Analyzing,
Retiring,
Retired,
Restoring,
}
impl From<RootState> for RegistryState {
fn from(state: RootState) -> Self {
match state {
RootState::Idle => Self::Idle,
RootState::Analyzing { .. } => Self::Analyzing,
RootState::Retiring { .. } => Self::Retiring,
RootState::Retired { .. } => Self::Retired,
RootState::Restoring => Self::Restoring,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Enum)]
#[graphql(rename_items = "lowercase")]
pub enum RegistryOrigin {
Vanished,
User,
}
impl From<RegistryOrigin> for RetireOrigin {
fn from(origin: RegistryOrigin) -> Self {
match origin {
RegistryOrigin::Vanished => Self::Vanished,
RegistryOrigin::User => Self::User,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, SimpleObject)]
#[graphql(name = "RegistryCounts")]
pub struct RegistryCountsView {
pub idle: u32,
pub analyzing: u32,
pub retiring: u32,
pub retired: u32,
}
impl From<FamilyCounts> for RegistryCountsView {
fn from(counts: FamilyCounts) -> Self {
Self {
idle: 0,
analyzing: wire_count(counts.analyzing),
retiring: wire_count(counts.retiring),
retired: wire_count(counts.retired),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, SimpleObject)]
pub struct RegistryEntry {
pub key: String,
pub state: RegistryState,
}
#[derive(Debug, Clone, PartialEq, Eq, SimpleObject)]
pub struct RegistryOptionsView {
pub debounce: String,
pub batch_max_items: u32,
pub batch_max_wait: String,
pub retire_drain: String,
pub settle: String,
}
impl From<RegistryOptions> for RegistryOptionsView {
fn from(options: RegistryOptions) -> Self {
Self {
debounce: format_duration(options.debounce()),
batch_max_items: wire_count(options.batch_max_items().get()),
batch_max_wait: format_duration(options.batch_max_wait()),
retire_drain: format_duration(options.retire_drain()),
settle: format_duration(options.settle()),
}
}
}
pub struct RegistryFamily {
dyn_registry: Option<Arc<dyn DynRegistry>>,
}
#[Object]
impl RegistryFamily {
async fn state(&self, key: String) -> RegistryState {
self
.dyn_registry
.as_ref()
.map_or(RootState::Idle, |registry| registry.state(&key))
.into()
}
async fn inflight(&self, key: String) -> u32 {
self
.dyn_registry
.as_ref()
.map_or(0, |registry| registry.state(&key).inflight())
}
async fn counts(&self) -> RegistryCountsView {
self
.dyn_registry
.as_ref()
.map(|registry| registry.counts())
.unwrap_or_default()
.into()
}
async fn recent(&self, n: Option<i32>) -> Vec<RegistryEntry> {
self
.dyn_registry
.as_ref()
.map(|registry| registry.recent(recent_limit(n)))
.unwrap_or_default()
.into_iter()
.map(|(key, state)| RegistryEntry {
key: key.to_string(),
state: state.into(),
})
.collect()
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RegistryQueryRoot;
#[Object]
impl RegistryQueryRoot {
#[cfg_attr(
doc,
doc = "The registry face for `family` — the lowercase spelling of a root type, `media` for \
`MediaId`."
)]
#[cfg_attr(doc, doc = "")]
#[cfg_attr(
doc,
doc = "Total: an unrecognised family answers a live object whose fields all read the honest"
)]
#[cfg_attr(doc, doc = "nothing rather than a refusal — see the module note.")]
async fn registry(&self, ctx: &Context<'_>, family: String) -> Result<RegistryFamily> {
let registries = ctx.data::<Arc<Registries>>()?;
Ok(RegistryFamily {
dyn_registry: registries.dyn_for(&family),
})
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RegistryMutationRoot;
impl RegistryMutationRoot {
fn dyn_for(ctx: &Context<'_>, family: &str) -> Result<Arc<dyn DynRegistry>> {
let registries = ctx.data::<Arc<Registries>>()?;
registries.dyn_for(family).ok_or_else(|| {
Error::new(format!(
"no family named {family:?} has been exposed to the registry face"
))
})
}
}
#[Object(name = "Mutation")]
impl RegistryMutationRoot {
#[expect(
clippy::too_many_arguments,
reason = "one argument per knob, and there are five of them"
)]
async fn registry_knobs(
&self,
ctx: &Context<'_>,
family: String,
debounce: Option<String>,
batch_max_items: Option<u32>,
batch_max_wait: Option<String>,
retire_drain: Option<String>,
settle: Option<String>,
) -> Result<RegistryOptionsView> {
let registry = Self::dyn_for(ctx, &family)?;
let mut over = RegistryOverride::new();
if let Some(text) = debounce {
over.set_debounce(Some(parse_duration("debounce", &text)?));
}
if let Some(items) = batch_max_items {
let items = core::num::NonZeroUsize::new(items as usize)
.ok_or_else(|| Error::new("batchMaxItems: must not be 0"))?;
over.set_batch_max_items(Some(items));
}
if let Some(text) = batch_max_wait {
over.set_batch_max_wait(Some(parse_duration("batchMaxWait", &text)?));
}
if let Some(text) = retire_drain {
over.set_retire_drain(Some(parse_duration("retireDrain", &text)?));
}
if let Some(text) = settle {
over.set_settle(Some(parse_duration("settle", &text)?));
}
registry.apply_knobs(&over);
Ok(registry.options().into())
}
async fn retire(
&self,
ctx: &Context<'_>,
family: String,
key: String,
origin: RegistryOrigin,
) -> Result<RegistryState> {
let registry = Self::dyn_for(ctx, &family)?;
registry
.retire(&key, origin.into())
.map(RegistryState::from)
.map_err(|_| {
Error::new(format!(
"key {key:?} is not a valid id for family {family:?}"
))
})
}
async fn restore(&self, ctx: &Context<'_>, family: String, key: String) -> Result<RegistryState> {
let registry = Self::dyn_for(ctx, &family)?;
registry
.restore(&key)
.map(RegistryState::from)
.map_err(|_| {
Error::new(format!(
"key {key:?} is not a valid id for family {family:?}"
))
})
}
async fn reanalyze(
&self,
ctx: &Context<'_>,
family: String,
key: String,
) -> Result<RegistryState> {
let registry = Self::dyn_for(ctx, &family)?;
registry
.reanalyze(&key)
.map(RegistryState::from)
.map_err(|_| {
Error::new(format!(
"key {key:?} is not a valid id for family {family:?}"
))
})
}
}