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
/// A replicated, versioned set of [`InstanceClass`]es
use std::fmt;

use async_trait::async_trait;
use futures::{TryFutureExt, TryStreamExt};

use tc_error::*;
use tc_scalar::Scalar;
use tc_state::object::InstanceClass;
use tc_state::State;
use tc_transact::fs;
use tc_transact::{Transact, Transaction, TxnId};
use tc_value::{Link, Version as VersionNumber};
use tcgeneric::{Id, Map};

use crate::txn::Txn;

use super::DirItem;

/// A version of a set of [`InstanceClass`]es
#[derive(Clone)]
pub struct Version {
    classes: tc_fs::File<(Link, Map<Scalar>)>,
}

impl Version {
    fn with_file(classes: tc_fs::File<(Link, Map<Scalar>)>) -> Self {
        Self { classes }
    }

    async fn to_state(&self, txn_id: TxnId) -> TCResult<State> {
        let mut classes = Map::new();

        let mut blocks = self.classes.iter(txn_id).await?;
        while let Some((block_id, class)) = blocks.try_next().await? {
            let (link, proto) = class.clone();

            classes.insert(
                (*block_id).clone(),
                State::Scalar(Scalar::Tuple(vec![link.into(), proto.into()].into())),
            );
        }

        Ok(State::Map(classes))
    }

    // TODO: there should be a way to return a reference to the block, not clone it
    pub async fn get_class(&self, txn_id: TxnId, name: &Id) -> TCResult<InstanceClass> {
        self.classes
            .read_block(txn_id, name)
            .map_ok(|block| InstanceClass::from(block.clone()))
            .await
    }
}

impl fmt::Debug for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a set of classes")
    }
}

/// A versioned set of [`InstanceClass`]es
#[derive(Clone)]
pub struct Class {
    dir: tc_fs::Dir,
}

impl Class {
    pub async fn latest(&self, txn_id: TxnId) -> TCResult<Option<VersionNumber>> {
        let file_names = self.dir.entry_names(txn_id).await?;

        let mut latest: Option<fs::Key> = None;
        for version in file_names {
            if let Some(prior) = latest.as_mut() {
                if &*version > &**prior {
                    *prior = version;
                }
            } else {
                latest = Some(version);
            }
        }

        if let Some(latest) = latest {
            let latest = latest.as_str().parse()?;
            Ok(Some(latest))
        } else {
            Ok(None)
        }
    }

    pub async fn get_version(&self, txn_id: TxnId, number: &VersionNumber) -> TCResult<Version> {
        self.dir
            .get_file(txn_id, &number.clone().into())
            .map_ok(|file| Version::with_file(file))
            .await
    }

    pub async fn to_state(&self, txn_id: TxnId) -> TCResult<State> {
        let mut versions = Map::new();
        for (number, file) in self.dir.files(txn_id).await? {
            let version = Version::with_file(file).to_state(txn_id).await?;
            versions.insert((*number).clone(), version);
        }

        Ok(State::Map(versions))
    }
}

#[async_trait]
impl DirItem for Class {
    type Schema = Map<InstanceClass>;
    type Version = Map<InstanceClass>;

    async fn create_version(
        &self,
        txn: &Txn,
        number: VersionNumber,
        schema: Map<InstanceClass>,
    ) -> TCResult<Map<InstanceClass>> {
        let txn_id = *txn.id();

        let blocks = self.dir.create_file(txn_id, number.into()).await?;

        for (name, class) in &schema {
            blocks
                .create_block(txn_id, name.clone(), class.clone().into_inner())
                .await?;
        }

        Ok(schema)
    }
}

#[async_trait]
impl Transact for Class {
    type Commit = ();

    async fn commit(&self, txn_id: TxnId) -> Self::Commit {
        self.dir.commit(txn_id, true).await
    }

    async fn rollback(&self, txn_id: &TxnId) {
        self.dir.rollback(*txn_id, true).await
    }

    async fn finalize(&self, txn_id: &TxnId) {
        self.dir.finalize(*txn_id).await
    }
}

#[async_trait]
impl fs::Persist<tc_fs::CacheBlock> for Class {
    type Txn = Txn;
    type Schema = ();

    async fn create(txn_id: TxnId, _schema: (), dir: tc_fs::Dir) -> TCResult<Self> {
        if dir.is_empty(txn_id).await? {
            Ok(Self { dir })
        } else {
            Err(bad_request!(
                "cannot create a new Class cluster with a non-empty directory",
            ))
        }
    }

    async fn load(_txn_id: TxnId, _schema: (), dir: tc_fs::Dir) -> TCResult<Self> {
        Ok(Self { dir })
    }

    fn dir(&self) -> tc_transact::fs::Inner<tc_fs::CacheBlock> {
        self.dir.clone().into_inner()
    }
}

impl fmt::Debug for Class {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a versioned set of classes")
    }
}