1use std::fmt;
25use std::io;
26
27use rig_core::conversation::{
28 Aside, AsideId, Author, Change, ChangeRecord, Conversation, Entry, Halt, Lineage, MessageId,
29};
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32
33pub const FORMAT: &str = "rig-session/4";
35
36pub const SESSION: &str = "session";
38
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Stamp {
46 pub n: u64,
50 pub seq: u64,
52 pub t: u64,
54}
55
56#[derive(Debug, thiserror::Error)]
59pub enum SessionError {
60 #[error(transparent)]
62 Io(#[from] io::Error),
63 #[error("this session was made by another version of rig; start a new session")]
66 OldLayout,
67 #[error(
70 "this session was made by another version of rig; start a new session (the log `{log}` \
71 is in format {}, not {FORMAT})",
72 .found.as_deref().unwrap_or("(none)")
73 )]
74 Format {
75 log: String,
77 found: Option<String>,
79 },
80 #[error("the log `{log}` cannot be read at line {line}: {why}")]
82 Record {
83 log: String,
85 line: usize,
87 why: String,
89 },
90 #[error("the log `{log}` changed since it was read")]
93 Changed {
94 log: String,
96 },
97}
98
99impl SessionError {
100 pub(crate) fn record(log: &str, line: usize, why: String) -> Self {
102 let log = log.to_owned();
103 Self::Record { log, line, why }
104 }
105}
106
107impl From<SessionError> for io::Error {
108 fn from(error: SessionError) -> Self {
112 match error {
113 SessionError::Io(error) => error,
114 error => io::Error::new(io::ErrorKind::InvalidData, error),
115 }
116 }
117}
118
119#[derive(Clone, Debug, PartialEq, Eq)]
121pub enum Repair {
122 TornTail {
127 log: String,
129 kept: u64,
131 cut: u64,
133 set_aside: Option<String>,
135 },
136 LostImage {
138 log: String,
140 why: String,
142 },
143}
144
145impl fmt::Display for Repair {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 match self {
148 Self::TornTail {
149 log,
150 cut,
151 set_aside,
152 ..
153 } => {
154 write!(f, "the log `{log}` ended in a line cut short ({cut} bytes)")?;
155 match set_aside {
156 Some(file) => write!(f, ", set aside in {file}"),
157 None => Ok(()),
158 }
159 }
160 Self::LostImage { log, why } => write!(f, "an image of the log `{log}` is lost: {why}"),
161 }
162 }
163}
164
165#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
167pub(crate) struct Header {
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub format: Option<String>,
170 #[serde(default)]
171 pub log: String,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub parent: Option<String>,
175 #[serde(default)]
178 pub lineage: Lineage,
179 #[serde(default, skip_serializing_if = "Vec::is_empty")]
181 pub rewrites: Vec<LogRewrite>,
182}
183
184#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
187pub struct LogRewrite {
188 pub t: u64,
190 pub by: Author,
192}
193
194impl Header {
195 pub fn new(log: &str, parent: Option<&str>) -> Self {
197 Self {
198 format: Some(FORMAT.to_owned()),
199 log: log.to_owned(),
200 parent: parent.map(str::to_owned),
201 lineage: Lineage::fresh(),
202 rewrites: Vec::new(),
203 }
204 }
205}
206
207#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
209#[serde(tag = "type", rename_all = "snake_case")]
210pub(crate) enum Meta {
211 Header(Header),
212 State {
213 key: String,
214 #[serde(default)]
215 value: Option<Value>,
216 },
217 Retired,
218}
219
220pub(crate) enum Body {
222 Meta(Meta),
223 Change(ChangeRecord),
225}
226
227#[derive(Deserialize)]
229struct Head<'a> {
230 seq: u64,
231 n: u64,
232 t: u64,
233 #[serde(rename = "type", borrow)]
234 kind: std::borrow::Cow<'a, str>,
235}
236
237const CHANGES: [&str; 5] = ["push", "splice", "halt", "aside", "reset"];
239
240pub(crate) fn stamp_of(line: &[u8]) -> Result<(Stamp, bool), String> {
243 let head: Head<'_> = serde_json::from_slice(line).map_err(|error| error.to_string())?;
244 Ok((head.stamp(), CHANGES.contains(&&*head.kind)))
245}
246
247impl Head<'_> {
248 fn stamp(&self) -> Stamp {
249 Stamp {
250 n: self.n,
251 seq: self.seq,
252 t: self.t,
253 }
254 }
255}
256
257#[derive(Deserialize)]
262struct Read<'a> {
263 seq: u64,
264 n: u64,
265 t: u64,
266 #[serde(rename = "type", borrow)]
267 kind: std::borrow::Cow<'a, str>,
268 #[serde(default)]
269 by: Option<Author>,
270 entries: Option<Vec<Entry>>,
271 from: Option<usize>,
272 to: Option<usize>,
273 removed: Option<Vec<MessageId>>,
274 with: Option<Vec<Entry>>,
275 #[serde(default)]
276 halt: Option<Halt>,
277 id: Option<AsideId>,
278 #[serde(default)]
279 aside: Option<Aside>,
280 state: Option<Box<Conversation>>,
281}
282
283impl Read<'_> {
284 fn change(self) -> Result<Change, String> {
286 fn given<T>(field: Option<T>, name: &str) -> Result<T, String> {
287 field.ok_or_else(|| format!("missing field `{name}`"))
288 }
289 Ok(match &*self.kind {
290 "push" => Change::Push {
291 entries: given(self.entries, "entries")?,
292 },
293 "splice" => Change::Splice {
294 from: given(self.from, "from")?,
295 to: given(self.to, "to")?,
296 removed: given(self.removed, "removed")?,
297 with: given(self.with, "with")?,
298 },
299 "halt" => Change::Halt { halt: self.halt },
300 "aside" => Change::Aside {
301 id: given(self.id, "id")?,
302 aside: self.aside,
303 },
304 "reset" => Change::Reset {
305 state: given(self.state, "state")?,
306 },
307 other => return Err(format!("unknown record type {other:?}")),
308 })
309 }
310}
311
312pub(crate) fn parse(line: &[u8]) -> Result<(Stamp, Body), String> {
314 let mut read: Read<'_> = serde_json::from_slice(line).map_err(|error| error.to_string())?;
315 let stamp = Stamp {
316 n: read.n,
317 seq: read.seq,
318 t: read.t,
319 };
320 let body = match &*read.kind {
321 "header" | "state" | "retired" => {
322 Body::Meta(serde_json::from_slice(line).map_err(|error| error.to_string())?)
323 }
324 _ => {
325 let by = read.by.take();
326 Body::Change(ChangeRecord {
327 change: read.change()?,
328 by,
329 at: Some(stamp.t),
330 })
331 }
332 };
333 Ok((stamp, body))
334}
335
336#[derive(Serialize)]
338struct Line<'a> {
339 seq: u64,
340 n: u64,
341 t: u64,
342 #[serde(skip_serializing_if = "Option::is_none")]
343 by: Option<&'a Author>,
344 #[serde(flatten)]
345 body: Out<'a>,
346}
347
348#[derive(Serialize)]
349#[serde(untagged)]
350enum Out<'a> {
351 Meta(&'a Meta),
352 Change(&'a Change),
353}
354
355pub(crate) fn write_meta(out: &mut Vec<u8>, stamp: Stamp, meta: &Meta) -> serde_json::Result<()> {
357 write(out, stamp, None, Out::Meta(meta))
358}
359
360pub(crate) fn write_change(
362 out: &mut Vec<u8>,
363 stamp: Stamp,
364 by: Option<&Author>,
365 change: &Change,
366) -> serde_json::Result<()> {
367 write(out, stamp, by, Out::Change(change))
368}
369
370fn write(
372 out: &mut Vec<u8>,
373 stamp: Stamp,
374 by: Option<&Author>,
375 body: Out<'_>,
376) -> serde_json::Result<()> {
377 let line = Line {
378 seq: stamp.seq,
379 n: stamp.n,
380 t: stamp.t,
381 by,
382 body,
383 };
384 serde_json::to_writer(&mut *out, &line)?;
385 out.push(b'\n');
386 Ok(())
387}
388
389#[derive(Clone, Debug, Default)]
392pub(crate) struct LogLines {
393 bytes: Vec<u8>,
394 ends: Vec<usize>,
396}
397
398impl LogLines {
399 pub fn parse(bytes: Vec<u8>) -> Self {
400 let mut ends: Vec<usize> = memchr::memchr_iter(b'\n', &bytes)
401 .map(|at| at + 1)
402 .collect();
403 let last_start = ends
404 .len()
405 .checked_sub(2)
406 .and_then(|at| ends.get(at))
407 .copied();
408 let last = ends
409 .last()
410 .and_then(|end| bytes.get(last_start.unwrap_or(0)..end.saturating_sub(1)));
411 if last.is_some_and(|line| {
412 !line.is_empty() && serde_json::from_slice::<serde::de::IgnoredAny>(line).is_err()
413 }) {
414 ends.pop();
415 }
416 Self { bytes, ends }
417 }
418
419 pub fn iter(&self) -> impl Iterator<Item = (usize, u64, &[u8])> {
422 let starts = std::iter::once(0).chain(self.ends.iter().copied());
423 starts
424 .zip(self.ends.iter().copied())
425 .enumerate()
426 .filter_map(|(at, (start, end))| {
427 let line = self.bytes.get(start..end.saturating_sub(1))?;
428 (!line.is_empty()).then_some((at + 1, end as u64, line))
429 })
430 }
431
432 pub fn len(&self) -> u64 {
434 self.ends.last().map_or(0, |end| *end as u64)
435 }
436
437 pub fn tail(&self) -> &[u8] {
439 let len = usize::try_from(self.len()).unwrap_or(usize::MAX);
440 self.bytes.get(len..).unwrap_or_default()
441 }
442
443 pub fn prefix(&self, len: u64) -> &[u8] {
445 let len = usize::try_from(len.min(self.len())).unwrap_or(0);
446 self.bytes.get(..len).unwrap_or_default()
447 }
448}
449
450#[cfg(test)]
451mod tests;