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

feat(scripts): add timestamp update to check-connect-data #17015

Merged
merged 1 commit into from
Feb 14, 2025

Conversation

karliatto
Copy link
Member

Description

Add timestamp update to check-connect-data

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

The changes introduce a new function, getLatestTimestamp, which calculates the latest timestamp from an array of string timestamps. This function returns the latest timestamp in ISO format or null if the input array is empty. Within the updateConfigFromJSON function, an array named timestamps is initialized to collect timestamps from the fetched authenticity data. After processing all authenticity data, the latest timestamp is determined using getLatestTimestamp. A sanity check is added to ensure that a timestamp is present before it is assigned to the deviceAuthenticityConfig. Additionally, the error handling for the absence of a timestamp has been improved with a specific error message.

✨ 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: 0

🧹 Nitpick comments (3)
scripts/ci/check-connect-data.ts (3)

38-47: Add input validation and optimize performance.

The timestamp handling logic could be more robust and efficient:

  1. Add validation for timestamp format
  2. Handle invalid dates
  3. Optimize for large arrays by using a single iteration

Consider this improved implementation:

 const getLatestTimestamp = (timestamps: string[]): string | null => {
     if (timestamps.length === 0) {
         return null;
     }
 
-    const dateObjects = timestamps.map(timestamp => new Date(timestamp));
-    const latestDate = new Date(Math.max(...dateObjects.map(date => date.getTime())));
+    let latestDate: Date | null = null;
+    for (const timestamp of timestamps) {
+        const date = new Date(timestamp);
+        if (isNaN(date.getTime())) {
+            console.warn(`Invalid timestamp format: ${timestamp}`);
+            continue;
+        }
+        if (!latestDate || date > latestDate) {
+            latestDate = date;
+        }
+    }
 
-    return latestDate.toISOString();
+    return latestDate ? latestDate.toISOString() : null;
 };

76-81: Enhance error handling with more descriptive message.

The error message could be more descriptive to aid in debugging.

Consider this improvement:

 const latestTimestamp = getLatestTimestamp(timestamps);
 
 if (!latestTimestamp) {
     // Sanity check and type safety.
-    throw new Error('Timestamp should always be present.');
+    console.error('Failed to determine latest timestamp from:', timestamps);
+    throw new Error('No valid timestamps found in authenticity data. This is unexpected as each authenticity file should contain a timestamp.');
 }

83-83: Improve type safety for timestamp assignment.

Consider using a constant for the timestamp key and ensuring type safety.

Consider these improvements:

// At the top of the file with other constants
const TIMESTAMP_KEY = 'timestamp' as const;

// Update the assignment
deviceAuthenticityConfig[TIMESTAMP_KEY] = latestTimestamp;

Also, ensure that DeviceAuthenticityConfig type (imported from './deviceAuthenticityConfigTypes') includes the timestamp property:

interface DeviceAuthenticityConfig {
  [key: string]: {
    rootPubKeys: string[];
    caPubKeys: string[];
    debug: {
      rootPubKeys: string[];
      caPubKeys: string[];
    };
  } | string; // Allow string for timestamp
  timestamp: string; // Explicitly define timestamp
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8304a7b and 7389924.

📒 Files selected for processing (1)
  • scripts/ci/check-connect-data.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: Analyze with CodeQL (javascript)
  • GitHub Check: Setup and Cache Dependencies
🔇 Additional comments (1)
scripts/ci/check-connect-data.ts (1)

56-62: Verify if dev timestamps should be included.

Currently, only timestamps from production authenticity data are being collected. Should timestamps from authenticityDev data also be considered?

Please confirm if this is intentional or if we should also collect timestamps from dev data:

 const timestamps: string[] = [];
 
 for (const deviceKey of devicesKeys) {
     const { authenticity, authenticityDev } = authenticityPaths[deviceKey];
     const authenticityUrl = `${AUTHENTICITY_BASE_URL}/${authenticity}`;
     const authenticityData = await fetchJSON(authenticityUrl);
     timestamps.push(authenticityData.timestamp);
+    const authenticityDevUrl = `${AUTHENTICITY_BASE_URL}/${authenticityDev}`;
+    const authenticityDevData = await fetchJSON(authenticityDevUrl);
+    timestamps.push(authenticityDevData.timestamp);

Comment on lines 43 to 46
const dateObjects = timestamps.map(timestamp => new Date(timestamp));
const latestDate = new Date(Math.max(...dateObjects.map(date => date.getTime())));

return latestDate.toISOString();
Copy link
Member

Choose a reason for hiding this comment

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

nitpick (no need for mapping the timestamps twice...):

Suggested change
const dateObjects = timestamps.map(timestamp => new Date(timestamp));
const latestDate = new Date(Math.max(...dateObjects.map(date => date.getTime())));
return latestDate.toISOString();
const latestTime = Math.max(...timestamps.map(Date.parse));
return new Date(latestTime).toISOString();
};

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, updated!

Copy link
Member

@matejkriz matejkriz left a comment

Choose a reason for hiding this comment

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

Works fine, thank you! Tested here #17016

Would be nice to apply it right away so the timestamp is already updated. we will see if it will work correctly during daily scheduled run.

@karliatto karliatto force-pushed the feat/check-connect-data-update-timestamp branch from 7389924 to 9d0d4d1 Compare February 14, 2025 17:04
@karliatto karliatto added the no-project This label is used to specify that PR doesn't need to be added to a project label Feb 14, 2025
@karliatto karliatto enabled auto-merge (rebase) February 14, 2025 17:05
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

🔭 Outside diff range comments (1)
scripts/ci/check-connect-data.ts (1)

175-175: ⚠️ Potential issue

Fix template literal syntax error.

There's an extra backtick at the end of the error message template literal.

Apply this diff to fix the syntax error:

-                    console.error(`Failed to delete branch ${branchName}:`, error.message``);
+                    console.error(`Failed to delete branch ${branchName}:`, error.message);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7389924 and 9d0d4d1.

📒 Files selected for processing (1)
  • scripts/ci/check-connect-data.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: check-project-or-issue
  • GitHub Check: run-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: build-web
  • GitHub Check: run-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (2)
scripts/ci/check-connect-data.ts (2)

38-46: Optimize timestamp calculation by combining map operations.

The implementation is correct but can be optimized by combining the timestamp parsing and max calculation into a single operation.

Apply this diff to optimize the implementation:

 const getLatestTimestamp = (timestamps: string[]): string | null => {
     if (timestamps.length === 0) {
         return null;
     }

-    const latestTime = Math.max(...timestamps.map(Date.parse));
-
-    return new Date(latestTime).toISOString();
+    const latestTime = Math.max(...timestamps.map(Date.parse));
+    return new Date(latestTime).toISOString();
 };

75-83: LGTM! Good error handling for timestamp update.

The implementation correctly handles the timestamp update with proper validation and error handling.

const updateConfigFromJSON = async () => {
try {
const devicesKeys = Object.keys(authenticityPaths) as AuthenticityPathsKeys[];

// Import the current configuration object
let { deviceAuthenticityConfig } = require(CONFIG_FILE_PATH);

const timestamps: string[] = [];
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 validation for timestamp presence in authenticity data.

The code assumes that authenticityData.timestamp exists without validation. This could lead to runtime errors if the timestamp is undefined.

Apply this diff to add validation:

 const timestamps: string[] = [];

 for (const deviceKey of devicesKeys) {
     const { authenticity, authenticityDev } = authenticityPaths[deviceKey];
     const authenticityUrl = `${AUTHENTICITY_BASE_URL}/${authenticity}`;
     const authenticityData = await fetchJSON(authenticityUrl);
-    timestamps.push(authenticityData.timestamp);
+    if (!authenticityData.timestamp) {
+        throw new Error(`Missing timestamp in authenticity data for ${deviceKey}`);
+    }
+    timestamps.push(authenticityData.timestamp);

Also applies to: 61-61

@karliatto karliatto merged commit 2ae804d into develop Feb 14, 2025
22 of 26 checks passed
@karliatto karliatto deleted the feat/check-connect-data-update-timestamp branch February 14, 2025 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-project This label is used to specify that PR doesn't need to be added to a project
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants