# Troubleshooting Guide

Common issues and solutions for @networkoptix/crdt-sync.

## Connection Issues

### Problem: "Not syncing across tabs/browsers"

**Symptoms**:
- Changes in one tab don't appear in another
- Connection status shows "offline"
- No active users detected

**Solutions**:

1. **Check room names match**:
```typescript
// ✅ Both tabs must use SAME room name
const ModelA = createSingletonModel({ room: 'my-room' }, 0);
const ModelB = createSingletonModel({ room: 'my-room' }, 0); // Same!

// ❌ Different rooms won't sync
const ModelA = createSingletonModel({ room: 'room-1' }, 0);
const ModelB = createSingletonModel({ room: 'room-2' }, 0); // Different!
```

2. **Verify WebRTC support**:
```javascript
// Check browser compatibility
if (!window.RTCPeerConnection) {
  console.error('WebRTC not supported in this browser');
}
```

3. **Check signaling server**:
```typescript
const model = new MyModel({
  provider: {
    webrtc: {
      signaling: ['wss://signal.myserver.com'] // Must be accessible
    }
  }
});
```

4. **Enable debug logging**:
```typescript
const model = new MyModel({
  debug: true  // See detailed logs in console
});
model.enableDebug();
```

### Problem: "WebRTC connection fails"

**Symptoms**:
- Console errors: "Failed to create peer connection"
- Falls back to WebSocket immediately

**Solutions**:

1. **Configure STUN/TURN servers**:
```typescript
const model = new MyModel({
  provider: {
    webrtc: {
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        {
          urls: 'turn:turn.myserver.com:3478',
          username: 'user',
          credential: 'pass'
        }
      ]
    }
  }
});
```

2. **Check firewall/network**:
- Corporate firewalls may block WebRTC
- Try from different network
- Enable WebSocket fallback

3. **Use WebSocket fallback**:
```typescript
const model = new MyModel({
  provider: {
    webrtc: { enabled: false },
    websocket: { enabled: true, url: 'wss://ws.myserver.com' }
  }
});
```

### Problem: "WebSocket connection refused"

**Symptoms**:
- Error: "WebSocket connection failed"
- Error: "ECONNREFUSED"

**Solutions**:

1. **Check WebSocket server is running**:
```bash
# Test WebSocket server
curl -i -N -H "Connection: Upgrade" \\
  -H "Upgrade: websocket" \\
  wss://your-server.com
```

2. **Verify URL format**:
```typescript
// ✅ Correct
websocket: { url: 'wss://server.com' }

// ❌ Wrong
websocket: { url: 'ws://server.com' }  // Use WSS in production
websocket: { url: 'https://server.com' } // Not HTTPS, use WSS
```

3. **Check CORS settings** (server-side):
```javascript
// y-websocket server
const wss = new WebSocketServer({
  server,
  verifyClient: (info) => {
    const origin = info.origin;
    return allowedOrigins.includes(origin);
  }
});
```

## Data Synchronization Issues

### Problem: "Data not persisting"

**Symptoms**:
- Refresh page → data lost
- Only works while tab open

**Solutions**:

1. **Persistence is NOT built-in**:
```typescript
// You must implement server-side persistence
// OR use browser storage

import { IndexeddbPersistence } from 'y-indexeddb';

const persistence = new IndexeddbPersistence('my-room', ydoc);
```

2. **Server-side persistence** (WebSocket provider):
```javascript
// y-websocket server with level-db
const persistence = new LeveldbPersistence('./db');
```

### Problem: "Conflicts not resolving"

**Symptoms**:
- Two users see different values
- Data inconsistency

**Explanation**: This SHOULDN'T happen with CRDTs, but if it does:

**Debug Steps**:

1. **Check both using same Yjs structure**:
```typescript
// ✅ Both must use same Y structure type
this.ymap = ydoc.getMap('data');  // Y.Map
this.yarray = ydoc.getArray('items'); // Y.Array

// ❌ Mixing types breaks sync
// Tab 1: ydoc.getMap('data')
// Tab 2: ydoc.getArray('data')  // WRONG!
```

2. **Verify transactions used for batches**:
```typescript
// ✅ Use transactions for multiple operations
ydoc.transact(() => {
  ymap.set('key1', 'value1');
  ymap.set('key2', 'value2');
});

// ⚠️ Without transaction = multiple sync messages
ymap.set('key1', 'value1');
ymap.set('key2', 'value2');
```

### Problem: "Updates delayed/laggy"

**Symptoms**:
- Changes take seconds to sync
- High latency between peers

**Solutions**:

1. **Check network latency**:
```typescript
import { useConnectionType } from '@networkoptix/crdt-sync/react';

const type = useConnectionType(model);
console.log('Connection:', type); // 'webrtc' | 'websocket' | 'broadcast'

// WebRTC = fastest
// WebSocket = slower (server roundtrip)
// Broadcast = instant (same browser)
```

2. **Optimize for WebRTC**:
```typescript
const model = new MyModel({
  provider: {
    webrtc: {
      enabled: true,
      maxConns: 35  // More peers = better mesh
    }
  }
});
```

3. **Reduce update frequency**:
```typescript
// Debounce rapid updates
import { debounce } from 'lodash';

const debouncedUpdate = debounce((value) => {
  model.setValue(value);
}, 100);  // Wait 100ms before syncing
```

## Framework-Specific Issues

### React: "Component not re-rendering"

**Problem**: UI doesn't update when data changes

**Solutions**:

1. **Ensure using hooks correctly**:
```typescript
// ✅ Correct
const [value, setValue, meta] = useSyncModel(Model);

// ❌ Wrong - missing dependency
const [value] = useSyncModel(Model);
// Then using `value` directly won't trigger re-renders
```

2. **Check React version**:
```bash
# React 18+ recommended
npm list react
```

3. **Verify mobx-react-lite installed**:
```bash
npm list mobx-react-lite
```

### Angular: "Signals not updating"

**Problem**: Angular signals don't reflect changes

**Solutions**:

1. **Verify DestroyRef injection**:
```typescript
// Angular 16+ uses DestroyRef for cleanup
import { DestroyRef } from '@angular/core';

// Signal automatically handles cleanup
const signal = createSyncSignal(Model);
```

2. **Check zone.js compatibility**:
```typescript
// In standalone components, no zone.js issues
@Component({
  standalone: true,
  // ...
})
```

### Vue: "Refs not reactive"

**Problem**: Vue refs don't update

**Solutions**:

1. **Use `.value` for refs**:
```typescript
const { value, setValue } = useSyncModelSync(Model);

// ✅ Correct
console.log(value.value);
setValue(value.value + 1);

// ❌ Wrong
console.log(value);  // Missing .value
```

2. **Ensure Composition API**:
```vue
<script setup>
// ✅ Use <script setup> or setup() function
</script>
```

## Performance Issues

### Problem: "High memory usage"

**Symptoms**:
- Browser tab using >500MB RAM
- Slow performance over time

**Solutions**:

1. **Limit document size**:
```typescript
// Monitor size
const docSize = Y.encodeStateAsUpdate(ydoc).length;
console.log('Doc size:', docSize, 'bytes');

// If > 10MB, consider:
// - Sharding into multiple rooms
// - Implementing garbage collection
// - Clearing old data
```

2. **Destroy unused models**:
```typescript
// Always cleanup on unmount
useEffect(() => {
  return () => {
    model.destroy();  // Frees memory
  };
}, []);
```

3. **Limit peer connections**:
```typescript
const model = new MyModel({
  provider: {
    webrtc: {
      maxConns: 20  // Fewer peers = less memory
    }
  }
});
```

### Problem: "Too many updates/network traffic"

**Symptoms**:
- High bandwidth usage
- Network tab shows constant activity

**Solutions**:

1. **Batch operations**:
```typescript
// ✅ Single transaction
ydoc.transact(() => {
  items.forEach(item => yarray.push([item]));
});

// ❌ Multiple sync messages
items.forEach(item => yarray.push([item]));
```

2. **Throttle/debounce UI updates**:
```typescript
import { throttle } from 'lodash';

const throttledUpdate = throttle((value) => {
  model.setValue(value);
}, 100);  // Max 10 updates/second
```

## Security Issues

### Problem: "Unauthorized users joining room"

**Symptom**: Anyone can join by guessing room name

**Solution**: Implement authentication

```typescript
// 1. Server-side auth
const roomToken = await fetch('/api/room-token', {
  headers: { 'Authorization': `Bearer ${userToken}` }
});

// 2. Use authenticated WebSocket
const model = new MyModel({
  provider: {
    websocket: {
      url: 'wss://secure.myserver.com',
      params: { token: roomToken }
    }
  }
});

// 3. Server validates token before allowing connection
```

See [SECURITY.md](../../SECURITY.md) for comprehensive security guidance.

## Build/TypeScript Issues

### Problem: "TypeScript errors in strict mode"

**Solution**: Configure tsconfig.json

```json
{
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true,  // Skip checking .d.ts files
    "esModuleInterop": true
  }
}
```

### Problem: "Module resolution errors"

**Solution**: Check module resolution

```json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}
```

## Debugging Tips

### Enable Debug Mode

```typescript
// Global debug
const model = new MyModel({ debug: true });

// Or enable later
model.enableDebug();

// Disable
model.disableDebug();
```

### Inspect Model State

```typescript
// Get snapshot of current state
const snapshot = model.getSnapshot();
console.log(JSON.stringify(snapshot, null, 2));

// Check connection status
console.log('Connected:', model.isConnected);
console.log('Active users:', model.activeUsers);
console.log('Connection type:', model.connectionStatus.type);
```

### Monitor Network Traffic

```typescript
// Listen to provider events
provider.on('peers', (event) => {
  console.log('Peers changed:', event);
});

provider.on('status', (event) => {
  console.log('Status changed:', event.status);
});
```

### Check Yjs Document

```typescript
// Inspect Yjs internals (advanced)
import * as Y from 'yjs';

const ydoc = model['ydoc'];
const state = Y.encodeStateAsUpdate(ydoc);
console.log('Doc state size:', state.length, 'bytes');
```

## Getting Help

If you're still stuck:

1. **Check existing issues**: [GitHub Issues](https://github.com/networkoptix/crdt-sync/issues)
2. **Ask in discussions**: [GitHub Discussions](https://github.com/networkoptix/crdt-sync/discussions)
3. **Provide debug info**:
   - Library version: `npm list @networkoptix/crdt-sync`
   - Framework version
   - Browser/Node version
   - Debug logs
   - Minimal reproduction

## Related Documentation

- [Installation Guide](../getting-started/installation.md)
- [Quick Start](../getting-started/quick-start.md)
- [Core Concepts](../getting-started/core-concepts.md)
- [Security Guide](../../SECURITY.md)
