const WebSocket = require('ws'); const fs = require('fs'); const readline =
require('readline'); const path = require('path');
function loadConfig() {
// 1. Base Defaults
let config = { host: '0.0.0.0', port: 8080, configFileUsed: 'None (using
defaults)' };
// 2. Check JSON config files (./ overrides ../)
const configPaths = [ path.join(__dirname, 'dmz_relay_cfg.json'),
path.join(__dirname, '..', 'dmz_relay_cfg.json') ];
for (const cfgPath of configPaths) {
if (fs.existsSync(cfgPath)) {
try {
const fileContent = fs.readFileSync(cfgPath, 'utf8');
const parsed = JSON.parse(fileContent);
if (parsed.listen_address) config.host = parsed.listen_address;
if (parsed.listen_port) config.port = parseInt(parsed.listen_port, 10);
config.configFileUsed = cfgPath;
break; // Stop looking once we find the closest config file
} catch (err) {
console.error(`[dVFS] WARNING: Found ${cfgPath} but failed to parse JSON.`,
err.message);
}
}
}
// 3. Environment Variables (Highest Priority)
if (process.env.DMZ_RELAY_LISTEN_ADDRESS) {
config.host = process.env.DMZ_RELAY_LISTEN_ADDRESS;
config.configFileUsed += ' (Overridden by Env Var: DMZ_RELAY_LISTEN_ADDRESS)'
;
}
if (process.env.DMZ_RELAY_LISTEN_PORT) {
config.port = parseInt(process.env.DMZ_RELAY_LISTEN_PORT, 10);
config.configFileUsed += ' (Overridden by Env Var: DMZ_RELAY_LISTEN_PORT)';
}
return config;
}
const CONFIG = loadConfig(); const ARCHIVE_FILE = path.join(__dirname,
'mesh_archive.jsonl');
/ Materialized view of the VFS in RAM
/ Map<string, { data: string, timestamp: number }>
const vfsState = new Map();
/ Open an append-only stream for efficient, ordered, concurrent-safe disk
writes
const archiveStream = fs.createWriteStream(ARCHIVE_FILE, { flags: 'a' });
async function rebuildStateFromLog() {
// Print configuration availability as requested
console.log('
======================================================');
console.log('[dVFS] Initialization Options Available:');
console.log(' 1. Environment Variables: DMZ_RELAY_LISTEN_ADDRESS,
DMZ_RELAY_LISTEN_PORT');
console.log(' 2. Config Files Checked: ./dmz_relay_cfg.json,
../dmz_relay_cfg.json');
console.log(' 3. Defaults: host="0.0.0.0", port=8080');
console.log('======================================================');
console.log(`[dVFS] Current Config Source: ${CONFIG.configFileUsed}`);
console.log(`[dVFS] Attempting to bind to ${CONFIG.host}:${CONFIG.port}
`);
if (!fs.existsSync(ARCHIVE_FILE)) {
console.log(`[dVFS] No existing archive found at ${ARCHIVE_FILE}. Starting
fresh.`);
return;
}
console.log(`[dVFS] Rebuilding state from ${ARCHIVE_FILE}...`);
const fileStream = fs.createReadStream(ARCHIVE_FILE);
const rl = readline.createInterface({ input: fileStream, crlfDelay:
Infinity });
let eventCount = 0;
for await (const line of rl) {
if (!line.trim()) continue;
try { const event = JSON.parse(line); applyEventToRAM(event);
eventCount++; }
catch (err) { console.error(`[dVFS] Corrupted log entry skipped: ${line}`,
err.message); }
}
console.log(`[dVFS] State rebuilt successfully. Replayed ${eventCount}
events. Tracking ${vfsState.size} active files.`);
}
function applyEventToRAM(event) {
const { type, path: filePath, data, timestamp } = event;
const current = vfsState.get(filePath);
if (current && current.timestamp > timestamp) return false;
if (type === 'VFS_WRITE') {
if (current && current.data === data) return false;
vfsState.set(filePath, { data, timestamp });
return true;
}
if (type === 'VFS_DELETE') {if (!current) return false; vfsState.delete(file
Path); return true; }
return false;
}
function startServer() {
const wss = new WebSocket.Server({ host: CONFIG.host, port: CONFIG.port });
wss.on('connection', (ws, req) => {
const clientIp = req.socket.remoteAddress;
console.log(`[dVFS] Client connected from ${clientIp}`);
vfsState.forEach((fileInfo, filePath) => {
ws.send(JSON.stringify({ type: 'VFS_WRITE', path: filePath, data:
fileInfo.data, timestamp: fileInfo.timestamp })); });
ws.on('message', (messageAsString) => {
let event;
try {
event = JSON.parse(messageAsString);
} catch (e) { console.warn(`[dVFS] Received malformed JSON from
${clientIp}`); return; }
if (!event.type || typeof event.path !== 'string' || typeof event.timestamp
!== 'number') {
console.warn(`[dVFS] Received invalid payload schema from ${clientIp}`);
return;
}
if (applyEventToRAM(event)) { archiveStream.write(JSON.stringify(event) + '
');
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(messageAsString); }
});
console.log(`[dVFS] Processed & Broadcasted ${event.type} for ${event.path}
(ts: ${event.timestamp})`);
}
});
ws.on('close', () => console.log(`[dVFS] Client disconnected:
${clientIp}`));
ws.on('error', (err) => console.error(`[dVFS] WS error for ${clientIp}:`,
err.message));
});
console.log(`[dVFS] Relay Node successfully running on ws://${CONFIG.host}:${C
ONFIG.port}`);
}
rebuildStateFromLog()
.then(startServer)
.catch((err) => {
if (err.code === 'EADDRINUSE') {
console.error(`
[dVFS] FATAL ERROR: Port ${CONFIG.port} is already in use.`);
console.error(`Please change 'listen_port' in dmz_relay_cfg.json or set
DMZ_RELAY_LISTEN_PORT env variable.
`);
} else { console.error('[dVFS] FATAL: Failed to initialize relay node',
err); }
process.exit(1);
});
process.on('SIGINT', () => {
console.log('
[dVFS] Shutting down relay node...'); archiveStream.end(); process.exit(0);
});