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
use std::fmt::Display;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use ulid::Ulid;

type BaseTxnIdType = u128;

#[derive(
    Copy, Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize,
)]
pub struct ActivationId {
    txn_id: BaseTxnIdType,
    subtxn_id: Ulid,
}

impl ActivationId {
    pub fn new_for_txn(txn_id: BaseTxnIdType) -> Self {
        Self {
            txn_id,
            subtxn_id: Ulid::nil(),
        }
    }

    pub fn new_subtxn(parent_activation_id: &Self) -> Self {
        Self {
            txn_id: parent_activation_id.txn_id,
            subtxn_id: Ulid::new(),
        }
    }

    pub fn belongs_to_root(&self) -> bool {
        self.subtxn_id.is_nil()
    }

    pub fn txn_id(&self) -> BaseTxnIdType {
        self.txn_id
    }
}

impl Display for ActivationId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.subtxn_id.is_nil() {
            true => f.write_fmt(format_args!("{}.0", self.txn_id)),
            false => f.write_fmt(format_args!(
                "{}.{}",
                self.txn_id,
                self.subtxn_id.to_string()
            )),
        }
    }
}

impl FromStr for ActivationId {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.split_once('.') {
            Some((txn_id_str, subtxn_id_str)) => Ok(Self {
                txn_id: txn_id_str
                    .parse()
                    .expect("failed to convert txn id from str"),
                subtxn_id: match subtxn_id_str.len() == 1 {
                    true => Ulid::nil(),
                    false => Ulid::from_str(subtxn_id_str).expect("failed to parse subtxn id"),
                },
            }),
            None => Err(format!("invalid string for activation id {}", s)),
        }
    }
}