Skip to main content

anda_engine/
lib.rs

1use anda_core::Json;
2use candid::Principal;
3use chrono::prelude::*;
4use rand::Rng;
5
6pub mod context;
7pub mod engine;
8pub mod extension;
9pub mod hook;
10pub mod management;
11pub mod memory;
12pub mod model;
13pub mod store;
14
15/// Gets current unix timestamp in milliseconds
16pub use structured_logger::unix_ms;
17
18/// Generates N random bytes
19pub use ic_cose::rand_bytes;
20
21/// This is used to represent unauthenticated or anonymous users in the system.
22pub const ANONYMOUS: Principal = Principal::anonymous();
23
24pub static APP_USER_AGENT: &str = concat!(
25    "Mozilla/5.0 anda.bot ",
26    env!("CARGO_PKG_NAME"),
27    "/",
28    env!("CARGO_PKG_VERSION"),
29);
30
31/// Generates a random number within the given range
32pub fn rand_number<T, R>(range: R) -> T
33where
34    T: rand::distr::uniform::SampleUniform,
35    R: rand::distr::uniform::SampleRange<T>,
36{
37    let mut rng = rand::rng();
38    rng.random_range(range)
39}
40
41/// Gets the current RFC 3339 datetime string
42pub fn rfc3339_datetime_now() -> String {
43    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
44}
45
46/// Gets the RFC 3339 datetime string for the given timestamp in milliseconds
47pub fn rfc3339_datetime(now_ms: u64) -> Option<String> {
48    let datetime = DateTime::<Utc>::from_timestamp_millis(now_ms as i64);
49    datetime.map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
50}
51
52/// Sets the Unix timestamp in milliseconds for each JSON object in the vector.
53pub fn json_set_unix_ms_timestamp(mut vals: Vec<Json>, timestamp_ms: u64) -> Vec<Json> {
54    for val in vals.iter_mut() {
55        if let Some(obj) = val.as_object_mut() {
56            obj.insert("timestamp".into(), timestamp_ms.into());
57        }
58    }
59    vals
60}
61
62/// Converts the Unix timestamp in milliseconds to RFC 3339 format for each JSON object in the vector.
63pub fn json_convert_rfc3339_timestamp(mut vals: Vec<Json>) -> Vec<Json> {
64    for val in vals.iter_mut() {
65        if let Some(obj) = val.as_object_mut()
66            && let Some(timestamp_ms) = obj.get("timestamp").and_then(Json::as_u64)
67        {
68            obj.insert("timestamp".into(), rfc3339_datetime(timestamp_ms).into());
69        }
70    }
71    vals
72}