Skip to content

Architecture: Migrate to backend-originated event emission #226

Closed

Description

@malibio

Context

Current implementation (PR #222) emits events from frontend adapters (HttpAdapter, TauriAdapter) after successful backend operations. This was a pragmatic choice to get event infrastructure working quickly, but has architectural limitations.

Current Architecture:

Backend (Rust) → Success Response → Frontend Adapter → Event Emission → EventBus

Proposed Architecture:

Backend (Rust) → Event Emission → Response with Events → Frontend Adapter → EventBus

Problem

Current Limitations:

  1. Code Duplication: Event emission logic duplicated in HttpAdapter AND TauriAdapter
  2. Inconsistency Risk: Frontend and backend states can diverge
  3. Performance: Extra GET requests before DELETE to capture metadata
  4. Limited Metadata: Frontend doesn't know what backend actually changed
  5. No Event Guarantees: If frontend crashes, events are lost

Example Inconsistency Scenario:

// Frontend thinks node was created (emitted event)
const nodeId = await createNode(data);
eventBus.emit({ type: 'node:created', nodeId }); 

// But backend actually rejected it (validation failed after response sent)
// Frontend state is now inconsistent with backend reality

Proposed Solution

Backend Event Emission

Rust backend emits events as part of operation response:

// node_endpoints.rs
pub async fn create_node(node: CreateNodeInput) -> Result<CreateNodeResponse> {
    let node_id = db.insert_node(&node)?;
    
    // Emit event
    let event = NodeEvent::Created {
        node_id: node_id.clone(),
        parent_id: node.parent_id,
        node_type: node.node_type,
    };
    
    Ok(CreateNodeResponse {
        node_id,
        events: vec![event],  // Include events in response
    })
}

Frontend adapters forward events to EventBus:

async createNode(node: NodeInput): Promise<string> {
  const response = await fetch('/api/nodes', { 
    method: 'POST', 
    body: JSON.stringify(node) 
  });
  
  const { nodeId, events } = await response.json();
  
  // Forward backend events to EventBus
  for (const event of events) {
    eventBus.emit(this.parseBackendEvent(event));
  }
  
  return nodeId;
}

Benefits

✅ Single Source of Truth: Backend controls event emission
✅ Eliminates Duplication: No frontend event logic needed
✅ Accurate Metadata: Backend knows exactly what changed
✅ Consistency: Frontend events match backend reality
✅ Performance: No extra GET before DELETE (metadata in response)

Challenges

❌ Breaking Change: Requires backend + frontend coordination
❌ IPC/HTTP Protocol Changes: Need to serialize events
❌ Event Schema Agreement: Frontend/backend must agree on types
❌ Migration Path: Can't switch atomically (need gradual migration)

Migration Strategy

Phase 1: Hybrid Approach (Backward Compatible)

Backend optionally includes events in responses:

{
  "nodeId": "abc123",
  "events": [...]  // Optional field
}

Frontend checks for backend events, falls back to local emission:

const { nodeId, events } = await response.json();

if (events && events.length > 0) {
  // Use backend events
  this.emitBackendEvents(events);
} else {
  // Fallback to frontend emission (current behavior)
  this.emitLocalEvents({ type: 'node:created', nodeId });
}

Phase 2: Backend Events Required

Once all endpoints support events, make it required:

const { nodeId, events } = await response.json();
this.emitBackendEvents(events); // No fallback

Phase 3: Remove Frontend Event Logic

Clean up all frontend event emission code.

Implementation Tasks

Backend Changes

  • Define event schema in Rust (shared types)
  • Implement event emission in NodeService
  • Include events in HTTP responses (CreateNodeResponse, etc.)
  • Add Tauri IPC support for event transmission
  • Write backend event emission tests

Frontend Changes

  • Parse backend event format
  • Forward backend events to EventBus
  • Implement hybrid fallback (Phase 1)
  • Update TypeScript event types
  • Write integration tests

Migration

  • Phase 1: Deploy hybrid approach (both systems work)
  • Phase 2: Verify all operations use backend events
  • Phase 3: Remove frontend event emission code
  • Phase 4: Update documentation

Acceptance Criteria

  • All backend operations include events in responses
  • Frontend adapters forward events to EventBus
  • All existing event tests still pass
  • No regression in event emission behavior
  • Performance equal or better (no extra GET requests)
  • TauriAdapter and HttpAdapter have identical behavior

Related Issues

Performance Impact

Current: 2 HTTP requests for delete (GET + DELETE)
After Migration: 1 HTTP request (DELETE returns events)
Improvement: 50% reduction in delete operation overhead


Priority: Medium (improves architecture but not urgent)
Complexity: High (requires backend + frontend coordination)
Estimated Impact: High (cleaner architecture, better performance)

Activity

  1. added
    enhancement
    on Oct 11, 2025
  2. malibio commented on Nov 28, 2025

    @malibio
    CollaboratorAuthor

    Closing as outdated.

    Problem Already Solved

    Events are already backend-originated - they are emitted from SurrealStore (database layer) at lines 545, 975, 1206, 1443, 1615, 1722, 1753, 1840, etc.

    Current Architecture:

    Backend (Rust SurrealStore) → Event Emission → Event Broadcast → Frontend
    

    Frontend adapters (HttpAdapter, TauriAdapter) do NOT emit events anymore - they receive events from the backend.

    Remaining Work Tracked Elsewhere

    The real remaining architectural improvement is tracked in #665:

    • Move event emission from SurrealStore (data layer) to NodeService (business logic layer)
    • Add source_client_id filtering to prevent feedback loops

    This will be possible after #676 (merge NodeOperations into NodeService) establishes a single unified business logic layer.


    Summary: Backend-originated events ✅ DONE. Client-ID filtering → See #665.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    architectureenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions