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

Add information about daily notable deaths #444

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

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.

Copy link

coderabbitai bot commented Feb 2, 2025

Walkthrough

The changes update the backend's status controller by adding daily data fetching capabilities. A new function, resetTodayDeces, is introduced to query an Elasticsearch endpoint for today’s records, filter the results using wikidata, and format them with buildResultSingle. The data is stored in a new variable todayDeces and merged into the response of the version method. Additionally, the resetAtMidnight function schedules a daily reset at midnight to update the data, ensuring the controller's status response remains current.

Changes

File Change Summary
backend/.../status.controller.ts Added imports for wikidata and buildResultSingle. Declared variable todayDeces, introduced functions resetTodayDeces (fetches and processes records) and resetAtMidnight (schedules reset at midnight), and updated the version method to include todayDeces in the response.

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

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!

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 75 to 84
const resetTodayDeces = async () => {
let today = new Date().toISOString().split('T')[0].replaceAll("-","")
const response = await axios(`http://elasticsearch:9200/deces/_search?q=DATE_DECES:${today}`);
const records = response.data.hits.hits.filter((item: any) => item._id in wikidata)
if (records.length > 0) {
return records.map((item: any) => buildResultSingle(item))
} else {
return []
}
}
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 type definitions to resetTodayDeces.

The function needs improvements in error handling and type safety.

Apply these improvements:

-const resetTodayDeces = async () => {
+const resetTodayDeces = async (): Promise<Array<any>> => {
   try {
     let today = new Date().toISOString().split('T')[0].replaceAll("-","")
-    const response = await axios(`http://elasticsearch:9200/deces/_search?q=DATE_DECES:${today}`);
+    const response = await axios({
+      url: `http://elasticsearch:9200/deces/_search`,
+      params: {
+        q: `DATE_DECES:${today}`
+      },
+      timeout: 5000
+    });
     const records = response.data.hits.hits.filter((item: any) => item._id in wikidata)
     if (records.length > 0) {
       return records.map((item: any) => buildResultSingle(item))
     } else {
       return []
     }
+  } catch (error) {
+    console.error('Failed to fetch today\'s deaths:', error);
+    return [];
+  }
 }
📝 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 resetTodayDeces = async () => {
let today = new Date().toISOString().split('T')[0].replaceAll("-","")
const response = await axios(`http://elasticsearch:9200/deces/_search?q=DATE_DECES:${today}`);
const records = response.data.hits.hits.filter((item: any) => item._id in wikidata)
if (records.length > 0) {
return records.map((item: any) => buildResultSingle(item))
} else {
return []
}
}
const resetTodayDeces = async (): Promise<Array<any>> => {
try {
let today = new Date().toISOString().split('T')[0].replaceAll("-","")
const response = await axios({
url: `http://elasticsearch:9200/deces/_search`,
params: {
q: `DATE_DECES:${today}`
},
timeout: 5000
});
const records = response.data.hits.hits.filter((item: any) => item._id in wikidata)
if (records.length > 0) {
return records.map((item: any) => buildResultSingle(item))
} else {
return []
}
} catch (error) {
console.error("Failed to fetch today's deaths:", error);
return [];
}
}

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.

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.

1 participant