Section 11 of 25

AppState, the composition root

Contents

AppState assembles the application and does nothing else. It may hold:

  • Arc<…Service> and …Handle values of slices;
  • read-only configuration;
  • a handle to the database writer.

It may not hold:

  • Mutex<Option<…>>, AtomicBool or Mutex<HashMap<…>> that describe some background process. That is actor state and belongs in core/<slice>/actor/state.rs;
  • fields that are a detail of one slice (caches, cancellation maps, queues).

Slices may not hide state in static variables either (OnceLock<Mutex<…>>, LazyLock<Mutex<…>>). The only exception is a constant computed once (OnceLock<PathBuf>) that never changes while the process lives.

The test: every field of AppState can be described with one noun from a slice ("recordings", "runs", "account"). A field that needs a sentence to describe belongs inside a slice.

pub struct AppState {
    pub paths: kit::paths::AppPaths,
    pub store: store::Store,
    pub recordings: recording::Handle,
    pub transcripts: Arc<transcript::TranscriptService>,
    pub boards: board::Handle,
    pub triggers: trigger::Handle,
    pub account: Result<Arc<account::AccountService>, account::Unavailable>,
}

11.1. kit::Jobs: one-shot background work

Generating a draft, comparing two folders or planning a task runs in the background, can be stopped, and produces one result. That does not need an actor. It needs a cancellation map, and that map belongs to the slice's service, not to AppState. kit::Jobs<K> is one concrete generic type for it:

pub struct Jobs<K> {
    next: AtomicU64,
    running: Mutex<HashMap<K, (u64, CancellationToken)>>,
}

impl<K: Eq + Hash + Clone> Jobs<K> {
    pub fn begin(&self, key: K) -> Job<K> { todo!() }
    pub fn stop(&self, key: &K) -> bool { todo!() }
}

begin cancels any earlier job with the same key, stores a new generation and returns a guard that removes the entry when it drops, but only if the generation still matches. The lock is held only inside these two short functions, never across an await. Because Jobs is a concrete type and not a trait, it does not break the rule against single-implementation traits.

This is not a loophole in the rules of section 11. They are about where state lives, not about its type. A lock inside kit::Jobs, owned by one slice's service and never held across an await, is that slice's private detail. The same map as a field of AppState is state that nobody owns.