Skip to content

Create HTTP dev server for web-mode testing with real database access #209

Closed

Description

@malibio

Context

Issue #208 requires comprehensive testing against real services (not mocks) with real database access. However, there's currently an architecture gap:

Current State:

  • bun run tauri:dev (port 1420): Tauri app with Rust backend via IPC + real database
  • bun run dev (port 1420): Web-only mode with NO backend access, mocked services

Problem:

  • Tests need real database access to catch regressions
  • Web mode (bun run dev) has no way to access Rust backend/database
  • AI agents with MCP DevTools can't inspect same data as Tauri app

Solution: HTTP Dev Server

Create a development-only HTTP server that exposes the same Rust backend as REST APIs.

Architecture

Development Mode:
├─ Port 1420: Vite dev server (frontend)
│  ├─ bun run tauri:dev → uses Tauri IPC adapter
│  └─ bun run dev → uses HTTP adapter (port 3001)
├─ Port 3001: HTTP dev server (Rust backend mirror)
│  └─ Only runs in development, NOT in production

Production Mode:
└─ Tauri app only (IPC, no HTTP server)

Scope of This Issue

This issue is responsible for:

Future endpoint expansion (NOT in this issue):

Implementation Decisions (Clarified)

1. HTTP Framework

Decision: Use axum (modern, ergonomic, tokio-integrated)

2. Database Strategy

Decision: Separate test database to avoid conflicts

  • Default: ~/.nodespace/database/nodespace-dev.db
  • Tests can pass custom paths via ?db_path= query parameter
  • Prevents conflicts with running Tauri app
  • Enables test isolation and cleanup

3. Server Lifecycle

Decision: Manual start via bun run dev:server

  • Simpler to implement and debug
  • Developers control when it runs
  • Tests can start/stop server as needed
  • Future: Can add auto-start once stable

4. Adapter Auto-Detection

Decision: Runtime detection based on window.__TAURI__

export function getBackendAdapter(): BackendAdapter {
  if (typeof window !== 'undefined' && window.__TAURI__) {
    return new TauriAdapter(); // Uses invoke()
  } else {
    return new HttpAdapter(); // Uses fetch to port 3001
  }
}

5. Implementation Scope

Decision: Phase 1 MVP only - future phases add their own endpoints

Implementation Tasks

1. Examine Existing Code

  • Review packages/desktop-app/src-tauri/src/commands/nodes.rs
  • Review packages/desktop-app/src-tauri/src/commands/db.rs
  • Review packages/desktop-app/src-tauri/src/lib.rs for all registered commands
  • Document command signatures for HTTP endpoint design

2. Create HTTP Dev Server Infrastructure (Rust)

  • Add axum, tower-http (CORS) dependencies to Cargo.toml
  • Create packages/desktop-app/src-tauri/src/dev_server/mod.rs (main module)
  • Create packages/desktop-app/src-tauri/src/dev_server/node_endpoints.rs (Phase 1 only)
  • Create packages/desktop-app/src-tauri/src/bin/dev-server.rs (separate binary)
  • Add dev-server feature flag to Cargo.toml

Server Infrastructure:

  • Main router setup with modular endpoint organization
  • CORS middleware for localhost:1420
  • Error handling middleware
  • JSON response helpers
  • Database state management (Arc)
  • Listen on port 3001 (configurable via DEV_SERVER_PORT)

Phase 1 Endpoints (in node_endpoints.rs):

  • POST /api/database/init?db_path= → initialize_database
  • POST /api/nodes → create_node
  • GET /api/nodes/:id → get_node
  • PATCH /api/nodes/:id → update_node
  • DELETE /api/nodes/:id → delete_node
  • GET /api/nodes/:id/children → get_children

Server Configuration:

  • Only compiles with --features dev-server
  • Proper HTTP status codes (200, 404, 400, 500)
  • JSON error responses matching Tauri's CommandError structure
  • Request/response logging for debugging

3. Organize for Future Expansion

Create modular structure for Phase 2/3 to add endpoints:

// src/dev_server/mod.rs
mod node_endpoints;        // Phase 1 (this issue)
// mod query_endpoints;    // Phase 2 (added by #211)
// mod embedding_endpoints; // Phase 3 (added by #212)

pub fn create_router(db: Arc<DatabaseService>, node_service: Arc<NodeService>) -> Router {
    Router::new()
        .merge(node_endpoints::routes(db.clone(), node_service.clone()))
        // Future phases add .merge() calls here
}
  • Create modular structure with clear extension points
  • Document how future phases should add endpoints
  • Leave commented placeholders for Phase 2/3 modules

4. Create Backend Adapter Pattern (TypeScript)

  • Create packages/desktop-app/src/lib/services/backend-adapter.ts
  • Define BackendAdapter interface with Phase 1 operations only
  • Implement TauriAdapter (uses invoke() for IPC)
  • Implement HttpAdapter (uses fetch() to port 3001)
  • Implement getBackendAdapter() with runtime detection
  • Export factory function for easy usage
  • Document how to extend interface for future phases

5. Update Frontend Services

  • Update ReactiveNodeService to use BackendAdapter
  • Replace direct invoke() calls with adapter pattern
  • Ensure backward compatibility with production builds
  • Handle adapter errors gracefully

6. Update Test Infrastructure

  • Update packages/desktop-app/src/tests/setup.ts
  • Configure tests to use HTTP adapter by default
  • Create test database utilities:
    • createTestDatabase(testName: string) - Returns unique DB path
    • cleanupTestDatabase(dbPath: string) - Deletes test DB
    • initializeTestDatabase(dbPath: string) - Calls init endpoint
  • Create TestNodeBuilder helper for scenario seeding
  • Add test fixtures for common node structures

7. Documentation & Scripts

  • Document HTTP dev server architecture in /docs/architecture/testing/http-dev-server.md
  • Document how to extend server for Phase 2/3 endpoints
  • Update testing guide with adapter pattern usage
  • Document Phase 1 endpoint API with curl examples
  • Add package.json scripts:
    • bun run dev:server - Start HTTP dev server
  • Add README in src-tauri/src/dev_server/ with:
    • Architecture overview
    • How to add endpoints for future phases
    • Testing guidelines

8. Validation

Acceptance Criteria

Core Functionality

  • HTTP dev server runs on port 3001 when started manually
  • Phase 1 MVP endpoints implemented and working
  • bun run dev (web mode) can access real database via HTTP adapter
  • bun run tauri:dev still uses Tauri IPC (no HTTP server)
  • Production builds do NOT include HTTP server code

Infrastructure Quality

  • Modular structure ready for Phase 2/3 expansion
  • Clear documentation for adding endpoints
  • Error handling consistent and robust
  • CORS properly configured

Adapter Pattern

  • Backend adapter properly abstracts Tauri vs HTTP
  • Runtime detection works correctly
  • Error handling consistent between adapters
  • TypeScript types fully defined
  • Easy to extend for future phases

Testing Infrastructure

  • Tests can use HTTP adapter to access real backend
  • Test database utilities work correctly
  • Database isolation between tests
  • Cleanup happens reliably

Documentation

  • Architecture documented
  • Phase 1 API endpoints documented with examples
  • Extension guide for Phase 2/3 documented
  • Testing guide updated
  • No breaking changes to existing functionality

Success Metrics

  • Phase 1 tests (Phase 1: Core + Hierarchy Operations Test Coverage (Sections 1-5, 51 tests) #210) can immediately start development
  • Server starts in <2 seconds
  • Endpoint response time <50ms for simple operations
  • Web mode (bun run dev) has same core functionality as Tauri mode
  • AI agents with DevTools MCP can inspect real database state
  • Zero performance impact on production builds
  • Phase 2/3 can easily add endpoints without refactoring

Related Issues

Implementation Notes

Security Considerations

  • HTTP server only compiles with dev-server feature
  • CORS restricted to localhost
  • No authentication needed (local development only)
  • Never runs in production

Error Handling

  • Mirror Tauri's CommandError structure in HTTP responses
  • Use proper HTTP status codes (404, 400, 500)
  • Return JSON errors with same format as Tauri
  • Include debug info in development

Performance

  • HTTP overhead negligible for development (~few ms per request)
  • No impact on production (code not compiled)
  • Async/await throughout for non-blocking operations

Code Organization for Multi-Phase Development

src/dev_server/
├─ mod.rs              # Main router, CORS, error handling
├─ node_endpoints.rs   # Phase 1 (this issue)
├─ query_endpoints.rs  # Phase 2 (added by #211)
└─ embedding_endpoints.rs # Phase 3 (added by #212)

Each phase adds their module with minimal conflicts.

Port Configuration

  • Default: 3001
  • Override via DEV_SERVER_PORT=3001
  • Document in testing guide

Activity

  1. self-assigned this
    on Oct 11, 2025
  2. 5 remaining items

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