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
//! Data used for general application setup: third-party connexions, et caetera.


use self::super::super::ops::{SolutionOrdering, LeaderboardOf};
use rocket::request::{FromRequest, Outcome as RequestOutcome};
use self::super::super::util::INITIALISE_DATABASE;
use diesel::r2d2::{self, ConnectionManager};
use rocket::request::{FormItems, FromForm};
use diesel::connection::SimpleConnection;
use chrono::{DateTime, Duration, Utc};
use rocket::{Request, Outcome, State};
use diesel::sqlite::SqliteConnection;
use rocket::Error as RocketError;
use std::sync::{Mutex, Arc};
use rocket::http::Status;
use std::path::PathBuf;
use std::ops::Deref;
use std::fs::File;
use std::io::Read;
use std::cmp;
use toml;


/// Connection request guard type: a wrapper around an r2d2 pooled connection.
///
/// Use this as an argument to a Rocket request handler after having it `manage()`d to gain access to the database.
///
/// # Examples
///
/// ```no_run
/// # #![feature(plugin)]
/// # #![plugin(rocket_codegen)]
/// # extern crate sudoku_backend;
/// # #[macro_use]
/// # extern crate rocket;
/// # use std::fs;
/// # use std::env::temp_dir;
/// # use sudoku_backend::ops::setup::DatabaseConnection;
/// #[get("/databased")]
/// fn databased(db: DatabaseConnection) -> String {
///     // Do some database ops, which are outside the scope of this document
/// #   let funxion_result = "henlo".to_string();
///     funxion_result
/// }
///
/// fn main() {
/// #   let database_file =
/// #     ("$ROOT/sudoku-backend.db".to_string(),
/// #      temp_dir().join("sudoku-backend-doctest").join("ops-setup-DatabaseConnection-initialise").join("sudoku-backend.db"));
/// #   fs::create_dir_all(database_file.1.parent().unwrap()).unwrap();
/// #   /*
///     let database_file: (String, PathBuf) = /* obtained elsewhere */;
/// #   */
///     rocket::ignite()
///         .manage(DatabaseConnection::initialise(&database_file))
///         .mount("/", routes![databased])
///         .launch();
/// }
/// ```
pub struct DatabaseConnection(r2d2::PooledConnection<ConnectionManager<SqliteConnection>>);

impl DatabaseConnection {
    /// Set up a connection to the main database located in the specified file and initialise it with
    /// [`util::INITIALISE_DATABASE`](../../../util/static.INITIALISE_DATABASE.html).
    pub fn initialise(db_file: &(String, PathBuf)) -> r2d2::Pool<ConnectionManager<SqliteConnection>> {
        let mgr = ConnectionManager::new(db_file.1.display().to_string().replace('\\', "/"));
        let pool: r2d2::Pool<ConnectionManager<SqliteConnection>> = r2d2::Pool::new(mgr).expect("Failed to open database");
        pool.get().unwrap().batch_execute(INITIALISE_DATABASE).unwrap();
        pool
    }
}

/// Attempts to retrieve a single connection from the managed database pool.
///
/// If no pool is currently managed, fails with an `InternalServerError` status.
/// If no connections are available, fails with a `ServiceUnavailable` status.
impl<'a, 'r> FromRequest<'a, 'r> for DatabaseConnection {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> RequestOutcome<DatabaseConnection, ()> {
        match request.guard::<State<r2d2::Pool<ConnectionManager<SqliteConnection>>>>()?.get() {
            Ok(conn) => Outcome::Success(DatabaseConnection(conn)),
            Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
        }
    }
}

impl Deref for DatabaseConnection {
    type Target = SqliteConnection;

    fn deref(&self) -> &SqliteConnection {
        &self.0
    }
}


/// Configuration of a leaderboard request.
//
/// Refer to [`doc/check.rs`](../../doc/check/) for more details.
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, PartialOrd, Ord)]
pub struct SpecificLeaderboardConfig {
    /// How many entries to return
    pub for_whom: LeaderboardOf,
    /// How many entries to return
    pub cfg: LeaderboardConfig,
}

#[derive_FromForm]
struct SpecificLeaderboardConfigData {
    pub count: Option<usize>,
    pub ordering: Option<SolutionOrdering>,
    pub of: Option<LeaderboardOf>,
}

impl<'f> FromForm<'f> for SpecificLeaderboardConfig {
    // Ideally this would be
    // type Error = <LeaderboardConfigData as FromForm<'f>>::Error;
    // But that's "leaking a private type" so
    type Error = RocketError;

    fn from_form(items: &mut FormItems<'f>, strict: bool) -> Result<Self, Self::Error> {
        SpecificLeaderboardConfigData::from_form(items, strict).map(|slcd| {
            let for_whom = slcd.of.unwrap_or_else(|| LeaderboardOf::Default);
            let defaults = match for_whom {
                LeaderboardOf::Solutions => &LeaderboardConfig::BOARD_DEFAULT_DEFAULT,
                LeaderboardOf::Users => &LeaderboardConfig::PLAYER_DEFAULT_DEFAULT,
            };

            SpecificLeaderboardConfig {
                for_whom: for_whom,
                cfg: LeaderboardConfig {
                    count: slcd.count.unwrap_or_else(|| defaults.count),
                    ordering: slcd.ordering.unwrap_or_else(|| defaults.ordering),
                },
            }
        })
    }
}

/// Configuration of a leaderboard request.
//
/// Refer to [`doc/check.rs`](../../doc/check/) for more details.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Hash, Eq, PartialEq, Ord)]
pub struct LeaderboardConfig {
    /// How many entries to return
    pub count: usize,
    /// How to order the returned entries
    pub ordering: SolutionOrdering,
}

impl LeaderboardConfig {
    /// Default no-spec return config for solutions.
    pub const BOARD_DEFAULT_DEFAULT: LeaderboardConfig = LeaderboardConfig {
        count: 10,
        ordering: SolutionOrdering::Default,
    };

    /// Default maximal unexceedable return config for solutions.
    pub const BOARD_DEFAULT_MAX: LeaderboardConfig = LeaderboardConfig {
        count: 42,
        ordering: SolutionOrdering::Default,
    };

    /// Default no-spec return config for players.
    pub const PLAYER_DEFAULT_DEFAULT: LeaderboardConfig = LeaderboardConfig {
        count: 3,
        ordering: SolutionOrdering::Default,
    };

    /// Default maximal unexceedable return config for players.
    pub const PLAYER_DEFAULT_MAX: LeaderboardConfig = LeaderboardConfig {
        count: 10,
        ordering: SolutionOrdering::Default,
    };
}

impl cmp::PartialOrd for LeaderboardConfig {
    fn partial_cmp(&self, other: &LeaderboardConfig) -> Option<cmp::Ordering> {
        self.count.partial_cmp(&other.count)
    }
}

/// Amalgam of max and default leaderboard configurations.
//
/// Refer to [`doc/check.rs`](../../doc/check/) for more details.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct LeaderboardGroupSettings {
    /// Default config to backfill from
    pub default: LeaderboardConfig,
    /// Unexceedable config
    pub max: LeaderboardConfig,
}

/// Amalgam of max and default leaderboard configurations.
//
/// Refer to [`doc/check.rs`](../../doc/check/) for more details.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct LeaderboardSettings {
    /// Settings for solves
    pub board: LeaderboardGroupSettings,
    /// Settings for people
    pub person: LeaderboardGroupSettings,
}

impl LeaderboardSettings {
    /// Load the settings from the ones specified in the specified file.
    pub fn load(settings_file: &(String, PathBuf)) -> Result<LeaderboardSettings, String> {
        let mut buf = String::new();
        File::open(&settings_file.1).map_err(|e| format!("Couldn't open leaderboard settings file: {}", e))?
            .read_to_string(&mut buf)
            .map_err(|e| format!("Couldn't read leaderboard settings file: {}", e))?;
        toml::from_str(&buf).map_err(|e| format!("Failed to parse leaderboard settings: {}", e))
    }
}

/// A time-limited cache of session IDs for "currently active" indicator.
//
/// Refer to [`doc/check.rs`](../../doc/check/) for more details.
///
/// # Examples
///
/// ```no_run
/// # #![feature(plugin)]
/// # #![plugin(rocket_codegen)]
/// # extern crate sudoku_backend;
/// # #[macro_use]
/// # extern crate rocket;
/// # use std::fs;
/// # use rocket::State;
/// # use std::env::temp_dir;
/// # use sudoku_backend::util::ACTIVITY_TIMEOUT_DEFAULT;
/// # use sudoku_backend::ops::setup::{DatabaseConnection, ActivityCache};
/// #[get("/endpoint")]
/// fn endpoint(db: DatabaseConnection, ac: State<ActivityCache>) -> String {
///     // Get the ID of this session
/// #   let session_id = 12;
///     ac.register_activity(12);
///
///     // rest of funxionality is outside the scope of this document
/// #   let funxion_result = "henlo".to_string();
///     funxion_result
/// }
///
/// #[get("/users_active")]
/// fn users_active(ac: State<ActivityCache>) -> String {
///     ac.active_users().to_string()
/// }
///
/// fn main() {
/// #   let database_file =
/// #     ("$ROOT/sudoku-backend.db".to_string(),
/// #      temp_dir().join("sudoku-backend-doctest").join("ops-setup-ActivityCache").join("sudoku-backend.db"));
/// #   fs::create_dir_all(database_file.1.parent().unwrap()).unwrap();
/// #   /*
///     let database_file: (String, PathBuf) = /* obtained elsewhere */;
/// #   */
///     rocket::ignite()
///         .manage(DatabaseConnection::initialise(&database_file))
///         .manage(ActivityCache::new(*ACTIVITY_TIMEOUT_DEFAULT))
///         .mount("/", routes![endpoint, users_active])
///         .launch();
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ActivityCache {
    timeout: Duration,
    session_ids: Arc<Mutex<Vec<(usize, DateTime<Utc>)>>>,
}

impl ActivityCache {
    /// Create a cache timing out after the specified duration.
    pub fn new(timeout: Duration) -> ActivityCache {
        ActivityCache {
            timeout: timeout,
            session_ids: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Mark the specified session ID as last active *now*.
    pub fn register_activity(&self, session_id: usize) {
        let mut session_ids = match self.session_ids.lock() {
            Ok(l) => l,
            Err(pl) => pl.into_inner(),
        };

        match session_ids.binary_search_by_key(&session_id, |&(id, _)| id) {
            Ok(idx) => session_ids[idx] = (session_id, Utc::now()),
            Err(idx) => session_ids.insert(idx, (session_id, Utc::now())),
        }
    }

    /// Get how many users can be considered "active", i.e. amount of sessions last active at most the previously-specified
    /// amount of time before *now*.
    pub fn active_users(&self) -> usize {
        let oldest_allowed = Utc::now() - self.timeout;
        let mut session_ids = match self.session_ids.lock() {
            Ok(l) => l,
            Err(pl) => pl.into_inner(),
        };

        session_ids.retain(|&(_, ts)| ts > oldest_allowed);
        session_ids.len()
    }
}