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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! ReQL is the RethinkDB query language. It offers a very powerful and
//! convenient way to manipulate JSON documents.
//!
//! # Start the server #
//!
//! ## Linux and OS X ##
//!
//! Start the server from a terminal window.
//!
//! ```bash
//! $ rethinkdb
//! ```
//!
//! ## Windows ##
//!
//! Start the server from the Windows command prompt.
//!
//! ```bash
//! C:\Path\To\RethinkDB\>rethinkdb.exe
//! ```
//!
//! # Import the driver #
//!
//! First, make sure you have `protoc` installed and in your `PATH`. See
//! [`prost-build` documentation](https://docs.rs/prost-build/0.7.0/prost_build/#sourcing-protoc)
//! for more details if it fails to compile.
//!
//! Add this crate (`reql`) and the `futures` crate to your dependencies in `Cargo.toml`.
//!
//! Now import the RethinkDB driver:
//!
//! ```
//! use reql::r;
//! ```
//!
//! You can now access RethinkDB commands through the [`r` struct](r).
//!
//! # Open a connection #
//!
//! When you first start RethinkDB, the server opens a port for the client
//! drivers (`28015` by default). Let's open a connection:
//!
//! ```
//! use reql::r;
//!
//! # async fn example() -> reql::Result<()> {
//! let session = r.connect(()).await?;
//! # Ok(()) };
//! ```
//!
//! The variable `connection` is now initialized and we can run queries.
//!
//! # Send a query to the database #
//!
//! ```
//! # reql::example(|r, conn| async_stream::stream! {
//! r.expr("Hello world!").run(conn)
//! # });
//! ```
//!
//! [See the `r` struct for more available commands](r)

#![allow(clippy::wrong_self_convention)]

pub mod cmd;
mod err;
mod proto;

use async_net::TcpStream;
use cmd::run::Response;
use cmd::StaticString;
use dashmap::DashMap;
use futures::channel::mpsc::{self, UnboundedReceiver, UnboundedSender};
use futures::lock::Mutex;
use log::trace;
use proto::Payload;
use ql2::query::QueryType;
use ql2::response::ResponseType;
use serde_json::json;
use std::borrow::Cow;
use std::ops::Drop;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use types::ServerInfo;

pub use err::*;
#[doc(hidden)]
pub use proto::Func;
pub use proto::Query;
#[doc(hidden)]
pub use ql2::term::TermType;
pub use reql_macros::*;
#[doc(inline)]
pub use reql_types as types;

#[doc(hidden)]
pub static VAR_COUNTER: AtomicU64 = AtomicU64::new(0);

#[doc(hidden)]
pub fn var_counter() -> u64 {
    VAR_COUNTER.fetch_add(1, Ordering::SeqCst)
}

/// Custom result returned by various ReQL commands
pub type Result<T> = std::result::Result<T, Error>;

type Sender = UnboundedSender<Result<(ResponseType, Response)>>;
type Receiver = UnboundedReceiver<Result<(ResponseType, Response)>>;

#[derive(Debug)]
struct InnerSession {
    db: Mutex<Cow<'static, str>>,
    stream: Mutex<TcpStream>,
    channels: DashMap<u64, Sender>,
    token: AtomicU64,
    broken: AtomicBool,
    change_feed: AtomicBool,
}

impl InnerSession {
    fn token(&self) -> u64 {
        let token = self
            .token
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1))
            .unwrap();
        if token == u64::MAX {
            self.mark_broken();
        }
        token
    }

    fn mark_broken(&self) {
        self.broken.store(true, Ordering::SeqCst);
    }

    fn broken(&self) -> Result<()> {
        if self.broken.load(Ordering::SeqCst) {
            return Err(err::Driver::ConnectionBroken.into());
        }
        Ok(())
    }

    fn mark_change_feed(&self) {
        self.change_feed.store(true, Ordering::SeqCst);
    }

    fn unmark_change_feed(&self) {
        self.change_feed.store(false, Ordering::SeqCst);
    }

    fn is_change_feed(&self) -> bool {
        self.change_feed.load(Ordering::SeqCst)
    }

    fn change_feed(&self) -> Result<()> {
        if self.change_feed.load(Ordering::SeqCst) {
            return Err(err::Driver::ConnectionLocked.into());
        }
        Ok(())
    }
}

/// The connection object returned by `r.connect()`
#[derive(Debug, Clone)]
pub struct Session {
    inner: Arc<InnerSession>,
}

impl Session {
    pub fn connection(&self) -> Result<Connection> {
        self.inner.broken()?;
        self.inner.change_feed()?;
        let token = self.inner.token();
        let (tx, rx) = mpsc::unbounded();
        self.inner.channels.insert(token, tx);
        Ok(Connection::new(self.clone(), rx, token))
    }

    /// Change the default database on this connection
    ///
    /// ## Example
    ///
    /// Change the default database so that we don’t need to specify the
    /// database when referencing a table.
    ///
    /// ```
    /// # reql::example(|r, conn| async_stream::stream! {
    /// conn.use_("marvel").await;
    /// r.table("heroes").run(conn) // refers to r.db("marvel").table("heroes")
    /// # });
    /// ```
    ///
    /// ## Related commands
    /// * [connect](r::connect)
    /// * [close](Connection::close)
    pub async fn use_<T>(&mut self, db_name: T)
    where
        T: StaticString,
    {
        *self.inner.db.lock().await = db_name.static_string();
    }

    /// Ensures that previous queries with the `noreply` flag have been
    /// processed by the server
    ///
    /// Note that this guarantee only applies to queries run on the given
    /// connection.
    ///
    /// ## Example
    ///
    /// We have previously run queries with [noreply](cmd::run::Options::noreply())
    /// set to `true`. Now wait until the server has processed them.
    ///
    /// ```
    /// # async fn example() -> reql::Result<()> {
    /// # let session = reql::r.connect(()).await?;
    /// session.noreply_wait().await
    /// # }
    /// ```
    ///
    pub async fn noreply_wait(&self) -> Result<()> {
        let mut conn = self.connection()?;
        let payload = Payload(QueryType::NoreplyWait, None, Default::default());
        trace!(
            "waiting for noreply operations to finish; token: {}",
            conn.token
        );
        let (typ, _) = conn.request(&payload, false).await?;
        trace!(
            "session.noreply_wait() run; token: {}, response type: {:?}",
            conn.token,
            typ,
        );
        Ok(())
    }

    pub async fn server(&self) -> Result<ServerInfo> {
        let mut conn = self.connection()?;
        let payload = Payload(QueryType::ServerInfo, None, Default::default());
        trace!("retrieving server information; token: {}", conn.token);
        let (typ, resp) = conn.request(&payload, false).await?;
        trace!(
            "session.server() run; token: {}, response type: {:?}",
            conn.token,
            typ,
        );
        let mut vec = serde_json::from_value::<Vec<ServerInfo>>(resp.r)?;
        let info = vec
            .pop()
            .ok_or_else(|| Driver::Other("server info is empty".into()))?;
        Ok(info)
    }

    #[doc(hidden)]
    pub fn is_broken(&self) -> bool {
        self.inner.broken.load(Ordering::SeqCst)
    }
}

#[derive(Debug, Clone)]
pub struct Connection {
    session: Session,
    rx: Arc<Mutex<Receiver>>,
    token: u64,
    closed: Arc<AtomicBool>,
}

impl Connection {
    fn new(session: Session, rx: Receiver, token: u64) -> Connection {
        Connection {
            session,
            token,
            rx: Arc::new(Mutex::new(rx)),
            closed: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Close an open connection
    ///
    /// ## Example
    ///
    /// Close an open connection, waiting for noreply writes to finish.
    ///
    /// ```
    /// # async fn example() -> reql::Result<()> {
    /// # let session = reql::r.connect(()).await?;
    /// # let mut conn = session.connection()?;
    /// conn.close(()).await
    /// # }
    /// ```
    ///
    /// [Read more about this command →](cmd::close)
    pub async fn close<T>(&mut self, arg: T) -> Result<()>
    where
        T: cmd::close::Arg,
    {
        if !self.session.inner.is_change_feed() {
            trace!(
                "ignoring conn.close() called on a normal connection; token: {}",
                self.token
            );
            return Ok(());
        }
        self.set_closed(true);
        let arg = if arg.noreply_wait() {
            None
        } else {
            Some(r.expr(json!({ "noreply": false })))
        };
        let payload = Payload(QueryType::Stop, arg, Default::default());
        trace!("closing a changefeed; token: {}", self.token);
        let (typ, _) = self.request(&payload, false).await?;
        self.session.inner.unmark_change_feed();
        trace!(
            "conn.close() run; token: {}, response type: {:?}",
            self.token,
            typ,
        );
        Ok(())
    }

    fn closed(&self) -> bool {
        self.closed.load(Ordering::SeqCst)
    }

    fn set_closed(&self, closed: bool) {
        self.closed.store(closed, Ordering::SeqCst);
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        self.session.inner.channels.remove(&self.token);
        if self.session.inner.is_change_feed() {
            self.session.inner.unmark_change_feed();
        }
    }
}

/// The top-level ReQL namespace
///
/// # Example
///
/// Set up your top-level namespace.
///
/// ```
/// use reql::r;
/// ```
#[allow(non_camel_case_types)]
pub struct r;

impl r {
    /// Create a new connection to the database server
    ///
    /// # Example
    ///
    /// Open a connection using the default host and port, specifying the default database.
    ///
    /// ```
    /// use reql::{r, cmd::connect::Options};
    ///
    /// # async fn example() -> reql::Result<()> {
    /// let session = r.connect(Options::new().db("marvel")).await?;
    /// # Ok(()) }
    /// ```
    ///
    /// Read more about this command [connect](cmd::connect)
    pub async fn connect<T>(self, options: T) -> Result<Session>
    where
        T: cmd::connect::Arg,
    {
        cmd::connect::new(options.into_connect_opts()).await
    }

    pub fn db_create<T>(self, arg: T) -> Query
    where
        T: cmd::db_create::Arg,
    {
        arg.into_query()
    }

    pub fn db_drop<T>(self, arg: T) -> Query
    where
        T: cmd::db_drop::Arg,
    {
        arg.into_query()
    }

    pub fn db_list(self) -> Query {
        Query::new(TermType::DbList)
    }

    /// Reference a database
    ///
    /// The `db` command is optional. If it is not present in a query, the
    /// query will run against the default database for the connection,
    /// specified in the `db` argument to [connect](r::connect).
    ///
    /// # Examples
    ///
    /// Explicitly specify a database for a query.
    ///
    /// ```
    /// # reql::example(|r, conn| async_stream::stream! {
    /// r.db("heroes").table("marvel").run(conn)
    /// # });
    /// ```
    pub fn db<T>(self, arg: T) -> Query
    where
        T: cmd::db::Arg,
    {
        arg.into_query()
    }

    /// See [Query::table_create]
    pub fn table_create<T>(self, arg: T) -> Query
    where
        T: cmd::table_create::Arg,
    {
        arg.into_query()
    }

    pub fn table<T>(self, arg: T) -> Query
    where
        T: cmd::table::Arg,
    {
        arg.into_query()
    }

    pub fn map<T>(self, arg: T) -> Query
    where
        T: cmd::map::Arg,
    {
        arg.into_query()
    }

    pub fn union<T>(self, arg: T) -> Query
    where
        T: cmd::union::Arg,
    {
        arg.into_query()
    }

    pub fn group<T>(self, arg: T) -> Query
    where
        T: cmd::group::Arg,
    {
        arg.into_query()
    }

    pub fn reduce<T>(self, arg: T) -> Query
    where
        T: cmd::reduce::Arg,
    {
        arg.into_query()
    }

    pub fn count<T>(self, arg: T) -> Query
    where
        T: cmd::count::Arg,
    {
        arg.into_query()
    }

    pub fn sum<T>(self, arg: T) -> Query
    where
        T: cmd::sum::Arg,
    {
        arg.into_query()
    }

    pub fn avg<T>(self, arg: T) -> Query
    where
        T: cmd::avg::Arg,
    {
        arg.into_query()
    }

    pub fn min<T>(self, arg: T) -> Query
    where
        T: cmd::min::Arg,
    {
        arg.into_query()
    }

    pub fn max<T>(self, arg: T) -> Query
    where
        T: cmd::max::Arg,
    {
        arg.into_query()
    }

    pub fn distinct<T>(self, arg: T) -> Query
    where
        T: cmd::distinct::Arg,
    {
        arg.into_query()
    }

    pub fn contains<T>(self, arg: T) -> Query
    where
        T: cmd::contains::Arg,
    {
        arg.into_query()
    }

    pub fn literal<T>(self, arg: T) -> Query
    where
        T: cmd::literal::Arg,
    {
        arg.into_query()
    }

    pub fn object<T>(self, arg: T) -> Query
    where
        T: cmd::object::Arg,
    {
        arg.into_query()
    }

    pub fn random<T>(self, arg: T) -> Query
    where
        T: cmd::random::Arg,
    {
        arg.into_query()
    }

    pub fn round<T>(self, arg: T) -> Query
    where
        T: cmd::round::Arg,
    {
        arg.into_query()
    }

    pub fn ceil<T>(self, arg: T) -> Query
    where
        T: cmd::ceil::Arg,
    {
        arg.into_query()
    }

    pub fn floor<T>(self, arg: T) -> Query
    where
        T: cmd::floor::Arg,
    {
        arg.into_query()
    }

    pub fn now(self) -> Query {
        Query::new(TermType::Now)
    }

    pub fn time<T>(self, arg: T) -> Query
    where
        T: cmd::time::Arg,
    {
        arg.into_query()
    }

    pub fn epoch_time<T>(self, arg: T) -> Query
    where
        T: cmd::epoch_time::Arg,
    {
        arg.into_query()
    }

    pub fn iso8601<T>(self, arg: T) -> Query
    where
        T: cmd::iso8601::Arg,
    {
        arg.into_query()
    }

    pub fn do_<T>(self, arg: T) -> Query
    where
        T: cmd::do_::Arg,
    {
        arg.into_query()
    }

    pub fn branch<T>(self, arg: T) -> Query
    where
        T: cmd::branch::Arg,
    {
        arg.into_query()
    }

    pub fn range<T>(self, arg: T) -> Query
    where
        T: cmd::range::Arg,
    {
        arg.into_query()
    }

    pub fn error<T>(self, arg: T) -> Query
    where
        T: cmd::error::Arg,
    {
        arg.into_query()
    }

    pub fn expr<T>(self, arg: T) -> Query
    where
        T: cmd::expr::Arg,
    {
        arg.into_query()
    }

    pub fn js<T>(self, arg: T) -> Query
    where
        T: cmd::js::Arg,
    {
        arg.into_query()
    }

    pub fn info<T>(self, arg: T) -> Query
    where
        T: cmd::info::Arg,
    {
        arg.into_query()
    }

    pub fn json<T>(self, arg: T) -> Query
    where
        T: cmd::json::Arg,
    {
        arg.into_query()
    }

    pub fn http<T>(self, arg: T) -> Query
    where
        T: cmd::http::Arg,
    {
        arg.into_query()
    }

    pub fn uuid<T>(self, arg: T) -> Query
    where
        T: cmd::uuid::Arg,
    {
        arg.into_query()
    }

    pub fn circle<T>(self, arg: T) -> Query
    where
        T: cmd::circle::Arg,
    {
        arg.into_query()
    }

    pub fn distance<T>(self, arg: T) -> Query
    where
        T: cmd::distance::Arg,
    {
        arg.into_query()
    }

    pub fn geojson<T>(self, arg: T) -> Query
    where
        T: cmd::geojson::Arg,
    {
        arg.into_query()
    }

    pub fn intersects<T>(self, arg: T) -> Query
    where
        T: cmd::intersects::Arg,
    {
        arg.into_query()
    }

    pub fn line<T>(self, arg: T) -> Query
    where
        T: cmd::line::Arg,
    {
        arg.into_query()
    }

    pub fn point<T>(self, arg: T) -> Query
    where
        T: cmd::point::Arg,
    {
        arg.into_query()
    }

    pub fn polygon<T>(self, arg: T) -> Query
    where
        T: cmd::polygon::Arg,
    {
        arg.into_query()
    }

    pub fn grant<T>(self, arg: T) -> Query
    where
        T: cmd::grant::Arg,
    {
        arg.into_query()
    }

    pub fn wait<T>(self, arg: T) -> Query
    where
        T: cmd::wait::Arg,
    {
        arg.into_query()
    }

    pub fn asc<T>(self, arg: T) -> cmd::asc::Asc
    where
        T: cmd::asc::Arg,
    {
        cmd::asc::Asc(arg.into_query())
    }

    pub fn desc<T>(self, arg: T) -> cmd::desc::Desc
    where
        T: cmd::desc::Arg,
    {
        cmd::desc::Desc(arg.into_query())
    }

    pub fn index<T>(self, arg: T) -> cmd::index::Index
    where
        T: cmd::index::Arg,
    {
        cmd::index::Index(arg.into_query())
    }

    pub fn args<T>(self, arg: T) -> cmd::args::Args<T> {
        cmd::args::Args(arg)
    }
}

// Helper for making writing examples less verbose
#[doc(hidden)]
pub fn example<'a, Q, F, S>(_query: Q)
where
    Q: FnOnce(r, &'a mut Session) -> async_stream::AsyncStream<(), F>,
    F: futures::Future<Output = S>,
    S: futures::Stream<Item = Result<serde_json::Value>>,
{
}