Skip to main content

openbutler_protocol/session/
read.rs

1//! The three disk-authoritative session reads: payload rules, the
2//! absolute-index page math, and the inline-attachment filter —
3//! `session.load`, `session.entries-range`, and `session.find-attachment`.
4//!
5//! Source: `daemon-host.ts` dispatch cases L3594-L3640 (read 2026-11-16).
6//! Each action's payload and answer shape live together here so one file owns
7//! the action end to end; the reading itself (where the record is and how it
8//! is parsed) is the daemon's `state` layer.
9
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12
13use super::entry::{FileAttachment, SessionEntry};
14use crate::constants::{INLINE_IMAGE_MEDIA_TYPES, MAX_ENTRIES_RANGE_LIMIT};
15use crate::error::ValidationError;
16use crate::payload::{require_integer, require_string};
17
18/// Page size when the client omits `limit` (TS `limit === undefined ? 50`).
19pub const DEFAULT_ENTRIES_LIMIT: u64 = 50;
20
21/// `before` accepts 0..=Number.MAX_SAFE_INTEGER (2^53-1).
22const MAX_BEFORE: u64 = 9_007_199_254_740_991;
23/// Byte caps of the payload ids.
24const SESSION_ID_MAX_BYTES: usize = 64;
25const ATTACHMENT_ID_MAX_BYTES: usize = 128;
26
27/// `session.load` payload: the chat to open by id.
28pub fn load_session_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
29    require_string(payload.get("sessionId"), "sessionId", SESSION_ID_MAX_BYTES)
30}
31
32/// `session.find-attachment` payload: the attachment id to resolve.
33pub fn find_attachment_id(payload: &Map<String, Value>) -> Result<String, ValidationError> {
34    require_string(
35        payload.get("attachmentId"),
36        "attachmentId",
37        ATTACHMENT_ID_MAX_BYTES,
38    )
39}
40
41/// `session.entries-range` payload after validation: `before` is `None` when
42/// the client asked for the tail (the answer substitutes `total`).
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct EntriesRangeRequest {
45    pub before: Option<u64>,
46    pub limit: u64,
47}
48
49/// Parses the range payload with the fixed rules and defaults. Extra keys
50/// are ignored, like the TypeScript index signature.
51pub fn entries_range(payload: &Map<String, Value>) -> Result<EntriesRangeRequest, ValidationError> {
52    let before = match payload.get("before") {
53        None => None,
54        Some(value) => Some(require_integer(Some(value), "before", 0, MAX_BEFORE)?),
55    };
56    let limit = match payload.get("limit") {
57        None => DEFAULT_ENTRIES_LIMIT,
58        Some(value) => require_integer(Some(value), "limit", 1, MAX_ENTRIES_RANGE_LIMIT as u64)?,
59    };
60    Ok(EntriesRangeRequest { before, limit })
61}
62
63impl EntriesRangeRequest {
64    /// The absolute window over a transcript of `total` entries: `before` is
65    /// clamped to `total` (TS `Math.min(total, before)`), the start is floored
66    /// at zero (TS `Math.max(0, before - limit)`), and an absent `before`
67    /// means the end. Returns the half-open `(start, end)` slice bounds.
68    pub fn resolve(&self, total: u64) -> (u64, u64) {
69        let end = self.before.map_or(total, |before| before.min(total));
70        let start = end.saturating_sub(self.limit);
71        (start, end)
72    }
73}
74
75/// `session.find-attachment` success payload (`{path, mediaType}`); a miss
76/// answers an explicit `null`, not a failure.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct InlineAttachment {
80    pub path: String,
81    pub media_type: String,
82}
83
84/// The host-side attachment lookup: user entries only, exact id, and only a
85/// type the browser can render inline (the flatMap + find over
86/// `INLINE_IMAGE_MEDIA_TYPES` — a pdf never resolves whatever its id).
87pub fn find_inline_attachment<'a>(
88    entries: &'a [SessionEntry],
89    id: &str,
90) -> Option<&'a FileAttachment> {
91    entries
92        .iter()
93        .filter_map(|entry| match entry {
94            SessionEntry::User {
95                attachments: Some(files),
96                ..
97            } => Some(files.as_slice()),
98            _ => None,
99        })
100        .flatten()
101        .find(|file| file.id == id && INLINE_IMAGE_MEDIA_TYPES.contains(&file.media_type.as_str()))
102}