-
-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: add health check for backend connection in middleware #185
base: main
Are you sure you want to change the base?
Conversation
📝 Walkthrough📝 WalkthroughWalkthroughThe changes implemented in this pull request modify the Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Middleware
participant Backend
Client->>Middleware: Request
Middleware->>Backend: Fetch /api/v1/health
alt Health Check Success
Middleware-->>Client: Proceed with request
else Health Check Failure
Middleware-->>Client: Redirect to /connect
end
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
📒 Files selected for processing (1)
src/hooks.server.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/hooks.server.ts
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
🪛 eslint
src/hooks.server.ts
[error] 37-37: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 40-40: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Check: Lint
src/hooks.server.ts
[failure] 37-37:
'error' is defined but never used
[failure] 40-40:
'error' is defined but never used
let hasConnection; | ||
|
||
try { | ||
await fetch(event.locals.backendUrl + '/api/v1/health') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick (assertive)
Address linting issues
- Use template literals instead of string concatenation
- Prefix unused error parameters with underscore
Apply these changes:
- await fetch(event.locals.backendUrl + '/api/v1/health')
+ await fetch(`${event.locals.backendUrl}/api/v1/health`)
- .catch((error) => {
+ .catch((_error) => {
- } catch (error) {
+ } catch (_error) {
Also applies to: 37-37, 40-40
🧰 Tools
🪛 Biome (1.9.4)
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
src/hooks.server.ts
Outdated
|
||
let hasConnection; | ||
|
||
try { | ||
await fetch(event.locals.backendUrl + '/api/v1/health') | ||
.then(() => { | ||
hasConnection = true; | ||
}) | ||
.catch((error) => { | ||
hasConnection = false; | ||
}); | ||
} catch (error) { | ||
hasConnection = false; | ||
} | ||
|
||
if (!hasConnection) { | ||
throw redirect(307, '/connect'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick (assertive)
Consider caching health check results
The current implementation performs a health check on every GET request, which could impact performance and put unnecessary load on the backend. Consider implementing a caching mechanism to store the health status for a short duration.
Consider these improvements:
- Add a simple in-memory cache with expiration:
let healthCache: { status: boolean; timestamp: number } | null = null;
const CACHE_DURATION = 30000; // 30 seconds
async function checkHealth(backendUrl: string): Promise<boolean> {
if (healthCache && Date.now() - healthCache.timestamp < CACHE_DURATION) {
return healthCache.status;
}
// Your health check implementation here
healthCache = { status: hasConnection, timestamp: Date.now() };
return hasConnection;
}
- Consider implementing a circuit breaker pattern for more robust error handling and backend protection.
🧰 Tools
🪛 Biome (1.9.4)
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
🪛 eslint
[error] 37-37: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 40-40: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Check: Lint
[failure] 37-37:
'error' is defined but never used
[failure] 40-40:
'error' is defined but never used
src/hooks.server.ts
Outdated
try { | ||
await fetch(event.locals.backendUrl + '/api/v1/health') | ||
.then(() => { | ||
hasConnection = true; | ||
}) | ||
.catch((error) => { | ||
hasConnection = false; | ||
}); | ||
} catch (error) { | ||
hasConnection = false; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve health check implementation for better reliability and maintainability
The current implementation has several areas for improvement:
- No timeout specified for the fetch request
- Response status is not validated
- Unnecessary nesting of promise chain within try-catch
- Silent error handling without logging
Consider this more robust implementation:
- try {
- await fetch(event.locals.backendUrl + '/api/v1/health')
- .then(() => {
- hasConnection = true;
- })
- .catch((error) => {
- hasConnection = false;
- });
- } catch (error) {
- hasConnection = false;
- }
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
+
+ const response = await fetch(`${event.locals.backendUrl}/api/v1/health`, {
+ signal: controller.signal
+ });
+ clearTimeout(timeoutId);
+
+ hasConnection = response.ok;
+
+ if (!response.ok) {
+ console.error(`Health check failed with status: ${response.status}`);
+ }
+ } catch (error) {
+ console.error('Backend health check failed:', error);
+ hasConnection = false;
+ }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
try { | |
await fetch(event.locals.backendUrl + '/api/v1/health') | |
.then(() => { | |
hasConnection = true; | |
}) | |
.catch((error) => { | |
hasConnection = false; | |
}); | |
} catch (error) { | |
hasConnection = false; | |
} | |
try { | |
const controller = new AbortController(); | |
const timeoutId = setTimeout(() => controller.abort(), 5000); | |
const response = await fetch(`${event.locals.backendUrl}/api/v1/health`, { | |
signal: controller.signal | |
}); | |
clearTimeout(timeoutId); | |
hasConnection = response.ok; | |
if (!response.ok) { | |
console.error(`Health check failed with status: ${response.status}`); | |
} | |
} catch (error) { | |
console.error('Backend health check failed:', error); | |
hasConnection = false; | |
} |
🧰 Tools
🪛 Biome (1.9.4)
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
🪛 eslint
[error] 37-37: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
[error] 40-40: 'error' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Check: Lint
[failure] 37-37:
'error' is defined but never used
[failure] 40-40:
'error' is defined but never used
9499285
to
2e2e4e8
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
📒 Files selected for processing (1)
src/hooks.server.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/hooks.server.ts
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
🔇 Additional comments (2)
src/hooks.server.ts (2)
30-42
: Improve health check implementation
The current implementation could be more robust. The previous review comments already provided comprehensive suggestions for improvements, including:
- Adding timeout handling
- Validating response status
- Simplifying promise handling
- Adding proper error logging
🧰 Tools
🪛 Biome (1.9.4)
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
33-33
: Use template literals instead of string concatenation
🧰 Tools
🪛 Biome (1.9.4)
[error] 33-33: Template literals are preferred over string concatenation.
Unsafe fix: Use a template literal.
(lint/style/useTemplate)
if (!hasConnection) { | ||
throw redirect(307, '/connect'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick (assertive)
Consider implementing redirect debouncing
While the redirect logic is correct, frequent health check failures could lead to rapid redirects, potentially causing a poor user experience. Consider implementing a grace period before redirecting.
// Add at the top of the file
let lastRedirectTime = 0;
const REDIRECT_COOLDOWN = 5000; // 5 seconds
// Replace the redirect logic
if (!hasConnection) {
const now = Date.now();
if (now - lastRedirectTime > REDIRECT_COOLDOWN) {
lastRedirectTime = now;
throw redirect(307, '/connect');
}
// If within cooldown period, continue with degraded service
console.warn('Backend connection failed but within redirect cooldown period');
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't want to be spamming health with every API call. We need to check request responses from backend like in the error interceptor. This should be removed also.
Summary by CodeRabbit
New Features
/connect
route if the backend service is unreachable.Bug Fixes