Sync
@idiomark/sync provides real-time synchronization of Idiomark files across devices using WebSockets, with offline-first support, Merkle tree diffing, and backpressure handling.
Installation
pnpm add @idiomark/sync
Key Features
- WebSocket Server — Broadcast file changes to connected clients
- Auto-Reconnecting Client — Resilient client with offline queue
- Merkle Tree Sync — Efficient diff detection using Merkle roots
- Backpressure Handling — Prevent overwhelming slow clients
- Offline Queue — Queue operations while disconnected, replay on reconnect
- Presence — Real-time user presence tracking
Quick Start
Server
import { SyncServer } from "@idiomark/sync";
const server = new SyncServer({
port: 8080,
auth: async (token) => await verifyToken(token),
});
await server.start();
server.on("connection", (client) => {
console.log("Client connected:", client.id);
});
server.on("file:created", (data) => {
console.log("File created:", data.fileId);
});
Client
import { SyncClient } from "@idiomark/sync";
const client = new SyncClient({
url: "wss://api.idiomark.protocol/sync",
token: userToken,
autoReconnect: true,
heartbeatInterval: 30000,
});
await client.connect();
// Subscribe to file updates
client.subscribe("idiomark:file-id");
// Listen for events
client.on("file:updated", (data) => {
console.log("File updated:", data.file);
});
Sync Protocol
Client → Server Messages
| Message Type | Description |
|---|---|
subscribe | Subscribe to a channel |
unsubscribe | Unsubscribe from a channel |
sync:pull | Request changes since timestamp |
presence:update | Update presence status |
Server → Client Messages
| Message Type | Description |
|---|---|
file:created | New file was created |
file:updated | File was modified |
file:deleted | File was deleted |
sync:started | Sync operation started |
sync:completed | Sync completed |
sync:conflict | Conflict detected |
presence:online | User came online |
presence:offline | User went offline |
Channels
Clients subscribe to channels for targeted updates:
| Pattern | Description |
|---|---|
idiomark:{fileId} | Updates for a specific file |
user:{userId} | Updates for all user's files |
presence:{userId} | User presence updates |
Advanced Components
SyncOrchestrator
Coordinates the full sync lifecycle:
import { SyncOrchestrator } from "@idiomark/sync";
const orchestrator = new SyncOrchestrator(config);
await orchestrator.syncAll();
MerkleTreeBuilder
Efficient diff detection using Merkle trees:
import { MerkleTreeBuilder } from "@idiomark/sync";
const merkle = new MerkleTreeBuilder();
const root = merkle.build(fileHashes);
BackpressureHandler
Prevents overwhelming slow clients:
import { BackpressureHandler } from "@idiomark/sync";
const bp = new BackpressureHandler();
bp.onPressure(() => console.log("Slow down!"));
OfflineQueue
Queues operations while disconnected:
import { OfflineQueue } from "@idiomark/sync";
const queue = new OfflineQueue();
queue.enqueue({ type: "subscribe", channel: "idiomark:file-id" });
// On reconnect, replay:
const ops = queue.drain();
SyncProtocolValidator
Validates sync messages:
import { SyncProtocolValidator } from "@idiomark/sync";
const validator = new SyncProtocolValidator();
const isValid = validator.validate(message);
API Reference
SyncServer
class SyncServer {
constructor(config: SyncServerConfig);
start(): Promise<void>;
stop(): Promise<void>;
broadcast(event: ServerEvent): void;
send(clientId: string, event: ServerEvent): void;
getConnectedClients(): ClientInfo[];
on(event: string, listener: (data: any) => void): void;
}
SyncClient
class SyncClient {
constructor(config: SyncClientConfig);
connect(): Promise<void>;
disconnect(): Promise<void>;
subscribe(channel: string): void;
unsubscribe(channel: string): void;
syncPull(since?: number): void;
updatePresence(status: string, data?: any): void;
getState(): ClientState;
on(event: string, listener: (data: any) => void): void;
}
Related
- Storage — Multi-provider Idiomark file storage
- Versioning — Git-based version control
- Teams — Team collaboration