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
//! Functions to simplify the construction of requests along with request types that can be
//! serialized to and from the JSON body.

use http::uri::PathAndQuery;
use hyper::{Body, Method, Request, Uri};
use serde::Serialize;
use serde_json;

/// Types that represent a request being made to the server.
pub trait RequestType {
    /// The HTTP method included with the header.
    const METHOD: Method;
    /// The component of the URI following the domain.
    const PATH_AND_QUERY: &'static str;
}

/// Types that may be converted into a serialized JSON body for a hyper request.
pub trait IntoBody {
    /// The body of the request, capable of being serialized to JSON.
    type Body: Serialize;
    /// Convert `self` into the serializable `Body` type.
    fn into_body(self) -> Self::Body;
}

/// Types that may be directly converted into a hyper Request.
pub trait IntoRequest: RequestType + IntoBody {
    /// The `base_uri` should include only the scheme and host - the path and query will be
    /// retrieved via `RequestType::PATH_AND_QUERY`.
    fn into_request(self, base_uri: Uri) -> Request<Body>;
}

/// The vector of bytes used as a key into a `sled::Tree`.
type Key = Vec<u8>;
/// The vector of bytes representing a value within a `sled::Tree`.
type Value = Vec<u8>;

/// Get a single entry from the DB, identified by the given unique key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Get {
    pub key: Key,
}

/// Delete the entry at the given key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Del {
    pub key: Key,
}

/// Set the entry with the given key and value, replacing the original if one exists.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Set {
    pub key: Key,
    pub value: Value,
}

/// Compare and swap. Capable of unique creation, conditional modification, or deletion.
///
/// If old is None, this will only set the value if it doesn't exist yet. If new is None, will
/// delete the value if old is correct. If both old and new are Some, will modify the value if old
/// is correct.
///
/// If Tree is read-only, will do nothing.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Cas {
    pub key: Key,
    pub old: Option<Value>,
    pub new: Option<Value>,
}

/// Merge a new value into the total state for a key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Merge {
    pub key: Key,
    pub value: Value,
}

/// Flushes any pending IO buffers to disk to ensure durability.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Flush;

/// Iterate over all entries within the `Tree`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Iter;

/// Iterate over all entries within the `Tree` that start at or follow the given key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Scan {
    pub key: Key,
}

/// Iterate over all entries within the `Tree` within the given key range.
///
/// The given range is non-inclusive of the `end` key.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ScanRange {
    pub start: Key,
    pub end: Key,
}

/// Retrieve the entry with the greatest `Key` in the `Tree`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Max;

/// Retrieve the entry that precedes the `Key`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Pred {
    pub key: Key,
}

/// Retrieve the entry that precedes or includes the `Key`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PredIncl {
    pub key: Key,
}

/// Retrieve the entry that follows the `Key`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Succ {
    pub key: Key,
}

/// Retrieve the entry that follows or includes the `Key`.
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SuccIncl {
    pub key: Key,
}

impl RequestType for Get {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/get";
}

impl RequestType for Del {
    const METHOD: Method = Method::DELETE;
    const PATH_AND_QUERY: &'static str = "/tree/entries/delete";
}

impl RequestType for Set {
    const METHOD: Method = Method::POST;
    const PATH_AND_QUERY: &'static str = "/tree/entries/set";
}

impl RequestType for Cas {
    const METHOD: Method = Method::PUT;
    const PATH_AND_QUERY: &'static str = "/tree/entries/cas";
}

impl RequestType for Merge {
    const METHOD: Method = Method::POST;
    const PATH_AND_QUERY: &'static str = "/tree/entries/merge";
}

impl RequestType for Flush {
    const METHOD: Method = Method::PUT;
    const PATH_AND_QUERY: &'static str = "/tree/entries/flush";
}

impl RequestType for Iter {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/iter";
}

impl RequestType for Scan {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/scan";
}

impl RequestType for ScanRange {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/scan_range";
}

impl RequestType for Max {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/max";
}

impl RequestType for Pred {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/pred";
}

impl RequestType for PredIncl {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/pred_incl";
}

impl RequestType for Succ {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/succ";
}

impl RequestType for SuccIncl {
    const METHOD: Method = Method::GET;
    const PATH_AND_QUERY: &'static str = "/tree/entries/succ_incl";
}

impl IntoBody for Get {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Del {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Set {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Cas {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Merge {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Flush {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Iter {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Scan {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for ScanRange {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Max {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Pred {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for PredIncl {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for Succ {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl IntoBody for SuccIncl {
    type Body = Self;
    fn into_body(self) -> Self::Body { self }
}

impl<T> IntoRequest for T
where
    T: RequestType + IntoBody,
{
    fn into_request(self, base_uri: Uri) -> Request<Body> {
        let method = T::METHOD;
        let uri = uri_with_path(base_uri, T::PATH_AND_QUERY);
        let body = self.into_body();
        let body_json = serde_json::to_vec(&body).expect("failed to serialize request body");
        Request::builder()
            .method(method)
            .uri(uri)
            .body(body_json.into())
            .expect("attempted to construct invalid request")
    }
}

/// Append the given path to the given `Uri`.
///
/// Assumes the `Uri` already contains the scheme and authority parts.
fn uri_with_path(uri: Uri, path: &str) -> Uri {
    let mut parts = uri.into_parts();
    let path_and_query = path
        .parse::<PathAndQuery>()
        .expect("failed to parse path and query for request URI");
    parts.path_and_query = Some(path_and_query);
    Uri::from_parts(parts)
        .expect("failed to construct request URI from parts")
}

/// A request to download the entire tree.
///
/// The body of the returned key is a `Get` serialized to JSON form.
pub fn from<T>(base_uri: Uri, req: T) -> Request<Body>
where
    T: IntoRequest,
{
    req.into_request(base_uri)
}

/// Shorthand for `from(base_uri, Get { key })`.
pub fn get(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, Get { key })
}

/// Shorthand for `from(base_uri, Del { key })`.
pub fn del(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, Del { key })
}

/// Shorthand for `from(base_uri, Set { key, value })`.
pub fn set(base_uri: Uri, key: Key, value: Value) -> Request<Body> {
    from(base_uri, Set { key, value })
}

/// Shorthand for `from(base_uri, Iter)`.
pub fn iter(base_uri: Uri) -> Request<Body> {
    from(base_uri, Iter)
}

/// Shorthand for `from(base_uri, Scan { key })`.
pub fn scan(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, Scan { key })
}

/// Shorthand for `from(base_uri, ScanRange { start, end })`.
pub fn scan_range(base_uri: Uri, start: Key, end: Key) -> Request<Body> {
    from(base_uri, ScanRange { start, end })
}

/// Shorthand for `from(base_uri, Max)`.
pub fn max(base_uri: Uri) -> Request<Body> {
    from(base_uri, Max)
}

/// Shorthand for `from(base_uri, Pred { key })`.
pub fn pred(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, Pred { key })
}

/// Shorthand for `from(base_uri, PredIncl { key })`.
pub fn pred_incl(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, PredIncl { key })
}

/// Shorthand for `from(base_uri, Succ { key })`.
pub fn succ(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, Succ { key })
}

/// Shorthand for `from(base_uri, SuccIncl { key })`.
pub fn succ_incl(base_uri: Uri, key: Key) -> Request<Body> {
    from(base_uri, SuccIncl { key })
}

/// Shorthand for `from(base_uri, Cas { key, old, new })`.
pub fn cas(base_uri: Uri, key: Key, old: Option<Value>, new: Option<Value>) -> Request<Body> {
    from(base_uri, Cas { key, old, new })
}

/// Shorthand for `from(base_uri, Merge { key, value })`.
pub fn merge(base_uri: Uri, key: Key, value: Value) -> Request<Body> {
    from(base_uri, Merge { key, value })
}

/// Shorthand for `from(base_uri, Flush)`.
pub fn flush(base_uri: Uri) -> Request<Body> {
    from(base_uri, Flush)
}