Files
DataStack/server/socket/handlers.js
T

121 lines
3.4 KiB
JavaScript
Raw Normal View History

2026-10-23 19:56:38 -07:00
const jwt = require("jsonwebtoken");
2026-10-23 11:43:49 -05:00
function setupSocketHandlers(io, bufferQueue, worker, options = {}) {
2026-10-23 19:56:38 -07:00
const jwtSecret = options.jwtSecret || process.env.DATASTACK_JWT_SECRET;
if (!jwtSecret) {
throw new Error(
"DATASTACK_JWT_SECRET must be configured before starting the socket server.",
);
}
2026-10-23 11:43:49 -05:00
const idempotencyMap = new Map();
const rateLimitMap = new Map();
// Middleware: Handshake Auth
io.use((socket, next) => {
const authHeader =
socket.handshake.auth?.token ||
socket.handshake.headers?.authorization ||
socket.handshake.query?.token;
if (!authHeader) {
2026-10-23 19:56:38 -07:00
return next(new Error("AUTH_REQUIRED: Handshake missing JWT"));
2026-10-23 11:43:49 -05:00
}
try {
2026-10-23 19:56:38 -07:00
const cleanToken = authHeader.startsWith("Bearer ")
? authHeader.slice(7)
: authHeader;
2026-10-23 11:43:49 -05:00
const decoded = jwt.verify(cleanToken, jwtSecret);
socket.data.clientId = decoded.clientId;
socket.data.rateLimit = decoded.rateLimit || 100;
next();
} catch (err) {
next(new Error(`AUTH_INVALID: ${err.message}`));
}
});
2026-10-23 19:56:38 -07:00
io.on("connection", (socket) => {
2026-10-23 11:43:49 -05:00
const clientId = socket.data.clientId;
const rateLimit = socket.data.rateLimit;
socket.join(`client:${clientId}`);
// Single event
2026-10-23 19:56:38 -07:00
socket.on("sync_data", (payload, callback) => {
2026-10-23 11:43:49 -05:00
try {
2026-10-23 19:56:38 -07:00
const eventId =
payload.eventId ||
`evt_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
2026-10-23 11:43:49 -05:00
const timestamp = payload.timestamp || new Date().toISOString();
// Idempotency
const key = `${clientId}:${eventId}`;
if (idempotencyMap.has(key)) {
2026-10-23 19:56:38 -07:00
if (callback)
callback({ success: true, eventId, note: "DUPLICATE_DROPPED" });
2026-10-23 11:43:49 -05:00
return;
}
idempotencyMap.set(key, Date.now());
// Rate limit
const now = Date.now();
const rl = rateLimitMap.get(clientId);
if (!rl || now - rl.start >= 1000) {
rateLimitMap.set(clientId, { count: 1, start: now });
} else if (rl.count >= rateLimit) {
2026-10-23 19:56:38 -07:00
if (callback)
callback({ success: false, error: "RATE_LIMIT_EXCEEDED" });
2026-10-23 11:43:49 -05:00
return;
} else {
rl.count += 1;
}
const event = {
clientId,
eventId,
timestamp,
2026-10-23 19:56:38 -07:00
payload:
typeof payload.data === "string"
? payload.data
: JSON.stringify(payload.data),
2026-10-23 11:43:49 -05:00
};
bufferQueue.push(event);
if (callback) callback({ success: true, eventId });
} catch (err) {
if (callback) callback({ success: false, error: err.message });
}
});
// Batch event
2026-10-23 19:56:38 -07:00
socket.on("batch_sync", (batch, callback) => {
2026-10-23 11:43:49 -05:00
if (!Array.isArray(batch)) {
2026-10-23 19:56:38 -07:00
if (callback) callback({ success: false, error: "Expected array" });
2026-10-23 11:43:49 -05:00
return;
}
let count = 0;
for (const item of batch) {
2026-10-23 19:56:38 -07:00
const eventId =
item.eventId ||
`evt_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
2026-10-23 11:43:49 -05:00
const timestamp = item.timestamp || new Date().toISOString();
bufferQueue.push({
clientId,
eventId,
timestamp,
2026-10-23 19:56:38 -07:00
payload:
typeof item.data === "string"
? item.data
: JSON.stringify(item.data),
2026-10-23 11:43:49 -05:00
});
count++;
}
if (callback) callback({ success: true, processed: count });
});
});
}
module.exports = { setupSocketHandlers };