encore-dev 2.0.0

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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
//! Redis databases.
//!
//! Databases are declared at module scope. Connection pools are initialized
//! lazily on first use and reused across calls.
//!
//! ```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
//! }
//! ```
//!
//! Each Redis database is a standalone resource with no separate cluster or
//! keyspace declarations; use whatever key naming scheme your application needs.
//!
//! # Commands
//!
//! Commands are grouped by data type and accessed through methods on
//! [`Database`]: [`Database::string`], [`Database::hash`], [`Database::list`],
//! [`Database::set`], [`Database::sorted_set`], [`Database::stream`],
//! [`Database::geo`], [`Database::bitmap`], [`Database::hyperloglog`], and
//! [`Database::generic`] for key-agnostic commands. Command names follow the
//! [`redis`] crate (`get`, `hset`, `zadd`, `xadd`), using [`ToRedisArgs`] and
//! [`FromRedisValue`] for conversions. In most cases, you choose the return
//! type at the call site:
//!
//! ```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(())
//! # }
//! ```
//!
//! Call each command directly on the group expression (for example,
//! `SESSIONS.string().get(...)`). This allows Encore to analyze command usage
//! statically and grant each service only the permissions it needs. Storing or
//! passing a command group value directly is a static analysis error—use a
//! database handle instead.
//!
//! Blocking commands such as [`list::Commands::blpop`],
//! [`sorted_set::Commands::bzpopmin`], and [`stream::Commands::xread_block`]
//! run on a dedicated connection so they never block other calls. Dropping the
//! future cancels the wait and closes that connection. Blocking commands cannot
//! be queued in pipelines or transactions, and cannot run on an
//! [acquired](Database::acquire) connection.
//!
//! # Arbitrary commands
//!
//! Use [`Database::command`] to run a Redis command not covered by the typed
//! groups, marking key arguments explicitly with `.key(...)`:
//!
//! ```no_run
//! # use encore::storage::redis::Database;
//! # static SESSIONS: Database = Database::new("sessions");
//! # async fn example() -> Result<(), encore::Error> {
//! let freq: i64 = SESSIONS.command("OBJECT").arg("FREQ").key("hot").invoke().await?;
//! # Ok(())
//! # }
//! ```
//!
//! The command name must be a string literal so Encore can grant the required
//! permissions statically. Before sending, Encore validates the command against
//! Redis's command table:
//!
//! - Every key argument must be passed via `.key(...)` so it receives the
//!   database's key prefix.
//! - Commands that bypass database isolation, mutate shared connection state,
//!   or have dedicated SDK methods (`MULTI`, `SUBSCRIBE`, `EVAL`, `SCAN`,
//!   `FLUSHALL`, etc.) are rejected with [`ErrCode::InvalidArgument`].
//! - Read-only handles reject commands marked as writes by Redis.
//! - Unknown commands (such as Redis module commands) are sent as-is with the
//!   marked keys prefixed.
//!
//! # Errors
//!
//! - Server rejections (such as `WRONGTYPE` or script errors) return
//!   [`ErrCode::Internal`] with the server's message.
//! - Aborted transactions return [`ErrCode::Aborted`].
//! - Connection failures return [`ErrCode::Unavailable`].
//!
//! # Handles
//!
//! A [`Database`] cannot be passed around by value. To pass it to helper
//! functions or libraries, create a handle with the access level it
//! needs—[`Database::write`], [`Database::read`], or
//! [`Database::read_primary`]—which grants that access level to the service:
//!
//! ```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
//!
//! Encore automatically namespaces every key with a per-database prefix to
//! isolate databases sharing a server and to isolate each test. The prefix is
//! added to outgoing keys and stripped from returned keys, so application code
//! never sees it. Keep two caveats in mind:
//!
//! * In a [`Script`], only keys passed through `KEYS` are prefixed. Script
//!   source code and `ARGV` values are sent untouched, so any key hardcoded in
//!   the script or built from `ARGV` bypasses database isolation. Always pass
//!   every key a script accesses through `KEYS`.
//! * [`Database::connection_string`] connects directly to Redis without
//!   applying the prefix, so external clients will not see keys under their
//!   unprefixed 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, Access, Client, redis as rs};

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

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

use self::commands::Cmd;

/// 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,
    client: OnceLock<Arc<Client>>,
    /// The clients its read handles run on, made from `client`:
    /// [`Access::Read`]'s, then [`Access::ReadPrimary`]'s.
    readers: [OnceLock<Arc<Client>>; 2],
}

impl Database {
    /// Declares a new Redis database.
    ///
    /// This function is `const` so it can initialize a module-scope `static`.
    /// The connection pool is created on first use. Chain builder methods to
    /// configure options:
    ///
    /// ```no_run
    /// use encore::storage::redis::Database;
    ///
    /// static SESSIONS: Database = Database::new("sessions");
    /// static LEDGER: Database = Database::new("ledger").persistent();
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            persistent: false,
            client: OnceLock::new(),
            readers: [OnceLock::new(), OnceLock::new()],
        }
    }

    /// References an existing Redis database by name. To declare a new
    /// database, use [`Database::new`] instead.
    ///
    /// `name` must be a string literal so Encore can resolve it statically.
    /// Referenced databases take no configuration options; options are set
    /// where the database is declared.
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Marks the database as persistent so its data survives restarts and is
    /// never evicted. Without this option, the database behaves as a cache and
    /// entries may be evicted or lost on restart.
    ///
    /// Must be called as part of the `static` declaration.
    pub const fn persistent(mut self) -> Self {
        self.persistent = true;
        self
    }

    /// Attaches a classification tag (`key`, `value`) to the database, such as
    /// `.tag("data", "pii")`, for policy evaluation.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be
    /// string literals of at most 63 characters (up to 32 tags per database).
    /// Keys may contain lowercase letters, digits, `_`, and `-`, must start
    /// with a letter, and cannot start with `encore` (reserved for Encore).
    /// Values use the same character set or may be empty.
    ///
    /// Must be called as part of the `static` declaration.
    ///
    /// ```no_run
    /// use encore::storage::redis::Database;
    ///
    /// static SESSIONS: Database = Database::new("sessions").tag("data", "pii");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        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. It reads from a read
    /// replica where the database has a read-only connection pool on one, and
    /// otherwise from the primary. Either way a command that writes is
    /// refused before it is sent. To always read from the primary server, use
    /// [`Database::read_primary`].
    pub const fn read(&'static self) -> ReadOnlyDatabaseRef {
        ReadOnlyDatabaseRef {
            db: self,
            access: Access::Read,
        }
    }

    /// A handle to the database that can only read, and reads from the
    /// primary server even where there are read replicas. A command that
    /// writes is refused before it is sent.
    pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef {
        ReadOnlyDatabaseRef {
            db: self,
            access: Access::ReadPrimary,
        }
    }

    /// 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())
    }

    /// The client a handle with `access` runs on, made from
    /// [`Database::client`]: see [`Client::with_access`].
    fn client_for(&self, access: Access) -> Result<Arc<Client>, Error> {
        let slot = match access {
            Access::ReadWrite => return self.client(),
            Access::Read => &self.readers[0],
            Access::ReadPrimary => &self.readers[1],
        };
        if let Some(reader) = slot.get() {
            return Ok(reader.clone());
        }
        let client = self.client()?;
        let reader = Arc::new(
            client
                .with_access(access)
                .map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?,
        );
        // Kept only beside the database's own client: under `encore test`
        // each test has its own instance.
        if !self
            .client
            .get()
            .is_some_and(|own| Arc::ptr_eq(own, &client))
        {
            return Ok(reader);
        }
        let _ = slot.set(reader);
        Ok(slot.get().expect("reader 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,
    /// [`Access::Read`] or [`Access::ReadPrimary`].
    access: Access,
}

/// 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,
            /// Commands on HyperLogLogs: estimates of how many distinct elements
            /// were added.
            hyperloglog,
            /// 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, hyperloglog, 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(),
            }
        }

        /// Queues a command the groups lack, by its name: see
        /// [`Database::command`]. Finish it with
        /// [`QueuedCommandInvocation::queue`]. A command that blocks can't be
        /// queued: the batch fails.
        pub fn command(&mut self, name: &'static str) -> QueuedCommandInvocation<'_> {
            QueuedCommandInvocation {
                queue: &mut self.queued,
                cmd: core_cache::Command::raw(name),
            }
        }

        /// 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,
            Access::ReadWrite
        ));

        /// 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, Access::ReadWrite),
                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, Access::ReadWrite),
                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 watching `keys`.
        ///
        /// Read values through the connection and queue writes on the
        /// transaction. Changes are applied atomically only if none of `keys`
        /// changed in the meantime; otherwise, `body` is retried.
        ///
        /// ```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!("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, Access::ReadWrite),
                script,
                read_only: false,
                keys: Vec::new(),
                args: Vec::new(),
            }
        }

        /// Builds an arbitrary Redis command by name (for example, `"OBJECT"`).
        ///
        /// `name` must be a string literal. Pass arguments in order using
        /// [`CommandInvocation::key`] and [`CommandInvocation::arg`], then call
        /// [`CommandInvocation::invoke`]. See the
        /// [module docs](self#arbitrary-commands) for validation rules.
        pub fn command(&self, name: &'static str) -> CommandInvocation<$lt> {
            let $this = self;
            CommandInvocation {
                target: Target::Database($db, Access::ReadWrite),
                cmd: core_cache::Command::raw(name),
            }
        }

        /// Returns a Redis connection URL for use with external clients.
        ///
        /// External clients connect directly without this SDK's key prefix
        /// (see the [module docs](self#keys)), so keys written there do not
        /// match the unprefixed names used by this SDK.
        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,
        this.access
    ));

    /// A command the groups lack, by its name: see [`Database::command`]. Only
    /// a command Redis says doesn't write is sent.
    pub fn command(&self, name: &'static str) -> CommandInvocation<'static> {
        CommandInvocation {
            target: Target::Database(self.db, self.access),
            cmd: core_cache::Command::raw(name).read_only(),
        }
    }

    /// 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, self.access),
            script,
            read_only: true,
            keys: Vec::new(),
            args: Vec::new(),
        }
    }
}

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

impl Target<'_> {
    fn client(&self) -> Result<Arc<Client>, Error> {
        match self {
            Target::Database(db, access) => db.client_for(*access),
            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, access) => match db.client_for(access) {
                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 value = self.reply(&cmd.inner).await.map_err(redis_err)?;
        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 replies = replies.map_err(redis_err)?;
        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 command the groups lack, on this connection: see
    /// [`Database::command`]. One that blocks is refused here.
    pub fn command(&self, name: &'static str) -> CommandInvocation<'_> {
        CommandInvocation {
            target: Target::Connection(self),
            cmd: core_cache::Command::raw(name),
        }
    }

    /// 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 keys passed through `KEYS` receive the database's key prefix (see the
/// [module docs](self#keys)). Script source code and `ARGV` are sent unchanged,
/// so any key hardcoded in the script or built from `ARGV` bypasses database
/// isolation. Always pass every key the script accesses 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,
                "read-only handles can only run 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));
    }
}

/// A command the groups lack, made by [`Database::command`].
pub struct CommandInvocation<'a> {
    target: Target<'a>,
    cmd: core_cache::Command,
}

impl CommandInvocation<'_> {
    /// The next argument, which is a key: it gets the database's prefix.
    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
        for key in key.to_redis_args() {
            self.cmd = self.cmd.key(key);
        }
        self
    }

    /// The next argument, which is not a key: it is sent as it is.
    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
        for arg in arg.to_redis_args() {
            self.cmd = self.cmd.arg(arg);
        }
        self
    }

    /// Sends the command and converts its reply. The reply is returned as sent
    /// by Redis, except that keys returned by blocking pops and stream reads
    /// have the database prefix stripped.
    pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
        let value = self.target.reply(&self.cmd).await.map_err(redis_err)?;
        T::from_redis_value(value)
    }
}

/// A command the groups lack being queued on a pipeline or a transaction.
pub struct QueuedCommandInvocation<'a> {
    queue: &'a mut Queued,
    cmd: core_cache::Command,
}

impl QueuedCommandInvocation<'_> {
    /// The next argument, which is a key: it gets the database's prefix.
    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
        for key in key.to_redis_args() {
            self.cmd = self.cmd.key(key);
        }
        self
    }

    /// The next argument, which is not a key: it is sent as it is.
    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
        for arg in arg.to_redis_args() {
            self.cmd = self.cmd.arg(arg);
        }
        self
    }

    /// Queues the command.
    pub fn queue(self) {
        self.queue.push(Cmd::from_core(self.cmd));
    }
}

/// 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)
    )
}

/// The error a failed command is, coded by what failed: the server
/// rejecting it, the server or the pool being out of reach, or the command
/// being refused before it was sent.
fn redis_err(err: core_cache::OpError) -> Error {
    Error::wrap(redis_err_code(&err.source), err)
}

fn redis_err_code(err: &core_cache::Error) -> ErrCode {
    let err = match err {
        core_cache::Error::Refused(_) => return ErrCode::InvalidArgument,
        core_cache::Error::PoolTimeout => return ErrCode::Unavailable,
        core_cache::Error::Redis(err) => err,
    };
    if let Some(code) = err.code() {
        return match code {
            "EXECABORT" | "BUSYKEY" => ErrCode::Aborted,
            // The server can't serve the command now, but will.
            "LOADING" | "BUSY" | "TRYAGAIN" | "CLUSTERDOWN" | "MASTERDOWN" => ErrCode::Unavailable,
            "NOPERM" => ErrCode::PermissionDenied,
            _ => ErrCode::Internal,
        };
    }
    match err.kind() {
        rs::ErrorKind::Client | rs::ErrorKind::InvalidClientConfig => ErrCode::InvalidArgument,
        rs::ErrorKind::Parse | rs::ErrorKind::UnexpectedReturnType => ErrCode::Internal,
        _ => ErrCode::Unavailable,
    }
}