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
use crate::server::{
    AddVersionResult, GetVersionResult, HistorySegment, Server, VersionId, NO_VERSION_ID,
};
use crate::storage::sqlite::StoredUuid;
use anyhow::Context;
use rusqlite::params;
use rusqlite::OptionalExtension;
use serde::{Deserialize, Serialize};
use std::path::Path;
use uuid::Uuid;

#[derive(Serialize, Deserialize, Debug)]
struct Version {
    version_id: VersionId,
    parent_version_id: VersionId,
    history_segment: HistorySegment,
}

pub struct LocalServer {
    con: rusqlite::Connection,
}

impl LocalServer {
    fn txn(&mut self) -> anyhow::Result<rusqlite::Transaction> {
        let txn = self.con.transaction()?;
        Ok(txn)
    }

    /// A server which has no notion of clients, signatures, encryption, etc.
    pub fn new<P: AsRef<Path>>(directory: P) -> anyhow::Result<LocalServer> {
        let db_file = directory
            .as_ref()
            .join("taskchampion-local-sync-server.sqlite3");
        let con = rusqlite::Connection::open(&db_file)?;

        let queries = vec![
            "CREATE TABLE IF NOT EXISTS data (key STRING PRIMARY KEY, value STRING);",
            "CREATE TABLE IF NOT EXISTS versions (version_id STRING PRIMARY KEY, parent_version_id STRING, data STRING);",
        ];
        for q in queries {
            con.execute(q, []).context("Creating table")?;
        }

        Ok(LocalServer { con })
    }

    fn get_latest_version_id(&mut self) -> anyhow::Result<VersionId> {
        let t = self.txn()?;
        let result: Option<StoredUuid> = t
            .query_row(
                "SELECT value FROM data WHERE key = 'latest_version_id' LIMIT 1",
                rusqlite::params![],
                |r| r.get(0),
            )
            .optional()?;
        Ok(result.map(|x| x.0).unwrap_or(NO_VERSION_ID))
    }

    fn set_latest_version_id(&mut self, version_id: VersionId) -> anyhow::Result<()> {
        let t = self.txn()?;
        t.execute(
            "INSERT OR REPLACE INTO data (key, value) VALUES ('latest_version_id', ?)",
            params![&StoredUuid(version_id)],
        )
        .context("Update task query")?;
        t.commit()?;
        Ok(())
    }

    fn get_version_by_parent_version_id(
        &mut self,
        parent_version_id: VersionId,
    ) -> anyhow::Result<Option<Version>> {
        let t = self.txn()?;
        let r = t.query_row(
            "SELECT version_id, parent_version_id, data FROM versions WHERE parent_version_id = ?",
            params![&StoredUuid(parent_version_id)],
            |r| {
                let version_id: StoredUuid = r.get("version_id")?;
                let parent_version_id: StoredUuid = r.get("parent_version_id")?;

                Ok(Version{
                version_id: version_id.0,
                parent_version_id: parent_version_id.0,
                history_segment: r.get("data")?,
            })}
            )
        .optional()
        .context("Get version query")
        ?;
        Ok(r)
    }

    fn add_version_by_parent_version_id(&mut self, version: Version) -> anyhow::Result<()> {
        let t = self.txn()?;
        t.execute(
            "INSERT INTO versions (version_id, parent_version_id, data) VALUES (?, ?, ?)",
            params![
                StoredUuid(version.version_id),
                StoredUuid(version.parent_version_id),
                version.history_segment
            ],
        )?;
        t.commit()?;
        Ok(())
    }
}

impl Server for LocalServer {
    // TODO: better transaction isolation for add_version (gets and sets should be in the same
    // transaction)

    /// Add a new version.  If the given version number is incorrect, this responds with the
    /// appropriate version and expects the caller to try again.
    fn add_version(
        &mut self,
        parent_version_id: VersionId,
        history_segment: HistorySegment,
    ) -> anyhow::Result<AddVersionResult> {
        // no client lookup
        // no signature validation

        // check the parent_version_id for linearity
        let latest_version_id = self.get_latest_version_id()?;
        if latest_version_id != NO_VERSION_ID && parent_version_id != latest_version_id {
            return Ok(AddVersionResult::ExpectedParentVersion(latest_version_id));
        }

        // invent a new ID for this version
        let version_id = Uuid::new_v4();

        self.add_version_by_parent_version_id(Version {
            version_id,
            parent_version_id,
            history_segment,
        })?;
        self.set_latest_version_id(version_id)?;

        Ok(AddVersionResult::Ok(version_id))
    }

    /// Get a vector of all versions after `since_version`
    fn get_child_version(
        &mut self,
        parent_version_id: VersionId,
    ) -> anyhow::Result<GetVersionResult> {
        if let Some(version) = self.get_version_by_parent_version_id(parent_version_id)? {
            Ok(GetVersionResult::Version {
                version_id: version.version_id,
                parent_version_id: version.parent_version_id,
                history_segment: version.history_segment,
            })
        } else {
            Ok(GetVersionResult::NoSuchVersion)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_empty() -> anyhow::Result<()> {
        let tmp_dir = TempDir::new()?;
        let mut server = LocalServer::new(&tmp_dir.path())?;
        let child_version = server.get_child_version(NO_VERSION_ID)?;
        assert_eq!(child_version, GetVersionResult::NoSuchVersion);
        Ok(())
    }

    #[test]
    fn test_add_zero_base() -> anyhow::Result<()> {
        let tmp_dir = TempDir::new()?;
        let mut server = LocalServer::new(&tmp_dir.path())?;
        let history = b"1234".to_vec();
        match server.add_version(NO_VERSION_ID, history.clone())? {
            AddVersionResult::ExpectedParentVersion(_) => {
                panic!("should have accepted the version")
            }
            AddVersionResult::Ok(version_id) => {
                let new_version = server.get_child_version(NO_VERSION_ID)?;
                assert_eq!(
                    new_version,
                    GetVersionResult::Version {
                        version_id,
                        parent_version_id: NO_VERSION_ID,
                        history_segment: history,
                    }
                );
            }
        }

        Ok(())
    }

    #[test]
    fn test_add_nonzero_base() -> anyhow::Result<()> {
        let tmp_dir = TempDir::new()?;
        let mut server = LocalServer::new(&tmp_dir.path())?;
        let history = b"1234".to_vec();
        let parent_version_id = Uuid::new_v4() as VersionId;

        // This is OK because the server has no latest_version_id yet
        match server.add_version(parent_version_id, history.clone())? {
            AddVersionResult::ExpectedParentVersion(_) => {
                panic!("should have accepted the version")
            }
            AddVersionResult::Ok(version_id) => {
                let new_version = server.get_child_version(parent_version_id)?;
                assert_eq!(
                    new_version,
                    GetVersionResult::Version {
                        version_id,
                        parent_version_id,
                        history_segment: history,
                    }
                );
            }
        }

        Ok(())
    }

    #[test]
    fn test_add_nonzero_base_forbidden() -> anyhow::Result<()> {
        let tmp_dir = TempDir::new()?;
        let mut server = LocalServer::new(&tmp_dir.path())?;
        let history = b"1234".to_vec();
        let parent_version_id = Uuid::new_v4() as VersionId;

        // add a version
        if let AddVersionResult::ExpectedParentVersion(_) =
            server.add_version(parent_version_id, history.clone())?
        {
            panic!("should have accepted the version")
        }

        // then add another, not based on that one
        if let AddVersionResult::Ok(_) = server.add_version(parent_version_id, history.clone())? {
            panic!("should not have accepted the version")
        }

        Ok(())
    }
}