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

Loading either the Sample or Default database doesn't create a default Agenda Item #2482 #2794

Closed
wants to merge 15 commits into from

Conversation

Ramneet04
Copy link

@Ramneet04 Ramneet04 commented Dec 26, 2024

Loading either the Sample or Default database is now creating a default Agenda Item.

Issue: #2482: #2482

Changes Implemented:
Imported the nanoid() function dynamically.
Add try catch to handle error

Other information
I have read the previous refactor PR and tried to keep things as uniform as possible.
Please suggest any other changes if required.

Summary by CodeRabbit

  • New Features

    • Introduced a new asynchronous function for generating unique tracing IDs.
    • Added a test case to verify the middleware functionality for tracing ID generation.
  • Bug Fixes

    • Enhanced error handling for tracing ID generation to improve reliability.

Copy link

coderabbitai bot commented Dec 26, 2024

Walkthrough

The changes introduce a new asynchronous function getNanoid in the request tracing library that dynamically imports the nanoid package. This modification allows for more flexible ID generation by deferring the import of the nanoid function until it is actually needed, replacing the previous static declaration. The implementation affects both middleware and tracing functions, wrapping the ID generation process in an asynchronous approach with improved error handling.

Changes

File Change Summary
src/libraries/requestTracing.ts Added getNanoid async function for dynamic nanoid import and updated tracing ID retrieval to use the asynchronous approach.
tests/libraries/requestTracing.spec.ts Added a new test case for the requestContext middleware to verify its execution flow with mock request and response objects.

Sequence Diagram

sequenceDiagram
    participant Middleware
    participant Trace
    participant getNanoid
    participant nanoid

    Middleware->>+getNanoid: Request nanoid function
    getNanoid->>+nanoid: Dynamically import
    nanoid-->>-getNanoid: Return customAlphabet
    getNanoid-->>-Middleware: Provide nanoid generator
    Middleware->>Middleware: Generate tracing ID
Loading

Poem

🐰 A rabbit's tale of dynamic delight,
Nanoid now imports with async might!
No more static, we dance and we prance,
Tracing IDs with a flexible glance 🌟
Dynamic imports, our coding delight! 🚀


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.

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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

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 (2)
src/libraries/requestTracing.ts (2)

33-36: Add an explicit return type for getNanoid to satisfy linting rules.

The static analysis tools are indicating that a return type should be explicitly declared. Since this function ultimately returns a () => string wrapped in a Promise, consider specifying Promise<() => string> as follows:

-const getNanoid = async () => {
+const getNanoid = async (): Promise<() => string> => {
  const { customAlphabet } = await import("nanoid");
  return customAlphabet(alphabets, 10);
};
🧰 Tools
🪛 eslint

[error] 33-33: Missing return type on function.

(@typescript-eslint/explicit-function-return-type)

🪛 GitHub Check: Check for linting, formatting, and type errors

[failure] 33-33:
Missing return type on function


88-96: Consider removing or refining the try/catch block.

The catch block simply rethrows the same error without additional handling or logging, which is flagged as unnecessary. If you do not need custom logging or cleanup, removing the try/catch entirely simplifies the flow. Otherwise, add meaningful actions or logs inside the catch block to justify its presence.

-export const trace = async <T>(
-  tracingId: string,
-  method: () => T,
-): Promise<void> => {
-  try {
-    const nanoid = await getNanoid();
-    await requestTracingNamespace.runAndReturn<T>(() => {
-      setTracingId(tracingId || nanoid());
-      return method();
-    });
-  } catch (error) {
-    throw error;
-  }
+export const trace = async <T>(tracingId: string, method: () => T): Promise<void> => {
+  const nanoid = await getNanoid();
+  await requestTracingNamespace.runAndReturn<T>(() => {
+    setTracingId(tracingId || nanoid());
+    return method();
+  });
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 95-95: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

🪛 eslint

[error] 88-96: Unnecessary try/catch wrapper.

(no-useless-catch)

🪛 GitHub Check: Check for linting, formatting, and type errors

[failure] 88-88:
Unnecessary try/catch wrapper

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c5b29a and 9fa1955.

📒 Files selected for processing (1)
  • src/libraries/requestTracing.ts (3 hunks)
🧰 Additional context used
🪛 eslint
src/libraries/requestTracing.ts

[error] 33-33: Missing return type on function.

(@typescript-eslint/explicit-function-return-type)


[error] 88-96: Unnecessary try/catch wrapper.

(no-useless-catch)

🪛 GitHub Check: Check for linting, formatting, and type errors
src/libraries/requestTracing.ts

[failure] 33-33:
Missing return type on function


[failure] 88-88:
Unnecessary try/catch wrapper

🪛 Biome (1.9.4)
src/libraries/requestTracing.ts

[error] 95-95: The catch clause that only rethrows the original error is useless.

An unnecessary catch clause can be confusing.
Unsafe fix: Remove the try/catch clause.

(lint/complexity/noUselessCatch)

src/libraries/requestTracing.ts Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 26, 2024
@Ramneet04
Copy link
Author

Ramneet04 commented Dec 29, 2024

hey @palisadoes here this got a issue which is in separate file a test case is failed so should I address it here or raise a pull request for it??

@palisadoes
Copy link
Contributor

Fix the issue in this PR

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

🔭 Outside diff range comments (1)
src/libraries/requestTracing.ts (1)

Line range hint 92-96: Fix return type and enhance error handling.

There are two issues to address:

  1. The function's return type is Promise<void> but it actually returns Promise<T>
  2. Error handling for getNanoid() should be explicit
 export const trace = async <T>(
   tracingId: string,
   method: () => T,
-): Promise<void> => {
+): Promise<T> => {
   const nanoid = await getNanoid();
-  await requestTracingNamespace.runAndReturn<T>(() => {
+  return requestTracingNamespace.runAndReturn<T>(() => {
     setTracingId(tracingId || nanoid());
     return method();
   });
 };
🧹 Nitpick comments (1)
src/libraries/requestTracing.ts (1)

33-36: Consider caching the nanoid function.

The current implementation dynamically imports customAlphabet on every call. Consider caching the result to avoid unnecessary imports and improve performance.

+let cachedNanoid: (() => string) | null = null;
 const getNanoid: () => Promise<() => string> = async () => {
+  if (cachedNanoid) return cachedNanoid;
   const { customAlphabet } = await import("nanoid");
-  return customAlphabet(alphabets, 10);
+  cachedNanoid = customAlphabet(alphabets, 10);
+  return cachedNanoid;
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fa1955 and 784a9a1.

📒 Files selected for processing (1)
  • src/libraries/requestTracing.ts (3 hunks)
🔇 Additional comments (2)
src/libraries/requestTracing.ts (2)

64-77: LGTM! Error handling has been properly implemented.

The changes properly handle asynchronous nanoid generation and include error handling as suggested in the previous review.


Line range hint 33-96: Verify the relationship with PR objectives.

The PR objectives mention fixing an issue with "Loading either the Sample or Default database doesn't create a default Agenda Item", but this file implements request tracing functionality. Could you clarify how these changes relate to the database loading and agenda item creation issue?

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 31, 2024
@Ramneet04
Copy link
Author

@palisadoes I am trying to fix the error but I'm unable to do it. could u please see it and suggest it to me what could I do.

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 784a9a1 and 2e7ad84.

📒 Files selected for processing (2)
  • src/libraries/requestTracing.ts (3 hunks)
  • tests/libraries/requestTracing.spec.ts (1 hunks)
🔇 Additional comments (3)
tests/libraries/requestTracing.spec.ts (1)

30-37: Test coverage looks good!
Your test for the requestContext middleware properly verifies that nextFunction is called once. This is a straightforward yet critical test to ensure middleware functionality.

src/libraries/requestTracing.ts (2)

33-36: Asynchronous import approach is valid.
Using import("nanoid") on-demand is a good optimization for only loading this dependency when necessary.


92-92: Ensure upstream error handling for getNanoid
If getNanoid fails here, it will throw asynchronously. Consider wrapping trace in a try/catch or letting it propagate to a higher-level error handler to avoid unhandled exceptions.

src/libraries/requestTracing.ts Outdated Show resolved Hide resolved
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

🔭 Outside diff range comments (1)
src/libraries/requestTracing.ts (1)

Line range hint 92-96: Fix return type and add error handling.

The trace function has two issues:

  1. The return type is Promise<void> but the function actually returns Promise<T>.
  2. Missing error handling for potential failures in getNanoid() or method().
-export const trace = async <T>(
+export const trace = async <T = void>(
   tracingId: string,
   method: () => T,
-): Promise<void> => {
+): Promise<T> => {
   const nanoid = await getNanoid();
-  await requestTracingNamespace.runAndReturn<T>(() => {
+  return requestTracingNamespace.runAndReturn<T>(() => {
     setTracingId(tracingId || nanoid());
     return method();
   });
 };

Also consider adding error handling:

export const trace = async <T = void>(
  tracingId: string,
  method: () => T,
): Promise<T> => {
  try {
    const nanoid = await getNanoid();
    return requestTracingNamespace.runAndReturn<T>(() => {
      setTracingId(tracingId || nanoid());
      return method();
    });
  } catch (error) {
    throw new Error(`Tracing failed: ${error.message}`);
  }
};
♻️ Duplicate comments (1)
src/libraries/requestTracing.ts (1)

63-77: ⚠️ Potential issue

Remove the duplicate next() call to prevent "Headers already sent" errors.

The middleware has a critical issue where next() is called twice:

  1. Inside the promise chain (line 71)
  2. After the promise chain (line 77)

This will cause "Cannot set headers after they are sent to the client" errors in Express.

     getNanoid()
       .then((nanoid) => {
         const tracingId = req.header(tracingIdHeaderName) || nanoid();
         req.headers[tracingIdHeaderName] = tracingId;
         res.header(tracingIdHeaderName, tracingId);

         requestTracingNamespace.run(() => {
           setTracingId(tracingId);
           next();
         });
       })
       .catch((error) => {
         next(error);
       });
-    next();
🧹 Nitpick comments (1)
src/libraries/requestTracing.ts (1)

33-36: LGTM! Consider adding error handling.

The dynamic import implementation is clean and follows best practices. However, consider adding explicit error handling for import failures.

 const getNanoid: () => Promise<() => string> = async () => {
-  const { customAlphabet } = await import("nanoid");
-  return customAlphabet(alphabets, 10);
+  try {
+    const { customAlphabet } = await import("nanoid");
+    return customAlphabet(alphabets, 10);
+  } catch (error) {
+    throw new Error(`Failed to load nanoid: ${error.message}`);
+  }
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2e7ad84 and 455e826.

📒 Files selected for processing (2)
  • src/libraries/requestTracing.ts (3 hunks)
  • tests/libraries/requestTracing.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/libraries/requestTracing.spec.ts

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 (1)
src/libraries/requestTracing.ts (1)

Line range hint 91-95: Add error handling for dynamic import.

While the async/await usage is correct, the function should handle potential failures in the dynamic import.

Consider adding try/catch:

 export const trace = async <T>(
   tracingId: string,
   method: () => T,
 ): Promise<void> => {
-  const nanoid = await getNanoid();
-  await requestTracingNamespace.runAndReturn<T>(() => {
-    setTracingId(tracingId || nanoid());
-    return method();
-  });
+  try {
+    const nanoid = await getNanoid();
+    await requestTracingNamespace.runAndReturn<T>(() => {
+      setTracingId(tracingId || nanoid());
+      return method();
+    });
+  } catch (error) {
+    // Log the error or handle it appropriately
+    throw new Error(`Failed to execute traced method: ${error.message}`);
+  }
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 455e826 and 00a9878.

📒 Files selected for processing (1)
  • src/libraries/requestTracing.ts (3 hunks)
🔇 Additional comments (2)
src/libraries/requestTracing.ts (2)

33-36: LGTM! Clean implementation of dynamic import.

The implementation of getNanoid follows best practices for dynamic imports and is properly typed.


63-76: ⚠️ Potential issue

Fix critical async/await and context propagation issues.

There are two significant issues in the middleware implementation:

  1. The next() call on line 76 executes immediately after starting the promise chain, not waiting for the async work to complete. This breaks the middleware chain.

  2. The next() call should be inside the namespace context to ensure proper context propagation to subsequent middleware.

Apply this fix:

    getNanoid()
      .then((nanoid) => {
        const tracingId = req.header(tracingIdHeaderName) || nanoid();
        req.headers[tracingIdHeaderName] = tracingId;
        res.header(tracingIdHeaderName, tracingId);

        requestTracingNamespace.run(() => {
          setTracingId(tracingId);
+         next();
        });
-      })
+      },
       (error) => {
         next(error);
       });
-    next();

Alternatively, consider using async/await for better readability:

-  return (req: Request, res: Response, next: NextFunction): void => {
+  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
     requestTracingNamespace.bindEmitter(req);
     requestTracingNamespace.bindEmitter(res);
     
+    try {
+      const nanoid = await getNanoid();
+      const tracingId = req.header(tracingIdHeaderName) || nanoid();
+      req.headers[tracingIdHeaderName] = tracingId;
+      res.header(tracingIdHeaderName, tracingId);
+
+      requestTracingNamespace.run(() => {
+        setTracingId(tracingId);
+        next();
+      });
+    } catch (error) {
+      next(error);
+    }
-    getNanoid()
-      .then((nanoid) => {
-        const tracingId = req.header(tracingIdHeaderName) || nanoid();
-        req.headers[tracingIdHeaderName] = tracingId;
-        res.header(tracingIdHeaderName, tracingId);
-
-        requestTracingNamespace.run(() => {
-          setTracingId(tracingId);
-        });
-      })
-      .catch((error) => {
-        next(error);
-      });
-    next();
   };

Likely invalid or redundant comment.

@Cioppolo14
Copy link
Contributor

@Ramneet04 Please fix the first comment so the PR can automatically close. Please fix the failed tests.

Copy link

This pull request did not get any activity in the past 10 days and will be closed in 180 days if no update occurs. Please verify it has no conflicts with the develop branch and rebase if needed. Mention it now if you need help or give permission to other people to finish your work.

@github-actions github-actions bot added the no-pr-activity No pull request activity label Jan 12, 2025
@palisadoes
Copy link
Contributor

Closing. Inactivity

@palisadoes palisadoes closed this Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-pr-activity No pull request activity
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants