1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/* Copyright 2023 Architect Financial Technologies LLC. This is free
 * software released under the GNU Affero Public License version 3. */

pub mod admin_stats;
pub mod client;
pub mod config;
pub mod hcstr;
pub mod protocol;
pub mod symbology;
pub mod version;

use clap::crate_version;
use const_format::concatcp;

pub const GIT_VERSION: &'static str = version::GIT_VERSION;
pub const GIT_VERSION_SHORT: &'static str = version::GIT_VERSION_SHORT;
pub const CARGO_AND_GIT_VERSION: &'static str =
    concatcp!(crate_version!(), "-", GIT_VERSION_SHORT);

// CR estokes: move to netidx, eliminate lazy_static from netidx, and
// #![forbid(unsafe_code)] test if the performance is as good as
// lazy_static (it should be since once_cell is based on lazy_static)
/// static pooled objects to avoid allocation
///
/// pool(vis, name, type, capacity, max_elt_size)
///
/// Create a static memory pool. Objects are taken from the pool or
/// allocated normally if it is empty, when they are dropped instead
/// of being deallocated they are cleared and inserted into the pool,
/// up to capacity elements no more than max_elt_size may be stored in
/// the pool.
#[macro_export]
macro_rules! pool {
    ($vis:vis, $name:ident, $ty:ty, $max_capacity:expr, $max_elt_size:expr) => {
        $vis fn $name() -> &'static netidx::pool::Pool<$ty> {
            static POOL: once_cell::race::OnceBox<netidx::pool::Pool<$ty>> = once_cell::race::OnceBox::new();
            POOL.get_or_init(|| Box::new(netidx::pool::Pool::new($max_capacity, $max_elt_size)))
        }
    };
    ($name:ident, $ty:ty, $max_capacity:expr, $max_elt_size:expr) => {
        fn $name() -> &'static netidx::pool::Pool<$ty> {
            static POOL: once_cell::race::OnceBox<netidx::pool::Pool<$ty>> = once_cell::race::OnceBox::new();
            POOL.get_or_init(|| Box::new(netidx::pool::Pool::new($max_capacity, $max_elt_size)))
        }
    }
}

// CR estokes: move to netidx
/// Implement Into<Value> and FromValue using Pack
#[macro_export]
macro_rules! packed_value {
    ($name:ident) => {
        impl Into<netidx::protocol::value::Value> for $name {
            fn into(self) -> netidx::protocol::value::Value {
                // this will never fail
                netidx::protocol::value::Value::Bytes(
                    netidx::utils::pack(&self).unwrap().freeze(),
                )
            }
        }

        impl netidx::protocol::value::FromValue for $name {
            fn from_value(v: netidx::protocol::value::Value) -> anyhow::Result<Self> {
                match v {
                    netidx::protocol::value::Value::Bytes(mut b) => {
                        Ok(netidx::pack::Pack::decode(&mut b)?)
                    }
                    _ => anyhow::bail!("invalid value, expected a bytes {:?}", v),
                }
            }
        }
    };
}

/// Implement a named wrapper type around a UUID
#[macro_export]
macro_rules! uuid_val {
    ($name:ident) => {
        #[derive(
            Debug,
            Clone,
            Copy,
            Hash,
            PartialEq,
            Eq,
            PartialOrd,
            Ord,
            Serialize,
            Deserialize,
            Pack,
        )]
        pub struct $name(pub uuid::Uuid);

        packed_value!($name);

        impl Deref for $name {
            type Target = uuid::Uuid;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl Borrow<uuid::Uuid> for $name {
            fn borrow(&self) -> &uuid::Uuid {
                &self.0
            }
        }

        impl JsonSchema for $name {
            fn schema_name() -> String {
                format!("{}Id", stringify!($name)).to_string()
            }

            fn json_schema(gen: &mut SchemaGenerator) -> Schema {
                uuid::Uuid::json_schema(gen)
            }
        }
    };
}

/// A hashconsed string identifier
///
/// This will generate a hashconsed string indexed identifier that is
/// Copy, and has an in place size of one word. Equality, Comparison,
/// and Hashing are all operations on a single pointer. The original
/// string is recoverable as the name field. This is suitable for use
/// with any indentifier that comes from a reasonably sized limited
/// set, since the associated strings will never be deallocated it
/// must not be used for identifiers from large sets.
#[macro_export]
macro_rules! hcstrid {
    ($name:ident) => {
        paste::paste! {
            #[derive(Debug)]
            pub struct [< $name Inner >] {
                pub name: Str,
                pub id: uuid::Uuid,
            }

            #[derive(Debug, Clone, Copy)]
            pub struct $name(&'static [< $name Inner >]);

            static [<$name:upper S>]: once_cell::sync::Lazy<
                arc_swap::ArcSwap<immutable_chunkmap::map::MapM<Str, $name>>
            > =
                once_cell::sync::Lazy::new(|| {
                    let map = std::sync::Arc::new(immutable_chunkmap::map::MapM::new());
                    arc_swap::ArcSwap::new(map)
                });

            impl $name {
                pub fn get(name: &str) -> $name {
                    loop {
                        let current = [<$name:upper S>].load();
                        match current.get(name) {
                            Some(v) => break *v,
                            None => {
				let name = if name.as_bytes().len() > 255 {
				    let mut i = 255;
				    while !name.is_char_boundary(i) {
					i -= 1;
				    }
				    name.split_at(i).0
				} else {
				    name
				};
                                let name = Str::try_from(name).unwrap();
                                let ns = uuid::Uuid::from_bytes([
                                    177, 37, 16, 167, 166, 29, 72, 91, 172, 51, 244, 227, 105, 166, 160, 67,
                                ]);
                                let id = uuid::Uuid::new_v5(&ns, name.as_bytes());
                                let desk = $name(Box::leak(Box::new([<$name Inner>] { name, id })));
                                let (new, _) = current.insert(name, desk);
                                let new = std::sync::Arc::new(new);
                                let replaced = [<$name:upper S>].compare_and_swap(current, std::sync::Arc::clone(&new));
                                if std::sync::Arc::ptr_eq(&replaced, &new) {
                                    break desk
                                }
                            }
                        }
                    }
                }

                pub fn all() -> std::sync::Arc<immutable_chunkmap::map::MapM<Str, $name>> {
                    [<$name:upper S>].load_full()
                }
            }

            impl std::ops::Deref for $name {
                type Target = [<$name Inner>];

                fn deref(&self) -> &'static [<$name Inner>] {
                    self.0
                }
            }

            impl Symbolic for $name {
                type Id = uuid::Uuid;

                fn name(&self) -> Str {
                    self.0.name
                }

                fn id(&self) -> Self::Id {
                    self.0.id
                }

                fn is_valid(&self) -> bool {
                    true
                }
            }

            impl std::cmp::PartialEq for $name {
                fn eq(&self, lhs: &Self) -> bool {
                    (self.0 as *const [<$name Inner>]) == (lhs.0 as *const [<$name Inner>])
                }
            }

            impl std::cmp::Eq for $name {}

            // This will produce a total order, but not a
            // lexicographic one. For that use name
            impl std::cmp::PartialOrd for $name {
                fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
                    (self.0 as *const [<$name Inner>]).partial_cmp(&(other.0 as *const [<$name Inner>]))
                }
            }

            impl std::cmp::Ord for $name {
                fn cmp(&self, other: &Self) -> std::cmp::Ordering {
                    (self.0 as *const [<$name Inner>]).cmp(&(other.0 as *const [<$name Inner>]))
                }
            }

            impl std::hash::Hash for $name {
                fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                    (self.0 as *const [<$name Inner>]).hash(state)
                }
            }

            impl netidx::pack::Pack for $name {
                fn encoded_len(&self) -> usize {
                    let len = self.name.as_bytes().len();
                    netidx::pack::varint_len(len as u64) + len
                }

                fn encode(&self, buf: &mut impl bytes::BufMut) -> Result<(), netidx::pack::PackError> {
                    netidx::pack::encode_varint(self.name.as_bytes().len() as u64, buf);
                    Ok(buf.put_slice(self.name.as_bytes()))
                }

                fn decode(buf: &mut impl bytes::Buf) -> Result<Self, netidx::pack::PackError> {
                    let len = netidx::pack::decode_varint(buf)? as usize;
                    if len > buf.remaining() {
                        return Err(netidx::pack::PackError::TooBig)
                    }
                    thread_local! {
                        static NAME: std::cell::RefCell<bytes::BytesMut> =
                            std::cell::RefCell::new(bytes::BytesMut::new());
                    }
                    NAME.with(|name| {
                        let mut name = name.borrow_mut();
                        name.resize(len, 0);
                        buf.copy_to_slice(&mut name);
                        let s = match std::str::from_utf8(&*name) {
                            Ok(s) => s,
                            Err(_) => return Err(netidx::pack::PackError::InvalidFormat)
                        };
                        Ok($name::get(s))
                    })
                }
            }

            impl serde::Serialize for $name {
                fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
                where S: serde::Serializer,
                {
                    serializer.serialize_str(self.name.as_str())
                }
            }

            // CR-soon alee: use macro-fu to only impl this if asked, then architect-core can drop schemars
            impl JsonSchema for $name {
                fn schema_name() -> String {
                    stringify!($name).to_string()
                }

                fn json_schema(gen: &mut SchemaGenerator) -> Schema {
                    String::json_schema(gen)
                }
            }

            struct [<$name Visitor>];

            impl<'de> serde::de::Visitor<'de> for [<$name Visitor>] {
                type Value = $name;

                fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                    write!(f, "expecting a string")
                }

                fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
                where E: serde::de::Error
                {
                    Ok($name::get(v))
                }
            }

            impl<'de> serde::Deserialize<'de> for $name {
                fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>
                where D: serde::Deserializer<'de>,
                {
                    deserializer.deserialize_str([<$name Visitor>])
                }
            }
        }
    }
}

/// Parse a duration string into a `chrono::Duration`.
///
/// A valid duration string is an integer or float followed by a
/// suffix. Supported suffixes are,
///
/// - d: days float
/// - h: hours float
/// - m: minutes float
/// - s: seconds float
/// - ms: milliseconds int
/// - us: microseconds int
/// - ns: nanoseconds int
///
/// e.g. 27ns, 1.7d, 22.2233h, 47.3m, ...
pub fn parse_duration(s: &str) -> anyhow::Result<chrono::Duration> {
    use anyhow::anyhow;
    use chrono::Duration;

    if s.ends_with("ns") {
        let s = s.strip_suffix("ns").unwrap().trim();
        let n = s.parse::<i64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::nanoseconds(n))
    } else if s.ends_with("us") {
        let s = s.strip_suffix("us").unwrap().trim();
        let n = s.parse::<i64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::microseconds(n))
    } else if s.ends_with("ms") {
        let s = s.strip_suffix("ms").unwrap().trim();
        let n = s.parse::<i64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::milliseconds(n))
    } else if s.ends_with("s") {
        let s = s.strip_suffix("s").unwrap().trim();
        let f = s.parse::<f64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::nanoseconds((f * 1e9).trunc() as i64))
    } else if s.ends_with("m") {
        let s = s.strip_suffix("m").unwrap().trim();
        let f = s.parse::<f64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::nanoseconds((f * 60. * 1e9).trunc() as i64))
    } else if s.ends_with("h") {
        let s = s.strip_suffix("h").unwrap().trim();
        let f = s.parse::<f64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::nanoseconds((f * 3600. * 1e9).trunc() as i64))
    } else if s.ends_with("d") {
        let s = s.strip_suffix("d").unwrap().trim();
        let f = s.parse::<f64>().map_err(|e| anyhow!(e.to_string()))?;
        Ok(Duration::nanoseconds((f * 86400. * 1e9).trunc() as i64))
    } else {
        Err(anyhow!("expected a suffix ns, us, ms, s, m, h, d"))
    }
}

/// a serde visitor for `chrono::Duration`
pub struct DurationVisitor;

impl<'de> serde::de::Visitor<'de> for DurationVisitor {
    type Value = chrono::Duration;

    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "expecting a string")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        parse_duration(s).map_err(|e| E::custom(e.to_string()))
    }
}

/// A serde deserialize function for `chrono::Duration`
///
/// using `parse_duration`
pub fn deserialize_duration<'de, D>(d: D) -> Result<chrono::Duration, D::Error>
where
    D: serde::Deserializer<'de>,
{
    d.deserialize_str(DurationVisitor)
}

pub fn deserialize_duration_opt<'de, D>(
    d: D,
) -> Result<Option<chrono::Duration>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    let s = Option::<String>::deserialize(d)?;
    match s {
        Some(s) => Ok(Some(parse_duration(&s).map_err(serde::de::Error::custom)?)),
        None => Ok(None),
    }
}

/// A serde serializer function for `chrono::Duration`
///
/// that writes the duration as an f64 number of seconds followed by
/// the s suffix.
pub fn serialize_duration<S>(d: &chrono::Duration, s: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    let secs = d.num_milliseconds() as f64 / 1000.;
    s.serialize_str(&format!("{}s", secs))
}

pub fn serialize_duration_opt<S>(
    d: &Option<chrono::Duration>,
    s: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match d {
        Some(d) => {
            let secs = d.num_milliseconds() as f64 / 1000.;
            s.serialize_some(&format!("{}s", secs))
        }
        None => s.serialize_none(),
    }
}