Skip to main content

subc_daemon/
activity.rs

1//! A bounded, single-writer activity ledger. File work never runs on a reader.
2
3use std::{
4    collections::{HashMap, VecDeque},
5    fs::File,
6    io::{self, BufRead, BufReader, Read, Seek, SeekFrom},
7    path::{Path, PathBuf},
8    sync::{
9        atomic::{AtomicBool, AtomicU64, Ordering},
10        Arc, Condvar, Mutex,
11    },
12    time::Instant,
13};
14
15use subc_control::{
16    ActivityActor, ActivityCursor, ActivityEntry, ActivityQueryRequest, ActivityQueryResponse,
17    ActivityRecordRequest, ACTIVITY_CURSOR_INCARNATION_MISMATCH, ACTIVITY_CURSOR_TOO_OLD,
18    ACTIVITY_KIND_FORBIDDEN, ACTIVITY_MALFORMED, ACTIVITY_RATE_LIMITED, ACTIVITY_SUBSCRIBER_LAGGED,
19    ACTIVITY_TOO_LARGE, ACTIVITY_UNAVAILABLE,
20};
21use tokio::sync::{mpsc, oneshot};
22
23const QUEUE_CAPACITY: usize = 64;
24const RING_CAPACITY: usize = 1024;
25const SUBSCRIBER_CAPACITY: usize = 256;
26
27/// Bounds include the active file, not just rotated generations.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
29#[serde(default)]
30pub struct ActivityConfig {
31    pub max_age_days: u32,
32    pub max_total_mb: u32,
33}
34
35impl Default for ActivityConfig {
36    fn default() -> Self {
37        Self {
38            max_age_days: 30,
39            max_total_mb: 64,
40        }
41    }
42}
43
44impl ActivityConfig {
45    fn retention(self) -> cortexkit_log::Retention {
46        let total = self.max_total_mb.max(1);
47        // Retention allows at most 255 rotated files. Scale the file bound for
48        // larger budgets while keeping active + rotated capacity within total.
49        let file_mb = total.div_ceil(256);
50        cortexkit_log::Retention {
51            max_file_mb: file_mb,
52            keep: (total / file_mb - 1) as u8,
53            max_age_days: self.max_age_days,
54        }
55    }
56}
57
58#[derive(Default)]
59struct SharedWriter {
60    writer: Mutex<Option<Writer>>,
61    ready: Condvar,
62    failed: AtomicBool,
63}
64
65impl SharedWriter {
66    fn lock(&self) -> Result<std::sync::MutexGuard<'_, Option<Writer>>, &'static str> {
67        let mut writer = self.writer.lock().unwrap_or_else(|p| p.into_inner());
68        while writer.is_none() {
69            if self.failed.load(Ordering::Relaxed) {
70                return Err(ACTIVITY_UNAVAILABLE);
71            }
72            writer = self.ready.wait(writer).unwrap_or_else(|p| p.into_inner());
73        }
74        Ok(writer)
75    }
76}
77
78struct Subscriber {
79    sender: mpsc::Sender<ActivityEntry>,
80    terminal: Arc<Mutex<Option<&'static str>>>,
81}
82
83pub(crate) struct ActivitySubscription {
84    pub(crate) replay: VecDeque<ActivityEntry>,
85    pub(crate) receiver: mpsc::Receiver<ActivityEntry>,
86    terminal: Arc<Mutex<Option<&'static str>>>,
87}
88
89impl ActivitySubscription {
90    pub(crate) fn terminal_code(&self) -> Option<&'static str> {
91        *self.terminal.lock().unwrap_or_else(|p| p.into_inner())
92    }
93}
94
95pub(crate) fn validate(module: &str, request: &ActivityRecordRequest) -> Result<(), &'static str> {
96    let name = request
97        .kind
98        .strip_prefix(module)
99        .and_then(|s| s.strip_prefix('.'));
100    // These daemon-owned audit kinds are not module-authored activity names.
101    let shortcut = module == "subc"
102        && matches!(
103            request.kind.as_str(),
104            "operator_shortcut" | "operator_shortcut_outcome"
105        );
106    if !shortcut && !name.is_some_and(|name| identifier(name, 64)) {
107        return Err(ACTIVITY_KIND_FORBIDDEN);
108    }
109    let summary_len = request.summary.chars().count();
110    if summary_len == 0 {
111        return Err(ACTIVITY_MALFORMED);
112    }
113    if summary_len > 200 {
114        return Err(ACTIVITY_TOO_LARGE);
115    }
116    if let Some(subject) = &request.subject {
117        if subject.subject_type.len() > 32 || subject.id.chars().count() > 256 {
118            return Err(ACTIVITY_TOO_LARGE);
119        }
120        if !identifier(&subject.subject_type, 32) || subject.id.is_empty() {
121            return Err(ACTIVITY_MALFORMED);
122        }
123    }
124    if let Some(details) = &request.details {
125        let bytes = serde_json::to_vec(details).map_err(|_| ACTIVITY_MALFORMED)?;
126        if bytes.len() > 4096 {
127            return Err(ACTIVITY_TOO_LARGE);
128        }
129    }
130    Ok(())
131}
132
133fn identifier(value: &str, max: usize) -> bool {
134    !value.is_empty()
135        && value.len() <= max
136        && value
137            .bytes()
138            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
139}
140
141struct Append {
142    module: String,
143    request: ActivityRecordRequest,
144    actor: ActivityActor,
145    at_ms: u64,
146    reply: Option<oneshot::Sender<Result<ActivityEntry, &'static str>>>,
147    lifecycle: Option<lifecycle::PendingLifecycle>,
148}
149
150/// Clones share the bounded queue and per-module rate credit until this daemon stops.
151#[derive(Clone)]
152pub(crate) struct ActivityLedger {
153    sender: mpsc::Sender<Append>,
154    read_errors: Arc<AtomicU64>,
155    shared: Arc<SharedWriter>,
156    lifecycle_counters: Arc<lifecycle::LifecycleCounters>,
157}
158
159impl std::fmt::Debug for ActivityLedger {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct("ActivityLedger").finish_non_exhaustive()
162    }
163}
164
165impl ActivityLedger {
166    pub(crate) fn read_errors(&self) -> u64 {
167        self.read_errors.load(Ordering::Relaxed)
168    }
169    #[cfg(test)]
170    pub(crate) fn remaining_capacity(&self) -> usize {
171        self.sender.capacity()
172    }
173    #[cfg(test)]
174    pub(crate) fn with_writer_lock(&self, work: impl FnOnce()) {
175        let _guard = self.shared.lock().unwrap();
176        work();
177    }
178    pub(crate) fn open(path: PathBuf, incarnation: String) -> Self {
179        Self::start(path, incarnation, QUEUE_CAPACITY, WriterHooks::default())
180    }
181
182    pub(crate) fn open_config(path: PathBuf, incarnation: String, config: ActivityConfig) -> Self {
183        Self::start_config(
184            path,
185            incarnation,
186            QUEUE_CAPACITY,
187            WriterHooks::default(),
188            config,
189        )
190    }
191
192    pub(crate) fn start(
193        path: PathBuf,
194        incarnation: String,
195        capacity: usize,
196        hooks: WriterHooks,
197    ) -> Self {
198        Self::start_config(
199            path,
200            incarnation,
201            capacity,
202            hooks,
203            ActivityConfig::default(),
204        )
205    }
206
207    fn start_config(
208        path: PathBuf,
209        incarnation: String,
210        capacity: usize,
211        hooks: WriterHooks,
212        config: ActivityConfig,
213    ) -> Self {
214        let (sender, mut receiver) = mpsc::channel::<Append>(capacity);
215        let read_errors = Arc::new(AtomicU64::new(0));
216        let writer_errors = read_errors.clone();
217        let shared = Arc::new(SharedWriter::default());
218        let worker = shared.clone();
219        // A dedicated thread also keeps filesystem stalls off Tokio's workers.
220        // Dropping the last sender ends it; shutdown never joins a stalled sink.
221        let started = std::thread::Builder::new()
222            .name("activity-writer".into())
223            .spawn(move || {
224                subc_os::protect_current_thread().expect("protect activity writer thread");
225                let writer = Writer::open(path, incarnation, hooks, &writer_errors, config);
226                let pause = writer.hooks.pause_hook();
227                *worker.writer.lock().unwrap_or_else(|p| p.into_inner()) = Some(writer);
228                worker.ready.notify_all();
229                pause.wait();
230                while let Some(append) = receiver.blocking_recv() {
231                    let mut append = append;
232                    let mut guard = worker.lock().unwrap();
233                    let writer = guard.as_mut().unwrap();
234                    match writer.prepare_lifecycle(&mut append, &writer_errors) {
235                        Ok(false) => {
236                            append.lifecycle.as_mut().unwrap().completed = true;
237                            continue;
238                        }
239                        Err(_) => continue,
240                        Ok(true) => {}
241                    }
242                    let result = writer.append(&append);
243                    if result.is_ok() {
244                        if let Some(pending) = &mut append.lifecycle {
245                            pending.completed = true;
246                        }
247                    }
248                    if let Some(reply) = append.reply.take() {
249                        let _ = reply.send(result);
250                    }
251                }
252            });
253        if let Err(error) = started {
254            tracing::warn!(%error, "activity writer unavailable");
255            let _guard = shared.writer.lock().unwrap_or_else(|p| p.into_inner());
256            shared.failed.store(true, Ordering::Relaxed);
257            shared.ready.notify_all();
258        }
259        Self {
260            sender,
261            read_errors,
262            shared,
263            lifecycle_counters: Arc::default(),
264        }
265    }
266
267    pub(crate) async fn query(
268        &self,
269        request: ActivityQueryRequest,
270    ) -> Result<ActivityQueryResponse, &'static str> {
271        let shared = self.shared.clone();
272        let errors = self.read_errors.clone();
273        tokio::task::spawn_blocking(move || {
274            let pinned = {
275                let guard = shared.lock()?;
276                guard.as_ref().unwrap().capture_read()?
277            };
278            pinned.read(request, &errors)
279        })
280        .await
281        .unwrap_or(Err(ACTIVITY_UNAVAILABLE))
282    }
283
284    pub(crate) async fn subscribe(
285        &self,
286        since: Option<ActivityCursor>,
287    ) -> Result<ActivitySubscription, &'static str> {
288        let shared = self.shared.clone();
289        tokio::task::spawn_blocking(move || shared.lock()?.as_mut().unwrap().subscribe(since))
290            .await
291            .unwrap_or(Err(ACTIVITY_UNAVAILABLE))
292    }
293
294    pub(crate) async fn configure(&self, config: ActivityConfig) -> Result<(), &'static str> {
295        let shared = self.shared.clone();
296        tokio::task::spawn_blocking(move || shared.lock()?.as_mut().unwrap().configure(config))
297            .await
298            .unwrap_or(Err(ACTIVITY_UNAVAILABLE))
299    }
300
301    pub(crate) async fn record(
302        &self,
303        module: String,
304        request: ActivityRecordRequest,
305        actor: ActivityActor,
306        at_ms: u64,
307    ) -> Result<ActivityEntry, &'static str> {
308        let (reply, received) = oneshot::channel();
309        self.sender
310            .try_send(Append {
311                module,
312                request,
313                actor,
314                at_ms,
315                reply: Some(reply),
316                lifecycle: None,
317            })
318            .map_err(|_| ACTIVITY_UNAVAILABLE)?;
319        received.await.unwrap_or(Err(ACTIVITY_UNAVAILABLE))
320    }
321}
322
323#[derive(Default)]
324pub(crate) struct WriterHooks {
325    #[cfg(test)]
326    pub(crate) open_failure: bool,
327    #[cfg(test)]
328    pub(crate) write_failure: bool,
329    #[cfg(test)]
330    pub(crate) pause: Option<Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>>,
331    #[cfg(test)]
332    pub(crate) read_pause: Option<Arc<(std::sync::Barrier, std::sync::Barrier)>>,
333    pub(crate) clock: Option<Arc<dyn Fn() -> u64 + Send + Sync>>,
334}
335
336impl WriterHooks {
337    fn pause_hook(&self) -> Self {
338        Self {
339            #[cfg(test)]
340            pause: self.pause.clone(),
341            ..Default::default()
342        }
343    }
344    fn wait(&self) {
345        #[cfg(test)]
346        if let Some(pause) = &self.pause {
347            let (lock, ready) = &**pause;
348            let mut paused = lock.lock().unwrap();
349            while *paused {
350                paused = ready.wait(paused).unwrap();
351            }
352        }
353    }
354}
355
356struct Bucket {
357    // One token is 100 ms of credit, avoiding floating-point boundary drift.
358    credit_ms: u64,
359    updated_ms: u64,
360}
361
362impl Bucket {
363    fn available(&mut self, now: u64) -> bool {
364        self.credit_ms = self
365            .credit_ms
366            .saturating_add(now.saturating_sub(self.updated_ms))
367            .min(6000);
368        self.updated_ms = self.updated_ms.max(now);
369        self.credit_ms >= 100
370    }
371}
372
373struct Writer {
374    sink: Option<cortexkit_log::LineSink>,
375    path: PathBuf,
376    config: ActivityConfig,
377    next_seq: u64,
378    first_seq: u64,
379    incarnation: String,
380    ring: VecDeque<ActivityEntry>,
381    subscribers: Vec<Subscriber>,
382    buckets: HashMap<String, Bucket>,
383    started: Instant,
384    hooks: WriterHooks,
385}
386
387impl Writer {
388    fn open(
389        path: PathBuf,
390        incarnation: String,
391        hooks: WriterHooks,
392        read_errors: &AtomicU64,
393        config: ActivityConfig,
394    ) -> Self {
395        let opened = (|| -> io::Result<_> {
396            #[cfg(test)]
397            if hooks.open_failure {
398                return Err(io::Error::other("injected open failure"));
399            }
400            let sink = open_sink(&path, config)?;
401            let highest = retained_max(&path, config.retention().keep, read_errors)?;
402            Ok((
403                sink,
404                highest
405                    .checked_add(1)
406                    .ok_or_else(|| io::Error::other("activity seq exhausted"))?,
407            ))
408        })();
409        let (sink, next_seq) = match opened {
410            Ok((sink, seq)) => (Some(sink), seq),
411            Err(error) => {
412                tracing::warn!(path = %path.display(), %error, "activity ledger unavailable");
413                (None, 1)
414            }
415        };
416        Self {
417            sink,
418            path,
419            config,
420            next_seq,
421            first_seq: next_seq,
422            incarnation,
423            ring: VecDeque::new(),
424            subscribers: Vec::new(),
425            buckets: HashMap::new(),
426            started: Instant::now(),
427            hooks,
428        }
429    }
430
431    fn append(&mut self, append: &Append) -> Result<ActivityEntry, &'static str> {
432        if append.lifecycle.is_none() {
433            validate(&append.module, &append.request)?;
434        }
435        if self.sink.is_none() || self.next_seq == u64::MAX {
436            return Err(ACTIVITY_UNAVAILABLE);
437        }
438        let now = self.hooks.clock.as_ref().map_or_else(
439            || self.started.elapsed().as_millis() as u64,
440            |clock| clock(),
441        );
442        let bucket = self.buckets.entry(append.module.clone()).or_insert(Bucket {
443            credit_ms: 6000,
444            updated_ms: now,
445        });
446        if append.lifecycle.is_none() && !bucket.available(now) {
447            return Err(ACTIVITY_RATE_LIMITED);
448        }
449        let entry = ActivityEntry {
450            seq: self.next_seq,
451            at_ms: append.at_ms,
452            daemon_incarnation: self.incarnation.clone(),
453            module: append.module.clone(),
454            kind: append.request.kind.clone(),
455            summary: append.request.summary.clone(),
456            subject: append.request.subject.clone(),
457            details: append.request.details.clone().unwrap_or_default(),
458            actor: append.actor.clone(),
459        };
460        let written = (|| -> io::Result<()> {
461            #[cfg(test)]
462            if self.hooks.write_failure {
463                return Err(io::Error::other("injected write failure"));
464            }
465            let bytes = serde_json::to_vec(&entry).map_err(io::Error::other)?;
466            self.sink
467                .as_mut()
468                .ok_or_else(|| io::Error::other("activity sink unavailable"))?
469                .write_line(&bytes)
470        })();
471        if let Err(error) = written {
472            // A partial write must not be followed by another append until reopen
473            // repairs its boundary. Failed attempts also leave rate credit intact.
474            self.sink = None;
475            tracing::warn!(kind = %entry.kind, %error, "activity append failed");
476            return Err(ACTIVITY_UNAVAILABLE);
477        }
478        if append.lifecycle.is_none() {
479            bucket.credit_ms -= 100;
480        }
481        self.next_seq += 1;
482        self.ring.push_back(entry.clone());
483        if self.ring.len() > RING_CAPACITY {
484            self.ring.pop_front();
485        }
486        self.subscribers.retain(
487            |subscriber| match subscriber.sender.try_send(entry.clone()) {
488                Ok(()) => true,
489                Err(mpsc::error::TrySendError::Full(_)) => {
490                    *subscriber
491                        .terminal
492                        .lock()
493                        .unwrap_or_else(|p| p.into_inner()) = Some(ACTIVITY_SUBSCRIBER_LAGGED);
494                    false
495                }
496                Err(mpsc::error::TrySendError::Closed(_)) => false,
497            },
498        );
499        Ok(entry)
500    }
501
502    fn subscribe(
503        &mut self,
504        since: Option<ActivityCursor>,
505    ) -> Result<ActivitySubscription, &'static str> {
506        if let Some(cursor) = &since {
507            if cursor.daemon_incarnation != self.incarnation {
508                return Err(ACTIVITY_CURSOR_INCARNATION_MISMATCH);
509            }
510            // After restart, a query's head cursor uses the new daemon's ID
511            // with the highest retained seq from the prior daemon. That cursor
512            // remains replayable until ring eviction would leave a gap; then
513            // query recovery is required rather than an incomplete replay.
514            if let Some(first) = self.ring.front() {
515                if first.seq > self.first_seq && cursor.seq.saturating_add(1) < first.seq {
516                    return Err(ACTIVITY_CURSOR_TOO_OLD);
517                }
518            }
519        }
520        let replay = self
521            .ring
522            .iter()
523            .filter(|entry| since.as_ref().is_some_and(|cursor| entry.seq > cursor.seq))
524            .cloned()
525            .collect();
526        let (sender, receiver) = mpsc::channel(SUBSCRIBER_CAPACITY);
527        let terminal = Arc::new(Mutex::new(None));
528        self.subscribers
529            .retain(|subscriber| !subscriber.sender.is_closed());
530        self.subscribers.push(Subscriber {
531            sender,
532            terminal: terminal.clone(),
533        });
534        Ok(ActivitySubscription {
535            replay,
536            receiver,
537            terminal,
538        })
539    }
540
541    fn configure(&mut self, config: ActivityConfig) -> Result<(), &'static str> {
542        if config == self.config {
543            return Ok(());
544        }
545        let sink = open_sink(&self.path, config).map_err(|error| {
546            tracing::warn!(%error, "activity retention update failed");
547            ACTIVITY_UNAVAILABLE
548        })?;
549        self.sink = Some(sink);
550        self.config = config;
551        Ok(())
552    }
553
554    fn capture_read(&self) -> Result<ActivityRead, &'static str> {
555        if self.sink.is_none() {
556            return Err(ACTIVITY_UNAVAILABLE);
557        }
558        let mut files = Vec::new();
559        for generation in 0..=self.config.retention().keep {
560            match File::open(generation_path(&self.path, generation)) {
561                Ok(file) => {
562                    let len = file.metadata().map_err(|_| ACTIVITY_UNAVAILABLE)?.len();
563                    files.push((file, len));
564                }
565                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
566                Err(_) => return Err(ACTIVITY_UNAVAILABLE),
567            }
568        }
569        Ok(ActivityRead {
570            files,
571            #[cfg(test)]
572            read_pause: self.hooks.read_pause.clone(),
573            head: ActivityCursor {
574                daemon_incarnation: self.incarnation.clone(),
575                seq: self.next_seq - 1,
576            },
577        })
578    }
579}
580
581struct ActivityRead {
582    files: Vec<(File, u64)>,
583    head: ActivityCursor,
584    #[cfg(test)]
585    read_pause: Option<Arc<(std::sync::Barrier, std::sync::Barrier)>>,
586}
587
588impl ActivityRead {
589    fn read(
590        self,
591        request: ActivityQueryRequest,
592        read_errors: &AtomicU64,
593    ) -> Result<ActivityQueryResponse, &'static str> {
594        #[cfg(test)]
595        if let Some(pause) = &self.read_pause {
596            pause.0.wait();
597            pause.1.wait();
598        }
599        let mut entries = Vec::new();
600        for (file, len) in self.files {
601            for line in BufReader::new(file.take(len)).split(b'\n') {
602                let line = line.map_err(|_| ACTIVITY_UNAVAILABLE)?;
603                let entry: ActivityEntry = match serde_json::from_slice(&line) {
604                    Ok(entry) => entry,
605                    Err(error) => {
606                        read_errors.fetch_add(1, Ordering::Relaxed);
607                        tracing::warn!(%error, "skipping unparseable activity line");
608                        continue;
609                    }
610                };
611                if request
612                    .agent
613                    .as_ref()
614                    .is_some_and(|v| entry.actor.agent_id.as_ref() != Some(v))
615                    || request
616                        .project
617                        .as_ref()
618                        .is_some_and(|v| entry.actor.project_root.as_ref() != Some(v))
619                    || request.module.as_ref().is_some_and(|v| &entry.module != v)
620                    || request.kind.as_ref().is_some_and(|v| &entry.kind != v)
621                    || request.since_ms.is_some_and(|v| entry.at_ms < v)
622                    || request.until_ms.is_some_and(|v| entry.at_ms > v)
623                    || request.cursor.is_some_and(|v| entry.seq >= v)
624                {
625                    continue;
626                }
627                entries.push(entry);
628            }
629        }
630        entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.seq));
631        entries.truncate(request.limit as usize);
632        Ok(ActivityQueryResponse {
633            cursor: entries.last().map(|entry| entry.seq),
634            head: self.head,
635            entries,
636        })
637    }
638}
639
640fn open_sink(path: &Path, config: ActivityConfig) -> io::Result<cortexkit_log::LineSink> {
641    let mut sink = cortexkit_log::LineSink::open(path, config.retention())?;
642    // A killed append without a trailing newline must not join the next valid
643    // record into one unparseable line. Add the missing separator on reopen.
644    let mut file = File::open(path)?;
645    if file.metadata()?.len() > 0 {
646        file.seek(SeekFrom::End(-1))?;
647        let mut last = [0];
648        file.read_exact(&mut last)?;
649        if last[0] != b'\n' {
650            sink.write_line(b"")?;
651        }
652    }
653    Ok(sink)
654}
655
656fn generation_path(path: &Path, generation: u8) -> PathBuf {
657    let mut name = path.as_os_str().to_owned();
658    if generation != 0 {
659        name.push(format!(".{generation}"));
660    }
661    PathBuf::from(name)
662}
663
664fn retained_max(path: &Path, keep: u8, read_errors: &AtomicU64) -> io::Result<u64> {
665    let mut highest = 0;
666    for generation in 0..=keep {
667        let file = match File::open(generation_path(path, generation)) {
668            Ok(file) => file,
669            Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
670            Err(error) => return Err(error),
671        };
672        for line in BufReader::new(file).split(b'\n') {
673            match serde_json::from_slice::<ActivityEntry>(&line?) {
674                Ok(entry) => highest = highest.max(entry.seq),
675                Err(error) => {
676                    read_errors.fetch_add(1, Ordering::Relaxed);
677                    tracing::warn!(%error, "skipping unparseable activity line");
678                }
679            }
680        }
681    }
682    Ok(highest)
683}
684
685#[cfg(test)]
686#[path = "activity_tests.rs"]
687mod tests;
688
689#[path = "activity_lifecycle.rs"]
690mod lifecycle;
691
692pub(crate) use lifecycle::{ExecOutcome, ExecOwner, ExecState, ImageFacts, RegistrationImage};
693
694#[cfg(test)]
695#[path = "activity_lifecycle_tests.rs"]
696mod lifecycle_tests;