Module WindAdvancedSync

Module WindAdvancedSync 

Source
Expand description

Wind UI framework synchronization.

§Wind Advanced Synchronization - Real-time Document & UI Sync

File Responsibilities: This module implements advanced synchronization features that keep Wind’s frontend state in sync with Mountain’s backend state in real-time. It handles document changes, UI state updates, and broadcast updates across the editor ecosystem.

Architectural Role in Wind-Mountain Connection:

The WindAdvancedSync module is responsible for:

  1. Document Synchronization: Real-time tracking and synchronization of document changes between Wind (frontend editor) and Mountain (backend services)
  2. UI State Sync: Synchronizing UI state across multiple editor windows
    • Cursor positions
    • Selection ranges
    • Zoom levels
    • Theme and layout
  3. Real-time Broadcasting: Broadcasting updates to interested subscribers
  4. Conflict Detection: Identifying and handling conflicting changes
  5. Performance Tracking: Monitoring sync performance and health

Synchronization Architecture:

Three Sync Layers:

1. Document Synchronization (Every 5 seconds):

Wind Editor (User Edits)
    |
    | Detect changes
    v
WindAdvancedSync
    |
    | Check for conflicts
    v
Mountain Services
    |
    | Apply changes
    v
File System / Storage

2. UI State Synchronization (Every 1 second):

Wind UI Window
    |
    | Capture state (cursor, selection, zoom)
    v
WindAdvancedSync
    |
    | Update internal state
    v
Apply to other windows

3. Real-time Updates (Every 100ms):

Subscribed Listeners
    ^
    | Broadcast updates
    |
WindAdvancedSync
    |
    | Queue updates
    v
Update Queue

Document Synchronization States:

enum SyncState {
	Modified,   // Changed locally, not synced
	Synced,     // Successfully synchronized
	Conflicted, // Conflicts need resolution
	Offline,    // Cannot sync (offline)
}

Change Types Supported:

enum ChangeType {
	Update, // File content updated
	Insert, // New file created
	Delete, // File deleted
	Move,   // File moved/renamed
	Other,  // Other changes
}

Conflict Detection (Microsoft-Inspired):

Detection Criteria:

  • Document modified recently (within 10 seconds of last sync)
  • Document is already in conflicted state
  • Multiple simultaneous changes detected

Conflict Response:

return Err(format!(
	"Conflict detected: Document {} was modified recently ({}s ago)",
	document_id,
	current_time - document.last_modified
));

Error Recovery (Circuit Breaker Pattern):

Circuit Breaker States:

  1. Closed (Normal): Operations proceed normally
  2. Open (Degraded): Too many failures, slow down sync interval
  3. Half-Open (Testing): Slowly testing if system recovered

Recovery Logic:

  • Track consecutive failures (max 3)
  • On reaching limit: Increase sync interval to 30s
  • On success: Reset interval to 5s
  • Provides protection against cascading failures

Trackable Metrics:

Sync.Status:

SyncStatus {
	total_documents:u32,       // All tracked documents
	synced_documents:u32,      // Successfully synced
	conflicted_documents:u32,  // Have conflicts
	offline_documents:u32,     // Cannot sync
	last_sync_duration_ms:u64, // Time for last sync
}

UI State Tracked:

UIStateSynchronization {
    active_editor: Option<String>,
    cursor_positions: HashMap<String, (u32, u32)>,  // Document -> (line, col)
    selection_ranges: HashMap<String, (u32, u32)>,   // Document -> (start, end)
    view_state: ViewState {
        zoom_level: f32,
        sidebar_visible: bool,
        panel_visible: bool,
        status_bar_visible: bool,
    },
    theme: String,
    layout: LayoutState,
}

Real-time Update System:

Update Flow:

  1. Queue updates as they occur
  2. Subscriber management per target
  3. Periodic broadcast (100ms)
  4. Emit events via Tauri

Subscription Model:

// Subscribe to updates for a target
sync.subscribe_to_updates("file-changes", "window-1").await?;

// Queue updates
sync.queue_update(RealTimeUpdate { target:"file-changes".to_string(), data:modified_content })
	.await?;

// Broadcasts go to:
// - "real-time-update-window-1"
// - "real-time-update-window-2"
// etc...

Tauri Commands:

  • mountain_add_document_for_sync - Add document to sync tracking
  • mountain_get_sync_status - Get current sync status
  • mountain_subscribe_to_updates - Subscribe to real-time updates

Events Emitted:

  • mountain_sync_status_update - Sync status changes
  • mountain_performance_update - Performance metrics
  • real-time-update-{subscriber} - Real-time updates

Initialization:

// In Mountain setup
let sync = Arc::new(WindAdvancedSync::new(runtime));
app_handle.manage(sync.clone());

// Start sync tasks
let sync_clone = sync.clone();
tokio::spawn(async move {
sync_clone.start_synchronization().await;
});

Usage Examples:

Add Document for Sync:

// From Wind TypeScript
await invoke('mountain_add_document_for_sync', {
    documentId: 'file-123',
    filePath: '/project/src/main.rs'
});

Check Sync Status:

const status = await invoke('mountain_get_sync_status');
console.log(`Synced: ${status.syncedDocuments}/${status.totalDocuments}`);

Subscribe to Updates:

await invoke('mountain_subscribe_to_updates', {
    target: 'file-changes',
    subscriber: 'my-window-id'
});

// Listen for updates
app.handle.listen('real-time-update-my-window-id', (event) => {
    console.log('Real-time update:', event.payload);
});

Performance Tracking:

Metrics Collected:

  • Total messages sent/received
  • Average latency
  • Connection uptime
  • Error count
  • Sync duration

Logged on Every Operation:

trace!(
"Document sync completed: {} success, {} errors, {:.2}ms",
success_count,
error_count,
sync_duration.as_millis()
);

Integration with Other Modules:

TauriIPCServer:

  • Used for broadcasting events to Wind
  • Emits sync and performance updates

AdvancedFeatures:

  • Collaboration sessions work with document sync
  • Shared focus on real-time updates

StatusReporter:

  • Sync status reported to Sky for monitoring
  • Performance metrics shared

Future Enhancements:

  • Operational Transformation: For collaborative editing
  • Conflict Resolution UI: User-facing conflict resolution
  • Delta Sync: Only sync changed portions
  • Sync Prioritization: Prioritize active documents
  • Offline Sync Support: Queue changes when offline

Structs§

DocumentChange
Document change
DocumentSynchronization
Document synchronization state
GridLayout
Grid layout
LayoutState
Editor layout state
RealTimeUpdate
Real-time update
RealTimeUpdates
Real-time updates manager
SyncStatus
Synchronization status
SynchronizedDocument
Single synchronized document
UIStateSynchronization
UI state synchronization
ViewState
View state
WindAdvancedSync
Advanced Wind synchronization features

Enums§

ChangeType
Change type for document modifications
SyncState
Document synchronization state

Functions§

initialize_wind_advanced_sync
Initialize Wind advanced synchronization
mountain_add_document_for_sync
Tauri command to add document for synchronization
mountain_get_sync_status
Tauri command to get sync status
mountain_subscribe_to_updates
Tauri command to subscribe to updates