rivescript_core/sessions/mod.rs
1//! # User Variable Session Adapters
2//!
3//! This module provides the trait and the default in-memory session adapter
4//! for storing user variables.
5//!
6//! In RiveScript, users are identified by their username which is passed in
7//! to the reply() function. Variables about the user which are set using tags
8//! like `<set>` or `{topic}` are stored in a User Variable Session Adapter.
9//!
10//! The default is to keep user variables in memory using HashMaps, and they
11//! can be exported and re-imported using functions like `get_uservars()` and
12//! `set_uservars()`. However, you may prefer to more proactively store user
13//! variables directly into something like a Redis cache or SQL database
14//! instead. The SessionManager trait from this module may allow you to do so.
15
16use async_trait::async_trait;
17use std::collections::HashMap;
18
19pub mod memory;
20
21/// What to do with frozen user variables after a thaw?
22pub enum ThawAction {
23 // Thaw means to restore the variables and erase the frozen copy.
24 Thaw,
25
26 // Discard means to cancel the frozen copy and not restore them.
27 Discard,
28
29 // Keep means to restore the variables but still keep the frozen copy.
30 Keep,
31}
32
33#[async_trait]
34pub trait SessionManager: Send + Sync {
35 /// Set one or more user variables from a hashmap.
36 async fn set(&self, username: &str, vars: HashMap<String, String>);
37
38 /// Add a message exchange to the user's history.
39 async fn add_history(&self, username: &str, input: &str, reply: &str);
40
41 /// Get the user's recent 9 inputs and replies.
42 async fn get_history(&self, username: &str) -> History;
43
44 /// Get a user variable, or return "undefined" if not set.
45 async fn get(&self, username: &str, name: &str) -> String;
46
47 /// Get all variables for a user.
48 async fn get_any(&self, username: &str) -> HashMap<String, String>;
49
50 /// Get all variables about all users.
51 async fn get_all(&self) -> HashMap<String, HashMap<String, String>>;
52
53 /// Clear all variables for a given user.
54 async fn clear(&self, username: &str);
55
56 /// Clear all variables about all users.
57 async fn clear_all(&self);
58
59 /// Freeze a snapshot of user variables that can later be thawed.
60 async fn freeze(&self, username: &str) -> Result<bool, String>;
61
62 /// Thaw frozen user variables, putting them back in place.
63 async fn thaw(&self, username: &str, action: ThawAction) -> Result<bool, String>;
64}
65
66#[derive(Debug, Clone)]
67pub struct History {
68 pub input: Vec<String>,
69 pub reply: Vec<String>,
70}
71
72impl Default for History {
73 fn default() -> Self {
74 Self {
75 input: vec!["undefined".to_string(); crate::MAX_HISTORY],
76 reply: vec!["undefined".to_string(); crate::MAX_HISTORY],
77 }
78 }
79}