khive_runtime/event_plane_read/
page.rs1use serde::Deserialize;
2use serde_json::{json, Value};
3
4use crate::{
5 micros_to_iso, page_budget_exceeded_error, row_exceeds_budget_error, EventReadPageRequest,
6 EventReadPageResult, KhiveRuntime, NamespaceToken, RuntimeError, RuntimeResult,
7};
8
9use super::parsing::{event_actor_read_scope, parse_event_kind, parse_rfc3339_micros};
10
11pub(super) const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
12
13#[derive(Deserialize)]
14#[serde(deny_unknown_fields)]
15struct EventPageParams {
16 since: Option<String>,
17 until: Option<String>,
18 kind: Option<String>,
19 kinds: Option<Vec<String>>,
20 namespaces: Option<Vec<String>>,
21 exclude_namespaces: Option<Vec<String>>,
22 actor: Option<String>,
23 all_actors: Option<bool>,
24 limit: Option<u32>,
25 after: Option<String>,
26}
27
28impl KhiveRuntime {
29 pub async fn read_event_page_response(
31 &self,
32 token: &NamespaceToken,
33 params: Value,
34 ) -> RuntimeResult<Value> {
35 let p: EventPageParams = serde_json::from_value(params)
36 .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;
37 let actor_scope = event_actor_read_scope(
38 self,
39 token,
40 p.actor.as_deref(),
41 p.all_actors.unwrap_or(false),
42 )?;
43 let since_raw = p.since.as_deref().ok_or_else(|| {
44 RuntimeError::InvalidInput(
45 "missing `since`: required ISO-8601/RFC-3339 datetime; expected e.g. \
46 \"2026-07-01T00:00:00Z\""
47 .to_string(),
48 )
49 })?;
50 let display_tz = self.config().display_timezone;
51 let since_us = parse_rfc3339_micros("since", since_raw, false, display_tz)?;
52 let until_us = p
53 .until
54 .as_deref()
55 .map(|raw| parse_rfc3339_micros("until", raw, true, display_tz))
56 .transpose()?;
57 let mut kinds = Vec::new();
58 for raw in p.kind.into_iter().chain(p.kinds.into_iter().flatten()) {
59 let kind = parse_event_kind(&raw)?;
60 if !kinds.contains(&kind) {
61 kinds.push(kind);
62 }
63 }
64 let result = self
65 .page_events(
66 token,
67 EventReadPageRequest {
68 since_us,
69 until_us,
70 kinds,
71 actors: actor_scope.actors,
72 namespaces: p.namespaces,
73 exclude_namespaces: p.exclude_namespaces.unwrap_or_default(),
74 limit: p.limit.unwrap_or(100),
75 after: p.after,
76 },
77 )
78 .await?;
79 event_page_json(result)
80 }
81}
82
83pub(super) fn event_page_json(result: EventReadPageResult) -> RuntimeResult<Value> {
84 let single_row = match (result.events.as_slice(), result.single_row_cursor) {
85 ([event], Some(cursor)) => Some((event.id, cursor)),
86 _ => None,
87 };
88 let mut events = Vec::with_capacity(result.events.len());
89 for event in result.events {
90 let created_at = event.created_at;
91 let mut value = serde_json::to_value(event).map_err(|_| {
92 RuntimeError::InvalidInput("event page response serialization failed".into())
93 })?;
94 value["created_at"] = json!(micros_to_iso(created_at));
95 events.push(value);
96 }
97 let value = json!({
98 "count": events.len(),
99 "events": events,
100 "has_more": result.has_more,
101 "next_after": result.next_after,
102 "since": micros_to_iso(result.since_us),
103 "until": micros_to_iso(result.until_us),
104 "scope": { "namespaces": result.namespaces },
105 "consistency": "live_ordered_window",
106 });
107 let encoded = serde_json::to_vec(&value).map_err(|_| {
108 RuntimeError::InvalidInput("event page response serialization failed".into())
109 })?;
110 if encoded.len() > MAX_RESPONSE_BYTES {
111 return Err(match single_row {
112 Some((event_id, cursor)) => row_exceeds_budget_error(event_id, cursor),
113 None => page_budget_exceeded_error(),
114 });
115 }
116 Ok(value)
117}