Skip to main content

adk_session/
redis.rs

1//! Redis-backed session service.
2//!
3//! Uses `fred` for async Redis operations with support for standalone
4//! and cluster deployments. Sessions are stored as Redis hashes, events
5//! as sorted sets (scored by append sequence), and state tiers as separate hashes.
6//!
7//! # Data Model
8//!
9//! The service picks its key layout from the connection: a standalone server (or Sentinel)
10//! keeps the names every release has written, and a Redis Cluster connection (`cluster_nodes`
11//! or a `redis-cluster://` URL) puts each session's keys under one hash tag.
12//!
13//! | Contents | Type | Standalone key | Cluster key |
14//! |---|---|---|---|
15//! | Session metadata + session-tier state | Hash | `<app>:<user>:<session>` | `adk:session:{<app>:<user>:<session>}` |
16//! | Events scored by append sequence | Sorted Set | `<app>:<user>:<session>:events` | `adk:session:{<app>:<user>:<session>}:events` |
17//! | App-tier state | Hash | `app_state:<app>` | `adk:app_state:{<app>}` |
18//! | User-tier state | Hash | `user_state:<app>:<user>` | `adk:user_state:{<app>:<user>}` |
19//! | Session IDs of an app and user | Set | `sessions_idx:<app>:<user>` | `adk:sessions_idx:{<app>:<user>}` |
20//! | Session IDs scored by last update (µs) | Sorted Set | `sessions_idx:<app>:<user>:updated` | `adk:sessions_idx:{<app>:<user>}:updated` |
21//! | Reverse lookup to `<app>:<user>` | String | `session_lookup:<session>` | `adk:session_lookup:{<session>}` |
22//!
23//! Each `<segment>` is percent-encoded (`%` → `%25`, `:` → `%3A`) so an identifier
24//! containing `:` cannot spill into the next segment. In the standalone layout an app name
25//! equal to one of the key-family prefixes (`app_state`, `user_state`, `sessions_idx`,
26//! `session_lookup`) has its first byte encoded too (`user_state` → `%75ser_state`) in the
27//! keys that start with the app name, and identifiers without these characters or names
28//! produce the same keys as before the encoding was introduced. The cluster layout also
29//! encodes `{` (`%7B`) and `}` (`%7D`), so no identifier can move a key's hash slot.
30//!
31//! Standalone servers keep the standalone layout so sessions written by earlier releases
32//! stay readable. Moving a deployment from a standalone server to a cluster means copying
33//! its keys to the cluster names.
34//!
35//! # Ordering
36//!
37//! Each event is scored one above the highest score in its sorted set, so reads return
38//! events in append order, and `get` then orders them by timestamp, keeping append order
39//! among equal timestamps. Events written by earlier releases are scored by their timestamp
40//! in milliseconds, so they keep their order, and events appended to such a session are
41//! scored after them.
42//!
43//! `list` pages through the `:updated` sorted set, newest first, with ties by session ID
44//! descending. Sessions created by earlier releases are in the set index only; `list` adds
45//! them to the sorted set, scored by their `updated_at`, when the two indexes differ in size.
46//!
47//! # Atomicity
48//!
49//! | Operation | Standalone | Cluster |
50//! |---|---|---|
51//! | `create` | One script that writes nothing when the session hash exists: session hash, app and user tier fields, index entries, lookup | A check that the session hash is absent; index entries, lookup, and the app and user tier fields; then the session hash, in a script that writes nothing when it exists |
52//! | `append_event` | One script: event, session-tier compare-and-swap, update-time index entry, app and user tier fields | One script: event and session-tier compare-and-swap; then the update-time index entry and the app and the user tier fields, one command each |
53//! | `delete` | One `MULTI`/`EXEC`: session hash, events, lookup, index entries | Session hash and events in one `DEL`, then the lookup and the index entries |
54//! | `delete_all_sessions` | One `MULTI`/`EXEC` over every session of the user, the index and the user tier | Each session as in `delete`, then the index and the user tier |
55//!
56//! A Redis Cluster runs a script or transaction only when every key it names hashes to one
57//! slot, and the app and user tiers are shared by many sessions, so in cluster mode they are
58//! written outside the session's script. The session tier keeps its compare-and-swap, and
59//! tier fields are still written one field at a time, so concurrent writers of different
60//! fields keep each other's values. What changes in cluster mode:
61//!
62//! - A reader can see an appended event before its app and user tier fields.
63//! - An append that fails after its script returns an error with the event already stored.
64//! - A `create` that fails part-way can leave its app and user tier fields, and index
65//!   entries and a lookup for a session that does not exist; `list` skips and removes such
66//!   entries, and `get` reports the session as not found.
67//! - Of two `create` calls racing for one identity, the one that loses fails with
68//!   `session.already_exists` after its app and user tier fields are written.
69//!
70//! Every operation validates its identifiers (non-empty, at most
71//! [`MAX_ID_LEN`](adk_core::identity::MAX_ID_LEN) bytes, no NUL) before it sends a command.
72
73use crate::history::{HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, SessionHistory};
74use crate::service::{
75    identity_not_found, session_already_exists, session_id_not_found, session_not_found_for,
76    validate_scope, validate_session_id,
77};
78use crate::{
79    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
80    ListRequest, Session, SessionService, State, state_utils,
81};
82use adk_core::identity::AdkIdentity;
83use adk_core::{ErrorCategory, ErrorComponent, Result};
84use async_trait::async_trait;
85use chrono::{DateTime, Utc};
86use fred::prelude::*;
87use serde_json::Value;
88use std::borrow::Cow;
89use std::collections::HashMap;
90use std::time::Duration;
91use tracing::instrument;
92use uuid::Uuid;
93
94/// Configuration for connecting to Redis.
95///
96/// The `Debug` output redacts credentials embedded in `url` (the userinfo
97/// password and any `*password*` query parameter), so the config is safe to log.
98#[derive(Clone)]
99pub struct RedisSessionConfig {
100    /// Redis connection URL (e.g. `redis://localhost:6379`).
101    pub url: String,
102    /// Optional TTL applied to session and events keys.
103    pub ttl: Option<Duration>,
104    /// Optional cluster node addresses for cluster mode.
105    pub cluster_nodes: Option<Vec<String>>,
106}
107
108impl std::fmt::Debug for RedisSessionConfig {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.debug_struct("RedisSessionConfig")
111            .field("url", &redact_url_credentials(&self.url))
112            .field("ttl", &self.ttl)
113            .field("cluster_nodes", &self.cluster_nodes)
114            .finish()
115    }
116}
117
118const REDACTED: &str = "[REDACTED]";
119
120/// Replaces the userinfo password and every `*password*` query value of a
121/// connection URL with `[REDACTED]`.
122fn redact_url_credentials(url: &str) -> String {
123    let (base, query) = match url.split_once('?') {
124        Some((base, query)) => (base, Some(query)),
125        None => (url, None),
126    };
127
128    let mut redacted = match base.split_once("://") {
129        Some((scheme, rest)) => {
130            let authority_end = rest.find('/').unwrap_or(rest.len());
131            let (authority, path) = rest.split_at(authority_end);
132            match authority.rsplit_once('@') {
133                // Without a `user:` prefix the whole userinfo can be a bare password.
134                Some((userinfo, host)) => match userinfo.split_once(':') {
135                    Some((user, _password)) => format!("{scheme}://{user}:{REDACTED}@{host}{path}"),
136                    None => format!("{scheme}://{REDACTED}@{host}{path}"),
137                },
138                None => base.to_string(),
139            }
140        }
141        None => base.to_string(),
142    };
143
144    if let Some(query) = query {
145        let params: Vec<String> = query
146            .split('&')
147            .map(|param| match param.split_once('=') {
148                Some((name, _value)) if name.to_ascii_lowercase().contains("password") => {
149                    format!("{name}={REDACTED}")
150                }
151                _ => param.to_string(),
152            })
153            .collect();
154        redacted.push('?');
155        redacted.push_str(&params.join("&"));
156    }
157
158    redacted
159}
160
161// --- Key generation functions ---
162
163/// Prefixes of the key families that do not start with the app name.
164///
165/// A session key for an app with one of these names would otherwise share the
166/// keyspace of that family, e.g. `session_key("user_state", a, u)` and
167/// `user_state_key(a, u)`.
168const RESERVED_PREFIXES: [&str; 4] = ["app_state", "user_state", "sessions_idx", "session_lookup"];
169
170/// Percent-encodes `%` and `:` so an encoded segment never contains the `:` delimiter.
171fn encode_segment(segment: &str) -> Cow<'_, str> {
172    if !segment.contains([':', '%']) {
173        return Cow::Borrowed(segment);
174    }
175    let mut encoded = String::with_capacity(segment.len() + 8);
176    for c in segment.chars() {
177        match c {
178            '%' => encoded.push_str("%25"),
179            ':' => encoded.push_str("%3A"),
180            other => encoded.push(other),
181        }
182    }
183    Cow::Owned(encoded)
184}
185
186/// Percent-encodes `%`, `:`, `{`, and `}`, so a segment of a cluster key can neither spill
187/// into the next segment nor move the key's hash slot.
188fn encode_cluster_segment(segment: &str) -> Cow<'_, str> {
189    if !segment.contains([':', '%', '{', '}']) {
190        return Cow::Borrowed(segment);
191    }
192    let mut encoded = String::with_capacity(segment.len() + 8);
193    for c in segment.chars() {
194        match c {
195            '%' => encoded.push_str("%25"),
196            ':' => encoded.push_str("%3A"),
197            '{' => encoded.push_str("%7B"),
198            '}' => encoded.push_str("%7D"),
199            other => encoded.push(other),
200        }
201    }
202    Cow::Owned(encoded)
203}
204
205/// Reverses [`encode_segment`].
206///
207/// Only `%25` and `%3A` are decoded; any other `%` is kept as written, so
208/// lookup values stored before the encoding existed still parse.
209fn decode_segment(segment: &str) -> Cow<'_, str> {
210    if !segment.contains('%') {
211        return Cow::Borrowed(segment);
212    }
213    let mut decoded = String::with_capacity(segment.len());
214    let mut rest = segment;
215    while let Some(pos) = rest.find('%') {
216        decoded.push_str(&rest[..pos]);
217        match rest.get(pos..pos + 3) {
218            Some("%25") => decoded.push('%'),
219            Some("%3A" | "%3a") => decoded.push(':'),
220            _ => {
221                decoded.push('%');
222                rest = &rest[pos + 1..];
223                continue;
224            }
225        }
226        rest = &rest[pos + 3..];
227    }
228    decoded.push_str(rest);
229    Cow::Owned(decoded)
230}
231
232/// Encodes the app segment of keys that start with the app name.
233///
234/// Applies [`encode_segment`], then encodes the first byte of an app name that
235/// equals a [`RESERVED_PREFIXES`] entry.
236fn leading_app_segment(app: &str) -> Cow<'_, str> {
237    let encoded = encode_segment(app);
238    if RESERVED_PREFIXES.contains(&encoded.as_ref()) {
239        // Reserved prefixes are ASCII, so the first byte is a whole character.
240        let (first, rest) = encoded.split_at(1);
241        return Cow::Owned(format!("%{:02X}{rest}", first.as_bytes()[0]));
242    }
243    encoded
244}
245
246/// Session metadata hash key of the standalone layout: `<app>:<user>:<session>`.
247pub fn session_key(app: &str, user: &str, session: &str) -> String {
248    format!("{}:{}:{}", leading_app_segment(app), encode_segment(user), encode_segment(session))
249}
250
251/// Events sorted set key of the standalone layout: `<app>:<user>:<session>:events`.
252pub fn events_key(app: &str, user: &str, session: &str) -> String {
253    format!(
254        "{}:{}:{}:events",
255        leading_app_segment(app),
256        encode_segment(user),
257        encode_segment(session)
258    )
259}
260
261/// App-level state hash key of the standalone layout: `app_state:<app>`.
262pub fn app_state_key(app: &str) -> String {
263    format!("app_state:{}", encode_segment(app))
264}
265
266/// User-level state hash key of the standalone layout: `user_state:<app>:<user>`.
267pub fn user_state_key(app: &str, user: &str) -> String {
268    format!("user_state:{}:{}", encode_segment(app), encode_segment(user))
269}
270
271/// Session index set key of the standalone layout: `sessions_idx:<app>:<user>`.
272pub fn index_key(app: &str, user: &str) -> String {
273    format!("sessions_idx:{}:{}", encode_segment(app), encode_segment(user))
274}
275
276/// Session index sorted set, scored by last update, of the standalone layout:
277/// `sessions_idx:<app>:<user>:updated`.
278pub fn updated_index_key(app: &str, user: &str) -> String {
279    format!("{}:updated", index_key(app, user))
280}
281
282/// Reverse lookup value naming the owner of a session: `<app>:<user>`.
283fn lookup_value(app: &str, user: &str) -> String {
284    format!("{}:{}", encode_segment(app), encode_segment(user))
285}
286
287/// Parses a [`lookup_value`] back into `(app, user)`.
288fn parse_lookup_value(value: &str) -> Option<(String, String)> {
289    let (app, user) = value.split_once(':')?;
290    Some((decode_segment(app).into_owned(), decode_segment(user).into_owned()))
291}
292
293/// The hash tag shared by one session's keys in the cluster layout.
294fn cluster_session_tag(app: &str, user: &str, session: &str) -> String {
295    format!(
296        "{{{}:{}:{}}}",
297        encode_cluster_segment(app),
298        encode_cluster_segment(user),
299        encode_cluster_segment(session)
300    )
301}
302
303/// Which key names a [`RedisSessionService`] reads and writes; see the module docs.
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305enum KeyLayout {
306    /// The names every release has written to a standalone server.
307    Standalone,
308    /// Hash-tagged names, so each session's keys share one Redis Cluster slot.
309    Cluster,
310}
311
312impl KeyLayout {
313    fn session(self, app: &str, user: &str, session: &str) -> String {
314        match self {
315            Self::Standalone => session_key(app, user, session),
316            Self::Cluster => format!("adk:session:{}", cluster_session_tag(app, user, session)),
317        }
318    }
319
320    fn events(self, app: &str, user: &str, session: &str) -> String {
321        match self {
322            Self::Standalone => events_key(app, user, session),
323            Self::Cluster => {
324                format!("adk:session:{}:events", cluster_session_tag(app, user, session))
325            }
326        }
327    }
328
329    fn app_state(self, app: &str) -> String {
330        match self {
331            Self::Standalone => app_state_key(app),
332            Self::Cluster => format!("adk:app_state:{{{}}}", encode_cluster_segment(app)),
333        }
334    }
335
336    fn user_state(self, app: &str, user: &str) -> String {
337        match self {
338            Self::Standalone => user_state_key(app, user),
339            Self::Cluster => format!(
340                "adk:user_state:{{{}:{}}}",
341                encode_cluster_segment(app),
342                encode_cluster_segment(user)
343            ),
344        }
345    }
346
347    fn index(self, app: &str, user: &str) -> String {
348        match self {
349            Self::Standalone => index_key(app, user),
350            Self::Cluster => format!(
351                "adk:sessions_idx:{{{}:{}}}",
352                encode_cluster_segment(app),
353                encode_cluster_segment(user)
354            ),
355        }
356    }
357
358    fn updated_index(self, app: &str, user: &str) -> String {
359        match self {
360            Self::Standalone => updated_index_key(app, user),
361            Self::Cluster => format!("{}:updated", self.index(app, user)),
362        }
363    }
364
365    fn lookup(self, session: &str) -> String {
366        match self {
367            Self::Standalone => format!("session_lookup:{}", encode_segment(session)),
368            Self::Cluster => {
369                format!("adk:session_lookup:{{{}}}", encode_cluster_segment(session))
370            }
371        }
372    }
373}
374
375/// Appends an event and its state delta in one atomic step.
376///
377/// `KEYS`: session hash, events sorted set, then the update-time index and the state tier
378/// hashes written in the same step (app, user), if any. `ARGV`: session-tier write flag
379/// (`"1"`), the `state` value the session hash must still hold, its replacement,
380/// `updated_at`, the event JSON, whether `KEYS[3]` is the update-time index (`"1"`), its score
381/// and member, then for each tier key a field count followed by that many field/value pairs.
382///
383/// The event is scored one above the highest score in the set. Returns `1` when applied, `0`
384/// when the session tier changed since it was read, and `-1` when the session does not exist.
385const APPEND_EVENT_SCRIPT: &str = r"
386if redis.call('EXISTS', KEYS[1]) == 0 then
387  return -1
388end
389if ARGV[1] == '1' then
390  local current = redis.call('HGET', KEYS[1], 'state')
391  if not current then
392    current = ''
393  end
394  if current ~= ARGV[2] then
395    return 0
396  end
397  redis.call('HSET', KEYS[1], 'state', ARGV[3])
398end
399redis.call('HSET', KEYS[1], 'updated_at', ARGV[4])
400local last = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
401local score = 1
402if last[2] then
403  score = math.floor(tonumber(last[2])) + 1
404end
405redis.call('ZADD', KEYS[2], string.format('%.0f', score), ARGV[5])
406local first_tier = 3
407if ARGV[6] == '1' then
408  redis.call('ZADD', KEYS[3], ARGV[7], ARGV[8])
409  first_tier = 4
410end
411local index = 9
412for tier = first_tier, #KEYS do
413  local count = tonumber(ARGV[index])
414  index = index + 1
415  for _ = 1, count do
416    redis.call('HSET', KEYS[tier], ARGV[index], ARGV[index + 1])
417    index = index + 2
418  end
419end
420return 1
421";
422
423/// Replaces a session's events and session-tier state in one atomic step while the session
424/// still holds what the rewrite was planned from.
425///
426/// `KEYS`: session hash, events sorted set. `ARGV`: the `state` and `updated_at` the session
427/// hash must still hold and the event count the set must still hold, the replacement `state`
428/// and `updated_at`, then a score and member for each event. Returns `1` when applied, `0` when
429/// the session changed since it was read, and `-1` when the session does not exist.
430const REWRITE_HISTORY_SCRIPT: &str = r"
431if redis.call('EXISTS', KEYS[1]) == 0 then
432  return -1
433end
434if (redis.call('HGET', KEYS[1], 'state') or '') ~= ARGV[1]
435  or (redis.call('HGET', KEYS[1], 'updated_at') or '') ~= ARGV[2]
436  or redis.call('ZCARD', KEYS[2]) ~= tonumber(ARGV[3]) then
437  return 0
438end
439redis.call('DEL', KEYS[2])
440for index = 6, #ARGV, 2 do
441  redis.call('ZADD', KEYS[2], ARGV[index], ARGV[index + 1])
442end
443redis.call('HSET', KEYS[1], 'state', ARGV[4], 'updated_at', ARGV[5])
444return 1
445";
446
447/// Writes a session hash and its events unless the session exists, replacing any events left
448/// under its key. `KEYS`: session hash, events sorted set. `ARGV`: the hash field count and
449/// field/value pairs, then a score and member for each event. Returns `1` when written and `0`
450/// when the session already exists.
451const IMPORT_SESSION_SCRIPT: &str = r"
452if redis.call('EXISTS', KEYS[1]) == 1 then
453  return 0
454end
455redis.call('DEL', KEYS[2])
456local fields = tonumber(ARGV[1])
457local index = 2
458for _ = 1, fields do
459  redis.call('HSET', KEYS[1], ARGV[index], ARGV[index + 1])
460  index = index + 2
461end
462for event = index, #ARGV, 2 do
463  redis.call('ZADD', KEYS[2], ARGV[event], ARGV[event + 1])
464end
465return 1
466";
467
468/// Creates a session in one atomic step on a standalone server, writing nothing when the
469/// session hash exists.
470///
471/// `KEYS`: session hash, index set, update-time index, lookup, app tier hash, user tier hash.
472/// `ARGV`: session ID, update-time score, lookup value, then for the app tier, the user tier,
473/// and the session hash a field count followed by that many field/value pairs.
474///
475/// Returns `1` when created and `0` when the session already exists.
476const CREATE_SESSION_SCRIPT: &str = r"
477if redis.call('EXISTS', KEYS[1]) == 1 then
478  return 0
479end
480redis.call('SADD', KEYS[2], ARGV[1])
481redis.call('ZADD', KEYS[3], ARGV[2], ARGV[1])
482redis.call('SET', KEYS[4], ARGV[3])
483local index = 4
484for _, key in ipairs({KEYS[5], KEYS[6], KEYS[1]}) do
485  local count = tonumber(ARGV[index])
486  index = index + 1
487  for _ = 1, count do
488    redis.call('HSET', key, ARGV[index], ARGV[index + 1])
489    index = index + 2
490  end
491end
492return 1
493";
494
495/// Writes the session hash unless it exists. `KEYS[1]`: the session hash; `ARGV`: its
496/// field/value pairs. Returns `1` when written and `0` when the session already exists.
497const CREATE_SESSION_HASH_SCRIPT: &str = r"
498if redis.call('EXISTS', KEYS[1]) == 1 then
499  return 0
500end
501for index = 1, #ARGV, 2 do
502  redis.call('HSET', KEYS[1], ARGV[index], ARGV[index + 1])
503end
504return 1
505";
506
507/// The update-time index score of `at`: microseconds since the epoch, exact in a double until
508/// the year 2255.
509fn updated_score(at: DateTime<Utc>) -> String {
510    at.timestamp_micros().to_string()
511}
512
513/// Attempts [`APPEND_EVENT_SCRIPT`] makes before giving up on a session whose state keeps
514/// changing between the read and the write.
515const MAX_STATE_WRITE_ATTEMPTS: usize = 32;
516
517/// Serializes each state value to JSON, the form the state hashes store.
518fn state_fields(state: &HashMap<String, Value>) -> Result<Vec<(String, String)>> {
519    state
520        .iter()
521        .map(|(key, value)| {
522            serde_json::to_string(value).map(|serialized| (key.clone(), serialized)).map_err(|e| {
523                adk_core::AdkError::session(format!("serialize state value failed: {e}"))
524            })
525        })
526        .collect()
527}
528
529/// Writes the fields of `state` into the hash at `key`; nothing when `state` is empty.
530///
531/// `client` is a client or a transaction, so the same writes run inside `MULTI`/`EXEC` on a
532/// standalone server and as single commands on a cluster.
533async fn write_state_hash<C: HashesInterface + Sync>(
534    client: &C,
535    key: &str,
536    state: &HashMap<String, Value>,
537) -> Result<()> {
538    if state.is_empty() {
539        return Ok(());
540    }
541    let _: () = client
542        .hset(key, state_fields(state)?)
543        .await
544        .map_err(|e| adk_core::AdkError::session(format!("redis hset failed: {e}")))?;
545    Ok(())
546}
547
548/// The keys and values [`SessionService::create`] writes for one session.
549struct NewSession<'a> {
550    session_key: String,
551    session_fields: Vec<(String, String)>,
552    app_key: String,
553    app_delta: &'a HashMap<String, Value>,
554    user_key: String,
555    user_delta: &'a HashMap<String, Value>,
556    index_key: String,
557    updated_index_key: String,
558    updated_at: DateTime<Utc>,
559    lookup_key: String,
560    lookup_value: String,
561    session_id: &'a str,
562}
563
564/// Appends a field count and the fields to `args`.
565fn push_fields(args: &mut Vec<String>, fields: Vec<(String, String)>) {
566    args.push(fields.len().to_string());
567    for (field, value) in fields {
568        args.push(field);
569        args.push(value);
570    }
571}
572
573impl NewSession<'_> {
574    /// Creates the session on a standalone server with [`CREATE_SESSION_SCRIPT`]; `false`
575    /// when it already exists.
576    async fn create_standalone(self, client: &Client) -> Result<bool> {
577        let keys = vec![
578            self.session_key,
579            self.index_key,
580            self.updated_index_key,
581            self.lookup_key,
582            self.app_key,
583            self.user_key,
584        ];
585        let mut args =
586            vec![self.session_id.to_string(), updated_score(self.updated_at), self.lookup_value];
587        push_fields(&mut args, state_fields(self.app_delta)?);
588        push_fields(&mut args, state_fields(self.user_delta)?);
589        push_fields(&mut args, self.session_fields);
590        let created: i64 = client
591            .eval(CREATE_SESSION_SCRIPT, keys, args)
592            .await
593            .map_err(|e| adk_core::AdkError::session(format!("redis eval failed: {e}")))?;
594        Ok(created == 1)
595    }
596
597    /// Creates the session on a cluster, where its keys span several slots: the index
598    /// entries, lookup, and tier fields first, then the session hash unless it exists; `false`
599    /// when it already exists.
600    ///
601    /// Until the session hash exists, `get` reports the session as not found, `list` skips its
602    /// index entries, and an append through its lookup finds no session, so a failure part-way
603    /// leaves no session that can be read without its index entries, lookup, or tier fields.
604    async fn create_clustered(self, client: &Client) -> Result<bool> {
605        let exists: bool = client
606            .exists(&self.session_key)
607            .await
608            .map_err(|e| adk_core::AdkError::session(format!("redis exists failed: {e}")))?;
609        if exists {
610            return Ok(false);
611        }
612        let _: () = client
613            .sadd(&self.index_key, self.session_id)
614            .await
615            .map_err(|e| adk_core::AdkError::session(format!("redis sadd failed: {e}")))?;
616        let _: () = client
617            .zadd(
618                &self.updated_index_key,
619                None,
620                None,
621                false,
622                false,
623                (self.updated_at.timestamp_micros() as f64, self.session_id),
624            )
625            .await
626            .map_err(|e| adk_core::AdkError::session(format!("redis zadd failed: {e}")))?;
627        let _: () = client
628            .set(&self.lookup_key, self.lookup_value, None, None, false)
629            .await
630            .map_err(|e| adk_core::AdkError::session(format!("redis set failed: {e}")))?;
631        // Only the delta's fields, so concurrent writers of other fields are kept.
632        write_state_hash(client, &self.app_key, self.app_delta).await?;
633        write_state_hash(client, &self.user_key, self.user_delta).await?;
634        let args: Vec<String> =
635            self.session_fields.into_iter().flat_map(|(field, value)| [field, value]).collect();
636        let created: i64 = client
637            .eval(CREATE_SESSION_HASH_SCRIPT, vec![self.session_key], args)
638            .await
639            .map_err(|e| adk_core::AdkError::session(format!("redis eval failed: {e}")))?;
640        Ok(created == 1)
641    }
642}
643
644/// Removes one session through `client`: its hash and events first, in one `DEL` (one slot
645/// in either layout), then its lookup and index entries.
646async fn remove_session<C>(
647    client: &C,
648    layout: KeyLayout,
649    app: &str,
650    user: &str,
651    session: &str,
652) -> Result<()>
653where
654    C: KeysInterface + SetsInterface + SortedSetsInterface + Sync,
655{
656    let _: () = client
657        .del(vec![layout.session(app, user, session), layout.events(app, user, session)])
658        .await
659        .map_err(|e| adk_core::AdkError::session(format!("redis del failed: {e}")))?;
660    let _: () = client
661        .del(layout.lookup(session))
662        .await
663        .map_err(|e| adk_core::AdkError::session(format!("redis del failed: {e}")))?;
664    let _: () = client
665        .srem(layout.index(app, user), session)
666        .await
667        .map_err(|e| adk_core::AdkError::session(format!("redis srem failed: {e}")))?;
668    let _: () = client
669        .zrem(layout.updated_index(app, user), session)
670        .await
671        .map_err(|e| adk_core::AdkError::session(format!("redis zrem failed: {e}")))?;
672    Ok(())
673}
674
675/// A session's history with the stored values a rewrite checks before it writes.
676struct StoredHistory {
677    history: SessionHistory,
678    /// Each decoded event's stored member, by event ID.
679    members: HashMap<String, String>,
680    /// The session hash's `state` field as stored.
681    state_field: String,
682    /// The session hash's `updated_at` field as stored.
683    updated_at_field: String,
684    /// How many members the events set holds, including ones that no longer decode.
685    stored_events: usize,
686}
687
688/// Redis-backed session service.
689///
690/// Stores sessions using Redis hashes, events as sorted sets scored by
691/// append sequence, and three-tier state (app, user, session) as separate hashes.
692/// Supports optional TTL on session keys and Redis Cluster, where each session's keys
693/// share one hash tag (see the module docs for both key layouts).
694///
695/// # Example
696///
697/// ```rust,ignore
698/// use adk_session::{RedisSessionConfig, RedisSessionService};
699///
700/// let config = RedisSessionConfig {
701///     url: "redis://localhost:6379".into(),
702///     ttl: None,
703///     cluster_nodes: None,
704/// };
705/// let service = RedisSessionService::new(config).await?;
706/// ```
707pub struct RedisSessionService {
708    client: Client,
709    ttl: Option<Duration>,
710    layout: KeyLayout,
711}
712
713impl RedisSessionService {
714    /// Connect to Redis (standalone or cluster).
715    ///
716    /// A connection with `cluster_nodes`, or a `redis-cluster://` URL, uses the cluster key
717    /// layout; any other connection uses the standalone layout.
718    ///
719    /// # Errors
720    ///
721    /// Returns an error with "redis connection failed" context if the
722    /// connection cannot be established.
723    pub async fn new(config: RedisSessionConfig) -> Result<Self> {
724        let redis_config = if let Some(ref nodes) = config.cluster_nodes {
725            let hosts: Vec<(String, u16)> = nodes
726                .iter()
727                .map(|n| {
728                    let parts: Vec<&str> = n.rsplitn(2, ':').collect();
729                    if parts.len() == 2 {
730                        let port = parts[0].parse::<u16>().unwrap_or(6379);
731                        (parts[1].to_string(), port)
732                    } else {
733                        (n.clone(), 6379)
734                    }
735                })
736                .collect();
737            Config { server: ServerConfig::new_clustered(hosts), ..Default::default() }
738        } else {
739            Config::from_url(&config.url)
740                .map_err(|e| adk_core::AdkError::session(format!("redis connection failed: {e}")))?
741        };
742        let layout = if redis_config.server.is_clustered() {
743            KeyLayout::Cluster
744        } else {
745            KeyLayout::Standalone
746        };
747
748        let client = Builder::from_config(redis_config)
749            .build()
750            .map_err(|e| adk_core::AdkError::session(format!("redis connection failed: {e}")))?;
751
752        client
753            .init()
754            .await
755            .map_err(|e| adk_core::AdkError::session(format!("redis connection failed: {e}")))?;
756
757        Ok(Self { client, ttl: config.ttl, layout })
758    }
759
760    /// Apply TTL to session-related keys if configured.
761    async fn apply_ttl(&self, session_k: &str, events_k: &str) -> Result<()> {
762        if let Some(ttl) = self.ttl {
763            let seconds = ttl.as_secs() as i64;
764            let _: () =
765                self.client.expire(session_k, seconds, None).await.map_err(|e| {
766                    adk_core::AdkError::session(format!("redis expire failed: {e}"))
767                })?;
768            let _: () =
769                self.client.expire(events_k, seconds, None).await.map_err(|e| {
770                    adk_core::AdkError::session(format!("redis expire failed: {e}"))
771                })?;
772        }
773        Ok(())
774    }
775
776    /// Reads the history of `identity` with the stored forms a rewrite checks and keeps.
777    async fn read_history(&self, identity: &AdkIdentity) -> Result<StoredHistory> {
778        let (app, user, session) =
779            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
780        let layout = self.layout;
781        let raw: HashMap<String, String> = self
782            .client
783            .hgetall(layout.session(app, user, session))
784            .await
785            .map_err(|e| adk_core::AdkError::session(format!("redis hgetall failed: {e}")))?;
786        if raw.is_empty() {
787            return Err(identity_not_found(identity));
788        }
789        let state_field = raw.get("state").cloned().unwrap_or_default();
790        let updated_at_field = raw.get("updated_at").cloned().unwrap_or_default();
791        let stored: HashMap<String, Value> = serde_json::from_str(&state_field).unwrap_or_default();
792        // Hashes written by earlier releases also hold a copy of the app and user tiers.
793        let (_, _, state) = state_utils::extract_state_deltas(&stored);
794        let initial_state = raw.get("initial_state").and_then(|s| serde_json::from_str(s).ok());
795
796        let raw_events: Vec<(String, f64)> = self
797            .client
798            .zrange(layout.events(app, user, session), 0, -1, None, false, None, true)
799            .await
800            .map_err(|e| adk_core::AdkError::session(format!("redis zrange failed: {e}")))?;
801        let stored_events = raw_events.len();
802        let mut members = HashMap::new();
803        let mut events = Vec::with_capacity(raw_events.len());
804        for (member, _score) in raw_events {
805            match serde_json::from_str::<Event>(&member) {
806                Ok(event) => {
807                    members.insert(event.id.clone(), member);
808                    events.push(event);
809                }
810                Err(error) => tracing::warn!(
811                    session.id = %session,
812                    error = %error,
813                    "skipping stored event that failed to deserialize"
814                ),
815            }
816        }
817        // Scores are append order; a stable sort keeps it among equal timestamps, as `get` does.
818        events.sort_by_key(|event| event.timestamp);
819        Ok(StoredHistory {
820            history: SessionHistory::new(events, state, initial_state),
821            members,
822            state_field,
823            updated_at_field,
824            stored_events,
825        })
826    }
827
828    /// Read a hash as `HashMap<String, Value>` (JSON values stored as strings).
829    async fn read_state_hash(&self, key: &str) -> Result<HashMap<String, Value>> {
830        let raw: HashMap<String, String> = self
831            .client
832            .hgetall(key)
833            .await
834            .map_err(|e| adk_core::AdkError::session(format!("redis hgetall failed: {e}")))?;
835        let mut map = HashMap::new();
836        for (k, v) in raw {
837            let val: Value = serde_json::from_str(&v).unwrap_or(Value::String(v));
838            map.insert(k, val);
839        }
840        Ok(map)
841    }
842
843    /// Adds the sessions of `(app_name, user_id)` that only the set index holds — sessions
844    /// created by earlier releases — to the update-time index, scored by their `updated_at`,
845    /// and drops set entries whose session no longer exists.
846    async fn index_legacy_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
847        let layout = self.layout;
848        let (idx_k, updated_k) =
849            (layout.index(app_name, user_id), layout.updated_index(app_name, user_id));
850        let in_set: u64 = self
851            .client
852            .scard(&idx_k)
853            .await
854            .map_err(|e| adk_core::AdkError::session(format!("redis scard failed: {e}")))?;
855        let in_sorted_set: u64 = self
856            .client
857            .zcard(&updated_k)
858            .await
859            .map_err(|e| adk_core::AdkError::session(format!("redis zcard failed: {e}")))?;
860        if in_set == in_sorted_set {
861            return Ok(());
862        }
863
864        let members: Vec<String> = self
865            .client
866            .smembers(&idx_k)
867            .await
868            .map_err(|e| adk_core::AdkError::session(format!("redis smembers failed: {e}")))?;
869        for sid in members {
870            let indexed: Option<f64> =
871                self.client.zscore(&updated_k, &sid).await.map_err(|e| {
872                    adk_core::AdkError::session(format!("redis zscore failed: {e}"))
873                })?;
874            if indexed.is_some() {
875                continue;
876            }
877            let updated_at: Option<String> = self
878                .client
879                .hget(layout.session(app_name, user_id, &sid), "updated_at")
880                .await
881                .map_err(|e| adk_core::AdkError::session(format!("redis hget failed: {e}")))?;
882            match updated_at.and_then(|at| at.parse::<DateTime<Utc>>().ok()) {
883                Some(at) => {
884                    let _: () = self
885                        .client
886                        .zadd(
887                            &updated_k,
888                            None,
889                            None,
890                            false,
891                            false,
892                            (at.timestamp_micros() as f64, sid.as_str()),
893                        )
894                        .await
895                        .map_err(|e| {
896                            adk_core::AdkError::session(format!("redis zadd failed: {e}"))
897                        })?;
898                }
899                None => self.unindex(app_name, user_id, &sid).await?,
900            }
901        }
902        Ok(())
903    }
904
905    /// Removes a session whose hash does not exist from both indexes.
906    async fn unindex(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
907        let layout = self.layout;
908        let _: () = self
909            .client
910            .srem(layout.index(app_name, user_id), session_id)
911            .await
912            .map_err(|e| adk_core::AdkError::session(format!("redis srem failed: {e}")))?;
913        let _: () = self
914            .client
915            .zrem(layout.updated_index(app_name, user_id), session_id)
916            .await
917            .map_err(|e| adk_core::AdkError::session(format!("redis zrem failed: {e}")))?;
918        Ok(())
919    }
920
921    /// Applies `event` to the session `(app_name, user_id, session_id)` and refreshes
922    /// its TTL.
923    ///
924    /// The app and user tiers receive only the fields in the delta. The session tier is a
925    /// single JSON field, so [`APPEND_EVENT_SCRIPT`] replaces it only while it still holds
926    /// the value the delta was merged into, and a changed value is merged again. On a
927    /// cluster the app and user tiers live in other slots than the session, so they are
928    /// written after the script instead of by it.
929    async fn apply_event(
930        &self,
931        app_name: &str,
932        user_id: &str,
933        session_id: &str,
934        event: &Event,
935    ) -> Result<()> {
936        let (app_delta, user_delta, session_delta) =
937            state_utils::extract_state_deltas(&event.actions.state_delta);
938
939        let layout = self.layout;
940        let session_k = layout.session(app_name, user_id, session_id);
941        let events_k = layout.events(app_name, user_id, session_id);
942        let updated_k = layout.updated_index(app_name, user_id);
943        let app_k = layout.app_state(app_name);
944        let user_k = layout.user_state(app_name, user_id);
945        let in_script = match layout {
946            KeyLayout::Standalone => true,
947            KeyLayout::Cluster => false,
948        };
949        let mut keys = vec![session_k.clone(), events_k.clone()];
950
951        let event_json = serde_json::to_string(event)
952            .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
953        // ARGV[4..]: updated_at, event, the update-time index flag, score, and member, then
954        // each tier's field count and fields.
955        let mut tail = vec![event.timestamp.to_rfc3339(), event_json];
956        if in_script {
957            keys.push(updated_k.clone());
958            tail.extend(["1".to_string(), updated_score(event.timestamp), session_id.to_string()]);
959            for (key, delta) in [(&app_k, &app_delta), (&user_k, &user_delta)] {
960                keys.push(key.clone());
961                push_fields(&mut tail, state_fields(delta)?);
962            }
963        } else {
964            tail.extend(["0".to_string(), String::new(), String::new()]);
965        }
966
967        for _ in 0..MAX_STATE_WRITE_ATTEMPTS {
968            // ARGV[1..=3]: whether to write the session tier, the value it must still
969            // hold, and its replacement.
970            let head = if session_delta.is_empty() {
971                vec!["0".to_string(), String::new(), String::new()]
972            } else {
973                let current: Option<String> =
974                    self.client.hget(&session_k, "state").await.map_err(|e| {
975                        adk_core::AdkError::session(format!("redis hget failed: {e}"))
976                    })?;
977                let stored: HashMap<String, Value> = current
978                    .as_deref()
979                    .and_then(|s| serde_json::from_str(s).ok())
980                    .unwrap_or_default();
981                // Hashes written by earlier releases also hold a copy of the app and user
982                // tiers; the rewrite keeps only the session tier.
983                let (_, _, mut session_state) = state_utils::extract_state_deltas(&stored);
984                session_state.extend(session_delta.clone());
985                let replacement = serde_json::to_string(&session_state).map_err(|e| {
986                    adk_core::AdkError::session(format!("serialize state failed: {e}"))
987                })?;
988                vec!["1".to_string(), current.unwrap_or_default(), replacement]
989            };
990
991            let args: Vec<String> = head.into_iter().chain(tail.iter().cloned()).collect();
992            let outcome: i64 = self
993                .client
994                .eval(APPEND_EVENT_SCRIPT, keys.clone(), args)
995                .await
996                .map_err(|e| adk_core::AdkError::session(format!("redis eval failed: {e}")))?;
997            match outcome {
998                1 => {
999                    if !in_script {
1000                        let _: () = self
1001                            .client
1002                            .zadd(
1003                                &updated_k,
1004                                None,
1005                                None,
1006                                false,
1007                                false,
1008                                (event.timestamp.timestamp_micros() as f64, session_id),
1009                            )
1010                            .await
1011                            .map_err(|e| {
1012                                adk_core::AdkError::session(format!("redis zadd failed: {e}"))
1013                            })?;
1014                        write_state_hash(&self.client, &app_k, &app_delta).await?;
1015                        write_state_hash(&self.client, &user_k, &user_delta).await?;
1016                    }
1017                    return self.apply_ttl(&session_k, &events_k).await;
1018                }
1019                -1 => return Err(session_not_found_for(app_name, user_id, session_id)),
1020                _ => continue,
1021            }
1022        }
1023
1024        Err(adk_core::AdkError::new(
1025            ErrorComponent::Session,
1026            ErrorCategory::Unavailable,
1027            "session.redis.state_contention",
1028            format!(
1029                "session '{session_id}' state changed on each of {MAX_STATE_WRITE_ATTEMPTS} \
1030                 write attempts; retry the append"
1031            ),
1032        ))
1033    }
1034}
1035
1036#[async_trait]
1037impl SessionService for RedisSessionService {
1038    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
1039    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
1040        req.try_identity()?;
1041        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
1042        let now = Utc::now();
1043        let layout = self.layout;
1044
1045        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
1046
1047        let session_k = layout.session(&req.app_name, &req.user_id, &session_id);
1048        let app_k = layout.app_state(&req.app_name);
1049        let user_k = layout.user_state(&req.app_name, &req.user_id);
1050        let state_json = serde_json::to_string(&session_state)
1051            .map_err(|e| adk_core::AdkError::session(format!("serialize state failed: {e}")))?;
1052        let new = NewSession {
1053            session_key: session_k.clone(),
1054            session_fields: vec![
1055                ("app_name".into(), req.app_name.clone()),
1056                ("user_id".into(), req.user_id.clone()),
1057                ("session_id".into(), session_id.clone()),
1058                ("initial_state".into(), state_json.clone()),
1059                ("state".into(), state_json),
1060                ("created_at".into(), now.to_rfc3339()),
1061                ("updated_at".into(), now.to_rfc3339()),
1062            ],
1063            app_key: app_k.clone(),
1064            app_delta: &app_delta,
1065            user_key: user_k.clone(),
1066            user_delta: &user_delta,
1067            index_key: layout.index(&req.app_name, &req.user_id),
1068            updated_index_key: layout.updated_index(&req.app_name, &req.user_id),
1069            updated_at: now,
1070            lookup_key: layout.lookup(&session_id),
1071            lookup_value: lookup_value(&req.app_name, &req.user_id),
1072            session_id: &session_id,
1073        };
1074
1075        let created = match layout {
1076            KeyLayout::Standalone => new.create_standalone(&self.client).await?,
1077            KeyLayout::Cluster => new.create_clustered(&self.client).await?,
1078        };
1079        if !created {
1080            return Err(session_already_exists(&req.app_name, &req.user_id, &session_id));
1081        }
1082
1083        // Apply TTL outside the script
1084        let events_k = layout.events(&req.app_name, &req.user_id, &session_id);
1085        self.apply_ttl(&session_k, &events_k).await?;
1086
1087        let app_state = self.read_state_hash(&app_k).await?;
1088        let user_state = self.read_state_hash(&user_k).await?;
1089
1090        Ok(Box::new(RedisSession {
1091            app_name: req.app_name,
1092            user_id: req.user_id,
1093            session_id,
1094            state: state_utils::merge_states(&app_state, &user_state, &session_state),
1095            events: Vec::new(),
1096            updated_at: now,
1097        }))
1098    }
1099
1100    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
1101    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
1102        req.try_identity()?;
1103        let layout = self.layout;
1104        let session_k = layout.session(&req.app_name, &req.user_id, &req.session_id);
1105
1106        let exists: bool = self
1107            .client
1108            .exists(&session_k)
1109            .await
1110            .map_err(|e| adk_core::AdkError::session(format!("redis exists failed: {e}")))?;
1111        if !exists {
1112            return Err(crate::service::session_not_found(&req));
1113        }
1114
1115        let raw: HashMap<String, String> = self
1116            .client
1117            .hgetall(&session_k)
1118            .await
1119            .map_err(|e| adk_core::AdkError::session(format!("redis hgetall failed: {e}")))?;
1120
1121        let updated_at: DateTime<Utc> =
1122            raw.get("updated_at").and_then(|s| s.parse().ok()).unwrap_or_else(Utc::now);
1123
1124        let stored_state: HashMap<String, Value> =
1125            raw.get("state").and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default();
1126        let app_state = self.read_state_hash(&layout.app_state(&req.app_name)).await?;
1127        let user_state =
1128            self.read_state_hash(&layout.user_state(&req.app_name, &req.user_id)).await?;
1129
1130        // Read events from the sorted set, in score (append) order
1131        let events_k = layout.events(&req.app_name, &req.user_id, &req.session_id);
1132        let raw_events: Vec<(String, f64)> = self
1133            .client
1134            .zrange(&events_k, 0, -1, None, false, None, true)
1135            .await
1136            .map_err(|e| adk_core::AdkError::session(format!("redis zrange failed: {e}")))?;
1137
1138        let mut events: Vec<Event> = raw_events
1139            .into_iter()
1140            .filter_map(|(json, _score)| match serde_json::from_str::<Event>(&json) {
1141                Ok(event) => Some(event),
1142                Err(error) => {
1143                    let event_id = serde_json::from_str::<Value>(&json)
1144                        .ok()
1145                        .and_then(|raw| raw.get("id").and_then(Value::as_str).map(str::to_string))
1146                        .unwrap_or_else(|| "<unknown>".to_string());
1147                    tracing::warn!(
1148                        session.id = %req.session_id,
1149                        event.id = %event_id,
1150                        error = %error,
1151                        "skipping stored event that failed to deserialize"
1152                    );
1153                    None
1154                }
1155            })
1156            .collect();
1157
1158        // Scores are append order; a stable sort keeps it among equal timestamps.
1159        events.sort_by_key(|event| event.timestamp);
1160        if let Some(num) = req.num_recent_events {
1161            let start = events.len().saturating_sub(num);
1162            events.drain(..start);
1163        }
1164        if let Some(after) = req.after {
1165            events.retain(|e| e.timestamp >= after);
1166        }
1167
1168        Ok(Box::new(RedisSession {
1169            app_name: req.app_name,
1170            user_id: req.user_id,
1171            session_id: req.session_id,
1172            state: state_utils::merge_current_tiers(&app_state, &user_state, &stored_state),
1173            events,
1174            updated_at,
1175        }))
1176    }
1177
1178    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
1179    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
1180        validate_scope(&req.app_name, &req.user_id)?;
1181        let layout = self.layout;
1182        let updated_k = layout.updated_index(&req.app_name, &req.user_id);
1183        self.index_legacy_sessions(&req.app_name, &req.user_id).await?;
1184
1185        if req.limit == Some(0) {
1186            return Ok(Vec::new());
1187        }
1188        let offset = req.offset.unwrap_or(0);
1189        let start = i64::try_from(offset).unwrap_or(i64::MAX);
1190        let stop = req.limit.map_or(-1, |limit| {
1191            i64::try_from(offset.saturating_add(limit)).map_or(i64::MAX, |end| end - 1)
1192        });
1193        // Reversed: newest first, equal scores by member descending.
1194        let session_ids: Vec<String> = self
1195            .client
1196            .zrange(&updated_k, start, stop, None, true, None, false)
1197            .await
1198            .map_err(|e| adk_core::AdkError::session(format!("redis zrange failed: {e}")))?;
1199
1200        let app_state = self.read_state_hash(&layout.app_state(&req.app_name)).await?;
1201        let user_state =
1202            self.read_state_hash(&layout.user_state(&req.app_name, &req.user_id)).await?;
1203
1204        let mut sessions: Vec<Box<dyn Session>> = Vec::new();
1205        for sid in session_ids {
1206            let session_k = layout.session(&req.app_name, &req.user_id, &sid);
1207            let raw: HashMap<String, String> =
1208                self.client.hgetall(&session_k).await.map_err(|e| {
1209                    adk_core::AdkError::session(format!("redis hgetall failed: {e}"))
1210                })?;
1211
1212            if raw.is_empty() {
1213                // Expired, or left by a create that failed part-way.
1214                self.unindex(&req.app_name, &req.user_id, &sid).await?;
1215                continue;
1216            }
1217
1218            let stored_state: HashMap<String, Value> =
1219                raw.get("state").and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default();
1220
1221            let updated_at: DateTime<Utc> =
1222                raw.get("updated_at").and_then(|s| s.parse().ok()).unwrap_or_else(Utc::now);
1223
1224            sessions.push(Box::new(RedisSession {
1225                app_name: req.app_name.clone(),
1226                user_id: req.user_id.clone(),
1227                session_id: sid,
1228                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored_state),
1229                events: Vec::new(),
1230                updated_at,
1231            }));
1232        }
1233
1234        Ok(sessions)
1235    }
1236
1237    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
1238    async fn delete(&self, req: DeleteRequest) -> Result<()> {
1239        req.try_identity()?;
1240        let layout = self.layout;
1241        match layout {
1242            KeyLayout::Standalone => {
1243                let trx = self.client.multi();
1244                remove_session(&trx, layout, &req.app_name, &req.user_id, &req.session_id).await?;
1245                let _: () = trx.exec(true).await.map_err(|e| {
1246                    adk_core::AdkError::session(format!("redis transaction failed: {e}"))
1247                })?;
1248            }
1249            KeyLayout::Cluster => {
1250                remove_session(&self.client, layout, &req.app_name, &req.user_id, &req.session_id)
1251                    .await?;
1252            }
1253        }
1254        Ok(())
1255    }
1256
1257    #[instrument(skip_all, fields(session_id = %session_id))]
1258    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
1259        validate_session_id(session_id)?;
1260        // Strip temp: keys
1261        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
1262
1263        // Use reverse lookup to find app_name and user_id
1264        let lookup_val: Option<String> = self
1265            .client
1266            .get(self.layout.lookup(session_id))
1267            .await
1268            .map_err(|e| adk_core::AdkError::session(format!("redis get failed: {e}")))?;
1269
1270        let lookup_val = lookup_val.ok_or_else(|| session_id_not_found(session_id))?;
1271
1272        let (app_name, user_id) = parse_lookup_value(&lookup_val)
1273            .ok_or_else(|| adk_core::AdkError::session("corrupt session lookup entry"))?;
1274
1275        self.apply_event(&app_name, &user_id, session_id, &event).await
1276    }
1277
1278    #[instrument(skip_all, fields(
1279        app_name = %req.identity.app_name,
1280        user_id = %req.identity.user_id,
1281        session_id = %req.identity.session_id,
1282    ))]
1283    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
1284        let mut event = req.event;
1285        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
1286
1287        // The key comes straight from the identity — no reverse lookup needed.
1288        self.apply_event(
1289            req.identity.app_name.as_ref(),
1290            req.identity.user_id.as_ref(),
1291            req.identity.session_id.as_ref(),
1292            &event,
1293        )
1294        .await
1295    }
1296
1297    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
1298    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
1299        validate_scope(app_name, user_id)?;
1300        let layout = self.layout;
1301        let idx_k = layout.index(app_name, user_id);
1302        let session_ids: Vec<String> = self
1303            .client
1304            .smembers(&idx_k)
1305            .await
1306            .map_err(|e| adk_core::AdkError::session(format!("redis smembers failed: {e}")))?;
1307        // The indexes and the user tier: a user whose sessions are already gone still has
1308        // the tier erased.
1309        let user_keys = vec![
1310            idx_k.clone(),
1311            layout.updated_index(app_name, user_id),
1312            layout.user_state(app_name, user_id),
1313        ];
1314
1315        match layout {
1316            KeyLayout::Standalone => {
1317                let trx = self.client.multi();
1318                for sid in &session_ids {
1319                    remove_session(&trx, layout, app_name, user_id, sid).await?;
1320                }
1321                let _: () = trx
1322                    .del(user_keys)
1323                    .await
1324                    .map_err(|e| adk_core::AdkError::session(format!("redis del failed: {e}")))?;
1325                let _: () = trx.exec(true).await.map_err(|e| {
1326                    adk_core::AdkError::session(format!("redis transaction failed: {e}"))
1327                })?;
1328            }
1329            KeyLayout::Cluster => {
1330                for sid in &session_ids {
1331                    remove_session(&self.client, layout, app_name, user_id, sid).await?;
1332                }
1333                // The set, the sorted set and the user tier share the `{<app>:<user>}` hash
1334                // tag.
1335                let _: () =
1336                    self.client.del(user_keys).await.map_err(|e| {
1337                        adk_core::AdkError::session(format!("redis del failed: {e}"))
1338                    })?;
1339            }
1340        }
1341
1342        Ok(())
1343    }
1344
1345    #[instrument(skip_all)]
1346    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
1347        Ok(self.read_history(identity).await?.history)
1348    }
1349
1350    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
1351        let identity = &req.identity;
1352        let (app, user, session) =
1353            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
1354        let layout = self.layout;
1355        let session_k = layout.session(app, user, session);
1356        let events_k = layout.events(app, user, session);
1357
1358        for _ in 0..MAX_STATE_WRITE_ATTEMPTS {
1359            let read = self.read_history(identity).await?;
1360            let rewritten =
1361                read.history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
1362            let state_json = serde_json::to_string(&rewritten.state)
1363                .map_err(|e| adk_core::AdkError::session(format!("serialize state failed: {e}")))?;
1364            let now = Utc::now();
1365            let mut args = vec![
1366                read.state_field.clone(),
1367                read.updated_at_field.clone(),
1368                read.stored_events.to_string(),
1369                state_json,
1370                now.to_rfc3339(),
1371            ];
1372            // Unchanged events keep their stored form; events that no longer decode are
1373            // dropped, as reads already skip them.
1374            for (index, event) in rewritten.events.iter().enumerate() {
1375                let member = match read.members.get(&event.id) {
1376                    Some(member) if !rewritten.change.replaced.contains(&event.id) => {
1377                        member.clone()
1378                    }
1379                    _ => serde_json::to_string(event).map_err(|e| {
1380                        adk_core::AdkError::session(format!("serialize failed: {e}"))
1381                    })?,
1382                };
1383                args.push((index + 1).to_string());
1384                args.push(member);
1385            }
1386            let outcome: i64 = self
1387                .client
1388                .eval(REWRITE_HISTORY_SCRIPT, vec![session_k.clone(), events_k.clone()], args)
1389                .await
1390                .map_err(|e| adk_core::AdkError::session(format!("redis eval failed: {e}")))?;
1391            match outcome {
1392                1 => {
1393                    let _: () = self
1394                        .client
1395                        .zadd(
1396                            layout.updated_index(app, user),
1397                            None,
1398                            None,
1399                            false,
1400                            false,
1401                            (now.timestamp_micros() as f64, session),
1402                        )
1403                        .await
1404                        .map_err(|e| {
1405                            adk_core::AdkError::session(format!("redis zadd failed: {e}"))
1406                        })?;
1407                    self.apply_ttl(&session_k, &events_k).await?;
1408                    let app_state = self.read_state_hash(&layout.app_state(app)).await?;
1409                    let user_state = self.read_state_hash(&layout.user_state(app, user)).await?;
1410                    let session = Box::new(RedisSession {
1411                        app_name: app.to_string(),
1412                        user_id: user.to_string(),
1413                        session_id: session.to_string(),
1414                        state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
1415                        events: rewritten.events,
1416                        updated_at: now,
1417                    });
1418                    return Ok(HistoryOutcome::new(session, rewritten.change));
1419                }
1420                -1 => return Err(identity_not_found(identity)),
1421                _ => continue,
1422            }
1423        }
1424        Err(adk_core::AdkError::new(
1425            ErrorComponent::Session,
1426            ErrorCategory::Unavailable,
1427            "session.redis.state_contention",
1428            format!(
1429                "session '{session}' changed on each of {MAX_STATE_WRITE_ATTEMPTS} rewrite \
1430                 attempts; retry the rewrite"
1431            ),
1432        ))
1433    }
1434
1435    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
1436        let identity = &req.identity;
1437        let (app, user, session) =
1438            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
1439        let layout = self.layout;
1440        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
1441        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
1442        let encode = |state: &HashMap<String, Value>| {
1443            serde_json::to_string(state)
1444                .map_err(|e| adk_core::AdkError::session(format!("serialize state failed: {e}")))
1445        };
1446        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
1447        let session_k = layout.session(app, user, session);
1448        let events_k = layout.events(app, user, session);
1449
1450        let exists: bool = self
1451            .client
1452            .exists(&session_k)
1453            .await
1454            .map_err(|e| adk_core::AdkError::session(format!("redis exists failed: {e}")))?;
1455        if exists {
1456            return Err(session_already_exists(app, user, session));
1457        }
1458        // Index entries first: until the session hash exists, reads skip them.
1459        let _: () = self
1460            .client
1461            .sadd(layout.index(app, user), session)
1462            .await
1463            .map_err(|e| adk_core::AdkError::session(format!("redis sadd failed: {e}")))?;
1464        let _: () = self
1465            .client
1466            .zadd(
1467                layout.updated_index(app, user),
1468                None,
1469                None,
1470                false,
1471                false,
1472                (updated_at.timestamp_micros() as f64, session),
1473            )
1474            .await
1475            .map_err(|e| adk_core::AdkError::session(format!("redis zadd failed: {e}")))?;
1476        let _: () = self
1477            .client
1478            .set(layout.lookup(session), lookup_value(app, user), None, None, false)
1479            .await
1480            .map_err(|e| adk_core::AdkError::session(format!("redis set failed: {e}")))?;
1481
1482        let fields = vec![
1483            ("app_name".to_string(), app.to_string()),
1484            ("user_id".to_string(), user.to_string()),
1485            ("session_id".to_string(), session.to_string()),
1486            ("state".to_string(), encode(&state)?),
1487            ("initial_state".to_string(), encode(&initial_state)?),
1488            ("created_at".to_string(), Utc::now().to_rfc3339()),
1489            ("updated_at".to_string(), updated_at.to_rfc3339()),
1490        ];
1491        let mut args = Vec::new();
1492        push_fields(&mut args, fields);
1493        for (index, event) in req.events.iter().enumerate() {
1494            args.push((index + 1).to_string());
1495            args.push(
1496                serde_json::to_string(event)
1497                    .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?,
1498            );
1499        }
1500        let created: i64 = self
1501            .client
1502            .eval(IMPORT_SESSION_SCRIPT, vec![session_k.clone(), events_k.clone()], args)
1503            .await
1504            .map_err(|e| adk_core::AdkError::session(format!("redis eval failed: {e}")))?;
1505        if created != 1 {
1506            return Err(session_already_exists(app, user, session));
1507        }
1508        self.apply_ttl(&session_k, &events_k).await?;
1509
1510        let app_state = self.read_state_hash(&layout.app_state(app)).await?;
1511        let user_state = self.read_state_hash(&layout.user_state(app, user)).await?;
1512        Ok(Box::new(RedisSession {
1513            app_name: app.to_string(),
1514            user_id: user.to_string(),
1515            session_id: session.to_string(),
1516            state: state_utils::merge_states(&app_state, &user_state, &state),
1517            events: req.events,
1518            updated_at,
1519        }))
1520    }
1521
1522    async fn health_check(&self) -> Result<()> {
1523        let _: String = self
1524            .client
1525            .ping(None)
1526            .await
1527            .map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
1528        Ok(())
1529    }
1530}
1531
1532/// In-memory representation of a session retrieved from Redis.
1533struct RedisSession {
1534    app_name: String,
1535    user_id: String,
1536    session_id: String,
1537    state: HashMap<String, Value>,
1538    events: Vec<Event>,
1539    updated_at: DateTime<Utc>,
1540}
1541
1542impl Session for RedisSession {
1543    fn id(&self) -> &str {
1544        &self.session_id
1545    }
1546
1547    fn app_name(&self) -> &str {
1548        &self.app_name
1549    }
1550
1551    fn user_id(&self) -> &str {
1552        &self.user_id
1553    }
1554
1555    fn state(&self) -> &dyn State {
1556        self
1557    }
1558
1559    fn events(&self) -> &dyn Events {
1560        self
1561    }
1562
1563    fn last_update_time(&self) -> DateTime<Utc> {
1564        self.updated_at
1565    }
1566
1567    fn take_events(&mut self) -> Vec<Event> {
1568        std::mem::take(&mut self.events)
1569    }
1570}
1571
1572impl State for RedisSession {
1573    fn get(&self, key: &str) -> Option<Value> {
1574        self.state.get(key).cloned()
1575    }
1576
1577    fn set(&mut self, key: String, value: Value) {
1578        if let Err(msg) = adk_core::validate_state_key(&key) {
1579            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1580            return;
1581        }
1582        self.state.insert(key, value);
1583    }
1584
1585    fn all(&self) -> HashMap<String, Value> {
1586        self.state.clone()
1587    }
1588}
1589
1590impl Events for RedisSession {
1591    fn all(&self) -> Vec<Event> {
1592        self.events.clone()
1593    }
1594
1595    fn len(&self) -> usize {
1596        self.events.len()
1597    }
1598
1599    fn at(&self, index: usize) -> Option<&Event> {
1600        self.events.get(index)
1601    }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606    use super::*;
1607
1608    fn config(url: &str) -> RedisSessionConfig {
1609        RedisSessionConfig { url: url.to_string(), ttl: None, cluster_nodes: None }
1610    }
1611
1612    #[test]
1613    fn debug_redacts_userinfo_password() {
1614        let rendered = format!("{:?}", config("redis://admin:hunter2@cache.internal:6379/0"));
1615        assert_eq!(
1616            rendered,
1617            "RedisSessionConfig { url: \"redis://admin:[REDACTED]@cache.internal:6379/0\", \
1618             ttl: None, cluster_nodes: None }"
1619        );
1620    }
1621
1622    #[test]
1623    fn debug_redacts_password_only_userinfo() {
1624        let rendered = format!("{:?}", config("rediss://:hunter2@cache.internal:6380"));
1625        assert!(!rendered.contains("hunter2"), "password leaked: {rendered}");
1626        assert!(rendered.contains("rediss://:[REDACTED]@cache.internal:6380"));
1627
1628        let bare = format!("{:?}", config("redis://hunter2@cache.internal"));
1629        assert!(!bare.contains("hunter2"), "bare userinfo leaked: {bare}");
1630        assert!(bare.contains("redis://[REDACTED]@cache.internal"));
1631    }
1632
1633    #[test]
1634    fn debug_redacts_password_query_parameters() {
1635        let url = "redis-sentinel://sentinel.internal:26379/0?sentinelServiceName=main&sentinelPassword=hunter2";
1636        let rendered = format!("{:?}", config(url));
1637        assert!(!rendered.contains("hunter2"), "query password leaked: {rendered}");
1638        assert!(rendered.contains("sentinelServiceName=main&sentinelPassword=[REDACTED]"));
1639    }
1640
1641    #[test]
1642    fn debug_keeps_credential_free_urls_unchanged() {
1643        assert_eq!(redact_url_credentials("redis://localhost:6379"), "redis://localhost:6379");
1644        assert_eq!(redact_url_credentials("localhost:6379"), "localhost:6379");
1645    }
1646
1647    #[test]
1648    fn test_lookup_value_round_trips_identifiers_with_delimiters() {
1649        for (app, user) in
1650            [("app", "user"), ("a:b", "c"), ("a", "b:c"), ("100%", "%3A"), ("::", "%")]
1651        {
1652            assert_eq!(
1653                parse_lookup_value(&lookup_value(app, user)),
1654                Some((app.to_string(), user.to_string()))
1655            );
1656        }
1657    }
1658
1659    #[test]
1660    fn test_lookup_value_parses_values_written_before_encoding() {
1661        assert_eq!(
1662            [
1663                parse_lookup_value("app:user"),
1664                parse_lookup_value("app:50%off"),
1665                parse_lookup_value("x")
1666            ],
1667            [
1668                Some(("app".to_string(), "user".to_string())),
1669                Some(("app".to_string(), "50%off".to_string())),
1670                None,
1671            ]
1672        );
1673    }
1674
1675    #[test]
1676    fn test_lookup_key_is_encoded() {
1677        let lookup = |session| KeyLayout::Standalone.lookup(session);
1678        assert_eq!(lookup("s:1"), "session_lookup:s%3A1");
1679        assert_ne!(lookup("u:s"), session_key("session_lookup", "u", "s"));
1680    }
1681
1682    /// Every key of one session in the cluster layout, in the order the session's script
1683    /// names them, followed by the shared tier, index, and lookup keys.
1684    fn cluster_keys(app: &str, user: &str, session: &str) -> [String; 6] {
1685        let layout = KeyLayout::Cluster;
1686        [
1687            layout.session(app, user, session),
1688            layout.events(app, user, session),
1689            layout.app_state(app),
1690            layout.user_state(app, user),
1691            layout.index(app, user),
1692            layout.lookup(session),
1693        ]
1694    }
1695
1696    #[test]
1697    fn cluster_keys_of_one_session_share_a_hash_slot() {
1698        for (app, user, session) in [
1699            ("app", "user", "session"),
1700            ("a:b", "{u}", "s}{"),
1701            ("{", "}", "{}"),
1702            ("100%", "%7B", "x{y}z"),
1703        ] {
1704            let [session_k, events_k, _, user_k, index_k, _] = cluster_keys(app, user, session);
1705            assert_eq!(
1706                fred::util::redis_keyslot(session_k.as_bytes()),
1707                fred::util::redis_keyslot(events_k.as_bytes()),
1708                "{app}/{user}/{session}: the session and its events hash to different slots"
1709            );
1710            assert_eq!(
1711                fred::util::redis_keyslot(user_k.as_bytes()),
1712                fred::util::redis_keyslot(index_k.as_bytes()),
1713                "{app}/{user}: the user state and the session index hash to different slots"
1714            );
1715        }
1716    }
1717
1718    #[test]
1719    fn cluster_keys_encode_hash_tag_delimiters() {
1720        assert_eq!(
1721            cluster_keys("a:b", "{u}", "s}{"),
1722            [
1723                "adk:session:{a%3Ab:%7Bu%7D:s%7D%7B}".to_string(),
1724                "adk:session:{a%3Ab:%7Bu%7D:s%7D%7B}:events".to_string(),
1725                "adk:app_state:{a%3Ab}".to_string(),
1726                "adk:user_state:{a%3Ab:%7Bu%7D}".to_string(),
1727                "adk:sessions_idx:{a%3Ab:%7Bu%7D}".to_string(),
1728                "adk:session_lookup:{s%7D%7B}".to_string(),
1729            ]
1730        );
1731        // Redis hashes the text between the first `{` and the next `}`; unencoded, `{x}` in
1732        // a user ID would become the hash tag of every session that user owns.
1733        let key = KeyLayout::Cluster.session("a", "{x}", "1");
1734        let open = key.find('{').unwrap();
1735        let close = open + key[open..].find('}').unwrap();
1736        assert_eq!(&key[open + 1..close], "a:%7Bx%7D:1");
1737    }
1738
1739    #[test]
1740    fn cluster_keys_of_different_identities_never_collide() {
1741        let identities = [
1742            ("a:b", "c", "s"),
1743            ("a", "b:c", "s"),
1744            ("a", "b", "c:s"),
1745            ("{a}", "b", "s"),
1746            ("%7Ba%7D", "b", "s"),
1747            ("a", "u", "s:events"),
1748        ];
1749        let mut seen = std::collections::HashSet::new();
1750        for (app, user, session) in identities {
1751            let [session_k, events_k, ..] = cluster_keys(app, user, session);
1752            assert!(
1753                seen.insert(session_k.clone()),
1754                "{app}/{user}/{session}: the session key collided"
1755            );
1756            assert!(
1757                seen.insert(events_k.clone()),
1758                "{app}/{user}/{session}: the events key collided"
1759            );
1760        }
1761    }
1762
1763    #[test]
1764    fn standalone_layout_keeps_existing_key_names() {
1765        let layout = KeyLayout::Standalone;
1766        assert_eq!(
1767            [
1768                layout.session("app", "{u}", "s"),
1769                layout.events("app", "{u}", "s"),
1770                layout.app_state("app"),
1771                layout.user_state("app", "{u}"),
1772                layout.index("app", "{u}"),
1773                layout.lookup("{s}"),
1774            ],
1775            [
1776                "app:{u}:s".to_string(),
1777                "app:{u}:s:events".to_string(),
1778                "app_state:app".to_string(),
1779                "user_state:app:{u}".to_string(),
1780                "sessions_idx:app:{u}".to_string(),
1781                "session_lookup:{s}".to_string(),
1782            ]
1783        );
1784    }
1785}