Skip to main content

encore/storage/redis/
mod.rs

1//! Redis databases.
2//!
3//! Databases are declared at module scope. Connection pools are initialized
4//! lazily on first use and reused across calls.
5//!
6//! ```no_run
7//! use encore::storage::redis::Database;
8//!
9//! static SESSIONS: Database = Database::new("sessions");
10//!
11//! async fn touch(user: &str) -> Result<Option<String>, encore::Error> {
12//!     SESSIONS.string().incr(format!("visits:{user}"), 1).await?;
13//!     SESSIONS.string().get(format!("name:{user}")).await
14//! }
15//! ```
16//!
17//! Each Redis database is a standalone resource with no separate cluster or
18//! keyspace declarations; use whatever key naming scheme your application needs.
19//!
20//! # Commands
21//!
22//! Commands are grouped by data type and accessed through methods on
23//! [`Database`]: [`Database::string`], [`Database::hash`], [`Database::list`],
24//! [`Database::set`], [`Database::sorted_set`], [`Database::stream`],
25//! [`Database::geo`], [`Database::bitmap`], [`Database::hyperloglog`], and
26//! [`Database::generic`] for key-agnostic commands. Command names follow the
27//! [`redis`] crate (`get`, `hset`, `zadd`, `xadd`), using [`ToRedisArgs`] and
28//! [`FromRedisValue`] for conversions. In most cases, you choose the return
29//! type at the call site:
30//!
31//! ```no_run
32//! # use encore::storage::redis::Database;
33//! # static SESSIONS: Database = Database::new("sessions");
34//! # async fn example() -> Result<(), encore::Error> {
35//! let name: Option<String> = SESSIONS.string().get("name:1").await?;
36//! let visits: u64 = SESSIONS.string().get("visits:1").await?;
37//! let fields: std::collections::HashMap<String, String> =
38//!     SESSIONS.hash().hgetall("user:1").await?;
39//! # Ok(())
40//! # }
41//! ```
42//!
43//! Call each command directly on the group expression (for example,
44//! `SESSIONS.string().get(...)`). This allows Encore to analyze command usage
45//! statically and grant each service only the permissions it needs. Storing or
46//! passing a command group value directly is a static analysis error—use a
47//! database handle instead.
48//!
49//! Blocking commands such as [`list::Commands::blpop`],
50//! [`sorted_set::Commands::bzpopmin`], and [`stream::Commands::xread_block`]
51//! run on a dedicated connection so they never block other calls. Dropping the
52//! future cancels the wait and closes that connection. Blocking commands cannot
53//! be queued in pipelines or transactions, and cannot run on an
54//! [acquired](Database::acquire) connection.
55//!
56//! # Arbitrary commands
57//!
58//! Use [`Database::command`] to run a Redis command not covered by the typed
59//! groups, marking key arguments explicitly with `.key(...)`:
60//!
61//! ```no_run
62//! # use encore::storage::redis::Database;
63//! # static SESSIONS: Database = Database::new("sessions");
64//! # async fn example() -> Result<(), encore::Error> {
65//! let freq: i64 = SESSIONS.command("OBJECT").arg("FREQ").key("hot").invoke().await?;
66//! # Ok(())
67//! # }
68//! ```
69//!
70//! The command name must be a string literal so Encore can grant the required
71//! permissions statically. Before sending, Encore validates the command against
72//! Redis's command table:
73//!
74//! - Every key argument must be passed via `.key(...)` so it receives the
75//!   database's key prefix.
76//! - Commands that bypass database isolation, mutate shared connection state,
77//!   or have dedicated SDK methods (`MULTI`, `SUBSCRIBE`, `EVAL`, `SCAN`,
78//!   `FLUSHALL`, etc.) are rejected with [`ErrCode::InvalidArgument`].
79//! - Read-only handles reject commands marked as writes by Redis.
80//! - Unknown commands (such as Redis module commands) are sent as-is with the
81//!   marked keys prefixed.
82//!
83//! # Errors
84//!
85//! - Server rejections (such as `WRONGTYPE` or script errors) return
86//!   [`ErrCode::Internal`] with the server's message.
87//! - Aborted transactions return [`ErrCode::Aborted`].
88//! - Connection failures return [`ErrCode::Unavailable`].
89//!
90//! # Handles
91//!
92//! A [`Database`] cannot be passed around by value. To pass it to helper
93//! functions or libraries, create a handle with the access level it
94//! needs—[`Database::write`], [`Database::read`], or
95//! [`Database::read_primary`]—which grants that access level to the service:
96//!
97//! ```no_run
98//! use encore::storage::redis::{Database, ReadOnlyDatabaseRef};
99//!
100//! static SESSIONS: Database = Database::new("sessions");
101//!
102//! // Library code takes a handle, and can only do what the handle allows.
103//! async fn name_of(db: ReadOnlyDatabaseRef, user: &str) -> Result<Option<String>, encore::Error> {
104//!     db.string().get(format!("name:{user}")).await
105//! }
106//!
107//! async fn greet(user: &str) -> Result<Option<String>, encore::Error> {
108//!     name_of(SESSIONS.read(), user).await
109//! }
110//! ```
111//!
112//! # Keys
113//!
114//! Encore automatically namespaces every key with a per-database prefix to
115//! isolate databases sharing a server and to isolate each test. The prefix is
116//! added to outgoing keys and stripped from returned keys, so application code
117//! never sees it. Keep two caveats in mind:
118//!
119//! * In a [`Script`], only keys passed through `KEYS` are prefixed. Script
120//!   source code and `ARGV` values are sent untouched, so any key hardcoded in
121//!   the script or built from `ARGV` bypasses database isolation. Always pass
122//!   every key a script accesses through `KEYS`.
123//! * [`Database::connection_string`] connects directly to Redis without
124//!   applying the prefix, so external clients will not see keys under their
125//!   unprefixed names.
126//!
127//! [`redis`]: https://docs.rs/redis/latest/redis/
128
129mod commands;
130#[cfg(test)]
131mod tests;
132pub mod types;
133
134use std::sync::{Arc, OnceLock};
135
136use encore_sdk_core::cache::{self as core_cache, Access, Client, redis as rs};
137
138use crate::error::{ErrCode, Error};
139use crate::runtime::core;
140use crate::testing;
141
142pub use self::commands::{
143    Scan, ScanOptions, bitmap, generic, geo, hash, hyperloglog, list, pubsub, set, sorted_set,
144    stream, string,
145};
146pub use self::types::{
147    FromRedisValue, Increment, Json, Popped, PoppedMany, PoppedScored, PoppedScoredMany,
148    ToRedisArgs, Value,
149};
150pub use rs::{Direction, ExistenceCheck, Expiry, SetExpiry, SetOptions};
151
152use self::commands::Cmd;
153
154/// A Redis database, backed by a lazily-built connection pool.
155pub struct Database {
156    name: &'static str,
157    /// Read by Encore's parser from the declaration, not by the runtime.
158    #[allow(dead_code)]
159    persistent: bool,
160    client: OnceLock<Arc<Client>>,
161    /// The clients its read handles run on, made from `client`:
162    /// [`Access::Read`]'s, then [`Access::ReadPrimary`]'s.
163    readers: [OnceLock<Arc<Client>>; 2],
164}
165
166impl Database {
167    /// Declares a new Redis database.
168    ///
169    /// This function is `const` so it can initialize a module-scope `static`.
170    /// The connection pool is created on first use. Chain builder methods to
171    /// configure options:
172    ///
173    /// ```no_run
174    /// use encore::storage::redis::Database;
175    ///
176    /// static SESSIONS: Database = Database::new("sessions");
177    /// static LEDGER: Database = Database::new("ledger").persistent();
178    /// ```
179    pub const fn new(name: &'static str) -> Self {
180        Self {
181            name,
182            persistent: false,
183            client: OnceLock::new(),
184            readers: [OnceLock::new(), OnceLock::new()],
185        }
186    }
187
188    /// References an existing Redis database by name. To declare a new
189    /// database, use [`Database::new`] instead.
190    ///
191    /// `name` must be a string literal so Encore can resolve it statically.
192    /// Referenced databases take no configuration options; options are set
193    /// where the database is declared.
194    pub const fn named(name: &'static str) -> Self {
195        Self::new(name)
196    }
197
198    /// Marks the database as persistent so its data survives restarts and is
199    /// never evicted. Without this option, the database behaves as a cache and
200    /// entries may be evicted or lost on restart.
201    ///
202    /// Must be called as part of the `static` declaration.
203    pub const fn persistent(mut self) -> Self {
204        self.persistent = true;
205        self
206    }
207
208    /// Attaches a classification tag (`key`, `value`) to the database, such as
209    /// `.tag("data", "pii")`, for policy evaluation.
210    ///
211    /// Call once per tag with unique keys. Both `key` and `value` must be
212    /// string literals of at most 63 characters (up to 32 tags per database).
213    /// Keys may contain lowercase letters, digits, `_`, and `-`, must start
214    /// with a letter, and cannot start with `encore` (reserved for Encore).
215    /// Values use the same character set or may be empty.
216    ///
217    /// Must be called as part of the `static` declaration.
218    ///
219    /// ```no_run
220    /// use encore::storage::redis::Database;
221    ///
222    /// static SESSIONS: Database = Database::new("sessions").tag("data", "pii");
223    /// ```
224    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
225        self
226    }
227
228    /// A handle to the database that can read and write.
229    ///
230    /// `const`, so a handle can initialize a module-scope `static`.
231    pub const fn write(&'static self) -> DatabaseRef {
232        DatabaseRef { db: self }
233    }
234
235    /// A handle to the database that can only read. It reads from a read
236    /// replica where the database has a read-only connection pool on one, and
237    /// otherwise from the primary. Either way a command that writes is
238    /// refused before it is sent. To always read from the primary server, use
239    /// [`Database::read_primary`].
240    pub const fn read(&'static self) -> ReadOnlyDatabaseRef {
241        ReadOnlyDatabaseRef {
242            db: self,
243            access: Access::Read,
244        }
245    }
246
247    /// A handle to the database that can only read, and reads from the
248    /// primary server even where there are read replicas. A command that
249    /// writes is refused before it is sent.
250    pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef {
251        ReadOnlyDatabaseRef {
252            db: self,
253            access: Access::ReadPrimary,
254        }
255    }
256
257    /// The client commands run on: the database's own, or under `encore test`
258    /// the one of the current test's instance of it (see [`crate::testing`]).
259    fn client(&self) -> Result<Arc<Client>, Error> {
260        // Never set under `encore test`, where the test's own comes first.
261        if let Some(client) = self.client.get() {
262            return Ok(client.clone());
263        }
264        if let Some(test) = testing::active()? {
265            return test.redis_client(self.name);
266        }
267        let client = core()
268            .cache()
269            .cluster(&self.name.into())
270            .client()
271            .map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?;
272        // A concurrent caller may win the race; either way `get` returns one.
273        let _ = self.client.set(Arc::new(client));
274        Ok(self.client.get().expect("client just set").clone())
275    }
276
277    /// The client a handle with `access` runs on, made from
278    /// [`Database::client`]: see [`Client::with_access`].
279    fn client_for(&self, access: Access) -> Result<Arc<Client>, Error> {
280        let slot = match access {
281            Access::ReadWrite => return self.client(),
282            Access::Read => &self.readers[0],
283            Access::ReadPrimary => &self.readers[1],
284        };
285        if let Some(reader) = slot.get() {
286            return Ok(reader.clone());
287        }
288        let client = self.client()?;
289        let reader = Arc::new(
290            client
291                .with_access(access)
292                .map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?,
293        );
294        // Kept only beside the database's own client: under `encore test`
295        // each test has its own instance.
296        if !self
297            .client
298            .get()
299            .is_some_and(|own| Arc::ptr_eq(own, &client))
300        {
301            return Ok(reader);
302        }
303        let _ = slot.set(reader);
304        Ok(slot.get().expect("reader just set").clone())
305    }
306}
307
308/// A handle to a [`Database`] that can read and write, made by
309/// [`Database::write`]. `Copy`, and free to pass to other code.
310#[derive(Clone, Copy)]
311pub struct DatabaseRef {
312    db: &'static Database,
313}
314
315/// A handle to a [`Database`] that can only read, made by [`Database::read`]
316/// or [`Database::read_primary`]. `Copy`, and free to pass to other code.
317///
318/// Its command groups hold the commands that read, and nothing else.
319#[derive(Clone, Copy)]
320pub struct ReadOnlyDatabaseRef {
321    db: &'static Database,
322    /// [`Access::Read`] or [`Access::ReadPrimary`].
323    access: Access,
324}
325
326/// The command groups, as methods returning `$form` of each.
327macro_rules! groups {
328    ($form:ident<$lt:lifetime>, |$this:ident| $target:expr) => {
329        groups!(@each $form<$lt>, |$this| $target;
330            /// Commands that work on a key of any type: expiry, deletion, renaming.
331            generic,
332            /// Commands on strings, which is what a plain value is.
333            string,
334            /// Commands on the bits of a string.
335            bitmap,
336            /// Commands on hashes: a key holding fields, each with a value.
337            hash,
338            /// Commands on lists.
339            list,
340            /// Commands on sets.
341            set,
342            /// Commands on sorted sets: members ordered by a score.
343            sorted_set,
344            /// Commands on geospatial indexes.
345            geo,
346            /// Commands on streams.
347            stream,
348            /// Commands on HyperLogLogs: estimates of how many distinct elements
349            /// were added.
350            hyperloglog,
351            /// Publishing to channels, and subscribing to them.
352            pubsub,
353        );
354    };
355    (@each $form:ident<$lt:lifetime>, |$this:ident| $target:expr; $($(#[$doc:meta])* $group:ident,)*) => {
356        $(
357            $(#[$doc])*
358            pub fn $group(&self) -> $group::$form<$lt> {
359                let $this = self;
360                $group::$form { target: $target }
361            }
362        )*
363    };
364}
365
366/// The command groups, as methods returning each one's queue.
367macro_rules! queues {
368    () => {
369        queues!(@each generic, string, bitmap, hash, list, set, sorted_set, geo, stream, hyperloglog, pubsub);
370    };
371    (@each $($group:ident),*) => {
372        $(
373            /// Queues commands of this group. Nothing is sent until `exec`.
374            pub fn $group(&mut self) -> $group::Queue<'_> {
375                $group::Queue { queue: &mut self.queued }
376            }
377        )*
378
379        /// Queues a call to `script`. Finish it with [`QueuedInvocation::queue`].
380        pub fn script(&mut self, script: &'static Script) -> QueuedInvocation<'_> {
381            QueuedInvocation {
382                queue: &mut self.queued,
383                script,
384                keys: Vec::new(),
385                args: Vec::new(),
386            }
387        }
388
389        /// Queues a command the groups lack, by its name: see
390        /// [`Database::command`]. Finish it with
391        /// [`QueuedCommandInvocation::queue`]. A command that blocks can't be
392        /// queued: the batch fails.
393        pub fn command(&mut self, name: &'static str) -> QueuedCommandInvocation<'_> {
394            QueuedCommandInvocation {
395                queue: &mut self.queued,
396                cmd: core_cache::Command::raw(name),
397            }
398        }
399
400        /// How many commands are queued.
401        pub fn len(&self) -> usize {
402            self.queued.commands.len()
403        }
404
405        /// Whether nothing is queued.
406        pub fn is_empty(&self) -> bool {
407            self.queued.commands.is_empty()
408        }
409    };
410}
411
412/// What reading and writing handles share, the [`Database`] among them.
413macro_rules! writer_methods {
414    ($lt:lifetime, |$this:ident| $db:expr) => {
415        groups!(Commands<$lt>, |$this| Target::Database(
416            $db,
417            Access::ReadWrite
418        ));
419
420        /// A batch of commands sent in one round trip. Not a transaction:
421        /// other clients' commands may run between them, and one failing does
422        /// not stop the rest.
423        ///
424        /// ```no_run
425        /// # use encore::storage::redis::Database;
426        /// # static SESSIONS: Database = Database::new("sessions");
427        /// # async fn example() -> Result<(), encore::Error> {
428        /// let mut pipe = SESSIONS.pipeline();
429        /// pipe.string().get("name:1");
430        /// pipe.string().get("name:2");
431        /// let (first, second): (Option<String>, Option<String>) = pipe.exec().await?;
432        /// # Ok(())
433        /// # }
434        /// ```
435        pub fn pipeline(&self) -> Pipeline<$lt> {
436            let $this = self;
437            Pipeline {
438                target: Target::Database($db, Access::ReadWrite),
439                queued: Queued::default(),
440            }
441        }
442
443        /// A transaction (`MULTI`/`EXEC`): the commands queued on it run
444        /// together, with no other client's in between, or not at all.
445        ///
446        /// Nothing is sent until [`Transaction::exec`], so a transaction is
447        /// never left open across an `.await`.
448        ///
449        /// ```no_run
450        /// # use encore::storage::redis::Database;
451        /// # static LEDGER: Database = Database::new("ledger").persistent();
452        /// # async fn example(now: u64) -> Result<(), encore::Error> {
453        /// let mut tx = LEDGER.transaction();
454        /// tx.string().incr("hits", 1);
455        /// tx.hash().hset("user:1", "seen", now);
456        /// let (hits, _): (i64, u64) = tx.exec().await?;
457        /// # Ok(())
458        /// # }
459        /// ```
460        pub fn transaction(&self) -> Transaction<$lt> {
461            let $this = self;
462            Transaction {
463                target: Target::Database($db, Access::ReadWrite),
464                queued: Queued::default(),
465            }
466        }
467
468        /// Takes a connection out of the pool, for what must run on one
469        /// connection: watching keys, then a transaction that depends on them.
470        /// It is returned to the pool when dropped.
471        pub async fn acquire(&self) -> Result<Connection, Error> {
472            let $this = self;
473            let client = ($db).client()?;
474            let inner = client.acquire().await.map_err(redis_err)?;
475            Ok(Connection {
476                inner: tokio::sync::Mutex::new(inner),
477                client,
478            })
479        }
480
481        /// Runs `body` as an optimistic transaction watching `keys`.
482        ///
483        /// Read values through the connection and queue writes on the
484        /// transaction. Changes are applied atomically only if none of `keys`
485        /// changed in the meantime; otherwise, `body` is retried.
486        ///
487        /// ```no_run
488        /// # use encore::storage::redis::Database;
489        /// # static LEDGER: Database = Database::new("ledger").persistent();
490        /// # async fn example() -> Result<(), encore::Error> {
491        /// let left: i64 = LEDGER
492        ///     .watch("balance", async |conn, tx| {
493        ///         let balance: i64 = conn.string().get("balance").await?;
494        ///         tx.string().set("balance", balance - 10);
495        ///         Ok(balance - 10)
496        ///     })
497        ///     .await?;
498        /// # Ok(())
499        /// # }
500        /// ```
501        pub async fn watch<T>(
502            &self,
503            keys: impl ToRedisArgs,
504            mut body: impl AsyncFnMut(&Connection, &mut WatchedTransaction<'_>) -> Result<T, Error>,
505        ) -> Result<T, Error> {
506            /// A key changing this many times in a row is not contention that
507            /// another attempt will get past.
508            const ATTEMPTS: usize = 64;
509
510            let keys = keys.to_redis_args();
511            let conn = self.acquire().await?;
512            for _ in 0..ATTEMPTS {
513                conn.watch(&keys).await?;
514                let mut tx = conn.transaction();
515                let out = body(&conn, &mut tx).await?;
516                if tx.exec::<Value>().await?.is_some() {
517                    return Ok(out);
518                }
519            }
520            Err(Error::new(
521                ErrCode::Aborted,
522                format!("watched keys kept changing; gave up after {ATTEMPTS} attempts"),
523            ))
524        }
525
526        /// A call to `script`, to give its keys and arguments and then
527        /// [`Invocation::invoke`].
528        pub fn script(&self, script: &'static Script) -> Invocation<$lt> {
529            let $this = self;
530            Invocation {
531                target: Target::Database($db, Access::ReadWrite),
532                script,
533                read_only: false,
534                keys: Vec::new(),
535                args: Vec::new(),
536            }
537        }
538
539        /// Builds an arbitrary Redis command by name (for example, `"OBJECT"`).
540        ///
541        /// `name` must be a string literal. Pass arguments in order using
542        /// [`CommandInvocation::key`] and [`CommandInvocation::arg`], then call
543        /// [`CommandInvocation::invoke`]. See the
544        /// [module docs](self#arbitrary-commands) for validation rules.
545        pub fn command(&self, name: &'static str) -> CommandInvocation<$lt> {
546            let $this = self;
547            CommandInvocation {
548                target: Target::Database($db, Access::ReadWrite),
549                cmd: core_cache::Command::raw(name),
550            }
551        }
552
553        /// Returns a Redis connection URL for use with external clients.
554        ///
555        /// External clients connect directly without this SDK's key prefix
556        /// (see the [module docs](self#keys)), so keys written there do not
557        /// match the unprefixed names used by this SDK.
558        pub fn connection_string(&self) -> Result<String, Error> {
559            let $this = self;
560            Ok(($db).client()?.connection_url())
561        }
562    };
563}
564
565impl Database {
566    writer_methods!('_, |this| this);
567}
568
569impl DatabaseRef {
570    writer_methods!('static, |this| this.db);
571}
572
573impl ReadOnlyDatabaseRef {
574    groups!(ReadCommands<'static>, |this| Target::Database(
575        this.db,
576        this.access
577    ));
578
579    /// A command the groups lack, by its name: see [`Database::command`]. Only
580    /// a command Redis says doesn't write is sent.
581    pub fn command(&self, name: &'static str) -> CommandInvocation<'static> {
582        CommandInvocation {
583            target: Target::Database(self.db, self.access),
584            cmd: core_cache::Command::raw(name).read_only(),
585        }
586    }
587
588    /// A call to `script`, which must be a [`Script::read_only`] one.
589    pub fn script(&self, script: &'static Script) -> Invocation<'static> {
590        Invocation {
591            target: Target::Database(self.db, self.access),
592            script,
593            read_only: true,
594            keys: Vec::new(),
595            args: Vec::new(),
596        }
597    }
598}
599
600/// Where a command runs: on a connection from the database's pool, through
601/// the client for a handle's access, or on one taken out of it.
602#[derive(Clone, Copy)]
603pub(crate) enum Target<'a> {
604    Database(&'a Database, Access),
605    Connection(&'a Connection),
606}
607
608impl Target<'_> {
609    fn client(&self) -> Result<Arc<Client>, Error> {
610        match self {
611            Target::Database(db, access) => db.client_for(*access),
612            Target::Connection(conn) => Ok(conn.client.clone()),
613        }
614    }
615
616    /// Runs `cmd`, returning Redis's reply as it came.
617    async fn reply(self, cmd: &core_cache::Command) -> Result<Value, core_cache::OpError> {
618        match self {
619            Target::Database(db, access) => match db.client_for(access) {
620                Ok(client) => client.execute(cmd).await,
621                Err(err) => Err(unavailable(cmd, err)),
622            },
623            Target::Connection(conn) => conn.inner.lock().await.execute(cmd).await,
624        }
625    }
626
627    /// Runs `cmd` and converts its reply.
628    pub(crate) async fn run<T: FromRedisValue>(self, cmd: Cmd) -> Result<T, Error> {
629        let value = self.reply(&cmd.inner).await.map_err(redis_err)?;
630        T::from_redis_value(value)
631    }
632
633    /// Runs `queued` in one round trip — as a transaction, if `atomic` — and
634    /// returns its replies as one array. `None` for a transaction that did
635    /// not run because a watched key changed.
636    async fn run_all(self, queued: Queued, atomic: bool) -> Result<Option<Value>, Error> {
637        let commands: Vec<core_cache::Command> = queued
638            .commands
639            .iter()
640            .map(|cmd| cmd.inner.clone())
641            .collect();
642        let client = self.client()?;
643        let replies = match self {
644            Target::Database(..) => Some(client.execute_all(&commands, atomic).await),
645            Target::Connection(conn) => conn
646                .inner
647                .lock()
648                .await
649                .execute_all(&commands, atomic)
650                .await
651                .transpose(),
652        };
653        let Some(replies) = replies else {
654            return Ok(None);
655        };
656        let replies = replies.map_err(redis_err)?;
657        Ok(Some(Value::Array(replies)))
658    }
659}
660
661/// The error for a command that could not be sent at all, in the shape the
662/// ones that were sent fail with.
663fn unavailable(cmd: &core_cache::Command, err: Error) -> core_cache::OpError {
664    core_cache::OpError::new(
665        cmd.operation(),
666        "",
667        core_cache::Error::Redis(std::io::Error::other(err.message).into()),
668    )
669}
670
671/// The commands queued on a [`Pipeline`] or a transaction.
672#[derive(Default)]
673pub(crate) struct Queued {
674    commands: Vec<Cmd>,
675}
676
677impl Queued {
678    pub(crate) fn push(&mut self, cmd: Cmd) {
679        self.commands.push(cmd);
680    }
681}
682
683/// A batch of commands sent in one round trip, made by
684/// [`Database::pipeline`]. Not a transaction.
685pub struct Pipeline<'a> {
686    target: Target<'a>,
687    queued: Queued,
688}
689
690impl Pipeline<'_> {
691    queues!();
692
693    /// Sends the queued commands and returns their replies, in order, as a
694    /// tuple or a `Vec`.
695    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
696        let replies = self.target.run_all(self.queued, false).await?;
697        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
698    }
699}
700
701/// A transaction, made by [`Database::transaction`]: the commands queued on it
702/// run together or not at all.
703pub struct Transaction<'a> {
704    target: Target<'a>,
705    queued: Queued,
706}
707
708impl Transaction<'_> {
709    queues!();
710
711    /// Runs the queued commands as one transaction and returns their replies,
712    /// in order, as a tuple or a `Vec`.
713    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
714        let replies = self.target.run_all(self.queued, true).await?;
715        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
716    }
717
718    /// Abandons the transaction. Nothing was sent, so there is nothing to
719    /// undo: this is dropping it, by name.
720    pub fn discard(self) {}
721}
722
723/// A transaction on a [`Connection`], made by [`Connection::transaction`]: it
724/// does nothing if a key the connection watches has changed.
725pub struct WatchedTransaction<'a> {
726    target: Target<'a>,
727    queued: Queued,
728}
729
730impl WatchedTransaction<'_> {
731    queues!();
732
733    /// Runs the queued commands as one transaction and returns their replies.
734    /// `None` if a watched key changed, in which case none of them ran. Either
735    /// way the connection watches nothing afterwards.
736    pub async fn exec<T: FromRedisValue>(&mut self) -> Result<Option<T>, Error> {
737        let queued = std::mem::take(&mut self.queued);
738        match self.target.run_all(queued, true).await? {
739            Some(replies) => T::from_redis_value(replies).map(Some),
740            None => Ok(None),
741        }
742    }
743}
744
745/// A connection taken out of the database's pool, made by
746/// [`Database::acquire`]. It is returned to the pool when dropped.
747pub struct Connection {
748    inner: tokio::sync::Mutex<core_cache::Connection>,
749    client: Arc<Client>,
750}
751
752impl Connection {
753    groups!(Commands<'_>, |this| Target::Connection(this));
754
755    /// Watches `keys`: a [`Connection::transaction`] then does nothing if any
756    /// of them has changed by the time it is run.
757    pub async fn watch(&self, keys: impl ToRedisArgs) -> Result<(), Error> {
758        self.inner
759            .lock()
760            .await
761            .watch(&keys.to_redis_args())
762            .await
763            .map_err(redis_err)
764    }
765
766    /// Stops watching every key.
767    pub async fn unwatch(&self) -> Result<(), Error> {
768        self.inner.lock().await.unwatch().await.map_err(redis_err)
769    }
770
771    /// A transaction on this connection, which depends on the keys it watches.
772    pub fn transaction(&self) -> WatchedTransaction<'_> {
773        WatchedTransaction {
774            target: Target::Connection(self),
775            queued: Queued::default(),
776        }
777    }
778
779    /// A batch of commands sent in one round trip on this connection.
780    pub fn pipeline(&self) -> Pipeline<'_> {
781        Pipeline {
782            target: Target::Connection(self),
783            queued: Queued::default(),
784        }
785    }
786
787    /// A command the groups lack, on this connection: see
788    /// [`Database::command`]. One that blocks is refused here.
789    pub fn command(&self, name: &'static str) -> CommandInvocation<'_> {
790        CommandInvocation {
791            target: Target::Connection(self),
792            cmd: core_cache::Command::raw(name),
793        }
794    }
795
796    /// A call to `script` on this connection.
797    pub fn script(&self, script: &'static Script) -> Invocation<'_> {
798        Invocation {
799            target: Target::Connection(self),
800            script,
801            read_only: false,
802            keys: Vec::new(),
803            args: Vec::new(),
804        }
805    }
806}
807
808/// A Lua script the database runs, declared at module scope.
809///
810/// ```no_run
811/// use encore::storage::redis::{Database, Script};
812///
813/// static LOCKS: Database = Database::new("locks");
814///
815/// static RELEASE: Script = Script::new(
816///     r#"
817///     if redis.call("get", KEYS[1]) == ARGV[1] then
818///         return redis.call("del", KEYS[1])
819///     end
820///     return 0
821///     "#,
822/// );
823///
824/// async fn release(job: &str, token: &str) -> Result<bool, encore::Error> {
825///     LOCKS.script(&RELEASE).key(format!("lock:{job}")).arg(token).invoke().await
826/// }
827/// ```
828///
829/// Only keys passed through `KEYS` receive the database's key prefix (see the
830/// [module docs](self#keys)). Script source code and `ARGV` are sent unchanged,
831/// so any key hardcoded in the script or built from `ARGV` bypasses database
832/// isolation. Always pass every key the script accesses through `KEYS`.
833pub struct Script {
834    source: &'static str,
835    read_only: bool,
836    /// The source's SHA-1, which the server caches the script under.
837    hash: OnceLock<String>,
838}
839
840impl Script {
841    /// Declare a script. `const`, so it can initialize a module-scope `static`.
842    pub const fn new(source: &'static str) -> Self {
843        Self {
844            source,
845            read_only: false,
846            hash: OnceLock::new(),
847        }
848    }
849
850    /// Declare a script that only reads. The server refuses to let it write,
851    /// which is what lets it run on a [`ReadOnlyDatabaseRef`].
852    pub const fn read_only(source: &'static str) -> Self {
853        Self {
854            source,
855            read_only: true,
856            hash: OnceLock::new(),
857        }
858    }
859
860    fn hash(&self) -> &str {
861        self.hash
862            .get_or_init(|| rs::Script::new(self.source).get_hash().to_string())
863    }
864
865    /// The command that runs the script: by its hash, which the server has if
866    /// it has run it before, or by its source.
867    fn command(&self, by_hash: bool, keys: &[Vec<u8>], args: &[Vec<u8>]) -> core_cache::Command {
868        let name = match (by_hash, self.read_only) {
869            (true, false) => "EVALSHA",
870            (true, true) => "EVALSHA_RO",
871            (false, false) => "EVAL",
872            (false, true) => "EVAL_RO",
873        };
874        let mut cmd = core_cache::Command::new("script", name, !self.read_only)
875            .arg(if by_hash { self.hash() } else { self.source })
876            .arg(keys.len().to_string());
877        for key in keys {
878            cmd = cmd.key(key.as_slice());
879        }
880        for arg in args {
881            cmd = cmd.arg(arg.as_slice());
882        }
883        cmd
884    }
885}
886
887/// A call to a [`Script`], made by [`Database::script`].
888pub struct Invocation<'a> {
889    target: Target<'a>,
890    script: &'static Script,
891    /// Whether the handle it was made from can only read.
892    read_only: bool,
893    keys: Vec<Vec<u8>>,
894    args: Vec<Vec<u8>>,
895}
896
897impl Invocation<'_> {
898    /// A key the script works on: the next of its `KEYS`.
899    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
900        self.keys.extend(key.to_redis_args());
901        self
902    }
903
904    /// An argument: the next of the script's `ARGV`, sent without the
905    /// database's key prefix.
906    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
907        self.args.extend(arg.to_redis_args());
908        self
909    }
910
911    /// Runs the script and converts what it returns.
912    pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
913        if self.read_only && !self.script.read_only {
914            return Err(Error::new(
915                ErrCode::FailedPrecondition,
916                "read-only handles can only run scripts declared with `Script::read_only`",
917            ));
918        }
919        let by_hash = self.script.command(true, &self.keys, &self.args);
920        let value = match self.target.reply(&by_hash).await {
921            Ok(value) => value,
922            // The server has not seen the script: send it, which also caches it.
923            Err(err) if is_no_script(&err) => {
924                let by_source = self.script.command(false, &self.keys, &self.args);
925                self.target.reply(&by_source).await.map_err(redis_err)?
926            }
927            Err(err) => return Err(redis_err(err)),
928        };
929        T::from_redis_value(value)
930    }
931}
932
933/// A call to a [`Script`] being queued on a pipeline or a transaction.
934pub struct QueuedInvocation<'a> {
935    queue: &'a mut Queued,
936    script: &'static Script,
937    keys: Vec<Vec<u8>>,
938    args: Vec<Vec<u8>>,
939}
940
941impl QueuedInvocation<'_> {
942    /// A key the script works on: the next of its `KEYS`.
943    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
944        self.keys.extend(key.to_redis_args());
945        self
946    }
947
948    /// An argument: the next of the script's `ARGV`, sent without the
949    /// database's key prefix.
950    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
951        self.args.extend(arg.to_redis_args());
952        self
953    }
954
955    /// Queues the call. Sent by source rather than by hash: a batch cannot
956    /// stop halfway to send a script the server turns out not to have.
957    pub fn queue(self) {
958        let inner = self.script.command(false, &self.keys, &self.args);
959        self.queue.push(Cmd::from_core(inner));
960    }
961}
962
963/// A command the groups lack, made by [`Database::command`].
964pub struct CommandInvocation<'a> {
965    target: Target<'a>,
966    cmd: core_cache::Command,
967}
968
969impl CommandInvocation<'_> {
970    /// The next argument, which is a key: it gets the database's prefix.
971    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
972        for key in key.to_redis_args() {
973            self.cmd = self.cmd.key(key);
974        }
975        self
976    }
977
978    /// The next argument, which is not a key: it is sent as it is.
979    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
980        for arg in arg.to_redis_args() {
981            self.cmd = self.cmd.arg(arg);
982        }
983        self
984    }
985
986    /// Sends the command and converts its reply. The reply is returned as sent
987    /// by Redis, except that keys returned by blocking pops and stream reads
988    /// have the database prefix stripped.
989    pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
990        let value = self.target.reply(&self.cmd).await.map_err(redis_err)?;
991        T::from_redis_value(value)
992    }
993}
994
995/// A command the groups lack being queued on a pipeline or a transaction.
996pub struct QueuedCommandInvocation<'a> {
997    queue: &'a mut Queued,
998    cmd: core_cache::Command,
999}
1000
1001impl QueuedCommandInvocation<'_> {
1002    /// The next argument, which is a key: it gets the database's prefix.
1003    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
1004        for key in key.to_redis_args() {
1005            self.cmd = self.cmd.key(key);
1006        }
1007        self
1008    }
1009
1010    /// The next argument, which is not a key: it is sent as it is.
1011    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
1012        for arg in arg.to_redis_args() {
1013            self.cmd = self.cmd.arg(arg);
1014        }
1015        self
1016    }
1017
1018    /// Queues the command.
1019    pub fn queue(self) {
1020        self.queue.push(Cmd::from_core(self.cmd));
1021    }
1022}
1023
1024/// Whether a command failed because the server does not have the script its
1025/// hash names.
1026fn is_no_script(err: &core_cache::OpError) -> bool {
1027    matches!(
1028        &err.source,
1029        core_cache::Error::Redis(err)
1030            if err.kind() == rs::ErrorKind::Server(rs::ServerErrorKind::NoScript)
1031    )
1032}
1033
1034/// The error a failed command is, coded by what failed: the server
1035/// rejecting it, the server or the pool being out of reach, or the command
1036/// being refused before it was sent.
1037fn redis_err(err: core_cache::OpError) -> Error {
1038    Error::wrap(redis_err_code(&err.source), err)
1039}
1040
1041fn redis_err_code(err: &core_cache::Error) -> ErrCode {
1042    let err = match err {
1043        core_cache::Error::Refused(_) => return ErrCode::InvalidArgument,
1044        core_cache::Error::PoolTimeout => return ErrCode::Unavailable,
1045        core_cache::Error::Redis(err) => err,
1046    };
1047    if let Some(code) = err.code() {
1048        return match code {
1049            "EXECABORT" | "BUSYKEY" => ErrCode::Aborted,
1050            // The server can't serve the command now, but will.
1051            "LOADING" | "BUSY" | "TRYAGAIN" | "CLUSTERDOWN" | "MASTERDOWN" => ErrCode::Unavailable,
1052            "NOPERM" => ErrCode::PermissionDenied,
1053            _ => ErrCode::Internal,
1054        };
1055    }
1056    match err.kind() {
1057        rs::ErrorKind::Client | rs::ErrorKind::InvalidClientConfig => ErrCode::InvalidArgument,
1058        rs::ErrorKind::Parse | rs::ErrorKind::UnexpectedReturnType => ErrCode::Internal,
1059        _ => ErrCode::Unavailable,
1060    }
1061}