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, the base operation id did not match
210    /// the delta that produced it, or a snapshot at it held another document.
211    Stale,
212    /// The operation id was already applied.
213    Duplicate,
214    #[serde(other)]
215    Unrecognized,
216}
217
218/// One entry in the state history of a session.
219#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
220#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
221pub struct StateChange {
222    /// The document revision after this record.
223    pub revision: u64,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub op_id: Option<String>,
226    pub outcome: StateOutcome,
227    pub at: LogPosition,
228    pub broker_ts: u64,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub old_digest: Option<Digest32>,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub new_digest: Option<Digest32>,
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub reason: Option<String>,
235}
236
237/// Conditions that make a session summary partial.
238#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
239#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
240pub struct SessionFlags {
241    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
242    pub label_truncated: bool,
243    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
244    pub overflow: bool,
245    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
246    pub events_truncated: bool,
247    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
248    pub lane_conflict: bool,
249    /// A control record arrived on a partition other than the session's
250    /// control route and was not applied.
251    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
252    pub control_conflict: bool,
253    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
254    pub rebuilding: bool,
255    /// Liveness is not known yet because the heartbeat tail has not caught
256    /// up, so `idle` is not meaningful.
257    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
258    pub liveness_unknown: bool,
259}
260
261/// The summary of one session.
262#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
263#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
264pub struct SessionInfo {
265    pub stream: String,
266    pub id: ConversationId,
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub label: Option<String>,
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub namespace: Option<String>,
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub agent: Option<AgentId>,
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub parent: Option<ConversationId>,
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub root: Option<ConversationId>,
277    pub status: SessionStatus,
278    pub idle: bool,
279    pub over_budget: bool,
280    pub pause_requested: bool,
281    /// The participants of the pause in force that have not acknowledged it.
282    #[serde(default, skip_serializing_if = "Vec::is_empty")]
283    pub awaiting: Vec<AgentId>,
284    pub cancel_requested: bool,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub started_at: Option<u64>,
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub ended_at: Option<u64>,
289    #[serde(default, skip_serializing_if = "Option::is_none")]
290    pub first_event_at: Option<u64>,
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub last_event_at: Option<u64>,
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub last_heartbeat_at: Option<u64>,
295    pub events: u64,
296    pub model_calls: u64,
297    pub tool_calls: u64,
298    pub tokens_in: u64,
299    pub tokens_out: u64,
300    pub cost_micros: u64,
301    pub errors: u64,
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub budget: Option<Budget>,
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub sdk: Option<SdkInfo>,
306    #[serde(default)]
307    pub flags: SessionFlags,
308    /// Work records held while the session was paused and not yet handled.
309    #[serde(default, skip_serializing_if = "is_zero")]
310    pub held: u64,
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub frontier: Vec<SourceFrontier>,
313}
314
315fn is_zero(value: &u64) -> bool {
316    *value == 0
317}
318
319/// One page of session summaries, newest created first. `page` counts from 1.
320#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
321#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322pub struct SessionPage {
323    pub items: Vec<SessionInfo>,
324    pub page: u32,
325    pub total_pages: u32,
326    pub total_results: u32,
327    /// The newest change the page covers. Pass it back with `series` for the
328    /// next page of the same walk.
329    pub as_of: u64,
330    /// The change series of the serving index.
331    pub series: u64,
332    /// The rows a substring search examined.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub searched: Option<u64>,
335    /// A substring search filled its scan window, so `total_results` counts
336    /// only the matches inside it.
337    pub truncated: bool,
338    /// The index is rebuilding on this node, so `items` and `total` can be incomplete.
339    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
340    pub rebuilding: bool,
341}
342
343/// One indexed record on a session timeline. The summary never holds prompt
344/// text or tool argument values.
345#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
346#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
347pub struct SessionEvent {
348    pub at: SourceRef,
349    pub session: ConversationId,
350    pub broker_ts: u64,
351    pub kind: String,
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub operation: Option<String>,
354    pub display: String,
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub agent: Option<AgentId>,
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub addressee: Option<String>,
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub correlation: Option<CorrelationId>,
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub cause: Option<LogPosition>,
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub tool: Option<String>,
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub usage: Option<TokenUsage>,
367    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
368    pub after_end: bool,
369    /// The principal whose enrolled key verified this record's signature.
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub verified_actor: Option<String>,
372    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
373    pub summary: BTreeMap<String, serde_json::Value>,
374}
375
376/// One page of a session timeline in server append time order. `page` counts
377/// from 1.
378#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
379#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
380pub struct SessionEventsPage {
381    pub items: Vec<SessionEvent>,
382    pub page: u32,
383    pub total_pages: u32,
384    pub total_results: u32,
385    /// The newest change the page covers. Pass it back with `series` for the
386    /// next page of the same walk.
387    pub as_of: u64,
388    /// The change series of the serving index.
389    pub series: u64,
390    #[serde(default, skip_serializing_if = "Vec::is_empty")]
391    pub ranges: Vec<PayloadRange>,
392    #[serde(default, skip_serializing_if = "Vec::is_empty")]
393    pub frontier: Vec<SourceFrontier>,
394    #[serde(default, skip_serializing_if = "Vec::is_empty")]
395    pub gaps: Vec<SourceGap>,
396}
397
398/// The folded state document of a session.
399#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
400#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
401pub struct SessionStateView {
402    pub revision: u64,
403    pub document: serde_json::Value,
404    #[serde(default, skip_serializing_if = "Vec::is_empty")]
405    pub history: Vec<StateChange>,
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub frontier: Option<SourceFrontier>,
408    pub complete: bool,
409    /// The `op_id` of the delta that produced `revision`, when known.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub head_op_id: Option<String>,
412}
413
414/// One resource a session wrote, recalled, or touched.
415#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
417pub struct SessionLink {
418    pub surface: LinkSurface,
419    pub resource: String,
420    pub item: String,
421    pub relation: LinkRelation,
422    pub first: LogPosition,
423    pub last: LogPosition,
424}
425
426/// The resources linked to one session.
427#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
428#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
429pub struct SessionLinksView {
430    pub links: Vec<SessionLink>,
431    #[serde(default, skip_serializing_if = "Vec::is_empty")]
432    pub frontier: Vec<SourceFrontier>,
433    pub truncated: bool,
434}
435
436/// The source partitions that hold records of one session.
437#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
438#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
439pub struct SessionSources {
440    pub sources: Vec<SourceFrontier>,
441    /// Registered lane topic ID, creation generation, and partition count.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub lane: Option<(u32, u64, u32)>,
444}
445
446/// One committed change batch in a stream.
447#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
449pub struct SessionChangeRow {
450    pub seq: u64,
451    pub sessions: Vec<ConversationId>,
452    /// The records behind the change: the folded records for `records`, the
453    /// link source records for `links`, and for `expiry` the folded record
454    /// whose time expired the sessions. Empty for `maintenance` and for an
455    /// expiry the clock decided.
456    #[serde(default, skip_serializing_if = "Vec::is_empty")]
457    pub positions: Vec<LogPosition>,
458    pub truncated: bool,
459    #[serde(default, skip_serializing_if = "SessionChangeOrigin::is_records")]
460    pub origin: SessionChangeOrigin,
461}
462
463/// What made the sessions of one change row change.
464#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
465#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
466#[serde(rename_all = "snake_case")]
467pub enum SessionChangeOrigin {
468    /// Records folded from the session sources.
469    #[default]
470    Records,
471    /// Links written by managed mutations or projections.
472    Links,
473    /// A source partition was reset or left the registration, and its
474    /// sessions were rebuilt.
475    Maintenance,
476    /// Sessions idle past their retention were removed.
477    Expiry,
478}
479
480impl SessionChangeOrigin {
481    pub fn is_records(&self) -> bool {
482        *self == Self::Records
483    }
484}
485
486/// One page of the change feed in sequence order. `total_results` is the
487/// newest sequence, pruned changes included, and `floor` the oldest retained
488/// sequence, or the next one when none is retained. A follower whose `series`
489/// differs, or whose next sequence is below `floor`, lists sessions again.
490#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
491#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
492pub struct SessionChanges {
493    pub items: Vec<SessionChangeRow>,
494    pub page: u32,
495    pub total_pages: u32,
496    pub total_results: u64,
497    /// The page size the server used, which fixes the sequence range of a page.
498    pub results: u32,
499    pub floor: u64,
500    /// The registration's change series.
501    pub series: u64,
502}
503
504/// The reply to every session read: `Ok` with the outcome, or `Err` with a
505/// failure.
506#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
507#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
508#[non_exhaustive]
509pub enum SessionReply {
510    Ok(SessionOutcome),
511    Err(SessionError),
512}
513
514/// The successful outcome of a session read, shaped per request.
515#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
516#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
517#[non_exhaustive]
518pub enum SessionOutcome {
519    Info(Box<SessionInfo>),
520    Page(SessionPage),
521    Events(SessionEventsPage),
522    State(SessionStateView),
523    Links(SessionLinksView),
524    Sources(SessionSources),
525    Changes(SessionChanges),
526}
527
528/// Why a session read failed.
529#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
530#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
531#[non_exhaustive]
532pub enum SessionError {
533    #[error("sessions not supported: {0}")]
534    Unsupported(String),
535    #[error("session not found: {0}")]
536    NotFound(String),
537    #[error("stream is not registered for sessions: {0}")]
538    NotRegistered(String),
539    #[error("invalid session request: {0}")]
540    Invalid(String),
541    #[error("session read not authorized: {0}")]
542    Unauthorized(String),
543    /// The request named a stream or topic generation the index does not hold.
544    #[error("stale session generation: {0}")]
545    Stale(String),
546    #[error("session backend error: {0}")]
547    Backend(String),
548    /// The identical request may succeed later.
549    #[error("temporarily unavailable: {0}")]
550    Unavailable(String),
551}
552
553/// The body of one process heartbeat on `agent.heartbeats`: the sessions in
554/// one stream that the process holds leases on. A process with sessions in
555/// several streams writes one heartbeat per stream.
556#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
557#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
558pub struct SessionHeartbeat {
559    pub process: String,
560    pub stream: String,
561    pub sessions: Vec<ConversationId>,
562    /// The creation time, in epoch microseconds, of the stream the leases
563    /// were taken on. `None` when the writer does not know it.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub stream_generation: Option<u64>,
566}
567
568impl SessionHeartbeat {
569    /// Whether a reader counts this heartbeat for the stream it read it from,
570    /// created at `stream_generation`. A stream deleted and created again
571    /// keeps its name, so a heartbeat that names another generation is ignored.
572    pub fn counts_for(&self, stream_generation: u64) -> bool {
573        self.stream_generation
574            .is_none_or(|generation| generation == stream_generation)
575    }
576}
577
578impl Validate for request::SessionList {
579    fn validate(&self) -> Result<(), InvalidError> {
580        if self.stream.is_empty() || self.stream.len() > MAX_FILTER_SOURCE_NAME_BYTES {
581            return Err(InvalidError::new(format!(
582                "session list stream must be 1..={MAX_FILTER_SOURCE_NAME_BYTES} bytes"
583            )));
584        }
585        let bounded = [
586            ("label prefix", &self.label_prefix, MAX_SESSION_LABEL_BYTES),
587            ("text", &self.text, MAX_SESSION_TEXT_QUERY_BYTES),
588        ];
589        for (label, value, cap) in bounded {
590            if let Some(value) = value
591                && value.len() > cap
592            {
593                return Err(InvalidError::new(format!(
594                    "session list {label} is {}B, exceeds cap {cap}B",
595                    value.len()
596                )));
597            }
598        }
599        if self.as_of.is_some() != self.series.is_some() {
600            return Err(InvalidError::new(
601                "session list as_of and series name one bound, set both or neither",
602            ));
603        }
604        Ok(())
605    }
606}
607
608impl Validate for SessionHeartbeat {
609    fn validate(&self) -> Result<(), InvalidError> {
610        if self.sessions.len() > MAX_HEARTBEAT_SESSIONS {
611            return Err(InvalidError::new("heartbeat lists too many sessions"));
612        }
613        Ok(())
614    }
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620
621    #[test]
622    fn given_a_session_list_over_its_caps_when_validated_then_should_refuse_it() {
623        let list = request::SessionList {
624            stream: "agents".to_owned(),
625            status: None,
626            root: None,
627            label_prefix: None,
628            agent: None,
629            text: None,
630            page: 0,
631            results: 0,
632            as_of: None,
633            series: None,
634        };
635        list.validate().expect("a plain session list is valid");
636        request::SessionList {
637            as_of: Some(4405),
638            series: Some(77),
639            ..list.clone()
640        }
641        .validate()
642        .expect("a bound names its sequence and series");
643        request::SessionList {
644            stream: "s".repeat(MAX_FILTER_SOURCE_NAME_BYTES),
645            label_prefix: Some("l".repeat(MAX_SESSION_LABEL_BYTES)),
646            text: Some("t".repeat(MAX_SESSION_TEXT_QUERY_BYTES)),
647            ..list.clone()
648        }
649        .validate()
650        .expect("every filter at its cap is valid");
651        request::SessionList {
652            text: Some(String::new()),
653            ..list.clone()
654        }
655        .validate()
656        .expect("an empty text is within its cap");
657        for invalid in [
658            request::SessionList {
659                stream: String::new(),
660                ..list.clone()
661            },
662            request::SessionList {
663                stream: "s".repeat(MAX_FILTER_SOURCE_NAME_BYTES + 1),
664                ..list.clone()
665            },
666            request::SessionList {
667                label_prefix: Some("l".repeat(MAX_SESSION_LABEL_BYTES + 1)),
668                ..list.clone()
669            },
670            request::SessionList {
671                text: Some("t".repeat(MAX_SESSION_TEXT_QUERY_BYTES + 1)),
672                ..list.clone()
673            },
674            request::SessionList {
675                as_of: Some(4405),
676                ..list.clone()
677            },
678            request::SessionList {
679                series: Some(77),
680                ..list.clone()
681            },
682        ] {
683            assert!(invalid.validate().is_err(), "{invalid:?}");
684        }
685    }
686
687    #[test]
688    fn given_a_heartbeat_when_checked_against_a_stream_generation_then_should_count_unless_it_names_another()
689     {
690        let heartbeat = |stream_generation| SessionHeartbeat {
691            process: "worker".to_owned(),
692            stream: "agents".to_owned(),
693            sessions: Vec::new(),
694            stream_generation,
695        };
696        assert!(
697            heartbeat(None).counts_for(7),
698            "a heartbeat that names no generation counts"
699        );
700        assert!(heartbeat(Some(7)).counts_for(7));
701        assert!(
702            !heartbeat(Some(6)).counts_for(7),
703            "a heartbeat of another stream generation is ignored"
704        );
705    }
706}