Skip to content

Centralize Domain Event Emission with Type-Safe Node Payloads #718

Closed

Description

@malibio

Overview

Refactor the domain event emission architecture to centralize change detection at the store layer with automatic notification, emit strongly-typed node payloads (TaskNode, SchemaNode, etc.), and solve the client_id tracking problem for shared NodeService singleton.

Architectural Discussion Summary

After extensive review with senior-architect-reviewer, we've identified critical issues with the current approach and designed a refined solution.

Current Architecture Problems

  1. Manual Emission Burden: 14+ emit_event() call sites scattered across NodeService methods
  2. Complex Method Risk: Methods with multiple store operations require tracking each change manually
  3. Client ID Tracking: Current client_id field doesn't work with shared singleton NodeService
  4. Forgetting to Emit: No compile-time guarantee that mutations emit events
  5. Type Mismatch: DomainEvent previously carried generic Node struct, consumers needed type-specific data

Refined Solution: Store-Level Automatic Notification

Based on architectural review, we're adopting a store-level automatic notification pattern that eliminates manual emission entirely.

Architecture Design

Layer 1: Store Change Detection

// packages/core/src/db/surreal_store.rs

pub enum StoreOperation {
    Created,
    Updated,
    Deleted,
}

pub struct StoreChange {
    pub operation: StoreOperation,
    pub node: Node,
    pub source: Option<String>,  // Optional for MVP (not persisted)
}

pub struct SurrealStore {
    db: Surreal<Db>,
    notifier: Option<Arc<dyn Fn(StoreChange) + Send + Sync>>,
}

impl SurrealStore {
    pub fn register_notifier<F>(&mut self, notifier: F)
    where F: Fn(StoreChange) + Send + Sync + 'static
    {
        self.notifier = Some(Arc::new(notifier));
    }
    
    async fn create_node(&self, node: Node, source: Option<String>) -> Result<Node> {
        // DB operation
        let created = self.db.create(("nodes", node.id.as_str())).content(node.clone()).await?;
        
        // ✅ Store automatically notifies on every mutation
        if let Some(notifier) = &self.notifier {
            notifier(StoreChange {
                operation: StoreOperation::Created,
                node: created.clone(),
                source,
            });
        }
        
        Ok(created)
    }
    
    // Same pattern for update_node, delete_node, etc.
}

Layer 2: NodeService Registration & Broadcast

// packages/core/src/services/node_service.rs

impl NodeService {
    pub async fn new(mut store: Arc<SurrealStore>) -> Result<Self> {
        let (event_tx, _) = broadcast::channel(128);
        
        // ✅ Register ONE centralized handler for ALL store changes
        let event_tx_clone = event_tx.clone();
        store.register_notifier(move |change: StoreChange| {
            let node_data = node_to_typed_value(&change.node)
                .unwrap_or_else(|_| serde_json::to_value(&change.node).unwrap());
            
            let event = match change.operation {
                StoreOperation::Created => DomainEvent::NodeCreated {
                    node_id: change.node.id.clone(),
                    node_data,
                    source_client_id: change.source,
                },
                StoreOperation::Updated => DomainEvent::NodeUpdated {
                    node_id: change.node.id.clone(),
                    node_data,
                    source_client_id: change.source,
                },
                StoreOperation::Deleted => DomainEvent::NodeDeleted {
                    id: change.node.id.clone(),
                    source_client_id: change.source,
                },
            };
            
            let _ = event_tx_clone.send(event);
        });
        
        Ok(Self { store, event_tx, /* ... */ })
    }
    
    // ✅ Methods just call store - NO manual emission!
    async fn create_node(&self, node: Node, source: Option<String>) -> Result<String> {
        let created = self.store.create_node(node, source).await?;
        // Events emitted automatically by store notification!
        Ok(created.id)
    }
}

Layer 3: Client Usage

// Each client passes their identifier per-request

// MCP Handler
let node_id = node_service.create_node(node, Some("mcp".to_string())).await?;

// Tauri Command
let node_id = node_service.create_node(node, Some("tauri".to_string())).await?;

// Proxy Server
let node_id = node_service.create_node(node, Some("proxy".to_string())).await?;

// Tests (no source needed)
let node_id = node_service.create_node(node, None).await?;

Layer 4: Event Subscription & SSE

┌─────────────────────────────────────────┐
│ Clients Subscribe to DomainEvents       │
│ - MCP: No subscription (doesn't need)   │
│ - Tauri: Subscribes for window updates  │
│ - Proxy: Subscribes, forwards via SSE   │
│ - CloudSync: Subscribes for sync        │
└─────────────────────────────────────────┘
         ↓ (Proxy forwards)
┌─────────────────────────────────────────┐
│ SSE → Multiple Browsers                 │
│ (All browsers treated as one client)    │
└─────────────────────────────────────────┘

Benefits

1. Automatic Emission (Can't Forget)

async fn complex_business_logic(&self, params: Params) -> Result<()> {
    // Multiple operations - all automatically emit events!
    self.store.update_node(&id_a, update_a, source.clone()).await?;
    
    if should_create_child() {
        self.store.create_node(child, source.clone()).await?;
    }
    
    for id in obsolete_ids {
        self.store.delete_node(&id, source.clone()).await?;
    }
    
    // ✅ All events emitted automatically!
    // ✅ No manual tracking needed!
}

2. Maintenance Reduction

  • Current: 14+ manual emit sites → Proposed: 0 manual emit sites
  • Current: ~150 lines of emit boilerplate → Proposed: ~20 lines setup
  • 87% reduction in emission-related code

3. Type-Safe Payloads

  • DomainEvent carries serde_json::Value with typed data
  • TaskNode has flat status/priority fields (not nested in properties)
  • Consumers receive ready-to-use data (no conversion needed)

4. Testing Confidence

  • If store was called → event was emitted (guaranteed)
  • Tests focus on WHAT changed, not IF notification happened
  • Single point of failure (notifier setup) vs 14+ potential failure points

Implementation Plan

Phase 1: Store Infrastructure ✅

  • Update DomainEvent to use serde_json::Value (completed)
  • Add StoreChange struct to surreal_store.rs
  • Add register_notifier() method to SurrealStore
  • Update all store mutation methods to call notifier

Phase 2: NodeService Integration

  • Register notifier in NodeService::new()
  • Remove all manual emit_event() calls from methods
  • Update method signatures to accept source: Option<String> parameter
  • Remove emit_node_created() and emit_node_updated() helper methods

Phase 3: Client Updates

  • Update MCP handlers to pass Some("mcp")
  • Update Tauri commands to pass Some("tauri")
  • Update Proxy handlers to pass Some("proxy")
  • Update tests to pass None

Phase 4: Testing & Verification

  • Update event emission tests for new structure
  • Add test verifying automatic notification
  • Verify all 740 Rust tests pass
  • Verify all 1546 frontend tests pass

Acceptance Criteria

  • DomainEvent::NodeCreated and NodeUpdated carry serde_json::Value instead of Node ✅
  • Store methods automatically notify on mutations (via registered callback)
  • NodeService registers ONE centralized notification handler
  • Zero manual emit_event() calls in NodeService methods
  • All store methods accept source: Option<String> parameter
  • SSE events contain type-specific data (TaskNode has flat status, not properties.status)
  • All existing tests pass
  • MCP→Store→Notification→SSE→UI reactivity works end-to-end

Technical Specifications

Files to Modify

Core Changes:

  • packages/core/src/db/events.rs - DomainEvent enum (✅ completed)
  • packages/core/src/db/surreal_store.rs - Add notification system
  • packages/core/src/services/node_service.rs - Remove manual emits, register handler

Test Updates:

  • packages/core/tests/event_emission_test.rs - Update for new structure (✅ completed)

Future Integration (not in scope):

  • dev-proxy SSE bridge (not implemented yet)
  • Frontend BrowserSyncService (not implemented yet)

Architectural Decision Rationale

Why Store-Level Notification?

  1. Scale: As business logic grows complex (50+ methods, 100+ emission sites), manual tracking becomes unsustainable
  2. Safety: Can't forget to emit - store automatically notifies on every mutation
  3. Industry Pattern: Similar to database triggers, RocksDB EventListener, event sourcing systems
  4. Separation: Store reports facts ("node created"), NodeService interprets domain meaning ("broadcast to all except source")
  5. Testing: Guaranteed emission improves test reliability

Why NOT Store Notification (Concerns Addressed):

  • ❌ "Store knows about domain events" → ✅ Store only knows generic StoreChange, not DomainEvent
  • ❌ "Callback complexity" → ✅ One-time setup, never touched after
  • ❌ "Wrong layer" → ✅ Change detection IS a store concern (like DB triggers)
  • ❌ "Client coupling" → ✅ source is optional metadata, not business logic

Design Principles:

  • Store = Persistence + Change Detection (infrastructure)
  • NodeService = Business Logic + Event Broadcasting (domain)
  • Clients = Event Consumers (application)

Related Issues

Non-Goals

  • Persisting source field to database (MVP is single-user)
  • Changing EdgeCreated/EdgeUpdated/EdgeDeleted events
  • Adding new event types
  • Modifying the broadcast channel mechanism

Notes

  • SSE bridge and BrowserSyncService mentioned in original issue don't exist yet
  • Implementation focuses on backend refactor (store notification + typed payloads)
  • Frontend integration will happen when SSE/Tauri event forwarding is implemented

Activity

  1. malibio commented on Dec 3, 2025

    @malibio
    CollaboratorAuthor

    Test baseline established: Frontend - 1546 tests passed (75 test files), Rust - 740 tests passed (16 ignored)

  2. self-assigned this
    on Dec 3, 2025
  3. malibio commented on Dec 3, 2025

    @malibio
    CollaboratorAuthor

    WIP commit created with Phase 1 complete and architectural decisions documented. See commit 28bec02 for handoff context. Next session should implement store-level automatic notification (Phases 2-5).

  4. added 3 commits that reference this issue on Dec 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions