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
//! This module contains syncronous versions of the backend trait, as well as an abstraction for
//! implementing the main, async traits through holding the syncronous version in a task.
//!
//! This trait is not meant to be consumed directly by a user of this library.
//!
//! Implementors of this trait are required to be send (as the operations are handled on an async task),
//! however, they are not required to be sync.
//!
//! Addtionally, as only one direct consumer of these traits is expected to exist, the implementors are
//! not required to be `Clone`.
//!
//! Methods in this module are intentionally left undocumented, as they are indented to be syncronus
//! versions of their async equivlants in the main Backend traits.
use crate::manifest::StoredArchive;
use crate::repository::backend::{
    backend_to_object, Backend, BackendObject, Index, Manifest, Result, SegmentDescriptor,
};
use crate::repository::{Chunk, ChunkID, ChunkSettings, EncryptedKey};

use async_trait::async_trait;
use chrono::prelude::*;
use futures::channel::oneshot;
use semver::Version;
use uuid::Uuid;

use std::collections::HashSet;
use std::thread;

pub trait SyncManifest: std::fmt::Debug {
    type Iterator: Iterator<Item = StoredArchive> + std::fmt::Debug + Send + 'static;
    fn last_modification(&mut self) -> Result<DateTime<FixedOffset>>;
    fn chunk_settings(&mut self) -> ChunkSettings;
    fn archive_iterator(&mut self) -> Self::Iterator;
    fn write_chunk_settings(&mut self, settings: ChunkSettings) -> Result<()>;
    fn write_archive(&mut self, archive: StoredArchive) -> Result<()>;
    fn touch(&mut self) -> Result<()>;
    fn seen_versions(&mut self) -> HashSet<(Version, Uuid)>;
}

pub trait SyncIndex: std::fmt::Debug {
    fn lookup_chunk(&mut self, id: ChunkID) -> Option<SegmentDescriptor>;
    fn set_chunk(&mut self, id: ChunkID, location: SegmentDescriptor) -> Result<()>;
    fn known_chunks(&mut self) -> HashSet<ChunkID>;
    fn commit_index(&mut self) -> Result<()>;
    fn chunk_count(&mut self) -> usize;
}

/// Note: In this version of the trait, the get index and get archive methods return mutable references,
/// instead of owned values. As this version of the trait is intrinsically single threaded, implementers
/// are expected to own a single instance of their Index and Manifest impls, and the reference will
/// never leak outside of their container task.
///
/// Also note, that we do not have the close method, as the wrapper type will handle that for us.
pub trait SyncBackend: 'static + std::fmt::Debug {
    type SyncManifest: SyncManifest + 'static;
    type SyncIndex: SyncIndex + 'static;
    fn get_index(&mut self) -> &mut Self::SyncIndex;
    fn get_manifest(&mut self) -> &mut Self::SyncManifest;
    fn write_key(&mut self, key: EncryptedKey) -> Result<()>;
    fn read_key(&mut self) -> Result<EncryptedKey>;
    fn read_chunk(&mut self, location: SegmentDescriptor) -> Result<Chunk>;
    fn write_chunk(&mut self, chunk: Chunk) -> Result<SegmentDescriptor>;
}

#[derive(Debug)]
enum SyncIndexCommand {
    Lookup(ChunkID, oneshot::Sender<Option<SegmentDescriptor>>),
    Set(ChunkID, SegmentDescriptor, oneshot::Sender<Result<()>>),
    KnownChunks(oneshot::Sender<HashSet<ChunkID>>),
    Commit(oneshot::Sender<Result<()>>),
    Count(oneshot::Sender<usize>),
}

#[derive(Debug)]
enum SyncManifestCommand<I> {
    LastMod(oneshot::Sender<Result<DateTime<FixedOffset>>>),
    ChunkSettings(oneshot::Sender<ChunkSettings>),
    ArchiveIterator(oneshot::Sender<I>),
    WriteChunkSettings(ChunkSettings, oneshot::Sender<Result<()>>),
    WriteArchive(StoredArchive, oneshot::Sender<Result<()>>),
    Touch(oneshot::Sender<Result<()>>),
    SeenVersions(oneshot::Sender<HashSet<(Version, Uuid)>>),
}

#[derive(Debug)]
enum SyncBackendCommand {
    ReadChunk(SegmentDescriptor, oneshot::Sender<Result<Chunk>>),
    WriteChunk(Chunk, oneshot::Sender<Result<SegmentDescriptor>>),
    ReadKey(oneshot::Sender<Result<EncryptedKey>>),
    WriteKey(EncryptedKey, oneshot::Sender<Result<()>>),
    Close(oneshot::Sender<()>),
}

#[derive(Debug)]
enum SyncCommand<I: std::fmt::Debug> {
    Index(SyncIndexCommand),
    Manifest(SyncManifestCommand<I>),
    Backend(SyncBackendCommand),
}

/// Wrapper Type for sync backends that converts them into async backends
///
/// Functions by moving the provided back end into a dedicated tokio task, and then sending `SyncCommands`
/// to instruct that task on what to do.
pub struct BackendHandle<B: SyncBackend> {
    channel:
        flume::Sender<SyncCommand<<<B as SyncBackend>::SyncManifest as SyncManifest>::Iterator>>,
}

impl<B> BackendHandle<B>
where
    B: SyncBackend + 'static,
{
    /// Constructs a new `BackendHandle`
    ///
    /// Spawns a new runner thread to handle commands on.
    ///
    /// Takes a closure that produces the required `SyncBackend`, in order to allow
    /// injecting non-`Send` backends into the spawned threads.
    ///
    /// `queue_depth` should be a positive (greater than 0) integer, that represents the
    /// number of requests to hold in the processing queue at any given time.
    pub fn new(queue_depth: usize, backend: impl FnOnce() -> B + Send + 'static) -> Self {
        let (input, output) = flume::bounded(queue_depth);
        thread::spawn(move || {
            let mut backend = backend();
            let mut final_ret: Option<oneshot::Sender<()>> = None;
            while let Ok(command) = output.recv() {
                match command {
                    SyncCommand::Index(index_command) => {
                        let index = backend.get_index();
                        match index_command {
                            SyncIndexCommand::Lookup(id, ret) => {
                                ret.send(index.lookup_chunk(id)).unwrap();
                            }
                            SyncIndexCommand::Set(id, location, ret) => {
                                ret.send(index.set_chunk(id, location)).unwrap();
                            }
                            SyncIndexCommand::KnownChunks(ret) => {
                                ret.send(index.known_chunks()).unwrap();
                            }
                            SyncIndexCommand::Commit(ret) => {
                                ret.send(index.commit_index()).unwrap();
                            }
                            SyncIndexCommand::Count(ret) => {
                                ret.send(index.chunk_count()).unwrap();
                            }
                        };
                    }
                    SyncCommand::Manifest(manifest_command) => {
                        let manifest = backend.get_manifest();
                        match manifest_command {
                            SyncManifestCommand::LastMod(ret) => {
                                ret.send(manifest.last_modification()).unwrap();
                            }
                            SyncManifestCommand::ChunkSettings(ret) => {
                                ret.send(manifest.chunk_settings()).unwrap();
                            }
                            SyncManifestCommand::ArchiveIterator(ret) => {
                                ret.send(manifest.archive_iterator()).unwrap();
                            }
                            SyncManifestCommand::WriteChunkSettings(settings, ret) => {
                                ret.send(manifest.write_chunk_settings(settings)).unwrap();
                            }
                            SyncManifestCommand::WriteArchive(archive, ret) => {
                                ret.send(manifest.write_archive(archive)).unwrap();
                            }
                            SyncManifestCommand::Touch(ret) => {
                                ret.send(manifest.touch()).unwrap();
                            }
                            SyncManifestCommand::SeenVersions(ret) => {
                                ret.send(manifest.seen_versions()).unwrap();
                            }
                        }
                    }
                    SyncCommand::Backend(backend_command) => match backend_command {
                        SyncBackendCommand::ReadChunk(location, ret) => {
                            ret.send(backend.read_chunk(location)).unwrap();
                        }
                        SyncBackendCommand::WriteChunk(chunk, ret) => {
                            ret.send(backend.write_chunk(chunk)).unwrap();
                        }
                        SyncBackendCommand::WriteKey(key, ret) => {
                            ret.send(backend.write_key(key)).unwrap();
                        }
                        SyncBackendCommand::ReadKey(ret) => {
                            ret.send(backend.read_key()).unwrap();
                        }
                        SyncBackendCommand::Close(ret) => {
                            final_ret = Some(ret);
                        }
                    },
                };
                if final_ret.is_some() {
                    break;
                }
            }
            std::mem::drop(backend);
            std::mem::drop(output);
            if let Some(ret) = final_ret {
                ret.send(()).unwrap();
            }
        });

        BackendHandle { channel: input }
    }
}

impl<B: SyncBackend> std::fmt::Debug for BackendHandle<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Opaque Backend Handle")
    }
}

impl<B: SyncBackend> Clone for BackendHandle<B> {
    fn clone(&self) -> Self {
        BackendHandle {
            channel: self.channel.clone(),
        }
    }
}

#[async_trait]
impl<B: SyncBackend> Manifest for BackendHandle<B> {
    type Iterator = <<B as SyncBackend>::SyncManifest as SyncManifest>::Iterator;
    async fn last_modification(&mut self) -> Result<DateTime<FixedOffset>> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::LastMod(i)))
            .await
            .unwrap();
        o.await?
    }
    async fn chunk_settings(&mut self) -> ChunkSettings {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::ChunkSettings(i)))
            .await
            .unwrap();
        o.await.unwrap()
    }
    async fn archive_iterator(&mut self) -> Self::Iterator {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::ArchiveIterator(
                i,
            )))
            .await
            .unwrap();
        o.await.unwrap()
    }
    async fn write_chunk_settings(&mut self, settings: ChunkSettings) -> Result<()> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(
                SyncManifestCommand::WriteChunkSettings(settings, i),
            ))
            .await
            .unwrap();
        o.await?
    }
    async fn write_archive(&mut self, archive: StoredArchive) -> Result<()> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::WriteArchive(
                archive, i,
            )))
            .await
            .unwrap();
        o.await?
    }
    async fn touch(&mut self) -> Result<()> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::Touch(i)))
            .await
            .unwrap();
        o.await?
    }
    async fn seen_versions(&mut self) -> HashSet<(Version, Uuid)> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Manifest(SyncManifestCommand::SeenVersions(i)))
            .await
            .unwrap();
        o.await.unwrap()
    }
}

#[async_trait]
impl<B: SyncBackend> Index for BackendHandle<B> {
    async fn lookup_chunk(&mut self, id: ChunkID) -> Option<SegmentDescriptor> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Index(SyncIndexCommand::Lookup(id, i)))
            .await
            .unwrap();
        o.await.unwrap()
    }
    async fn set_chunk(&mut self, id: ChunkID, location: SegmentDescriptor) -> Result<()> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Index(SyncIndexCommand::Set(id, location, i)))
            .await
            .unwrap();
        o.await?
    }
    async fn known_chunks(&mut self) -> HashSet<ChunkID> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Index(SyncIndexCommand::KnownChunks(i)))
            .await
            .unwrap();
        o.await.unwrap()
    }
    async fn commit_index(&mut self) -> Result<()> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Index(SyncIndexCommand::Commit(i)))
            .await
            .unwrap();
        o.await?
    }
    async fn count_chunk(&mut self) -> usize {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Index(SyncIndexCommand::Count(i)))
            .await
            .unwrap();
        o.await.unwrap()
    }
}

#[async_trait]
impl<B: SyncBackend> Backend for BackendHandle<B> {
    type Manifest = Self;
    type Index = Self;
    fn get_index(&self) -> Self::Index {
        self.clone()
    }
    async fn write_key(&self, key: &EncryptedKey) -> Result<()> {
        // We pull some jank here to access the channel without having to change the signature to
        // &mut self. This clone should be okay, performance wise, as it should only happen very
        // rarely
        let new_self = self.clone();
        let (i, o) = oneshot::channel();
        new_self
            .channel
            .send_async(SyncCommand::Backend(SyncBackendCommand::WriteKey(
                key.clone(),
                i,
            )))
            .await
            .unwrap();
        o.await.unwrap()
    }
    async fn read_key(&self) -> Result<EncryptedKey> {
        // We pull some jank here to access the channel without having to change the signature to
        // &mut self. This clone should be okay, performance wise, as it should only happen very
        // rarely
        let new_self = self.clone();
        let (i, o) = oneshot::channel();
        new_self
            .channel
            .send_async(SyncCommand::Backend(SyncBackendCommand::ReadKey(i)))
            .await
            .unwrap();
        o.await?
    }
    fn get_manifest(&self) -> Self::Manifest {
        self.clone()
    }
    async fn read_chunk(&mut self, location: SegmentDescriptor) -> Result<Chunk> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Backend(SyncBackendCommand::ReadChunk(
                location, i,
            )))
            .await
            .unwrap();
        o.await?
    }
    async fn write_chunk(&mut self, chunk: Chunk) -> Result<SegmentDescriptor> {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Backend(SyncBackendCommand::WriteChunk(
                chunk, i,
            )))
            .await
            .unwrap();
        o.await?
    }
    async fn close(&mut self) {
        let (i, o) = oneshot::channel();
        self.channel
            .send_async(SyncCommand::Backend(SyncBackendCommand::Close(i)))
            .await
            .unwrap();
        o.await.unwrap()
    }

    fn get_object_handle(&self) -> BackendObject {
        backend_to_object(self.clone())
    }
}