1use rusqlite::params;
18use serde::{Deserialize, Serialize};
19
20use super::store::Store;
21use super::StoreError;
22
23pub(crate) const SCHEMA: &str = "
26 CREATE TABLE IF NOT EXISTS db_google_grants (
27 agent_id TEXT NOT NULL,
28 account_id TEXT NOT NULL,
29 service TEXT NOT NULL,
30 level TEXT NOT NULL,
31 updated_at INTEGER NOT NULL DEFAULT 0,
32 PRIMARY KEY (agent_id, account_id, service)
33 );
34 CREATE TABLE IF NOT EXISTS db_google_calls (
35 id INTEGER PRIMARY KEY AUTOINCREMENT,
36 account_id TEXT NOT NULL,
37 at INTEGER NOT NULL,
38 agent_id TEXT NOT NULL DEFAULT '',
39 agent_name TEXT NOT NULL DEFAULT '',
40 service TEXT NOT NULL,
41 action TEXT NOT NULL,
42 ids TEXT NOT NULL DEFAULT '',
43 outcome TEXT NOT NULL DEFAULT ''
44 );
45 CREATE INDEX IF NOT EXISTS idx_google_calls_account ON db_google_calls(account_id, at);";
46
47pub const CALLS_RETENTION_MS: i64 = 30 * 24 * 60 * 60 * 1000;
49
50pub const SERVICES: [&str; 3] = ["calendar", "drive", "gmail"];
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
55#[serde(rename_all = "lowercase")]
56pub enum GrantLevel {
57 Read,
58 Write,
60}
61
62impl GrantLevel {
63 pub fn as_str(self) -> &'static str {
64 match self {
65 GrantLevel::Read => "read",
66 GrantLevel::Write => "write",
67 }
68 }
69
70 pub fn parse(s: &str) -> Result<Option<GrantLevel>, String> {
72 match s.trim() {
73 "read" => Ok(Some(GrantLevel::Read)),
74 "write" => Ok(Some(GrantLevel::Write)),
75 "off" | "" => Ok(None),
76 other => Err(format!("level \"{other}\": read, write or off")),
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct GoogleGrant {
84 pub agent_id: String,
85 pub account_id: String,
86 pub service: String,
87 pub level: GrantLevel,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum CallsCounted {
93 All,
94 Ok,
96 Asked,
98}
99
100#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102pub struct GoogleCall {
103 pub at: i64,
104 pub agent_id: String,
105 pub agent_name: String,
106 pub service: String,
107 pub action: String,
108 pub ids: String,
110 pub outcome: String,
112}
113
114fn check_service(service: &str) -> Result<(), StoreError> {
115 if SERVICES.contains(&service) {
116 Ok(())
117 } else {
118 Err(StoreError::Other(format!("no Google service \"{service}\"")))
119 }
120}
121
122fn row_to_grant(r: &rusqlite::Row) -> rusqlite::Result<GoogleGrant> {
123 let level: String = r.get(3)?;
124 Ok(GoogleGrant {
125 agent_id: r.get(0)?,
126 account_id: r.get(1)?,
127 service: r.get(2)?,
128 level: if level == "write" { GrantLevel::Write } else { GrantLevel::Read },
129 })
130}
131
132impl Store {
133 pub fn google_grant_set(
135 &self,
136 agent_id: &str,
137 account_id: &str,
138 service: &str,
139 level: Option<GrantLevel>,
140 now_ms: i64,
141 ) -> Result<(), StoreError> {
142 check_service(service)?;
143 let conn = self.conn().lock().unwrap();
144 match level {
145 Some(l) => conn.execute(
146 "INSERT INTO db_google_grants (agent_id, account_id, service, level, updated_at)
147 VALUES (?1, ?2, ?3, ?4, ?5)
148 ON CONFLICT(agent_id, account_id, service) DO UPDATE SET level = excluded.level, updated_at = excluded.updated_at",
149 params![agent_id, account_id, service, l.as_str(), now_ms],
150 )?,
151 None => conn.execute(
152 "DELETE FROM db_google_grants WHERE agent_id = ?1 AND account_id = ?2 AND service = ?3",
153 params![agent_id, account_id, service],
154 )?,
155 };
156 Ok(())
157 }
158
159 pub fn google_grant_get(&self, agent_id: &str, account_id: &str, service: &str) -> Result<Option<GrantLevel>, StoreError> {
161 Ok(self
162 .google_grants_for_agent(agent_id)?
163 .into_iter()
164 .find(|g| g.account_id == account_id && g.service == service)
165 .map(|g| g.level))
166 }
167
168 pub fn google_grants_for_agent(&self, agent_id: &str) -> Result<Vec<GoogleGrant>, StoreError> {
170 let conn = self.conn().lock().unwrap();
171 let mut stmt = conn.prepare(
172 "SELECT agent_id, account_id, service, level FROM db_google_grants WHERE agent_id = ?1 ORDER BY account_id, service",
173 )?;
174 let rows = stmt.query_map(params![agent_id], row_to_grant)?;
175 rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
176 }
177
178 pub fn google_grants_for_account(&self, account_id: &str) -> Result<Vec<GoogleGrant>, StoreError> {
180 let conn = self.conn().lock().unwrap();
181 let mut stmt = conn.prepare(
182 "SELECT agent_id, account_id, service, level FROM db_google_grants WHERE account_id = ?1 ORDER BY agent_id, service",
183 )?;
184 let rows = stmt.query_map(params![account_id], row_to_grant)?;
185 rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
186 }
187
188 pub fn google_account_forget(&self, account_id: &str) -> Result<(), StoreError> {
190 let conn = self.conn().lock().unwrap();
191 conn.execute("DELETE FROM db_google_grants WHERE account_id = ?1", params![account_id])?;
192 conn.execute("DELETE FROM db_google_calls WHERE account_id = ?1", params![account_id])?;
193 Ok(())
194 }
195
196 pub fn google_call_log(&self, account_id: &str, call: &GoogleCall) -> Result<(), StoreError> {
199 let conn = self.conn().lock().unwrap();
200 conn.execute(
201 "INSERT INTO db_google_calls (account_id, at, agent_id, agent_name, service, action, ids, outcome)
202 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
203 params![account_id, call.at, call.agent_id, call.agent_name, call.service, call.action, call.ids, call.outcome],
204 )?;
205 conn.execute("DELETE FROM db_google_calls WHERE at < ?1", params![call.at - CALLS_RETENTION_MS])?;
206 Ok(())
207 }
208
209 pub fn google_calls_count(
213 &self,
214 account_id: &str,
215 agent_id: &str,
216 service: &str,
217 actions: &[&str],
218 since_ms: i64,
219 which: CallsCounted,
220 ) -> Result<usize, StoreError> {
221 let conn = self.conn().lock().unwrap();
222 let marks = vec!["?"; actions.len()].join(",");
223 let sql = format!(
224 "SELECT COUNT(*) FROM db_google_calls WHERE account_id = ? AND agent_id = ? AND service = ? AND at > ?
225 AND action IN ({marks}){}",
226 match which {
227 CallsCounted::All => "",
228 CallsCounted::Ok => " AND outcome = 'ok'",
229 CallsCounted::Asked => " AND (outcome = 'ok' OR outcome LIKE 'error: the person %')",
232 }
233 );
234 let mut args: Vec<rusqlite::types::Value> = vec![account_id.to_string().into(), agent_id.to_string().into(), service.to_string().into(), since_ms.into()];
235 args.extend(actions.iter().map(|a| rusqlite::types::Value::from(a.to_string())));
236 let n: i64 = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0))?;
237 Ok(n.max(0) as usize)
238 }
239
240 pub fn google_calls(&self, account_id: &str, limit: usize) -> Result<Vec<GoogleCall>, StoreError> {
242 let conn = self.conn().lock().unwrap();
243 let mut stmt = conn.prepare(
244 "SELECT at, agent_id, agent_name, service, action, ids, outcome FROM db_google_calls
245 WHERE account_id = ?1 ORDER BY at DESC, id DESC LIMIT ?2",
246 )?;
247 let rows = stmt.query_map(params![account_id, limit as i64], |r| {
248 Ok(GoogleCall {
249 at: r.get(0)?,
250 agent_id: r.get(1)?,
251 agent_name: r.get(2)?,
252 service: r.get(3)?,
253 action: r.get(4)?,
254 ids: r.get(5)?,
255 outcome: r.get(6)?,
256 })
257 })?;
258 rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
259 }
260}
261
262#[cfg(test)]
263#[path = "google_grants_tests.rs"]
264mod tests;