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