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: Add codeOwner to logging context #17172

Merged
merged 4 commits into from
Dec 10, 2024
Merged

feat: Add codeOwner to logging context #17172

merged 4 commits into from
Dec 10, 2024

Conversation

eirikurn
Copy link
Member

@eirikurn eirikurn commented Dec 8, 2024

What

Add codeOwner to our logs.

Why

See #17092

Adding the codeOwner to tracing tags didn't work as expected. It only adds it to the current span. Not nested spans, logs or metrics. We'll make do with having it on one span, but this PR adds codeOwner to our logs.

Summary by CodeRabbit

  • New Features

    • Introduced a new method for setting code ownership with enhanced logging capabilities.
    • Updated logging context to include CODE_OWNER from the environment variable.
  • Bug Fixes

    • Improved tests to ensure correct logging behavior when CODE_OWNER is set or overridden.
  • Tests

    • Expanded test cases for logging context and code ownership functionality, including new assertions for the updated method.
    • Renamed existing tests for clarity and accuracy.

@eirikurn eirikurn requested review from a team as code owners December 8, 2024 10:34
Copy link
Contributor

coderabbitai bot commented Dec 8, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

error Received malformed response from registry for "typescript". The registry may be down.

Walkthrough

The changes in this pull request involve significant modifications to the code ownership functionality within the logging context. The setCodeOwner function has been renamed to withCodeOwner, which now accepts a callback and additional arguments, enhancing its utility in managing logging context. The test suite has been updated to reflect these changes, ensuring that logging behavior is correctly verified under various conditions. Additionally, the logging context has been adjusted to incorporate the CODE_OWNER environment variable, improving the overall logging output.

Changes

File Path Change Summary
libs/infra-tracing/src/lib/code-owner.ts Renamed setCodeOwner to withCodeOwner, updated method signature to include a callback and args.
libs/infra-tracing/src/lib/code-owner.spec.ts Updated tests to reflect the new withCodeOwner function, added tests for callback execution and logging behavior.
libs/logging/src/lib/context.ts Added defaultCodeOwner variable to include CODE_OWNER in logging context if available.
libs/logging/src/lib/context.spec.ts Added tests for logging context behavior with CODE_OWNER, updated existing tests for clarity.
libs/nest/core/src/lib/code-owner/code-owner.interceptor.ts Updated import from setCodeOwner to withCodeOwner, modified intercept method to use the new function.
libs/nest/core/src/lib/code-owner/code-owner.interceptor.spec.ts Updated tests to use withCodeOwner, added tests for handler execution with the new function.

Possibly related PRs

  • feat(endorsement-system): Improved error logs #16835: This PR is unrelated as it focuses on error handling and logging improvements in a different service, with no direct connection to the changes made in the code-owner functionality or the withCodeOwner function.

Suggested reviewers

  • kksteini

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. (Experiment)
  • @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

codecov bot commented Dec 8, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 35.73%. Comparing base (fcadfe5) to head (68b8a71).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #17172   +/-   ##
=======================================
  Coverage   35.73%   35.73%           
=======================================
  Files        6928     6928           
  Lines      147824   147828    +4     
  Branches    42129    42130    +1     
=======================================
+ Hits        52818    52826    +8     
+ Misses      95006    95002    -4     
Flag Coverage Δ
air-discount-scheme-backend 48.16% <25.00%> (-0.06%) ⬇️
air-discount-scheme-web 0.00% <ø> (ø)
api 3.33% <ø> (ø)
api-catalogue-services 75.81% <0.00%> (-0.76%) ⬇️
api-domains-air-discount-scheme 37.87% <0.00%> (-0.06%) ⬇️
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.41% <0.00%> (-0.02%) ⬇️
api-domains-criminal-record 47.88% <0.00%> (-0.11%) ⬇️
api-domains-driving-license 44.80% <0.00%> (-0.04%) ⬇️
api-domains-education 31.18% <0.00%> (-0.05%) ⬇️
api-domains-health-insurance 35.28% <0.00%> (-0.08%) ⬇️
api-domains-mortgage-certificate 35.14% <0.00%> (-0.05%) ⬇️
api-domains-payment-schedule 42.01% <0.00%> (-0.07%) ⬇️
application-api-files 61.70% <0.00%> (-0.17%) ⬇️
application-core 76.01% <ø> (ø)
application-system-api 38.74% <25.00%> (-0.02%) ⬇️
application-template-api-modules 27.80% <0.00%> (+0.01%) ⬆️
application-templates-accident-notification 28.93% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 25.78% <ø> (ø)
application-templates-driving-license 18.12% <ø> (ø)
application-templates-estate 13.79% <ø> (ø)
application-templates-example-payment 24.71% <ø> (ø)
application-templates-financial-aid 14.42% <ø> (ø)
application-templates-general-petition 23.13% <ø> (ø)
application-templates-inheritance-report 6.54% <ø> (ø)
application-templates-marriage-conditions 15.11% <ø> (ø)
application-templates-mortgage-certificate 43.56% <ø> (ø)
application-templates-parental-leave 29.95% <ø> (ø)
application-types 6.57% <ø> (ø)
application-ui-components 1.24% <ø> (ø)
application-ui-shell 22.43% <ø> (ø)
auth-admin-web 2.43% <ø> (ø)
auth-nest-tools 31.52% <0.00%> (-0.24%) ⬇️
auth-react 24.50% <ø> (ø)
clients-charge-fjs-v2 28.35% <ø> (ø)
clients-driving-license 40.76% <0.00%> (-0.09%) ⬇️
clients-driving-license-book 43.81% <0.00%> (-0.07%) ⬇️
clients-financial-statements-inao 49.56% <0.00%> (-0.11%) ⬇️
clients-license-client 1.26% <ø> (ø)
clients-middlewares 73.13% <0.00%> (-0.51%) ⬇️
clients-regulations 42.83% <0.00%> (-0.10%) ⬇️
clients-rsk-company-registry 31.04% <0.00%> (-0.10%) ⬇️
clients-rsk-personal-tax-return 38.32% <0.00%> (-0.71%) ⬇️
clients-smartsolutions 12.77% <ø> (ø)
clients-syslumenn 49.39% <0.00%> (-0.07%) ⬇️
clients-zendesk 50.35% <0.00%> (-0.36%) ⬇️
cms 0.40% <ø> (ø)
cms-translations 38.74% <0.00%> (-0.02%) ⬇️
content-search-toolkit 8.20% <ø> (ø)
contentful-apps 4.72% <ø> (ø)
dokobit-signing 62.01% <0.00%> (-0.43%) ⬇️
email-service 60.00% <0.00%> (-0.36%) ⬇️
file-storage 45.75% <0.00%> (-0.28%) ⬇️
financial-aid-backend 51.39% <0.00%> (-0.05%) ⬇️
icelandic-names-registry-backend 54.33% <25.00%> (-0.17%) ⬇️
infra-nest-server 48.06% <25.00%> (-0.24%) ⬇️
infra-tracing 69.63% <62.50%> (-0.96%) ⬇️
judicial-system-api 19.97% <ø> (ø)
judicial-system-audit-trail 68.86% <ø> (ø)
judicial-system-backend 55.74% <0.00%> (-0.01%) ⬇️
judicial-system-message 66.29% <0.00%> (-0.38%) ⬇️
judicial-system-message-handler 47.97% <0.00%> (-0.25%) ⬇️
judicial-system-web 27.89% <ø> (ø)
license-api 42.83% <30.00%> (-0.18%) ⬇️
localization 10.15% <ø> (ø)
logging 58.02% <100.00%> (+1.61%) ⬆️
message-queue 67.76% <0.00%> (-0.49%) ⬇️
nest-audit 65.78% <0.00%> (-1.06%) ⬇️
nest-aws 51.93% <0.00%> (-0.88%) ⬇️
nest-config 76.32% <0.00%> (-0.65%) ⬇️
nest-core 53.16% <100.00%> (ø)
nest-feature-flags 50.94% <0.00%> (-0.20%) ⬇️
nest-problem 45.64% <25.00%> (-0.18%) ⬇️
nest-sequelize 94.44% <ø> (ø)
nest-swagger 51.13% <0.00%> (-0.51%) ⬇️
nova-sms 61.33% <0.00%> (-0.45%) ⬇️
portals-admin-regulations-admin 1.80% <ø> (ø)
portals-core 19.76% <ø> (ø)
services-auth-admin-api 52.55% <25.00%> (-0.02%) ⬇️
services-auth-delegation-api 58.44% <25.00%> (-0.03%) ⬇️
services-auth-ids-api 52.52% <25.00%> (-0.01%) ⬇️
services-auth-public-api 49.39% <25.00%> (-0.01%) ⬇️
services-sessions 65.33% <25.00%> (-0.12%) ⬇️
services-university-gateway 49.49% <25.00%> (-0.03%) ⬇️
services-user-notification 46.55% <30.00%> (-0.02%) ⬇️
services-user-profile 56.97% <30.00%> (-0.06%) ⬇️
shared-components 30.08% <ø> (ø)
shared-form-fields 33.88% <ø> (ø)
skilavottord-ws 24.31% <0.00%> (-0.05%) ⬇️
web 2.43% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
libs/infra-tracing/src/lib/code-owner.ts 100.00% <100.00%> (ø)
libs/logging/src/lib/context.ts 100.00% <100.00%> (ø)
.../core/src/lib/code-owner/code-owner.interceptor.ts 100.00% <100.00%> (ø)

... and 2 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update fcadfe5...68b8a71. Read the comment docs.

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

🧹 Outside diff range and nitpick comments (4)
libs/infra-tracing/src/lib/code-owner.ts (1)

6-10: Update function documentation to reflect new behavior

The function documentation may be outdated after refactoring setCodeOwner to withCodeOwner, which now accepts a callback and arguments. Please update the doc comment to accurately describe the new behavior of wrapping a callback to set the code owner for the current dd-trace span and all nested log entries during the execution of the callback.

libs/logging/src/lib/context.spec.ts (3)

15-33: Consider using a constant for the team name

The test is well-structured with clear AAA pattern. Consider extracting 'default-team' to a constant to improve maintainability and reusability across tests.

+const DEFAULT_TEAM = 'default-team' as const;
 it('should add default CODE_OWNER when environment variable is set', () => {
   // Arrange
-  process.env.CODE_OWNER = 'default-team'
+  process.env.CODE_OWNER = DEFAULT_TEAM

35-57: Consider adding runtime validation for CodeOwners type

While the TypeScript type assertion is good, consider adding runtime validation to ensure 'context-team' is a valid CodeOwner value.

+  const isValidCodeOwner = (value: string): value is CodeOwners => {
+    return Object.values(CodeOwners).includes(value as CodeOwners);
+  };
+
   it('should override default CODE_OWNER with context codeOwner', () => {
     // Arrange
     process.env.CODE_OWNER = 'default-team'
     const formatter = includeContextFormatter()
     const logInfo = {
       level: 'info',
       message: 'Test message',
     }
-    const context = { codeOwner: 'context-team' as CodeOwners }
+    const contextTeam = 'context-team';
+    if (!isValidCodeOwner(contextTeam)) {
+      throw new Error(`Invalid code owner: ${contextTeam}`);
+    }
+    const context = { codeOwner: contextTeam }

Line range hint 83-122: Consider extracting common test data setup

The tests share common setup code for logInfo and formatter. Consider using beforeEach to reduce duplication and improve maintainability.

 describe('Winston context', () => {
   const originalEnv = process.env
+  let formatter: ReturnType<typeof includeContextFormatter>;
+  let baseLogInfo: { level: string; message: string };
 
   beforeEach(() => {
     process.env = { ...originalEnv }
+    formatter = includeContextFormatter()
+    baseLogInfo = {
+      level: 'info',
+      message: 'Test message',
+    }
   })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1a6abd6 and 1a1a40a.

📒 Files selected for processing (5)
  • libs/infra-tracing/src/lib/code-owner.spec.ts (2 hunks)
  • libs/infra-tracing/src/lib/code-owner.ts (2 hunks)
  • libs/logging/src/lib/context.spec.ts (5 hunks)
  • libs/logging/src/lib/context.ts (1 hunks)
  • libs/nest/core/src/lib/code-owner/code-owner.interceptor.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
libs/logging/src/lib/context.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/core/src/lib/code-owner/code-owner.interceptor.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/logging/src/lib/context.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/infra-tracing/src/lib/code-owner.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/infra-tracing/src/lib/code-owner.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (5)
libs/nest/core/src/lib/code-owner/code-owner.interceptor.ts (1)

23-23: LGTM

Wrapping next.handle() with withCodeOwner correctly applies the code owner context to the request handling pipeline.

libs/logging/src/lib/context.ts (1)

22-27: LGTM

The code appropriately incorporates the CODE_OWNER environment variable into the logging context, ensuring that the default codeOwner is included in log entries when not specified elsewhere.

libs/infra-tracing/src/lib/code-owner.spec.ts (1)

Line range hint 1-79: LGTM

The updated tests correctly verify the new behavior of withCodeOwner, ensuring that the code owner is set on the active span and that the callback function is executed with the correct arguments. The tests also handle cases where no active span exists, confirming that the logging warning is triggered appropriately.

libs/logging/src/lib/context.spec.ts (2)

Line range hint 1-14: LGTM! Well-structured test setup

The environment setup follows testing best practices with proper environment variable management and TypeScript usage.


Line range hint 1-122: Excellent compliance with coding guidelines

The implementation effectively uses TypeScript and creates reusable test patterns, fully adhering to the coding guidelines for libs/**/* files.

libs/infra-tracing/src/lib/code-owner.ts Outdated Show resolved Hide resolved
@datadog-island-is
Copy link

datadog-island-is bot commented Dec 8, 2024

Datadog Report

All test runs 0283c97 🔗

90 Total Test Services: 0 Failed, 82 Passed
🔻 Test Sessions change in coverage: 36 decreased, 1 increased (+1.67%), 163 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
air-discount-scheme-backend 0 0 0 63 0 30.11s N/A Link
air-discount-scheme-web 0 0 0 2 0 7.17s N/A Link
api 0 0 0 4 0 2.33s N/A Link
api-catalogue-services 0 0 0 23 0 9.01s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 15.69s N/A Link
api-domains-assets 0 0 0 3 0 9.49s N/A Link
api-domains-auth-admin 0 0 0 18 0 10.19s N/A Link
api-domains-communications 0 0 0 5 0 29s 1 decreased (-0.02%) Link
api-domains-criminal-record 0 0 0 5 0 8.63s N/A Link
api-domains-driving-license 0 0 0 23 0 27.15s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (36)

This report shows up to 5 code coverage decreases.

  • nest-audit - jest 66.46% (-1.24%) - Details
  • infra-tracing - jest 74.15% (-1.13%) - Details
  • nest-aws - jest 52.22% (-1.02%) - Details
  • clients-rsk-personal-tax-return - jest 42.36% (-0.9%) - Details
  • nest-config - jest 77.77% (-0.73%) - Details

coderabbitai[bot]
coderabbitai bot previously requested changes Dec 8, 2024
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: 1

🧹 Outside diff range and nitpick comments (3)
libs/infra-tracing/src/lib/code-owner.ts (1)

6-10: Consider enhancing TypeScript documentation

While the current documentation explains the functionality well, consider adding TypeScript-specific documentation for better IDE support:

 /**
  * Sets a code owner for the current dd-trace span and all nested log entries.
  *
  * The assumption here is that each trace / request has only one "dynamic"
  * code owner. This way we skip cluttering the trace with extra spans.
+ * @param codeOwner - The code owner to set for the current context
+ * @param callback - The function to execute within the code owner context
+ * @param args - Arguments to pass to the callback function
+ * @returns The result of the callback function
  */
libs/nest/core/src/lib/code-owner/code-owner.interceptor.spec.ts (2)

11-13: Consider adding types to mock implementation

The mock implementation could benefit from explicit typing for better type safety during tests.

 jest.mock('@island.is/infra-tracing', () => ({
-  withCodeOwner: jest.fn((codeOwner, callback) => callback()),
+  withCodeOwner: jest.fn(<R, TArgs extends unknown[]>(
+    codeOwner: CodeOwners,
+    callback: (...args: TArgs) => R,
+    ...args: TArgs
+  ) => callback(...args)),
 }))

Line range hint 78-92: Consider enhancing multiple requests test

While the test effectively verifies the number of calls, consider adding verification for the order of calls to ensure consistent behavior.

   // Verify that withCodeOwner was called exactly twice (for the two 'with-owner' requests)
   expect(withCodeOwner).toHaveBeenCalledTimes(2)
-  expect(withCodeOwner).toHaveBeenCalledWith(
-    CodeOwners.Core,
-    expect.any(Function),
-  )
+  expect(withCodeOwner.mock.calls).toEqual([
+    [CodeOwners.Core, expect.any(Function)],
+    [CodeOwners.Core, expect.any(Function)],
+  ])
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1a1a40a and 07fbcb9.

📒 Files selected for processing (2)
  • libs/infra-tracing/src/lib/code-owner.ts (2 hunks)
  • libs/nest/core/src/lib/code-owner/code-owner.interceptor.spec.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/infra-tracing/src/lib/code-owner.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/nest/core/src/lib/code-owner/code-owner.interceptor.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (3)
libs/infra-tracing/src/lib/code-owner.ts (2)

1-1: LGTM: Import changes align with PR objective

The addition of withLoggingContext import is appropriate for integrating code ownership with logging context.


Line range hint 11-27: Implementation looks solid, verify error handling

The implementation effectively combines tracing and logging context while maintaining type safety. The generic type parameters allow for flexible reuse across different contexts.

Let's verify the error handling by checking for similar patterns in the codebase:

✅ Verification successful

Error handling implementation is consistent and robust

The error handling in withCodeOwner follows established patterns across the codebase:

  • Proper logging of missing spans with stack traces
  • Consistent use of logger.warn for non-critical issues
  • Graceful fallback to logging context when tracing is unavailable
  • Stack trace inclusion for better debugging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar error handling patterns with dd-trace
rg -A 2 "scope\(\)\.active\(\)" | grep -B 2 "warn"

# Check for other uses of withLoggingContext to ensure consistent pattern
ast-grep --pattern 'withLoggingContext({ $$$}, $_, $$$)'

Length of output: 215


Script:

#!/bin/bash
# Let's check for similar error handling patterns with tracer.scope()
rg -A 5 "tracer\.scope\(\)" 

# Let's also check for similar stack trace logging patterns
rg -A 3 "new Error\(\)\.stack"

# And check the logger usage pattern
rg "logger\.warn\(" -A 2

Length of output: 66188

libs/nest/core/src/lib/code-owner/code-owner.interceptor.spec.ts (1)

53-76: LGTM: Test cases provide good coverage

The test cases effectively verify both the presence and absence of the CodeOwner decorator, with clear assertions and proper function call verification.

Copy link
Member

@svanaeinars svanaeinars left a comment

Choose a reason for hiding this comment

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

LGTM

@eirikurn eirikurn added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Dec 9, 2024
@eirikurn
Copy link
Member Author

@coderabbitai resolve

@eirikurn eirikurn dismissed coderabbitai[bot]’s stale review December 10, 2024 10:00

not relevant anymore

@eirikurn eirikurn removed the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Dec 10, 2024
@eirikurn eirikurn added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Dec 10, 2024
Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

✅ Actions performed

Comments resolved and changes approved.

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

🧹 Outside diff range and nitpick comments (2)
libs/infra-tracing/src/lib/code-owner.ts (1)

6-10: Enhance function documentation with callback parameter details

The documentation should include information about the callback parameter and its return value handling.

Add these details to the documentation:

 /**
  * Sets a code owner for the current dd-trace span and all nested log entries.
  *
  * The assumption here is that each trace / request has only one "dynamic"
  * code owner. This way we skip cluttering the trace with extra spans.
+ *
+ * @param codeOwner - The code owner to be set
+ * @param callback - The function to be executed within the code owner context
+ * @param args - Arguments to be passed to the callback function
+ * @returns The result of the callback function execution
  */
libs/infra-tracing/src/lib/code-owner.spec.ts (1)

70-81: Consider adding test cases for different return types

While the current test verifies basic return value handling, consider adding test cases for:

  • Primitive return types (number, string, boolean)
  • Promise return values
  • null/undefined handling
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 07fbcb9 and 68b8a71.

📒 Files selected for processing (2)
  • libs/infra-tracing/src/lib/code-owner.spec.ts (2 hunks)
  • libs/infra-tracing/src/lib/code-owner.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/infra-tracing/src/lib/code-owner.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/infra-tracing/src/lib/code-owner.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (5)
libs/infra-tracing/src/lib/code-owner.ts (2)

11-15: LGTM! Well-typed function signature

The generic type parameters and callback function type definitions are well structured, providing both type safety and flexibility.


16-25: LGTM! Robust implementation with proper error handling

The implementation correctly:

  • Handles both active and inactive span scenarios
  • Suppresses warnings in development environment
  • Integrates with logging context while maintaining the code owner information
libs/infra-tracing/src/lib/code-owner.spec.ts (3)

Line range hint 1-24: LGTM! Comprehensive test setup with proper mocking

The test setup is well-structured with:

  • Proper mocking of all dependencies
  • Clear beforeEach setup
  • Appropriate mock implementation for withLoggingContext

27-43: LGTM! Thorough test coverage for the happy path

The test case properly verifies:

  • Code owner tag setting on active span
  • Logging context integration
  • Callback execution with correct arguments

46-68: LGTM! Good error path coverage

The test case thoroughly verifies the behavior when no active span exists:

  • Warning message is logged
  • Callback still executes correctly
  • Logging context is maintained

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

🧹 Outside diff range and nitpick comments (1)
libs/infra-tracing/src/lib/code-owner.ts (1)

6-15: Enhance function documentation with parameter descriptions

While the general description is good, consider adding parameter descriptions to document the generic types and callback functionality.

 /**
  * Sets a code owner for the current dd-trace span and all nested log entries.
  *
  * The assumption here is that each trace / request has only one "dynamic"
  * code owner. This way we skip cluttering the trace with extra spans.
+ *
+ * @param codeOwner - The code owner to be set for the current context
+ * @param callback - The function to be executed within the code owner context
+ * @param args - Arguments to be passed to the callback function
+ * @returns The result of the callback execution
  */
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 07fbcb9 and 68b8a71.

📒 Files selected for processing (2)
  • libs/infra-tracing/src/lib/code-owner.spec.ts (2 hunks)
  • libs/infra-tracing/src/lib/code-owner.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/infra-tracing/src/lib/code-owner.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/infra-tracing/src/lib/code-owner.spec.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (5)
libs/infra-tracing/src/lib/code-owner.ts (2)

1-1: LGTM: Import statement is correctly updated

The addition of withLoggingContext import aligns with the new functionality requirements.


16-25: LGTM: Implementation follows best practices

The implementation correctly handles:

  • Span tagging with error handling
  • Development environment awareness
  • Context propagation through withLoggingContext

Let's verify the usage of this function across the codebase:

✅ Verification successful

Implementation verified: Code owner tracing is properly integrated

The verification confirms:

  • withCodeOwner is correctly used in the NestJS interceptor and test files
  • No legacy setCodeOwner function calls remain in the codebase
  • The span tag codeOwner is exclusively set in this implementation
  • Context propagation through withLoggingContext is properly integrated
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining uses of the old setCodeOwner function
rg "setCodeOwner\(" --type ts

# Search for current usage patterns of withCodeOwner
rg "withCodeOwner\(" -A 2 --type ts

Length of output: 995


Script:

#!/bin/bash
# Check if there are any other functions in the codebase that set code owner tags
ast-grep --pattern 'span.setTag("codeOwner", $_)'

# Check the implementation of withLoggingContext to verify context propagation
ast-grep --pattern 'function withLoggingContext($_) { $$$ }'

# Check for any other span tag setters related to code owners
rg 'span.*setTag.*codeOwner' --type ts

Length of output: 236

libs/infra-tracing/src/lib/code-owner.spec.ts (3)

Line range hint 1-24: LGTM: Test setup is comprehensive

The test setup properly mocks all dependencies and includes the new withLoggingContext functionality.


27-43: LGTM: Test case thoroughly verifies the happy path

The test case follows AAA pattern and includes comprehensive assertions for:

  • Span tag setting
  • Logging context setup
  • Callback execution with correct arguments

46-81: LGTM: Edge cases and return values are well tested

The test suite properly covers:

  • Behavior when no active span exists
  • Warning message generation
  • Return value propagation

@kodiakhq kodiakhq bot merged commit 1ebd671 into main Dec 10, 2024
250 of 259 checks passed
@kodiakhq kodiakhq bot deleted the tweak-codeowner branch December 10, 2024 11:27
thorhildurt pushed a commit that referenced this pull request Dec 11, 2024
* feat: Add codeOwner to logging context

* Fix tests

* fix: Silence warning in development
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants