Skip to main content

laser_wire/
session.rs

1use crate::agent::{
2    AgentId, Budget, ConversationId, CorrelationId, LogPosition, SdkInfo, SessionStatus, TokenUsage,
3};
4use crate::error::InvalidError;
5use crate::graph::SourceRef;
6use crate::limits::{
7    MAX_FILTER_SOURCE_NAME_BYTES, MAX_HEARTBEAT_SESSIONS, MAX_SESSION_LABEL_BYTES,
8    MAX_SESSION_TEXT_QUERY_BYTES,
9};
10use crate::schema::Digest32;
11use crate::validate::Validate;
12use serde::{Deserialize, Serialize};
13use std::collections::BTreeMap;
14
15/// The resource surface used to narrow a session link read.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
18#[serde(rename_all = "snake_case")]
19pub enum LinkSurface {
20    Memory,
21    Kv,
22    GraphNode,
23    GraphEdge,
24    Projection,
25    Child,
26}
27
28/// The relationship a session has with a linked resource.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
31#[serde(rename_all = "snake_case")]
32pub enum LinkRelation {
33    Wrote,
34    Recalled,
35    Touched,
36}
37
38/// Read requests. Every request names the stream before any other field.
39pub mod request {
40    use super::*;
41
42    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44    pub struct SessionGet {
45        pub stream: String,
46        pub id: ConversationId,
47    }
48
49    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
50    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
51    pub struct SessionList {
52        pub stream: String,
53        #[serde(default, skip_serializing_if = "Option::is_none")]
54        pub status: Option<SessionStatus>,
55        /// Only sessions in the tree rooted at this session.
56        #[serde(default, skip_serializing_if = "Option::is_none")]
57        pub root: Option<ConversationId>,
58        /// Only sessions whose label starts with this prefix.
59        #[serde(default, skip_serializing_if = "Option::is_none")]
60        pub label_prefix: Option<String>,
61        #[serde(default, skip_serializing_if = "Option::is_none")]
62        pub agent: Option<AgentId>,
63        #[serde(default, skip_serializing_if = "Option::is_none")]
64        pub text: Option<String>,
65        /// The 1-based page. Zero reads the first page.
66        pub page: u32,
67        /// The sessions per page. Zero leaves it to the server.
68        pub results: u32,
69        /// The bound of a walk: the `as_of` its first page returned. Later
70        /// pages pass it back so sessions folded after it stay out.
71        #[serde(default, skip_serializing_if = "Option::is_none")]
72        pub as_of: Option<u64>,
73        /// The change series `as_of` belongs to, from the same first page.
74        #[serde(default, skip_serializing_if = "Option::is_none")]
75        pub series: Option<u64>,
76    }
77
78    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
79    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
80    pub struct SessionEvents {
81        pub stream: String,
82        pub id: ConversationId,
83        /// The 1-based page. Zero reads the first page.
84        pub page: u32,
85        /// The events per page. Zero leaves it to the server.
86        pub results: u32,
87        /// The bound of a walk: the `as_of` its first page returned. Later
88        /// pages pass it back so events folded after it stay out.
89        #[serde(default, skip_serializing_if = "Option::is_none")]
90        pub as_of: Option<u64>,
91        /// The change series `as_of` belongs to, from the same first page.
92        #[serde(default, skip_serializing_if = "Option::is_none")]
93        pub series: Option<u64>,
94    }
95
96    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
97    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
98    pub struct SessionState {
99        pub stream: String,
100        pub id: ConversationId,
101        /// The most history rows. Zero leaves it to the server.
102        pub history_limit: u32,
103    }
104
105    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
106    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
107    pub struct SessionLinks {
108        pub stream: String,
109        pub id: ConversationId,
110        #[serde(default, skip_serializing_if = "Option::is_none")]
111        pub surface: Option<LinkSurface>,
112    }
113
114    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
115    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
116    pub struct SessionSources {
117        pub stream: String,
118        pub id: ConversationId,
119        /// Return only the registered lane identity for a native lane writer.
120        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
121        pub lane_only: bool,
122    }
123
124    /// A page of the change feed. Page `p` of size `r` holds the changes with
125    /// sequence `(p - 1) * r + 1 ..= p * r`, so appends and pruning never
126    /// shift a page.
127    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
128    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
129    pub struct SessionChanges {
130        pub stream: String,
131        /// The 1-based page. Zero reads the first page.
132        pub page: u32,
133        /// The changes per page. Zero leaves it to the server.
134        pub results: u32,
135    }
136}
137
138/// How far the session index has folded one source partition. Offsets are
139/// never compared across topics. `topic_generation` is the topic creation time
140/// in microseconds, so a recreated topic with a reused id is a different source.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
142#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
143pub struct SourceFrontier {
144    pub topic_id: u32,
145    pub topic_generation: u64,
146    pub partition_id: u32,
147    /// The last offset folded into the index, absent before the first record.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub folded: Option<u64>,
150    /// The live partition head when the read probed it.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub head: Option<u64>,
153    /// The first offset still retained by the source.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub retained_from: Option<u64>,
156}
157
158/// Why part of a session timeline is missing.
159#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
161#[serde(rename_all = "snake_case")]
162pub enum GapReason {
163    /// The source expired these offsets before the index folded them.
164    ExpiredBeforeFold,
165    /// The index pruned these offsets after the source expired them.
166    Pruned,
167    /// The session reached its event cap, so these records were counted only.
168    Truncated,
169    /// The source is being rebuilt after a reset.
170    Rebuilding,
171    #[serde(other)]
172    Unrecognized,
173}
174
175/// A missing inclusive offset range on one source partition.
176#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
178pub struct SourceGap {
179    pub topic_id: u32,
180    pub topic_generation: u64,
181    pub partition_id: u32,
182    pub from: u64,
183    pub to: u64,
184    pub reason: GapReason,
185}
186
187/// The inclusive offset range on one source partition that holds the payloads
188/// of a timeline page. A range is a hint for bounded polls, not a promise that
189/// every offset in it belongs to the session.
190#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
191#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
192pub struct PayloadRange {
193    pub topic_id: u32,
194    pub topic_generation: u64,
195    pub partition_id: u32,
196    pub first: u64,
197    pub last: u64,
198}
199
200/// What the fold did with one state record.
201#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203#[serde(rename_all = "snake_case")]
204pub enum StateOutcome {
205    /// The patch or snapshot changed the document.
206    Applied,
207    /// A patch operation failed, so the whole patch was rejected.
208    Rejected,
209    /// The base revision did not match the applied revision, or a snapshot at it held another document.
210    Stale,
211    /// The operation id was already applied.
212    Duplicate,
213    #[serde(other)]
214    Unrecognized,
215}
216
217/// One entry in the state history of a session.
218#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
219#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
220pub struct StateChange {
221    /// The document revision after this record.
222    pub revision: u64,
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub op_id: Option<String>,
225    pub outcome: StateOutcome,
226    pub at: LogPosition,
227    pub broker_ts: u64,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub old_digest: Option<Digest32>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub new_digest: Option<Digest32>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub reason: Option<String>,
234}
235
236/// Conditions that make a session summary partial.
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
238#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
239pub struct SessionFlags {
240    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
241    pub label_truncated: bool,
242    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
243    pub overflow: bool,
244    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
245    pub events_truncated: bool,
246    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
247    pub lane_conflict: bool,
248    /// A control record arrived on a partition other than the session's
249    /// control route and was not applied.
250    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
251    pub control_conflict: bool,
252    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
253    pub rebuilding: bool,
254    /// Liveness is not known yet because the heartbeat tail has not caught
255    /// up, so `idle` is not meaningful.
256    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
257    pub liveness_unknown: bool,
258}
259
260/// The summary of one session.
261#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
262#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
263pub struct SessionInfo {
264    pub stream: String,
265    pub id: ConversationId,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub label: Option<String>,
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub namespace: Option<String>,
270    #[serde(default, skip_serializing_if = "Option::is_none")]
271    pub agent: Option<AgentId>,
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub parent: Option<ConversationId>,
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub root: Option<ConversationId>,
276    pub status: SessionStatus,
277    pub idle: bool,
278    pub over_budget: bool,
279    pub pause_requested: bool,
280    /// The participants of the pause in force that have not acknowledged it.
281    #[serde(default, skip_serializing_if = "Vec::is_empty")]
282    pub awaiting: Vec<AgentId>,
283    pub cancel_requested: bool,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub started_at: Option<u64>,
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub ended_at: Option<u64>,
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub first_event_at: Option<u64>,
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub last_event_at: Option<u64>,
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub last_heartbeat_at: Option<u64>,
294    pub events: u64,
295    pub model_calls: u64,
296    pub tool_calls: u64,
297    pub tokens_in: u64,
298    pub tokens_out: u64,
299    pub cost_micros: u64,
300    pub errors: u64,
301    #[serde(default, skip_serializing_if = "Option::is_none")]
302    pub budget: Option<Budget>,
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub sdk: Option<SdkInfo>,
305    #[serde(default)]
306    pub flags: SessionFlags,
307    /// Work records held while the session was paused and not yet handled.
308    #[serde(default, skip_serializing_if = "is_zero")]
309    pub held: u64,
310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
311    pub frontier: Vec<SourceFrontier>,
312}
313
314fn is_zero(value: &u64) -> bool {
315    *value == 0
316}
317
318/// One page of session summaries, newest created first. `page` counts from 1.
319#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
320#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
321pub struct SessionPage {
322    pub items: Vec<SessionInfo>,
323    pub page: u32,
324    pub total_pages: u32,
325    pub total_results: u32,
326    /// The newest change the page covers. Pass it back with `series` for the
327    /// next page of the same walk.
328    pub as_of: u64,
329    /// The change series of the serving index.
330    pub series: u64,
331    /// The rows a substring search examined.
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub searched: Option<u64>,
334    /// A substring search filled its scan window, so `total_results` counts
335    /// only the matches inside it.
336    pub truncated: bool,
337    /// The index is rebuilding on this node, so `items` and `total` can be incomplete.
338    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
339    pub rebuilding: bool,
340}
341
342/// One indexed record on a session timeline. The summary never holds prompt
343/// text or tool argument values.
344#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
345#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
346pub struct SessionEvent {
347    pub at: SourceRef,
348    pub session: ConversationId,
349    pub broker_ts: u64,
350    pub kind: String,
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub operation: Option<String>,
353    pub display: String,
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub agent: Option<AgentId>,
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub addressee: Option<String>,
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub correlation: Option<CorrelationId>,
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub cause: Option<LogPosition>,
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub tool: Option<String>,
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub usage: Option<TokenUsage>,
366    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
367    pub after_end: bool,
368    /// The principal whose enrolled key verified this record's signature.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub verified_actor: Option<String>,
371    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
372    pub summary: BTreeMap<String, serde_json::Value>,
373}
374
375/// One page of a session timeline in server append time order. `page` counts
376/// from 1.
377#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
379pub struct SessionEventsPage {
380    pub items: Vec<SessionEvent>,
381    pub page: u32,
382    pub total_pages: u32,
383    pub total_results: u32,
384    /// The newest change the page covers. Pass it back with `series` for the
385    /// next page of the same walk.
386    pub as_of: u64,
387    /// The change series of the serving index.
388    pub series: u64,
389    #[serde(default, skip_serializing_if = "Vec::is_empty")]
390    pub ranges: Vec<PayloadRange>,
391    #[serde(default, skip_serializing_if = "Vec::is_empty")]
392    pub frontier: Vec<SourceFrontier>,
393    #[serde(default, skip_serializing_if = "Vec::is_empty")]
394    pub gaps: Vec<SourceGap>,
395}
396
397/// The folded state document of a session.
398#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
399#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
400pub struct SessionStateView {
401    pub revision: u64,
402    pub document: serde_json::Value,
403    #[serde(default, skip_serializing_if = "Vec::is_empty")]
404    pub history: Vec<StateChange>,
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub frontier: Option<SourceFrontier>,
407    pub complete: bool,
408}
409
410/// One resource a session wrote, recalled, or touched.
411#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
412#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
413pub struct SessionLink {
414    pub surface: LinkSurface,
415    pub resource: String,
416    pub item: String,
417    pub relation: LinkRelation,
418    pub first: LogPosition,
419    pub last: LogPosition,
420}
421
422/// The resources linked to one session.
423#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
424#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
425pub struct SessionLinksView {
426    pub links: Vec<SessionLink>,
427    #[serde(default, skip_serializing_if = "Vec::is_empty")]
428    pub frontier: Vec<SourceFrontier>,
429    pub truncated: bool,
430}
431
432/// The source partitions that hold records of one session.
433#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
434#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
435pub struct SessionSources {
436    pub sources: Vec<SourceFrontier>,
437    /// Registered lane topic ID, creation generation, and partition count.
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub lane: Option<(u32, u64, u32)>,
440}
441
442/// One committed change batch in a stream.
443#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
444#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
445pub struct SessionChangeRow {
446    pub seq: u64,
447    pub sessions: Vec<ConversationId>,
448    /// The records behind the change: the folded records for `records`, the
449    /// link source records for `links`, and for `expiry` the folded record
450    /// whose time expired the sessions. Empty for `maintenance` and for an
451    /// expiry the clock decided.
452    #[serde(default, skip_serializing_if = "Vec::is_empty")]
453    pub positions: Vec<LogPosition>,
454    pub truncated: bool,
455    #[serde(default, skip_serializing_if = "SessionChangeOrigin::is_records")]
456    pub origin: SessionChangeOrigin,
457}
458
459/// What made the sessions of one change row change.
460#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
461#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
462#[serde(rename_all = "snake_case")]
463pub enum SessionChangeOrigin {
464    /// Records folded from the session sources.
465    #[default]
466    Records,
467    /// Links written by managed mutations or projections.
468    Links,
469    /// A source partition was reset or left the registration, and its
470    /// sessions were rebuilt.
471    Maintenance,
472    /// Sessions idle past their retention were removed.
473    Expiry,
474}
475
476impl SessionChangeOrigin {
477    pub fn is_records(&self) -> bool {
478        *self == Self::Records
479    }
480}
481
482/// One page of the change feed in sequence order. `total_results` is the
483/// newest sequence, pruned changes included, and `floor` the oldest retained
484/// sequence, or the next one when none is retained. A follower whose `series`
485/// differs, or whose next sequence is below `floor`, lists sessions again.
486#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
487#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
488pub struct SessionChanges {
489    pub items: Vec<SessionChangeRow>,
490    pub page: u32,
491    pub total_pages: u32,
492    pub total_results: u64,
493    /// The page size the server used, which fixes the sequence range of a page.
494    pub results: u32,
495    pub floor: u64,
496    /// The registration's change series.
497    pub series: u64,
498}
499
500/// The reply to every session read: `Ok` with the outcome, or `Err` with a
501/// failure.
502#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
503#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
504#[non_exhaustive]
505pub enum SessionReply {
506    Ok(SessionOutcome),
507    Err(SessionError),
508}
509
510/// The successful outcome of a session read, shaped per request.
511#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
512#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
513#[non_exhaustive]
514pub enum SessionOutcome {
515    Info(Box<SessionInfo>),
516    Page(SessionPage),
517    Events(SessionEventsPage),
518    State(SessionStateView),
519    Links(SessionLinksView),
520    Sources(SessionSources),
521    Changes(SessionChanges),
522}
523
524/// Why a session read failed.
525#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
526#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
527#[non_exhaustive]
528pub enum SessionError {
529    #[error("sessions not supported: {0}")]
530    Unsupported(String),
531    #[error("session not found: {0}")]
532    NotFound(String),
533    #[error("stream is not registered for sessions: {0}")]
534    NotRegistered(String),
535    #[error("invalid session request: {0}")]
536    Invalid(String),
537    #[error("session read not authorized: {0}")]
538    Unauthorized(String),
539    /// The request named a stream or topic generation the index does not hold.
540    #[error("stale session generation: {0}")]
541    Stale(String),
542    #[error("session backend error: {0}")]
543    Backend(String),
544    /// The identical request may succeed later.
545    #[error("temporarily unavailable: {0}")]
546    Unavailable(String),
547}
548
549/// The body of one process heartbeat on `agent.heartbeats`: the sessions in
550/// one stream that the process holds leases on. A process with sessions in
551/// several streams writes one heartbeat per stream.
552#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
554pub struct SessionHeartbeat {
555    pub process: String,
556    pub stream: String,
557    pub sessions: Vec<ConversationId>,
558}
559
560impl Validate for request::SessionList {
561    fn validate(&self) -> Result<(), InvalidError> {
562        if self.stream.is_empty() || self.stream.len() > MAX_FILTER_SOURCE_NAME_BYTES {
563            return Err(InvalidError::new(format!(
564                "session list stream must be 1..={MAX_FILTER_SOURCE_NAME_BYTES} bytes"
565            )));
566        }
567        let bounded = [
568            ("label prefix", &self.label_prefix, MAX_SESSION_LABEL_BYTES),
569            ("text", &self.text, MAX_SESSION_TEXT_QUERY_BYTES),
570        ];
571        for (label, value, cap) in bounded {
572            if let Some(value) = value
573                && value.len() > cap
574            {
575                return Err(InvalidError::new(format!(
576                    "session list {label} is {}B, exceeds cap {cap}B",
577                    value.len()
578                )));
579            }
580        }
581        if self.as_of.is_some() != self.series.is_some() {
582            return Err(InvalidError::new(
583                "session list as_of and series name one bound, set both or neither",
584            ));
585        }
586        Ok(())
587    }
588}
589
590impl Validate for SessionHeartbeat {
591    fn validate(&self) -> Result<(), InvalidError> {
592        if self.sessions.len() > MAX_HEARTBEAT_SESSIONS {
593            return Err(InvalidError::new("heartbeat lists too many sessions"));
594        }
595        Ok(())
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn given_a_session_list_over_its_caps_when_validated_then_should_refuse_it() {
605        let list = request::SessionList {
606            stream: "agents".to_owned(),
607            status: None,
608            root: None,
609            label_prefix: None,
610            agent: None,
611            text: None,
612            page: 0,
613            results: 0,
614            as_of: None,
615            series: None,
616        };
617        list.validate().expect("a plain session list is valid");
618        request::SessionList {
619            as_of: Some(4405),
620            series: Some(77),
621            ..list.clone()
622        }
623        .validate()
624        .expect("a bound names its sequence and series");
625        request::SessionList {
626            stream: "s".repeat(MAX_FILTER_SOURCE_NAME_BYTES),
627            label_prefix: Some("l".repeat(MAX_SESSION_LABEL_BYTES)),
628            text: Some("t".repeat(MAX_SESSION_TEXT_QUERY_BYTES)),
629            ..list.clone()
630        }
631        .validate()
632        .expect("every filter at its cap is valid");
633        request::SessionList {
634            text: Some(String::new()),
635            ..list.clone()
636        }
637        .validate()
638        .expect("an empty text is within its cap");
639        for invalid in [
640            request::SessionList {
641                stream: String::new(),
642                ..list.clone()
643            },
644            request::SessionList {
645                stream: "s".repeat(MAX_FILTER_SOURCE_NAME_BYTES + 1),
646                ..list.clone()
647            },
648            request::SessionList {
649                label_prefix: Some("l".repeat(MAX_SESSION_LABEL_BYTES + 1)),
650                ..list.clone()
651            },
652            request::SessionList {
653                text: Some("t".repeat(MAX_SESSION_TEXT_QUERY_BYTES + 1)),
654                ..list.clone()
655            },
656            request::SessionList {
657                as_of: Some(4405),
658                ..list.clone()
659            },
660            request::SessionList {
661                series: Some(77),
662                ..list.clone()
663            },
664        ] {
665            assert!(invalid.validate().is_err(), "{invalid:?}");
666        }
667    }
668}