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
#![deny(missing_docs)]

//! Store and retrieve chunks, on another thread or something.

#[macro_use]
extern crate log;
extern crate crossbeam_channel as chan;

use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
use std::{io, mem, thread};

mod chunk;
pub use chunk::Chunk;

mod store;
pub use store::Store;

// State Transitions
// =================
// - load:     None      -> Loading
// - loaded:   Loading   -> Loaded
// - reload:   None      -> Loading
// - reload:   Loaded    -> Loading
// - reap:     Loaded    -> Unloading (good)
// - reap:     Loaded    -> None      (bad)
// - unloaded: Unloading -> Loading (reload)
// - unloaded: Unloading -> Loaded  (error)
// - unloaded: Unloading -> None    (normal)

/// It keeps your chunks warm for you.
pub struct Chunks<S: Store> {
    chunks: HashMap<S::Key, State<S>>,
    req: chan::Sender<Req<S>>,
    res: chan::Receiver<Res<S>>,
}

impl<S: Store> Chunks<S> {
    /// Make one of these things.
    pub fn new(mut store: S) -> Self {
        let (reqt, reqr) = chan::unbounded();
        let (rest, resr) = chan::unbounded();

        thread::spawn(move || {
            while let Some(msg) = reqr.recv() {
                let res = match msg {
                    Req::Load(key) => Res::Load(key, store.load(key)),
                    Req::Unload(key, value) => {
                        let res = store.store(key, &value);
                        Res::Unload(key, value, res)
                    }
                    Req::Save(key, value) => {
                        if let Err(e) = store.store(key, &value) {
                            error!("Couldn't save chunk {:?} ({}).", key, e);
                        }

                        continue;
                    }
                };

                rest.send(res);
            }
        });

        Chunks {
            chunks: HashMap::new(),
            req: reqt,
            res: resr,
        }
    }

    /// Process any completed I/O requests.
    pub fn tick(&mut self) {
        while let Some(res) = self.res.try_recv() {
            self.handle_response(res);
        }
    }

    /// Evict any chunks that weren't used since the last reap.
    pub fn reap(&mut self) {
        let Self { chunks, req, .. } = self;

        chunks.retain(|key, state| {
            let null = State::Loaded {
                used: false,
                chunk: Chunk::Bad,
            };

            *state = match mem::replace(state, null) {
                State::Loaded { used: true, chunk } => State::Loaded { used: false, chunk },
                State::Loaded { used: false, chunk } => match chunk {
                    Chunk::Good { save: true, value } => {
                        req.send(Req::Unload(*key, value));
                        State::Unloading { reload: false }
                    }
                    _ => return false,
                },
                other => other,
            };

            true
        });
    }

    /// Get the chunk or begin loading it.
    pub fn load(&mut self, key: S::Key) -> Option<&mut Chunk<S>> {
        match self.chunks.entry(key) {
            Occupied(entry) => match entry.into_mut() {
                State::Loaded { used, chunk } => {
                    *used = true;
                    Some(chunk)
                }
                State::Loading => None,
                State::Unloading { reload } => {
                    *reload = true;
                    None
                }
            },
            Vacant(entry) => {
                self.req.send(Req::Load(key));
                entry.insert(State::Loading);
                None
            }
        }
    }

    /// Get the chunk or wait until it's been loaded.
    pub fn load_sync(&mut self, key: S::Key) -> &mut Chunk<S> {
        //TODO(quadrupleslap): Remove unsafe when NLL lands.
        if let Some(entry) = (unsafe { &mut *(self as *mut Self) }).load(key) {
            return entry;
        }

        loop {
            let res = self.res.recv().unwrap();

            let done = match res {
                Res::Load(p, _) => p == key,
                _ => false,
            };

            self.handle_response(res);

            if done {
                break;
            }
        }

        match self.chunks.get_mut(&key) {
            Some(State::Loaded { chunk, .. }) => chunk,
            _ => unreachable!(),
        }
    }

    /// Reload the chunk, discarding any changes.
    pub fn reload(&mut self, key: S::Key) {
        match self.chunks.entry(key) {
            Occupied(entry) => match entry.into_mut() {
                entry @ State::Loaded { .. } => {
                    self.req.send(Req::Load(key));
                    *entry = State::Loading;
                }
                State::Loading => {}
                State::Unloading { reload } => {
                    *reload = true;
                }
            },
            Vacant(entry) => {
                self.req.send(Req::Load(key));
                entry.insert(State::Loading);
            }
        }
    }

    fn handle_response(&mut self, res: Res<S>) {
        match res {
            Res::Load(key, value) => {
                debug_assert!(self.chunks.get(&key).unwrap().is_loading());

                let chunk = match value {
                    Ok(value) => Chunk::Good { save: false, value },
                    Err(e) => {
                        error!("Couldn't load chunk {:?} ({}).", key, e);
                        Chunk::Bad
                    }
                };

                self.chunks.insert(key, State::Loaded { used: true, chunk });
            }
            Res::Unload(key, value, result) => {
                debug_assert!(self.chunks.get(&key).unwrap().is_unloading());

                let reload = match self.chunks.get(&key) {
                    Some(&State::Unloading { reload }) => reload,
                    _ => false,
                };

                let error = if let Err(e) = result {
                    error!("Couldn't unload chunk {:?} ({}).", key, e);
                    true
                } else {
                    false
                };

                if reload {
                    self.req.send(Req::Load(key));
                    self.chunks.insert(key, State::Loading);
                } else if error {
                    self.chunks.insert(
                        key,
                        State::Loaded {
                            used: false,
                            chunk: Chunk::Good { save: true, value },
                        },
                    );
                } else {
                    self.chunks.remove(&key);
                }
            }
        }
    }
}

impl<S: Store> Chunks<S>
where
    S::Value: Clone,
{
    /// Save any unsaved chunks.
    pub fn save(&mut self) {
        for (key, state) in self.chunks.iter_mut() {
            if let State::Loaded {
                chunk: Chunk::Good { save, value },
                ..
            } = state
            {
                if *save {
                    self.req.send(Req::Save(*key, value.clone()));
                    *save = false;
                }
            }
        }
    }
}

enum State<S: Store> {
    Loading,
    Unloading { reload: bool },
    Loaded { used: bool, chunk: Chunk<S> },
}

impl<S: Store> State<S> {
    fn is_loading(&self) -> bool {
        if let State::Loading = self {
            true
        } else {
            false
        }
    }

    fn is_unloading(&self) -> bool {
        if let State::Unloading { .. } = self {
            true
        } else {
            false
        }
    }
}

enum Req<S: Store> {
    Load(S::Key),
    Unload(S::Key, S::Value),
    Save(S::Key, S::Value),
}

enum Res<S: Store> {
    Load(S::Key, io::Result<S::Value>),
    Unload(S::Key, S::Value, io::Result<()>),
}