1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//! The one compaction state of an agent.
//!
//! Automatic, idle, manual and tool-called compaction all reach the window
//! through this state, so there is only ever one handoff in the making: it is
//! either running in the background, landed and waiting for a request
//! boundary, or absent. Starting a compaction of any kind retires whatever
//! the state held, and a handoff forked from an older window is therefore
//! never applied on top of a newer one.
use crate::context::{CompletedCompaction, HandoffDocument, PendingCompaction};
/// Where the agent's compaction stands.
#[derive(Debug, Default)]
pub enum CompactionState {
/// No compaction is running or waiting.
#[default]
Idle,
/// A compaction forked alongside the run is still in flight.
Running(PendingCompaction),
/// A compaction finished and waits for the next request boundary.
Landed(CompletedCompaction),
}
impl CompactionState {
/// Whether a compaction is running or waiting to be applied.
pub const fn is_active(&self) -> bool {
!matches!(self, Self::Idle)
}
/// Whether a compaction is still in flight.
pub const fn is_running(&self) -> bool {
matches!(self, Self::Running(_))
}
/// Makes `pending` the compaction in flight, retiring whatever was there.
pub fn start(&mut self, pending: PendingCompaction) {
*self = Self::Running(pending);
}
/// Takes the compaction in flight out to be polled, leaving the state
/// idle until it is [`resume`](Self::resume)d or [`land`](Self::land)ed.
pub fn take_running(&mut self) -> Option<PendingCompaction> {
match std::mem::take(self) {
Self::Running(pending) => Some(pending),
other => {
*self = other;
None
}
}
}
/// Puts a compaction taken with [`take_running`](Self::take_running) back.
pub fn resume(&mut self, pending: Option<PendingCompaction>) {
if let Some(pending) = pending {
*self = Self::Running(pending);
}
}
/// Records that a compaction forked at `fork_point` finished.
pub fn land(&mut self, fork_point: u64, handoff: HandoffDocument) {
*self = Self::Landed(CompletedCompaction {
fork_point,
handoff,
});
}
/// The finished compaction, if one waits, left in place.
pub const fn landed(&self) -> Option<&CompletedCompaction> {
match self {
Self::Landed(completed) => Some(completed),
_ => None,
}
}
/// Takes the finished compaction, if one waits.
pub fn take_landed(&mut self) -> Option<CompletedCompaction> {
match std::mem::take(self) {
Self::Landed(completed) => Some(completed),
other => {
*self = other;
None
}
}
}
/// Drops any compaction in flight or waiting: it was forked from a window
/// that is about to change under it.
pub fn retire(&mut self) {
*self = Self::Idle;
}
}