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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use crate::core::{ErrorKind, Key, Memcached, Meta, MtopError, SlabItems, Slabs, Stats, Value};
use crate::discovery::{Server, ServerID};
use crate::net::{tcp_connect, tcp_tls_connect, tls_client_config, TlsConfig};
use crate::pool::{ClientFactory, ClientPool, ClientPoolConfig, PooledClient};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::Hasher;
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::sync::RwLock;
use tokio_rustls::rustls::pki_types::ServerName;
use tokio_rustls::rustls::ClientConfig;
use tracing::instrument::WithSubscriber;

#[derive(Debug, Clone)]
pub struct MemcachedClientConfig {
    pub pool_max_idle: u64,
}

impl Default for MemcachedClientConfig {
    fn default() -> Self {
        Self { pool_max_idle: 4 }
    }
}

/// Implementation of a `ClientFactory` that creates new Memcached clients that
/// use plaintext or TLS TCP connections.
#[derive(Debug)]
pub struct MemcachedFactory {
    client_config: Option<Arc<ClientConfig>>,
    server_name: Option<ServerName<'static>>,
}

impl MemcachedFactory {
    pub async fn new(handle: Handle, tls: TlsConfig) -> Result<Self, MtopError> {
        let server_name = if tls.enabled { tls.server_name.clone() } else { None };

        let client_config = if tls.enabled {
            Some(Arc::new(tls_client_config(handle, tls).await?))
        } else {
            None
        };

        Ok(Self {
            client_config,
            server_name,
        })
    }
}

impl ClientFactory<Server, Memcached> for MemcachedFactory {
    async fn make(&self, addr: &Server) -> Result<Memcached, MtopError> {
        if let Some(cfg) = &self.client_config {
            let server_name = self.server_name.clone().unwrap_or_else(|| addr.server_name());
            let (read, write) = tcp_tls_connect(addr.address(), server_name, cfg.clone()).await?;
            Ok(Memcached::new(read, write))
        } else {
            let (read, write) = tcp_connect(addr.address()).await?;
            Ok(Memcached::new(read, write))
        }
    }
}

/// Logic for picking a server to "own" a particular cache key that uses
/// rendezvous hashing.
///
/// See https://en.wikipedia.org/wiki/Rendezvous_hashing
#[derive(Debug)]
pub struct SelectorRendezvous {
    servers: RwLock<Vec<Server>>,
}

impl SelectorRendezvous {
    /// Create a new instance with the provided initial server list
    pub fn new(servers: Vec<Server>) -> Self {
        Self {
            servers: RwLock::new(servers),
        }
    }

    fn score(server: &Server, key: &Key) -> u64 {
        let mut hasher = DefaultHasher::new();
        hasher.write(server.id().as_ref().as_bytes());
        hasher.write(key.as_ref().as_bytes());
        hasher.finish()
    }

    /// Get a copy of all current servers.
    pub async fn servers(&self) -> Vec<Server> {
        let servers = self.servers.read().await;
        servers.clone()
    }

    /// Get the `Server` that owns the given key, or none if there are no servers.
    pub async fn server(&self, key: &Key) -> Option<Server> {
        let servers = self.servers.read().await;
        if servers.is_empty() {
            None
        } else if servers.len() == 1 {
            servers.first().cloned()
        } else {
            let mut max = u64::MIN;
            let mut choice = None;

            for server in servers.iter() {
                let score = Self::score(server, key);
                if score > max {
                    choice = Some(server);
                    max = score;
                }
            }

            choice.cloned()
        }
    }

    /// Update the list of potential servers to pick from.
    pub async fn set_servers(&self, servers: Vec<Server>) {
        let mut current = self.servers.write().await;
        *current = servers
    }
}

/// Response for both values and errors from multiple servers, indexed by server.
#[derive(Debug, Default)]
pub struct ServersResponse<T> {
    pub values: HashMap<ServerID, T>,
    pub errors: HashMap<ServerID, MtopError>,
}

impl<T> ServersResponse<T> {
    /// Return true if there are any errors, false otherwise.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }
}

/// Response for values indexed by key and errors indexed by server.
#[derive(Debug, Default)]
pub struct ValuesResponse {
    pub values: HashMap<String, Value>,
    pub errors: HashMap<ServerID, MtopError>,
}

impl ValuesResponse {
    /// Return true if there are any errors, false otherwise.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }
}

#[derive(Debug)]
pub struct MemcachedClient<F>
where
    F: ClientFactory<Server, Memcached> + Send + Sync + 'static,
{
    handle: Handle,
    selector: SelectorRendezvous,
    pool: Arc<ClientPool<Server, Memcached, F>>,
}

/// Run a method for a particular server in a spawned future.
macro_rules! spawn_for_host {
    ($self:ident, $method:ident, $host:expr $(, $args:expr)* $(,)?) => {{
        let pool = $self.pool.clone();
        $self.handle.spawn(async move {
            let mut conn = pool.get($host).await?;
            match conn.$method($($args,)*).await {
                Ok(v) => {
                    pool.put(conn).await;
                    Ok(v)
                }
                Err(e) => {
                    // Only return the client to the pool if error was due to an
                    // expected server error. Otherwise, we have no way to know the
                    // state of the client and associated connection.
                    if e.kind() == ErrorKind::Protocol {
                        pool.put(conn).await;
                    }
                    Err(e)
                }
            }
        }
        // Ensure this new future uses the same subscriber as the current one.
        .with_current_subscriber())
    }};
}

/// Run a method on a connection to a particular server based on the hash of a single key.
macro_rules! operation_for_key {
    ($self:ident, $method:ident, $key:expr $(, $args:expr)* $(,)?) => {{
        let key = Key::one($key)?;
        if let Some(s) = $self.selector.server(&key).await {
            let mut conn = $self.pool.get(&s).await?;
            match conn.$method(&key, $($args,)*).await {
                Ok(v) => {
                    $self.pool.put(conn).await;
                    Ok(v)
                }
                Err(e) => {
                    // Only return the client to the pool if error was due to an expected
                    // server error. Otherwise, we have no way to know the state of the client
                    // and associated connection.
                    if e.kind() == ErrorKind::Protocol {
                        $self.pool.put(conn).await;
                    }
                    Err(e)
                }
            }
        } else {
            Err(MtopError::runtime("no servers available"))
        }
    }};
}

/// Run a method on a connection to every server and bucket the results and errors by server.
macro_rules! operation_for_all {
    ($self:ident, $method:ident) => {{
        let servers = $self.selector.servers().await;
        let tasks = servers
            .into_iter()
            .map(|server| (server.clone(), spawn_for_host!($self, $method, &server)))
            .collect::<Vec<_>>();

        let mut values = HashMap::with_capacity(tasks.len());
        let mut errors = HashMap::new();

        for (server, task) in tasks {
            match task.await {
                Ok(Ok(results)) => {
                    values.insert(server.id(), results);
                }
                Ok(Err(e)) => {
                    errors.insert(server.id(), e);
                }
                Err(e) => {
                    errors.insert(server.id(), MtopError::runtime_cause("fetching cluster values", e));
                }
            };
        }

        Ok(ServersResponse { values, errors })
    }};
}

impl<F> MemcachedClient<F>
where
    F: ClientFactory<Server, Memcached> + Send + Sync + 'static,
{
    /// Create a new `MemcachedClient` instance.
    ///
    /// `handle` is used to spawn multiple async tasks to fetch data from servers in
    /// parallel. `selector` is used to determine which server "owns" a particular key.
    /// `pool` is used for pooling or establishing new connections to each server as
    /// needed.
    pub fn new(cfg: MemcachedClientConfig, handle: Handle, selector: SelectorRendezvous, factory: F) -> Self {
        let pool_config = ClientPoolConfig {
            name: "memcached-tcp".to_owned(),
            max_idle: cfg.pool_max_idle,
        };

        Self {
            handle,
            selector,
            pool: Arc::new(ClientPool::new(pool_config, factory)),
        }
    }

    /// Get a connection to a particular server from the pool if available, otherwise
    /// establish a new connection.
    pub async fn raw_open(&self, server: &Server) -> Result<PooledClient<Server, Memcached>, MtopError> {
        self.pool.get(server).await
    }

    /// Return a connection to a particular server to the pool if fewer than the configured
    /// number of idle connections to that server are currently in the pool, otherwise close
    /// it immediately.
    pub async fn raw_close(&self, connection: PooledClient<Server, Memcached>) {
        self.pool.put(connection).await
    }

    /// Get a `Stats` object with the current values of the interesting stats for each server.
    ///
    /// A future is spawned for each server with results and any errors indexed by server. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn stats(&self) -> Result<ServersResponse<Stats>, MtopError> {
        operation_for_all!(self, stats)
    }

    /// Get a `Slabs` object with information about each set of `Slab`s maintained by each server.
    /// You can think of each `Slab` as a class of objects that are stored together in memory. Note
    /// that `Slab` IDs may not be contiguous based on the size of items actually stored by the server.
    ///
    /// A future is spawned for each server with results and any errors indexed by server. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn slabs(&self) -> Result<ServersResponse<Slabs>, MtopError> {
        operation_for_all!(self, slabs)
    }

    /// Get a `SlabsItems` object with information about the `SlabItem` items stored in
    /// each slab class maintained by each server. The ID of each `SlabItem` corresponds to a
    /// `Slab` maintained by the server. Note that `SlabItem` IDs may not be contiguous based
    /// on the size of items actually stored by the server.
    ///
    /// A future is spawned for each server with results and any errors indexed by server. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn items(&self) -> Result<ServersResponse<SlabItems>, MtopError> {
        operation_for_all!(self, items)
    }

    /// Get a `Meta` object for every item in the cache for each server which includes its key
    /// and expiration time as a UNIX timestamp. Expiration time will be `-1` if the item was
    /// set with an infinite TTL.
    ///
    /// A future is spawned for each server with results and any errors indexed by server. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn metas(&self) -> Result<ServersResponse<Vec<Meta>>, MtopError> {
        operation_for_all!(self, metas)
    }

    /// Send a simple command to verify our connection each known server.
    ///
    /// A future is spawned for each server with results and any errors indexed by server. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn ping(&self) -> Result<ServersResponse<()>, MtopError> {
        operation_for_all!(self, ping)
    }

    /// Get a map of the requested keys and their corresponding `Value` in the cache
    /// including the key, flags, and data.
    ///
    /// This method uses a selector implementation to determine which server "owns" each of the
    /// provided keys. A future is spawned for each server and the results merged together. A
    /// pooled connection to each server is used if available, otherwise new connections are
    /// established.
    pub async fn get<I, K>(&self, keys: I) -> Result<ValuesResponse, MtopError>
    where
        I: IntoIterator<Item = K>,
        K: Into<String>,
    {
        let keys = Key::many(keys)?;
        if keys.is_empty() {
            return Ok(ValuesResponse::default());
        }

        let num_keys = keys.len();
        let mut by_server: HashMap<Server, Vec<Key>> = HashMap::new();
        for key in keys {
            if let Some(s) = self.selector.server(&key).await {
                let entry = by_server.entry(s).or_default();
                entry.push(key);
            }
        }

        let tasks = by_server
            .into_iter()
            .map(|(server, keys)| (server.clone(), spawn_for_host!(self, get, &server, &keys)))
            .collect::<Vec<_>>();

        let mut values = HashMap::with_capacity(num_keys);
        let mut errors = HashMap::new();

        for (server, task) in tasks {
            match task.await {
                Ok(Ok(results)) => {
                    values.extend(results);
                }
                Ok(Err(e)) => {
                    errors.insert(server.id(), e);
                }
                Err(e) => {
                    errors.insert(server.id(), MtopError::runtime_cause("fetching keys", e));
                }
            };
        }

        Ok(ValuesResponse { values, errors })
    }

    /// Increment the value of a key by the given delta if the value is numeric returning
    /// the new value. Returns an error if the value is not set or _not_ numeric.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn incr<K>(&self, key: K, delta: u64) -> Result<u64, MtopError>
    where
        K: Into<String>,
    {
        operation_for_key!(self, incr, key, delta)
    }

    /// Decrement the value of a key by the given delta if the value is numeric returning
    /// the new value with a minimum of 0. Returns an error if the value is not set or _not_
    /// numeric.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn decr<K>(&self, key: K, delta: u64) -> Result<u64, MtopError>
    where
        K: Into<String>,
    {
        operation_for_key!(self, decr, key, delta)
    }

    /// Store the provided item in the cache, regardless of whether it already exists.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn set<K, V>(&self, key: K, flags: u64, ttl: u32, data: V) -> Result<(), MtopError>
    where
        K: Into<String>,
        V: AsRef<[u8]>,
    {
        operation_for_key!(self, set, key, flags, ttl, data)
    }

    /// Store the provided item in the cache only if it does not already exist.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn add<K, V>(&self, key: K, flags: u64, ttl: u32, data: V) -> Result<(), MtopError>
    where
        K: Into<String>,
        V: AsRef<[u8]>,
    {
        operation_for_key!(self, add, key, flags, ttl, data)
    }

    /// Store the provided item in the cache only if it already exists.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn replace<K, V>(&self, key: K, flags: u64, ttl: u32, data: V) -> Result<(), MtopError>
    where
        K: Into<String>,
        V: AsRef<[u8]>,
    {
        operation_for_key!(self, replace, key, flags, ttl, data)
    }

    /// Update the TTL of an item in the cache if it exists, return an error otherwise.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn touch<K>(&self, key: K, ttl: u32) -> Result<(), MtopError>
    where
        K: Into<String>,
    {
        operation_for_key!(self, touch, key, ttl)
    }

    /// Delete an item from the cache if it exists, return an error otherwise.
    ///
    /// This method uses a selector implementation to determine which server "owns" the provided
    /// key. A pooled connection to the server is used if available, otherwise a new connection
    /// is established.
    pub async fn delete<K>(&self, key: K) -> Result<(), MtopError>
    where
        K: Into<String>,
    {
        operation_for_key!(self, delete, key)
    }
}

#[cfg(test)]
mod test {
    // TODO: Actually figure out how to test this without a bunch of boilerplate.

    ///////////
    // stats //
    ///////////

    #[tokio::test]
    async fn test_memcached_client_stats_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_stats_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_stats_some_errors() {}

    ///////////
    // slabs //
    ///////////

    #[tokio::test]
    async fn test_memcached_client_slabs_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_slabs_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_slabs_some_errors() {}

    ///////////
    // items //
    ///////////

    #[tokio::test]
    async fn test_memcached_client_items_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_items_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_items_some_errors() {}

    ///////////
    // metas //
    ///////////

    #[tokio::test]
    async fn test_memcached_client_metas_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_metas_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_metas_some_errors() {}

    //////////
    // ping //
    //////////

    #[tokio::test]
    async fn test_memcached_client_ping_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_ping_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_ping_some_errors() {}

    /////////
    // get //
    /////////

    #[tokio::test]
    async fn test_memcached_client_get_invalid_keys() {}

    #[tokio::test]
    async fn test_memcached_client_get_no_keys() {}

    #[tokio::test]
    async fn test_memcached_client_get_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_get_no_errors() {}

    #[tokio::test]
    async fn test_memcached_client_get_some_errors() {}

    //////////
    // incr //
    //////////

    #[tokio::test]
    async fn test_memcached_client_incr_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_incr_success() {}

    //////////
    // decr //
    //////////

    #[tokio::test]
    async fn test_memcached_client_decr_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_decr_success() {}

    /////////
    // set //
    /////////

    #[tokio::test]
    async fn test_memcached_client_set_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_set_success() {}

    /////////
    // add //
    /////////

    #[tokio::test]
    async fn test_memcached_client_add_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_add_success() {}

    /////////////
    // replace //
    /////////////

    #[tokio::test]
    async fn test_memcached_client_replace_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_replace_success() {}

    ///////////
    // touch //
    ///////////

    #[tokio::test]
    async fn test_memcached_client_touch_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_touch_success() {}

    ////////////
    // delete //
    ////////////

    #[tokio::test]
    async fn test_memcached_client_delete_no_servers() {}

    #[tokio::test]
    async fn test_memcached_client_delete_success() {}
}