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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::{
    fs,
    path::{Path, PathBuf},
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use std::{
    convert::TryInto,
    io::{Error as IoError, ErrorKind},
};

use r2d2::PooledConnection;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::ToSql;

use crate::{
    config::Config,
    database::{DATABASE_VERSION, EVENTS_DB_NAME},
    error::{Error, Result},
    events::{Event, SerializedEvent},
    index::{Index, Writer},
    Connection, Database,
};

use crate::EventType;
use serde_json::Value;

/// Database that can be used to reindex the events.
///
/// Reindexing the database may be needed if the index schema changes. This may
/// happen occasionally on upgrades or if language settings for the database
/// change.
pub struct RecoveryDatabase {
    path: PathBuf,
    connection: PooledConnection<SqliteConnectionManager>,
    pool: r2d2::Pool<SqliteConnectionManager>,
    config: Config,
    recovery_info: RecoveryInfo,
    index_deleted: bool,
    index: Option<Index>,
    index_writer: Option<Writer>,
}

#[derive(Debug, Clone)]
/// Info about the recovery process.
///
/// This can be used to track the progress of the reindex.
///
/// `RecoveryInfo` implements `Send` and `Sync` so it can be shared between
/// threads if for example the UI is in a separate thread.
pub struct RecoveryInfo {
    total_event_count: u64,
    reindexed_events: Arc<AtomicU64>,
}

impl RecoveryInfo {
    /// The total number of events that the database holds.
    pub fn total_events(&self) -> u64 {
        self.total_event_count
    }

    /// The number of events that are processed and reindexed.
    pub fn reindexed_events(&self) -> &AtomicU64 {
        &self.reindexed_events
    }
}

impl RecoveryDatabase {
    /// Open a read-only Seshat database.
    ///
    /// # Arguments
    ///
    /// * `path` - The directory where the database will be stored in. This
    /// should be an empty directory if a new database should be created.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self>
    where
        PathBuf: std::convert::From<P>,
    {
        Self::new_with_config(path, &Config::new())
    }

    /// Open a recovery Seshat database with the provided config.
    ///
    /// # Arguments
    ///
    /// * `path` - The directory where the database will be stored in. This
    /// should be an empty directory if a new database should be created.
    ///
    /// * `config` - Configuration that changes the behaviour of the database.
    pub fn new_with_config<P: AsRef<Path>>(path: P, config: &Config) -> Result<Self>
    where
        PathBuf: std::convert::From<P>,
    {
        let db_path = path.as_ref().join(EVENTS_DB_NAME);
        let manager = SqliteConnectionManager::file(db_path);
        let pool = r2d2::Pool::new(manager)?;

        let mut connection = pool.get()?;
        connection.pragma_update(None, "foreign_keys", &1 as &dyn ToSql)?;

        Database::unlock(&connection, config)?;

        let (version, _) = match Database::get_version(&mut connection) {
            Ok(ret) => ret,
            Err(e) => return Err(Error::DatabaseOpenError(e.to_string())),
        };

        Database::create_tables(&connection)?;

        if version != DATABASE_VERSION {
            return Err(Error::DatabaseVersionError);
        }

        let event_count = Database::get_event_count(&connection)?;

        let info = RecoveryInfo {
            total_event_count: event_count as u64,
            reindexed_events: Arc::new(AtomicU64::new(0)),
        };

        Ok(Self {
            path: path.into(),
            connection,
            pool,
            config: config.clone(),
            recovery_info: info,
            index_deleted: false,
            index: None,
            index_writer: None,
        })
    }

    /// Delete the Seshat index, leaving only the events database.
    ///
    /// After this operation is done, the index can be rebuilt.
    pub fn delete_the_index(&mut self) -> Result<()> {
        let writer = self.index_writer.take();
        let index = self.index.take();

        drop(writer);
        drop(index);

        for entry in fs::read_dir(&self.path)? {
            let entry = entry?;
            let path = entry.path();

            // Skip removing directories, we don't create subdirs in our
            // database dir.
            if path.is_dir() {
                continue;
            }

            if let Some(file_name) = path.file_name() {
                // Skip removing the events database, those will be needed for
                // reindexing.
                if file_name.to_string_lossy().starts_with(EVENTS_DB_NAME) {
                    continue;
                }

                fs::remove_file(path)?
            }
        }
        self.index_deleted = true;
        Ok(())
    }

    pub(crate) fn event_from_json(event_source: &str) -> std::io::Result<Event> {
        let object: Value = serde_json::from_str(event_source)?;
        let content = &object["content"];
        let event_type = &object["type"];

        let event_type = match event_type.as_str().unwrap_or_default() {
            "m.room.message" => EventType::Message,
            "m.room.name" => EventType::Name,
            "m.room.topic" => EventType::Topic,
            _ => return Err(IoError::new(ErrorKind::Other, "Invalid event type.")),
        };

        let (content_value, msgtype) = match event_type {
            EventType::Message => (
                content["body"]
                    .as_str()
                    .ok_or_else(|| IoError::new(ErrorKind::Other, "No content value found"))?,
                Some("m.text"),
            ),
            EventType::Topic => (
                content["topic"]
                    .as_str()
                    .ok_or_else(|| IoError::new(ErrorKind::Other, "No content value found"))?,
                None,
            ),
            EventType::Name => (
                content["name"]
                    .as_str()
                    .ok_or_else(|| IoError::new(ErrorKind::Other, "No content value found"))?,
                None,
            ),
        };

        let event_id = object["event_id"]
            .as_str()
            .ok_or_else(|| IoError::new(ErrorKind::Other, "No event id found"))?;
        let sender = object["sender"]
            .as_str()
            .ok_or_else(|| IoError::new(ErrorKind::Other, "No sender found"))?;
        let server_ts = object["origin_server_ts"]
            .as_u64()
            .ok_or_else(|| IoError::new(ErrorKind::Other, "No server timestamp found"))?;
        let room_id = object["room_id"]
            .as_str()
            .ok_or_else(|| IoError::new(ErrorKind::Other, "No room id found"))?;

        Ok(Event::new(
            event_type,
            content_value,
            msgtype,
            event_id,
            sender,
            server_ts.try_into().map_err(|_e| {
                IoError::new(ErrorKind::Other, "Server timestamp out of valid range")
            })?,
            room_id,
            event_source,
        ))
    }

    /// Load deserialized events from the database.
    ///
    /// * `limit` - The number of events to load.
    /// * `from_event` - The event where to continue loading from.
    ///
    /// Events that fail to be deserialized will be filtered out.
    pub fn load_events_deserialized(
        &self,
        limit: usize,
        from_event: Option<&Event>,
    ) -> Result<Vec<Event>> {
        let serialized_events = self.load_events(limit, from_event)?;

        let events = serialized_events
            .iter()
            .map(|e| RecoveryDatabase::event_from_json(e))
            .filter_map(std::io::Result::ok)
            .collect();

        Ok(events)
    }

    /// Load serialized events from the database.
    ///
    /// * `limit` - The number of events to load.
    /// * `from_event` - The event where to continue loading from.
    pub fn load_events(
        &self,
        limit: usize,
        from_event: Option<&Event>,
    ) -> Result<Vec<SerializedEvent>> {
        Ok(Database::load_all_events(
            &self.connection,
            limit,
            from_event,
        )?)
    }

    /// Create and open a new index.
    ///
    /// Returns `ReindexError` if the index wasn't deleted first.
    pub fn open_index(&mut self) -> Result<()> {
        if !self.index_deleted {
            return Err(Error::ReindexError);
        }

        let index = Index::new(&self.path, &self.config)?;
        let writer = index.get_writer()?;
        self.index = Some(index);
        self.index_writer = Some(writer);

        Ok(())
    }

    /// Get the recovery info for the database.
    pub fn info(&self) -> &RecoveryInfo {
        &self.recovery_info
    }

    /// Get a database connection.
    ///
    /// Note that this connection should only be used for reading.
    pub fn get_connection(&self) -> Result<Connection> {
        let connection = self.pool.get()?;
        Database::unlock(&connection, &self.config)?;
        Database::set_pragmas(&connection)?;

        Ok(Connection {
            inner: connection,
            path: self.path.clone(),
        })
    }

    /// Re-index a batch of events.
    ///
    /// # Arguments
    ///
    /// * `events` - The events that should be reindexed.
    ///
    /// Returns `ReindexError` if the index wasn't previously deleted and
    /// opened.
    pub fn index_events(&mut self, events: &[Event]) -> Result<()> {
        match self.index_writer.as_mut() {
            Some(writer) => events.iter().map(|e| writer.add_event(e)).collect(),
            None => panic!("Index wasn't deleted"),
        }

        self.recovery_info
            .reindexed_events
            .fetch_add(events.len() as u64, Ordering::SeqCst);

        Ok(())
    }

    /// Commit to the index.
    ///
    /// Returns true if the commit was forwarded, false if not enough events are
    /// queued up.
    ///
    /// Returns `ReindexError` if the index wasn't previously deleted and
    /// opened.
    pub fn commit(&mut self) -> Result<bool> {
        match self.index_writer.as_mut() {
            Some(writer) => {
                let ret = writer.commit()?;
                Ok(ret)
            }
            None => Err(Error::ReindexError),
        }
    }

    /// Commit the remaining added events and mark the reindex as done.
    ///
    /// Returns `ReindexError` if the index wasn't previously deleted and
    /// opened.
    pub fn commit_and_close(mut self) -> Result<()> {
        match self.index_writer.as_mut() {
            Some(writer) => {
                writer.force_commit()?;
                self.connection
                    .execute("UPDATE reindex_needed SET reindex_needed = ?1", [false])?;
                Ok(())
            }
            None => Err(Error::ReindexError),
        }
    }

    /// Shut the database down.
    ///
    /// This will terminate the writer thread making sure that no writes will
    /// happen after this operation.
    pub fn shutdown(mut self) -> Result<()> {
        let index_writer = self.index_writer.take();
        index_writer.map_or(Ok(()), |i| i.wait_merging_threads())?;

        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod test {
    use crate::{
        database::DATABASE_VERSION, Database, Error, Event, RecoveryDatabase, Result, SearchConfig,
    };

    use std::{path::PathBuf, sync::atomic::Ordering};

    pub(crate) fn reindex_loop(
        db: &mut RecoveryDatabase,
        initial_events: Vec<Event>,
    ) -> Result<()> {
        let mut events = initial_events;

        loop {
            let serialized_events = db.load_events(10, events.last())?;
            if serialized_events.is_empty() {
                break;
            }

            events = serialized_events
                .iter()
                .map(|e| RecoveryDatabase::event_from_json(e))
                .filter_map(std::io::Result::ok)
                .collect();

            db.index_events(&events)?;
            db.commit()?;
        }
        Ok(())
    }

    #[test]
    fn test_recovery() {
        let mut path = PathBuf::from(file!());
        path.pop();
        path.pop();
        path.pop();
        path.push("data/database/v2");
        let db = Database::new(&path);

        match db {
            Ok(_) => panic!("Database doesn't need a reindex."),
            Err(e) => match e {
                Error::ReindexError => (),
                e => panic!("Database doesn't need a reindex: {}", e),
            },
        }

        let mut recovery_db = RecoveryDatabase::new(&path).expect("Can't open recovery db");
        assert_ne!(recovery_db.info().total_events(), 0);
        recovery_db
            .delete_the_index()
            .expect("Can't delete the index");
        recovery_db
            .open_index()
            .expect("Can't open the new the index");

        let events = recovery_db
            .load_events_deserialized(10, None)
            .expect("Can't load events");

        assert!(!events.is_empty());
        assert_eq!(events.len(), 10);

        recovery_db.index_events(&events).unwrap();
        assert_eq!(
            recovery_db
                .info()
                .reindexed_events()
                .load(Ordering::Relaxed),
            10
        );

        reindex_loop(&mut recovery_db, events).expect("Can't reindex the db");

        assert_eq!(
            recovery_db
                .info()
                .reindexed_events()
                .load(Ordering::Relaxed),
            999
        );

        recovery_db.commit_and_close().unwrap();

        let db = Database::new(&path).unwrap();
        let mut connection = db.get_connection().unwrap();

        let (version, reindex_needed) = Database::get_version(&mut connection).unwrap();

        assert_eq!(version, DATABASE_VERSION);
        assert!(!reindex_needed);

        let result = db.search("Hello", &SearchConfig::new()).unwrap().results;
        assert!(!result.is_empty())
    }
}