Skip to content

Commit 4a6f16e

Browse files
committed
feat: Implement log buffering for SSE client connections
1 parent a212b0b commit 4a6f16e

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

packages/client-direct/src/manage-api.ts

+28-1
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ let cpuMetrics = {
9191
lastUpdate: Date.now()
9292
};
9393

94+
const LOG_BUFFER_SIZE = 100; // Keep last 100 log entries
95+
const logBuffer: string[] = [];
96+
97+
// Add this function to maintain the log buffer
98+
function addToLogBuffer(logData: string) {
99+
logBuffer.push(logData);
100+
if (logBuffer.length > LOG_BUFFER_SIZE) {
101+
logBuffer.shift(); // Remove oldest entry
102+
}
103+
}
104+
105+
// Subscribe to logs at the application level to maintain the buffer
106+
elizaLogger.subscribe(addToLogBuffer);
107+
94108
async function verifyTokenMiddleware(req: any, res: any, next) {
95109
// if JWT is not enabled, skip verification
96110
if (!(settings.JWT_ENABLED && settings.JWT_ENABLED.toLowerCase() === 'true')) {
@@ -562,6 +576,15 @@ export function createManageApiRouter(
562576

563577
// Send initial connection message
564578
res.write(`data: {"level":30,"time":${now},"msg":"${clientId} connected"}\n\n`);
579+
580+
// Send buffered logs to the new client
581+
logBuffer.forEach(logData => {
582+
try {
583+
res.write(`data: ${logData}\n\n`);
584+
} catch (err) {
585+
// Ignore errors when sending buffer
586+
}
587+
});
565588

566589
// Setup heartbeat
567590
const heartbeatInterval = setInterval(() => {
@@ -573,7 +596,7 @@ export function createManageApiRouter(
573596
}
574597
}, 30000);
575598

576-
// Subscribe to logs
599+
// Subscribe to new logs
577600
const unsubscribe = elizaLogger.subscribe((logData) => {
578601
try {
579602
res.write(`data: ${logData}\n\n`);
@@ -586,6 +609,7 @@ export function createManageApiRouter(
586609
const cleanup = () => {
587610
clearInterval(heartbeatInterval);
588611
unsubscribe();
612+
elizaLogger.debug(`Log client ${clientId} disconnected`);
589613
};
590614

591615
// Handle client disconnect
@@ -604,6 +628,9 @@ export function createManageApiRouter(
604628
req.on('close', () => {
605629
clearTimeout(connectionTimeout);
606630
});
631+
632+
// Log that a new client connected
633+
elizaLogger.debug(`New log client ${clientId} connected`);
607634
});
608635

609636
router.get("/system/metrics", async (req, res) => {

0 commit comments

Comments
 (0)