Skip to content

feat: Algolia config error handling#4126

Open
Ketan-Agarwal wants to merge 3 commits intoOWASP:mainfrom
Ketan-Agarwal:feat/algolia-config-error-handling
Open

feat: Algolia config error handling#4126
Ketan-Agarwal wants to merge 3 commits intoOWASP:mainfrom
Ketan-Agarwal:feat/algolia-config-error-handling

Conversation

@Ketan-Agarwal
Copy link

Proposed change

Resolves #4107

This PR introduces error handling for Algolia search configuration and data fetching across backend and frontend. It specifically addresses cases where Algolia credentials may be missing or incorrectly configured, preventing unhandled exceptions and providing a better contributing experience.

Checklist

  • Required: I followed the contributing workflow
  • Required: I verified that my code works as intended and resolves the issue as described
  • Required: I ran make check-test locally: all warnings addressed, tests passed
  • I used AI for code, documentation, tests, or communication related to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 28, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced local development experience with credential validation for Algolia search; gracefully returns empty results when credentials are missing instead of causing failures.
    • Non-local environments remain unaffected.
    • Added logging for configuration errors.
  • Tests

    • Added tests verifying credential validation and error handling behavior across different environment configurations.

Walkthrough

Adds a local development guard to the Algolia search function that validates required configuration credentials and returns empty results if missing, along with corresponding test fixtures and test cases to verify the behavior in both local and non-local environments.

Changes

Cohort / File(s) Summary
Algolia Configuration Validation
backend/apps/core/api/internal/algolia.py
Introduces logging and a local development guard that checks ENVIRONMENT variable and validates ALGOLIA_APPLICATION_ID and ALGOLIA_WRITE_API_KEY. Returns empty result set {"hits": [], "nbPages": 0} in local environment when credentials are missing, without proceeding to cache retrieval.
Test Coverage for Algolia Validation
backend/tests/apps/core/api/internal/algolia_test.py
Adds autouse fixture mock_algolia_settings to mock Algolia settings and two test cases: one verifying error logging and empty results when credentials are missing in local environment, another verifying non-local environments bypass the configuration precheck.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR partially addresses issue #4107 with backend error handling for missing Algolia credentials, but lacks the frontend error handling and user-facing message components required by the issue. Implement frontend error handling to catch the backend's Algolia configuration error and display a clear, user-facing message (e.g., toast notification) as specified in issue #4107.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding error handling for Algolia configuration.
Description check ✅ Passed The description is related to the changeset, referencing issue #4107 and explaining the purpose of adding error handling for Algolia configuration.
Out of Scope Changes check ✅ Passed All changes are directly related to the stated objective of adding Algolia configuration error handling; no out-of-scope modifications were introduced.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@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

🧹 Nitpick comments (2)
frontend/src/server/fetchAlgoliaData.ts (1)

60-64: Consider simplifying the redundant AppError check.

The condition error instanceof Error && error.name === 'AppError' is redundant since error instanceof AppError already covers all proper AppError instances. The AppError class explicitly sets this.name = 'AppError' in its constructor, so any instance passing instanceof AppError will also have that name.

♻️ Simplify condition
   } catch (error) {
-    if (error instanceof AppError || (error instanceof Error && error.name === 'AppError')) {
+    if (error instanceof AppError) {
       throw error
     }
     throw new AppError(500, 'Search service error')
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@frontend/src/server/fetchAlgoliaData.ts` around lines 60 - 64, In the catch
block of fetchAlgoliaData (handling errors from the search call), simplify the
redundant check by only testing error instanceof AppError and rethrowing it;
remove the extra (error instanceof Error && error.name === 'AppError') branch so
non-AppError errors are wrapped with new AppError(500, 'Search service error')
as before.
backend/tests/apps/core/api/internal/algolia_test.py (1)

30-37: Consider adding ENVIRONMENT to the mock settings for robustness.

The fixture sets the two Algolia credentials, but get_search_results also accesses settings.ENVIRONMENT. Current tests work because they mock get_search_results or its dependencies, but future tests calling through to the real implementation would get a Mock object for ENVIRONMENT.

🔧 Suggested improvement
 `@pytest.fixture`(autouse=True)
 def mock_algolia_settings():
     """Mock Algolia settings."""
     with patch("apps.core.api.internal.algolia.settings") as mock_settings:
         mock_settings.ALGOLIA_APPLICATION_ID = "test-app-id"
         mock_settings.ALGOLIA_WRITE_API_KEY = "test-api-key"
+        mock_settings.ENVIRONMENT = "test"
         yield mock_settings
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/apps/core/api/internal/algolia_test.py` around lines 30 - 37,
The mock_algolia_settings fixture is missing settings.ENVIRONMENT which
get_search_results expects; update the fixture (mock_algolia_settings) to set
mock_settings.ENVIRONMENT to a concrete string (e.g., "test" or "development")
so tests that exercise get_search_results or the real implementation see a real
environment value rather than a Mock object.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@frontend/src/app/chapters/page.tsx`:
- Around line 30-51: The useEffect that fetches map data currently varies
hitsPerPage by currentPage and re-runs on [currentPage], causing geoLocData
(used for the map) to be replaced with only 25 items when paginating; update the
effect in page.tsx so it always requests hitsPerPage = 1000 from
fetchAlgoliaData and runs only once on mount (useEffect dependency []), calling
fetchAlgoliaData(indexName: 'chapters', query: '', currentPage: 1, hitsPerPage:
1000) and storing the result via setGeoLocData so the map always has the full
dataset independent of pagination state.

---

Nitpick comments:
In `@backend/tests/apps/core/api/internal/algolia_test.py`:
- Around line 30-37: The mock_algolia_settings fixture is missing
settings.ENVIRONMENT which get_search_results expects; update the fixture
(mock_algolia_settings) to set mock_settings.ENVIRONMENT to a concrete string
(e.g., "test" or "development") so tests that exercise get_search_results or the
real implementation see a real environment value rather than a Mock object.

In `@frontend/src/server/fetchAlgoliaData.ts`:
- Around line 60-64: In the catch block of fetchAlgoliaData (handling errors
from the search call), simplify the redundant check by only testing error
instanceof AppError and rethrowing it; remove the extra (error instanceof Error
&& error.name === 'AppError') branch so non-AppError errors are wrapped with new
AppError(500, 'Search service error') as before.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d1c458 and d02dc9f.

📒 Files selected for processing (5)
  • backend/apps/core/api/internal/algolia.py
  • backend/tests/apps/core/api/internal/algolia_test.py
  • frontend/src/app/chapters/page.tsx
  • frontend/src/app/page.tsx
  • frontend/src/server/fetchAlgoliaData.ts

cubic-dev-ai[bot]
cubic-dev-ai bot previously approved these changes Feb 28, 2026
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 5 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 28, 2026
@Ketan-Agarwal
Copy link
Author

Hi @arkid15r, the PR is ready for review. Please let me know if any changes are required.

@Ketan-Agarwal
Copy link
Author

Hi! Just a quick ping on this PR since the original issue deadline just passed. No rush but please let me know if you need me to make any changes.

Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might work but seems a bit to much to me.
@Ketan-Agarwal let's narrow it down to local environment and backend only.
When running backend it should just show a good error message notifying about the misconfiguration. Not having Algolia configured should never be the case for frontend.

- Remove redundant error handling
- Add `mock_settings.ENVIRONMENT` for Algolia test suite
@sonarqubecloud
Copy link

sonarqubecloud bot commented Mar 8, 2026

@Ketan-Agarwal Ketan-Agarwal requested a review from arkid15r March 8, 2026 08:18
Copy link
Contributor

@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.

🧹 Nitpick comments (1)
backend/tests/apps/core/api/internal/algolia_test.py (1)

296-325: Minor: Test name references "warning" but tests logger.error.

The test method name test_algolia_search_logs_warning_when_not_configured_in_local and the docstring mention "warning", but the implementation correctly tests logger.error (line 319), which matches the production code. Consider renaming for consistency:

Suggested rename
     `@patch`("apps.core.api.internal.algolia.settings")
-    def test_algolia_search_logs_warning_when_not_configured_in_local(self, mock_settings):
-        """Test warning is logged and empty results returned locally.
+    def test_algolia_search_logs_error_when_not_configured_in_local(self, mock_settings):
+        """Test error is logged and empty results returned locally.
 
         Verify that when Algolia is not configured in local environment,
-        a warning is logged and empty results are returned.
+        an error is logged and empty results are returned.
         """
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/apps/core/api/internal/algolia_test.py` around lines 296 - 325,
The test name and docstring for
test_algolia_search_logs_warning_when_not_configured_in_local are inconsistent
with the assertion that checks logger.error; rename the test method (and update
its docstring) to reference "error" instead of "warning" — e.g.,
test_algolia_search_logs_error_when_not_configured_in_local — and keep the
assertion against logger.error and the call to algolia_search unchanged so the
behavior and assertions remain consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/tests/apps/core/api/internal/algolia_test.py`:
- Around line 296-325: The test name and docstring for
test_algolia_search_logs_warning_when_not_configured_in_local are inconsistent
with the assertion that checks logger.error; rename the test method (and update
its docstring) to reference "error" instead of "warning" — e.g.,
test_algolia_search_logs_error_when_not_configured_in_local — and keep the
assertion against logger.error and the call to algolia_search unchanged so the
behavior and assertions remain consistent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c52a5cc3-904b-490f-a0d6-ddbdcac8e5e8

📥 Commits

Reviewing files that changed from the base of the PR and between 7255954 and ed3d09f.

📒 Files selected for processing (2)
  • backend/apps/core/api/internal/algolia.py
  • backend/tests/apps/core/api/internal/algolia_test.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve error handling for missing Algolia configuration

2 participants