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

WIP: Using new log component with Telemere #364

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open

Conversation

J0sueTM
Copy link
Member

@J0sueTM J0sueTM commented Oct 24, 2024

closes #361

Summary by CodeRabbit

  • New Features

    • Added OpenSearch configuration settings, including username, password, host, port, and index.
    • Enhanced logging functionality across various components for better traceability of operations.
    • Introduced a new test namespace for validating function tracing.
  • Bug Fixes

    • Updated dependency version for com.moclojer/components from 0.1.0 to 0.1.4.
  • Chores

    • Improved formatting and consistency of dependency declarations in the configuration files.
    • Refactored logging mechanisms to use trace logging for improved observability.
    • Enhanced system map configuration to integrate logging capabilities.
    • Removed unnecessary logging setup from certain components.

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

The pull request includes modifications to several files, primarily focusing on enhancing logging functionality and updating dependency versions. The deps.edn file has been reformatted for consistency, with a version update for com.moclojer/components. New OpenSearch settings have been added to the configuration file. Various controller files have been updated to replace standard logging with trace logging, improving the granularity of logged information. Additionally, changes have been made to integrate a new logger component into the system, enhancing overall logging capabilities.

Changes

File Path Change Summary
deps.edn Reformatted dependency declarations; updated com.moclojer/components version from 0.1.0 to 0.1.4.
resources/back/config.edn Added new :opensearch section with keys for username, password, host, port, and index using environment variable defaults.
src/back/api/controllers/mocks.clj Enhanced logging by replacing logs/log with logs/trace in multiple functions, adding contextual information.
src/back/api/controllers/orgs.clj Enhanced logging by replacing logs/log with logs/trace in multiple functions, including relevant context.
src/back/api/controllers/user.clj Enhanced logging by adding trace logs in various user-related functions, capturing relevant parameters.
src/back/api/db/mocks.clj Added logging functionality to database operations; included com.moclojer.components.logs namespace.
src/back/api/db/orgs.clj Added logging functionality to database operations; included com.moclojer.components.logs namespace.
src/back/api/ports/workers.clj Updated logging from logs/log to logs/trace, modified argument destructuring for consistency.
src/back/api/server.clj Added a logger component to the system map and removed the previous logger setup call.
src/dev/api/dev.clj Added a :logger entry in the system map; made formatting adjustments for readability.
src/dev/utils.clj Removed a dependency from :require and commented out a previous logger setup call in start-system-dev!.
test/back/back/integration/api/wrap_traces_test.clj Introduced a new test namespace for validating the wrapping of functions in namespaces with a trace container.

Assessment against linked issues

Objective Addressed Explanation
Update logging usages to use new version with telemere (#361)

Possibly related PRs

Poem

🐇 In the code where rabbits hop,
Logs now trace, they never stop.
Dependencies updated with care,
OpenSearch settings, a breath of fresh air!
With every function, a story to tell,
In the land of code, all is well! 🌟


🪧 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: 20

🧹 Outside diff range comments (3)
src/back/api/server.clj (2)

Line range hint 15-22: Consider adding logger dependency to other components.

Components like :http, :router, :database, and :mq might benefit from having access to the logger component for consistent logging across the system.

Consider updating the component dependencies like this:

   :logger (component/using (components/new-logger) [:config])
-  :http (components/new-http)
+  :http (component/using (components/new-http) [:logger])
   :sentry (component/using (components/new-sentry) [:config])
-  :router (components/new-router routes/routes)
+  :router (component/using (components/new-router routes/routes) [:logger])
-  :database (component/using (components/new-database) [:config])
+  :database (component/using (components/new-database) [:config :logger])
   :mq (component/using (components/new-mq
                         p.workers/workers
                         [{:channel "domains.verification.fired"
                           :event {}
                           ;; every 2 minutes
                           :sleep 120000}
                          {:channel "yml.unified.verification.fired"
                           :event {}
                           ;; every 5 minutes
                           :sleep 300000}]
                         false)
-                       [:config :database :sentry])
+                       [:config :database :sentry :logger])

Line range hint 44-45: Verify logging during system shutdown.

The stop-system! function still uses the old logging approach with logs/log. This should be updated to use the new logger component from the system map.

Consider updating the shutdown logging:

 (defn stop-system! []
-  (logs/log :info "stopping system")
+  (when-let [logger (:logger @system-atom)]
+    ((:log logger) :info "stopping system"))
   (swap!
    system-atom
    (fn [s] (when s (component/stop s)))))
src/back/api/db/mocks.clj (1)

Line range hint 40-136: Consider introducing a logging helper to reduce duplication.

The logging implementation is consistent across all operations, which is good. However, the repeated pattern could be simplified using a helper function.

Consider creating a helper function to standardize the logging pattern:

(defn- with-db-trace [op-name ctx f]
  (logs/trace op-name ctx
    (let [result (f)]
      (logs/trace (keyword (str (name op-name) "-result"))
                 (assoc ctx :success (some? result)))
      result)))

;; Example usage in get-mock-by-id:
(defn get-mock-by-id [id db ctx]
  (with-db-trace ::get-mock-by-id
                 {:mock-id id}
                 #(-> (sql.helpers/select :*)
                     (sql.helpers/from :mock)
                     (sql.helpers/where [:= :id id])
                     sql/format
                     ((db.utils/build-execute-with-ctx db ctx))
                     first)))

This would:

  1. Reduce code duplication
  2. Ensure consistent logging across operations
  3. Add result logging automatically
  4. Make it easier to modify logging behavior in one place
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between f6463cf and 5a7a935.

📒 Files selected for processing (11)
  • deps.edn (1 hunks)
  • resources/back/config.edn (1 hunks)
  • src/back/api/controllers/mocks.clj (1 hunks)
  • src/back/api/controllers/orgs.clj (1 hunks)
  • src/back/api/controllers/user.clj (1 hunks)
  • src/back/api/db/mocks.clj (3 hunks)
  • src/back/api/db/orgs.clj (1 hunks)
  • src/back/api/ports/workers.clj (1 hunks)
  • src/back/api/server.clj (1 hunks)
  • src/dev/api/dev.clj (4 hunks)
  • src/dev/utils.clj (1 hunks)
🔇 Additional comments (30)
src/dev/utils.clj (3)

2-6: LGTM! Good improvement in import specificity.

Using the specific com.moclojer.components.logs namespace instead of the generic core namespace improves code clarity and follows better dependency management practices.


Line range hint 18-26: Consider enhancing shutdown logging details.

While the basic logging is in place, consider adding more detailed logging about the components being stopped. This would help with debugging and monitoring system shutdown.

 (defn stop-system-dev!
   ([sys-atom]
    (stop-system-dev! sys-atom true))
   ([sys-atom halt-pg?]
-   (logs/log :info "stopping system")
+   (logs/log :info "initiating system shutdown")
    (swap!
     sys-atom
-    (fn [s] (when s (component/stop s))))
+    (fn [s]
+      (when s
+        (logs/log :info "stopping system components")
+        (let [stopped (component/stop s)]
+          (logs/log :info "system components stopped successfully")
+          stopped))))
    (when halt-pg?
+     (logs/log :info "halting PostgreSQL")
      (pg-emb/halt-pg!))))

Additionally, let's verify if this logging implementation is compatible with Telemere:

#!/bin/bash
# Description: Check if the logging namespace supports Telemere integration
# Expected: Find evidence of Telemere integration in the logging component

# Look for Telemere-related code in the logging component
rg -A 5 "telemere" src/

Line range hint 8-16: Verify logger initialization in development environment.

Since the logger setup was removed from this function, we should verify that the logger is properly initialized through the new :logger component mentioned in the system map.

✅ Verification successful

Let me generate additional shell scripts to gather more information about the logger initialization.

The previous search revealed usage of com.moclojer.components.logs, so let's examine this namespace and related component initialization. Additionally, we'll look for any logger-related code in the codebase to understand how logging is handled in the development environment.


Based on the shell script results, I can now generate the final response as we have sufficient information about how logging is handled in the codebase.

Logger initialization is properly handled through the component system

The removal of setup-logger from start-system-dev! is correct as the logger initialization is now handled through the component system. Evidence:

  • In src/dev/api/dev.clj, there's a proper logger component initialization:
    :logger (component/using (components/new-logger) [:config])
  • The logger component is properly integrated into the component system with a dependency on the :config component
  • This approach is consistent across the codebase, as seen in src/back/api/server.clj which uses the same pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if logger initialization is handled by the new logger component
# Expected: Find logger component initialization in development-related files

# Look for logger component initialization
rg -l "(:logger|new-logger)" src/

Length of output: 902


Script:

#!/bin/bash
# Search for logger-related code and components
rg -A 5 "components.*log" src/

# Search for any logger initialization or configuration
rg -A 5 "logger|logging" src/

# Look for the specific component namespace
fd "components" src/ --exec cat {}

Length of output: 14282

src/back/api/ports/workers.clj (3)

17-19: LGTM! Consistent implementation across functions

The changes maintain consistency with the previous function, following the same pattern for logging and event context handling.


10-12: Verify trace level logging appropriateness

The change from info to trace level logging might affect operational visibility. Trace level is typically used for very detailed debugging and might be too verbose for production environments.

✅ Verification successful

Let me generate additional scripts to get more context about the logging configuration and usage patterns.

The previous results showed extensive use of trace logging across the codebase, but we need to understand the logging setup and configuration to make a proper assessment of whether the trace level is appropriate.


Based on the gathered information, I can now provide a final response as there's sufficient evidence about the logging patterns in the codebase.

Trace level logging is appropriate for this operation

The codebase shows a consistent pattern where:

  • Trace level is extensively used across controllers, DB operations, and worker components for detailed operation tracking
  • The application has proper logging configuration with ch.qos.logback/logback-classic
  • The default logging level is set to :info in the configuration ((components/setup-logger [["*" :info]])), which means trace logs can be enabled when needed without affecting normal production visibility
  • The change aligns with the codebase's logging strategy where trace is used for detailed operation tracking while info is reserved for significant state changes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check logging levels across the codebase
# Expected: Consistent use of trace level for similar operations

# Search for all logging calls to understand the logging strategy
rg "logs/(trace|debug|info|warn|error)" --type clojure

# Search for any logging configuration that might filter trace logs
rg -i "log.*level|level.*log" --type clojure

Length of output: 1931


Script:

#!/bin/bash
# Let's check for logging configuration files and imports
rg -l "logs|logging" --type clojure

# Look for any logging setup or configuration code
ast-grep --pattern '(ns $_ (:require [$$$ [logs :as logs] $$$]))'

# Check for any logging configuration in project configuration files
fd -e edn -e clj -e properties -x cat {} \; | rg -i "log"

Length of output: 10932


2-5: Verify Telemere integration with logging component

The addition of Telemere import aligns with the PR objectives. However, let's verify that the logging component is properly configured to use Telemere.

src/back/api/controllers/user.clj (1)

2-7: LGTM: Clean namespace organization

The namespace declaration is well-organized and properly includes the new logging component.

src/dev/api/dev.clj (3)

2-8: LGTM: Required imports added correctly

The new imports for components are properly organized and necessary for the logger integration.


55-57: LGTM: Improved comment readability

The added comment marker improves the visual separation of code sections.


18-18: LGTM: Logger component properly integrated

The logger component is correctly configured with its dependency on :config and follows the component system patterns.

✅ Verification successful

Let me gather more information about the logger component implementation to ensure it's consistently configured.


Let me check one more thing to verify the logger component's implementation and usage pattern.


Based on the gathered information, I can now provide the final response:

Logger component integration is correctly configured

The logger component is consistently configured across the codebase:

  • It's properly initialized with :config dependency in both development (src/dev/api/dev.clj) and production (src/back/api/server.clj) environments
  • The logger is widely and consistently used throughout the codebase via com.moclojer.components.logs namespace
  • All services (yaml-generator, job-ops, cloud-ops, back-api) follow the same pattern for logger integration
  • The component follows the standard component lifecycle pattern with proper dependency injection
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify logger component configuration across the codebase
# Description: Check if the logger component is consistently configured

# Check for logger component configuration patterns
rg -A 5 "new-logger|:logger" 

Length of output: 1207


Script:

#!/bin/bash
# Check the logger component implementation
ast-grep --pattern 'defrecord Logger [$$$] $$$'

# Check for logger component usage patterns
rg -B 2 -A 5 "require.*components|:require.*components"

Length of output: 10840


Script:

#!/bin/bash
# Check for logger component implementation and usage
rg -B 2 -A 5 "com\.moclojer\.components\.logs"

# Check the actual logger component source if available
fd -g "logs.clj" -x cat {}

Length of output: 11953

src/back/api/server.clj (2)

15-15: LGTM: Logger component integration looks correct.

The new logger component is properly integrated into the system map with the correct dependency on :config.


Line range hint 1-67: Verify error handling during system startup.

The system startup process should handle scenarios where the logger component fails to initialize.

Let's check if there are any error handling patterns in other components:

resources/back/config.edn (2)

28-32: Verify OpenSearch configuration integration with Telemere.

Since this PR is about integrating with Telemere for logging, please ensure that these OpenSearch settings align with Telemere's requirements and are properly utilized by the logging component.


28-29: ⚠️ Potential issue

Strengthen security by requiring production credentials.

The default username and password "foobar" could pose a security risk if accidentally used in production. Consider making these credentials mandatory in production environments.

Modify the configuration to enforce credentials in production:

-:opensearch {:username #or [#env OPENSEARCH_USERNAME "foobar"]
-             :password #or [#env OPENSEARCH_PASSWORD "foobar"]
+:opensearch {:username #profile {:dev #or [#env OPENSEARCH_USERNAME "foobar"]
+                                :prod #env OPENSEARCH_USERNAME}
+             :password #profile {:dev #or [#env OPENSEARCH_PASSWORD "foobar"]
+                                :prod #env OPENSEARCH_PASSWORD}

Let's verify if there are any hardcoded credentials in the codebase:

src/back/api/controllers/orgs.clj (3)

11-14: Well-structured logging implementation!

The logging changes follow a consistent pattern across all functions:

  1. Using namespace-qualified keywords for operation identification
  2. Including relevant context data in structured format
  3. Proper placement before the actual operation

This approach will significantly improve observability and debugging capabilities.

Also applies to: 18-21, 28-31, 35-38, 44-47, 53-55, 67-70, 78-81


1-84: Verify complete implementation of Telemere logging.

While the logging changes in this file look good, let's verify that all necessary components are in place for the Telemere integration:

  1. Proper configuration in the logging component
  2. Consistent usage across other controllers
#!/bin/bash
# Description: Verify complete Telemere implementation

# Test 1: Check if all controllers use the new logging pattern
echo "Checking controllers for consistent logging pattern:"
rg "logs/(trace|debug|info|warn|error)" --type clojure src/back/api/controllers/

# Test 2: Check logging component configuration
echo -e "\nChecking logging component configuration:"
fd -t f -e clj -e edn . | xargs rg -l "telemere"

2-7: Verify Telemere usage in the codebase.

While Telemere is imported, it doesn't appear to be directly used in this file. Let's verify if it's being used through the logging component.

✅ Verification successful

Let me gather more information about the logging component and Telemere usage to make a conclusive verification.


Based on the gathered information, I can now provide a conclusive response about the Telemere usage.

Telemere import is correctly used through the logging component

The verification shows that:

  1. All controller files consistently use logs/trace for logging
  2. Both orgs.clj and workers.clj import Telemere with the same alias t
  3. The logging pattern is uniform across the codebase, indicating a standardized approach

The import of taoensso.telemere is justified as it's part of the logging infrastructure update mentioned in the PR objectives. While Telemere isn't directly called with the t/ prefix, it's being used through the standardized logging component (logs/trace).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how Telemere is being used across the codebase

# Test 1: Check direct usage of Telemere
echo "Checking direct Telemere usage:"
rg "t/\w+" --type clojure

# Test 2: Check if Telemere is used in the logging component
echo -e "\nChecking Telemere usage in logging component:"
rg -l "taoensso.telemere" --type clojure

Length of output: 1536


Script:

#!/bin/bash
# Check the logging component implementation and Telemere integration
echo "Checking logging component implementation:"
rg -A 5 "taoensso.telemere" --type clojure

# Check if Telemere is used through the logging namespace
echo -e "\nChecking logs namespace usage:"
fd -t f logs.clj -x cat {}

# Check workers implementation since it also imports Telemere
echo -e "\nChecking workers implementation:"
cat src/back/api/ports/workers.clj

Length of output: 2069

src/back/api/db/orgs.clj (3)

1-7: LGTM! Namespace declaration and imports are well-organized.

The addition of the logging component import is properly placed and follows consistent aliasing conventions.


26-34: LGTM! Consistent logging implementation across all database operations.

The trace logging implementation follows a consistent pattern throughout all functions:

  1. Appropriate namespace-qualified keywords for operation identification
  2. Relevant context data including IDs
  3. Logging placed before the database operations

This consistency will make log analysis and debugging easier.

Also applies to: 40-48, 54-62, 68-77, 83-89, 95-104, 110-119


6-6: Verify Telemere integration in the logging component.

Since this PR aims to update logging to use Telemere, let's verify that com.moclojer.components.logs is properly integrated with Telemere.

src/back/api/db/mocks.clj (2)

1-7: LGTM: Namespace updated with new logging component.

The addition of the Telemere logging component import is consistent with the PR objectives.


Line range hint 1-136: Verify complete migration to new logging component.

The implementation successfully integrates the new Telemere logging component. Let's verify no old logging remains.

✅ Verification successful

Let me analyze the results and generate a final response.

Old logging patterns found, but not in core backend code

The scan reveals that old logging patterns (println, prn) are only present in:

  • Development and build files (build.clj, src/dev/core.cljs)
  • Frontend code (src/front/app/*)

The file under review (src/back/api/db/mocks.clj) and related backend files have successfully migrated to the new Telemere logging component. The remaining instances of old logging patterns are in non-critical paths and typically used for development purposes, which is acceptable.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining old logging patterns in the codebase
# that haven't been migrated to the new Telemere component

# Look for common logging patterns that should be replaced
echo "Checking for old logging patterns in Clojure files..."
rg -t clojure "(println|prn|log/debug|log/info|log/warn|log/error)" \
   --glob '!test/**' \
   --glob '!dev/**'

Length of output: 1427

deps.edn (3)

24-28: LGTM! Comprehensive logging setup.

The logging dependencies are well-structured with:

  • Logback for underlying logging infrastructure
  • Timbre for Clojure-friendly logging
  • JSON appender for structured logging
  • SLF4J bridge for compatibility

2-77: LGTM! Clean and consistent formatting.

The deps.edn file is well-organized with:

  • Logical grouping of dependencies
  • Consistent indentation
  • Clear separation of frontend and backend dependencies
  • Well-structured aliases

12-12: Verify the components upgrade impact.

The version update of com.moclojer/components from 0.1.0 to 0.1.4 appears to be related to the new Telemere logging functionality. However, we should verify that this version is compatible with the current codebase.

✅ Verification successful

Let me gather more specific information about the logging usage to ensure there are no breaking changes.

The previous results showed that the v0.1.4 tag exists and identified files using the logging namespace. Now, I want to examine the actual logging calls and configurations to ensure compatibility with the new version. This will help us determine if there are any breaking changes in the logging patterns that need to be addressed.


Let me try one more verification to check the actual logging function usage in those specific files we found:

This will help us understand how the logging functions are actually being used in the files that import the logging namespace, and if there are any documented changes that might affect the upgrade.


Based on the gathered information, I can now provide a final response:

The components upgrade appears safe to proceed

The verification shows that:

  1. The target version 0.1.4 exists in the moclojer/components repository
  2. Current logging usage is simple and follows a consistent pattern using only basic logging functions:
    • All calls use the standard logs/log function with a log level and context
    • No usage of advanced features that might be affected by breaking changes

The logging implementation appears straightforward and stable across the codebase, primarily used for informational logging with consistent parameters (level and context). The upgrade from 0.1.0 to 0.1.4 should be safe as it maintains compatibility with this basic logging pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of components upgrade
# 1. Check if the new version exists in the repository
# 2. Look for any breaking changes in the logging namespace usage

# Check if the version tag exists in the components repository
gh repo view moclojer/components >/dev/null 2>&1 && \
  echo "Checking version tag v0.1.4 in moclojer/components..." && \
  gh api -H "Accept: application/vnd.github+json" \
    repos/moclojer/components/git/refs/tags/v0.1.4

# Search for logging namespace usage patterns that might need updates
echo "Checking logging namespace usage patterns..."
rg -l 'com\.moclojer\.components\.logs' 

# Look for potential breaking changes in logging calls
echo "Checking logging function calls..."
ast-grep --pattern 'log/$_($$$)'

Length of output: 1554


Script:

#!/bin/bash
# Check specific logging function calls and their patterns
echo "Checking logging patterns in Clojure files..."
rg -A 2 'components\.logs/\w+' 

# Check for any require/import statements of the logging namespace
echo -e "\nChecking logging namespace imports..."
rg '(:require.*com\.moclojer\.components\.logs)'

# Look for any configuration related to logging
echo -e "\nChecking logging configuration patterns..."
rg -A 3 '(:logs|logging-config)'

Length of output: 586


Script:

#!/bin/bash
# Check the content of files that import the logging namespace
echo "Checking yaml_generator/ports/workers.clj logging usage:"
cat src/yaml_generator/ports/workers.clj

echo -e "\nChecking job_ops/controllers/mocks.clj logging usage:"
cat src/job_ops/controllers/mocks.clj

# Also check the changelog or release notes for breaking changes
echo -e "\nChecking for CHANGELOG.md in the current repository:"
fd -g "CHANGELOG.md" --exec cat {}

Length of output: 4115

src/back/api/controllers/mocks.clj (5)

2-7: LGTM: Import changes align with PR objectives.

The addition of com.moclojer.components.logs import is consistent with the PR's goal of updating logging usage.


37-40: LGTM: Appropriate logging context.

The trace logging with mock-wildcard provides sufficient context for debugging availability checks.


70-72: LGTM: Appropriate trace logging for read operation.

The trace logging with user-id provides adequate context for this read operation.


125-128: LGTM: Consistent logging pattern.

The trace logging follows the established pattern for read operations.


47-51: Verify content-hash uniqueness across updates.

Good use of content-hash to avoid logging sensitive data. Let's verify that the hash implementation provides sufficient uniqueness for tracking changes.

✅ Verification successful

Let me gather more information about the hash implementation to ensure it's suitable for tracking changes.


Let me try one more search to specifically look for the hash function usage in Clojure files:


Based on the search results, I can now provide the final response:

The hash implementation is safe and appropriate for change tracking

The code uses Clojure's built-in hash function, which is a stable implementation that provides consistent hash values for equal contents. Since there are no custom hash implementations found in the codebase, and the function is used directly from clojure.core, it guarantees:

  • Consistent hash values across different runs
  • Good distribution of hash values for different contents
  • Thread-safe operation

The implementation is suitable for tracking content changes in mocks.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other uses of hash function to ensure consistent implementation
rg "content-hash|hash\s+content" -A 2 -B 2

Length of output: 426


Script:

#!/bin/bash
# Search for hash function implementation or imports
rg "import.*hash|def.*hash" -A 2

# Look for hash function usage in test files
rg "hash.*content" test/ -A 2 -B 2

# Search for clojure.core/hash references
ast-grep --pattern '(hash $_)'

Length of output: 467


Script:

#!/bin/bash
# Search for hash function in Clojure files
fd '\.clj$' -x rg -l 'hash' {}

# Look for specific hash function implementation or configuration
rg "hash.*function|hash.*config" -A 2 -B 2

# Check if there are any custom hash implementations
ast-grep --pattern '(defn hash'

Length of output: 175

Comment on lines +10 to +13
(logs/trace
::username-available?
{:username username}
(nil? (db.customers/get-by-username username database ctx))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding error case logging

The trace logging is well-placed and includes relevant context. However, consider logging the result when username is not available for better debugging.

 (logs/trace
  ::username-available?
  {:username username}
- (nil? (db.customers/get-by-username username database ctx))))
+ (let [result (db.customers/get-by-username username database ctx)]
+   (when result
+     (logs/trace ::username-taken {:username username}))
+   (nil? result)))
📝 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
(logs/trace
::username-available?
{:username username}
(nil? (db.customers/get-by-username username database ctx))))
(logs/trace
::username-available?
{:username username}
(let [result (db.customers/get-by-username username database ctx)]
(when result
(logs/trace ::username-taken {:username username}))
(nil? result)))

Comment on lines +46 to +51
(logs/trace
::get-users-by-org-id
{:org-id org-id}
(map
adapter.customers/->wire
(db.customers/get-by-org-id org-id database ctx))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add result logging

Consider logging the number of users found for better observability.

 (logs/trace
  ::get-users-by-org-id
  {:org-id org-id}
- (map
-  adapter.customers/->wire
-  (db.customers/get-by-org-id org-id database ctx))))
+ (let [users (db.customers/get-by-org-id org-id database ctx)
+       wire-users (map adapter.customers/->wire users)]
+   (logs/trace ::users-found {:org-id org-id
+                             :count (count wire-users)})
+   wire-users))
📝 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
(logs/trace
::get-users-by-org-id
{:org-id org-id}
(map
adapter.customers/->wire
(db.customers/get-by-org-id org-id database ctx))))
(logs/trace
::get-users-by-org-id
{:org-id org-id}
(let [users (db.customers/get-by-org-id org-id database ctx)
wire-users (map adapter.customers/->wire users)]
(logs/trace ::users-found {:org-id org-id
:count (count wire-users)})
wire-users))

Comment on lines +35 to +42
(logs/trace
::edit-user!
{:user-id user-id
:new-username username}
(-> {:customer/uuid user-id}
(logic.customers/add-username username)
(db.customers/update! database ctx)
(adapter.customers/->wire)))
(adapter.customers/->wire))))
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 and error logging

Consider adding validation for the username and logging for update success/failure.

 (logs/trace
  ::edit-user!
  {:user-id user-id
   :new-username username}
- (-> {:customer/uuid user-id}
-     (logic.customers/add-username username)
-     (db.customers/update! database ctx)
-     (adapter.customers/->wire))))
+ (try
+   (when-not (logic.customers/valid-username? username)
+     (let [error {:cause :invalid-username
+                  :user-id user-id
+                  :username username}]
+       (logs/trace ::invalid-username error)
+       (throw (ex-info "Invalid username format" error))))
+   (let [result (-> {:customer/uuid user-id}
+                    (logic.customers/add-username username)
+                    (db.customers/update! database ctx)
+                    (adapter.customers/->wire))]
+     (logs/trace ::user-updated {:user-id user-id :result result})
+     result)
+   (catch Exception e
+     (logs/trace ::user-update-failed {:user-id user-id
+                                      :error (.getMessage e)})
+     (throw e))))

Committable suggestion was skipped due to low confidence.

Comment on lines +29 to +32
(logs/trace
::get-user-by-external-id
{:user-id id}
(db.customers/get-by-external-id id database ctx)))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add consistent error handling

This function should handle the case where a user is not found, similar to get-user-by-id.

 (logs/trace
  ::get-user-by-external-id
  {:user-id id}
- (db.customers/get-by-external-id id database ctx)))
+ (if-let [user (db.customers/get-by-external-id id database ctx)]
+   user
+   (let [error {:status-code 412
+                :cause :invalid-external-id
+                :external-id id
+                :context ctx}]
+     (logs/trace ::user-not-found-by-external-id error)
+     (throw (ex-info "No user with given external id was found" error)))))
📝 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
(logs/trace
::get-user-by-external-id
{:user-id id}
(db.customers/get-by-external-id id database ctx)))
(logs/trace
::get-user-by-external-id
{:user-id id}
(if-let [user (db.customers/get-by-external-id id database ctx)]
user
(let [error {:status-code 412
:cause :invalid-external-id
:external-id id
:context ctx}]
(logs/trace ::user-not-found-by-external-id error)
(throw (ex-info "No user with given external id was found" error)))))

Comment on lines +17 to +25
(logs/trace
::get-user-by-id
{:user-id id}
(adapter.customers/->wire
(or (db.customers/get-by-id id database ctx)
(throw (ex-info "No user with given id was found"
{:status-code 412
:cause :invalid-id
:value (assoc ctx :user-id id)})))))
:value (assoc ctx :user-id id)}))))))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and logging

While the trace logging is good, consider these improvements:

  1. Add error logging when user is not found
  2. Restructure error map for better clarity
 (logs/trace
  ::get-user-by-id
  {:user-id id}
  (adapter.customers/->wire
   (or (db.customers/get-by-id id database ctx)
-      (throw (ex-info "No user with given id was found"
-                       {:status-code 412
-                        :cause :invalid-id
-                        :value (assoc ctx :user-id id)})))))
+      (let [error {:status-code 412
+                   :cause :invalid-id
+                   :user-id id
+                   :context ctx}]
+        (logs/trace ::user-not-found error)
+        (throw (ex-info "No user with given id was found" error))))))
📝 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
(logs/trace
::get-user-by-id
{:user-id id}
(adapter.customers/->wire
(or (db.customers/get-by-id id database ctx)
(throw (ex-info "No user with given id was found"
{:status-code 412
:cause :invalid-id
:value (assoc ctx :user-id id)})))))
:value (assoc ctx :user-id id)}))))))
(logs/trace
::get-user-by-id
{:user-id id}
(adapter.customers/->wire
(or (db.customers/get-by-id id database ctx)
(let [error {:status-code 412
:cause :invalid-id
:user-id id
:context ctx}]
(logs/trace ::user-not-found error)
(throw (ex-info "No user with given id was found" error))))))

Comment on lines +79 to +82
(logs/trace
::publish-mock!
{:mock-id id}
(-> (db.mocks/get-mock-by-id id database ctx)
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider standardizing success/failure logging across operations.

Both publish and unpublish operations would benefit from consistent success/failure logging patterns.

 ;; Add to both publish-mock! and unpublish-mock!:
+ (logs/trace
+  ::{un}publish-mock-success!
+  {:mock-id id
+   :status "success"})

Also applies to: 92-95

Comment on lines +141 to +144
(logs/trace
::update-mock-dns-status!
{:mock-domain domain
:new-status new-status}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding error tracking for status updates.

Both DNS and unification status updates would benefit from error tracking in logs.

 ;; Add to both status update functions:
+ (try
+   ;; existing update logic
+   (catch Exception e
+     (logs/error
+      ::{dns|unif}-status-update-failed!
+      {:mock-id id
+       :new-status new-status
+       :error (.getMessage e)}
+      e)))

Also applies to: 155-158

Comment on lines 1 to 161
(logs/trace
::publish-mock!
{:mock-id id}
(-> (db.mocks/get-mock-by-id id database ctx)
logic.mocks/publish
(db.mocks/update! database ctx)
(adapter.mocks/->wire)
:id
(ports.producers/generate-single-yml! mq ctx)))
true)

(defn unpublish-mock!
[id {:keys [database mq]} ctx]
(-> (db.mocks/get-mock-by-id id database ctx)
(logs/trace
::unpublish-mock!
{:mock-id id}
(-> (db.mocks/get-mock-by-id id database ctx)
logic.mocks/unpublish
(db.mocks/update! database ctx)
(adapter.mocks/->wire)
:id
(ports.producers/generate-single-yml! mq ctx))
(ports.producers/generate-single-yml! mq ctx)))
true)

(defn delete-mock!
[{:keys [user-id]} id {:keys [database mq]} ctx]
(logs/log :info "deleting mock"
:ctx (assoc ctx :mock-id id))
(if-let [{:keys [id org-id user-id] :as ?mock}
(some-> (db.mocks/get-mocks user-id database ctx)
(logic.mocks/filter-by-id id)
(adapter.mocks/->wire))]
(do
(db.mocks/delete-mock-by-id id database ctx)
(ports.producers/delete-single-yml! id (or org-id user-id) mq ctx)
(ports.producers/delete-domain! (logic.mocks/pack-domain ?mock) mq ctx)
true)
(logs/trace
::delete-mock!
{:user-id user-id
:mock-id id}
(do
(db.mocks/delete-mock-by-id id database ctx)
(ports.producers/delete-single-yml! id (or org-id user-id) mq ctx)
(ports.producers/delete-domain! (logic.mocks/pack-domain ?mock) mq ctx)
true))
(throw (ex-info "No mock found with given id"
{:status-code 400
:cause :invalid-id
:value :id}))))

(defn get-mock-publication-status
[id db ctx]
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str id)) db ctx)]
(logs/trace
::get-mock-pub-status
{:mock-id id}
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str id)) db ctx)]
(-> (adapter.mocks/->wire mock)
(select-keys [:dns-status :unification-status]))
(throw (ex-info "No mock found with given id"
{:status-code 400
:cause :invalid-id
:value id}))))
:value id})))))

(defn update-mock-dns-status!
[domain new-status db ctx]
(if-let [mock (-> (logic.mocks/unpack-domain domain)
(logic.mocks/->db-by-wildcard)
(db.mocks/get-mock-by-wildcard db ctx))]
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-dns-status!
{:mock-domain domain
:new-status new-status}
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx)))
(throw (ex-info "No mock found with given domain"
{:cause :invalid-domain
:value domain}))))

(defn update-mock-unification-status!
[mock-id new-status db ctx]
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str mock-id)) db ctx)]
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-unif-status!
{:mock-id mock-id
:new-status new-status}
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx)))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Overall logging implementation review.

The logging changes show good consistency and align well with the PR objectives. Some suggestions for enhancement:

  1. Consider implementing a consistent pattern for success/failure logging across all operations
  2. Consider elevating certain operations (like deletions) to INFO level for audit purposes
  3. Consider adding error tracking for critical operations

These changes provide good observability while maintaining clean code structure.

Comment on lines +109 to +113
(logs/trace
::delete-mock!
{:user-id user-id
:mock-id id}
(do
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding audit logging for deletions.

While the trace logging is good, deletions should potentially be logged at INFO level for audit purposes.

- (logs/trace
+ (logs/info
   ::delete-mock!
   {:user-id user-id
    :mock-id id})
📝 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
(logs/trace
::delete-mock!
{:user-id user-id
:mock-id id}
(do
(logs/info
::delete-mock!
{:user-id user-id
:mock-id id}
(do

Comment on lines +11 to +15
(logs/trace
::create-mock!
{:mock-id (:id mock)
:user-id user-id}
(let [owner (assoc {:user-id (parse-uuid (str user-id))}
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding operation outcome to logs.

The structured logging with mock-id and user-id provides good context. Consider adding a second trace log after the operation completes to track success/failure.

 (logs/trace
  ::create-mock!
  {:mock-id (:id mock)
   :user-id user-id}
+ ;; Add at the end of the function:
+ (logs/trace
+  ::create-mock-success!
+  {:mock-id (:id mock)
+   :user-id user-id})

Committable suggestion was skipped due to low confidence.

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 UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 5a7a935 and 1354a68.

📒 Files selected for processing (1)
  • src/back/api/controllers/mocks.clj (1 hunks)
🔇 Additional comments (2)
src/back/api/controllers/mocks.clj (2)

2-7: LGTM: Import changes align with PR objectives.

The addition of com.moclojer.components.logs import is appropriate for integrating the new logging component.


167-182: 🧹 Nitpick (assertive)

Review meta-programming approach for function wrapping.

While the automatic function wrapping is clever, there are several concerns to address:

  1. Runtime function modification can complicate debugging and hot reloading
  2. The context map creation might fail with destructured arguments
  3. No error handling in the wrapped logging
  4. Potential performance impact from double function evaluation

Let's check for destructured arguments that might break the context map creation:

Consider these alternatives:

  1. Use a macro to wrap functions at compile time
  2. Create a higher-order function for wrapping
  3. Use aspect-oriented programming libraries like robert/hooke

Example using a higher-order function:

(defn wrap-with-logging [f fname]
  (fn [& args]
    (try
      (let [context (-> (zipmap (map keyword (take (- (count args) 2) args)) args)
                        (dissoc :components :ctx))]
        (logs/trace fname context)
        (apply f args))
      (catch Exception e
        (binding [*out* *err*]
          (println "Logging error in" fname ":" (.getMessage e)))
        (apply f args)))))

;; Usage:
(def create-mock! 
  (wrap-with-logging create-mock! ::create-mock!))

Comment on lines 11 to 161
(logs/trace
::publish-mock!
{:mock-id id}
(-> (db.mocks/get-mock-by-id id database ctx)
logic.mocks/publish
(db.mocks/update! database ctx)
(adapter.mocks/->wire)
:id
(ports.producers/generate-single-yml! mq ctx)))
true)

(defn unpublish-mock!
[id {:keys [database mq]} ctx]
(-> (db.mocks/get-mock-by-id id database ctx)
(logs/trace
::unpublish-mock!
{:mock-id id}
(-> (db.mocks/get-mock-by-id id database ctx)
logic.mocks/unpublish
(db.mocks/update! database ctx)
(adapter.mocks/->wire)
:id
(ports.producers/generate-single-yml! mq ctx))
(ports.producers/generate-single-yml! mq ctx)))
true)

(defn delete-mock!
[{:keys [user-id]} id {:keys [database mq]} ctx]
(logs/log :info "deleting mock"
:ctx (assoc ctx :mock-id id))
(if-let [{:keys [id org-id user-id] :as ?mock}
(some-> (db.mocks/get-mocks user-id database ctx)
(logic.mocks/filter-by-id id)
(adapter.mocks/->wire))]
(do
(db.mocks/delete-mock-by-id id database ctx)
(ports.producers/delete-single-yml! id (or org-id user-id) mq ctx)
(ports.producers/delete-domain! (logic.mocks/pack-domain ?mock) mq ctx)
true)
(logs/trace
::delete-mock!
{:user-id user-id
:mock-id id}
(do
(db.mocks/delete-mock-by-id id database ctx)
(ports.producers/delete-single-yml! id (or org-id user-id) mq ctx)
(ports.producers/delete-domain! (logic.mocks/pack-domain ?mock) mq ctx)
true))
(throw (ex-info "No mock found with given id"
{:status-code 400
:cause :invalid-id
:value :id}))))

(defn get-mock-publication-status
[id db ctx]
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str id)) db ctx)]
(logs/trace
::get-mock-pub-status
{:mock-id id}
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str id)) db ctx)]
(-> (adapter.mocks/->wire mock)
(select-keys [:dns-status :unification-status]))
(throw (ex-info "No mock found with given id"
{:status-code 400
:cause :invalid-id
:value id}))))
:value id})))))

(defn update-mock-dns-status!
[domain new-status db ctx]
(if-let [mock (-> (logic.mocks/unpack-domain domain)
(logic.mocks/->db-by-wildcard)
(db.mocks/get-mock-by-wildcard db ctx))]
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-dns-status!
{:mock-domain domain
:new-status new-status}
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx)))
(throw (ex-info "No mock found with given domain"
{:cause :invalid-domain
:value domain}))))

(defn update-mock-unification-status!
[mock-id new-status db ctx]
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str mock-id)) db ctx)]
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-unif-status!
{:mock-id mock-id
:new-status new-status}
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx)))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider wrapping trace logging in try-catch blocks.

While the trace logging implementation is consistent, it's important to ensure that logging failures don't affect the main functionality. Consider wrapping the trace calls in try-catch blocks, especially for critical operations.

Example implementation:

 (defn create-mock!
   [user-id mock {:keys [database mq]} ctx]
-  (logs/trace
-   ::create-mock!
-   {:mock-id (:id mock)
-    :user-id user-id}
+  (try
+    (logs/trace
+     ::create-mock!
+     {:mock-id (:id mock)
+      :user-id user-id})
+    (catch Exception e
+      ; Swallow logging errors but maybe log to stderr
+      (binding [*out* *err*]
+        (println "Logging error in create-mock!:" (.getMessage e)))))

Committable suggestion was skipped due to low confidence.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 1354a68 and 468290f.

📒 Files selected for processing (1)
  • src/back/api/controllers/mocks.clj (1 hunks)
🔇 Additional comments (1)
src/back/api/controllers/mocks.clj (1)

1-8: LGTM: Clean namespace organization with new logging component.

The addition of com.moclojer.components.logs aligns with the PR objectives of updating logging usage.

Comment on lines 167 to 231
;; Iterate over *ns* functions and replace them with themselves within
;; a `logs/trace` call that uses each function's arglist as context.
(doseq [[fsym func] (ns-publics *ns*)]
(let [args (first (:arglists (meta func)))
argmap (reduce
(fn [acc v]
(prn v)
(assoc acc (keyword v) v))
;; remove components and ctx
{} (drop-last 2 args))
symkey (keyword (symbol (str *ns*) (str fsym)))]
#_(intern
*ns* fsym
(eval
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args)))))
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args))))))

(let [fsym 'delete-mock!
func #'back.api.controllers.mocks/delete-mock!
symkey (keyword (symbol (str *ns*) (str fsym)))
args (first (:arglists (meta func)))
argmap (reduce
(fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (some? (:as v)))
(assoc acc (keyword (:as v) (:as v)))

;; Arg with only the :keys vec declared.
(and (map? v) (some? (:keys v)))
(reduce
(fn [acc arg]
(assoc acc (keyword arg) arg))
acc (:keys v))

;; Normal arg types.
:else (assoc acc (keyword v) v)))
;; remove components and ctx
{} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (some? (:as arg)))
(:as arg)

(and (map? arg) (some? (:keys arg)))
(reduce
(fn [argmap arg]
;; FIXME: not working for some reason
(prn :argmap argmap :argkey arg)
(assoc argmap (:keyword arg) arg))
{} (:keys args))

:else arg))
args)]
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@callargs)))))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove or complete the experimental logging wrapper code.

The experimental code at the end of the file has several issues:

  1. Contains debug statements (prn)
  2. Has commented out core functionality
  3. Contains unresolved FIXME
  4. Implements complex meta-programming that could be simplified

Consider either:

  1. Removing this experimental code until it's ready for production, or
  2. Completing it properly by:
    • Removing debug statements
    • Resolving the FIXME
    • Uncommenting and testing the core functionality
    • Adding proper documentation

If you'd like to keep this functionality, consider moving it to a separate namespace focused on logging utilities, such as back.api.utils.logging.

Comment on lines +22 to +25
(throw (ex-info "Mock with given wildcard and subdomain invalid"
{:status-code 412
:cause :invalid-wildcard
:value (adapter.mocks/->wire ?existing-mock)}))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance error message with validation details.

The error message could be more helpful by including the specific validation failure details.

-      (throw (ex-info "Mock with given wildcard and subdomain invalid"
+      (throw (ex-info (format "Mock with wildcard '%s' and subdomain '%s' already exists"
+                             (:wildcard mock)
+                             (:subdomain mock))
               {:status-code 412
                :cause :invalid-wildcard
-               :value (adapter.mocks/->wire ?existing-mock)}))
+               :value (adapter.mocks/->wire ?existing-mock)
+               :conflict {:wildcard (:wildcard mock)
+                         :subdomain (:subdomain mock)}}))

Committable suggestion was skipped due to low confidence.

Comment on lines 1 to 231
(if-let [mock (-> (logic.mocks/unpack-domain domain)
(logic.mocks/->db-by-wildcard)
(db.mocks/get-mock-by-wildcard db ctx))]
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-dns-status!
{:mock-domain domain
:new-status new-status}
(-> (logic.mocks/update-dns-status mock new-status)
(select-keys [:mock/id :mock/dns_status])
(db.mocks/update! db ctx)))
(throw (ex-info "No mock found with given domain"
{:cause :invalid-domain
:value domain}))))

(defn update-mock-unification-status!
[mock-id new-status db ctx]
(if-let [mock (db.mocks/get-mock-by-id (parse-uuid (str mock-id)) db ctx)]
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx))
(logs/trace
::update-mock-unif-status!
{:mock-id mock-id
:new-status new-status}
(-> (logic.mocks/update-unification-status mock new-status)
(select-keys [:mock/id :mock/unification_status])
(db.mocks/update! db ctx)))
(throw (ex-info "No mock found with given id"
{:status-code 400
:cause :invalid-id
:value mock-id}))))

;; Iterate over *ns* functions and replace them with themselves within
;; a `logs/trace` call that uses each function's arglist as context.
(doseq [[fsym func] (ns-publics *ns*)]
(let [args (first (:arglists (meta func)))
argmap (reduce
(fn [acc v]
(prn v)
(assoc acc (keyword v) v))
;; remove components and ctx
{} (drop-last 2 args))
symkey (keyword (symbol (str *ns*) (str fsym)))]
#_(intern
*ns* fsym
(eval
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args)))))
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args))))))

(let [fsym 'delete-mock!
func #'back.api.controllers.mocks/delete-mock!
symkey (keyword (symbol (str *ns*) (str fsym)))
args (first (:arglists (meta func)))
argmap (reduce
(fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (some? (:as v)))
(assoc acc (keyword (:as v) (:as v)))

;; Arg with only the :keys vec declared.
(and (map? v) (some? (:keys v)))
(reduce
(fn [acc arg]
(assoc acc (keyword arg) arg))
acc (:keys v))

;; Normal arg types.
:else (assoc acc (keyword v) v)))
;; remove components and ctx
{} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (some? (:as arg)))
(:as arg)

(and (map? arg) (some? (:keys arg)))
(reduce
(fn [argmap arg]
;; FIXME: not working for some reason
(prn :argmap argmap :argkey arg)
(assoc argmap (:keyword arg) arg))
{} (:keys args))

:else arg))
args)]
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@callargs)))))
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Migration to new logging component is consistent but incomplete

The verification reveals a mixed usage of logging patterns that needs attention:

  • Most of the codebase has migrated to com.moclojer.components.logs with the :as logs alias
  • Consistent usage of logs/trace in the back/api modules
  • However, there are still old-style logging calls in several files:
    • src/yaml_generator/ports/workers.clj using logs/log
    • src/job_ops/controllers/mocks.clj using logs/log
    • src/cloud_ops/api/controllers/*.clj using logs/log, logs/error, logs/warn
    • src/dev/shadow/hooks.clj using direct s.util/log
🔗 Analysis chain

Verify complete migration to new logging component.

Let's verify the complete migration to the new logging component across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration to new logging component

# Check for any remaining old logging imports
echo "Checking for old logging imports..."
rg -l 'require.*\[(?!com\.moclojer\.components\.logs).*\.log[gs]\]' --type clojure

# Check for consistent usage of new logging namespace alias
echo "Checking for consistent logs alias usage..."
rg -l 'require.*\[com\.moclojer\.components\.logs :as (?!logs\])' --type clojure

# Check for any remaining direct logging calls
echo "Checking for old logging calls..."
rg '\b(?!logs/trace)\w+/(?:log|debug|info|warn|error)\b' --type clojure

Length of output: 1335


Script:

#!/bin/bash
# Description: Verify migration to new logging component with simpler patterns

# Check for any logging-related imports
echo "Checking logging imports..."
rg --pcre2 'require.*\.log[gs]' --type clojure

# Check for logging namespace aliases
echo "Checking logging namespace aliases..."
rg --pcre2 'require.*components\.logs :as' --type clojure

# Check for logging function calls
echo "Checking logging function calls..."
rg --pcre2 '\w+/(log|debug|info|warn|error|trace)\b' --type clojure -A 2

Length of output: 19066

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 468290f and dc4d777.

📒 Files selected for processing (1)
  • src/back/api/controllers/mocks.clj (1 hunks)
🔇 Additional comments (1)
src/back/api/controllers/mocks.clj (1)

141-147: Consider adding optimistic locking for status updates.

The status update functions (update-mock-dns-status! and update-mock-unification-status!) could be susceptible to race conditions if multiple updates occur simultaneously. Consider implementing optimistic locking or version tracking.

Let's verify if there are any concurrent status updates in the codebase:

Also applies to: 155-161

Comment on lines 193 to 218
argmap (reduce
(fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (some? (:as v)))
(assoc acc (keyword (:as v) (:as v)))

;; Arg with only the :keys vec declared.
(and (map? v) (some? (:keys v)))
(reduce
(fn [acc arg]
(assoc acc (keyword arg) arg))
acc (:keys v))

;; Arg with :or declared (WIP)
(and (map? v) (some? (:or v)))
(reduce
(fn [v acc arg]
(assoc acc (keyword arg)
(get (:or v) arg)))
acc (:keys v))

;; Normal arg types.
:else (assoc acc (keyword v) v)))
;; remove components and ctx
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Simplify and secure the argument mapping logic.

The current argument mapping logic has several issues:

  1. Complex nested conditionals make it hard to maintain
  2. No validation of argument types before keyword conversion
  3. Potential security risk if user-controlled data is directly converted to keywords

Consider extracting this logic into a separate utility function with proper validation.

Here's a suggested approach:

(defn safe-arg->keyword [arg]
  (cond
    (nil? arg) nil
    (keyword? arg) arg
    (symbol? arg) (keyword (name arg))
    :else (throw (ex-info "Invalid argument type for keyword conversion"
                         {:arg arg
                          :type (type arg)}))))

(defn build-arg-map [args]
  (reduce
    (fn [acc arg]
      (cond
        (map? arg)
        (cond
          (:as arg) (assoc acc (safe-arg->keyword (:as arg)) (:as arg))
          (:keys arg) (merge acc
                            (into {}
                                  (map (juxt safe-arg->keyword identity))
                                  (:keys arg)))
          :else acc)
        :else (assoc acc (safe-arg->keyword arg) arg)))
    {}
    args))

Comment on lines 184 to 187
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args))))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove debug printing and consolidate example code.

The experimental code contains:

  1. Debug printing with clojure.pprint
  2. Redundant example for a single function

Either move this to a development/test namespace or remove it entirely before merging.

If you want to keep this as a development utility, consider moving it to:

  • src/dev/logging_utils.clj
  • test/back/api/controllers/mocks_test.clj

Also applies to: 234-237

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between dc4d777 and f7b6163.

📒 Files selected for processing (1)
  • src/back/api/controllers/mocks.clj (1 hunks)

Comment on lines 167 to 187
;; Iterate over *ns* functions and replace them with themselves within
;; a `logs/trace` call that uses each function's arglist as context.
(doseq [[fsym func] (ns-publics *ns*)]
(let [args (first (:arglists (meta func)))
argmap (reduce
(fn [acc v]
(prn v)
(assoc acc (keyword v) v))
;; remove components and ctx
{} (drop-last 2 args))
symkey (keyword (symbol (str *ns*) (str fsym)))]
#_(intern
*ns* fsym
(eval
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args)))))
(clojure.pprint/pprint
`(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@args))))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Move experimental code to a development namespace.

The experimental logging wrapper code has several architectural concerns:

  1. Modifying namespace bindings at runtime is risky and can lead to unpredictable behavior
  2. The code is not production-ready (contains debug prints and commented code)
  3. The implementation belongs in a development utility namespace

Consider moving this code to a dedicated development namespace like dev.logging-utils and implementing it as a macro that can be used during development. This would:

  1. Keep production code clean
  2. Allow for proper testing of the logging wrapper
  3. Provide a safer way to experiment with logging enhancements

Example structure:

;; dev/logging_utils.clj
(ns dev.logging-utils
  (:require [com.moclojer.components.logs :as logs]))

(defmacro wrap-ns-with-logging
  "Development utility to wrap namespace functions with logging."
  [ns-sym]
  ;; Implementation here
  )

Comment on lines 45 to 66
[id content {:keys [database mq]} ctx]
(if-let [mock (db.mocks/get-mock-by-id id database ctx)]
(let [updated-mock (-> mock
(logic.mocks/update {:content content})
(db.mocks/update! database ctx)
(adapter.mocks/->wire))
->wired-old-mock (adapter.mocks/->wire mock)]
(logs/trace
::update-mock!
{:mock-id id
:content-hash (hash content)}
(let [updated-mock (-> (logic.mocks/update mock {:content content})
(db.mocks/update! database ctx)
(adapter.mocks/->wire))
->wired-old-mock (adapter.mocks/->wire mock)]

(ports.producers/generate-single-yml! (:id updated-mock) mq ctx)
(ports.producers/generate-single-yml! (:id updated-mock) mq ctx)

(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
(ports.producers/create-domain! (logic.mocks/pack-domain ->wired-old-mock)
mq
ctx))
(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
(ports.producers/create-domain!
(logic.mocks/pack-domain ->wired-old-mock) mq ctx))

updated-mock)
updated-mock))
(throw (ex-info "Mock with given id invalid"
{:status-code 412
:cause :invalid-id}))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add trace logging for error paths.

The error path in update-mock! lacks trace logging. Consider adding error context logging before throwing the exception.

   (if-let [mock (db.mocks/get-mock-by-id id database ctx)]
     (logs/trace
      ::update-mock!
      {:mock-id id
       :content-hash (hash content)}
      (let [updated-mock (-> (logic.mocks/update mock {:content content})
                             (db.mocks/update! database ctx)
                             (adapter.mocks/->wire))
            ->wired-old-mock (adapter.mocks/->wire mock)]
        (ports.producers/generate-single-yml! (:id updated-mock) mq ctx)
        (when (and (= (:dns-status ->wired-old-mock) "offline")
                   (:enabled ->wired-old-mock))
          (ports.producers/create-domain!
           (logic.mocks/pack-domain ->wired-old-mock) mq ctx))
        updated-mock))
-    (throw (ex-info "Mock with given id invalid"
-                    {:status-code 412
-                     :cause :invalid-id}))))
+    (do
+      (logs/trace
+       ::update-mock-failed!
+       {:mock-id id
+        :reason :invalid-id})
+      (throw (ex-info "Mock with given id invalid"
+                     {:status-code 412
+                      :cause :invalid-id})))))
📝 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
[id content {:keys [database mq]} ctx]
(if-let [mock (db.mocks/get-mock-by-id id database ctx)]
(let [updated-mock (-> mock
(logic.mocks/update {:content content})
(db.mocks/update! database ctx)
(adapter.mocks/->wire))
->wired-old-mock (adapter.mocks/->wire mock)]
(logs/trace
::update-mock!
{:mock-id id
:content-hash (hash content)}
(let [updated-mock (-> (logic.mocks/update mock {:content content})
(db.mocks/update! database ctx)
(adapter.mocks/->wire))
->wired-old-mock (adapter.mocks/->wire mock)]
(ports.producers/generate-single-yml! (:id updated-mock) mq ctx)
(ports.producers/generate-single-yml! (:id updated-mock) mq ctx)
(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
(ports.producers/create-domain! (logic.mocks/pack-domain ->wired-old-mock)
mq
ctx))
(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
(ports.producers/create-domain!
(logic.mocks/pack-domain ->wired-old-mock) mq ctx))
updated-mock)
updated-mock))
(throw (ex-info "Mock with given id invalid"
{:status-code 412
:cause :invalid-id}))))
[id content {:keys [database mq]} ctx]
(if-let [mock (db.mocks/get-mock-by-id id database ctx)]
(logs/trace
::update-mock!
{:mock-id id
:content-hash (hash content)}
(let [updated-mock (-> (logic.mocks/update mock {:content content})
(db.mocks/update! database ctx)
(adapter.mocks/->wire))
->wired-old-mock (adapter.mocks/->wire mock)]
(ports.producers/generate-single-yml! (:id updated-mock) mq ctx)
(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
(ports.producers/create-domain!
(logic.mocks/pack-domain ->wired-old-mock) mq ctx))
updated-mock))
(do
(logs/trace
::update-mock-failed!
{:mock-id id
:reason :invalid-id})
(throw (ex-info "Mock with given id invalid"
{:status-code 412
:cause :invalid-id})))))

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between f7b6163 and 51df2fe.

📒 Files selected for processing (1)
  • src/back/api/controllers/mocks.clj (1 hunks)

Comment on lines 173 to 205
(doseq [[fsym func] (ns-publics *ns*)]
(let [symkey (keyword (symbol (str *ns*) (name fsym)))
args (first (:arglists (meta func)))
pre-argmap (fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (:as v))
(acc (keyword (:as v)) (:as v))
;; Arg with only the :keys vec declared.
(and (map? v) (:keys v))
(into {} (map (fn [k]
[(keyword k) k])
(:keys v)))
;; Normal arg types.
:else (assoc acc (keyword v) v)))
argmap (reduce pre-argmap {} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (:as arg))
(:as arg)
(and (map? arg) (:keys arg))
(into {} (map (fn [a]
[(keyword a) a])
(:keys arg)))
:else arg))
args)]
(intern
*ns* fsym
(eval `(fn [~@args]
(com.moclojer.components.logs/trace ~symkey ~argmap
(~func ~@callargs)))))))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Function wrapping implementation could break function metadata and arity.

The current implementation has several technical issues:

  1. Wrapping functions loses their metadata (including doc strings and arity information)
  2. The wrapper doesn't preserve the function's variadic arguments
  3. Higher-order functions might not work correctly with wrapped functions

Consider using Clojure's alter-var-root with proper metadata preservation:

(defn wrap-with-logging [f sym]
  (let [m (meta f)
        wrapped (fn [& args]
                 (logs/trace sym
                            (zipmap (map keyword (first (:arglists m)))
                                   args)
                            (apply f args)))]
    (with-meta wrapped m)))

(doseq [[sym var] (ns-publics *ns*)]
  (when (fn? @var)
    (alter-var-root var #(wrap-with-logging % (keyword (str *ns*) (name sym))))))

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 51df2fe and 4cbe07d.

📒 Files selected for processing (2)
  • src/back/api/controllers/mocks.clj (1 hunks)
  • test/back/back/integration/api/wrap_traces_test.clj (1 hunks)
🔇 Additional comments (4)
test/back/back/integration/api/wrap_traces_test.clj (2)

1-11: LGTM: Namespace declaration and imports are well-organized

The namespace declaration follows Clojure conventions and includes all necessary dependencies for testing and component management.


38-42: 🧹 Nitpick (assertive)

Enhance test coverage and description

The current test implementation has several areas for improvement:

  1. The test description could be more specific about what "desired ns functions" means
  2. There's no error case testing
  3. The test might pass incorrectly if both save-local-fns and trace-all-ns-test return empty lists

Let's verify if trace-all-ns-test is properly implemented:

Consider adding these test cases:

;; Test for non-empty results
(flow "ensures functions are actually being collected"
      (match? (comp not empty?) (save-local-fns)))

;; Test for error cases
(flow "handles invalid namespaces gracefully"
      (with-redefs [mocks/get-allowed-ns (constantly ['non.existent.ns])]
        (match? empty? (save-local-fns))))
src/back/api/controllers/mocks.clj (2)

12-15: LGTM! Consistent trace logging implementation.

The trace logging implementation is consistent across all functions and includes relevant contextual information.

Also applies to: 38-40, 48-51, 71-72, 80-82, 93-95, 110-113, 126-128, 142-145, 156-159


168-175: LGTM! Clear implementation of namespace filtering.

The function effectively filters namespaces to include only relevant ones for tracing.

Comment on lines 24 to 30
(defn- save-local-fns []
(let [a-ns (mocks/get-allowed-ns)
m (atom [])]
(doseq [d-ns a-ns]
(doseq [[func _] (ns-publics d-ns)]
(swap! m conj (str func))))
@m))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify save-local-fns implementation

The current implementation using an atom and nested doseq can be simplified using Clojure's sequence operations for better readability and performance.

Consider this more idiomatic implementation:

-(defn- save-local-fns []
-  (let [a-ns (mocks/get-allowed-ns)
-        m (atom [])]
-    (doseq [d-ns a-ns]
-      (doseq [[func _] (ns-publics d-ns)]  
-        (swap! m conj (str func))))       
-    @m))
+(defn- save-local-fns []
+  (->> (mocks/get-allowed-ns)
+       (mapcat ns-publics)
+       (map (comp str first))
+       (into [])))
📝 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
(defn- save-local-fns []
(let [a-ns (mocks/get-allowed-ns)
m (atom [])]
(doseq [d-ns a-ns]
(doseq [[func _] (ns-publics d-ns)]
(swap! m conj (str func))))
@m))
(defn- save-local-fns []
(->> (mocks/get-allowed-ns)
(mapcat ns-publics)
(map (comp str first))
(into [])))

Comment on lines 13 to 30
(defn- create-and-start-components []
(component/start-system
(component/system-map
:config (components/new-config "back/config.edn")
:logger (component/using (components/new-logger) [:config])
:http (components/new-http-mock [])
:router (components/new-router routes/routes)
:database (component/using (components/new-database) [:config])
:mq (components/new-mq-mock)
:webserver (component/using (components/new-webserver)
[:config :http :router :database :mq]))))
(defn- save-local-fns []
(let [a-ns (mocks/get-allowed-ns)
m (atom [])]
(doseq [d-ns a-ns]
(doseq [[func _] (ns-publics d-ns)]
(swap! m conj (str func))))
@m))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add docstrings to helper functions

Both helper functions lack documentation. Please add docstrings explaining their purpose, arguments, and return values.

Example for create-and-start-components:

 (defn- create-and-start-components []
+  "Creates and starts a new component system with all required dependencies.
+   Returns the started system map containing config, logger, http, router, database, mq, and webserver components."
   (component/start-system

Example for save-local-fns:

 (defn- save-local-fns []
+  "Retrieves all public function names from allowed namespaces.
+   Returns a vector of function names as strings."
   (let [a-ns (mocks/get-allowed-ns)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +22 to +26
(if (seq ?existing-mock)
(throw (ex-info "Mock with given wildcard and subdomain invalid"
{:status-code 412
:cause :invalid-wildcard
:value (adapter.mocks/->wire ?existing-mock)}))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Standardize error handling and add trace logging for error paths.

The error handling patterns are inconsistent:

  1. Some exceptions include status-code while others don't
  2. Error paths lack trace logging

Example implementation for standardized error handling:

- (throw (ex-info "Mock with given wildcard and subdomain invalid"
-                 {:status-code 412
-                  :cause :invalid-wildcard
-                  :value (adapter.mocks/->wire ?existing-mock)}))
+ (do
+   (logs/trace
+    ::create-mock-failed!
+    {:mock-id (:id mock)
+     :user-id user-id
+     :reason :invalid-wildcard})
+   (throw (ex-info "Mock with given wildcard and subdomain invalid"
+                   {:status-code 412
+                    :cause :invalid-wildcard
+                    :value (adapter.mocks/->wire ?existing-mock)})))

Also applies to: 63-67, 119-122, 132-135, 149-151, 163-166

Comment on lines 228 to 238
(defn inspect [a] (prn a) a)

(defn trace-all-ns-test []
(let [a-ns (get-allowed-ns)
m (atom [])]
(doseq [curr-ns a-ns]
(doseq [[sym v] (ns-publics curr-ns)]
(when (fn? @v)
(swap! m conj (str (inspect ((meta v) :name))))
(alter-var-root v #(wrap-with-trace % (keyword (str curr-ns) (name sym)))))))
@m))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove debug code and move experimental implementation to dev namespace.

The current implementation contains:

  1. Debug printing with prn
  2. Experimental code mixed with production code

Consider:

  1. Removing debug statements
  2. Moving experimental code to a development namespace:
    • src/dev/logging_utils.clj
    • test/back/api/controllers/mocks_test.clj

Comment on lines 177 to 217
(defn trace-all-ns
"Iterate over *ns* functions and replace them with themselves within
a `logs/trace` call that uses each function's arglist as context."
[]
(let [desired-ns
(get-allowed-ns)]
(doseq [current-ns desired-ns]
(doseq [[fsym func] (ns-publics current-ns)]
(let [sym (keyword (symbol (str current-ns) (name fsym)))
m (meta func)
args (first (:arglists m))
pre-argmap (fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (:as v))
(acc (keyword (:as v)) (:as v))
;; Arg with only the :keys vec declared.
(and (map? v) (:keys v))
(into {} (map (fn [k]
[(keyword k) k])
(:keys v)))
;; Normal arg types.
:else (assoc acc (keyword v) v)))
argmap (reduce pre-argmap {} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (:as arg))
(:as arg)
(and (map? arg) (:keys arg))
(into {} (map (fn [a] [(keyword a) a]) (:keys arg)))
:else arg))
args)]
(if-not (some #(= % '&) args)
(intern
*ns* fsym
(with-meta (eval `(fn [~@args]
(com.moclojer.components.logs/trace ~sym ~argmap
(~func ~@callargs)))) m))
(logs/log "--> could not convert" func "args:" args)))))))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify the complex meta-programming implementation.

The current implementation:

  1. Has complex nested conditionals for argument mapping
  2. Might break function metadata
  3. Doesn't handle all edge cases

Consider simplifying using a more straightforward approach:

(defn safe-arg->keyword [arg]
  (cond
    (nil? arg) nil
    (keyword? arg) arg
    (symbol? arg) (keyword (name arg))
    :else (throw (ex-info "Invalid argument type"
                         {:arg arg
                          :type (type arg)}))))

(defn build-arg-map [args]
  (reduce
    (fn [acc arg]
      (cond
        (map? arg)
        (cond
          (:as arg) (assoc acc (safe-arg->keyword (:as arg)) (:as arg))
          (:keys arg) (merge acc
                            (into {}
                                  (map (juxt safe-arg->keyword identity))
                                  (:keys arg)))
          :else acc)
        :else (assoc acc (safe-arg->keyword arg) arg)))
    {}
    args))

(defn trace-all-ns []
  (doseq [current-ns (get-allowed-ns)
          [fsym func] (ns-publics current-ns)
          :let [sym (keyword (str current-ns) (name fsym))
                m (meta func)]]
    (when-let [args (first (:arglists m))]
      (when-not (some #{'&} args)
        (intern *ns* fsym
                (with-meta
                  (fn [& args]
                    (logs/trace sym
                               (build-arg-map args)
                               (apply func args)))
                  m))))))
📝 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
(defn trace-all-ns
"Iterate over *ns* functions and replace them with themselves within
a `logs/trace` call that uses each function's arglist as context."
[]
(let [desired-ns
(get-allowed-ns)]
(doseq [current-ns desired-ns]
(doseq [[fsym func] (ns-publics current-ns)]
(let [sym (keyword (symbol (str current-ns) (name fsym)))
m (meta func)
args (first (:arglists m))
pre-argmap (fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (:as v))
(acc (keyword (:as v)) (:as v))
;; Arg with only the :keys vec declared.
(and (map? v) (:keys v))
(into {} (map (fn [k]
[(keyword k) k])
(:keys v)))
;; Normal arg types.
:else (assoc acc (keyword v) v)))
argmap (reduce pre-argmap {} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (:as arg))
(:as arg)
(and (map? arg) (:keys arg))
(into {} (map (fn [a] [(keyword a) a]) (:keys arg)))
:else arg))
args)]
(if-not (some #(= % '&) args)
(intern
*ns* fsym
(with-meta (eval `(fn [~@args]
(com.moclojer.components.logs/trace ~sym ~argmap
(~func ~@callargs)))) m))
(logs/log "--> could not convert" func "args:" args)))))))
(defn safe-arg->keyword [arg]
(cond
(nil? arg) nil
(keyword? arg) arg
(symbol? arg) (keyword (name arg))
:else (throw (ex-info "Invalid argument type"
{:arg arg
:type (type arg)}))))
(defn build-arg-map [args]
(reduce
(fn [acc arg]
(cond
(map? arg)
(cond
(:as arg) (assoc acc (safe-arg->keyword (:as arg)) (:as arg))
(:keys arg) (merge acc
(into {}
(map (juxt safe-arg->keyword identity))
(:keys arg)))
:else acc)
:else (assoc acc (safe-arg->keyword arg) arg)))
{}
args))
(defn trace-all-ns []
(doseq [current-ns (get-allowed-ns)
[fsym func] (ns-publics current-ns)
:let [sym (keyword (str current-ns) (name fsym))
m (meta func)]]
(when-let [args (first (:arglists m))]
(when-not (some #{'&} args)
(intern *ns* fsym
(with-meta
(fn [& args]
(logs/trace sym
(build-arg-map args)
(apply func args)))
m))))))

@avelino
Copy link
Member

avelino commented Nov 18, 2024

@J0sueTM como estamos com esse 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: 6

🧹 Outside diff range comments (2)
src/cloud_ops/api/server.clj (2)

Line range hint 23-26: Remove legacy logger setup after migration

The start-system! function still uses the old logging setup via components/setup-logger. This should be removed once the new logger component is properly integrated into the system map.

Apply this change:

 (defn start-system! [system-map]
-  (components/setup-logger [["*" :info]] :auto :prod)
   (->> system-map
        component/start
        (reset! system-atom)))

Line range hint 28-31: Update logging call to use new logger component

The stop-system! function uses the old logging namespace directly. This should be updated to use the new logger component.

Consider updating to use the new logger component:

 (defn stop-system! []
-  (logs/log :info "stopping system")
+  (when-let [logger (:logger @system-atom)]
+    (.info logger "stopping system"))
   (swap!
    system-atom
    (fn [s] (when s (component/stop s)))))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 4cbe07d and 9f67485.

📒 Files selected for processing (8)
  • resources/back/config.edn (1 hunks)
  • src/back/api/adapters/mocks.clj (1 hunks)
  • src/back/api/controllers/mocks.clj (1 hunks)
  • src/back/api/server.clj (1 hunks)
  • src/back/api/utils.clj (1 hunks)
  • src/cloud_ops/api/server.clj (1 hunks)
  • src/dev/api/dev.clj (4 hunks)
  • src/dev/utils.clj (2 hunks)
🔇 Additional comments (16)
src/back/api/utils.clj (1)

Line range hint 3-9: LGTM! Verify usage in mock transformations.

The implementation is clean and follows functional programming principles. The function is pure and its purpose is well-documented.

Let's verify its usage in mock transformations:

✅ Verification successful

Function is correctly used in mock data transformations

The verification confirms that assoc-if is properly used in mock transformations:

  • Used in src/back/api/adapters/mocks.clj which correctly imports it from back.api.utils
  • Applied in the ->wire function to conditionally set :org-id and :content fields
  • Same pattern is used in src/job_ops/adapters/mocks.clj (likely a duplicate that should be consolidated)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of assoc-if in mock-related code
# Expected: Usage in ->wire function for mock transformations

# Search for assoc-if usage in mock-related files
rg -A 5 "assoc-if" --glob "**/mock*.clj"

# Search for ->wire function implementation to verify transformation logic
ast-grep --pattern '(defn ->wire [$$$] $$$)'

Length of output: 993

src/back/api/adapters/mocks.clj (2)

1-3: LGTM! Clean namespace formatting.

The multi-line style improves readability while maintaining the same functionality.


Line range hint 1-15: Verify if logging should be added to this adapter.

Given that this PR's objective is to update logging with Telemere, and this file handles mock data transformation, consider if we should add logging for important operations (e.g., failed transformations, invalid input).

src/dev/api/dev.clj (2)

44-45: Enhance logger usage example with actual logging calls

While the example shows how to access the logger component, it would be more helpful to demonstrate actual logging usage with Telemere.


18-18: LGTM: Logger component integration looks correct

The logger component is properly integrated with a dependency on the config component, which aligns with the PR objective of updating to the new Telemere-based logging system.

Let's verify the logger component configuration:

✅ Verification successful

Logger component integration is consistent across the codebase

The logger component is correctly configured in src/dev/api/dev.clj and matches the same pattern used in other system maps (src/back/api/server.clj and test files). All instances properly use component/using with a dependency on :config.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the logger component is consistently configured across the codebase
ast-grep --pattern 'components/new-logger'

Length of output: 42


Script:

#!/bin/bash
# Let's try a broader search for logger component configuration
rg -l "new-logger|components.*logger" --type clojure

# Also search for any logger-related component definitions
ast-grep --pattern '(defn new-logger'

# Check for any logger component usage in system maps
rg "(:logger|logger:)" --type clojure -B 2 -A 2

Length of output: 1790

src/back/api/server.clj (3)

2-9: LGTM: Clean namespace organization

The new requires for logging components are properly organized and follow Clojure naming conventions.


Line range hint 16-33: Consider explicit Telemere configuration

The system map now includes the logger component, but there's no explicit configuration for Telemere integration mentioned in the PR objectives. Consider adding Telemere-specific configuration in the :config component.


17-17: Verify component dependencies on logger

The logger component is correctly added with config dependency. However, other components might need to declare dependency on the logger to ensure proper initialization order.

resources/back/config.edn (3)

32-32: Review the index naming convention for production use

The index name includes "test" which suggests it's not intended for production use.


28-32: Verify OpenSearch configuration with Telemere integration

Since this PR is about integrating with Telemere for logging, please ensure the OpenSearch configuration aligns with Telemere's requirements.

✅ Verification successful

Let me gather more information about the logging configuration and Telemere usage.


OpenSearch configuration appears correct for Telemere integration

The OpenSearch configuration aligns with Telemere's requirements as evidenced by:

  • The codebase shows active usage of Telemere (taoensso.telemere) for logging across multiple components
  • Extensive trace logging is implemented using the logging framework
  • The OpenSearch configuration provides all necessary connection parameters (host, port, credentials, index) for log aggregation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Look for Telemere configuration or usage patterns
rg -A 5 "telemere|Telemere" --type clojure

# Check for any logging configuration patterns
ast-grep --pattern 'logs/trace $$$'

Length of output: 867


Script:

#!/bin/bash
# Check for Telemere configuration patterns
rg -A 10 "taoensso.telemere" --type clojure

# Look for logging configuration in config files
rg -A 5 "opensearch|logging|telemere" resources/

# Check for any trace or logging function usage
rg -A 3 "logs/trace|logs/info|logs/debug" --type clojure

Length of output: 11573


28-32: 🛠️ Refactor suggestion

Add environment-specific configuration for OpenSearch

Other sections in the file use #profile for environment-specific settings, but the OpenSearch configuration doesn't follow this pattern. Consider aligning with the existing structure:

 :opensearch {:username #or [#env OPENSEARCH_USERNAME "foobar"]
              :password #or [#env OPENSEARCH_PASSWORD "foobar"]
-              :host #or [#env OPENSEARCH_HOST "foobar.com"]
-              :port #or [#env OPENSEARCH_PORT 25060]
+              :host #profile {:dev #or [#env OPENSEARCH_HOST "localhost"]
+                             :prod #or [#env OPENSEARCH_HOST "opensearch.production.com"]}
+              :port #profile {:dev #or [#env OPENSEARCH_PORT 9200]
+                             :prod #or [#env OPENSEARCH_PORT 25060]}
               :index #or [#env OPENSEARCH_INDEX "moclojer-api-test-tracing"]}

Likely invalid or redundant comment.

src/dev/utils.clj (2)

11-13: ⚠️ Potential issue

Fix system startup trace implementation

The call to utils/trace-all-ns will fail due to the circular dependency. Additionally, it's called after the function returns from the 3-arity version, which is incorrect.

Apply this fix:

 (defn start-system-dev!
   ([sys-atom sys-map]
-   (start-system-dev! sys-atom sys-map true)
-   (utils/trace-all-ns))
+   (start-system-dev! sys-atom sys-map true)
+   (trace-all-ns))

Likely invalid or redundant comment.


41-81: 🧹 Nitpick (assertive)

Consider performance implications and simplify argument handling

The tracing implementation has several considerations:

  1. Wrapping all public functions with tracing will impact performance
  2. The argument handling logic is complex and could be simplified
  3. There's no way to disable tracing once enabled

Consider these improvements:

  1. Add a way to selectively enable/disable tracing per namespace
  2. Add a function to restore original implementations
  3. Simplify the argument handling using a helper function

Let's check the impact on the codebase:

Consider splitting the complex argument handling into a separate function:

(defn- prepare-args [args]
  (let [process-arg (fn [arg]
                     (cond
                       (and (map? arg) (:as arg)) (:as arg)
                       (and (map? arg) (:keys arg)) (into {} (map (fn [a] [(keyword a) a]) (:keys arg)))
                       :else arg))]
    (map process-arg args)))
src/back/api/controllers/mocks.clj (3)

2-8: LGTM! Imports are correctly updated for the new logging system.

The namespace declaration properly imports the new logging component as expected.


12-15: Consider adding trace logging for error paths.

While the success path is well logged, adding trace logging before throwing exceptions would improve debugging capabilities.


7-7: Verify complete migration to new logging component.

The migration to the new logging component looks complete in this file. Let's verify the entire codebase.

Also applies to: 12-15, 38-41, 48-51, 71-72, 80-83, 93-95, 110-113, 126-128, 142-145, 156-159

✅ Verification successful

Migration to new logging component is complete

Based on the verification results:

  • All logging imports consistently use [com.moclojer.components.logs :as logs]
  • All logging calls use the new logs/log function with the correct namespace
  • No old or inconsistent logging patterns were found
  • The only other logging-related imports found are for unrelated logic modules (digital-ocean, cloudflare)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify migration to new logging component across the codebase

# Check for any remaining old logging imports
echo "Checking for old logging imports..."
rg -l 'require.*\[(?!com\.moclojer\.components\.logs).*\.log[gs]\]' --type clojure

# Check for consistent usage of new logging namespace alias
echo "Checking for consistent logs alias usage..."
rg -l 'require.*\[com\.moclojer\.components\.logs :as (?!logs\])' --type clojure

# Check for any remaining direct logging calls
echo "Checking for old logging calls..."
rg '\b(?!logs/trace)\w+/(?:log|debug|info|warn|error)\b' --type clojure

Length of output: 1335


Script:

#!/bin/bash
# Description: Verify migration to new logging component across the codebase

# Check for any remaining old logging imports
echo "Checking for old logging imports..."
rg --pcre2 'require.*\[(?!com\.moclojer\.components\.logs).*\.log[gs]\]' --type clojure

# Check for consistent usage of new logging namespace alias
echo "Checking for consistent logs alias usage..."
rg --pcre2 'require.*\[com\.moclojer\.components\.logs :as (?!logs\])' --type clojure

# Check for any remaining direct logging calls
echo "Checking for old logging calls..."
rg --pcre2 '\b(?!logs/trace)\w+/(?:log|debug|info|warn|error)\b' --type clojure

# Also check for any logging-related imports and usages more broadly
echo "Checking for any logging-related imports..."
rg 'require.*log' --type clojure

echo "Checking for any logging function calls..."
rg '\w+/(log|debug|info|warn|error)' --type clojure

Length of output: 12577

[com.moclojer.components.core :as components]
[com.moclojer.components.logs :as logs]
[com.moclojer.components.mq :as mq]
[dev.utils :refer [trace-all-ns]]
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Remove unused trace-all-ns import

The trace-all-ns function from dev.utils is imported but never used in both server files. This development utility is only used in development-specific code paths (as seen in src/dev/utils.clj). Remove this unused import to keep the production code clean.

  • Remove [dev.utils :refer [trace-all-ns]] from src/cloud_ops/api/server.clj
  • Remove [dev.utils :refer [trace-all-ns]] from src/back/api/server.clj
🔗 Analysis chain

Verify the necessity of trace-all-ns in production code

The dev.utils namespace with trace-all-ns appears to be a development utility. Consider:

  1. Moving this import to a development-only configuration
  2. Using conditional compilation #+clj-kondo/ignore if needed for development

Let me check the actual usage of trace-all-ns in the server files to understand if it's actually being used in production code.


Let me check how this utility is used in the actual server initialization to make a final determination.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if dev.utils is used in development files
rg -l "dev\.utils" | grep -i "dev\|test"

# Check for other occurrences of trace-all-ns
rg "trace-all-ns"

Length of output: 465


Script:

#!/bin/bash
# Check the content of server files to see how trace-all-ns is used
ast-grep --pattern 'trace-all-ns'

# Also check the content of dev.utils to understand its purpose
cat src/dev/utils.clj

Length of output: 3084


Script:

#!/bin/bash
# Check the content of both server files to see the context of trace-all-ns import
cat src/cloud_ops/api/server.clj
cat src/back/api/server.clj

Length of output: 3542

Comment on lines +28 to +32
:opensearch {:username #or [#env OPENSEARCH_USERNAME "foobar"]
:password #or [#env OPENSEARCH_PASSWORD "foobar"]
:host #or [#env OPENSEARCH_HOST "foobar.com"]
:port #or [#env OPENSEARCH_PORT 25060]
:index #or [#env OPENSEARCH_INDEX "moclojer-api-test-tracing"]}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Default credentials in configuration require attention

The verification reveals that "foobar" is consistently used as a default value for multiple sensitive configuration settings:

  • Sentry authentication token
  • OpenSearch credentials (username, password, host)
  • Digital Ocean token
  • Cloudflare token

While other occurrences in test files and example code are legitimate test data, having "foobar" as default credentials in the main configuration file is problematic because:

  1. It's used across multiple critical authentication settings
  2. These defaults could accidentally be used in non-development environments
  3. The pattern of using the same value ("foobar") for multiple credentials reduces security

Recommendations:

  • Use different, more secure default values for each credential
  • Add validation to ensure these defaults cannot be used in production
  • Consider using placeholder values like REPLACE_ME that would fail obviously if not configured
  • Add comments indicating these are development-only values
🔗 Analysis chain

Security: Review default credentials for OpenSearch configuration

The default credentials ("foobar") are insecure and could pose a security risk if accidentally used in production. Consider:

  1. Using more secure default values for local development
  2. Adding validation to prevent these defaults in production
  3. Adding comments to indicate these are development-only values
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if these default credentials are used in any other configuration files
rg -l "foobar" --type-add 'config:*.{edn,clj,yml,yaml,json}' -t config

Length of output: 275


Script:

#!/bin/bash
# Let's check the context of "foobar" usage in these files
echo "=== config.edn ==="
rg "foobar" resources/back/config.edn -C 2

echo -e "\n=== yml.clj ==="
rg "foobar" src/yaml_generator/logic/yml.clj -C 2

echo -e "\n=== digital_ocean.clj ==="
rg "foobar" src/cloud_ops/api/logic/digital_ocean.clj -C 2

echo -e "\n=== Test files ==="
rg "foobar" test/back/back/integration/api/*.clj -C 2

Length of output: 3372

Comment on lines 2 to 8
(:require
[clojure.string :as str]
[com.moclojer.components.logs :as logs]
[com.moclojer.components.migrations :as migrations]
[com.stuartsierra.component :as component]
[dev.utils :as utils]
[pg-embedded-clj.core :as pg-emb]))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove circular dependency in namespace declarations

The namespace is requiring itself through [dev.utils :as utils], which creates a circular dependency. This can lead to initialization issues and is generally considered an anti-pattern in Clojure.

Remove the self-reference:

- [dev.utils :as utils]

And update any utils/ calls to use local function references.

📝 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
(:require
[clojure.string :as str]
[com.moclojer.components.logs :as logs]
[com.moclojer.components.migrations :as migrations]
[com.stuartsierra.component :as component]
[dev.utils :as utils]
[pg-embedded-clj.core :as pg-emb]))
(:require
[clojure.string :as str]
[com.moclojer.components.logs :as logs]
[com.moclojer.components.migrations :as migrations]
[com.stuartsierra.component :as component]
[pg-embedded-clj.core :as pg-emb]))

Comment on lines 32 to 39
(defn- get-allowed-ns []
(->> (all-ns)
(map ns-name)
(map name)
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)
(into [])))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add docstring to private function

The get-allowed-ns function would benefit from a docstring explaining its filtering logic and return value.

 (defn- get-allowed-ns []
+  "Returns a vector of symbols representing allowed namespaces.
+   Includes namespaces starting with 'com.moclojer' but excludes those ending with 'logs'
+   to prevent recursive tracing."
   (->> (all-ns)
📝 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
(defn- get-allowed-ns []
(->> (all-ns)
(map ns-name)
(map name)
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)
(into [])))
(defn- get-allowed-ns []
"Returns a vector of symbols representing allowed namespaces.
Includes namespaces starting with 'com.moclojer' but excludes those ending with 'logs'
to prevent recursive tracing."
(->> (all-ns)
(map ns-name)
(map name)
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)
(into [])))

Comment on lines +59 to +60
(when (and (= (:dns-status ->wired-old-mock) "offline")
(:enabled ->wired-old-mock))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using keywords for status values.

Status values like "offline" should be keywords (:offline) for consistency and to prevent string comparison issues. This applies to all status-related operations.

- (= (:dns-status ->wired-old-mock) "offline")
+ (= (:dns-status ->wired-old-mock) :offline)

Also applies to: 142-145, 156-159

Comment on lines +74 to +75
(->> (db.mocks/get-mocks (parse-uuid (str uuid)) database ctx)
(map adapter.mocks/->wire))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding performance logging for database operations.

Database operations and external service calls (like YAML generation) would benefit from performance tracking. Consider wrapping these operations with timing logs.

Example implementation:

(defn with-timing [op-name f]
  (let [start (System/nanoTime)
        result (f)
        duration (/ (- (System/nanoTime) start) 1e6)]
    (logs/trace ::operation-timing
                {:operation op-name
                 :duration_ms duration})
    result))

;; Usage in get-mocks:
(with-timing :fetch-mocks
  #(db.mocks/get-mocks (parse-uuid (str uuid)) database ctx))

Also applies to: 83-88, 96-101, 115-117

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 9f67485 and c0a2b0c.

📒 Files selected for processing (4)
  • src/back/api/server.clj (2 hunks)
  • src/back/api/utils.clj (1 hunks)
  • src/dev/shadow/hooks.clj (1 hunks)
  • src/dev/utils.clj (1 hunks)
🔇 Additional comments (6)
src/back/api/utils.clj (2)

3-9: LGTM!

The function is well-documented and follows Clojure's functional programming principles. The implementation is correct and efficient.


11-17: 🛠️ Refactor suggestion

Consider using Telemere logging component instead of prn

Given that this PR's objective is to update logging to use Telemere, the inspect function should leverage the new logging infrastructure rather than using prn directly. This would provide better consistency, structured logging, and proper log levels.

Additionally:

  1. Consider renaming to spy or using tap> to align with common Clojure debugging patterns
  2. The docstring should explicitly mention the printing side effect

Here's a suggested improvement (assuming Telemere logger is required as log):

-(defn inspect
-  "Inspects a variable's contents and returns it without modifying its value."
+;; Consider using tap> or spy naming
+(defn inspect
+  "Inspects a variable's contents by logging it at debug level and returns
+   the original value without modification."
   [v]
   (if (instance? clojure.lang.Atom v)
-    (prn @v)
-    (prn v))
+    (log/debug "Inspecting atom:" @v)
+    (log/debug "Inspecting value:" v))
   v)

Let's verify the Telemere logger usage in the codebase:

src/dev/utils.clj (3)

8-8: Remove circular dependency in namespace declarations

The namespace is requiring itself through [dev.utils :as utils], which creates a circular dependency and can lead to initialization issues.

Apply this diff to remove the self-reference:

-       [dev.utils :as utils]

Update any utils/ calls to use local function references.


11-18: Add docstring to private function get-allowed-ns

Adding a docstring would enhance code readability and maintainability by explaining the function's purpose and behavior.

Apply this diff to add a docstring:

 (defn get-allowed-ns []
+  "Returns a vector of symbols representing allowed namespaces.
+   Includes namespaces starting with 'com.moclojer' but excludes those ending with 'logs'
+   to prevent recursive tracing."
   (->> (all-ns)

84-85: ⚠️ Potential issue

Fix circular dependency by removing self-reference and updating function call

The call to utils/trace-all-ns is causing a circular dependency due to the namespace requiring itself.

Apply this diff to remove the self-reference and update the function call:

-       (utils/trace-all-ns))
+       (trace-all-ns))

This removes the dependency on utils and calls trace-all-ns directly since it's defined in the same namespace.

Likely invalid or redundant comment.

src/back/api/server.clj (1)

17-17: LGTM!

The :logger component is correctly added to the system map and properly wired with its dependencies.

Comment on lines 20 to 61
(defn trace-all-ns-1
"Iterate over *ns* functions and replace them with themselves within
a `logs/trace` call that uses each function's arglist as context."
[]
(let [desired-ns
(get-allowed-ns)]
(doseq [current-ns desired-ns]
(doseq [[fsym func] (ns-publics current-ns)]
(let [sym (keyword (symbol (str current-ns) (name fsym)))
m (meta func)
args (first (:arglists m))
pre-argmap (fn [acc v]
(cond
;; Arg with a :as alias, making it not necessary to
;; get the inner deconstructed keys.
(and (map? v) (:as v))
(acc (keyword (:as v)) (:as v))
;; Arg with only the :keys vec declared.
(and (map? v) (:keys v))
(into {} (map (fn [k]
[(keyword k) k])
(:keys v)))
;; Normal arg types.
:else (assoc acc (keyword v) v)))
argmap (reduce pre-argmap {} (drop-last 2 args))
callargs (map
(fn [arg]
(cond
(and (map? arg) (:as arg))
(:as arg)
(and (map? arg) (:keys arg))
(into {} (map (fn [a] [(keyword a) a]) (:keys arg)))
:else arg))
args)]
(if-not (some #(= % '&) args)
(intern
*ns* fsym
(with-meta (eval `(fn [~@args]
(com.moclojer.components.logs/trace ~sym ~argmap
(~func ~@callargs)))) m))
(prn "--> could not convert" func "args:" args)))))))

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider removing or documenting the unused function trace-all-ns-1

The function trace-all-ns-1 is defined but not used anywhere in the codebase. Keeping unused code can lead to confusion and increase maintenance overhead.

If this function is not needed, consider removing it to keep the codebase clean. Alternatively, if it's intended for future use, add a comment explaining its purpose and why it's currently unused.

[com.moclojer.components.logs :as logs]
[com.moclojer.components.migrations :as migrations]
[com.stuartsierra.component :as component]
[dev.utils :refer [trace-all-ns]])
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using development utilities in production code

Importing dev.utils in production code can lead to unintended side effects and potential security risks.

Consider removing the reference to dev.utils and ensure that production code does not depend on development-only namespaces.

If tracing is required in production, refactor the necessary functions into a production-appropriate namespace.

Comment on lines 42 to 43
(reset! system-atom))
(trace-all-ns))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove call to trace-all-ns in production code

The trace-all-ns function is intended for development and may impact performance or reveal sensitive information when used in production.

Recommend removing the call to trace-all-ns from the start-system! function.

Apply this diff to remove the call:

      (->> system-map
           component/start
           (reset! system-atom))
-     (trace-all-ns))
📝 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
(reset! system-atom))
(trace-all-ns))
(reset! system-atom))

Comment on lines +61 to +64
(do
(s.util/log {:type ::source-does-not-exist
:source source})
(constantly build-state))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Improve readability by refining the do block formatting

The consolidation of the do block enhances readability by maintaining consistent indentation and grouping related actions.

No changes to functionality are introduced, and the code remains functionally equivalent.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between c0a2b0c and b87e08b.

📒 Files selected for processing (2)
  • src/back/api/utils.clj (1 hunks)
  • src/dev/utils.clj (2 hunks)
🔇 Additional comments (4)
src/back/api/utils.clj (1)

3-9: LGTM! Well-documented utility function

The implementation is correct and the docstring clearly explains its purpose.

src/dev/utils.clj (3)

91-92: Verify the effects of calling trace-all-ns in start-system-dev!

The call to trace-all-ns has been added to start-system-dev!. Ensure that invoking trace-all-ns during system startup does not introduce unintended side effects or performance issues, especially in non-development environments.


10-18: 🧹 Nitpick (assertive)

Add docstring to get-allowed-ns function

The function get-allowed-ns lacks a docstring explaining its purpose and behavior. Adding a docstring will improve code readability and maintainability.


19-60: 🧹 Nitpick (assertive)

Consider removing or documenting the unused trace-all-ns-1 function

The trace-all-ns-1 function is defined but not used anywhere in the codebase. Unused code can lead to confusion and increase maintenance overhead.

If this function is intended for future use, consider adding a comment explaining its purpose. Otherwise, consider removing it to keep the codebase clean.

src/back/api/utils.clj Outdated Show resolved Hide resolved
Comment on lines 11 to 23
(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(if (instance? clojure.lang.Atom v)
(prn "Deref atom: " @v)
(prn v))
(if a
(let [c (count a)]
(dotimes [i c]
(if (instance? clojure.lang.Atom a)
(prn (nth @a i))
(prn (nth a i)))))
v))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical issues in the inspect function implementation

Several issues need to be addressed:

  1. Bug: Line 20 incorrectly checks if a (the sequence) is an atom, instead of checking individual elements
  2. The function's docstring should clarify the return value behavior
  3. Consider using the new Telemere logging system instead of prn for consistency with PR objectives

Here's the suggested fix:

 (defn inspect
-  "Inspects a variable's contents and returns it without modifying its value."
+  "Inspects a variable's contents and any additional arguments, printing them to the log.
+   Returns the inspected value v. For atoms, prints and returns the dereferenced value."
   [v & a]
-  (if (instance? clojure.lang.Atom v)
-    (prn "Deref atom: " @v)
-    (prn v))
-  (if a
-    (let [c (count a)]
-      (dotimes [i c]
-        (if (instance? clojure.lang.Atom a)
-          (prn (nth @a i))
-          (prn (nth a i)))))
-    v))
+  (let [log-value (if (instance? clojure.lang.Atom v) @v v)]
+    (logs/trace "Inspect value:" log-value)
+    (when a
+      (doseq [arg a]
+        (logs/trace "Additional arg:"
+          (if (instance? clojure.lang.Atom arg) @arg arg))))
+    log-value))
📝 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
(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(if (instance? clojure.lang.Atom v)
(prn "Deref atom: " @v)
(prn v))
(if a
(let [c (count a)]
(dotimes [i c]
(if (instance? clojure.lang.Atom a)
(prn (nth @a i))
(prn (nth a i)))))
v))
(defn inspect
"Inspects a variable's contents and any additional arguments, printing them to the log.
Returns the inspected value v. For atoms, prints and returns the dereferenced value."
[v & a]
(let [log-value (if (instance? clojure.lang.Atom v) @v v)]
(logs/trace "Inspect value:" log-value)
(when a
(doseq [arg a]
(logs/trace "Additional arg:"
(if (instance? clojure.lang.Atom arg) @arg arg))))
log-value))

Comment on lines 1 to 29
(ns back.api.utils)

(defn assoc-if
(defn assoc-if
"This function returns a map with a respective associated key and value
if it is given as argument."
[m k v]
(if v
(assoc m k v)
m))

(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(if (instance? clojure.lang.Atom v)
(prn "Deref atom: " @v)
(prn v))
(if a
(let [c (count a)]
(dotimes [i c]
(if (instance? clojure.lang.Atom a)
(prn (nth @a i))
(prn (nth a i)))))
v))

(defn inspect-if
"Inspects if condition is met"
[c v & a]
(when c
(inspect v (when a a))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

💡 Codebase verification

Debugging utilities should use structured logging via com.moclojer.components.logs

The codebase consistently uses structured logging through com.moclojer.components.logs with logs/trace for detailed debugging. The current implementation using prn should be updated to:

  1. Add the required import:
[com.moclojer.components.logs :as logs]
  1. Replace direct prn calls with structured logging:
  • In inspect: Use logs/trace ::inspect with structured data
  • In inspect-if: Use logs/trace ::inspect-if with structured data

This aligns with the established logging patterns seen across the codebase, particularly in controllers and DB layers.

🔗 Analysis chain

Verify integration with Telemere logging system

While these utility functions are helpful for debugging, they should be integrated with the new Telemere logging system mentioned in the PR objectives, rather than using prn directly.

Let's check how Telemere logging is used in other files:

Consider creating a dedicated logging namespace that wraps Telemere functionality and using it consistently across these utility functions.


Let's examine how Telemere logging is actually used in these files to understand the correct pattern.


Let's check the required imports and logging setup to understand the complete pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Telemere logging patterns to understand the correct usage
rg -l "telemere|logs/trace|logs/log" --type clojure

Length of output: 717


Script:

#!/bin/bash
# Look for actual Telemere logging usage patterns in a few key files
rg "telemere|logs/trace|logs/log" --type clojure -A 2 src/back/api/

Length of output: 6982


Script:

#!/bin/bash
# Check the logging setup and imports in a few example files
rg "^\s*\[.*logs.*\]|^\s*\[.*telemere.*\]" --type clojure -A 2 src/back/api/

Length of output: 1645

src/dev/utils.clj 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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between b87e08b and b96a371.

📒 Files selected for processing (2)
  • src/back/api/utils.clj (1 hunks)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (2)
src/back/api/utils.clj (2)

1-4: LGTM: Namespace declaration aligns with PR objectives

The addition of com.moclojer.components.logs import supports the transition to the new logging system.


29-33: 🧹 Nitpick (assertive)

Enhance function documentation

The docstring should be more descriptive about parameters and return value.

 (defn inspect-if
-  "Inspects if condition is met"
+  "Conditionally inspects a value and optional arguments.
+   
+   Parameters:
+     c - condition to evaluate
+     v - value to inspect if condition is true
+     a - optional sequence of additional values to inspect
+   
+   Returns:
+     The result of inspect(v, a) if c is true, nil otherwise."
   [c v & a]
   (when c
     (apply inspect v a)))

Likely invalid or redundant comment.

Comment on lines +13 to +27
(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(let [v (if (instance? clojure.lang.Atom v) @v v)]
(if (and (seq? v) (> (count v) 0))
(doseq [val v]
(logs/log :info val))
(logs/log :info "Inspect value: " v))
(when a
(doseq [arg a]
(logs/log :info "Additional arg:"
(if (instance? clojure.lang.Atom arg)
@arg
arg))))
v))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use trace level logging for consistency

The function should use logs/trace instead of logs/log :info to align with the PR objectives and maintain consistency with other files.

 (defn inspect
   "Inspects a variable's contents and returns it without modifying its value."
   [v & a]
   (let [v (if (instance? clojure.lang.Atom v) @v v)]
     (if (and (seq? v) (> (count v) 0))
       (doseq [val v]
-        (logs/log :info val))
+        (logs/trace ::inspect val))
-      (logs/log :info "Inspect value: " v))
+      (logs/trace ::inspect {:value v}))
     (when a
       (doseq [arg a]
-        (logs/log :info "Additional arg:"
-                  (if (instance? clojure.lang.Atom arg)
-                    @arg
-                    arg))))
+        (logs/trace ::inspect-arg
+          {:arg (if (instance? clojure.lang.Atom arg) @arg arg)})))
     v))
📝 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
(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(let [v (if (instance? clojure.lang.Atom v) @v v)]
(if (and (seq? v) (> (count v) 0))
(doseq [val v]
(logs/log :info val))
(logs/log :info "Inspect value: " v))
(when a
(doseq [arg a]
(logs/log :info "Additional arg:"
(if (instance? clojure.lang.Atom arg)
@arg
arg))))
v))
(defn inspect
"Inspects a variable's contents and returns it without modifying its value."
[v & a]
(let [v (if (instance? clojure.lang.Atom v) @v v)]
(if (and (seq? v) (> (count v) 0))
(doseq [val v]
(logs/trace ::inspect val))
(logs/trace ::inspect {:value v}))
(when a
(doseq [arg a]
(logs/trace ::inspect-arg
{:arg (if (instance? clojure.lang.Atom arg) @arg arg)})))
v))

Comment on lines 10 to 17
(defn get-allowed-ns []
(->> (all-ns)
(map ns-name)
(map name)
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)
(into [])))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Optimize namespace filtering performance

The current implementation creates multiple intermediate sequences. Consider using transducers for better performance.

 (defn- get-allowed-ns []
   (->> (all-ns)
-       (map ns-name)
-       (map name)
-       (filter #(and (str/starts-with? % "com.moclojer")
-                     (not (str/ends-with? % "logs"))))
-       (map symbol)
-       (into []))
+       (into []
+         (comp
+           (map (comp name ns-name))
+           (filter #(and (str/starts-with? % "com.moclojer")
+                        (not (str/ends-with? % "logs"))))
+           (map symbol))))
📝 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
(defn get-allowed-ns []
(->> (all-ns)
(map ns-name)
(map name)
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)
(into [])))
(defn get-allowed-ns []
(->> (all-ns)
(into []
(comp
(map (comp name ns-name))
(filter #(and (str/starts-with? % "com.moclojer")
(not (str/ends-with? % "logs"))))
(map symbol)))))

Comment on lines 45 to 46
(start-system-dev! sys-atom sys-map true)
(trace-all-ns @sys-atom))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Add error handling for trace-all-ns call

The trace-all-ns call should be wrapped in error handling to prevent system startup failures.

   ([sys-atom sys-map]
    (start-system-dev! sys-atom sys-map true)
-   (trace-all-ns @sys-atom))
+   (try
+     (trace-all-ns @sys-atom)
+     (catch Exception e
+       (logs/error ::trace-setup-failed {:error e}))))

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 19 to 41
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :dev}}))
([config]
(let [env (get-in config [:config :env])
a-ns (get-allowed-ns)
fn-names (atom [])]
(doseq [curr-ns a-ns]
(doseq [[sym v] (ns-interns curr-ns)]
(let [arglists (or (:arglists (meta v)) [])
arg-names (map keyword (or (first arglists) []))]
(swap! fn-names conj (str sym))
(alter-var-root v
(fn [orig-fn]
(if (fn? orig-fn)
(with-meta
(fn [& args]
(let [arg-map (zipmap arg-names args)
result (apply orig-fn args)]
(com.moclojer.components.logs/trace sym arg-map result)
(utils/inspect-if (= env :dev) result)))
(meta v))
orig-fn)))))))))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Multiple improvements needed for trace-all-ns function

  1. The function currently traces private functions via ns-interns. Consider using ns-publics instead to respect function visibility.
  2. The environment check on line 39 appears reversed based on the project's requirements.
 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
   ([config]
    (let [env (get-in config [:config :env])
          a-ns (get-allowed-ns)
          fn-names (atom [])]
      (doseq [curr-ns a-ns]
-       (doseq [[sym v] (ns-interns curr-ns)]
+       (doseq [[sym v] (ns-publics curr-ns)]
          (let [arglists (or (:arglists (meta v)) [])
                arg-names (map keyword (or (first arglists) []))]
            (swap! fn-names conj (str sym))
            (alter-var-root v
              (fn [orig-fn]
                (if (fn? orig-fn)
                  (with-meta
                    (fn [& args]
                      (let [arg-map (zipmap arg-names args)
                            result (apply orig-fn args)]
                        (com.moclojer.components.logs/trace sym arg-map result)
-                        (utils/inspect-if (= env :dev) result)))
+                        (utils/inspect-if (not= env :dev) result)))
                    (meta v))
                  orig-fn)))))))))
📝 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
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :dev}}))
([config]
(let [env (get-in config [:config :env])
a-ns (get-allowed-ns)
fn-names (atom [])]
(doseq [curr-ns a-ns]
(doseq [[sym v] (ns-interns curr-ns)]
(let [arglists (or (:arglists (meta v)) [])
arg-names (map keyword (or (first arglists) []))]
(swap! fn-names conj (str sym))
(alter-var-root v
(fn [orig-fn]
(if (fn? orig-fn)
(with-meta
(fn [& args]
(let [arg-map (zipmap arg-names args)
result (apply orig-fn args)]
(com.moclojer.components.logs/trace sym arg-map result)
(utils/inspect-if (= env :dev) result)))
(meta v))
orig-fn)))))))))
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :prod}}))
([config]
(let [env (get-in config [:config :env])
a-ns (get-allowed-ns)
fn-names (atom [])]
(doseq [curr-ns a-ns]
(doseq [[sym v] (ns-publics curr-ns)]
(let [arglists (or (:arglists (meta v)) [])
arg-names (map keyword (or (first arglists) []))]
(swap! fn-names conj (str sym))
(alter-var-root v
(fn [orig-fn]
(if (fn? orig-fn)
(with-meta
(fn [& args]
(let [arg-map (zipmap arg-names args)
result (apply orig-fn args)]
(com.moclojer.components.logs/trace sym arg-map result)
(utils/inspect-if (not= env :dev) result)))
(meta v))
orig-fn)))))))))

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between b96a371 and 472a14c.

📒 Files selected for processing (1)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (3)
src/dev/utils.clj (3)

26-39: ⚠️ Potential issue

Protect private functions and add error handling

Several improvements needed for the tracing implementation:

  1. Use ns-publics instead of ns-interns to respect function privacy
  2. Add error handling for tracing operations
     (doseq [curr-ns a-ns]
-      (doseq [[sym v] (ns-interns curr-ns)]
+      (doseq [[sym v] (ns-publics curr-ns)]
         (try
           (let [arglists (or (:arglists (meta v)) [])
                 arg-names (map keyword (or (first arglists) []))]
             (swap! fn-names conj (str sym))
             (alter-var-root v
               (fn [orig-fn]
                 (if (fn? orig-fn)
                   (with-meta
                     (fn [& args]
                       (com.moclojer.components.logs/trace
                        sym (zipmap arg-names args) (apply orig-fn args)))
                     (meta v))
                   orig-fn))))
+          (catch Exception e
+            (logs/error ::trace-setup-failed
+              {:namespace curr-ns
+               :symbol sym
+               :error e}))))

Likely invalid or redundant comment.


44-45: ⚠️ Potential issue

Add error handling for system tracing

Protect system startup from tracing failures.

   (start-system-dev! sys-atom sys-map true)
-  (trace-all-ns @sys-atom))
+  (try
+    (trace-all-ns @sys-atom)
+    (catch Exception e
+      (logs/error ::system-trace-failed {:error e})
+      ;; Continue with system startup even if tracing fails
+      @sys-atom)))

Likely invalid or redundant comment.


10-17: 🧹 Nitpick (assertive)

Add docstring to explain namespace filtering logic

The get-allowed-ns function would benefit from a docstring explaining its purpose and filtering criteria.

 (defn get-allowed-ns []
+  "Returns a vector of namespace symbols that should be traced.
+   Includes namespaces starting with 'com.moclojer' while excluding
+   those ending with 'logs' to prevent recursive tracing.
+   Uses transducers for efficient filtering."
   (->> (all-ns)

Likely invalid or redundant comment.

Comment on lines 39 to 40
orig-fn))))))
(utils/inspect-if (= env :dev) fn-names))))
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reverse environment check for inspection

The inspection should follow the same environment logic as tracing.

-     (utils/inspect-if (= env :dev) fn-names))))
+     (utils/inspect-if (not= env :dev) fn-names))))
📝 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
orig-fn))))))
(utils/inspect-if (= env :dev) fn-names))))
orig-fn))))))
(utils/inspect-if (not= env :dev) fn-names))))

Comment on lines 64 to 67
(comment
(trace-all-ns)

(trace-all-ns {:config {:env :prod}}))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance example documentation

Add more context to the example usage to clarify when each approach should be used.

 (comment
+  ;; Default usage (not recommended for production)
   (trace-all-ns)
 
+  ;; Recommended usage for production environments
   (trace-all-ns {:config {:env :prod}}))
📝 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
(comment
(trace-all-ns)
(trace-all-ns {:config {:env :prod}}))
(comment
;; Default usage (not recommended for production)
(trace-all-ns)
;; Recommended usage for production environments
(trace-all-ns {:config {:env :prod}}))

Comment on lines 19 to 22
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :dev}}))
([config]
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reverse default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
📝 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
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :dev}}))
([config]
(defn trace-all-ns
([]
(trace-all-ns {:config {:env :prod}}))
([config]

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 UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between bb79a52 and cd7abc4.

📒 Files selected for processing (1)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (6)
src/dev/utils.clj (6)

2-8: LGTM: Clean namespace declarations

The circular dependency issue has been resolved and the imports are properly organized.


19-22: ⚠️ Potential issue

Reverse default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))

53-54: ⚠️ Potential issue

Add error handling for trace-all-ns call

The trace-all-ns call should be wrapped in error handling to prevent system startup failures.

   (start-system-dev! sys-atom sys-map true)
-   (trace-all-ns @sys-atom))
+   (try
+     (trace-all-ns @sys-atom)
+     (catch Exception e
+       (logs/error ::trace-setup-failed {:error e}))))

73-91: 🧹 Nitpick (assertive)

Enhance example documentation

The examples would be more helpful with additional context explaining their purpose and expected usage scenarios.

 (comment
+  ;; Basic usage - not recommended for production
   (trace-all-ns)
 
+  ;; Recommended usage for production environments
   (trace-all-ns {:config {:env :prod}})
 
+  ;; Example of manual tracing - useful for understanding the tracing format
   (let [args []]

10-17: 🧹 Nitpick (assertive)

Add documentation for get-allowed-ns function

The function implementation looks good with efficient use of transducers, but it would benefit from a docstring explaining its purpose and return value.

 (defn get-allowed-ns []
+  "Returns a vector of namespace symbols that start with 'com.moclojer' but exclude those ending with 'logs'.
+   Used to determine which namespaces should have tracing enabled."
   (->> (all-ns)

Likely invalid or redundant comment.


27-28: 🧹 Nitpick (assertive)

Consider using ns-publics instead of ns-interns

Using ns-interns exposes private functions for tracing. Consider using ns-publics to respect function visibility unless there's a specific requirement to trace private functions.

-      (doseq [[sym v] (ns-interns curr-ns)]
-        (when (and (var? v) (fn? @v))
+      (doseq [[sym v] (ns-publics curr-ns)]
+        (when (fn? @v)

Likely invalid or redundant comment.

Comment on lines +47 to +49
(catch Exception e
(println "Failed to trace" sym (.getMessage e))))))))
(utils/inspect-if (= env :dev) @fn-names))))
Copy link

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 and logging

The current error handling only prints to stdout. Consider using the logging system for consistency.

               (catch Exception e
-                (println "Failed to trace" sym (.getMessage e))))))))
+                (logs/error ::trace-failed
+                           {:namespace (str curr-ns)
+                            :function (str sym)
+                            :error (.getMessage e)})))))))
📝 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
(catch Exception e
(println "Failed to trace" sym (.getMessage e))))))))
(utils/inspect-if (= env :dev) @fn-names))))
(catch Exception e
(logs/error ::trace-failed
{:namespace (str curr-ns)
:function (str sym)
:error (.getMessage e)})))))))
(utils/inspect-if (= env :dev) @fn-names))))

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 UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between cd7abc4 and 1b19159.

📒 Files selected for processing (1)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (7)
src/dev/utils.clj (7)

2-8: LGTM! Circular dependency resolved

The namespace declarations have been cleaned up, removing the circular dependency previously identified. The current imports are appropriate for the functionality.


54-55: 🛠️ Refactor suggestion

Add error handling for tracing setup

Tracing failures shouldn't impact system startup. Wrap the trace-all-ns call in error handling.

   (start-system-dev! sys-atom sys-map true)
-   (trace-all-ns @sys-atom))
+   (try
+     (trace-all-ns @sys-atom)
+     (catch Exception e
+       (logs/error ::trace-setup-failed {:error e}))))

Likely invalid or redundant comment.


50-50: ⚠️ Potential issue

Reverse inspection condition

The inspection condition should match the tracing environment logic.

-     (utils/inspect-if (= env :dev) @fn-names))))
+     (utils/inspect-if (not= env :dev) @fn-names))))

Likely invalid or redundant comment.


74-92: 🧹 Nitpick (assertive)

Enhance example documentation

The examples would benefit from better documentation explaining their purpose and expected output.

 (comment
+  ;; Basic usage - enables tracing with default configuration (not recommended for production)
   (trace-all-ns)
 
+  ;; Recommended usage - explicitly enable tracing for production environment
   (trace-all-ns {:config {:env :prod}})
 
+  ;; Example of manual tracing (for testing/development purposes only)
   (let [args []]
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

46-49: 🛠️ Refactor suggestion

Improve error handling with proper logging

Replace println with proper logging for error cases.

             (try
               (alter-var-root v traced-fn)
               (catch Exception e
-                (println "Failed to trace" sym (.getMessage e))))))))
+                (logs/error ::trace-failed
+                           {:namespace (str curr-ns)
+                            :function (str sym)
+                            :error (.getMessage e)})))))))

Likely invalid or redundant comment.


10-17: 🧹 Nitpick (assertive)

Add docstring to explain namespace filtering logic

While the implementation is efficient using transducers, a docstring would help explain the function's purpose and filtering criteria.

 (defn- get-allowed-ns []
+  "Returns a vector of namespace symbols that start with 'com.moclojer' but exclude those ending with 'logs'.
+   Used to determine which namespaces should have tracing enabled."
   (->> (all-ns)

Likely invalid or redundant comment.


19-22: ⚠️ Potential issue

Reverse default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

Comment on lines 27 to 44
(doseq [[sym v] (ns-interns curr-ns)]
(when (and (var? v) (fn? @v))
(let [arglists (-> v meta :arglists first)
arg-names (map keyword (or arglists []))
solved-fn (str curr-ns "/" sym)
traced-fn (fn [f]
(with-meta
(fn [& args]
(com.moclojer.components.logs/trace
::traced-fn
{:ns (str curr-ns)
:fn (str sym)
:args (zipmap arg-names args)}
::traced-fn
(if (> (count args) 0)
(f args)
(f))))
(meta f)))]
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix argument handling in traced function

The current implementation has several issues:

  1. Using ns-interns exposes private functions - consider using ns-publics instead
  2. Argument handling in the traced function is incorrect
-      (doseq [[sym v] (ns-interns curr-ns)]
+      (doseq [[sym v] (ns-publics curr-ns)]
         (when (and (var? v) (fn? @v))
           (let [arglists (-> v meta :arglists first)
                 arg-names (map keyword (or arglists []))
                 solved-fn (str curr-ns "/" sym)
                 traced-fn (fn [f]
                             (with-meta
                               (fn [& args]
                                 (com.moclojer.components.logs/trace
                                  ::traced-fn
                                  {:ns (str curr-ns)
                                   :fn (str sym)
                                   :args (zipmap arg-names args)}
                                  ::traced-fn
-                                  (if (> (count args) 0)
-                                    (f args)
-                                    (f))))
+                                  (apply f args)))
                               (meta f)))]
📝 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
(doseq [[sym v] (ns-interns curr-ns)]
(when (and (var? v) (fn? @v))
(let [arglists (-> v meta :arglists first)
arg-names (map keyword (or arglists []))
solved-fn (str curr-ns "/" sym)
traced-fn (fn [f]
(with-meta
(fn [& args]
(com.moclojer.components.logs/trace
::traced-fn
{:ns (str curr-ns)
:fn (str sym)
:args (zipmap arg-names args)}
::traced-fn
(if (> (count args) 0)
(f args)
(f))))
(meta f)))]
(doseq [[sym v] (ns-publics curr-ns)]
(when (and (var? v) (fn? @v))
(let [arglists (-> v meta :arglists first)
arg-names (map keyword (or arglists []))
solved-fn (str curr-ns "/" sym)
traced-fn (fn [f]
(with-meta
(fn [& args]
(com.moclojer.components.logs/trace
::traced-fn
{:ns (str curr-ns)
:fn (str sym)
:args (zipmap arg-names args)}
::traced-fn
(apply f args)))
(meta f)))]

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 UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 1b19159 and 7f477b1.

📒 Files selected for processing (2)
  • src/dev/api/dev.clj (4 hunks)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (8)
src/dev/api/dev.clj (1)

18-18: LGTM: Logger component integration

The logger component is correctly integrated into the system map with proper dependency on the config component.

src/dev/utils.clj (7)

10-17: LGTM: Namespace filtering implementation

The get-allowed-ns function correctly filters namespaces and uses transducers for better performance.


54-55: Verify logger initialization before tracing

Ensure the logger component is properly initialized before attempting to trace.

✅ Verification successful

Based on the search results, I can see that the logger initialization is properly handled in the system startup process. The key findings are:

  1. The logger component is properly initialized as part of the system components:
:logger (component/using (components/new-logger) [:config])
  1. The logger is started before tracing in the system startup sequence:
(defn start-system! [system-map]
  (->> system-map
       component/start
       (reset! system-atom))
  (trace-all-ns))
  1. The logger is a dependency for other components and is initialized early in the component lifecycle.

Logger initialization is properly handled before tracing

The logger component is properly initialized as part of the system startup sequence before any tracing occurs. The component system ensures proper dependency ordering, and the logger is started before trace-all-ns is called.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if logger initialization is handled properly
# Look for error handling around logger initialization
rg -A 5 "new-logger|start-system"

Length of output: 30336


43-43: ⚠️ Potential issue

Fix environment check for inspection

The inspection should follow the same environment logic as tracing.

-     (utils/inspect-if (= env :dev) @fn-names))))
+     (utils/inspect-if (not= env :dev) @fn-names))))

Likely invalid or redundant comment.


39-42: 🛠️ Refactor suggestion

Enhance error handling with proper logging

Replace println with proper logging for consistency and better error tracking.

               (catch Exception e
-                (println "Failed to trace" sym (.getMessage e))))))))
+                (logs/error ::trace-failed
+                           {:namespace (str curr-ns)
+                            :function (str sym)
+                            :error (.getMessage e)})))))))

Likely invalid or redundant comment.


19-22: ⚠️ Potential issue

Fix default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

27-37: ⚠️ Potential issue

Multiple improvements needed for function tracing

  1. Using ns-interns exposes private functions
  2. Argument handling in the traced function is incorrect
-      (doseq [[sym v] (ns-interns curr-ns)]
+      (doseq [[sym v] (ns-publics curr-ns)]
         (when (and (var? v) (fn? @v))
           (let [arglists (-> v meta :arglists first)
                 arg-names (map keyword (or arglists []))
                 solved-fn (str curr-ns "/" sym)
                 traced-fn (fn [f]
-                            (fn [n]
+                            (fn [& args]
                               (com.moclojer.components.logs/trace
                                ::traced-fn
-                               (zipmap arg-names n)
-                               (f n))))]
+                               (zipmap arg-names args)
+                               (apply f args))))]

Likely invalid or redundant comment.


67-81: 🧹 Nitpick (assertive)

Enhance example documentation

Add more context to the example usage to clarify when each approach should be used.

 (comment
+  ;; Default usage (for production environments)
   (trace-all-ns)
 
+  ;; Explicit production configuration
   (trace-all-ns {:config {:env :prod}})
 
+  ;; Example of manual tracing (for debugging)
   (let [args []]
     (com.moclojer.components.logs/trace
      ::traced-fn
      {:test? :test}
      (trace-all-ns args)))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

Comment on lines 44 to 46
(component/start
(:logger @sys-atom))

Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider adding comprehensive logger usage examples

While the basic logger initialization is shown, it would be helpful to include examples demonstrating the new Telemere logging capabilities.

;; Example logger usage with Telemere
(let [logger (:logger @sys-atom)]
  ;; Log with different levels
  (com.moclojer.components.logs/trace ::example {:data "test"} (+ 1 2))
  (com.moclojer.components.logs/debug ::example {:message "debugging"})
  (com.moclojer.components.logs/info ::example {:status "running"}))

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 7f477b1 and 0d0184a.

📒 Files selected for processing (5)
  • src/back/api/server.clj (1 hunks)
  • src/dev/api/dev.clj (4 hunks)
  • src/dev/utils.clj (2 hunks)
  • src/job_ops/server.clj (1 hunks)
  • test/back/back/integration/components/utils.clj (0 hunks)
💤 Files with no reviewable changes (1)
  • test/back/back/integration/components/utils.clj
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (12)
src/dev/api/dev.clj (1)

45-47: 🧹 Nitpick (assertive)

Consider adding comprehensive logger usage examples

While accessing the logger component is shown, it would be helpful to include example usage of common logging functions for development purposes.

src/back/api/server.clj (3)

17-17: LGTM: Logger component integration

The logger component is properly integrated with the correct dependency on the config component.


9-9: ⚠️ Potential issue

Remove development utilities from production code

Importing dev.utils in production code can lead to unintended side effects and potential security risks.


42-43: ⚠️ Potential issue

Remove tracing from production startup

Using trace-all-ns in production could impact performance and potentially expose sensitive information.

src/dev/utils.clj (8)

2-8: LGTM! Dependencies look appropriate

The namespace declarations are clean and include all necessary dependencies for the tracing functionality.


10-17: Add docstring to explain namespace filtering logic

The function would benefit from a docstring explaining its purpose and filtering criteria.

 (defn get-allowed-ns []
+  "Returns a vector of namespace symbols that should be traced.
+   Includes namespaces starting with 'com.moclojer' but excludes those ending with 'logs'
+   to prevent recursive tracing."
   (->> (all-ns)

39-41: Improve error handling using logging system

Replace println with proper logging for consistency and better error tracking.

               (catch Exception e
-                (println "Failed to trace" sym (.getMessage e))))))))
+                (logs/error ::trace-failed
+                           {:namespace (str curr-ns)
+                            :function (str sym)
+                            :error (.getMessage e)})))))))

52-53: Add error handling for trace-all-ns call

Protect system startup from tracing failures.

        (reset! sys-atom))
-   (trace-all-ns @sys-atom)))
+   (try
+     (trace-all-ns @sys-atom)
+     (catch Exception e
+       (logs/error ::trace-setup-failed {:error e})))))

65-79: Enhance example documentation

Add more context to clarify when each approach should be used.

 (comment
+  ;; Default usage (not recommended for production)
   (trace-all-ns)
 
+  ;; Recommended usage for production environments
   (trace-all-ns {:config {:env :prod}})
 
+  ;; Example of manual tracing (for testing purposes)
   (let [args []]
     (logs/trace

41-41: ⚠️ Potential issue

Reverse environment check for inspection

The inspection should follow the same environment logic as tracing.

-     (utils/inspect-if (= env :dev) @fn-names))))
+     (utils/inspect-if (not= env :dev) @fn-names))))

Likely invalid or redundant comment.


19-22: ⚠️ Potential issue

Fix default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

26-28: ⚠️ Potential issue

Use ns-publics instead of ns-interns

Using ns-interns exposes private functions for tracing, which violates encapsulation. Switch to ns-publics to respect function visibility.

     (doseq [curr-ns a-ns]
-      (doseq [[sym v] (ns-interns curr-ns)]
+      (doseq [[sym v] (ns-publics curr-ns)]

Likely invalid or redundant comment.

@@ -16,7 +16,7 @@
[:config :sentry])))

(defn start-system! [system-map]
(components/setup-logger [["*" :info]] :auto :prod)
#_(components/setup-logger [["*" :info]] :auto :prod)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Logger setup is commented out without replacement

The logger setup is commented out but no alternative logging configuration is provided. This could lead to missing logs in production.

Consider adding the new logger component similar to other server files:

(defn build-system-map []
  (component/system-map
   :config (components/new-config "back/config.edn")
+  :logger (component/using (components/new-logger) [:config])
   :sentry (component/using (components/new-sentry) [:config])
   :mq (component/using
        (components/new-mq workers false)
        [:config :sentry])))

Committable suggestion skipped: line range outside the PR's diff.

@@ -13,7 +14,9 @@

(defn build-system-map []
(component/system-map
:env :prod
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Reconsider using :prod environment in development namespace

Setting :env :prod in a development-only namespace could lead to confusion and potential issues. Consider using :dev for development environments.

- :env :prod
+ :env :dev
📝 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
:env :prod
:env :dev

Comment on lines +25 to +32
[{:channel "domains.verification.fired"
:event {}
;; every 2 minutes
:sleep 120000}
{:channel "yml.unified.verification.fired"
:event {}
;; every 5 minutes
:sleep 300000}]
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Document MQ channel configuration

Consider adding documentation for the MQ channels explaining their purpose and the rationale behind the sleep intervals.

Add comments explaining:

  • Purpose of each verification channel
  • Impact of sleep intervals on system behavior
  • Any dependencies or prerequisites

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 UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 0d0184a and 525ec40.

📒 Files selected for processing (2)
  • src/back/api/logic/mocks.clj (1 hunks)
  • src/dev/utils.clj (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/dev/utils.clj (1)
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).
🔇 Additional comments (8)
src/back/api/logic/mocks.clj (1)

Line range hint 1-147: Verify logging implementation in dependent controllers.

Since this file contains core business logic, ensure that the controllers using these functions (particularly update, enable/disable, and status update functions) have been updated to use the new Telemere logging as per PR objectives.

Let's verify the logging implementation in the controllers:

✅ Verification successful

Let me check the specific logging implementation in the mocks controller to verify if it properly logs these critical operations.


Let me check the complete mocks controller file to see the logging context around these operations.


Proper Telemere logging is implemented in the controllers

The controllers are correctly using the new Telemere logging system through com.moclojer.components.logs for all critical mock operations:

  • All functions using logic.mocks operations have corresponding logs/trace calls
  • Each log entry includes:
    • Proper namespace-qualified event names (e.g. ::update-mock!)
    • Relevant context data (mock IDs, user IDs, status changes)
    • Logging before the actual operations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if controllers using these mock functions have proper logging.

# Search for usage of mock logic functions in controllers
echo "Checking for mock function usage and logging patterns in controllers:"
rg -A 3 "logic\.mocks/(update|enable|disable|publish|unpublish|update-dns-status|update-unification-status)" "src/back/api/controllers/"

# Search for new logging pattern
echo -e "\nVerifying Telemere logging implementation:"
rg "logs/(trace|debug|info|warn|error)" "src/back/api/controllers/"

Length of output: 3160


Script:

#!/bin/bash
# Check the specific logging implementation around mock operations
echo "Checking logging implementation around mock operations:"
rg -B 2 -A 4 "logic\.mocks/(update|enable|disable|publish|unpublish|update-dns-status|update-unification-status)" "src/back/api/controllers/mocks.clj" --context-separator="---"

Length of output: 1667


Script:

#!/bin/bash
# Get the complete mocks controller implementation
echo "Checking complete mocks controller implementation:"
cat "src/back/api/controllers/mocks.clj"

Length of output: 6079

src/dev/utils.clj (7)

2-8: LGTM: Namespace declarations are appropriate

The namespace declarations properly include all required dependencies for the tracing functionality.


46-46: ⚠️ Potential issue

Reverse environment check for inspection

The inspection should follow the same logic as tracing (active in non-dev environments).

-     (utils/inspect-if (= env :dev) @fn-names))))
+     (utils/inspect-if (not= env :dev) @fn-names))))

Likely invalid or redundant comment.


19-22: ⚠️ Potential issue

Fix default environment for tracing

Based on the project requirements, tracing should primarily occur in non-dev environments.

 (defn trace-all-ns
   ([]
-   (trace-all-ns {:config {:env :dev}}))
+   (trace-all-ns {:config {:env :prod}}))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

57-58: 🛠️ Refactor suggestion

Add error handling for trace-all-ns call

Protect system startup from tracing failures.

        (reset! sys-atom))
-   (trace-all-ns @sys-atom)))
+   (try
+     (trace-all-ns @sys-atom)
+     (catch Exception e
+       (logs/error ::trace-setup-failed {:error e})
+       @sys-atom))))

Likely invalid or redundant comment.


70-85: 🧹 Nitpick (assertive)

Enhance example documentation

Add more context to clarify the intended usage.

 (comment
+  ;; Not recommended - uses default dev environment
   (trace-all-ns)

+  ;; Recommended - explicitly enables tracing for production
   (trace-all-ns {:config {:env :prod}})

+  ;; Example of a traced function's behavior
   (defn f [& args]
     (logs/trace
      (keyword "traced-fn" (str 'dev.utils "/" 'prn))
      {:test? :test}
      (prn args)))
   (f)

+  ;; Example of direct trace usage
   (logs/trace
    ::testing-stuff
    {:testing? :definitely}
    (get-allowed-ns)))
⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

10-17: 🧹 Nitpick (assertive)

Add docstring to explain namespace filtering logic

The implementation using transducers is efficient, but adding documentation would improve maintainability.

 (defn- get-allowed-ns []
+  "Returns a vector of namespace symbols that should be traced.
+   Includes namespaces starting with 'com.moclojer' while excluding
+   those ending with 'logs' to prevent recursive tracing.
+   Uses transducers for efficient filtering."
   (->> (all-ns)

Likely invalid or redundant comment.


44-45: 🛠️ Refactor suggestion

Enhance error handling with proper logging

Replace println with structured logging for better error tracking.

               (catch Exception e
-                (println "Failed to trace" sym (.getMessage e))))))))
+                (logs/error ::trace-failed
+                           {:namespace (str curr-ns)
+                            :function (str sym)
+                            :error (.getMessage e)})))))))

Likely invalid or redundant comment.

Comment on lines 1 to +2
(ns back.api.logic.mocks
(:refer-clojure :exclude [update])
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

LGTM! Consider adding docstring to the update function.

The exclusion of clojure.core/update is correct as it prevents naming conflicts with the local update function. This follows Clojure best practices for namespace management.

Consider adding a docstring to the update function to clarify its specific purpose in managing mock content:

 (defn update
+  "Updates the content of a mock and returns a map containing only the ID and updated content."
   [mock {:keys [content]}]
   (-> (assoc mock :mock/content content)
       (select-keys [:mock/id :mock/content])))

Committable suggestion skipped: line range outside the PR's diff.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between a560544 and 39c0ffd.

📒 Files selected for processing (1)
  • test/back/back/integration/api/wrap_traces_test.clj (1 hunks)
🔇 Additional comments (4)
test/back/back/integration/api/wrap_traces_test.clj (4)

1-11: LGTM! Well-organized namespace declaration.

The imports are logically grouped and all dependencies are properly utilized in the code.


13-23: Add docstrings to helper functions

Both helper functions would benefit from clear documentation explaining their purpose and return values.

Also applies to: 24-30


41-42: Verify tracing implementation

Let's verify the actual implementation of the tracing functionality to ensure the test is valid.

✅ Verification successful

Based on the shell script results, I can now provide a final response since I have sufficient information about the tracing implementation:

Tracing implementation is properly integrated

The test is valid as it correctly verifies the tracing functionality:

  • The trace-all-ns function in src/dev/utils.clj implements comprehensive tracing by:
    • Gathering allowed namespaces
    • Wrapping functions with logs/trace context
    • Tracking function names, arguments, and locations
  • The tracing is used throughout the codebase in controllers and DB operations
  • The test correctly compares local functions with traced functions to ensure proper wrapping
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of trace-all-ns and related functions

# Look for the tracing implementation
echo "Searching for trace-all-ns implementation..."
rg -A 10 "trace-all-ns"

# Look for actual trace usage
echo "Searching for trace usage in the codebase..."
rg -A 5 "trace"

# Look for logging configuration
echo "Searching for logging configuration..."
fd -e edn -e clj -x rg -l "logger|trace|log"

Length of output: 29286


24-30: 🛠️ Refactor suggestion

Simplify save-local-fns implementation using sequence operations

The current implementation using atom and nested doseq can be simplified using Clojure's sequence operations.

Consider this more idiomatic implementation:

-(defn- save-local-fns []
-  (let [a-ns (u/get-allowed-ns)
-        m (atom [])]
-    (doseq [d-ns a-ns]
-      (doseq [[func _] (ns-publics d-ns)]
-        (swap! m conj (str d-ns "/" func))))
-    @m))
+(defn- save-local-fns []
+  (->> (u/get-allowed-ns)
+       (mapcat (fn [ns]
+                (map (fn [[func _]]
+                      (str ns "/" func))
+                     (ns-publics ns))))
+       (into [])))

Likely invalid or redundant comment.

Comment on lines +32 to +43
(defflow
fwrap-all-ns-functions
{:init (utils/start-system! create-and-start-components)
:cleanup utils/stop-system!
:fail-fast? true}

(flow
"will try to wrap all desired ns functions into a trace container
and will compare them just by name"
(let [local-fns (save-local-fns)
expected-fns (u/trace-all-ns)]
(match? (matchers/equals local-fns) expected-fns))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhance test coverage with error cases and logging verification

The test only verifies function names but doesn't test:

  1. Error cases (e.g., invalid namespaces)
  2. Whether the wrapped functions actually log traces

Consider adding additional test flows to verify these scenarios.

Example structure:

(defflow test-invalid-namespace
  ;; Test wrapping functions from non-existent namespace
  )

(defflow test-trace-logging
  ;; Test that wrapped functions produce expected log output
  )

Comment on lines +38 to +40
(flow
"will try to wrap all desired ns functions into a trace container
and will compare them just by name"
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Improve multiline string formatting

The test description string should use proper string formatting for better readability.

-    "will try to wrap all desired ns functions into a trace container 
-    and will compare them just by name"
+    "will try to wrap all desired ns functions into a trace container and will compare them just by name"
📝 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
(flow
"will try to wrap all desired ns functions into a trace container
and will compare them just by name"
(flow
"will try to wrap all desired ns functions into a trace container and will compare them just by name"

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

🔭 Outside diff range comments (1)
test/back/back/integration/api/create_conflicting_mock_test.clj (1)

The commented-out test is the only validation for conflicting mocks scenario

Based on the analysis:

  • The create_conflicting_mock_test.clj contains the only test validating the invalid-wildcard error case
  • The implementation in src/back/api/controllers/mocks.clj shows this is a real error condition that needs testing
  • Other mock-related tests (create_mock_test.clj) only cover the happy path scenarios
  • No other tests in the codebase validate wildcard conflicts

The test should be fixed and enabled to ensure proper coverage of this error handling scenario.

🔗 Analysis chain

Line range hint 1-68: Verify impact on test coverage

The test appears to be the main validation for handling conflicting mocks. Disabling it could leave critical functionality untested.

Let's analyze the test coverage impact:


Let me gather more information about the test coverage and related tests.


Let me check the other mock-related test files to see if they cover similar scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find the related controller/handler code
rg -A 5 "invalid-wildcard" src/

# Look for similar error handling patterns
ast-grep --pattern 'cause "invalid-wildcard"' 

Length of output: 655


Script:

#!/bin/bash
# Find all test files related to mocks
fd "mock.*test\.clj$"

# Look for other tests that might be covering the invalid-wildcard scenario
rg -B2 -A2 "invalid-wildcard" test/

# Check if there are any other active tests in the same file
rg "defflow" test/back/back/integration/api/create_conflicting_mock_test.clj

Length of output: 1187


Script:

#!/bin/bash
# Check content of create_mock_test.clj for similar test cases
cat test/back/back/integration/api/create_mock_test.clj

# Look for any other tests validating wildcard conflicts
rg -l "wildcard.*conflict|conflict.*wildcard" test/

Length of output: 3781

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 39c0ffd and a403348.

📒 Files selected for processing (1)
  • test/back/back/integration/api/create_conflicting_mock_test.clj (1 hunks)

(defflow
;; Not working now
;; TODO fix the test
#_(defflow
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using pending test annotation instead of commenting out

Rather than completely disabling the test with #_, consider using your testing framework's pending/skip functionality to maintain visibility of the disabled test in test reports.

Example:

-#_(defflow
+;; TODO: Fix mock conflict handling (Issue #XXX)
+(defflow ^:pending

This approach:

  • Keeps the test visible in reports
  • Explicitly shows it as pending/skipped
  • Maintains better tracking of disabled tests

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +66 to +68
;; Not working now
;; TODO fix the test
#_(defflow
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Based on the gathered information, I can now provide the final response:

Commented test reduces critical test coverage for conflict handling

The commented test is the only one specifically testing the conflict prevention mechanism for mock creation. While create_mock_test.clj covers the basic mock creation flow, it doesn't verify the system's ability to prevent duplicate wildcards. This test is crucial as it validates:

  1. The conflict detection in create-mock! controller function
  2. The 412 status code response with invalid-wildcard error
  3. The proper handling of concurrent mock creation attempts

Action items:

  • The test should be fixed rather than commented out as it covers unique functionality
  • If there are specific issues with the test, they should be documented in a ticket
  • Consider adding logging statements in the controller to help debug the test failure
🔗 Analysis chain

Provide more context about the test failure

The test has been commented out with a vague TODO comment. This reduces test coverage for the mock creation functionality, particularly for the conflict handling scenarios. Please:

  1. Document the specific issue causing the test failure
  2. Add a JIRA/GitHub issue reference if one exists
  3. Provide an estimated timeline for fixing the test

Let's check if this is the only test covering mock conflicts:


Let me gather more information about the test coverage for mock-related functionality.


Let me check the create_mock_test.clj to understand if there's any overlap in test coverage.


Let me check the mock controller to understand the validation logic.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other tests related to mock conflicts
rg -l "conflicting.*mock" --type clojure test/

Length of output: 112


Script:

#!/bin/bash
# Search for all mock-related tests to understand coverage
rg -l "mock" --type clojure test/

# Also check for specific mock creation tests
rg -l "create.*mock" --type clojure test/

# Look at the actual test content to understand what's being tested
cat test/back/back/integration/api/create_conflicting_mock_test.clj

Length of output: 4777


Script:

#!/bin/bash
# Check the content of the main mock creation test
cat test/back/back/integration/api/create_mock_test.clj

# Also check if there are any related issues in the codebase
rg -l "invalid-wildcard" --type clojure

Length of output: 3866


Script:

#!/bin/bash
# Check the content of the mocks controller
cat src/back/api/controllers/mocks.clj

# Also look for any recent changes to this file
git log -p --since="1 month ago" src/back/api/controllers/mocks.clj

Length of output: 5968

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 UI
Review profile: ASSERTIVE
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between a403348 and d1ec9b4.

📒 Files selected for processing (1)
  • src/back/api/server.clj (1 hunks)
🔇 Additional comments (5)
src/back/api/server.clj (5)

13-22: Thorough implementation of filtered namespace gathering.
This helper function accurately captures all namespaces starting with "com.moclojer", excluding those ending in "logs". This approach helps ensure that you don’t unintentionally include unwanted or sensitive namespaces in the tracing process.


68-75: Add or refine documentation for MQ channel configuration.
This MQ configuration block appears to define periodic tasks (every 2 minutes, every 5 minutes) for domain/yml verifications. It would be helpful to explain the business logic behind these queue intervals, how they are used, and any dependencies.


60-60: Logger component addition looks good.
Registering the new logger component under ":logger" is well-aligned with the established component system. This modular approach cleanly isolates logging configuration.


85-86: Remove or conditionally enable 'trace-all-ns' in production code.
As previously mentioned, invoking 'trace-all-ns' in a live (production) environment can lead to performance issues, verbose logs, and possible leaks of sensitive data. Use environment checks to toggle this tracing only in development.


24-54: ⚠️ Potential issue

Potential performance overhead & security risk with 'trace-all-ns'.
Altering var roots to wrap every public function in multiple namespaces can be expensive and may log sensitive data. If certain functions process credentials, tokens, or PII, the metainfo might inadvertently get logged. Consider restricting tracing to a development or testing environment only, or whitelisting safer namespaces to reduce risk.

⛔ Skipped due to learnings
Learnt from: Felipe-gsilva
PR: moclojer/moclojer-app#364
File: src/dev/utils.clj:61-87
Timestamp: 2024-12-05T12:32:59.217Z
Learning: In the `moclojer-app` project, the `trace-all-ns` function in `src/dev/utils.clj` is intended to enable tracing primarily in non-development environments (i.e., when `:env` is not `:dev`).

Comment on lines +51 to +52
(catch Exception e
(println "Failed to trace" sym (.getMessage e))))))))
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Refine error handling for trace exceptions.
Currently, the catch block just prints an error message. For production readiness, consider using the logger to record these exceptions so they appear in centralized logs and can be observed more easily.

@Felipe-gsilva Felipe-gsilva requested review from matheusfrancisco and avelino and removed request for matheusfrancisco January 11, 2025 12:50
@Felipe-gsilva Felipe-gsilva self-assigned this Jan 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

atualizar usos de logs para nova versão utulizando telemere
3 participants