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
use bytes::{BufMut, Bytes, BytesMut};

use std::sync::atomic::{AtomicBool, Ordering};

use crate::database::FdbDatabase;
use crate::error::{FdbError, FdbResult};
use crate::transaction::{FdbTransaction, ReadTransaction, Transaction, TransactionOption};
use crate::Tenant;

const TENANT_MAP_PREFIX: &[u8; 25] = b"\xFF\xFF/management/tenant_map/";

/// The FDB API includes function to manage the set of tenants in a
/// cluster.
#[derive(Debug)]
pub struct TenantManagement;

impl TenantManagement {
    /// Creates a new tenant in the cluster using a transaction
    /// created on the specified [`FdbDatabase`].
    pub async fn create_tenant_db(
        db: &FdbDatabase,
        tenant_name: impl Into<Tenant>,
    ) -> FdbResult<()> {
        let checked_existence = AtomicBool::new(false);
        let key = {
            let mut b = BytesMut::new();
            b.put(TENANT_MAP_PREFIX.as_ref());
            b.put(Into::<Bytes>::into(tenant_name.into()));
            Into::<Bytes>::into(b)
        };

        let checked_existence_ref = &checked_existence;
        let key_ref = &key;

        db.run(|tr| async move {
            unsafe {
                tr.set_option(TransactionOption::SpecialKeySpaceEnableWrites)?;
            }

            if checked_existence_ref.load(Ordering::SeqCst) {
                tr.set(key_ref.clone(), Bytes::new());
                Ok(())
            } else {
                let maybe_key = tr.get(key_ref.clone()).await?;

                checked_existence_ref.store(true, Ordering::SeqCst);

                match maybe_key {
                    None => {
                        tr.set(key_ref.clone(), Bytes::new());
                        Ok(())
                    }
                    Some(_) => {
                        // `tenant_already_exists` error
                        Err(FdbError::new(2132))
                    }
                }
            }
        })
        .await
    }

    /// Creates a new tenant in the cluster.
    pub fn create_tenant_tr(tr: &FdbTransaction, tenant_name: impl Into<Tenant>) -> FdbResult<()> {
        unsafe {
            tr.set_option(TransactionOption::SpecialKeySpaceEnableWrites)?;
        }

        tr.set(
            {
                let mut b = BytesMut::new();
                b.put(TENANT_MAP_PREFIX.as_ref());
                b.put(Into::<Bytes>::into(tenant_name.into()));
                Into::<Bytes>::into(b)
            },
            Bytes::new(),
        );

        Ok(())
    }

    /// Deletes a tenant from the cluster using a transaction created
    /// on the specified [`FdbDatabase`].
    pub async fn delete_tenant_db(
        db: &FdbDatabase,
        tenant_name: impl Into<Tenant>,
    ) -> FdbResult<()> {
        let checked_existence = AtomicBool::new(false);
        let key = {
            let mut b = BytesMut::new();
            b.put(TENANT_MAP_PREFIX.as_ref());
            b.put(Into::<Bytes>::into(tenant_name.into()));
            Into::<Bytes>::into(b)
        };

        let checked_existence_ref = &checked_existence;
        let key_ref = &key;

        db.run(|tr| async move {
            unsafe {
                tr.set_option(TransactionOption::SpecialKeySpaceEnableWrites)?;
            }

            if checked_existence_ref.load(Ordering::SeqCst) {
                tr.clear(key_ref.clone());
                Ok(())
            } else {
                let maybe_key = tr.get(key_ref.clone()).await?;

                checked_existence_ref.store(true, Ordering::SeqCst);

                match maybe_key {
                    None => {
                        // `tenant_not_found` error
                        Err(FdbError::new(2131))
                    }
                    Some(_) => {
                        tr.clear(key_ref.clone());
                        Ok(())
                    }
                }
            }
        })
        .await
    }

    /// Deletes a tenant from the cluster.
    pub fn delete_tenant_tr(tr: &FdbTransaction, tenant_name: impl Into<Tenant>) -> FdbResult<()> {
        unsafe {
            tr.set_option(TransactionOption::SpecialKeySpaceEnableWrites)?;
        }

        tr.clear({
            let mut b = BytesMut::new();
            b.put(TENANT_MAP_PREFIX.as_ref());
            b.put(Into::<Bytes>::into(tenant_name.into()));
            Into::<Bytes>::into(b)
        });

        Ok(())
    }
}