encore-dev 2.0.0-alpha.16

Rust SDK for Encore applications
Documentation
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Redis databases. Declared at module scope; the connection pool is built
//! lazily from the runtime on first use and reused thereafter.
//!
//! ```no_run
//! use encore::storage::redis::Database;
//!
//! static SESSIONS: Database = Database::new("sessions");
//!
//! async fn touch(user: &str) -> Result<Option<String>, encore::Error> {
//!     SESSIONS.string().incr(format!("visits:{user}"), 1).await?;
//!     SESSIONS.string().get(format!("name:{user}")).await
//! }
//! ```
//!
//! A database is a resource of its own: there is no cluster to put it in, and
//! no keyspaces to declare in it. Its keys are whatever the code passes.
//!
//! # Commands
//!
//! Commands are grouped by the data type they work on, each group reached
//! through a method of the database: [`Database::string`], [`Database::hash`],
//! [`Database::list`], [`Database::set`], [`Database::sorted_set`],
//! [`Database::stream`], [`Database::geo`], [`Database::bitmap`], and
//! [`Database::generic`] for the ones that work on any key. Within a group the
//! commands have the names the [`redis`] crate gives them — `get`, `hset`,
//! `zadd`, `xadd` — and take and return what its conversion traits allow
//! ([`ToRedisArgs`], [`FromRedisValue`]). A reply's type is usually the
//! caller's to choose:
//!
//! ```no_run
//! # use encore::storage::redis::Database;
//! # static SESSIONS: Database = Database::new("sessions");
//! # async fn example() -> Result<(), encore::Error> {
//! let name: Option<String> = SESSIONS.string().get("name:1").await?;
//! let visits: u64 = SESSIONS.string().get("visits:1").await?;
//! let fields: std::collections::HashMap<String, String> =
//!     SESSIONS.hash().hgetall("user:1").await?;
//! # Ok(())
//! # }
//! ```
//!
//! A command is called in the same expression that names its group. That is
//! what lets Encore grant each service exactly the access it uses: the command
//! is visible at the call, so the parser can read it. A group that is stored
//! or passed on instead says nothing about what it will be used for, and is
//! reported as an error — to do that, start from a handle.
//!
//! # Handles
//!
//! A database cannot be passed around as a value. To hand it to other code,
//! make a handle with the access that code needs — [`Database::write`],
//! [`Database::read`] or [`Database::read_primary`] — which the service is
//! then granted in full:
//!
//! ```no_run
//! use encore::storage::redis::{Database, ReadOnlyDatabaseRef};
//!
//! static SESSIONS: Database = Database::new("sessions");
//!
//! // Library code takes a handle, and can only do what the handle allows.
//! async fn name_of(db: ReadOnlyDatabaseRef, user: &str) -> Result<Option<String>, encore::Error> {
//!     db.string().get(format!("name:{user}")).await
//! }
//!
//! async fn greet(user: &str) -> Result<Option<String>, encore::Error> {
//!     name_of(SESSIONS.read(), user).await
//! }
//! ```
//!
//! # Keys
//!
//! Every key is stored under a prefix of the database's own, which is what
//! keeps databases sharing a server apart, and gives each test a database of
//! its own. It is applied to every key a command takes and removed from every
//! key a command returns, so code never sees it. Two things follow:
//!
//! * only the keys a [`Script`] is passed, through `KEYS`, get the prefix.
//!   Its source and `ARGV` are sent as they are, so a key the script names
//!   itself or builds from an argument reaches the server unprefixed, outside
//!   the database's isolation, where it may be another database's. Neither
//!   Redis nor this SDK can check what a script touches, so a script must take
//!   every key it uses through `KEYS`;
//! * [`Database::connection_string`] connects past the prefix, so a client
//!   using it does not see the keys this SDK writes under the same names.
//!
//! [`redis`]: https://docs.rs/redis/latest/redis/

mod commands;
#[cfg(test)]
mod tests;
pub mod types;

use std::sync::{Arc, OnceLock};

use encore_sdk_core::cache::{self as core_cache, redis as rs, Client};

use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;

pub use self::commands::{
    bitmap, generic, geo, hash, list, pubsub, set, sorted_set, stream, string, Scan, ScanOptions,
};
pub use self::types::{FromRedisValue, Increment, Json, ToRedisArgs, Value};
pub use rs::{Direction, ExistenceCheck, Expiry, SetExpiry, SetOptions};

use self::commands::{strip_reply_keys, Cmd};

/// What a database evicts when it runs out of memory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvictionPolicy {
    /// Evict nothing: a write that needs memory fails.
    NoEviction,
    /// The least recently used key, of all keys.
    AllKeysLru,
    /// The least frequently used key, of all keys.
    AllKeysLfu,
    /// A random key, of all keys.
    AllKeysRandom,
    /// The least recently used key, of those with an expiry.
    VolatileLru,
    /// The least frequently used key, of those with an expiry.
    VolatileLfu,
    /// The key closest to expiring.
    VolatileTtl,
    /// A random key, of those with an expiry.
    VolatileRandom,
}

/// A Redis database, backed by a lazily-built connection pool.
pub struct Database {
    name: &'static str,
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    persistent: bool,
    #[allow(dead_code)]
    eviction_policy: Option<EvictionPolicy>,
    client: OnceLock<Arc<Client>>,
}

impl Database {
    /// Declare a database. `const` so it can initialize a module-scope
    /// `static`; the pool is built on first use.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```no_run
    /// use encore::storage::redis::{Database, EvictionPolicy};
    ///
    /// static SESSIONS: Database = Database::new("sessions");
    /// static LEDGER: Database = Database::new("ledger").persistent();
    /// static THUMBNAILS: Database =
    ///     Database::new("thumbnails").eviction_policy(EvictionPolicy::AllKeysLfu);
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            persistent: false,
            eviction_policy: None,
            client: OnceLock::new(),
        }
    }

    /// Reference an existing database by name. To declare a new database, use
    /// [`Database::new`] instead.
    ///
    /// The name must be a string literal, so Encore can resolve it statically.
    /// A named database takes no options: it is configured where it is
    /// declared.
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// The data must survive a restart, and is never evicted. Without it a
    /// database is a cache: what it holds may be lost or evicted.
    ///
    /// Part of the declaration: it takes the database by value, so it cannot
    /// be called on the `static`.
    pub const fn persistent(mut self) -> Self {
        self.persistent = true;
        self
    }

    /// What to evict when the database runs out of memory. The least recently
    /// used key, unless said otherwise. A [`Database::persistent`] database
    /// evicts nothing and takes no policy.
    pub const fn eviction_policy(mut self, policy: EvictionPolicy) -> Self {
        self.eviction_policy = Some(policy);
        self
    }

    /// A handle to the database that can read and write.
    ///
    /// `const`, so a handle can initialize a module-scope `static`.
    pub const fn write(&'static self) -> DatabaseRef {
        DatabaseRef { db: self }
    }

    /// A handle to the database that can only read, which may connect to a
    /// read replica. To always read from the primary server, use
    /// [`Database::read_primary`].
    pub const fn read(&'static self) -> ReadOnlyDatabaseRef {
        ReadOnlyDatabaseRef {
            db: self,
            primary: false,
        }
    }

    /// A handle to the database that can only read, and connects to the
    /// primary server even if there are read replicas available.
    pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef {
        ReadOnlyDatabaseRef {
            db: self,
            primary: true,
        }
    }

    /// The client commands run on: the database's own, or under `encore test`
    /// the one of the current test's instance of it (see [`crate::testing`]).
    fn client(&self) -> Result<Arc<Client>, Error> {
        // Never set under `encore test`, where the test's own comes first.
        if let Some(client) = self.client.get() {
            return Ok(client.clone());
        }
        if let Some(test) = testing::active()? {
            return test.redis_client(self.name);
        }
        let client = core()
            .cache()
            .cluster(&self.name.into())
            .client()
            .map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?;
        // A concurrent caller may win the race; either way `get` returns one.
        let _ = self.client.set(Arc::new(client));
        Ok(self.client.get().expect("client just set").clone())
    }
}

/// A handle to a [`Database`] that can read and write, made by
/// [`Database::write`]. `Copy`, and free to pass to other code.
#[derive(Clone, Copy)]
pub struct DatabaseRef {
    db: &'static Database,
}

/// A handle to a [`Database`] that can only read, made by [`Database::read`]
/// or [`Database::read_primary`]. `Copy`, and free to pass to other code.
///
/// Its command groups hold the commands that read, and nothing else.
#[derive(Clone, Copy)]
pub struct ReadOnlyDatabaseRef {
    db: &'static Database,
    /// The runtime gives a database one pool for now, on the primary, which
    /// every handle shares.
    #[allow(dead_code)]
    primary: bool,
}

/// The command groups, as methods returning `$form` of each.
macro_rules! groups {
    ($form:ident<$lt:lifetime>, |$this:ident| $target:expr) => {
        groups!(@each $form<$lt>, |$this| $target;
            /// Commands that work on a key of any type: expiry, deletion, renaming.
            generic,
            /// Commands on strings, which is what a plain value is.
            string,
            /// Commands on the bits of a string.
            bitmap,
            /// Commands on hashes: a key holding fields, each with a value.
            hash,
            /// Commands on lists.
            list,
            /// Commands on sets.
            set,
            /// Commands on sorted sets: members ordered by a score.
            sorted_set,
            /// Commands on geospatial indexes.
            geo,
            /// Commands on streams.
            stream,
            /// Publishing to channels, and subscribing to them.
            pubsub,
        );
    };
    (@each $form:ident<$lt:lifetime>, |$this:ident| $target:expr; $($(#[$doc:meta])* $group:ident,)*) => {
        $(
            $(#[$doc])*
            pub fn $group(&self) -> $group::$form<$lt> {
                let $this = self;
                $group::$form { target: $target }
            }
        )*
    };
}

/// The command groups, as methods returning each one's queue.
macro_rules! queues {
    () => {
        queues!(@each generic, string, bitmap, hash, list, set, sorted_set, geo, stream, pubsub);
    };
    (@each $($group:ident),*) => {
        $(
            /// Queues commands of this group. Nothing is sent until `exec`.
            pub fn $group(&mut self) -> $group::Queue<'_> {
                $group::Queue { queue: &mut self.queued }
            }
        )*

        /// Queues a call to `script`. Finish it with [`QueuedInvocation::queue`].
        pub fn script(&mut self, script: &'static Script) -> QueuedInvocation<'_> {
            QueuedInvocation {
                queue: &mut self.queued,
                script,
                keys: Vec::new(),
                args: Vec::new(),
            }
        }

        /// How many commands are queued.
        pub fn len(&self) -> usize {
            self.queued.commands.len()
        }

        /// Whether nothing is queued.
        pub fn is_empty(&self) -> bool {
            self.queued.commands.is_empty()
        }
    };
}

/// What reading and writing handles share, the [`Database`] among them.
macro_rules! writer_methods {
    ($lt:lifetime, |$this:ident| $db:expr) => {
        groups!(Commands<$lt>, |$this| Target::Database($db));

        /// A batch of commands sent in one round trip. Not a transaction:
        /// other clients' commands may run between them, and one failing does
        /// not stop the rest.
        ///
        /// ```no_run
        /// # use encore::storage::redis::Database;
        /// # static SESSIONS: Database = Database::new("sessions");
        /// # async fn example() -> Result<(), encore::Error> {
        /// let mut pipe = SESSIONS.pipeline();
        /// pipe.string().get("name:1");
        /// pipe.string().get("name:2");
        /// let (first, second): (Option<String>, Option<String>) = pipe.exec().await?;
        /// # Ok(())
        /// # }
        /// ```
        pub fn pipeline(&self) -> Pipeline<$lt> {
            let $this = self;
            Pipeline {
                target: Target::Database($db),
                queued: Queued::default(),
            }
        }

        /// A transaction (`MULTI`/`EXEC`): the commands queued on it run
        /// together, with no other client's in between, or not at all.
        ///
        /// Nothing is sent until [`Transaction::exec`], so a transaction is
        /// never left open across an `.await`.
        ///
        /// ```no_run
        /// # use encore::storage::redis::Database;
        /// # static LEDGER: Database = Database::new("ledger").persistent();
        /// # async fn example(now: u64) -> Result<(), encore::Error> {
        /// let mut tx = LEDGER.transaction();
        /// tx.string().incr("hits", 1);
        /// tx.hash().hset("user:1", "seen", now);
        /// let (hits, _): (i64, u64) = tx.exec().await?;
        /// # Ok(())
        /// # }
        /// ```
        pub fn transaction(&self) -> Transaction<$lt> {
            let $this = self;
            Transaction {
                target: Target::Database($db),
                queued: Queued::default(),
            }
        }

        /// Takes a connection out of the pool, for what must run on one
        /// connection: watching keys, then a transaction that depends on them.
        /// It is returned to the pool when dropped.
        pub async fn acquire(&self) -> Result<Connection, Error> {
            let $this = self;
            let client = ($db).client()?;
            let inner = client.acquire().await.map_err(redis_err)?;
            Ok(Connection {
                inner: tokio::sync::Mutex::new(inner),
                client,
            })
        }

        /// Runs `body` as an optimistic transaction on `keys`: it reads what
        /// it needs through the connection, queues its changes on the
        /// transaction, and the changes are applied only if none of `keys`
        /// changed in between. If one did, `body` runs again.
        ///
        /// ```no_run
        /// # use encore::storage::redis::Database;
        /// # static LEDGER: Database = Database::new("ledger").persistent();
        /// # async fn example() -> Result<(), encore::Error> {
        /// let left: i64 = LEDGER
        ///     .watch("balance", async |conn, tx| {
        ///         let balance: i64 = conn.string().get("balance").await?;
        ///         tx.string().set("balance", balance - 10);
        ///         Ok(balance - 10)
        ///     })
        ///     .await?;
        /// # Ok(())
        /// # }
        /// ```
        pub async fn watch<T>(
            &self,
            keys: impl ToRedisArgs,
            mut body: impl AsyncFnMut(&Connection, &mut WatchedTransaction<'_>) -> Result<T, Error>,
        ) -> Result<T, Error> {
            /// A key changing this many times in a row is not contention that
            /// another attempt will get past.
            const ATTEMPTS: usize = 64;

            let keys = keys.to_redis_args();
            let conn = self.acquire().await?;
            for _ in 0..ATTEMPTS {
                conn.watch(&keys).await?;
                let mut tx = conn.transaction();
                let out = body(&conn, &mut tx).await?;
                if tx.exec::<Value>().await?.is_some() {
                    return Ok(out);
                }
            }
            Err(Error::new(
                ErrCode::Aborted,
                format!("the watched keys kept changing: gave up after {ATTEMPTS} attempts"),
            ))
        }

        /// A call to `script`, to give its keys and arguments and then
        /// [`Invocation::invoke`].
        pub fn script(&self, script: &'static Script) -> Invocation<$lt> {
            let $this = self;
            Invocation {
                target: Target::Database($db),
                script,
                read_only: false,
                keys: Vec::new(),
                args: Vec::new(),
            }
        }

        /// The connection string to connect to this database with, for a
        /// client other than this SDK's.
        ///
        /// It connects past the database's key prefix (see the [module
        /// docs](self#keys)): what that client stores under a name is not what
        /// this SDK reads under it.
        pub fn connection_string(&self) -> Result<String, Error> {
            let $this = self;
            Ok(($db).client()?.connection_url())
        }
    };
}

impl Database {
    writer_methods!('_, |this| this);
}

impl DatabaseRef {
    writer_methods!('static, |this| this.db);
}

impl ReadOnlyDatabaseRef {
    groups!(ReadCommands<'static>, |this| Target::Database(this.db));

    /// A call to `script`, which must be a [`Script::read_only`] one.
    pub fn script(&self, script: &'static Script) -> Invocation<'static> {
        Invocation {
            target: Target::Database(self.db),
            script,
            read_only: true,
            keys: Vec::new(),
            args: Vec::new(),
        }
    }
}

/// Where a command runs: on a connection from the database's pool, or on one
/// taken out of it.
#[derive(Clone, Copy)]
pub(crate) enum Target<'a> {
    Database(&'a Database),
    Connection(&'a Connection),
}

impl Target<'_> {
    fn client(&self) -> Result<Arc<Client>, Error> {
        match self {
            Target::Database(db) => db.client(),
            Target::Connection(conn) => Ok(conn.client.clone()),
        }
    }

    /// Runs `cmd`, returning Redis's reply as it came.
    async fn reply(self, cmd: &core_cache::Command) -> Result<Value, core_cache::OpError> {
        match self {
            Target::Database(db) => match db.client() {
                Ok(client) => client.execute(cmd).await,
                Err(err) => Err(unavailable(cmd, err)),
            },
            Target::Connection(conn) => conn.inner.lock().await.execute(cmd).await,
        }
    }

    /// Runs `cmd` and converts its reply.
    pub(crate) async fn run<T: FromRedisValue>(self, cmd: Cmd) -> Result<T, Error> {
        let mut value = self.reply(&cmd.inner).await.map_err(redis_err)?;
        if cmd.reply_keys {
            strip_reply_keys(&mut value, self.client()?.key_prefix());
        }
        T::from_redis_value(value)
    }

    /// Runs `queued` in one round trip — as a transaction, if `atomic` — and
    /// returns its replies as one array. `None` for a transaction that did
    /// not run because a watched key changed.
    async fn run_all(self, queued: Queued, atomic: bool) -> Result<Option<Value>, Error> {
        let commands: Vec<core_cache::Command> = queued
            .commands
            .iter()
            .map(|cmd| cmd.inner.clone())
            .collect();
        let client = self.client()?;
        let replies = match self {
            Target::Database(_) => Some(client.execute_all(&commands, atomic).await),
            Target::Connection(conn) => conn
                .inner
                .lock()
                .await
                .execute_all(&commands, atomic)
                .await
                .transpose(),
        };
        let Some(replies) = replies else {
            return Ok(None);
        };
        let mut replies = replies.map_err(redis_err)?;
        for (cmd, reply) in queued.commands.iter().zip(&mut replies) {
            if cmd.reply_keys {
                strip_reply_keys(reply, client.key_prefix());
            }
        }
        Ok(Some(Value::Array(replies)))
    }
}

/// The error for a command that could not be sent at all, in the shape the
/// ones that were sent fail with.
fn unavailable(cmd: &core_cache::Command, err: Error) -> core_cache::OpError {
    core_cache::OpError::new(
        cmd.operation(),
        "",
        core_cache::Error::Redis(std::io::Error::other(err.message).into()),
    )
}

/// The commands queued on a [`Pipeline`] or a transaction.
#[derive(Default)]
pub(crate) struct Queued {
    commands: Vec<Cmd>,
}

impl Queued {
    pub(crate) fn push(&mut self, cmd: Cmd) {
        self.commands.push(cmd);
    }
}

/// A batch of commands sent in one round trip, made by
/// [`Database::pipeline`]. Not a transaction.
pub struct Pipeline<'a> {
    target: Target<'a>,
    queued: Queued,
}

impl Pipeline<'_> {
    queues!();

    /// Sends the queued commands and returns their replies, in order, as a
    /// tuple or a `Vec`.
    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
        let replies = self.target.run_all(self.queued, false).await?;
        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
    }
}

/// A transaction, made by [`Database::transaction`]: the commands queued on it
/// run together or not at all.
pub struct Transaction<'a> {
    target: Target<'a>,
    queued: Queued,
}

impl Transaction<'_> {
    queues!();

    /// Runs the queued commands as one transaction and returns their replies,
    /// in order, as a tuple or a `Vec`.
    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
        let replies = self.target.run_all(self.queued, true).await?;
        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
    }

    /// Abandons the transaction. Nothing was sent, so there is nothing to
    /// undo: this is dropping it, by name.
    pub fn discard(self) {}
}

/// A transaction on a [`Connection`], made by [`Connection::transaction`]: it
/// does nothing if a key the connection watches has changed.
pub struct WatchedTransaction<'a> {
    target: Target<'a>,
    queued: Queued,
}

impl WatchedTransaction<'_> {
    queues!();

    /// Runs the queued commands as one transaction and returns their replies.
    /// `None` if a watched key changed, in which case none of them ran. Either
    /// way the connection watches nothing afterwards.
    pub async fn exec<T: FromRedisValue>(&mut self) -> Result<Option<T>, Error> {
        let queued = std::mem::take(&mut self.queued);
        match self.target.run_all(queued, true).await? {
            Some(replies) => T::from_redis_value(replies).map(Some),
            None => Ok(None),
        }
    }
}

/// A connection taken out of the database's pool, made by
/// [`Database::acquire`]. It is returned to the pool when dropped.
pub struct Connection {
    inner: tokio::sync::Mutex<core_cache::Connection>,
    client: Arc<Client>,
}

impl Connection {
    groups!(Commands<'_>, |this| Target::Connection(this));

    /// Watches `keys`: a [`Connection::transaction`] then does nothing if any
    /// of them has changed by the time it is run.
    pub async fn watch(&self, keys: impl ToRedisArgs) -> Result<(), Error> {
        self.inner
            .lock()
            .await
            .watch(&keys.to_redis_args())
            .await
            .map_err(redis_err)
    }

    /// Stops watching every key.
    pub async fn unwatch(&self) -> Result<(), Error> {
        self.inner.lock().await.unwatch().await.map_err(redis_err)
    }

    /// A transaction on this connection, which depends on the keys it watches.
    pub fn transaction(&self) -> WatchedTransaction<'_> {
        WatchedTransaction {
            target: Target::Connection(self),
            queued: Queued::default(),
        }
    }

    /// A batch of commands sent in one round trip on this connection.
    pub fn pipeline(&self) -> Pipeline<'_> {
        Pipeline {
            target: Target::Connection(self),
            queued: Queued::default(),
        }
    }

    /// A call to `script` on this connection.
    pub fn script(&self, script: &'static Script) -> Invocation<'_> {
        Invocation {
            target: Target::Connection(self),
            script,
            read_only: false,
            keys: Vec::new(),
            args: Vec::new(),
        }
    }
}

/// A Lua script the database runs, declared at module scope.
///
/// ```no_run
/// use encore::storage::redis::{Database, Script};
///
/// static LOCKS: Database = Database::new("locks");
///
/// static RELEASE: Script = Script::new(
///     r#"
///     if redis.call("get", KEYS[1]) == ARGV[1] then
///         return redis.call("del", KEYS[1])
///     end
///     return 0
///     "#,
/// );
///
/// async fn release(job: &str, token: &str) -> Result<bool, encore::Error> {
///     LOCKS.script(&RELEASE).key(format!("lock:{job}")).arg(token).invoke().await
/// }
/// ```
///
/// Only the keys a script is passed, through `KEYS`, get the database's key
/// prefix (see the [module docs](self#keys)). Its source and `ARGV` are sent as
/// they are: a key the script names itself, or builds from an argument,
/// reaches the server unprefixed, outside the database's isolation. Nothing
/// checks this, so a script must take every key it uses through `KEYS`.
pub struct Script {
    source: &'static str,
    read_only: bool,
    /// The source's SHA-1, which the server caches the script under.
    hash: OnceLock<String>,
}

impl Script {
    /// Declare a script. `const`, so it can initialize a module-scope `static`.
    pub const fn new(source: &'static str) -> Self {
        Self {
            source,
            read_only: false,
            hash: OnceLock::new(),
        }
    }

    /// Declare a script that only reads. The server refuses to let it write,
    /// which is what lets it run on a [`ReadOnlyDatabaseRef`].
    pub const fn read_only(source: &'static str) -> Self {
        Self {
            source,
            read_only: true,
            hash: OnceLock::new(),
        }
    }

    fn hash(&self) -> &str {
        self.hash
            .get_or_init(|| rs::Script::new(self.source).get_hash().to_string())
    }

    /// The command that runs the script: by its hash, which the server has if
    /// it has run it before, or by its source.
    fn command(&self, by_hash: bool, keys: &[Vec<u8>], args: &[Vec<u8>]) -> core_cache::Command {
        let name = match (by_hash, self.read_only) {
            (true, false) => "EVALSHA",
            (true, true) => "EVALSHA_RO",
            (false, false) => "EVAL",
            (false, true) => "EVAL_RO",
        };
        let mut cmd = core_cache::Command::new("script", name, !self.read_only)
            .arg(if by_hash { self.hash() } else { self.source })
            .arg(keys.len().to_string());
        for key in keys {
            cmd = cmd.key(key.as_slice());
        }
        for arg in args {
            cmd = cmd.arg(arg.as_slice());
        }
        cmd
    }
}

/// A call to a [`Script`], made by [`Database::script`].
pub struct Invocation<'a> {
    target: Target<'a>,
    script: &'static Script,
    /// Whether the handle it was made from can only read.
    read_only: bool,
    keys: Vec<Vec<u8>>,
    args: Vec<Vec<u8>>,
}

impl Invocation<'_> {
    /// A key the script works on: the next of its `KEYS`.
    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
        self.keys.extend(key.to_redis_args());
        self
    }

    /// An argument: the next of the script's `ARGV`, sent without the
    /// database's key prefix.
    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
        self.args.extend(arg.to_redis_args());
        self
    }

    /// Runs the script and converts what it returns.
    pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
        if self.read_only && !self.script.read_only {
            return Err(Error::new(
                ErrCode::FailedPrecondition,
                "a handle that can only read runs only scripts declared with `Script::read_only`",
            ));
        }
        let by_hash = self.script.command(true, &self.keys, &self.args);
        let value = match self.target.reply(&by_hash).await {
            Ok(value) => value,
            // The server has not seen the script: send it, which also caches it.
            Err(err) if is_no_script(&err) => {
                let by_source = self.script.command(false, &self.keys, &self.args);
                self.target.reply(&by_source).await.map_err(redis_err)?
            }
            Err(err) => return Err(redis_err(err)),
        };
        T::from_redis_value(value)
    }
}

/// A call to a [`Script`] being queued on a pipeline or a transaction.
pub struct QueuedInvocation<'a> {
    queue: &'a mut Queued,
    script: &'static Script,
    keys: Vec<Vec<u8>>,
    args: Vec<Vec<u8>>,
}

impl QueuedInvocation<'_> {
    /// A key the script works on: the next of its `KEYS`.
    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
        self.keys.extend(key.to_redis_args());
        self
    }

    /// An argument: the next of the script's `ARGV`, sent without the
    /// database's key prefix.
    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
        self.args.extend(arg.to_redis_args());
        self
    }

    /// Queues the call. Sent by source rather than by hash: a batch cannot
    /// stop halfway to send a script the server turns out not to have.
    pub fn queue(self) {
        let inner = self.script.command(false, &self.keys, &self.args);
        self.queue.push(Cmd::from_core(inner));
    }
}

/// Whether a command failed because the server does not have the script its
/// hash names.
fn is_no_script(err: &core_cache::OpError) -> bool {
    matches!(
        &err.source,
        core_cache::Error::Redis(err)
            if err.kind() == rs::ErrorKind::Server(rs::ServerErrorKind::NoScript)
    )
}

fn redis_err(err: core_cache::OpError) -> Error {
    Error::wrap(ErrCode::Unavailable, err)
}