Skip to main content

universal_exports/
timeline.rs

1//! The Operation activity timeline: one authorized, redacted, cursor-paginated view of what
2//! changed across an Operation.
3//!
4//! Items come from two durable sources in the shared Registry: the activity events
5//! (`ai6::TimelineEvent`: lifecycle transitions, control outcomes, Cables sent, Sleeper
6//! authorizations) and the audit records (Mission requests and controls, proposal
7//! decisions, Agent role, quarantine and Station settings changes). Live terminal frames
8//! are never part of it.
9
10use ai6::TimelineDetailKey;
11use std::collections::{BTreeMap, BTreeSet};
12use std::time::Duration;
13
14use ai6::{AuditRecord, AuthorizationRequest, Authorizer, TimelineDetail, TimelineEvent};
15use ai6_diptel::{MissionId, OperationId};
16use axum::Json;
17use axum::extract::{Path, Query, State};
18use axum::http::HeaderMap;
19use serde::{Deserialize, Serialize};
20
21use crate::controls::ControlStatus;
22use crate::{ApiError, Gateway, authorize_operation_action, bearer, resolve_user, unix_timestamp};
23
24/// Audit actions whose target is a Mission ID.
25const MISSION_AUDITS: [&str; 6] = [
26    "mission.create.requested",
27    "mission.cancel",
28    "mission.retry",
29    "mission.resume",
30    "mission.rename",
31    "run.interrupt",
32];
33
34/// One entry of an Operation's activity timeline: metadata only.
35#[non_exhaustive]
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct TimelineItem {
38    /// Stable identity: `event:<id>` for an activity event, `audit:<id>` for an audit record.
39    pub id: String,
40    /// When it happened, as Unix seconds.
41    pub at: f64,
42    /// `lifecycle`, `control`, `cable`, `sleeper` or `audit`.
43    pub kind: String,
44    /// What happened: a Mission state, `<action>.<outcome>`, `sent`, `authorized`,
45    /// `revoked`, or the audit action.
46    pub action: String,
47    /// The Operation whose timeline this is.
48    pub operation_id: String,
49    /// The Station involved, when known.
50    pub station_id: Option<String>,
51    /// The Mission involved, when there is one: its UID.
52    pub mission_id: Option<String>,
53    /// What that Mission is called now.
54    pub handle: Option<String>,
55    /// The Run involved, when there is one.
56    pub run_id: Option<String>,
57    /// Who acted: a person ID or an Agent codename.
58    pub actor: Option<String>,
59    /// An audit record's target: a Mission, proposal, role, Agent or setting name.
60    pub target: Option<String>,
61    /// Further safe identifiers and names.
62    pub detail: TimelineDetail,
63}
64
65/// One page of a timeline, newest first.
66#[non_exhaustive]
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub struct TimelinePage {
69    /// The Operation.
70    pub operation_id: String,
71    /// At most the requested number of items, newest first.
72    pub items: Vec<TimelineItem>,
73    /// Pass back as `cursor` for the next, older page; absent on the last page.
74    pub next_cursor: Option<String>,
75}
76
77#[derive(Deserialize)]
78#[serde(deny_unknown_fields)]
79pub(crate) struct TimelineQuery {
80    cursor: Option<String>,
81    mission: Option<String>,
82    limit: Option<usize>,
83}
84
85/// Text from a record as the timeline shows it: no control characters, bounded.
86fn clean(value: &str, chars: usize) -> String {
87    value
88        .chars()
89        .filter(|character| !character.is_control())
90        .take(chars)
91        .collect()
92}
93
94fn clean_option(value: Option<&str>, chars: usize) -> Option<String> {
95    value
96        .map(|value| clean(value, chars))
97        .filter(|value| !value.is_empty())
98}
99
100fn from_event(event: TimelineEvent, chars: usize) -> TimelineItem {
101    TimelineItem {
102        id: format!("event:{}", event.id),
103        at: event.at,
104        kind: clean(&event.kind, chars),
105        action: clean(&event.action, chars),
106        operation_id: clean(&event.operation, chars),
107        station_id: clean_option(event.station.as_deref(), chars),
108        mission_id: clean_option(event.mission.as_deref(), chars),
109        handle: None,
110        run_id: clean_option(event.run.as_deref(), chars),
111        actor: clean_option(event.actor.as_deref(), chars),
112        target: None,
113        detail: event
114            .detail
115            .iter()
116            .map(|(key, value)| {
117                (
118                    TimelineDetailKey::from_name(clean(key.as_str(), chars)),
119                    clean(value, chars),
120                )
121            })
122            .collect(),
123    }
124}
125
126fn from_audit(record: &AuditRecord, operation: &str, chars: usize) -> TimelineItem {
127    TimelineItem {
128        id: format!("audit:{}", record.id),
129        at: record.at,
130        kind: "audit".to_owned(),
131        action: clean(&record.action, chars),
132        operation_id: operation.to_owned(),
133        station_id: clean_option(
134            record
135                .resource
136                .as_deref()
137                .and_then(|resource| resource.strip_prefix("station:")),
138            chars,
139        ),
140        mission_id: MISSION_AUDITS
141            .contains(&record.action.as_str())
142            .then(|| clean(&record.target, chars)),
143        handle: None,
144        run_id: None,
145        actor: clean_option(Some(&record.actor), chars),
146        target: clean_option(Some(&record.target), chars),
147        detail: TimelineDetail::default(),
148    }
149}
150
151/// An opaque position: the item's time bits and identity.
152fn cursor_of(item: &TimelineItem) -> String {
153    format!("{:016x}.{}", item.at.to_bits(), item.id)
154}
155
156fn parse_cursor(cursor: &str) -> Option<(f64, String)> {
157    let (bits, id) = cursor.split_once('.')?;
158    if bits.len() != 16 || id.is_empty() || id.len() > 300 {
159        return None;
160    }
161    let at = f64::from_bits(u64::from_str_radix(bits, 16).ok()?);
162    at.is_finite().then(|| (at, id.to_owned()))
163}
164
165/// Newest first; ties broken by identity so the order never changes between pages.
166fn newer_first(left: &TimelineItem, right: &TimelineItem) -> std::cmp::Ordering {
167    right
168        .at
169        .total_cmp(&left.at)
170        .then_with(|| right.id.cmp(&left.id))
171}
172
173pub(crate) async fn operation_timeline(
174    State(gateway): State<Gateway>,
175    headers: HeaderMap,
176    Path(operation_id): Path<String>,
177    Query(query): Query<TimelineQuery>,
178) -> Result<Json<TimelinePage>, ApiError> {
179    let person = resolve_user(&gateway, bearer(&headers)?).await?;
180    let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
181    let table = &gateway.config.unex().timeline;
182    let limit = query
183        .limit
184        .unwrap_or_else(|| usize::try_from(table.page).unwrap_or(usize::MAX));
185    if limit == 0 || !table.max_page.allows(limit) {
186        return Err(ApiError::bad_request());
187    }
188    let mission = query
189        .mission
190        .map(MissionId::new)
191        .transpose()
192        .map_err(|_| ApiError::bad_request())?;
193    let mission = match mission {
194        Some(mission) => Some(crate::mission_key(&gateway, mission.as_str()).await?),
195        None => None,
196    };
197    let cursor = query
198        .cursor
199        .as_deref()
200        .map(|cursor| parse_cursor(cursor).ok_or_else(ApiError::bad_request))
201        .transpose()?;
202    authorize_operation_action(&gateway, person.clone(), &operation, "audit.read").await?;
203    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
204    let authorizer = gateway.authorizer()?;
205    let operation = operation.to_string();
206    let chars = table.text_chars.or_max();
207    let page = tokio::task::spawn_blocking(move || {
208        let mut items = registry
209            .timeline_events(&operation)
210            .map_err(|_| ApiError::internal())?
211            .into_iter()
212            .map(|event| from_event(event, chars))
213            .collect::<Vec<_>>();
214        let hosts = registry
215            .stations(Duration::MAX)
216            .map_err(|_| ApiError::internal())?
217            .into_iter()
218            .filter(|station| station.check_in().common.operations.contains(&operation))
219            .map(|station| format!("station:{}", station.station()))
220            .collect::<BTreeSet<_>>();
221        let mut station_access = BTreeMap::new();
222        for record in registry.audit_records().map_err(|_| ApiError::internal())? {
223            let visible = if record.operation == operation {
224                true
225            } else if let Some(resource) = record.resource.as_ref()
226                && record.operation.is_empty()
227                && hosts.contains(resource)
228            {
229                // A Station's own records are shown only to who may read that Station's.
230                match station_access.get(resource) {
231                    Some(allowed) => *allowed,
232                    None => {
233                        let allowed = authorizer
234                            .authorize(AuthorizationRequest {
235                                person: person.clone(),
236                                action: "audit.read".to_owned(),
237                                resource: resource.clone(),
238                                ancestors: Vec::new(),
239                            })
240                            .map_err(|_| ApiError::internal())?
241                            .allowed;
242                        station_access.insert(resource.clone(), allowed);
243                        allowed
244                    }
245                }
246            } else {
247                false
248            };
249            if visible {
250                items.push(from_audit(&record, &operation, chars));
251            }
252        }
253        if let Some(mission) = &mission {
254            items.retain(|item| item.mission_id.as_ref() == Some(mission));
255        }
256        items.sort_by(newer_first);
257        if let Some((at, id)) = &cursor {
258            items.retain(|item| {
259                item.at
260                    .total_cmp(at)
261                    .then_with(|| item.id.as_str().cmp(id.as_str()))
262                    .is_lt()
263            });
264        }
265        let next_cursor = (items.len() > limit).then(|| cursor_of(&items[limit - 1]));
266        items.truncate(limit);
267        let mut handles = BTreeMap::new();
268        for item in &mut items {
269            if let Some(mission) = &item.mission_id {
270                item.handle = handles
271                    .entry(mission.clone())
272                    .or_insert_with(|| {
273                        registry
274                            .resolve_mission(mission)
275                            .ok()
276                            .flatten()
277                            .map(|found| found.handle)
278                    })
279                    .clone();
280            }
281        }
282        Ok::<_, ApiError>(TimelinePage {
283            operation_id: operation,
284            items,
285            next_cursor,
286        })
287    })
288    .await
289    .map_err(|_| ApiError::internal())??;
290    Ok(Json(page))
291}
292
293/// Records a control's outcome in its Operation's timeline; the control stands either way.
294pub(crate) async fn record_control(gateway: &Gateway, status: &ControlStatus) {
295    let Some(registry) = gateway.registry.clone() else {
296        return;
297    };
298    let Ok(at) = unix_timestamp() else {
299        return;
300    };
301    let mut event = TimelineEvent::new(
302        "control",
303        format!("{}.{}", status.action, status.status),
304        status.operation_id.clone(),
305        status.finished_at.unwrap_or(at),
306    )
307    .station(status.station_id.clone())
308    .mission(status.mission_id.clone())
309    .actor(status.requested_by.clone())
310    .detail(TimelineDetailKey::Control, status.control_id.clone());
311    if let Some(run) = &status.run_id {
312        event = event.run(run.clone());
313    }
314    if let Some(agent) = &status.agent {
315        event = event.detail(TimelineDetailKey::Agent, agent.clone());
316    }
317    if let Some(state) = &status.state {
318        event = event.detail(TimelineDetailKey::State, state.clone());
319    }
320    if let Some(reason) = &status.reason {
321        event = event.detail(
322            TimelineDetailKey::Reason,
323            clean(reason, gateway.config.unex().timeline.text_chars.or_max()),
324        );
325    }
326    let _ = tokio::task::spawn_blocking(move || registry.record_event(&event)).await;
327}
328
329/// A Run's lifecycle transition as the gateway saw it.
330pub(crate) struct Transition {
331    pub(crate) operation: String,
332    pub(crate) mission: String,
333    pub(crate) run: String,
334    pub(crate) state: String,
335    pub(crate) station: Option<String>,
336    pub(crate) at: f64,
337}
338
339/// Records a lifecycle transition; publication stands either way.
340pub(crate) async fn record_transition(gateway: &Gateway, transition: Transition) {
341    let Some(registry) = gateway.registry.clone() else {
342        return;
343    };
344    let mut event = TimelineEvent::new(
345        "lifecycle",
346        transition.state,
347        transition.operation,
348        transition.at,
349    )
350    .mission(transition.mission)
351    .run(transition.run);
352    if let Some(station) = transition.station {
353        event = event.station(station);
354    }
355    let _ = tokio::task::spawn_blocking(move || registry.record_event(&event)).await;
356}
357
358#[cfg(test)]
359mod tests {
360    use ai6::directorates::registry::backend::*;
361    use ai6::{AuditRecord, TimelineEvent};
362    use axum::http::StatusCode;
363
364    use crate::controls::tests::{STATION_TOKEN, Served, ask, report, served, take};
365
366    async fn timeline(served: &Served, token: &str, query: &str) -> reqwest::Response {
367        reqwest::Client::new()
368            .get(format!(
369                "{}/v1/user/operations/G/timeline{query}",
370                served.base
371            ))
372            .bearer_auth(token)
373            .send()
374            .await
375            .unwrap()
376    }
377
378    async fn page(served: &Served, token: &str, query: &str) -> serde_json::Value {
379        let response = timeline(served, token, query).await;
380        assert_eq!(response.status(), StatusCode::OK);
381        response.json().await.unwrap()
382    }
383
384    async fn publish(served: &Served, path: &str, body: Vec<u8>, json: bool) {
385        let mut request = reqwest::Client::new()
386            .post(format!("{}/v1/station/runs/run-g/{path}", served.base))
387            .bearer_auth(STATION_TOKEN)
388            .body(body);
389        if json {
390            request = request.header("content-type", "application/json");
391        }
392        assert_eq!(request.send().await.unwrap().status(), StatusCode::ACCEPTED);
393    }
394
395    fn lifecycle(state: &str) -> Vec<u8> {
396        serde_json::json!({"operation_id": "G", "mission_id": "mission-g", "state": state})
397            .to_string()
398            .into_bytes()
399    }
400
401    fn ids(page: &serde_json::Value) -> Vec<String> {
402        page["items"]
403            .as_array()
404            .unwrap()
405            .iter()
406            .map(|item| item["id"].as_str().unwrap().to_owned())
407            .collect()
408    }
409
410    #[tokio::test]
411    async fn the_timeline_correlates_lifecycle_controls_and_audit_without_content() {
412        let served = served().await;
413        publish(&served, "lifecycle/1", lifecycle("working"), true).await;
414        publish(&served, "lifecycle/2", lifecycle("working"), true).await;
415        publish(&served, "terminal/3", b"TERMINAL-SECRET".to_vec(), false).await;
416        publish(&served, "lifecycle/4", lifecycle("blocked"), true).await;
417        let asked = ask(
418            &served,
419            &served.operator,
420            "G",
421            "mission-g",
422            serde_json::json!({
423                "action": "resume",
424                "message": "carry on, MESSAGE-SECRET",
425                "idempotency_key": "resume-1"
426            }),
427        )
428        .await;
429        assert_eq!(asked.status(), StatusCode::ACCEPTED);
430        let control = take(&served, "worker").await.unwrap();
431        assert_eq!(
432            report(
433                &served,
434                control.control_id().as_str(),
435                serde_json::json!({
436                    "station": "worker", "outcome": "applied", "state": "working", "reason": null
437                }),
438            )
439            .await,
440            StatusCode::NO_CONTENT
441        );
442        served
443            .registry
444            .record_event(&TimelineEvent::new("sleeper", "authorized", "L", 5.0))
445            .unwrap();
446        served
447            .registry
448            .record_audit(&AuditRecord {
449                id: "settings-1".to_owned(),
450                actor: "operator-007".to_owned(),
451                action: "station.settings.update".to_owned(),
452                operation: String::new(),
453                resource: Some("station:worker".to_owned()),
454                target: "max_concurrent_missions".to_owned(),
455                at: 6.0,
456            })
457            .unwrap();
458
459        let viewed = page(&served, &served.viewer, "").await;
460        let text = viewed.to_string();
461        assert!(!text.contains("SECRET"), "{text}");
462        let items = viewed["items"].as_array().unwrap();
463        let actions = items
464            .iter()
465            .map(|item| {
466                (
467                    item["kind"].as_str().unwrap(),
468                    item["action"].as_str().unwrap(),
469                )
470            })
471            .collect::<Vec<_>>();
472        // Newest first; a repeated state is not a second transition; another Operation's
473        // events and Station records the viewer may not read stay out.
474        assert_eq!(
475            actions,
476            [
477                ("control", "resume.applied"),
478                ("audit", "mission.resume"),
479                ("lifecycle", "blocked"),
480                ("lifecycle", "working"),
481            ]
482        );
483        assert!(
484            items
485                .iter()
486                .all(|item| item["mission_id"] == "mission-g" && item["operation_id"] == "G")
487        );
488        assert_eq!(items[0]["station_id"], "worker");
489        assert_eq!(items[0]["actor"], "operator-007");
490        assert_eq!(items[0]["detail"]["state"], "working");
491        assert_eq!(items[2]["run_id"], "run-g");
492        assert_eq!(viewed["next_cursor"], serde_json::Value::Null);
493
494        // The operator may read the Station's records too.
495        let operated = page(&served, &served.operator, "").await;
496        assert!(operated["items"].as_array().unwrap().iter().any(|item| {
497            item["action"] == "station.settings.update" && item["station_id"] == "worker"
498        }));
499
500        let filtered = page(&served, &served.viewer, "?mission=mission-g").await;
501        assert_eq!(ids(&filtered), ids(&viewed));
502        let other = page(&served, &served.viewer, "?mission=mission-x").await;
503        assert!(ids(&other).is_empty());
504    }
505
506    #[tokio::test]
507    async fn pages_follow_the_cursor_without_gaps_or_repeats() {
508        let served = served().await;
509        for (index, at) in [10.0, 20.0, 20.0, 30.0, 40.0, 50.0, 60.0]
510            .into_iter()
511            .enumerate()
512        {
513            let mut event = TimelineEvent::new("lifecycle", "working", "G", at)
514                .mission("mission-g")
515                .run("run-g");
516            event.id = format!("event-{index}");
517            served.registry.record_event(&event).unwrap();
518        }
519        let everything = ids(&page(&served, &served.viewer, "?limit=200").await);
520        assert_eq!(everything.len(), 7);
521
522        let mut seen = Vec::new();
523        let mut query = "?limit=3".to_owned();
524        loop {
525            let current = page(&served, &served.viewer, &query).await;
526            seen.extend(ids(&current));
527            if seen.len() == 3 {
528                // A newer event arriving between pages does not shift the older ones.
529                served
530                    .registry
531                    .record_event(&TimelineEvent::new("lifecycle", "done", "G", 99.0))
532                    .unwrap();
533            }
534            match current["next_cursor"].as_str() {
535                Some(cursor) => query = format!("?limit=3&cursor={cursor}"),
536                None => break,
537            }
538        }
539        assert_eq!(seen, everything);
540
541        for invalid in ["?limit=0", "?limit=201", "?cursor=nonsense", "?unknown=1"] {
542            assert_eq!(
543                timeline(&served, &served.viewer, invalid).await.status(),
544                StatusCode::BAD_REQUEST,
545                "{invalid}"
546            );
547        }
548    }
549
550    #[tokio::test]
551    async fn another_operations_timeline_is_refused() {
552        let served = served().await;
553        let refused = reqwest::Client::new()
554            .get(format!("{}/v1/user/operations/L/timeline", served.base))
555            .bearer_auth(&served.viewer)
556            .send()
557            .await
558            .unwrap();
559        assert_eq!(refused.status(), StatusCode::FORBIDDEN);
560        let anonymous = reqwest::Client::new()
561            .get(format!("{}/v1/user/operations/G/timeline", served.base))
562            .send()
563            .await
564            .unwrap();
565        assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
566    }
567
568    #[tokio::test]
569    async fn version_one_timeline_detail_keeps_its_wire_bytes() {
570        let stored = r#"{"id":"fixed","at":1.0,"kind":"control","action":"cancel.applied","operation":"G","mission":"m-1","detail":{"agent":"ada","control":"c-1","state":"abandoned"}}"#;
571        let event: TimelineEvent = serde_json::from_str(stored).unwrap();
572        assert_eq!(serde_json::to_string(&event).unwrap(), stored);
573
574        let served = served().await;
575        served.registry.record_event(&event).unwrap();
576        let response = timeline(&served, &served.viewer, "?mission=m-1").await;
577        assert_eq!(response.status(), StatusCode::OK);
578        let fixture = r#"{"operation_id":"G","items":[{"id":"event:fixed","at":1.0,"kind":"control","action":"cancel.applied","operation_id":"G","station_id":null,"mission_id":"m-1","handle":null,"run_id":null,"actor":null,"target":null,"detail":{"agent":"ada","control":"c-1","state":"abandoned"}}],"next_cursor":null}"#;
579        assert_eq!(response.text().await.unwrap(), fixture);
580        let page: super::TimelinePage = serde_json::from_str(fixture).unwrap();
581        assert_eq!(serde_json::to_string(&page).unwrap(), fixture);
582    }
583}