1use std::{fmt, net::IpAddr, sync::LazyLock};
4
5use chrono::{DateTime, TimeDelta, Utc};
6use redis::{
7 RedisFuture, Script, Value,
8 aio::{ConnectionLike, ConnectionManager},
9 cluster_async::ClusterConnection,
10};
11use serde::Serialize;
12use sha2::{Digest, Sha256};
13use uuid::Uuid;
14
15use super::{
16 ClaimScope, SessionRecord, SessionStore, SessionUpdate, Supersede, TokenLookup, TokenRecord, session_bucket,
17 token_bucket,
18};
19use crate::{
20 checks::Check,
21 error::StoreError,
22 event::{ClientSummary, EventKind, SessionEvent, SessionOrigin},
23 fingerprint::Baseline,
24 token::TokenHash,
25};
26
27const PURGE_BATCH: usize = 500;
29
30const SREM_BATCH: usize = 1000;
32
33macro_rules! lua_helpers {
36 () => {
37 r"
38local function read_session(P, sid)
39 local v = redis.call('HMGET', P .. 's:' .. sid,
40 'subject', 'created', 'auth', 'seen', 'expires', 'step_up', 'baseline', 'origin')
41 if not v[1] then return nil end
42 return {sid, v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8] or ''}
43end
44
45-- Deletes a session and its tokens; returns its subject, or false if it did not exist.
46local function del_session(P, sid)
47 local s = P .. 's:' .. sid
48 local k = P .. 'k:' .. sid
49 local subject = redis.call('HGET', s, 'subject')
50 for _, hex in ipairs(redis.call('ZRANGE', k, 0, -1)) do
51 redis.call('DEL', P .. 't:' .. hex)
52 end
53 redis.call('DEL', k)
54 redis.call('ZREM', P .. 'x', sid)
55 redis.call('ZREM', P .. 'i', sid)
56 if subject then
57 redis.call('DEL', s)
58 return subject
59 end
60 return false
61end
62"
63 };
64}
65
66static INSERT: LazyLock<Script> = LazyLock::new(|| {
69 Script::new(
70 r"
71local P = ARGV[1]
72if redis.call('EXISTS', KEYS[1]) == 1 or redis.call('EXISTS', KEYS[2]) == 1 then return 0 end
73redis.call('HSET', KEYS[1], 'subject', ARGV[4], 'created', ARGV[5], 'auth', ARGV[6],
74 'seen', ARGV[7], 'expires', ARGV[8], 'step_up', ARGV[9], 'baseline', ARGV[10],
75 'exp_ms', ARGV[11], 'cur', ARGV[3], 'seq', 1)
76if ARGV[12] ~= '' then redis.call('HSET', KEYS[1], 'origin', ARGV[12]) end
77redis.call('HSET', KEYS[2], 'sid', ARGV[2], 'seq', 1, 'issued', ARGV[5])
78redis.call('ZADD', KEYS[3], 1, ARGV[3])
79redis.call('ZADD', KEYS[4], ARGV[8], ARGV[2])
80redis.call('ZADD', P .. 'i', ARGV[7], ARGV[2])
81redis.call('PEXPIREAT', KEYS[1], ARGV[11])
82redis.call('PEXPIREAT', KEYS[2], ARGV[11])
83redis.call('PEXPIREAT', KEYS[3], ARGV[11])
84return 1
85",
86 )
87});
88
89static INDEX_ADD: LazyLock<Script> = LazyLock::new(|| {
92 Script::new(
93 r"
94redis.call('SADD', KEYS[1], ARGV[1])
95local pt = redis.call('PEXPIRETIME', KEYS[1])
96if pt == -1 or pt < tonumber(ARGV[2]) then redis.call('PEXPIREAT', KEYS[1], ARGV[2]) end
97return 1
98",
99 )
100});
101
102static INDEX_MOVE: LazyLock<Script> = LazyLock::new(|| {
106 Script::new(
107 r"
108local pt = redis.call('PEXPIRETIME', KEYS[1])
109if pt ~= -2 then
110 local cur = redis.call('PEXPIRETIME', KEYS[2])
111 redis.call('SUNIONSTORE', KEYS[2], KEYS[2], KEYS[1])
112 local at = math.max(pt, cur)
113 if at > 0 then redis.call('PEXPIREAT', KEYS[2], at) end
114 redis.call('DEL', KEYS[1])
115end
116return redis.call('SMEMBERS', KEYS[2])
117",
118 )
119});
120
121static NEWER_USED: LazyLock<Script> = LazyLock::new(|| {
124 Script::new(
125 r"
126local P = ARGV[1]
127local t = redis.call('HMGET', KEYS[1], 'sid', 'seq')
128if not t[1] then return {} end
129local out = {}
130for _, hex in ipairs(redis.call('ZRANGEBYSCORE', P .. 'k:' .. t[1], '(' .. t[2], '+inf')) do
131 local n = redis.call('HMGET', P .. 't:' .. hex, 'issued', 'used', 'sup')
132 if n[2] then
133 out[#out + 1] = hex
134 out[#out + 1] = n[1]
135 out[#out + 1] = n[2]
136 out[#out + 1] = n[3] or ''
137 end
138end
139return out
140",
141 )
142});
143
144static FIND: LazyLock<Script> = LazyLock::new(|| {
146 Script::new(concat!(
147 lua_helpers!(),
148 r"
149local P = ARGV[1]
150local t = redis.call('HMGET', KEYS[1], 'sid', 'seq', 'issued', 'used', 'sup')
151if not t[1] then return false end
152local rec = read_session(P, t[1])
153if not rec then return false end
154local newer = 0
155for _, hex in ipairs(redis.call('ZRANGEBYSCORE', P .. 'k:' .. t[1], '(' .. t[2], '+inf')) do
156 if redis.call('HEXISTS', P .. 't:' .. hex, 'used') == 1 then
157 newer = 1
158 break
159 end
160end
161rec[10] = t[3]
162rec[11] = t[4] or ''
163rec[12] = t[5] or ''
164rec[13] = tostring(newer)
165return rec
166",
167 ))
168});
169
170static READ: LazyLock<Script> = LazyLock::new(|| {
172 Script::new(concat!(
173 lua_helpers!(),
174 "return read_session(ARGV[1], ARGV[2]) or false\n"
175 ))
176});
177
178static APPLY: LazyLock<Script> = LazyLock::new(|| {
181 Script::new(
182 r"
183local s = KEYS[1]
184if redis.call('EXISTS', s) == 0 then return 0 end
185local P, sid, now, mode = ARGV[1], ARGV[2], ARGV[3], ARGV[4]
186local rotated = 0
187if mode ~= '' then
188 local cur = redis.call('HGET', s, 'cur')
189 if cur then
190 local ck = P .. 't:' .. cur
191 local holds = false
192 if mode == 'exact' then
193 holds = cur == ARGV[5]
194 elseif mode == 'before' then
195 local issued = tonumber(redis.call('HGET', ck, 'issued'))
196 holds = issued ~= nil and issued < tonumber(ARGV[5])
197 elseif mode == 'current' then
198 holds = redis.call('EXISTS', ck) == 1
199 end
200 local nk = P .. 't:' .. ARGV[6]
201 if holds and redis.call('EXISTS', nk) == 0 then
202 local k = P .. 'k:' .. sid
203 redis.call('HSET', ck, 'sup', now)
204 local seq = redis.call('HINCRBY', s, 'seq', 1)
205 redis.call('HSET', nk, 'sid', sid, 'seq', seq, 'issued', now)
206 local exp = redis.call('HGET', s, 'exp_ms')
207 if exp then redis.call('PEXPIREAT', nk, exp) end
208 redis.call('ZADD', k, seq, ARGV[6])
209 redis.call('HSET', s, 'cur', ARGV[6])
210 local cutoff = tonumber(ARGV[7])
211 for _, hex in ipairs(redis.call('ZRANGE', k, 0, -1)) do
212 local sup = tonumber(redis.call('HGET', P .. 't:' .. hex, 'sup'))
213 if sup ~= nil and sup < cutoff then
214 redis.call('DEL', P .. 't:' .. hex)
215 redis.call('ZREM', k, hex)
216 end
217 end
218 rotated = 1
219 end
220 end
221end
222if ARGV[8] ~= '' then
223 local mk = P .. 't:' .. ARGV[8]
224 if redis.call('HGET', mk, 'sid') == sid and redis.call('HEXISTS', mk, 'used') == 0 then
225 redis.call('HSET', mk, 'used', now)
226 end
227end
228redis.call('HSET', s, 'seen', now)
229redis.call('ZADD', P .. 'i', now, sid)
230if ARGV[9] ~= '' then redis.call('HSET', s, 'baseline', ARGV[9]) end
231if ARGV[10] ~= '' then redis.call('HSET', s, 'step_up', ARGV[10]) end
232if ARGV[11] ~= '' then redis.call('HSET', s, 'auth', ARGV[11]) end
233return rotated
234",
235 )
236});
237
238static DELETE: LazyLock<Script> = LazyLock::new(|| {
241 Script::new(concat!(
242 lua_helpers!(),
243 r"
244if ARGV[3] and redis.call('HGET', KEYS[1], 'subject') ~= ARGV[3] then return false end
245return del_session(ARGV[1], ARGV[2])
246",
247 ))
248});
249
250static DELETE_EXPIRED: LazyLock<Script> = LazyLock::new(|| {
252 Script::new(concat!(
253 lua_helpers!(),
254 r"
255local P = ARGV[1]
256local found, n = 0, 0
257for _, idx in ipairs({{'x', ARGV[2]}, {'i', ARGV[3]}}) do
258 local ids = redis.call('ZRANGEBYSCORE', P .. idx[1], '-inf', idx[2], 'LIMIT', 0, ARGV[4])
259 found = found + #ids
260 for _, sid in ipairs(ids) do
261 if del_session(P, sid) then n = n + 1 end
262 end
263end
264return {n, found}
265",
266 ))
267});
268
269static DELETE_EVENTS: LazyLock<Script> = LazyLock::new(|| {
271 Script::new(
272 r"
273local bound = '(' .. ARGV[2]
274local n = redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', bound)
275for _, m in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', bound)) do
276 redis.call('DEL', ARGV[1] .. 'c:' .. m)
277end
278redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', bound)
279return n
280",
281 )
282});
283
284static CLAIM: LazyLock<Script> = LazyLock::new(|| {
286 Script::new(
287 r"
288local at = tonumber(redis.call('GET', KEYS[1]))
289if at ~= nil and tonumber(ARGV[1]) - at < tonumber(ARGV[2]) then return 0 end
290redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[3])
291redis.call('ZADD', KEYS[2], ARGV[1], ARGV[4])
292return 1
293",
294 )
295});
296
297#[derive(Clone)]
299enum Conn {
300 Standalone(ConnectionManager),
301 Cluster(ClusterConnection),
302}
303
304impl ConnectionLike for Conn {
305 fn req_packed_command<'a>(&'a mut self, cmd: &'a redis::Cmd) -> RedisFuture<'a, Value> {
306 match self {
307 Self::Standalone(conn) => conn.req_packed_command(cmd),
308 Self::Cluster(conn) => conn.req_packed_command(cmd),
309 }
310 }
311
312 fn req_packed_commands<'a>(
313 &'a mut self,
314 pipeline: &'a redis::Pipeline,
315 offset: usize,
316 count: usize,
317 ) -> RedisFuture<'a, Vec<Value>> {
318 match self {
319 Self::Standalone(conn) => conn.req_packed_commands(pipeline, offset, count),
320 Self::Cluster(conn) => conn.req_packed_commands(pipeline, offset, count),
321 }
322 }
323
324 fn get_db(&self) -> i64 {
325 match self {
326 Self::Standalone(conn) => conn.get_db(),
327 Self::Cluster(conn) => conn.get_db(),
328 }
329 }
330}
331
332#[derive(Clone)]
389pub struct ValkeyStore {
390 conn: Conn,
391 prefix: String,
392}
393
394impl fmt::Debug for ValkeyStore {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 f.debug_struct("ValkeyStore")
397 .field("key_prefix", &self.prefix)
398 .finish_non_exhaustive()
399 }
400}
401
402impl ValkeyStore {
403 pub fn new(conn: ConnectionManager) -> Self {
405 Self {
406 conn: Conn::Standalone(conn),
407 prefix: "sg:".to_owned(),
408 }
409 }
410
411 pub fn from_cluster(conn: ClusterConnection) -> Self {
413 Self {
414 conn: Conn::Cluster(conn),
415 prefix: "sg:".to_owned(),
416 }
417 }
418
419 pub async fn connect_cluster<T: redis::IntoConnectionInfo>(
426 nodes: impl IntoIterator<Item = T>,
427 ) -> Result<Self, redis::RedisError> {
428 let client = redis::cluster::ClusterClient::new(nodes)?;
429 Ok(Self::from_cluster(client.get_async_connection().await?))
430 }
431
432 pub async fn connect(url: &str) -> Result<Self, redis::RedisError> {
439 let client = redis::Client::open(url)?;
440 Ok(Self::new(ConnectionManager::new(client).await?))
441 }
442
443 #[must_use]
451 pub fn key_prefix(mut self, prefix: impl Into<String>) -> Self {
452 let prefix = prefix.into();
453 assert!(
454 !prefix.contains(['{', '}']),
455 "ValkeyStore key prefix must not contain '{{' or '}}'"
456 );
457 self.prefix = prefix;
458 self
459 }
460
461 fn bucket_prefix(&self, bucket: u8) -> String {
463 format!("{}{{{bucket:02x}}}:", self.prefix)
464 }
465
466 fn key(&self, bucket: u8, kind: &str, id: &str) -> String {
468 format!("{}{kind}:{id}", self.bucket_prefix(bucket))
469 }
470
471 fn plain_key(&self, bucket: u8, kind: &str) -> String {
473 format!("{}{kind}", self.bucket_prefix(bucket))
474 }
475
476 fn conn(&self) -> Conn {
477 self.conn.clone()
478 }
479
480 async fn unindex(&self, subject: &str, session_id: Uuid) {
483 let bucket = subject_bucket(subject);
484 for kind in ["u", "ur"] {
485 let _removed: Result<i64, _> = redis::cmd("SREM")
486 .arg(self.key(bucket, kind, subject))
487 .arg(session_id.to_string())
488 .query_async(&mut self.conn())
489 .await;
490 }
491 }
492}
493
494fn subject_bucket(subject: &str) -> u8 {
496 Sha256::digest(subject.as_bytes())[0]
497}
498
499fn ensure_aligned(session_id: Uuid, token: &TokenHash) -> Result<(), StoreError> {
500 if session_bucket(session_id) == token_bucket(token) {
501 Ok(())
502 } else {
503 Err("valkey store: token and session id are in different buckets".into())
504 }
505}
506
507fn micros(at: DateTime<Utc>) -> String {
508 at.timestamp_micros().to_string()
509}
510
511fn parse_time(value: &str) -> Result<DateTime<Utc>, StoreError> {
512 value
513 .parse::<i64>()
514 .ok()
515 .and_then(DateTime::from_timestamp_micros)
516 .ok_or_else(|| "valkey store: malformed timestamp".into())
517}
518
519fn parse_optional_time(value: &str) -> Result<Option<DateTime<Utc>>, StoreError> {
520 if value.is_empty() {
521 Ok(None)
522 } else {
523 parse_time(value).map(Some)
524 }
525}
526
527fn parse_session(fields: &[String]) -> Result<SessionRecord, StoreError> {
529 let [id, subject, created, auth, seen, expires, step_up, baseline, origin] = fields else {
530 return Err("valkey store: malformed session".into());
531 };
532 let baseline: Baseline = serde_json::from_str(baseline)?;
533 let origin: Option<SessionOrigin> = if origin.is_empty() {
534 None
535 } else {
536 Some(serde_json::from_str(origin)?)
537 };
538 Ok(SessionRecord {
539 id: Uuid::parse_str(id)?,
540 subject: subject.clone(),
541 created_at: parse_time(created)?,
542 authenticated_at: parse_time(auth)?,
543 last_seen_at: parse_time(seen)?,
544 expires_at: parse_time(expires)?,
545 step_up_required: step_up == "1",
546 baseline,
547 origin,
548 })
549}
550
551#[derive(Serialize)]
552struct EventRow<'a> {
553 id: Uuid,
555 session_id: Uuid,
556 subject: &'a str,
557 kind: EventKind,
558 enforced: bool,
559 score: Option<u32>,
560 signals: &'a [Check],
561 ip: IpAddr,
562 user_agent: Option<&'a str>,
563 client: &'a ClientSummary,
564 at: DateTime<Utc>,
565}
566
567impl SessionStore for ValkeyStore {
568 fn sharded(&self) -> bool {
569 true
570 }
571
572 async fn insert_session(&self, session: &SessionRecord, token: &TokenHash) -> Result<(), StoreError> {
573 ensure_aligned(session.id, token)?;
574 let bucket = session_bucket(session.id);
575 let sid = session.id.to_string();
576 let hex = token.to_hex();
577 let exp_ms = session
578 .expires_at
579 .timestamp_micros()
580 .saturating_add(999)
581 .div_euclid(1000);
582 let sbucket = subject_bucket(&session.subject);
584 let _: i64 = INDEX_ADD
585 .key(self.key(sbucket, "u", &session.subject))
586 .arg(&sid)
587 .arg(exp_ms)
588 .invoke_async(&mut self.conn())
589 .await?;
590 let inserted: i64 = INSERT
591 .key(self.key(bucket, "s", &sid))
592 .key(self.key(bucket, "t", &hex))
593 .key(self.key(bucket, "k", &sid))
594 .key(self.plain_key(bucket, "x"))
595 .arg(self.bucket_prefix(bucket))
596 .arg(&sid)
597 .arg(&hex)
598 .arg(&session.subject)
599 .arg(micros(session.created_at))
600 .arg(micros(session.authenticated_at))
601 .arg(micros(session.last_seen_at))
602 .arg(micros(session.expires_at))
603 .arg(if session.step_up_required { "1" } else { "0" })
604 .arg(serde_json::to_string(&session.baseline)?)
605 .arg(exp_ms)
606 .arg(match &session.origin {
607 Some(origin) => serde_json::to_string(origin)?,
608 None => String::new(),
609 })
610 .invoke_async(&mut self.conn())
611 .await?;
612 if inserted != 1 {
613 return Err("duplicate session id or token".into());
614 }
615 let indexed: bool = redis::cmd("SISMEMBER")
616 .arg(self.key(sbucket, "u", &session.subject))
617 .arg(&sid)
618 .query_async(&mut self.conn())
619 .await?;
620 if !indexed {
621 let exists: bool = redis::cmd("EXISTS")
622 .arg(self.key(bucket, "s", &sid))
623 .query_async(&mut self.conn())
624 .await?;
625 if exists {
626 self.delete_session(session.id).await?;
629 return Err("valkey store: subject was revoked while the session was created".into());
630 }
631 }
632 Ok(())
633 }
634
635 async fn find_by_token(&self, token: &TokenHash) -> Result<Option<TokenLookup>, StoreError> {
636 let bucket = token_bucket(token);
637 let fields: Option<Vec<String>> = FIND
638 .key(self.key(bucket, "t", &token.to_hex()))
639 .arg(self.bucket_prefix(bucket))
640 .invoke_async(&mut self.conn())
641 .await?;
642 let Some(fields) = fields else {
643 return Ok(None);
644 };
645 let [session @ .., issued, used, superseded, newer] = fields.as_slice() else {
646 return Err("valkey store: malformed token lookup".into());
647 };
648 Ok(Some(TokenLookup {
649 session: parse_session(session)?,
650 token: TokenRecord {
651 hash: *token,
652 issued_at: parse_time(issued)?,
653 first_used_at: parse_optional_time(used)?,
654 superseded_at: parse_optional_time(superseded)?,
655 },
656 newer_token_used: newer == "1",
657 }))
658 }
659
660 async fn newer_used_tokens(&self, token: &TokenHash) -> Result<Option<Vec<TokenRecord>>, StoreError> {
661 let bucket = token_bucket(token);
662 let fields: Vec<String> = NEWER_USED
663 .key(self.key(bucket, "t", &token.to_hex()))
664 .arg(self.bucket_prefix(bucket))
665 .invoke_async(&mut self.conn())
666 .await?;
667 let tokens = fields
668 .chunks(4)
669 .map(|record| {
670 let [hex, issued, used, superseded] = record else {
671 return Err("valkey store: malformed newer token list".into());
672 };
673 Ok(TokenRecord {
674 hash: TokenHash::from_hex(hex).ok_or("valkey store: malformed token hash")?,
675 issued_at: parse_time(issued)?,
676 first_used_at: parse_optional_time(used)?,
677 superseded_at: parse_optional_time(superseded)?,
678 })
679 })
680 .collect::<Result<Vec<_>, StoreError>>()?;
681 Ok(Some(tokens))
682 }
683
684 async fn apply(&self, update: &SessionUpdate) -> Result<bool, StoreError> {
685 if let Some(rotation) = &update.rotation {
686 ensure_aligned(update.session_id, &rotation.new_token)?;
687 }
688 if let Some(used) = &update.mark_used {
689 ensure_aligned(update.session_id, used)?;
690 }
691 let bucket = session_bucket(update.session_id);
692 let sid = update.session_id.to_string();
693 let (mode, mode_arg, new_token, prune) = match &update.rotation {
694 None => ("", String::new(), String::new(), String::new()),
695 Some(rotation) => {
696 let (mode, arg) = match rotation.supersede {
697 Supersede::Exact(hash) => ("exact", hash.to_hex()),
698 Supersede::CurrentIssuedBefore(at) => ("before", micros(at)),
699 Supersede::Current => ("current", String::new()),
700 };
701 (
702 mode,
703 arg,
704 rotation.new_token.to_hex(),
705 micros(rotation.prune_superseded_before),
706 )
707 }
708 };
709 let baseline = match &update.baseline {
710 Some(baseline) => serde_json::to_string(baseline)?,
711 None => String::new(),
712 };
713 let step_up = match update.step_up_required {
714 Some(true) => "1",
715 Some(false) => "0",
716 None => "",
717 };
718 let rotated: i64 = APPLY
719 .key(self.key(bucket, "s", &sid))
720 .arg(self.bucket_prefix(bucket))
721 .arg(&sid)
722 .arg(micros(update.now))
723 .arg(mode)
724 .arg(mode_arg)
725 .arg(new_token)
726 .arg(prune)
727 .arg(update.mark_used.map(|h| h.to_hex()).unwrap_or_default())
728 .arg(baseline)
729 .arg(step_up)
730 .arg(update.authenticated_at.map(micros).unwrap_or_default())
731 .invoke_async(&mut self.conn())
732 .await?;
733 Ok(rotated == 1)
734 }
735
736 async fn delete_session(&self, session_id: Uuid) -> Result<bool, StoreError> {
737 let bucket = session_bucket(session_id);
738 let sid = session_id.to_string();
739 let subject: Option<String> = DELETE
740 .key(self.key(bucket, "s", &sid))
741 .arg(self.bucket_prefix(bucket))
742 .arg(&sid)
743 .invoke_async(&mut self.conn())
744 .await?;
745 let Some(subject) = subject else {
746 return Ok(false);
747 };
748 self.unindex(&subject, session_id).await;
749 Ok(true)
750 }
751
752 async fn delete_subject_sessions(&self, subject: &str) -> Result<Vec<Uuid>, StoreError> {
753 let sbucket = subject_bucket(subject);
754 let revoking = self.key(sbucket, "ur", subject);
755 let members: Vec<String> = INDEX_MOVE
756 .key(self.key(sbucket, "u", subject))
757 .key(&revoking)
758 .invoke_async(&mut self.conn())
759 .await?;
760 let mut deleted = Vec::new();
761 for member in &members {
762 let Ok(id) = Uuid::parse_str(member) else { continue };
764 let bucket = session_bucket(id);
765 let removed: Option<String> = DELETE
766 .key(self.key(bucket, "s", member))
767 .arg(self.bucket_prefix(bucket))
768 .arg(member)
769 .arg(subject)
770 .invoke_async(&mut self.conn())
771 .await?;
772 if removed.is_some() {
773 deleted.push(id);
774 }
775 }
776 for chunk in members.chunks(SREM_BATCH) {
778 let _removed: i64 = redis::cmd("SREM")
779 .arg(&revoking)
780 .arg(chunk)
781 .query_async(&mut self.conn())
782 .await?;
783 }
784 Ok(deleted)
785 }
786
787 async fn list_subject_sessions(&self, subject: &str) -> Result<Vec<SessionRecord>, StoreError> {
788 let sbucket = subject_bucket(subject);
789 let members: Vec<String> = redis::cmd("SUNION")
790 .arg(self.key(sbucket, "u", subject))
791 .arg(self.key(sbucket, "ur", subject))
792 .query_async(&mut self.conn())
793 .await?;
794 let mut sessions = Vec::with_capacity(members.len());
795 let mut stale = Vec::new();
796 for member in &members {
797 let Ok(id) = Uuid::parse_str(member) else {
798 stale.push(member);
799 continue;
800 };
801 let bucket = session_bucket(id);
802 let fields: Option<Vec<String>> = READ
803 .key(self.key(bucket, "s", member))
804 .arg(self.bucket_prefix(bucket))
805 .arg(member)
806 .invoke_async(&mut self.conn())
807 .await?;
808 match fields.map(|fields| parse_session(&fields)).transpose()? {
809 Some(record) if record.subject == subject => sessions.push(record),
810 _ => stale.push(member),
811 }
812 }
813 for chunk in stale.chunks(SREM_BATCH) {
816 for kind in ["u", "ur"] {
817 let _removed: Result<i64, _> = redis::cmd("SREM")
818 .arg(self.key(sbucket, kind, subject))
819 .arg(chunk)
820 .query_async(&mut self.conn())
821 .await;
822 }
823 }
824 Ok(sessions)
825 }
826
827 async fn delete_expired(&self, now: DateTime<Utc>, idle_cutoff: DateTime<Utc>) -> Result<u64, StoreError> {
828 let mut total = 0;
829 for bucket in 0..=u8::MAX {
830 loop {
831 let (deleted, found): (u64, u64) = DELETE_EXPIRED
832 .key(self.plain_key(bucket, "x"))
833 .arg(self.bucket_prefix(bucket))
834 .arg(micros(now))
835 .arg(micros(idle_cutoff))
836 .arg(PURGE_BATCH)
837 .invoke_async(&mut self.conn())
838 .await?;
839 total += deleted;
840 if found == 0 {
841 break;
842 }
843 }
844 }
845 Ok(total)
846 }
847
848 async fn record_event(&self, event: &SessionEvent) -> Result<(), StoreError> {
849 let row = EventRow {
850 id: Uuid::new_v4(),
851 session_id: event.session_id,
852 subject: &event.subject,
853 kind: event.kind,
854 enforced: event.enforced,
855 score: event.score,
856 signals: &event.signals,
857 ip: event.ip,
858 user_agent: event.user_agent.as_deref(),
859 client: &event.client,
860 at: event.at,
861 };
862 let _added: i64 = redis::cmd("ZADD")
863 .arg(self.plain_key(session_bucket(event.session_id), "e"))
864 .arg(event.at.timestamp_micros())
865 .arg(serde_json::to_string(&row)?)
866 .query_async(&mut self.conn())
867 .await?;
868 Ok(())
869 }
870
871 async fn delete_events_before(&self, cutoff: DateTime<Utc>) -> Result<u64, StoreError> {
872 let mut total = 0;
873 for bucket in 0..=u8::MAX {
874 let deleted: u64 = DELETE_EVENTS
875 .key(self.plain_key(bucket, "e"))
876 .key(self.plain_key(bucket, "cz"))
877 .arg(self.bucket_prefix(bucket))
878 .arg(micros(cutoff))
879 .invoke_async(&mut self.conn())
880 .await?;
881 total += deleted;
882 }
883 Ok(total)
884 }
885
886 async fn claim_event(
887 &self,
888 scope: ClaimScope<'_>,
889 kind: EventKind,
890 now: DateTime<Utc>,
891 window: TimeDelta,
892 ) -> Result<bool, StoreError> {
893 let (bucket, member) = match scope {
895 ClaimScope::Session(session_id) => (session_bucket(session_id), format!("{session_id}:{kind}")),
896 ClaimScope::Subject(subject) => (subject_bucket(subject), format!("s:{subject}:{kind}")),
897 };
898 let micros_window = window.num_microseconds().unwrap_or(i64::MAX);
899 let millis_window = window.num_milliseconds().max(1);
900 let claimed: i64 = CLAIM
901 .key(self.key(bucket, "c", &member))
902 .key(self.plain_key(bucket, "cz"))
903 .arg(micros(now))
904 .arg(micros_window)
905 .arg(millis_window)
906 .arg(&member)
907 .invoke_async(&mut self.conn())
908 .await?;
909 Ok(claimed == 1)
910 }
911}