1use std::fmt;
4use std::path::{Path, PathBuf};
5
6use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
7use async_trait::async_trait;
8use serde_json::Value;
9use tokio::sync::{Mutex, RwLock};
10
11use super::rule::StandingRule;
12
13#[async_trait]
25pub trait StandingRuleStore: fmt::Debug + Send + Sync {
26 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>>;
28 async fn grant(&self, rule: StandingRule) -> Result<StandingRule>;
30 async fn revoke(&self, app: &str, id: &str) -> Result<bool>;
32 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>>;
34
35 async fn replace(&self, rule: StandingRule) -> Result<bool> {
49 let _ = rule;
50 Err(AdkError::new(
51 ErrorComponent::Agent,
52 ErrorCategory::Unsupported,
53 "harness.rule.replace_unsupported",
54 "this standing rule store cannot change a rule in one step, so a rule cannot be \
55 extended: implement `StandingRuleStore::replace` for it, or stop the rule and \
56 allow it again",
57 ))
58 }
59}
60
61fn validate(rule: &StandingRule) -> Result<()> {
62 if rule.id.trim().is_empty() || rule.tool.trim().is_empty() {
63 return Err(AdkError::new(
64 ErrorComponent::Agent,
65 ErrorCategory::InvalidInput,
66 "harness.rule.invalid",
67 "a standing rule needs a non-empty id and tool pattern",
68 ));
69 }
70 Ok(())
71}
72
73fn applies_to_session(rule: &StandingRule, app: &str, user: &str, session: &str) -> bool {
74 rule.scope.app_name() == app
75 && rule.scope.user_id() == user
76 && rule.scope.session_id().is_none_or(|own| own == session)
77}
78
79#[derive(Debug, Default)]
88pub struct InMemoryStandingRuleStore {
89 rules: RwLock<Vec<StandingRule>>,
90}
91
92impl InMemoryStandingRuleStore {
93 pub fn new() -> Self {
95 Self::default()
96 }
97}
98
99#[async_trait]
100impl StandingRuleStore for InMemoryStandingRuleStore {
101 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
102 Ok(self
103 .rules
104 .read()
105 .await
106 .iter()
107 .filter(|rule| applies_to_session(rule, app, user, session))
108 .cloned()
109 .collect())
110 }
111
112 async fn grant(&self, rule: StandingRule) -> Result<StandingRule> {
113 validate(&rule)?;
114 let mut rules = self.rules.write().await;
115 rules.retain(|existing| existing.id != rule.id);
116 rules.push(rule.clone());
117 Ok(rule)
118 }
119
120 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
121 let mut rules = self.rules.write().await;
122 let before = rules.len();
123 rules.retain(|rule| !(rule.scope.app_name() == app && rule.id == id));
124 Ok(rules.len() != before)
125 }
126
127 async fn replace(&self, rule: StandingRule) -> Result<bool> {
128 validate(&rule)?;
129 let mut rules = self.rules.write().await;
130 let held = rules.iter_mut().find(|existing| {
131 existing.scope.app_name() == rule.scope.app_name() && existing.id == rule.id
132 });
133 Ok(held.map(|existing| *existing = rule).is_some())
134 }
135
136 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
137 Ok(self
138 .rules
139 .read()
140 .await
141 .iter()
142 .filter(|rule| rule.scope.app_name() == app && rule.scope.user_id() == user)
143 .cloned()
144 .collect())
145 }
146}
147
148#[derive(Debug)]
163pub struct FileStandingRuleStore {
164 root: PathBuf,
165 write: Mutex<()>,
166}
167
168impl FileStandingRuleStore {
169 pub fn new(root: impl Into<PathBuf>) -> Self {
171 Self { root: root.into(), write: Mutex::new(()) }
172 }
173
174 pub fn in_home() -> Result<Self> {
180 Ok(Self::new(crate::fsutil::adk_home()?.join("approvals")))
181 }
182
183 fn app_dir(&self, app: &str) -> PathBuf {
184 let safe = !app.is_empty()
185 && app != "."
186 && app != ".."
187 && app.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
188 if safe { self.root.join(app) } else { self.root.join(crate::fsutil::sha256_hex(app)) }
189 }
190
191 fn user_file(&self, app: &str, user: &str) -> PathBuf {
192 self.app_dir(app).join(format!("{}.json", crate::fsutil::sha256_hex(user)))
193 }
194
195 async fn read_entries(path: &Path) -> Result<Vec<Value>> {
196 let Some(bytes) = crate::fsutil::read_optional(path).await? else {
197 return Ok(Vec::new());
198 };
199 match serde_json::from_slice::<Value>(&bytes) {
200 Ok(Value::Array(entries)) => Ok(entries),
201 _ => {
202 tracing::warn!(path = %path.display(), "standing rule file is not a JSON array; ignoring it");
203 Ok(Vec::new())
204 }
205 }
206 }
207
208 fn parse(entries: &[Value]) -> Vec<StandingRule> {
209 entries
210 .iter()
211 .filter_map(|entry| match serde_json::from_value::<StandingRule>(entry.clone()) {
212 Ok(rule) => Some(rule),
213 Err(error) => {
214 tracing::warn!(error = %error, "ignoring a standing rule this release cannot parse");
215 None
216 }
217 })
218 .collect()
219 }
220
221 async fn write_entries(path: &Path, entries: &[Value]) -> Result<()> {
222 let bytes = serde_json::to_vec_pretty(entries)
223 .map_err(|error| crate::fsutil::serialize_error("standing rules", &error))?;
224 crate::fsutil::write_atomic_private(path, &bytes).await
225 }
226}
227
228fn entry_id(entry: &Value) -> Option<&str> {
229 entry.get("id").and_then(Value::as_str)
230}
231
232#[async_trait]
233impl StandingRuleStore for FileStandingRuleStore {
234 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
235 let entries = Self::read_entries(&self.user_file(app, user)).await?;
236 Ok(Self::parse(&entries)
237 .into_iter()
238 .filter(|rule| applies_to_session(rule, app, user, session))
239 .collect())
240 }
241
242 async fn grant(&self, rule: StandingRule) -> Result<StandingRule> {
243 validate(&rule)?;
244 let _guard = self.write.lock().await;
245 let path = self.user_file(rule.scope.app_name(), rule.scope.user_id());
246 let mut entries = Self::read_entries(&path).await?;
247 entries.retain(|entry| entry_id(entry) != Some(rule.id.as_str()));
248 entries.push(
249 serde_json::to_value(&rule)
250 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?,
251 );
252 Self::write_entries(&path, &entries).await?;
253 Ok(rule)
254 }
255
256 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
257 let _guard = self.write.lock().await;
258 let dir = self.app_dir(app);
259 let mut listing = match tokio::fs::read_dir(&dir).await {
260 Ok(listing) => listing,
261 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
262 Err(error) => {
263 return Err(AdkError::new(
264 ErrorComponent::Agent,
265 ErrorCategory::Unavailable,
266 "harness.store.io",
267 format!("list {}: {error}", dir.display()),
268 ));
269 }
270 };
271 let mut removed = false;
272 while let Ok(Some(file)) = listing.next_entry().await {
273 let path = file.path();
274 if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
275 continue;
276 }
277 let mut entries = Self::read_entries(&path).await?;
278 let before = entries.len();
279 entries.retain(|entry| entry_id(entry) != Some(id));
280 if entries.len() != before {
281 Self::write_entries(&path, &entries).await?;
282 removed = true;
283 }
284 }
285 Ok(removed)
286 }
287
288 async fn replace(&self, rule: StandingRule) -> Result<bool> {
289 validate(&rule)?;
290 let _guard = self.write.lock().await;
291 let path = self.user_file(rule.scope.app_name(), rule.scope.user_id());
292 let mut entries = Self::read_entries(&path).await?;
293 let Some(entry) =
294 entries.iter_mut().find(|entry| entry_id(entry) == Some(rule.id.as_str()))
295 else {
296 return Ok(false);
297 };
298 *entry = serde_json::to_value(&rule)
299 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
300 Self::write_entries(&path, &entries).await?;
301 Ok(true)
302 }
303
304 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
305 let entries = Self::read_entries(&self.user_file(app, user)).await?;
306 Ok(Self::parse(&entries)
307 .into_iter()
308 .filter(|rule| rule.scope.app_name() == app && rule.scope.user_id() == user)
309 .collect())
310 }
311}
312
313#[cfg(feature = "sqlite")]
324#[derive(Debug, Clone)]
325pub struct SqliteStandingRuleStore {
326 pool: sqlx::SqlitePool,
327 #[cfg(feature = "encrypted")]
328 envelope: Option<crate::encrypted::StoreEnvelope>,
329}
330
331#[cfg(feature = "sqlite")]
332impl SqliteStandingRuleStore {
333 pub fn new(pool: sqlx::SqlitePool) -> Self {
335 Self {
336 pool,
337 #[cfg(feature = "encrypted")]
338 envelope: None,
339 }
340 }
341
342 #[cfg(feature = "encrypted")]
344 #[must_use]
345 pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
346 self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "rules"));
347 self
348 }
349
350 #[cfg(feature = "encrypted")]
359 pub async fn rewrap(&self) -> Result<u64> {
360 let Some(envelope) = &self.envelope else {
361 return Ok(0);
362 };
363 let rows: Vec<(String, String, String)> =
364 sqlx::query_as("SELECT app_name, id, rule FROM adk_harness_rules")
365 .fetch_all(&self.pool)
366 .await
367 .map_err(crate::fsutil::db_error)?;
368 let mut changed = 0;
369 for (app, id, text) in rows {
370 if let Some(resealed) = envelope.reseal_or_seal(&[&app, &id], &text)? {
371 sqlx::query("UPDATE adk_harness_rules SET rule = ? WHERE app_name = ? AND id = ?")
372 .bind(resealed)
373 .bind(&app)
374 .bind(&id)
375 .execute(&self.pool)
376 .await
377 .map_err(crate::fsutil::db_error)?;
378 changed += 1;
379 }
380 }
381 Ok(changed)
382 }
383
384 #[cfg(feature = "encrypted")]
385 fn encode(&self, address: &[&str], text: String) -> Result<String> {
386 crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
387 }
388
389 #[cfg(not(feature = "encrypted"))]
390 fn encode(&self, _address: &[&str], text: String) -> Result<String> {
391 Ok(text)
392 }
393
394 #[cfg(feature = "encrypted")]
395 fn decode(&self, address: &[&str], text: String) -> Result<String> {
396 crate::encrypted::decode_row(self.envelope.as_ref(), "rules", address, text)
397 }
398
399 #[cfg(not(feature = "encrypted"))]
400 fn decode(&self, _address: &[&str], text: String) -> Result<String> {
401 Ok(text)
402 }
403
404 pub async fn migrate(&self) -> Result<()> {
410 sqlx::query(
411 "CREATE TABLE IF NOT EXISTS adk_harness_rules (\
412 app_name TEXT NOT NULL, id TEXT NOT NULL, user_id TEXT NOT NULL, \
413 session_id TEXT, rule TEXT NOT NULL, PRIMARY KEY (app_name, id))",
414 )
415 .execute(&self.pool)
416 .await
417 .map_err(crate::fsutil::db_error)?;
418 Ok(())
419 }
420
421 fn parse(&self, app: &str, rows: Vec<(String, String)>) -> Result<Vec<StandingRule>> {
422 let mut rules = Vec::with_capacity(rows.len());
423 for (id, text) in rows {
424 let text = self.decode(&[app, &id], text)?;
425 match serde_json::from_str::<StandingRule>(&text) {
426 Ok(rule) => rules.push(rule),
427 Err(error) => {
428 tracing::warn!(error = %error, "ignoring a standing rule this release cannot parse");
429 }
430 }
431 }
432 Ok(rules)
433 }
434}
435
436#[cfg(feature = "sqlite")]
437#[async_trait]
438impl StandingRuleStore for SqliteStandingRuleStore {
439 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
440 let rows: Vec<(String, String)> = sqlx::query_as(
441 "SELECT id, rule FROM adk_harness_rules WHERE app_name = ? AND user_id = ? \
442 AND (session_id IS NULL OR session_id = ?) ORDER BY rowid",
443 )
444 .bind(app)
445 .bind(user)
446 .bind(session)
447 .fetch_all(&self.pool)
448 .await
449 .map_err(crate::fsutil::db_error)?;
450 Ok(self
451 .parse(app, rows)?
452 .into_iter()
453 .filter(|rule| applies_to_session(rule, app, user, session))
454 .collect())
455 }
456
457 async fn grant(&self, rule: StandingRule) -> Result<StandingRule> {
458 validate(&rule)?;
459 let text = serde_json::to_string(&rule)
460 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
461 let text = self.encode(&[rule.scope.app_name(), &rule.id], text)?;
462 sqlx::query(
463 "INSERT INTO adk_harness_rules (app_name, id, user_id, session_id, rule) VALUES (?, ?, ?, ?, ?) \
464 ON CONFLICT (app_name, id) DO UPDATE SET user_id = excluded.user_id, \
465 session_id = excluded.session_id, rule = excluded.rule",
466 )
467 .bind(rule.scope.app_name())
468 .bind(&rule.id)
469 .bind(rule.scope.user_id())
470 .bind(rule.scope.session_id())
471 .bind(text)
472 .execute(&self.pool)
473 .await
474 .map_err(crate::fsutil::db_error)?;
475 Ok(rule)
476 }
477
478 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
479 let result = sqlx::query("DELETE FROM adk_harness_rules WHERE app_name = ? AND id = ?")
480 .bind(app)
481 .bind(id)
482 .execute(&self.pool)
483 .await
484 .map_err(crate::fsutil::db_error)?;
485 Ok(result.rows_affected() > 0)
486 }
487
488 async fn replace(&self, rule: StandingRule) -> Result<bool> {
489 validate(&rule)?;
490 let text = serde_json::to_string(&rule)
491 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
492 let text = self.encode(&[rule.scope.app_name(), &rule.id], text)?;
493 let result = sqlx::query(
494 "UPDATE adk_harness_rules SET user_id = ?, session_id = ?, rule = ? \
495 WHERE app_name = ? AND id = ?",
496 )
497 .bind(rule.scope.user_id())
498 .bind(rule.scope.session_id())
499 .bind(text)
500 .bind(rule.scope.app_name())
501 .bind(&rule.id)
502 .execute(&self.pool)
503 .await
504 .map_err(crate::fsutil::db_error)?;
505 Ok(result.rows_affected() > 0)
506 }
507
508 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
509 let rows: Vec<(String, String)> = sqlx::query_as(
510 "SELECT id, rule FROM adk_harness_rules WHERE app_name = ? AND user_id = ? ORDER BY rowid",
511 )
512 .bind(app)
513 .bind(user)
514 .fetch_all(&self.pool)
515 .await
516 .map_err(crate::fsutil::db_error)?;
517 self.parse(app, rows)
518 }
519}
520
521#[cfg(any(feature = "postgres", feature = "redis"))]
523fn parse_rule_texts(texts: impl IntoIterator<Item = String>) -> Vec<StandingRule> {
524 texts
525 .into_iter()
526 .filter_map(|text| match serde_json::from_str::<StandingRule>(&text) {
527 Ok(rule) => Some(rule),
528 Err(error) => {
529 tracing::warn!(error = %error, "ignoring a standing rule this release cannot parse");
530 None
531 }
532 })
533 .collect()
534}
535
536#[cfg(any(feature = "postgres", feature = "redis"))]
538const RULE_CACHE_ENTRIES: usize = 1024;
539
540#[cfg(any(feature = "postgres", feature = "redis"))]
549#[derive(Debug)]
550struct RuleCache<K> {
551 entries: RwLock<std::collections::HashMap<K, VersionedRules>>,
552}
553
554#[cfg(any(feature = "postgres", feature = "redis"))]
556type VersionedRules = (i64, std::sync::Arc<Vec<StandingRule>>);
557
558#[cfg(any(feature = "postgres", feature = "redis"))]
559impl<K: Eq + std::hash::Hash> RuleCache<K> {
560 fn new() -> Self {
561 Self { entries: RwLock::new(std::collections::HashMap::new()) }
562 }
563
564 async fn get(&self, key: &K, version: i64) -> Option<std::sync::Arc<Vec<StandingRule>>> {
565 let entries = self.entries.read().await;
566 entries.get(key).filter(|(at, _)| *at == version).map(|(_, rules)| rules.clone())
567 }
568
569 async fn put(&self, key: K, version: i64, rules: std::sync::Arc<Vec<StandingRule>>) {
570 let mut entries = self.entries.write().await;
571 if entries.len() >= RULE_CACHE_ENTRIES && !entries.contains_key(&key) {
572 entries.clear();
573 }
574 entries.insert(key, (version, rules));
575 }
576
577 async fn forget(&self, matches: impl Fn(&K) -> bool) {
578 self.entries.write().await.retain(|key, _| !matches(key));
579 }
580}
581
582#[cfg(feature = "postgres")]
584const POSTGRES_RULE_MIGRATIONS: &[(i64, &str, &str)] = &[(
585 1,
586 "create standing rule tables",
587 "CREATE TABLE IF NOT EXISTS adk_harness_rules (\
588 seq BIGINT GENERATED ALWAYS AS IDENTITY, app_name TEXT NOT NULL, id TEXT NOT NULL, \
589 user_id TEXT NOT NULL, session_id TEXT, rule TEXT NOT NULL, \
590 PRIMARY KEY (app_name, id)); \
591 CREATE INDEX IF NOT EXISTS adk_harness_rules_by_user \
592 ON adk_harness_rules (app_name, user_id, seq); \
593 CREATE TABLE IF NOT EXISTS adk_harness_rule_versions (\
594 app_name TEXT PRIMARY KEY, version BIGINT NOT NULL);",
595)];
596
597#[cfg(feature = "postgres")]
627#[derive(Debug, Clone)]
628pub struct PostgresStandingRuleStore {
629 pool: sqlx::PgPool,
630 cache: std::sync::Arc<RuleCache<(String, String)>>,
631}
632
633#[cfg(feature = "postgres")]
634impl PostgresStandingRuleStore {
635 pub fn new(pool: sqlx::PgPool) -> Self {
637 Self { pool, cache: std::sync::Arc::new(RuleCache::new()) }
638 }
639
640 pub async fn connect(database_url: &str) -> Result<Self> {
646 let pool = sqlx::PgPool::connect(database_url).await.map_err(crate::fsutil::db_error)?;
647 Ok(Self::new(pool))
648 }
649
650 pub async fn migrate(&self) -> Result<()> {
657 crate::fsutil::migrate_postgres(
658 &self.pool,
659 "_adk_harness_rule_migrations",
660 POSTGRES_RULE_MIGRATIONS,
661 )
662 .await
663 }
664
665 async fn user_rules(&self, app: &str, user: &str) -> Result<std::sync::Arc<Vec<StandingRule>>> {
667 let version: Option<(i64,)> =
668 sqlx::query_as("SELECT version FROM adk_harness_rule_versions WHERE app_name = $1")
669 .bind(app)
670 .fetch_optional(&self.pool)
671 .await
672 .map_err(crate::fsutil::db_error)?;
673 let version = version.map_or(0, |(version,)| version);
674 let key = (app.to_string(), user.to_string());
675 if let Some(rules) = self.cache.get(&key, version).await {
676 return Ok(rules);
677 }
678 let rows: Vec<(String,)> = sqlx::query_as(
679 "SELECT rule FROM adk_harness_rules WHERE app_name = $1 AND user_id = $2 ORDER BY seq",
680 )
681 .bind(app)
682 .bind(user)
683 .fetch_all(&self.pool)
684 .await
685 .map_err(crate::fsutil::db_error)?;
686 let rules = std::sync::Arc::new(parse_rule_texts(rows.into_iter().map(|(text,)| text)));
687 self.cache.put(key, version, rules.clone()).await;
688 Ok(rules)
689 }
690}
691
692#[cfg(feature = "postgres")]
694const BUMP_RULE_VERSION: &str = "INSERT INTO adk_harness_rule_versions (app_name, version) \
695 VALUES ($1, 1) ON CONFLICT (app_name) \
696 DO UPDATE SET version = adk_harness_rule_versions.version + 1";
697
698#[cfg(feature = "postgres")]
699#[async_trait]
700impl StandingRuleStore for PostgresStandingRuleStore {
701 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
702 Ok(self
703 .user_rules(app, user)
704 .await?
705 .iter()
706 .filter(|rule| applies_to_session(rule, app, user, session))
707 .cloned()
708 .collect())
709 }
710
711 async fn grant(&self, rule: StandingRule) -> Result<StandingRule> {
712 validate(&rule)?;
713 let text = serde_json::to_string(&rule)
714 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
715 let app = rule.scope.app_name().to_string();
716 let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
717 sqlx::query(BUMP_RULE_VERSION)
718 .bind(&app)
719 .execute(&mut *tx)
720 .await
721 .map_err(crate::fsutil::db_error)?;
722 sqlx::query(
723 "INSERT INTO adk_harness_rules (app_name, id, user_id, session_id, rule) \
724 VALUES ($1, $2, $3, $4, $5) ON CONFLICT (app_name, id) DO UPDATE SET \
725 user_id = excluded.user_id, session_id = excluded.session_id, rule = excluded.rule",
726 )
727 .bind(&app)
728 .bind(&rule.id)
729 .bind(rule.scope.user_id())
730 .bind(rule.scope.session_id())
731 .bind(text)
732 .execute(&mut *tx)
733 .await
734 .map_err(crate::fsutil::db_error)?;
735 tx.commit().await.map_err(crate::fsutil::db_error)?;
736 self.cache.forget(|(cached, _)| *cached == app).await;
737 Ok(rule)
738 }
739
740 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
741 let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
742 sqlx::query(BUMP_RULE_VERSION)
743 .bind(app)
744 .execute(&mut *tx)
745 .await
746 .map_err(crate::fsutil::db_error)?;
747 let deleted = sqlx::query("DELETE FROM adk_harness_rules WHERE app_name = $1 AND id = $2")
748 .bind(app)
749 .bind(id)
750 .execute(&mut *tx)
751 .await
752 .map_err(crate::fsutil::db_error)?
753 .rows_affected();
754 if deleted == 0 {
755 tx.rollback().await.map_err(crate::fsutil::db_error)?;
756 return Ok(false);
757 }
758 tx.commit().await.map_err(crate::fsutil::db_error)?;
759 self.cache.forget(|(cached, _)| cached == app).await;
760 Ok(true)
761 }
762
763 async fn replace(&self, rule: StandingRule) -> Result<bool> {
764 validate(&rule)?;
765 let text = serde_json::to_string(&rule)
766 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
767 let app = rule.scope.app_name().to_string();
768 let mut tx = self.pool.begin().await.map_err(crate::fsutil::db_error)?;
769 sqlx::query(BUMP_RULE_VERSION)
770 .bind(&app)
771 .execute(&mut *tx)
772 .await
773 .map_err(crate::fsutil::db_error)?;
774 let updated = sqlx::query(
775 "UPDATE adk_harness_rules SET user_id = $1, session_id = $2, rule = $3 \
776 WHERE app_name = $4 AND id = $5",
777 )
778 .bind(rule.scope.user_id())
779 .bind(rule.scope.session_id())
780 .bind(text)
781 .bind(&app)
782 .bind(&rule.id)
783 .execute(&mut *tx)
784 .await
785 .map_err(crate::fsutil::db_error)?
786 .rows_affected();
787 if updated == 0 {
788 tx.rollback().await.map_err(crate::fsutil::db_error)?;
789 return Ok(false);
790 }
791 tx.commit().await.map_err(crate::fsutil::db_error)?;
792 self.cache.forget(|(cached, _)| *cached == app).await;
793 Ok(true)
794 }
795
796 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
797 Ok(self
798 .user_rules(app, user)
799 .await?
800 .iter()
801 .filter(|rule| rule.scope.app_name() == app && rule.scope.user_id() == user)
802 .cloned()
803 .collect())
804 }
805}
806
807#[cfg(feature = "redis")]
810const GRANT_SCRIPT: &str = r#"
811redis.call('INCR', KEYS[1])
812redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
813if not redis.call('ZSCORE', KEYS[3], ARGV[1]) then
814 redis.call('ZADD', KEYS[3], redis.call('INCR', KEYS[4]), ARGV[1])
815end
816return 1
817"#;
818
819#[cfg(feature = "redis")]
821const REVOKE_SCRIPT: &str = r#"
822if redis.call('HDEL', KEYS[2], ARGV[1]) == 0 then return 0 end
823redis.call('ZREM', KEYS[3], ARGV[1])
824redis.call('INCR', KEYS[1])
825return 1
826"#;
827
828#[cfg(feature = "redis")]
831const REPLACE_SCRIPT: &str = r#"
832if redis.call('HEXISTS', KEYS[2], ARGV[1]) == 0 then return 0 end
833redis.call('HSET', KEYS[2], ARGV[1], ARGV[2])
834redis.call('INCR', KEYS[1])
835return 1
836"#;
837
838#[cfg(feature = "redis")]
841const READ_RULES_SCRIPT: &str = r#"
842local out = { redis.call('GET', KEYS[1]) or '0' }
843for _, id in ipairs(redis.call('ZRANGE', KEYS[3], 0, -1)) do
844 local rule = redis.call('HGET', KEYS[2], id)
845 if rule then table.insert(out, rule) end
846end
847return out
848"#;
849
850#[cfg(feature = "redis")]
883#[derive(Debug, Clone)]
884pub struct RedisStandingRuleStore {
885 client: fred::prelude::Client,
886 namespace: String,
887 cache: std::sync::Arc<RuleCache<String>>,
888}
889
890#[cfg(feature = "redis")]
891impl RedisStandingRuleStore {
892 pub fn from_client(client: fred::prelude::Client) -> Self {
894 Self {
895 client,
896 namespace: crate::fsutil::REDIS_NAMESPACE.to_string(),
897 cache: std::sync::Arc::new(RuleCache::new()),
898 }
899 }
900
901 pub async fn connect(url: &str) -> Result<Self> {
907 Ok(Self::from_client(crate::fsutil::redis_connect(url).await?))
908 }
909
910 #[must_use]
913 pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
914 self.namespace = crate::fsutil::redis_namespace(&namespace.into());
915 self
916 }
917
918 pub async fn migrate(&self) -> Result<()> {
924 use fred::prelude::LuaInterface as _;
925 for script in [GRANT_SCRIPT, REVOKE_SCRIPT, REPLACE_SCRIPT, READ_RULES_SCRIPT] {
926 let _: String = self
927 .client
928 .script_load(script)
929 .await
930 .map_err(|error| crate::fsutil::redis_error("load a script", &error))?;
931 }
932 Ok(())
933 }
934
935 fn keys(&self, app: &str) -> [String; 4] {
937 let prefix = format!("{}:{{{}}}", self.namespace, crate::fsutil::redis_segment(app));
938 [
939 format!("{prefix}:rule-version"),
940 format!("{prefix}:rules"),
941 format!("{prefix}:rule-order"),
942 format!("{prefix}:rule-seq"),
943 ]
944 }
945
946 async fn app_rules(&self, app: &str) -> Result<std::sync::Arc<Vec<StandingRule>>> {
948 use fred::prelude::{KeysInterface as _, LuaInterface as _};
949 let [version_key, rules_key, order_key, _] = self.keys(app);
950 let version: Option<i64> = self
951 .client
952 .get(&version_key)
953 .await
954 .map_err(|error| crate::fsutil::redis_error("read the rule version", &error))?;
955 if let Some(rules) = self.cache.get(&app.to_string(), version.unwrap_or(0)).await {
956 return Ok(rules);
957 }
958 let reply: Vec<String> = self
959 .client
960 .eval(READ_RULES_SCRIPT, vec![version_key, rules_key, order_key], Vec::<String>::new())
961 .await
962 .map_err(|error| crate::fsutil::redis_error("read standing rules", &error))?;
963 let mut reply = reply.into_iter();
964 let version = reply.next().and_then(|version| version.parse::<i64>().ok()).unwrap_or(0);
965 let rules = std::sync::Arc::new(parse_rule_texts(reply));
966 self.cache.put(app.to_string(), version, rules.clone()).await;
967 Ok(rules)
968 }
969}
970
971#[cfg(feature = "redis")]
972#[async_trait]
973impl StandingRuleStore for RedisStandingRuleStore {
974 async fn rules_for(&self, app: &str, user: &str, session: &str) -> Result<Vec<StandingRule>> {
975 Ok(self
976 .app_rules(app)
977 .await?
978 .iter()
979 .filter(|rule| applies_to_session(rule, app, user, session))
980 .cloned()
981 .collect())
982 }
983
984 async fn grant(&self, rule: StandingRule) -> Result<StandingRule> {
985 use fred::prelude::LuaInterface as _;
986 validate(&rule)?;
987 let text = serde_json::to_string(&rule)
988 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
989 let app = rule.scope.app_name();
990 let _: i64 = self
991 .client
992 .eval(GRANT_SCRIPT, self.keys(app).to_vec(), vec![rule.id.clone(), text])
993 .await
994 .map_err(|error| crate::fsutil::redis_error("grant a standing rule", &error))?;
995 self.cache.forget(|cached| cached == app).await;
996 Ok(rule)
997 }
998
999 async fn revoke(&self, app: &str, id: &str) -> Result<bool> {
1000 use fred::prelude::LuaInterface as _;
1001 let [version_key, rules_key, order_key, _] = self.keys(app);
1002 let removed: i64 = self
1003 .client
1004 .eval(REVOKE_SCRIPT, vec![version_key, rules_key, order_key], vec![id.to_string()])
1005 .await
1006 .map_err(|error| crate::fsutil::redis_error("revoke a standing rule", &error))?;
1007 self.cache.forget(|cached| cached == app).await;
1008 Ok(removed == 1)
1009 }
1010
1011 async fn replace(&self, rule: StandingRule) -> Result<bool> {
1012 use fred::prelude::LuaInterface as _;
1013 validate(&rule)?;
1014 let text = serde_json::to_string(&rule)
1015 .map_err(|error| crate::fsutil::serialize_error("standing rule", &error))?;
1016 let app = rule.scope.app_name();
1017 let [version_key, rules_key, _, _] = self.keys(app);
1018 let replaced: i64 = self
1019 .client
1020 .eval(REPLACE_SCRIPT, vec![version_key, rules_key], vec![rule.id.clone(), text])
1021 .await
1022 .map_err(|error| crate::fsutil::redis_error("replace a standing rule", &error))?;
1023 self.cache.forget(|cached| cached == app).await;
1024 Ok(replaced == 1)
1025 }
1026
1027 async fn list(&self, app: &str, user: &str) -> Result<Vec<StandingRule>> {
1028 Ok(self
1029 .app_rules(app)
1030 .await?
1031 .iter()
1032 .filter(|rule| rule.scope.app_name() == app && rule.scope.user_id() == user)
1033 .cloned()
1034 .collect())
1035 }
1036}