Skip to main content

encore/storage/redis/
mod.rs

1//! Redis databases. Declared at module scope; the connection pool is built
2//! lazily from the runtime on first use and reused thereafter.
3//!
4//! ```no_run
5//! use encore::storage::redis::Database;
6//!
7//! static SESSIONS: Database = Database::new("sessions");
8//!
9//! async fn touch(user: &str) -> Result<Option<String>, encore::Error> {
10//!     SESSIONS.string().incr(format!("visits:{user}"), 1).await?;
11//!     SESSIONS.string().get(format!("name:{user}")).await
12//! }
13//! ```
14//!
15//! A database is a resource of its own: there is no cluster to put it in, and
16//! no keyspaces to declare in it. Its keys are whatever the code passes.
17//!
18//! # Commands
19//!
20//! Commands are grouped by the data type they work on, each group reached
21//! through a method of the database: [`Database::string`], [`Database::hash`],
22//! [`Database::list`], [`Database::set`], [`Database::sorted_set`],
23//! [`Database::stream`], [`Database::geo`], [`Database::bitmap`], and
24//! [`Database::generic`] for the ones that work on any key. Within a group the
25//! commands have the names the [`redis`] crate gives them — `get`, `hset`,
26//! `zadd`, `xadd` — and take and return what its conversion traits allow
27//! ([`ToRedisArgs`], [`FromRedisValue`]). A reply's type is usually the
28//! caller's to choose:
29//!
30//! ```no_run
31//! # use encore::storage::redis::Database;
32//! # static SESSIONS: Database = Database::new("sessions");
33//! # async fn example() -> Result<(), encore::Error> {
34//! let name: Option<String> = SESSIONS.string().get("name:1").await?;
35//! let visits: u64 = SESSIONS.string().get("visits:1").await?;
36//! let fields: std::collections::HashMap<String, String> =
37//!     SESSIONS.hash().hgetall("user:1").await?;
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! A command is called in the same expression that names its group. That is
43//! what lets Encore grant each service exactly the access it uses: the command
44//! is visible at the call, so the parser can read it. A group that is stored
45//! or passed on instead says nothing about what it will be used for, and is
46//! reported as an error — to do that, start from a handle.
47//!
48//! # Handles
49//!
50//! A database cannot be passed around as a value. To hand it to other code,
51//! make a handle with the access that code needs — [`Database::write`],
52//! [`Database::read`] or [`Database::read_primary`] — which the service is
53//! then granted in full:
54//!
55//! ```no_run
56//! use encore::storage::redis::{Database, ReadOnlyDatabaseRef};
57//!
58//! static SESSIONS: Database = Database::new("sessions");
59//!
60//! // Library code takes a handle, and can only do what the handle allows.
61//! async fn name_of(db: ReadOnlyDatabaseRef, user: &str) -> Result<Option<String>, encore::Error> {
62//!     db.string().get(format!("name:{user}")).await
63//! }
64//!
65//! async fn greet(user: &str) -> Result<Option<String>, encore::Error> {
66//!     name_of(SESSIONS.read(), user).await
67//! }
68//! ```
69//!
70//! # Keys
71//!
72//! Every key is stored under a prefix of the database's own, which is what
73//! keeps databases sharing a server apart, and gives each test a database of
74//! its own. It is applied to every key a command takes and removed from every
75//! key a command returns, so code never sees it. Two things follow:
76//!
77//! * only the keys a [`Script`] is passed, through `KEYS`, get the prefix.
78//!   Its source and `ARGV` are sent as they are, so a key the script names
79//!   itself or builds from an argument reaches the server unprefixed, outside
80//!   the database's isolation, where it may be another database's. Neither
81//!   Redis nor this SDK can check what a script touches, so a script must take
82//!   every key it uses through `KEYS`;
83//! * [`Database::connection_string`] connects past the prefix, so a client
84//!   using it does not see the keys this SDK writes under the same names.
85//!
86//! [`redis`]: https://docs.rs/redis/latest/redis/
87
88mod commands;
89#[cfg(test)]
90mod tests;
91pub mod types;
92
93use std::sync::{Arc, OnceLock};
94
95use encore_sdk_core::cache::{self as core_cache, redis as rs, Client};
96
97use crate::error::{ErrCode, Error};
98use crate::runtime::core;
99use crate::testing;
100
101pub use self::commands::{
102    bitmap, generic, geo, hash, list, pubsub, set, sorted_set, stream, string, Scan, ScanOptions,
103};
104pub use self::types::{FromRedisValue, Increment, Json, ToRedisArgs, Value};
105pub use rs::{Direction, ExistenceCheck, Expiry, SetExpiry, SetOptions};
106
107use self::commands::{strip_reply_keys, Cmd};
108
109/// What a database evicts when it runs out of memory.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum EvictionPolicy {
112    /// Evict nothing: a write that needs memory fails.
113    NoEviction,
114    /// The least recently used key, of all keys.
115    AllKeysLru,
116    /// The least frequently used key, of all keys.
117    AllKeysLfu,
118    /// A random key, of all keys.
119    AllKeysRandom,
120    /// The least recently used key, of those with an expiry.
121    VolatileLru,
122    /// The least frequently used key, of those with an expiry.
123    VolatileLfu,
124    /// The key closest to expiring.
125    VolatileTtl,
126    /// A random key, of those with an expiry.
127    VolatileRandom,
128}
129
130/// A Redis database, backed by a lazily-built connection pool.
131pub struct Database {
132    name: &'static str,
133    /// Read by Encore's parser from the declaration, not by the runtime.
134    #[allow(dead_code)]
135    persistent: bool,
136    #[allow(dead_code)]
137    eviction_policy: Option<EvictionPolicy>,
138    client: OnceLock<Arc<Client>>,
139}
140
141impl Database {
142    /// Declare a database. `const` so it can initialize a module-scope
143    /// `static`; the pool is built on first use.
144    ///
145    /// Options follow the name, each a method of its own:
146    ///
147    /// ```no_run
148    /// use encore::storage::redis::{Database, EvictionPolicy};
149    ///
150    /// static SESSIONS: Database = Database::new("sessions");
151    /// static LEDGER: Database = Database::new("ledger").persistent();
152    /// static THUMBNAILS: Database =
153    ///     Database::new("thumbnails").eviction_policy(EvictionPolicy::AllKeysLfu);
154    /// ```
155    pub const fn new(name: &'static str) -> Self {
156        Self {
157            name,
158            persistent: false,
159            eviction_policy: None,
160            client: OnceLock::new(),
161        }
162    }
163
164    /// Reference an existing database by name. To declare a new database, use
165    /// [`Database::new`] instead.
166    ///
167    /// The name must be a string literal, so Encore can resolve it statically.
168    /// A named database takes no options: it is configured where it is
169    /// declared.
170    pub const fn named(name: &'static str) -> Self {
171        Self::new(name)
172    }
173
174    /// The data must survive a restart, and is never evicted. Without it a
175    /// database is a cache: what it holds may be lost or evicted.
176    ///
177    /// Part of the declaration: it takes the database by value, so it cannot
178    /// be called on the `static`.
179    pub const fn persistent(mut self) -> Self {
180        self.persistent = true;
181        self
182    }
183
184    /// What to evict when the database runs out of memory. The least recently
185    /// used key, unless said otherwise. A [`Database::persistent`] database
186    /// evicts nothing and takes no policy.
187    pub const fn eviction_policy(mut self, policy: EvictionPolicy) -> Self {
188        self.eviction_policy = Some(policy);
189        self
190    }
191
192    /// A handle to the database that can read and write.
193    ///
194    /// `const`, so a handle can initialize a module-scope `static`.
195    pub const fn write(&'static self) -> DatabaseRef {
196        DatabaseRef { db: self }
197    }
198
199    /// A handle to the database that can only read, which may connect to a
200    /// read replica. To always read from the primary server, use
201    /// [`Database::read_primary`].
202    pub const fn read(&'static self) -> ReadOnlyDatabaseRef {
203        ReadOnlyDatabaseRef {
204            db: self,
205            primary: false,
206        }
207    }
208
209    /// A handle to the database that can only read, and connects to the
210    /// primary server even if there are read replicas available.
211    pub const fn read_primary(&'static self) -> ReadOnlyDatabaseRef {
212        ReadOnlyDatabaseRef {
213            db: self,
214            primary: true,
215        }
216    }
217
218    /// The client commands run on: the database's own, or under `encore test`
219    /// the one of the current test's instance of it (see [`crate::testing`]).
220    fn client(&self) -> Result<Arc<Client>, Error> {
221        // Never set under `encore test`, where the test's own comes first.
222        if let Some(client) = self.client.get() {
223            return Ok(client.clone());
224        }
225        if let Some(test) = testing::active()? {
226            return test.redis_client(self.name);
227        }
228        let client = core()
229            .cache()
230            .cluster(&self.name.into())
231            .client()
232            .map_err(|err| Error::wrap(ErrCode::Unavailable, format!("{err:#}")))?;
233        // A concurrent caller may win the race; either way `get` returns one.
234        let _ = self.client.set(Arc::new(client));
235        Ok(self.client.get().expect("client just set").clone())
236    }
237}
238
239/// A handle to a [`Database`] that can read and write, made by
240/// [`Database::write`]. `Copy`, and free to pass to other code.
241#[derive(Clone, Copy)]
242pub struct DatabaseRef {
243    db: &'static Database,
244}
245
246/// A handle to a [`Database`] that can only read, made by [`Database::read`]
247/// or [`Database::read_primary`]. `Copy`, and free to pass to other code.
248///
249/// Its command groups hold the commands that read, and nothing else.
250#[derive(Clone, Copy)]
251pub struct ReadOnlyDatabaseRef {
252    db: &'static Database,
253    /// The runtime gives a database one pool for now, on the primary, which
254    /// every handle shares.
255    #[allow(dead_code)]
256    primary: bool,
257}
258
259/// The command groups, as methods returning `$form` of each.
260macro_rules! groups {
261    ($form:ident<$lt:lifetime>, |$this:ident| $target:expr) => {
262        groups!(@each $form<$lt>, |$this| $target;
263            /// Commands that work on a key of any type: expiry, deletion, renaming.
264            generic,
265            /// Commands on strings, which is what a plain value is.
266            string,
267            /// Commands on the bits of a string.
268            bitmap,
269            /// Commands on hashes: a key holding fields, each with a value.
270            hash,
271            /// Commands on lists.
272            list,
273            /// Commands on sets.
274            set,
275            /// Commands on sorted sets: members ordered by a score.
276            sorted_set,
277            /// Commands on geospatial indexes.
278            geo,
279            /// Commands on streams.
280            stream,
281            /// Publishing to channels, and subscribing to them.
282            pubsub,
283        );
284    };
285    (@each $form:ident<$lt:lifetime>, |$this:ident| $target:expr; $($(#[$doc:meta])* $group:ident,)*) => {
286        $(
287            $(#[$doc])*
288            pub fn $group(&self) -> $group::$form<$lt> {
289                let $this = self;
290                $group::$form { target: $target }
291            }
292        )*
293    };
294}
295
296/// The command groups, as methods returning each one's queue.
297macro_rules! queues {
298    () => {
299        queues!(@each generic, string, bitmap, hash, list, set, sorted_set, geo, stream, pubsub);
300    };
301    (@each $($group:ident),*) => {
302        $(
303            /// Queues commands of this group. Nothing is sent until `exec`.
304            pub fn $group(&mut self) -> $group::Queue<'_> {
305                $group::Queue { queue: &mut self.queued }
306            }
307        )*
308
309        /// Queues a call to `script`. Finish it with [`QueuedInvocation::queue`].
310        pub fn script(&mut self, script: &'static Script) -> QueuedInvocation<'_> {
311            QueuedInvocation {
312                queue: &mut self.queued,
313                script,
314                keys: Vec::new(),
315                args: Vec::new(),
316            }
317        }
318
319        /// How many commands are queued.
320        pub fn len(&self) -> usize {
321            self.queued.commands.len()
322        }
323
324        /// Whether nothing is queued.
325        pub fn is_empty(&self) -> bool {
326            self.queued.commands.is_empty()
327        }
328    };
329}
330
331/// What reading and writing handles share, the [`Database`] among them.
332macro_rules! writer_methods {
333    ($lt:lifetime, |$this:ident| $db:expr) => {
334        groups!(Commands<$lt>, |$this| Target::Database($db));
335
336        /// A batch of commands sent in one round trip. Not a transaction:
337        /// other clients' commands may run between them, and one failing does
338        /// not stop the rest.
339        ///
340        /// ```no_run
341        /// # use encore::storage::redis::Database;
342        /// # static SESSIONS: Database = Database::new("sessions");
343        /// # async fn example() -> Result<(), encore::Error> {
344        /// let mut pipe = SESSIONS.pipeline();
345        /// pipe.string().get("name:1");
346        /// pipe.string().get("name:2");
347        /// let (first, second): (Option<String>, Option<String>) = pipe.exec().await?;
348        /// # Ok(())
349        /// # }
350        /// ```
351        pub fn pipeline(&self) -> Pipeline<$lt> {
352            let $this = self;
353            Pipeline {
354                target: Target::Database($db),
355                queued: Queued::default(),
356            }
357        }
358
359        /// A transaction (`MULTI`/`EXEC`): the commands queued on it run
360        /// together, with no other client's in between, or not at all.
361        ///
362        /// Nothing is sent until [`Transaction::exec`], so a transaction is
363        /// never left open across an `.await`.
364        ///
365        /// ```no_run
366        /// # use encore::storage::redis::Database;
367        /// # static LEDGER: Database = Database::new("ledger").persistent();
368        /// # async fn example(now: u64) -> Result<(), encore::Error> {
369        /// let mut tx = LEDGER.transaction();
370        /// tx.string().incr("hits", 1);
371        /// tx.hash().hset("user:1", "seen", now);
372        /// let (hits, _): (i64, u64) = tx.exec().await?;
373        /// # Ok(())
374        /// # }
375        /// ```
376        pub fn transaction(&self) -> Transaction<$lt> {
377            let $this = self;
378            Transaction {
379                target: Target::Database($db),
380                queued: Queued::default(),
381            }
382        }
383
384        /// Takes a connection out of the pool, for what must run on one
385        /// connection: watching keys, then a transaction that depends on them.
386        /// It is returned to the pool when dropped.
387        pub async fn acquire(&self) -> Result<Connection, Error> {
388            let $this = self;
389            let client = ($db).client()?;
390            let inner = client.acquire().await.map_err(redis_err)?;
391            Ok(Connection {
392                inner: tokio::sync::Mutex::new(inner),
393                client,
394            })
395        }
396
397        /// Runs `body` as an optimistic transaction on `keys`: it reads what
398        /// it needs through the connection, queues its changes on the
399        /// transaction, and the changes are applied only if none of `keys`
400        /// changed in between. If one did, `body` runs again.
401        ///
402        /// ```no_run
403        /// # use encore::storage::redis::Database;
404        /// # static LEDGER: Database = Database::new("ledger").persistent();
405        /// # async fn example() -> Result<(), encore::Error> {
406        /// let left: i64 = LEDGER
407        ///     .watch("balance", async |conn, tx| {
408        ///         let balance: i64 = conn.string().get("balance").await?;
409        ///         tx.string().set("balance", balance - 10);
410        ///         Ok(balance - 10)
411        ///     })
412        ///     .await?;
413        /// # Ok(())
414        /// # }
415        /// ```
416        pub async fn watch<T>(
417            &self,
418            keys: impl ToRedisArgs,
419            mut body: impl AsyncFnMut(&Connection, &mut WatchedTransaction<'_>) -> Result<T, Error>,
420        ) -> Result<T, Error> {
421            /// A key changing this many times in a row is not contention that
422            /// another attempt will get past.
423            const ATTEMPTS: usize = 64;
424
425            let keys = keys.to_redis_args();
426            let conn = self.acquire().await?;
427            for _ in 0..ATTEMPTS {
428                conn.watch(&keys).await?;
429                let mut tx = conn.transaction();
430                let out = body(&conn, &mut tx).await?;
431                if tx.exec::<Value>().await?.is_some() {
432                    return Ok(out);
433                }
434            }
435            Err(Error::new(
436                ErrCode::Aborted,
437                format!("the watched keys kept changing: gave up after {ATTEMPTS} attempts"),
438            ))
439        }
440
441        /// A call to `script`, to give its keys and arguments and then
442        /// [`Invocation::invoke`].
443        pub fn script(&self, script: &'static Script) -> Invocation<$lt> {
444            let $this = self;
445            Invocation {
446                target: Target::Database($db),
447                script,
448                read_only: false,
449                keys: Vec::new(),
450                args: Vec::new(),
451            }
452        }
453
454        /// The connection string to connect to this database with, for a
455        /// client other than this SDK's.
456        ///
457        /// It connects past the database's key prefix (see the [module
458        /// docs](self#keys)): what that client stores under a name is not what
459        /// this SDK reads under it.
460        pub fn connection_string(&self) -> Result<String, Error> {
461            let $this = self;
462            Ok(($db).client()?.connection_url())
463        }
464    };
465}
466
467impl Database {
468    writer_methods!('_, |this| this);
469}
470
471impl DatabaseRef {
472    writer_methods!('static, |this| this.db);
473}
474
475impl ReadOnlyDatabaseRef {
476    groups!(ReadCommands<'static>, |this| Target::Database(this.db));
477
478    /// A call to `script`, which must be a [`Script::read_only`] one.
479    pub fn script(&self, script: &'static Script) -> Invocation<'static> {
480        Invocation {
481            target: Target::Database(self.db),
482            script,
483            read_only: true,
484            keys: Vec::new(),
485            args: Vec::new(),
486        }
487    }
488}
489
490/// Where a command runs: on a connection from the database's pool, or on one
491/// taken out of it.
492#[derive(Clone, Copy)]
493pub(crate) enum Target<'a> {
494    Database(&'a Database),
495    Connection(&'a Connection),
496}
497
498impl Target<'_> {
499    fn client(&self) -> Result<Arc<Client>, Error> {
500        match self {
501            Target::Database(db) => db.client(),
502            Target::Connection(conn) => Ok(conn.client.clone()),
503        }
504    }
505
506    /// Runs `cmd`, returning Redis's reply as it came.
507    async fn reply(self, cmd: &core_cache::Command) -> Result<Value, core_cache::OpError> {
508        match self {
509            Target::Database(db) => match db.client() {
510                Ok(client) => client.execute(cmd).await,
511                Err(err) => Err(unavailable(cmd, err)),
512            },
513            Target::Connection(conn) => conn.inner.lock().await.execute(cmd).await,
514        }
515    }
516
517    /// Runs `cmd` and converts its reply.
518    pub(crate) async fn run<T: FromRedisValue>(self, cmd: Cmd) -> Result<T, Error> {
519        let mut value = self.reply(&cmd.inner).await.map_err(redis_err)?;
520        if cmd.reply_keys {
521            strip_reply_keys(&mut value, self.client()?.key_prefix());
522        }
523        T::from_redis_value(value)
524    }
525
526    /// Runs `queued` in one round trip — as a transaction, if `atomic` — and
527    /// returns its replies as one array. `None` for a transaction that did
528    /// not run because a watched key changed.
529    async fn run_all(self, queued: Queued, atomic: bool) -> Result<Option<Value>, Error> {
530        let commands: Vec<core_cache::Command> = queued
531            .commands
532            .iter()
533            .map(|cmd| cmd.inner.clone())
534            .collect();
535        let client = self.client()?;
536        let replies = match self {
537            Target::Database(_) => Some(client.execute_all(&commands, atomic).await),
538            Target::Connection(conn) => conn
539                .inner
540                .lock()
541                .await
542                .execute_all(&commands, atomic)
543                .await
544                .transpose(),
545        };
546        let Some(replies) = replies else {
547            return Ok(None);
548        };
549        let mut replies = replies.map_err(redis_err)?;
550        for (cmd, reply) in queued.commands.iter().zip(&mut replies) {
551            if cmd.reply_keys {
552                strip_reply_keys(reply, client.key_prefix());
553            }
554        }
555        Ok(Some(Value::Array(replies)))
556    }
557}
558
559/// The error for a command that could not be sent at all, in the shape the
560/// ones that were sent fail with.
561fn unavailable(cmd: &core_cache::Command, err: Error) -> core_cache::OpError {
562    core_cache::OpError::new(
563        cmd.operation(),
564        "",
565        core_cache::Error::Redis(std::io::Error::other(err.message).into()),
566    )
567}
568
569/// The commands queued on a [`Pipeline`] or a transaction.
570#[derive(Default)]
571pub(crate) struct Queued {
572    commands: Vec<Cmd>,
573}
574
575impl Queued {
576    pub(crate) fn push(&mut self, cmd: Cmd) {
577        self.commands.push(cmd);
578    }
579}
580
581/// A batch of commands sent in one round trip, made by
582/// [`Database::pipeline`]. Not a transaction.
583pub struct Pipeline<'a> {
584    target: Target<'a>,
585    queued: Queued,
586}
587
588impl Pipeline<'_> {
589    queues!();
590
591    /// Sends the queued commands and returns their replies, in order, as a
592    /// tuple or a `Vec`.
593    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
594        let replies = self.target.run_all(self.queued, false).await?;
595        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
596    }
597}
598
599/// A transaction, made by [`Database::transaction`]: the commands queued on it
600/// run together or not at all.
601pub struct Transaction<'a> {
602    target: Target<'a>,
603    queued: Queued,
604}
605
606impl Transaction<'_> {
607    queues!();
608
609    /// Runs the queued commands as one transaction and returns their replies,
610    /// in order, as a tuple or a `Vec`.
611    pub async fn exec<T: FromRedisValue>(self) -> Result<T, Error> {
612        let replies = self.target.run_all(self.queued, true).await?;
613        T::from_redis_value(replies.unwrap_or(Value::Array(Vec::new())))
614    }
615
616    /// Abandons the transaction. Nothing was sent, so there is nothing to
617    /// undo: this is dropping it, by name.
618    pub fn discard(self) {}
619}
620
621/// A transaction on a [`Connection`], made by [`Connection::transaction`]: it
622/// does nothing if a key the connection watches has changed.
623pub struct WatchedTransaction<'a> {
624    target: Target<'a>,
625    queued: Queued,
626}
627
628impl WatchedTransaction<'_> {
629    queues!();
630
631    /// Runs the queued commands as one transaction and returns their replies.
632    /// `None` if a watched key changed, in which case none of them ran. Either
633    /// way the connection watches nothing afterwards.
634    pub async fn exec<T: FromRedisValue>(&mut self) -> Result<Option<T>, Error> {
635        let queued = std::mem::take(&mut self.queued);
636        match self.target.run_all(queued, true).await? {
637            Some(replies) => T::from_redis_value(replies).map(Some),
638            None => Ok(None),
639        }
640    }
641}
642
643/// A connection taken out of the database's pool, made by
644/// [`Database::acquire`]. It is returned to the pool when dropped.
645pub struct Connection {
646    inner: tokio::sync::Mutex<core_cache::Connection>,
647    client: Arc<Client>,
648}
649
650impl Connection {
651    groups!(Commands<'_>, |this| Target::Connection(this));
652
653    /// Watches `keys`: a [`Connection::transaction`] then does nothing if any
654    /// of them has changed by the time it is run.
655    pub async fn watch(&self, keys: impl ToRedisArgs) -> Result<(), Error> {
656        self.inner
657            .lock()
658            .await
659            .watch(&keys.to_redis_args())
660            .await
661            .map_err(redis_err)
662    }
663
664    /// Stops watching every key.
665    pub async fn unwatch(&self) -> Result<(), Error> {
666        self.inner.lock().await.unwatch().await.map_err(redis_err)
667    }
668
669    /// A transaction on this connection, which depends on the keys it watches.
670    pub fn transaction(&self) -> WatchedTransaction<'_> {
671        WatchedTransaction {
672            target: Target::Connection(self),
673            queued: Queued::default(),
674        }
675    }
676
677    /// A batch of commands sent in one round trip on this connection.
678    pub fn pipeline(&self) -> Pipeline<'_> {
679        Pipeline {
680            target: Target::Connection(self),
681            queued: Queued::default(),
682        }
683    }
684
685    /// A call to `script` on this connection.
686    pub fn script(&self, script: &'static Script) -> Invocation<'_> {
687        Invocation {
688            target: Target::Connection(self),
689            script,
690            read_only: false,
691            keys: Vec::new(),
692            args: Vec::new(),
693        }
694    }
695}
696
697/// A Lua script the database runs, declared at module scope.
698///
699/// ```no_run
700/// use encore::storage::redis::{Database, Script};
701///
702/// static LOCKS: Database = Database::new("locks");
703///
704/// static RELEASE: Script = Script::new(
705///     r#"
706///     if redis.call("get", KEYS[1]) == ARGV[1] then
707///         return redis.call("del", KEYS[1])
708///     end
709///     return 0
710///     "#,
711/// );
712///
713/// async fn release(job: &str, token: &str) -> Result<bool, encore::Error> {
714///     LOCKS.script(&RELEASE).key(format!("lock:{job}")).arg(token).invoke().await
715/// }
716/// ```
717///
718/// Only the keys a script is passed, through `KEYS`, get the database's key
719/// prefix (see the [module docs](self#keys)). Its source and `ARGV` are sent as
720/// they are: a key the script names itself, or builds from an argument,
721/// reaches the server unprefixed, outside the database's isolation. Nothing
722/// checks this, so a script must take every key it uses through `KEYS`.
723pub struct Script {
724    source: &'static str,
725    read_only: bool,
726    /// The source's SHA-1, which the server caches the script under.
727    hash: OnceLock<String>,
728}
729
730impl Script {
731    /// Declare a script. `const`, so it can initialize a module-scope `static`.
732    pub const fn new(source: &'static str) -> Self {
733        Self {
734            source,
735            read_only: false,
736            hash: OnceLock::new(),
737        }
738    }
739
740    /// Declare a script that only reads. The server refuses to let it write,
741    /// which is what lets it run on a [`ReadOnlyDatabaseRef`].
742    pub const fn read_only(source: &'static str) -> Self {
743        Self {
744            source,
745            read_only: true,
746            hash: OnceLock::new(),
747        }
748    }
749
750    fn hash(&self) -> &str {
751        self.hash
752            .get_or_init(|| rs::Script::new(self.source).get_hash().to_string())
753    }
754
755    /// The command that runs the script: by its hash, which the server has if
756    /// it has run it before, or by its source.
757    fn command(&self, by_hash: bool, keys: &[Vec<u8>], args: &[Vec<u8>]) -> core_cache::Command {
758        let name = match (by_hash, self.read_only) {
759            (true, false) => "EVALSHA",
760            (true, true) => "EVALSHA_RO",
761            (false, false) => "EVAL",
762            (false, true) => "EVAL_RO",
763        };
764        let mut cmd = core_cache::Command::new("script", name, !self.read_only)
765            .arg(if by_hash { self.hash() } else { self.source })
766            .arg(keys.len().to_string());
767        for key in keys {
768            cmd = cmd.key(key.as_slice());
769        }
770        for arg in args {
771            cmd = cmd.arg(arg.as_slice());
772        }
773        cmd
774    }
775}
776
777/// A call to a [`Script`], made by [`Database::script`].
778pub struct Invocation<'a> {
779    target: Target<'a>,
780    script: &'static Script,
781    /// Whether the handle it was made from can only read.
782    read_only: bool,
783    keys: Vec<Vec<u8>>,
784    args: Vec<Vec<u8>>,
785}
786
787impl Invocation<'_> {
788    /// A key the script works on: the next of its `KEYS`.
789    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
790        self.keys.extend(key.to_redis_args());
791        self
792    }
793
794    /// An argument: the next of the script's `ARGV`, sent without the
795    /// database's key prefix.
796    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
797        self.args.extend(arg.to_redis_args());
798        self
799    }
800
801    /// Runs the script and converts what it returns.
802    pub async fn invoke<T: FromRedisValue>(self) -> Result<T, Error> {
803        if self.read_only && !self.script.read_only {
804            return Err(Error::new(
805                ErrCode::FailedPrecondition,
806                "a handle that can only read runs only scripts declared with `Script::read_only`",
807            ));
808        }
809        let by_hash = self.script.command(true, &self.keys, &self.args);
810        let value = match self.target.reply(&by_hash).await {
811            Ok(value) => value,
812            // The server has not seen the script: send it, which also caches it.
813            Err(err) if is_no_script(&err) => {
814                let by_source = self.script.command(false, &self.keys, &self.args);
815                self.target.reply(&by_source).await.map_err(redis_err)?
816            }
817            Err(err) => return Err(redis_err(err)),
818        };
819        T::from_redis_value(value)
820    }
821}
822
823/// A call to a [`Script`] being queued on a pipeline or a transaction.
824pub struct QueuedInvocation<'a> {
825    queue: &'a mut Queued,
826    script: &'static Script,
827    keys: Vec<Vec<u8>>,
828    args: Vec<Vec<u8>>,
829}
830
831impl QueuedInvocation<'_> {
832    /// A key the script works on: the next of its `KEYS`.
833    pub fn key(mut self, key: impl ToRedisArgs) -> Self {
834        self.keys.extend(key.to_redis_args());
835        self
836    }
837
838    /// An argument: the next of the script's `ARGV`, sent without the
839    /// database's key prefix.
840    pub fn arg(mut self, arg: impl ToRedisArgs) -> Self {
841        self.args.extend(arg.to_redis_args());
842        self
843    }
844
845    /// Queues the call. Sent by source rather than by hash: a batch cannot
846    /// stop halfway to send a script the server turns out not to have.
847    pub fn queue(self) {
848        let inner = self.script.command(false, &self.keys, &self.args);
849        self.queue.push(Cmd::from_core(inner));
850    }
851}
852
853/// Whether a command failed because the server does not have the script its
854/// hash names.
855fn is_no_script(err: &core_cache::OpError) -> bool {
856    matches!(
857        &err.source,
858        core_cache::Error::Redis(err)
859            if err.kind() == rs::ErrorKind::Server(rs::ServerErrorKind::NoScript)
860    )
861}
862
863fn redis_err(err: core_cache::OpError) -> Error {
864    Error::wrap(ErrCode::Unavailable, err)
865}