Files
FamReynaBrain/projects/colanode-hermes-bridge/src/index.ts
T
2026-09-14 22:38:47 -04:00

124 lines
4.1 KiB
TypeScript

import { setTimeout as delay } from 'node:timers/promises';
import { loadConfig } from './config.js';
import { ColanodeClient, requireWorkspace, synchronizerId } from './colanode.js';
import { StateStore } from './state.js';
import { processNodeUpdate, type NodeCache } from './processor.js';
import type { SyncCollaborationData, SyncNodeUpdateData, SynchronizerInput } from './types.js';
const config = await loadConfig();
const state = new StateStore(config.stateFile);
await state.load();
let stopping = false;
process.on('SIGTERM', () => {
stopping = true;
});
process.on('SIGINT', () => {
stopping = true;
});
const colanode = new ColanodeClient(config.httpBaseUrl, config.socketBaseUrl, config.token);
const sync = await colanode.authenticate(config.email, config.password);
const workspace = requireWorkspace(sync, config.workspaceName);
const botUserId = workspace.user.id;
const activeRoots = new Set<string>();
const cache: NodeCache = new Map();
let backoff = 1000;
while (!stopping) {
try {
await runSocketLoop();
backoff = 1000;
} catch (error) {
if (!stopping) {
console.error(`Bridge loop error: ${(error as Error).message}`);
await delay(backoff);
backoff = Math.min(backoff * 2, 30_000);
}
}
}
async function runSocketLoop(): Promise<void> {
const socket = await colanode.createSocket();
const ids = new Map<string, { key: string; input: SynchronizerInput }>();
const subscribe = (input: SynchronizerInput) => {
const key = cursorKey(input);
const id = colanode.sendSynchronizer(socket, botUserId, input, state.getCursor(key));
ids.set(id, { key, input });
};
await new Promise<void>((resolve, reject) => {
const ping = setInterval(() => {
if (socket.readyState !== socket.OPEN) return;
for (const item of ids.values()) colanode.sendSynchronizer(socket, botUserId, item.input, state.getCursor(item.key));
}, 60_000);
socket.on('open', () => {
subscribe({ type: 'users' });
subscribe({ type: 'collaborations' });
for (const rootId of activeRoots) subscribe({ type: 'node.updates', rootId });
});
socket.on('message', (raw) => {
void handleMessage(raw.toString(), ids, subscribe).catch((error) => console.error(`Event handling error: ${error.message}`));
});
socket.on('close', () => {
clearInterval(ping);
resolve();
});
socket.on('error', (error) => {
clearInterval(ping);
reject(error);
});
const stopTimer = setInterval(() => {
if (stopping) {
clearInterval(stopTimer);
socket.close();
}
}, 500);
});
}
async function handleMessage(
raw: string,
ids: Map<string, { key: string; input: SynchronizerInput }>,
subscribe: (input: SynchronizerInput) => void
): Promise<void> {
let message: { type?: string; id?: string; items?: { cursor: string; data: unknown }[] };
try {
message = JSON.parse(raw) as typeof message;
} catch {
return;
}
if (message.type !== 'synchronizer.output' || !message.id || !Array.isArray(message.items)) return;
const registration = ids.get(message.id);
if (!registration) return;
let lastCursor: string | null = null;
for (const item of message.items) {
if (registration.input.type === 'collaborations') {
const data = item.data as SyncCollaborationData;
if (!data.deletedAt && !activeRoots.has(data.nodeId)) {
activeRoots.add(data.nodeId);
subscribe({ type: 'node.updates', rootId: data.nodeId });
}
} else if (registration.input.type === 'node.updates') {
await processNodeUpdate({
update: item.data as SyncNodeUpdateData,
botUserId,
workspaceId: workspace.id,
cache,
state,
hermes: { bin: config.hermesBin, timeoutMs: config.hermesTimeoutMs, maxOutputBytes: config.hermesMaxOutputBytes },
colanode
});
}
lastCursor = item.cursor;
}
if (lastCursor) await state.setCursor(registration.key, lastCursor);
}
function cursorKey(input: SynchronizerInput): string {
return input.type === 'node.updates' ? `${input.rootId}.node.updates` : input.type;
}
void synchronizerId;