Skip to content
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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

davidemarcoli
Copy link
Collaborator

@davidemarcoli davidemarcoli commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a health check for the backend service before processing requests, enhancing reliability.
    • Users will be redirected to the /connect route if the backend service is unreachable.
  • Bug Fixes

    • Improved error handling for cases where the backend service is not available, ensuring a smoother user experience.

Copy link

coderabbitai bot commented Nov 29, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes implemented in this pull request modify the configureClientMiddleware function in the src/hooks.server.ts file. A health check is added to verify the backend service's availability by making a fetch request to its health endpoint. A new variable, hasConnection, is introduced to track the success of this operation. If the health check fails, the middleware redirects to the /connect route. The existing error handling logic remains unchanged.

Changes

File Change Summary
src/hooks.server.ts Modified configureClientMiddleware to include a health check for the backend service before request resolution. Introduced hasConnection variable to track fetch success and redirect to /connect if the health check fails. Error handling logic remains unchanged.

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
Loading

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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between efba13e and 9499285.

📒 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')
Copy link

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

  1. Use template literals instead of string concatenation
  2. 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)

Comment on lines 29 to 46

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');
}
Copy link

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:

  1. 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;
}
  1. 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

Comment on lines 32 to 42
try {
await fetch(event.locals.backendUrl + '/api/v1/health')
.then(() => {
hasConnection = true;
})
.catch((error) => {
hasConnection = false;
});
} catch (error) {
hasConnection = false;
}
Copy link

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:

  1. No timeout specified for the fetch request
  2. Response status is not validated
  3. Unnecessary nesting of promise chain within try-catch
  4. 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.

Suggested change
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

@davidemarcoli davidemarcoli force-pushed the bugfix/redirect-to-connect-page-on-error branch from 9499285 to 2e2e4e8 Compare November 29, 2024 14:41
Copy link

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9499285 and 2e2e4e8.

📒 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)

Comment on lines +44 to +46
if (!hasConnection) {
throw redirect(307, '/connect');
}
Copy link

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');
}

Copy link
Collaborator

@Gaisberg Gaisberg left a 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants