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

Logging to Logtail inside the Netlify update-settings function #1265

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

jaybuidl
Copy link
Member

@jaybuidl jaybuidl commented Oct 9, 2023

PR-Codex overview

This PR focuses on making changes related to the settings and notifications functionality. It includes the deletion of some files, updates to configuration files, addition of new types/interfaces, addition of new regular expressions, creation of new scripts, and updates to various components and utils.

Detailed summary

  • Deleted index.tsx, FormNotifs/index.tsx, FormEmail.tsx, and vscode/settings.json files.
  • Updated prettier.configPath and added sonarlint.connectedMode.project in vscode/settings.json.
  • Added new interfaces ISettings, IHelp, and IDappList in navbar/index.tsx.
  • Updated Help.tsx to import IHelp from ...
  • Added new entry contactDetails in eip712-messages.ts.
  • Updated index.ts to add new regex constants.
  • Created new script generateSupabaseTypes.sh.
  • Updated Menu/index.tsx to import IHelp and ISettings from ...
  • Updated navbar/Menu/Settings/index.tsx to import ISettings from ../../index.
  • Updated navbar/Menu/Settings/Notifications/index.tsx to import ISettings from ../../../index and added new component FormContactDetails.
  • Updated package.json to add new script generate:supabase.
  • Created new component FormContact in navbar/Menu/Settings/Notifications/FormContactDetails/FormContact.tsx.
  • Updated dependencies and devDependencies in package.json.

The following files were skipped due to too many changes: web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx, web/src/types/supabase-notification.ts, web/netlify/functions/update-settings.ts, web/src/types/supabase-datalake.ts, yarn.lock

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Enhanced error handling and logging functionality for improved robustness.
    • Introduced a new logging utility with structured logging capabilities.
  • Bug Fixes

    • Improved error reporting for various scenarios, including invalid inputs and missing data.
  • Chores

    • Added new dependencies to enhance logging capabilities.

@netlify
Copy link

netlify bot commented Oct 9, 2023

Deploy Preview for kleros-v2 ready!

Name Link
🔨 Latest commit a54c071
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2/deploys/652490f377389300080d3e60
😎 Deploy Preview https://deploy-preview-1265--kleros-v2.netlify.app/
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@jaybuidl jaybuidl force-pushed the feat(web)/notification-system-logtail branch from b48bee3 to a54c071 Compare October 9, 2023 23:46
@codeclimate
Copy link

codeclimate bot commented Oct 9, 2023

Code Climate has analyzed commit a54c071 and detected 113 issues on this pull request.

Here's the issue category breakdown:

Category Count
Complexity 2
Duplication 37
Style 74

View more on Code Climate.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Oct 9, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 2 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

@jaybuidl jaybuidl changed the title Feat(web)/notification system logtail Logging to Logtail inside the Netlify update-settings function Oct 9, 2023
@jaybuidl jaybuidl changed the base branch from dev to feat(web)/notification-system October 9, 2023 23:49
Base automatically changed from feat(web)/notification-system to dev October 9, 2023 23:52
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The changes primarily involve enhancements to error handling and logging within the update-settings.ts file, along with the introduction of a new logging utility in logger.ts. The update-settings.ts file now utilizes a centralized logging function for better error management and includes a logger initialized with environment tokens. Additionally, the package.json file has been updated with new dependencies to support the logging functionality. These modifications aim to improve the robustness and traceability of the code.

Changes

File Path Change Summary
web/netlify/functions/update-settings.ts Enhanced error handling and logging; added logAndThrowNewError method; improved JSON parsing error management.
web/package.json Added dependencies: @logtail/pino, pino, and pino-pretty for logging capabilities.
web/src/utils/logger.ts Introduced createLogger and throwNewError functions for structured logging and error handling.

Poem

In the code where errors dwell,
A logger's tale begins to swell.
With tokens bright and logs so clear,
We chase the bugs, we hold them near.
So hop along, let errors flee,
For logging's here, as bright as can be! 🐇✨


🪧 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 or @coderabbitai title 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
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: 6

🧹 Outside diff range and nitpick comments (2)
web/src/utils/logger.ts (1)

24-24: Simplify object property shorthand for targets

You can simplify the code by using the object property shorthand syntax when the property name and the variable name are the same.

Apply this diff to simplify:

-     pino.transport({ targets: targets })
+     pino.transport({ targets })
web/netlify/functions/update-settings.ts (1)

Line range hint 88-96: Correct the usage of verifyTypedData; compare the recovered address

The verifyTypedData function returns the recovered address, not a boolean. Currently, the code assigns the return value to isValid and checks if it's falsy, which will not work as intended. To properly verify the signature, compare the recovered address with the expected address.

Apply this diff to fix the verification logic:

-const isValid = await verifyTypedData({
+const recoveredAddress = await verifyTypedData({
   ...data,
   signature,
 });
-if (!isValid) {
-  // If the recovered address does not match the provided address, return an error
+if (recoveredAddress.toLowerCase() !== lowerCaseAddress) {
+  // The recovered address does not match the provided address
   logAndThrowNewError("Signature verification failed");
-  throw new Error("Signature verification failed");
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a2a7b5d and a54c071.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • web/netlify/functions/update-settings.ts (7 hunks)
  • web/package.json (2 hunks)
  • web/src/utils/logger.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
web/netlify/functions/update-settings.ts (1)

Line range hint 101-109: Verify consistency in table names between deletion and upsert operations

In the deletion operation, the code references the "users" table, whereas the upsert operation uses the "user-settings" table. Please confirm that this is intentional and that the correct tables are being accessed. Inconsistent table usage might lead to data integrity issues.

Run the following script to verify the table usage across the codebase:

✅ Verification successful

Table Usage is Consistent and Intentional

After verifying the codebase, both the "users" and "user-settings" tables are exclusively used within web/netlify/functions/update-settings.ts. The "users" table handles the deletion of user records, while the "user-settings" table manages the upsertion of user-specific settings. This separation ensures clear boundary management between general user data and user settings, maintaining data integrity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of "users" and "user-settings" tables in the codebase.

# Search for usages of the "users" table
echo "Usages of 'from(\"users\")':"
rg 'from\("users"\)'

# Search for usages of the "user-settings" table
echo "Usages of 'from(\"user-settings\")':"
rg 'from\("user-settings"\)'

Length of output: 418


Script:

#!/bin/bash
# Description: Further verify the distinct roles of "users" and "user-settings" tables in the codebase.

# Search for all usages of the "users" table and display surrounding context
echo "Detailed usages of 'from(\"users\")':"
rg -C 3 'from\("users"\)'

# Search for all usages of the "user-settings" table and display surrounding context
echo "Detailed usages of 'from(\"user-settings\")':"
rg -C 3 'from\("user-settings"\)'

Length of output: 1480

@@ -70,6 +70,7 @@
"@filebase/client": "^0.0.5",
"@kleros/kleros-v2-contracts": "workspace:^",
"@kleros/ui-components-library": "^2.6.2",
"@logtail/pino": "^0.4.12",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Unused logging dependencies detected

It appears that "@logtail/pino" is added as a dependency but is not being utilized in the codebase. Additionally, "pino-pretty" is included but not referenced in any npm scripts or configuration files.

Please verify whether these dependencies are intended to be used and ensure they are properly integrated. If they are not required, consider removing them to maintain a clean and efficient dependency list.

🔗 Analysis chain

New logging dependencies added

The addition of "@logtail/pino", "pino", and "pino-pretty" dependencies indicates an enhancement in the project's logging capabilities. This aligns with the PR objectives of improving error handling and logging.

A few points to consider:

  1. Ensure that these new dependencies are compatible with the existing project setup.
  2. Verify that the chosen versions are stable and appropriate for the project's needs.
  3. Update any relevant documentation to reflect the new logging system.
  4. Consider adding a brief comment in the package.json file explaining the purpose of these new dependencies for future reference.

To ensure these new dependencies are being utilized in the project, let's run the following script:

Also applies to: 91-92

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new logging dependencies in the project

# Test: Search for import or require statements of the new logging libraries
echo "Searching for usage of new logging libraries:"
rg --type typescript --type javascript -e "from ['\"]@logtail/pino['\"]" -e "from ['\"]pino['\"]" -e "require\(['\"]@logtail/pino['\"]" -e "require\(['\"]pino['\"]"

# Test: Check if pino-pretty is used in any npm scripts
echo "Checking for pino-pretty usage in npm scripts:"
jq '.scripts | to_entries[] | select(.value | contains("pino-pretty"))' web/package.json

Length of output: 512


Script:

#!/bin/bash
# Description: Verify the usage of new logging dependencies in the project

# Test: Search for import or require statements of the new logging libraries
echo "Searching for usage of new logging libraries in .ts and .js files:"
rg -g "*.ts" -g "*.js" -e "from ['\"]@logtail/pino['\"]" -e "from ['\"]pino['\"]" -e "require\(['\"]@logtail/pino['\"]\)" -e "require\(['\"]pino['\"]\)" .

# Test: Check if pino-pretty is used in any npm scripts
echo "Checking for pino-pretty usage in npm scripts:"
jq '.scripts | to_entries[] | select(.value | contains("pino-pretty"))' web/package.json

# Additional Test: Search for pino-pretty usage in configuration files
echo "Searching for pino-pretty usage in configuration files:"
rg -g "*.config.*" "pino-pretty"

Length of output: 886

Comment on lines +7 to +10
target: "pino-pretty",
options: {},
level: "info",
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider removing pino-pretty from production logging

pino-pretty is intended for development and debugging purposes and is not recommended for use in production environments due to performance overhead and potential security concerns. Including it in your production logger could impact performance.

Comment on lines +28 to +40
export const throwNewError = (logger: pino.Logger, message: string, error?: any) => {
if (!error) {
logger.error(message);
throw new Error(message);
}
if (typeof error === "string") {
logger.error(error, message);
throw new Error(message + ": " + error);
} else if (error instanceof Error) {
logger.error(error, message);
throw new Error(message + ": " + error.name + ": " + error.message);
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling in throwNewError function

Consider refactoring the function to handle all error types consistently and to preserve stack traces by re-throwing the original error when possible. This ensures that the original error information is not lost, making debugging easier.

Apply this diff to improve error handling:

-export const throwNewError = (logger: pino.Logger, message: string, error?: any) => {
-  if (!error) {
-    logger.error(message);
-    throw new Error(message);
-  }
-  if (typeof error === "string") {
-    logger.error(error, message);
-    throw new Error(message + ": " + error);
-  } else if (error instanceof Error) {
-    logger.error(error, message);
-    throw new Error(message + ": " + error.name + ": " + error.message);
-  }
-};
+export const throwNewError = (logger: pino.Logger, message: string, error?: unknown): never => {
+  logger.error({ error }, message);
+  if (error instanceof Error) {
+    throw error;
+  } else if (typeof error === "string") {
+    throw new Error(`${message}: ${error}`);
+  } else {
+    throw new Error(message);
+  }
+};
📝 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
export const throwNewError = (logger: pino.Logger, message: string, error?: any) => {
if (!error) {
logger.error(message);
throw new Error(message);
}
if (typeof error === "string") {
logger.error(error, message);
throw new Error(message + ": " + error);
} else if (error instanceof Error) {
logger.error(error, message);
throw new Error(message + ": " + error.name + ": " + error.message);
}
};
export const throwNewError = (logger: pino.Logger, message: string, error?: unknown): never => {
logger.error({ error }, message);
if (error instanceof Error) {
throw error;
} else if (typeof error === "string") {
throw new Error(`${message}: ${error}`);
} else {
throw new Error(message);
}
};

Comment on lines +95 to 96
logAndThrowNewError("Signature verification failed");
throw new Error("Signature verification failed");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove redundant throw after logAndThrowNewError

The logAndThrowNewError function already throws an error after logging. The subsequent throw new Error("Signature verification failed"); will not be reached and is redundant.

Apply this diff to remove the redundant throw statement:

   logAndThrowNewError("Signature verification failed");
-  throw new Error("Signature verification failed");
📝 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
logAndThrowNewError("Signature verification failed");
throw new Error("Signature verification failed");
logAndThrowNewError("Signature verification failed");

return { statusCode: 500, body: JSON.stringify({ message: `Error: ${err}` }) };
} finally {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid returning internal error details in HTTP responses

Returning internal error objects directly to the client can expose sensitive information or implementation details. It's safer to provide a generic error message to the client while logging the detailed error internally.

Apply this diff to return a generic error message:

 logger.error(err);
-return { statusCode: 500, body: JSON.stringify({ message: `Error: ${err}` }) };
+return { statusCode: 500, body: JSON.stringify({ message: "An unexpected error occurred." }) };

Committable suggestion was skipped due to low confidence.

Comment on lines +20 to +21
const logger = createLogger(process.env.LOGTAIL_TOKEN).child({ function: "update-settings" });
const logAndThrowNewError = (message: string, error?: any) => throwNewError(logger, message, error);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure LOGTAIL_TOKEN is defined and handle missing token cases

The LOGTAIL_TOKEN environment variable is used to initialize the logger without a check for its existence. If LOGTAIL_TOKEN is undefined, createLogger may fail or behave unexpectedly. To prevent potential runtime errors, consider adding a check to handle missing or invalid LOGTAIL_TOKEN values.

Apply this diff to add the check:

+if (!process.env.LOGTAIL_TOKEN) {
+  throw new Error("LOGTAIL_TOKEN environment variable is not set.");
+}
 const logger = createLogger(process.env.LOGTAIL_TOKEN).child({ function: "update-settings" });
📝 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 logger = createLogger(process.env.LOGTAIL_TOKEN).child({ function: "update-settings" });
const logAndThrowNewError = (message: string, error?: any) => throwNewError(logger, message, error);
if (!process.env.LOGTAIL_TOKEN) {
throw new Error("LOGTAIL_TOKEN environment variable is not set.");
}
const logger = createLogger(process.env.LOGTAIL_TOKEN).child({ function: "update-settings" });
const logAndThrowNewError = (message: string, error?: any) => throwNewError(logger, message, error);

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.

1 participant