1use std::sync::Arc;
18use std::time::Duration;
19
20use agentmux_common::time::now_ms;
21use chrono::NaiveDate;
22
23use super::{kinds, record, PERSON};
24use crate::backend::mps::Broker;
25use crate::backend::storage::store::Store;
26use crate::backend::storage::vault::VaultRow;
27use crate::backend::storage::work_board::{requested, NewCard, WorkEvent};
28use crate::backend::storage::work_queue::{work_state, WorkItem};
29
30pub const FIELD: &str = "expires";
32pub const ACTOR: &str = "Vault";
34pub const REMINDED: &str = "reminded";
35pub const TASK_KIND: &str = "vault-rotation";
37const TASK_MARK: &str = "; rotation task #";
39const EVERY: Duration = Duration::from_secs(6 * 60 * 60);
41const MADE: &[&str] = &crate::backend::storage::vault::VALUE_SETTING;
44
45pub fn parse(text: &str) -> Result<NaiveDate, String> {
47 let text = text.trim();
48 if text.len() != 10 {
49 return Err(format!("expires is a date as YYYY-MM-DD, not {:?}", clip(text)));
50 }
51 NaiveDate::parse_from_str(text, "%Y-%m-%d").map_err(|_| format!("expires is a date as YYYY-MM-DD, not {:?}", clip(text)))
52}
53
54pub fn normalize(text: &str) -> Option<String> {
57 let text = text.trim();
58 if let Ok(d) = parse(text) {
59 return Some(d.to_string());
60 }
61 let (y, m) = match text.split_once('/') {
62 Some((m, y)) => (y.trim(), m.trim()),
63 None => text.split_once('-')?,
64 };
65 let (y, m): (i32, u32) = (y.parse().ok().filter(|_| y.len() == 4)?, m.parse().ok()?);
66 let first_of_next = if m == 12 { NaiveDate::from_ymd_opt(y + 1, 1, 1) } else { NaiveDate::from_ymd_opt(y, m + 1, 1) };
67 first_of_next.filter(|_| (1..=12).contains(&m)).and_then(|d| d.pred_opt()).map(|d| d.to_string())
68}
69
70pub fn settle_imported(kind: &kinds::Kind, fields: &mut std::collections::BTreeMap<String, String>) {
74 let Some(text) = fields.remove(FIELD) else { return };
75 match normalize(&text) {
76 Some(date) => {
77 fields.insert(FIELD.to_string(), date);
78 }
79 None if kind.fields.contains(&"notes") => {
80 let line = format!("Expires: {text}");
81 let notes = fields.remove("notes").filter(|n| !n.is_empty()).map(|n| format!("{n}\n{line}")).unwrap_or(line);
82 fields.insert("notes".to_string(), notes);
83 }
84 None => {}
85 }
86}
87
88fn clip(text: &str) -> String {
89 text.chars().take(40).collect()
90}
91
92pub fn today() -> NaiveDate {
93 chrono::Local::now().date_naive()
94}
95
96pub fn of(row: &VaultRow) -> Option<NaiveDate> {
98 if !kinds::kind(&row.kind).is_some_and(|k| k.fields.contains(&FIELD)) {
99 return None;
100 }
101 let fields: std::collections::BTreeMap<String, String> = serde_json::from_str(&row.fields).ok()?;
102 parse(fields.get(FIELD)?).ok()
103}
104
105pub fn expired(row: &VaultRow, today: NaiveDate) -> bool {
107 of(row).is_some_and(|d| d < today)
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum Stage {
113 TwoWeeks,
114 ThreeDays,
115 OnTheDay,
116}
117
118impl Stage {
119 pub fn due(days_left: i64) -> Option<Stage> {
122 match days_left {
123 d if d <= 0 => Some(Stage::OnTheDay),
124 1..=3 => Some(Stage::ThreeDays),
125 4..=14 => Some(Stage::TwoWeeks),
126 _ => None,
127 }
128 }
129
130 fn words(self) -> &'static str {
131 match self {
132 Stage::TwoWeeks => "14 days before",
133 Stage::ThreeDays => "3 days before",
134 Stage::OnTheDay => "on the day",
135 }
136 }
137}
138
139pub fn reminder_key(date: NaiveDate, stage: Stage) -> String {
142 format!("expires {date}, {}", stage.words())
143}
144
145pub fn notice(date: NaiveDate, days_left: i64) -> String {
147 match days_left {
148 d if d < 0 => format!("Expired on {date}. It still works where it is used, until it's replaced."),
149 0 => format!("Expires today, {date}."),
150 1 => format!("Expires tomorrow, {date}."),
151 d => format!("Expires in {d} days, on {date}."),
152 }
153}
154
155#[derive(Debug, Clone, PartialEq)]
157pub struct Due {
158 pub id: String,
159 pub label: String,
160 pub date: NaiveDate,
161 pub days_left: i64,
162 pub stage: Stage,
163 pub first: bool,
166 pub agent: Option<String>,
168 pub rotates: bool,
170}
171
172pub fn due(store: &Store, today: NaiveDate) -> Result<Vec<Due>, String> {
174 let mut out = Vec::new();
175 for row in store.vault_list().map_err(|e| e.to_string())? {
176 let Some(date) = of(&row) else { continue };
177 let days_left = (date - today).num_days();
178 let Some(stage) = Stage::due(days_left) else { continue };
179 let reminded = store.vault_activity_for_entry(&row.id, &[REMINDED], row.created_at, 10_000).map_err(|e| e.to_string())?;
182 let sent_for_date = format!("expires {date}, ");
183 let sent: Vec<&str> = reminded.iter().filter(|l| l.target.starts_with(&sent_for_date)).map(|l| l.target.as_str()).collect();
184 if sent.iter().any(|t| t.starts_with(&reminder_key(date, stage))) {
185 continue;
186 }
187 let made = store.vault_activity_for_entry(&row.id, MADE, row.created_at, 1).map_err(|e| e.to_string())?;
189 let agent = made.into_iter().next().map(|l| super::history::agent_of(&l.actor).to_string()).filter(|a| a != PERSON && !a.is_empty());
190 let rotates = row.kind != super::card::KIND;
191 out.push(Due { id: row.id, label: row.label, date, days_left, stage, first: !sent.iter().any(|t| t.contains(TASK_MARK)), agent, rotates });
192 }
193 Ok(out)
194}
195
196pub fn task_title(d: &Due) -> String {
197 format!("Rotate {}: it expires on {}", d.label, d.date)
198}
199
200pub fn task_body(d: &Due) -> String {
201 format!(
202 "The Vault entry `{}` ({}) expires on {}.\n\n\
203 Make a new value where it is issued, put it where the old one is used, and save it in the entry, \
204 without seeing it: `Vault` `generate` makes one the Vault keeps, and `Terminal` `run` with `secrets`, \
205 `stdin_secret` or `secret_files` hands it to a command. Then set the entry's new expiry date.\n\n\
206 The old value keeps working until it expires, so nothing breaks before then.",
207 d.id, d.label, d.date
208 )
209}
210
211pub fn file_task(work: &Store, d: &Due, now: i64) -> Result<i64, String> {
213 let item = WorkItem {
214 id: uuid::Uuid::new_v4().to_string(),
215 title: task_title(d),
216 payload: task_body(d),
217 kind: TASK_KIND.to_string(),
218 target_agent: d.agent.clone().unwrap_or_default(),
219 target_group: String::new(),
220 priority: 0,
221 state: String::new(),
222 claimed_by: String::new(),
223 target_agent_uid: String::new(),
224 claimed_by_uid: String::new(),
225 claim_expires: None,
226 attempts: 0,
227 max_attempts: 3,
228 created_by: ACTOR.to_string(),
229 created_by_uid: String::new(),
230 created_at: now,
231 updated_at: now,
232 not_before: None,
233 result: String::new(),
234 };
235 work.work_queue_enqueue(&item).map_err(|e| e.to_string())?;
236 let card = NewCard {
237 review_required: false,
238 requested_by: ACTOR.to_string(),
239 requested_by_kind: requested::OTHER.to_string(),
240 filed_by: ACTOR.to_string(),
241 ..Default::default()
242 };
243 let num = work.work_card_create(&item.id, &card, now).map_err(|e| e.to_string())?;
244 let event = WorkEvent {
245 work_id: item.id.clone(),
246 at: now,
247 actor: ACTOR.to_string(),
248 actor_kind: "system".to_string(),
249 kind: "created".to_string(),
250 to_state: work_state::OPEN.to_string(),
251 ..Default::default()
252 };
253 work.work_event_add(&event).map_err(|e| e.to_string())?;
254 Ok(num)
255}
256
257pub struct Sent {
259 pub notices: Vec<(Due, String)>,
260 pub filed: bool,
261}
262
263pub fn send(store: &Store, work: Option<&Store>, today: NaiveDate) -> Result<Sent, String> {
267 let mut sent = Sent { notices: Vec::new(), filed: false };
268 for d in due(store, today)? {
269 let mut target = reminder_key(d.date, d.stage);
270 if d.first && d.rotates {
271 if let Some(work) = work {
272 match file_task(work, &d, now_ms()) {
273 Ok(num) => {
274 sent.filed = true;
275 let whom = d.agent.as_deref().map(|a| format!(" for {a}")).unwrap_or_default();
276 target.push_str(&format!("{TASK_MARK}{num}{whom}"));
277 }
278 Err(e) => tracing::warn!(entry = %d.id, error = %e, "vault: couldn't file a rotation task"),
279 }
280 }
281 }
282 record(store, &d.id, &d.label, ACTOR, REMINDED, &target, "done");
283 let text = notice(d.date, d.days_left);
284 sent.notices.push((d, text));
285 }
286 Ok(sent)
287}
288
289pub fn notify_key(id: &str) -> String {
291 format!("vault:{id}")
292}
293
294pub const MAX_TOASTS: usize = 3;
296
297#[derive(Debug, PartialEq)]
299pub struct Toast {
300 pub key: String,
301 pub name: String,
302 pub body: String,
303}
304
305pub fn toasts(notices: &[(Due, String)]) -> Vec<Toast> {
308 if notices.len() <= MAX_TOASTS {
309 return notices.iter().map(|(d, text)| Toast { key: notify_key(&d.id), name: d.label.clone(), body: text.clone() }).collect();
310 }
311 let named: Vec<&str> = notices.iter().take(MAX_TOASTS).map(|(d, _)| d.label.as_str()).collect();
312 let body = format!(
313 "{}, and {} more expire within 14 days, or have expired. The Vault's Expiring soon filter lists them.",
314 named.join(", "),
315 notices.len() - named.len()
316 );
317 vec![Toast { key: "vault:expiring".into(), name: format!("{} entries", notices.len()), body }]
318}
319
320pub async fn run(store: Arc<Store>, work: Arc<Store>, broker: Arc<Broker>) {
324 loop {
325 match crate::backend::notify::router::get(&broker) {
326 Some(router) if !router.holds_back_attention() => {}
327 _ => {
328 tokio::time::sleep(Duration::from_secs(15 * 60)).await;
329 continue;
330 }
331 }
332 let (s, w) = (store.clone(), work.clone());
333 match tokio::task::spawn_blocking(move || send(&s, Some(&w), today())).await {
334 Ok(Ok(sent)) => {
335 if sent.filed {
336 broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
337 }
338 if !sent.notices.is_empty() {
339 let event = crate::backend::mps_events::VaultEvent {
341 requests: super::requests::requests().list(),
342 uses: super::uses::uses().list(),
343 changed_ms: agentmux_common::time::now_ms_u64(),
344 };
345 broker.publish_event::<crate::backend::mps_events::Vault>(&event, vec![], 0);
346 }
347 for (d, _) in &sent.notices {
348 tracing::info!(entry = %d.id, date = %d.date, "vault: expiry reminder");
349 }
350 if let Some(router) = crate::backend::notify::router::get(&broker) {
351 for t in toasts(&sent.notices) {
352 let router = router.clone();
353 let _ = tokio::task::spawn_blocking(move || router.vault_expiring(&t.key, &t.name, t.body)).await;
354 }
355 }
356 }
357 Ok(Err(e)) => tracing::warn!(error = %e, "vault: couldn't check expiry dates"),
358 Err(e) => tracing::warn!(error = %e, "vault: the expiry check stopped"),
359 }
360 tokio::time::sleep(EVERY).await;
361 }
362}
363
364#[cfg(test)]
365#[path = "expiry_tests.rs"]
366mod tests;