use super::{SeededUlidGenerator, Ulid, UlidEntropyError, pseudo};
use crate::Principal;
use ic_platform_protocol::raw_rand;
use ic_platform_runtime::{
call::{Call, Outcome, Wait},
system,
};
async fn fresh_suffix() -> Result<[u8; 10], UlidEntropyError> {
let call = Call::new(
Principal::management_canister(),
raw_rand::METHOD,
Wait::Bounded { seconds: 10 },
)
.args(raw_rand::encode(6).map_err(|_| UlidEntropyError::InvalidFrame)?)
.execute()
.await
.map_err(|_| UlidEntropyError::Unavailable)?;
let Outcome::Reply(reply) = call.into_parts().0 else {
return Err(UlidEntropyError::Unavailable);
};
let bytes = raw_rand::decode(&reply, 42).map_err(|_| UlidEntropyError::InvalidFrame)?;
Ok(std::array::from_fn(|i| bytes[i]))
}
fn identity() -> (Principal, u64) {
(system::canister_self(), system::canister_version())
}
impl SeededUlidGenerator {
pub fn next_id(&mut self) -> Ulid {
self.at(system::time())
}
}
impl Ulid {
#[must_use]
pub fn generate_prand() -> Self {
pseudo::generate(system::time(), identity)
}
pub async fn generator() -> Result<SeededUlidGenerator, UlidEntropyError> {
Ok(SeededUlidGenerator::new(fresh_suffix().await?))
}
#[must_use]
pub fn generator_prand() -> SeededUlidGenerator {
pseudo::owned(identity())
}
}