Skip to content

Add HTTP Adapter Support for SchemaService #386

Closed

Description

@malibio

Add HTTP Adapter Support for SchemaService

Problem

The SchemaService now has working Tauri commands (Issue #388), but it still bypasses the BackendAdapter pattern. This creates an architectural inconsistency and prevents browser-based development/testing.

Current State (After #388):

  • ✅ NodeService, EmbeddingService - Use BackendAdapter pattern (work in both Tauri and HTTP modes)
  • ❌ SchemaService - Directly calls Tauri invoke() commands (Tauri-only, no HTTP mode)

Impact:

  • Cannot test schema operations in browser/HTTP mode
  • Cannot develop schema UI components without running Tauri
  • Inconsistent with project architecture patterns
  • Browser mode only has static mock data for getSchema(), no real backend

Background: The BackendAdapter Pattern

NodeSpace uses a Backend Adapter Pattern to support two runtime environments:

  1. Tauri Mode (Desktop App): Uses IPC via invoke() → Rust Tauri commands
  2. HTTP Mode (Browser/Testing): Uses REST API via fetch() → dev server on port 3001

Both adapters implement the same BackendAdapter interface, providing seamless environment switching.

Current Architecture (After #388)

Tauri Commands Now Exist ✅

// packages/desktop-app/src/lib/services/schema-service.ts
async getSchema(schemaId: string): Promise<SchemaDefinition> {
  const result = await invoke<SchemaDefinition>(
    'get_schema_definition',  // ← Real Tauri command (created by #388)
    { schemaId }
  );
  return result;
}

Backend Implementation:

// packages/desktop-app/src-tauri/src/commands/schemas.rs
#[tauri::command]
pub async fn get_schema_definition(
    service: State<'_, SchemaService>,
    schema_id: String,
) -> Result<SchemaDefinition, CommandError> {
    service.get_schema(&schema_id).await.map_err(Into::into)
}

Problem: No BackendAdapter Integration

SchemaService does not use the adapter pattern:

  • Directly calls invoke() instead of going through BackendAdapter
  • Cannot switch to HTTP mode for browser testing
  • Inconsistent with how NodeService and EmbeddingService work

Solution

Integrate SchemaService with the BackendAdapter pattern:

  1. Add 5 schema methods to BackendAdapter interface
  2. Implement in TauriAdapter (calls the Tauri commands from Implement Missing Tauri Commands for Schema Operations #388)
  3. Implement in HttpAdapter (calls HTTP endpoints - to be created)
  4. Create HTTP endpoints in Rust dev server
  5. Refactor SchemaService to use getBackendAdapter() instead of direct invoke()

Implementation Guide

Phase 1: Add Schema Methods to BackendAdapter Interface

File: packages/desktop-app/src/lib/services/backend-adapter.ts

Add 5 methods to the BackendAdapter interface (around line 230):

export interface BackendAdapter {
  // ... existing methods ...

  // === Schema Management Operations ===

  getSchema(schemaId: string): Promise<SchemaDefinition>;
  addSchemaField(schemaId: string, config: AddFieldConfig): Promise<AddFieldResult>;
  removeSchemaField(schemaId: string, fieldName: string): Promise<RemoveFieldResult>;
  extendSchemaEnum(schemaId: string, fieldName: string, value: string): Promise<ExtendEnumResult>;
  removeSchemaEnumValue(schemaId: string, fieldName: string, value: string): Promise<RemoveEnumValueResult>;
}

Add type imports:

import type {
  SchemaDefinition,
  AddFieldConfig,
  AddFieldResult,
  RemoveFieldResult,
  ExtendEnumResult,
  RemoveEnumValueResult
} from '$lib/types/schema';

Phase 2: Implement Schema Methods in TauriAdapter

File: packages/desktop-app/src/lib/services/backend-adapter.ts

Add implementations to TauriAdapter class that call the Tauri commands from #388:

class TauriAdapter implements BackendAdapter {
  // ... existing methods ...

  async getSchema(schemaId: string): Promise<SchemaDefinition> {
    try {
      return await invoke<SchemaDefinition>('get_schema_definition', {
        schemaId  // Tauri command created by #388
      });
    } catch (error) {
      throw toError(error, 'getSchema');
    }
  }

  async addSchemaField(schemaId: string, config: AddFieldConfig): Promise<AddFieldResult> {
    try {
      const result = await invoke<{
        schema_id: string;
        new_version: number;
      }>('add_schema_field', {
        schemaId,
        field: {
          name: config.fieldName,
          fieldType: config.fieldType,
          indexed: config.indexed ?? false,
          required: config.required,
          default: config.default,
          description: config.description,
          itemType: config.itemType,
          enumValues: config.enumValues,
          extensible: config.extensible
        }
      });

      return {
        schemaId: result.schema_id,
        newVersion: result.new_version,
        success: true
      };
    } catch (error) {
      throw toError(error, 'addSchemaField');
    }
  }

  async removeSchemaField(schemaId: string, fieldName: string): Promise<RemoveFieldResult> {
    try {
      const result = await invoke<{
        schema_id: string;
        new_version: number;
      }>('remove_schema_field', {
        schemaId,
        fieldName
      });

      return {
        schemaId: result.schema_id,
        newVersion: result.new_version,
        success: true
      };
    } catch (error) {
      throw toError(error, 'removeSchemaField');
    }
  }

  async extendSchemaEnum(schemaId: string, fieldName: string, value: string): Promise<ExtendEnumResult> {
    try {
      const result = await invoke<{
        schema_id: string;
        new_version: number;
      }>('extend_schema_enum', {
        schemaId,
        fieldName,
        value
      });

      return {
        schemaId: result.schema_id,
        newVersion: result.new_version,
        success: true
      };
    } catch (error) {
      throw toError(error, 'extendSchemaEnum');
    }
  }

  async removeSchemaEnumValue(
    schemaId: string,
    fieldName: string,
    value: string
  ): Promise<RemoveEnumValueResult> {
    try {
      const result = await invoke<{
        schema_id: string;
        new_version: number;
      }>('remove_schema_enum_value', {
        schemaId,
        fieldName,
        value
      });

      return {
        schemaId: result.schema_id,
        newVersion: result.new_version,
        success: true
      };
    } catch (error) {
      throw toError(error, 'removeSchemaEnumValue');
    }
  }
}

Key Pattern: TauriAdapter now calls the real Tauri commands (not mcp_call_tool).


Phase 3: Implement Schema Methods in HttpAdapter

File: packages/desktop-app/src/lib/services/backend-adapter.ts

Add HTTP implementations to HttpAdapter class:

class HttpAdapter implements BackendAdapter {
  // ... existing methods ...

  async getSchema(schemaId: string): Promise<SchemaDefinition> {
    return await this.retryOnTransientError(async () => {
      const response = await globalThis.fetch(
        `${this.baseUrl}/api/schemas/${encodeURIComponent(schemaId)}`,
        {
          method: 'GET',
          headers: { 'Content-Type': 'application/json' }
        }
      );

      return await this.handleResponse<SchemaDefinition>(response);
    });
  }

  async addSchemaField(schemaId: string, config: AddFieldConfig): Promise<AddFieldResult> {
    return await this.retryOnTransientError(async () => {
      const response = await globalThis.fetch(
        `${this.baseUrl}/api/schemas/${encodeURIComponent(schemaId)}/fields`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(config)
        }
      );

      return await this.handleResponse<AddFieldResult>(response);
    });
  }

  async removeSchemaField(schemaId: string, fieldName: string): Promise<RemoveFieldResult> {
    return await this.retryOnTransientError(async () => {
      const response = await globalThis.fetch(
        `${this.baseUrl}/api/schemas/${encodeURIComponent(schemaId)}/fields/${encodeURIComponent(fieldName)}`,
        {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' }
        }
      );

      return await this.handleResponse<RemoveFieldResult>(response);
    });
  }

  async extendSchemaEnum(
    schemaId: string,
    fieldName: string,
    value: string
  ): Promise<ExtendEnumResult> {
    return await this.retryOnTransientError(async () => {
      const response = await globalThis.fetch(
        `${this.baseUrl}/api/schemas/${encodeURIComponent(schemaId)}/fields/${encodeURIComponent(fieldName)}/enum-values`,
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ value })
        }
      );

      return await this.handleResponse<ExtendEnumResult>(response);
    });
  }

  async removeSchemaEnumValue(
    schemaId: string,
    fieldName: string,
    value: string
  ): Promise<RemoveEnumValueResult> {
    return await this.retryOnTransientError(async () => {
      const response = await globalThis.fetch(
        `${this.baseUrl}/api/schemas/${encodeURIComponent(schemaId)}/fields/${encodeURIComponent(fieldName)}/enum-values/${encodeURIComponent(value)}`,
        {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' }
        }
      );

      return await this.handleResponse<RemoveEnumValueResult>(response);
    });
  }
}

HTTP Endpoint URLs:

  • GET /api/schemas/:schemaId - Get schema
  • POST /api/schemas/:schemaId/fields - Add field
  • DELETE /api/schemas/:schemaId/fields/:fieldName - Remove field
  • POST /api/schemas/:schemaId/fields/:fieldName/enum-values - Extend enum
  • DELETE /api/schemas/:schemaId/fields/:fieldName/enum-values/:value - Remove enum value

Phase 4: Create Rust HTTP Endpoints

File (NEW): packages/desktop-app/src-tauri/src/dev_server/schema_endpoints.rs

Create HTTP endpoints that call the existing Tauri command implementations:

use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};
use serde::{Deserialize, Serialize};
use crate::SchemaService;

// GET /api/schemas/:schema_id
pub async fn get_schema(
    Path(schema_id): Path<String>,
    State(service): State<Arc<SchemaService>>,
) -> Result<Json<SchemaDefinition>, (StatusCode, String)> {
    let schema = service
        .get_schema(&schema_id)
        .await
        .map_err(|e| (StatusCode::NOT_FOUND, e.to_string()))?;

    Ok(Json(schema))
}

// POST /api/schemas/:schema_id/fields
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddFieldRequest {
    field_name: String,
    field_type: String,
    indexed: Option<bool>,
    required: Option<bool>,
    default: Option<serde_json::Value>,
    description: Option<String>,
    item_type: Option<String>,
    enum_values: Option<Vec<String>>,
    extensible: Option<bool>,
}

pub async fn add_field(
    Path(schema_id): Path<String>,
    State(service): State<Arc<SchemaService>>,
    Json(request): Json<AddFieldRequest>,
) -> Result<Json<AddFieldResult>, (StatusCode, String)> {
    let field = SchemaField {
        name: request.field_name,
        field_type: request.field_type,
        // ... construct field from request
    };

    service
        .add_field(&schema_id, field)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;

    Ok(Json(AddFieldResult {
        schema_id,
        new_version: /* get from service */,
        success: true,
    }))
}

// DELETE /api/schemas/:schema_id/fields/:field_name
pub async fn remove_field(
    Path((schema_id, field_name)): Path<(String, String)>,
    State(service): State<Arc<SchemaService>>,
) -> Result<Json<RemoveFieldResult>, (StatusCode, String)> {
    service
        .remove_field(&schema_id, &field_name)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;

    Ok(Json(RemoveFieldResult {
        schema_id,
        new_version: /* get from service */,
        success: true,
    }))
}

// POST /api/schemas/:schema_id/fields/:field_name/enum-values
pub async fn extend_enum(
    Path((schema_id, field_name)): Path<(String, String)>,
    State(service): State<Arc<SchemaService>>,
    Json(payload): Json<serde_json::Value>,
) -> Result<Json<ExtendEnumResult>, (StatusCode, String)> {
    let value = payload["value"]
        .as_str()
        .ok_or((StatusCode::BAD_REQUEST, "Missing 'value' field".to_string()))?;

    service
        .extend_enum_field(&schema_id, &field_name, value.to_string())
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;

    Ok(Json(ExtendEnumResult {
        schema_id,
        new_version: /* get from service */,
        success: true,
    }))
}

// DELETE /api/schemas/:schema_id/fields/:field_name/enum-values/:value
pub async fn remove_enum_value(
    Path((schema_id, field_name, value)): Path<(String, String, String)>,
    State(service): State<Arc<SchemaService>>,
) -> Result<Json<RemoveEnumValueResult>, (StatusCode, String)> {
    service
        .remove_enum_value(&schema_id, &field_name, &value)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;

    Ok(Json(RemoveEnumValueResult {
        schema_id,
        new_version: /* get from service */,
        success: true,
    }))
}

Register routes in mod.rs:

// packages/desktop-app/src-tauri/src/dev_server/mod.rs
mod schema_endpoints;

// In router setup:
.route("/api/schemas/:schema_id", 
    axum::routing::get(schema_endpoints::get_schema))
.route("/api/schemas/:schema_id/fields", 
    axum::routing::post(schema_endpoints::add_field))
.route("/api/schemas/:schema_id/fields/:field_name", 
    axum::routing::delete(schema_endpoints::remove_field))
.route("/api/schemas/:schema_id/fields/:field_name/enum-values",
    axum::routing::post(schema_endpoints::extend_enum)
    .delete(schema_endpoints::remove_enum_value))

Phase 5: Refactor SchemaService to Use Adapter

File: packages/desktop-app/src/lib/services/schema-service.ts

Replace direct invoke() calls with getBackendAdapter():

import { getBackendAdapter, type BackendAdapter } from './backend-adapter';

export class SchemaService {
  private adapter: BackendAdapter;

  constructor(adapter?: BackendAdapter) {
    this.adapter = adapter ?? getBackendAdapter();
  }

  async getSchema(schemaId: string): Promise<SchemaDefinition> {
    // Validation
    if (!schemaId || schemaId.trim() === '') {
      throw new SchemaOperationError('Schema ID cannot be empty', schemaId, 'get');
    }

    try {
      // Adapter automatically handles Tauri vs HTTP!
      return await this.adapter.getSchema(schemaId);
    } catch (error) {
      const message = formatSchemaError(error, 'get', schemaId);
      throw new SchemaOperationError(message, schemaId, 'get', error);
    }
  }

  // Similar refactor for addField, removeField, extendEnum, removeEnumValue
}

Key Changes:

  • ✅ Remove direct invoke() calls
  • ✅ Remove browser mode detection (adapter handles it)
  • ✅ Remove mock schema fallback (adapter handles it)
  • ✅ Keep validation and error formatting

Update factory:

export function createSchemaService(adapter?: BackendAdapter): SchemaService {
  return new SchemaService(adapter);
}

Phase 6: Testing

Unit Tests:

describe('SchemaService with BackendAdapter', () => {
  let mockAdapter: BackendAdapter;
  let service: SchemaService;

  beforeEach(() => {
    mockAdapter = {
      getSchema: vi.fn(),
      addSchemaField: vi.fn(),
      // ... other methods
    } as unknown as BackendAdapter;

    service = new SchemaService(mockAdapter);
  });

  it('should call adapter.getSchema()', async () => {
    vi.mocked(mockAdapter.getSchema).mockResolvedValue(mockSchema);
    await service.getSchema('task');
    expect(mockAdapter.getSchema).toHaveBeenCalledWith('task');
  });
});

Integration Tests:

# Start dev server
cd packages/desktop-app/src-tauri
cargo run --bin dev_server

# Test HTTP endpoints
curl http://localhost:3001/api/schemas/task

Acceptance Criteria

  • All 5 schema methods added to BackendAdapter interface
  • TauriAdapter implementation calls Tauri commands from Implement Missing Tauri Commands for Schema Operations #388
  • HttpAdapter implementation calls HTTP endpoints
  • 5 HTTP endpoints created in schema_endpoints.rs
  • Routes registered in mod.rs
  • SchemaService refactored to use adapter
  • Browser mode detection removed (adapter handles it)
  • All tests passing
  • Quality checks pass: bun run quality:fix

Dependencies

Files to Modify

File Type Changes
backend-adapter.ts TypeScript Add interface methods + 2 implementations (~350 lines)
schema-service.ts TypeScript Refactor to use adapter (~100 lines changed)
schema_endpoints.rs Rust New file (~250 lines)
mod.rs Rust Register routes (~10 lines)
schema-service.test.ts TypeScript Update tests (~50 lines)

Total: ~5 files, ~760 lines

Estimated Effort

  • Time: 6-8 hours
  • Complexity: Medium (following established adapter pattern)

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions