src / syncManager.ts
import { SyncEvent } from "./types";
export class SyncManager {
private queue: SyncEvent[] = [];
private processing = false;
private delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async enqueue(artifactId: string, action: "create" | "update" | "delete"): Promise<void> {
const event: SyncEvent = {
id: `${artifactId}_${Date.now()}`,
artifactId,
action,
timestamp: Date.now(),
retries: 0,
};
this.queue.push(event);
if (!this.processing) {
this.processing = true;
await this.processQueue();
this.processing = false;
}
}
private async processQueue(): Promise<void> {
while (this.queue.length > 0) {
const event = this.queue.shift()!;
await this.process(event);
}
}
private async process(event: SyncEvent): Promise<void> {
try {
await this.delay(10);
} catch {
if (event.retries < 3) {
event.retries++;
this.queue.unshift(event);
await this.delay(Math.pow(2, event.retries) * 1000);
}
}
}
getPending(): SyncEvent[] {
return [...this.queue];
}
}