Skip to content

feat: Add type-safe state machines for read model construction #161

@jwilger

Description

@jwilger

Context

During the implementation of multi-stream query patterns (#148), expert agents suggested using type-safe state machines for constructing read models. This would make invalid state transitions impossible at compile time.

Current State

Read models allow invalid states (e.g., ended_at without a status, or active sessions with an ended_at timestamp).

Proposed Solution

Implement type-safe state machines using phantom types:

pub struct SessionSummary<S> {
    session_id: SessionId,
    user_id: UserId,
    // ... other fields
    _state: PhantomData<S>,
}

pub struct Active;
pub struct Ended;

impl SessionSummary<Active> {
    pub fn end(self, ended_at: Timestamp, status: SessionStatus) -> SessionSummary<Ended> {
        // State transition
    }
}

impl SessionSummary<Ended> {
    // Methods only available for ended sessions
    pub fn duration(&self) -> Duration {
        // ...
    }
}

Benefits

  • Compile-time guarantees about state validity
  • Self-documenting API
  • Impossible to misuse
  • Clear state transitions

Tasks

  • Design state machines for each read model
  • Implement phantom type pattern
  • Update projection builders to use state machines
  • Add tests for state transitions
  • Document the pattern for future developers

Related

Labels

  • enhancement
  • type-safety

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions