fix: wait for database initialization before processing session-init requests
Fixes a race condition where the UserPromptSubmit hook could call /api/sessions/init before the database is fully initialized, resulting in a 500 error with "Database not initialized". Root cause: - Worker starts HTTP server immediately for fast startup - Health endpoint (/api/health) returns OK when server is listening - session-init hook waits for health check, then calls /api/sessions/init - Database initialization happens in background, creating a race window Solution: - Add early handler for /api/sessions/init that waits for initialization - Uses same pattern as existing /api/context/inject handler - Returns 503 with retry message if initialization times out The fix ensures hooks receive proper responses even during the brief startup window when the server is listening but DB isn't ready yet. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
committed by
Alex Newman
parent
9789a1969c
commit
27aa98c269
@@ -250,6 +250,27 @@ export class WorkerService {
|
||||
|
||||
next(); // Delegate to SearchRoutes handler
|
||||
});
|
||||
|
||||
// Early handler for /api/sessions/init to wait for database initialization
|
||||
// Fixes race condition where session-init hook is called before DB is ready
|
||||
// See: https://github.com/thedotmack/claude-mem/issues/XXX
|
||||
this.server.app.post('/api/sessions/init', async (req, res, next) => {
|
||||
const timeoutMs = 30000; // 30 second timeout for session init
|
||||
const timeoutPromise = new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Database initialization timeout')), timeoutMs)
|
||||
);
|
||||
|
||||
try {
|
||||
await Promise.race([this.initializationComplete, timeoutPromise]);
|
||||
next(); // Delegate to SessionRoutes handler
|
||||
} catch (error) {
|
||||
logger.error('HTTP', 'Session init failed waiting for initialization', {}, error as Error);
|
||||
res.status(503).json({
|
||||
error: 'Service initializing',
|
||||
message: 'Database is still initializing, please retry'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user