Skip to content

Add information about daily notable deaths #444

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

Open
wants to merge 12 commits into
base: dev
Choose a base branch
from
Open

Conversation

cristianpb
Copy link
Member

@cristianpb cristianpb commented Feb 2, 2025

  • Prendre en compte les données avec information sur wikidata.
  • Possibilité d'utiliser sur le front ainsi:

homepage

Summary by CodeRabbit

  • New Features
    • The system now automatically refreshes daily status data, ensuring that health checks include the most up-to-date information.
    • A daily reset mechanism has been introduced to update status data at midnight, enhancing reliability and timeliness of status information.
  • Bug Fixes
    • Improved CSV output formatting for better readability.
  • Tests
    • Added new test coverage to verify daily status data fetching functionality.

Copy link

coderabbitai bot commented Feb 2, 2025

Walkthrough

The changes add daily data fetching and caching of death records in the backend's status controller. A new asynchronous function resetTodayDeces queries Elasticsearch via HTTP for today's records, filters and maps them, and stores the results in todayDeces. The resetAtMidnight function schedules this update to run daily at midnight, maintaining fresh cached data independently of existing methods.

Changes

File Change Summary
backend/src/controllers/status.controller.ts Added variable todayDeces; new functions resetTodayDeces (fetches and processes today's death records) and resetAtMidnight (schedules daily refresh at midnight); added standardized logging helper; updated /version endpoint to include cached data.
backend/package.json Updated multiple dependencies and devDependencies to newer versions; removed eslint-plugin-react.
backend/src/controllers/aggregation.controller.ts Replaced string concatenations with template literals for CSV output; removed ESLint disable comments related to string conversion.
backend/src/controllers/search.spec.ts Added test for resetTodayDeces function verifying it returns expected data for a given date.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SC as StatusController
    participant ES as ElasticSearch

    Client->>SC: Request version info
    SC->>SC: Check if todayDeces exists
    alt todayDeces is empty
        SC->>ES: Query for today's records
        ES-->>SC: Return records
        SC->>SC: Filter and map records (using wikidata & buildResultSingle)
    else
        Note over SC: Use cached todayDeces value
    end
    SC-->Client: Return response with version info and todayDeces
    Note over SC: resetAtMidnight schedules a reset at midnight daily
Loading

Possibly related PRs

  • Fix/socket control #463: Refactors Elasticsearch calls in status.controller.ts to use the official @elastic/elasticsearch client instead of HTTP requests, relating to data access and caching in the same controller.

Suggested reviewers

  • rhanka

Poem

I'm a little rabbit with code so spry,
Hopping through logic as the midnight draws nigh.
With queries at dusk and resets in the night,
I fetch fresh data, making everything right.
Carrots and code twirl in a delightful spree,
Celebrating changes with a joyful, swift glee!
Happy leaps in logic, from me to thee!

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f892098 and 061e241.

📒 Files selected for processing (1)
  • backend/src/controllers/status.controller.ts (2 hunks)

Comment on lines +3 to +4
import { wikidata } from '../wikidata';
import { buildResultSingle } from '../models/result';
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider moving state management inside the class.

The todayDeces variable is declared outside the class scope. This could lead to state management issues if multiple instances of the controller are created.

Consider these improvements:

  1. Move the variable inside the class
  2. Add proper typing instead of []
-let todayDeces: [];
 @Route('')
 export class StatusController extends Controller {
+  private todayDeces: Array<any> = [];

Also applies to: 11-11

Comment on lines 59 to 61
if (! todayDeces) {
todayDeces = await resetTodayDeces()
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and consider parallelizing requests.

The version method could be improved in terms of error handling and performance.

  1. Add error handling for resetTodayDeces
  2. Consider parallelizing the independent requests
-    if (! todayDeces) {
-      todayDeces = await resetTodayDeces()
-    }
+    if (!todayDeces) {
+      try {
+        todayDeces = await resetTodayDeces();
+      } catch (error) {
+        console.error('Failed to fetch today\'s deaths:', error);
+        todayDeces = [];
+      }
+    }

Consider using Promise.all to parallelize the requests:

const [countResponse, lastRecordResponse, updateResponse, todayResponse] = await Promise.all([
  !uniqRecordsCount ? axios(`http://elasticsearch:9200/deces/_count`) : null,
  (!lastRecordDate || !lastDataset) ? axios(`http://elasticsearch:9200/deces/_search?sort=SOURCE:desc,DATE_DECES.raw:desc&size=1`) : null,
  !updateDate ? axios(`http://elasticsearch:9200/_cat/indices/deces?h=creation.date.string`) : null,
  !todayDeces ? resetTodayDeces() : null
]);

Comment on lines 86 to 102
const resetAtMidnight = () => {
const now = new Date();
const night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
0, 0, 0
);
const msToMidnight = night.getTime() - now.getTime();

setTimeout(() => {
resetTodayDeces();
resetAtMidnight();
}, msToMidnight);
}

resetAtMidnight();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address potential memory leaks in resetAtMidnight.

The current implementation could lead to memory leaks and lacks proper error handling.

Consider these improvements:

+let midnightTimer: NodeJS.Timeout;
+
 const resetAtMidnight = () => {
     const now = new Date();
     const night = new Date(
         now.getFullYear(),
         now.getMonth(),
         now.getDate() + 1,
         0, 0, 0
     );
     const msToMidnight = night.getTime() - now.getTime();

-    setTimeout(() => {
-        resetTodayDeces();
-        resetAtMidnight();
-    }, msToMidnight);
+    // Clear existing timer to prevent memory leaks
+    if (midnightTimer) {
+      clearTimeout(midnightTimer);
+    }
+
+    midnightTimer = setTimeout(async () => {
+        try {
+            todayDeces = await resetTodayDeces();
+            resetAtMidnight();
+        } catch (error) {
+            console.error('Failed to reset at midnight:', error);
+            // Retry in 5 minutes if failed
+            setTimeout(resetAtMidnight, 5 * 60 * 1000);
+        }
+    }, msToMidnight);
 }

+// Add cleanup method
+export const cleanup = () => {
+    if (midnightTimer) {
+        clearTimeout(midnightTimer);
+    }
+};
📝 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
const resetAtMidnight = () => {
const now = new Date();
const night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
0, 0, 0
);
const msToMidnight = night.getTime() - now.getTime();
setTimeout(() => {
resetTodayDeces();
resetAtMidnight();
}, msToMidnight);
}
resetAtMidnight();
let midnightTimer: NodeJS.Timeout;
const resetAtMidnight = () => {
const now = new Date();
const night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
0, 0, 0
);
const msToMidnight = night.getTime() - now.getTime();
// Clear existing timer to prevent memory leaks
if (midnightTimer) {
clearTimeout(midnightTimer);
}
midnightTimer = setTimeout(async () => {
try {
todayDeces = await resetTodayDeces();
resetAtMidnight();
} catch (error) {
console.error('Failed to reset at midnight:', error);
// Retry in 5 minutes if failed
setTimeout(resetAtMidnight, 5 * 60 * 1000);
}
}, msToMidnight);
}
resetAtMidnight();
// Add cleanup method
export const cleanup = () => {
if (midnightTimer) {
clearTimeout(midnightTimer);
}
};

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

🧹 Nitpick comments (4)
backend/src/controllers/status.controller.ts (4)

14-21: Add type definition for the log function parameter.

The log function's parameter should have a more specific type than any to ensure type safety.

-const log = (json:any) => {
+interface LogData {
+  resetTodayDecesError?: unknown;
+  [key: string]: unknown;
+}
+const log = (json: LogData): void => {

74-82: Define a proper interface for the version endpoint response.

The response type is currently any, which reduces type safety. Define an interface for the response structure.

+interface VersionResponse {
+  backend: string;
+  uniqRecordsCount: number;
+  lastRecordDate: string;
+  lastDataset: string;
+  updateDate: string;
+  todayDeces: Array<any>;  // Replace 'any' with proper type from buildResultSingle
+}

-  public async version(): Promise<any> {
+  public async version(): Promise<VersionResponse> {

92-92: Consider making the size limit configurable.

The hardcoded size limit of 3 might be too restrictive. Consider making it configurable through environment variables.

+const DAILY_DEATHS_LIMIT = process.env.DAILY_DEATHS_LIMIT || '10';
+
 const resetTodayDeces = async (): Promise<Array<any>> => {
   try {
     const response = await axios({
       url: `http://elasticsearch:9200/deces/_search`,
       params: {
         q: `DATE_DECES:${today}`,
-        size: 3
+        size: parseInt(DAILY_DEATHS_LIMIT, 10)
       },

124-124: Control the initialization of the midnight reset.

The immediate invocation of resetAtMidnight might cause issues during testing or server restarts. Consider controlling this through the class initialization.

-resetAtMidnight();
+export const initializeResetSchedule = () => {
+  resetAtMidnight();
+};

Then initialize it in your server startup code where you have better control over the timing and can skip it during tests.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 061e241 and dbb1775.

📒 Files selected for processing (1)
  • backend/src/controllers/status.controller.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: 🐳 Build docker image

Comment on lines 108 to 122
const resetAtMidnight = () => {
const now = new Date();
const night = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1,
0, 0, 0
);
const msToMidnight = night.getTime() - now.getTime();

setTimeout(() => {
resetTodayDeces();
resetAtMidnight();
}, msToMidnight);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timezone handling for accurate midnight calculation.

The midnight calculation doesn't account for timezones, which could cause issues in different regions.

+const TIMEZONE = process.env.TIMEZONE || 'UTC';
+
 const resetAtMidnight = () => {
-    const now = new Date();
+    const now = new Date().toLocaleString('en-US', { timeZone: TIMEZONE });
     const night = new Date(
         now.getFullYear(),
         now.getMonth(),
         now.getDate() + 1,
         0, 0, 0
     );
+    // Convert to timezone-specific timestamp
+    night.setTime(night.getTime() + night.getTimezoneOffset() * 60 * 1000);
     const msToMidnight = night.getTime() - now.getTime();

Committable suggestion skipped: line range outside the PR's diff.

@rhanka
Copy link
Member

rhanka commented Jul 11, 2025

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef2bb51 and bf8793d.

📒 Files selected for processing (2)
  • backend/src/controllers/search.spec.ts (2 hunks)
  • backend/src/controllers/status.controller.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/controllers/status.controller.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
backend/src/controllers/search.spec.ts (1)
backend/src/controllers/status.controller.ts (1)
  • resetTodayDeces (130-154)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: 🐳 Build docker image

@@ -1,4 +1,5 @@
import { SearchController } from './search.controller';
import { resetTodayDeces } from './status.controller';
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Move test to the appropriate file.

The import suggests that this test file is testing functionality from status.controller.ts, but the tests should be colocated with their respective controllers.

Consider moving the test to status.spec.ts instead of importing the function here.

🤖 Prompt for AI Agents
In backend/src/controllers/search.spec.ts at line 2, the test imports a function
from status.controller, indicating it tests status controller functionality. To
keep tests organized, move this test code from search.spec.ts to status.spec.ts
so that tests are colocated with their respective controllers. Remove the import
and related tests from search.spec.ts after moving.

Comment on lines +157 to +162
describe('status.controller.ts - today deaths', () => {
it('today deaths', async () => {
const todayDeces = await resetTodayDeces('20200620');
expect(todayDeces.length).to.equal(1);
});
});
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 test robustness and relocate to appropriate file.

This test has several issues that should be addressed:

  1. Wrong location: The test is in search.spec.ts but tests functionality from status.controller.ts
  2. Brittle assertion: Expecting exactly 1 result for a hardcoded date could fail if test data changes
  3. Limited validation: Only checks array length, not the actual content or structure

Move this test to status.spec.ts and improve the test:

-describe('status.controller.ts - today deaths', () => {
-  it('today deaths', async () => {
-    const todayDeces = await resetTodayDeces('20200620');
-    expect(todayDeces.length).to.equal(1);
-  });
-});

In backend/src/controllers/status.spec.ts:

describe('status.controller.ts - today deaths', () => {
  it('should return array of death records for valid date', async () => {
    const todayDeces = await resetTodayDeces('20200620');
    expect(Array.isArray(todayDeces)).to.equal(true);
    expect(todayDeces.length).to.be.greaterThanOrEqual(0);
    expect(todayDeces.length).to.be.lessThanOrEqual(3);
    
    // Verify structure if records exist
    if (todayDeces.length > 0) {
      expect(todayDeces[0]).to.have.property('name');
      expect(todayDeces[0]).to.have.property('death');
    }
  });
  
  it('should return empty array for invalid date', async () => {
    const todayDeces = await resetTodayDeces('invalid-date');
    expect(todayDeces).to.be.an('array');
    expect(todayDeces.length).to.equal(0);
  });
});
🤖 Prompt for AI Agents
In backend/src/controllers/search.spec.ts around lines 157 to 162, the test for
today deaths is misplaced and fragile. Move this test to
backend/src/controllers/status.spec.ts and improve it by checking that the
result is an array, validating the length is within a reasonable range, and
verifying the structure of the records if any exist. Also, add a test case for
invalid dates that expects an empty array. This will make the tests more robust
and correctly located.

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