Skip to content

Conversation

@juanhiginio
Copy link
Contributor

@juanhiginio juanhiginio commented Jul 7, 2025

A client is implemented in Utils to allow bas interaction with the Operaton REST API via HTTP requests, allowing continuous polling of external service tasks, communication with it to execute a business logic and finally complete and resolve the external service task.

Summary by CodeRabbit

  • New Features
    • Added integration with an external task API, enabling users to fetch, lock, complete, unlock, and manage tasks seamlessly.
    • Improved task operation reliability with enhanced error handling and data formatting.

@juanhiginio juanhiginio requested a review from L-Zuluaga July 7, 2025 20:14
@juanhiginio juanhiginio self-assigned this Jul 7, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jul 7, 2025

Walkthrough

A new Ruby class, ExternalTaskClient, has been added under the Bas::Utils::Operaton namespace. This class provides methods to interact with an external task API via HTTP, supporting operations such as fetching, locking, completing, unlocking tasks, retrieving variables, and reporting failures, all with JSON-formatted requests and responses. Additionally, the Gemfile was updated to include faraday and json gems required for HTTP communication and JSON handling.

Changes

File(s) Change Summary
lib/bas/utils/operaton/external_task_client.rb Added new ExternalTaskClient class for HTTP-based interaction with an external task API.
Gemfile Added gem dependencies: faraday (> 2.9) and json (> 2.8) for HTTP requests and JSON parsing.

Sequence Diagram(s)

sequenceDiagram
    participant Client as ExternalTaskClient
    participant API as External Task API

    Client->>API: fetch_and_lock(topics, lock_duration, ...)
    API-->>Client: List of locked tasks

    Client->>API: complete(task_id, variables)
    API-->>Client: Completion confirmation

    Client->>API: get_variables(task_id)
    API-->>Client: Task variables

    Client->>API: unlock(task_id)
    API-->>Client: Unlock confirmation

    Client->>API: report_failure(task_id, error_message, ...)
    API-->>Client: Failure reported confirmation
Loading

Poem

A clever new client now hops in the code,
To fetch and to lock, down the API road.
With tasks to complete and variables to find,
It unlocks, reports failures—never behind!
JSON in its basket, requests sent with glee,
This bunny brings tasks home, as quick as can be! 🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c2e08ca and 1f8bbdf.

📒 Files selected for processing (1)
  • Gemfile (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Gemfile

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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: 4

🧹 Nitpick comments (4)
lib/bas/utils/operaton/external_task_client.rb (4)

21-38: Consider extracting topic formatting logic.

The method exceeds the recommended length limit and mixes input validation with business logic.

Extract the topic formatting logic into a private method:

 def fetch_and_lock(topics_str, lock_duration: 10_000, max_tasks: 1, use_priority: true, variables: [])
-  topic_names = topics_str.is_a?(Array) ? topics_str : topics_str.to_s.split(',')
-
-  formatted_topics = topic_names.map do |name|
-    {
-      topicName: name.strip,
-      lockDuration: lock_duration,
-      variables: variables
-    }
-  end
-
   post("/external-task/fetchAndLock", {
          workerId: @worker_id,
          maxTasks: max_tasks,
          usePriority: use_priority,
-         topics: formatted_topics
+         topics: format_topics(topics_str, lock_duration, variables)
        })
 end

+private
+
+def format_topics(topics_str, lock_duration, variables)
+  topic_names = topics_str.is_a?(Array) ? topics_str : topics_str.to_s.split(',')
+  topic_names.map do |name|
+    {
+      topicName: name.strip,
+      lockDuration: lock_duration,
+      variables: variables
+    }
+  end
+end

42-44: Fix hash indentation.

The hash indentation is inconsistent with Ruby style guidelines.

 post("/external-task/#{task_id}/complete", {
-  workerId: @worker_id,
-  variables: format_variables(variables)
-})
+       workerId: @worker_id,
+       variables: format_variables(variables)
+     })

57-62: Fix hash indentation.

The hash indentation is inconsistent with Ruby style guidelines.

 post("/external-task/#{task_id}/failure", {
-  workerId: @worker_id,
-  errorMessage: error_message,
-  errorDetails: error_details,
-  retries: retries,
-  retryTimeout: retry_timeout
-})
+       workerId: @worker_id,
+       errorMessage: error_message,
+       errorDetails: error_details,
+       retries: retries,
+       retryTimeout: retry_timeout
+     })

96-104: Consider edge cases in type mapping.

The type mapping doesn't handle some Ruby types that might be commonly used.

Consider adding support for additional Ruby types:

 def ruby_type_to_operaton_type(value)
   case value
   when String then "String"
   when Integer then "Integer"
   when Float then "Double"
   when TrueClass, FalseClass then "Boolean"
+  when NilClass then "Null"
+  when Array, Hash then "Object"
+  when Date, Time, DateTime then "String"
   else "Object"
   end
 end
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b85ecf2 and 8b9cbb9.

📒 Files selected for processing (1)
  • lib/bas/utils/operaton/external_task_client.rb (1 hunks)
🧰 Additional context used
🪛 RuboCop (1.75.5)
lib/bas/utils/operaton/external_task_client.rb

[convention] 9-9: Missing top-level documentation comment for class Bas::Utils::Operaton::ExternalTaskClient.

(Style/Documentation)


[convention] 21-38: Method has too many lines. [14/10]

(Metrics/MethodLength)


[convention] 22-22: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 42-42: Use 2 spaces for indentation in a hash, relative to the first position after the preceding left parenthesis.

(Layout/FirstHashElementIndentation)


[convention] 44-44: Indent the right brace the same as the first position after the preceding left parenthesis.

(Layout/FirstHashElementIndentation)


[convention] 57-57: Use 2 spaces for indentation in a hash, relative to the first position after the preceding left parenthesis.

(Layout/FirstHashElementIndentation)


[convention] 62-62: Indent the right brace the same as the first position after the preceding left parenthesis.

(Layout/FirstHashElementIndentation)


[convention] 80-80: Use a guard clause (raise "Operaton API Error #{response.status}: #{response.body}" unless response.success?) instead of wrapping the code inside a conditional expression.

(Style/GuardClause)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Ruby 3.2.2

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

🧹 Nitpick comments (1)
Gemfile (1)

20-20: Match string-literal style used elsewhere

Every other gem declaration uses double quotes; switch here to silence Style/StringLiterals warnings.

-gem 'json', '~> 2.8'
+gem "json", "~> 2.8"
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9cbb9 and d8bd18f.

📒 Files selected for processing (1)
  • Gemfile (1 hunks)
🧰 Additional context used
🪛 RuboCop (1.75.5)
Gemfile

[convention] 20-20: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)


[convention] 20-20: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

(Style/StringLiterals)

@coveralls
Copy link

coveralls commented Jul 7, 2025

Pull Request Test Coverage Report for Build 16128544331

Details

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 98.695%

Totals Coverage Status
Change from base Build 16080024474: 0.0%
Covered Lines: 1437
Relevant Lines: 1456

💛 - Coveralls

L-Zuluaga
L-Zuluaga previously approved these changes Jul 7, 2025
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

♻️ Duplicate comments (3)
Gemfile (2)

18-18: Pin Faraday to a stable series.


20-20: json gem is usually unnecessary and can introduce ABI conflicts.

lib/bas/utils/operaton/external_task_client.rb (1)

90-94: Improve error handling to avoid sensitive information exposure.

The current error handling exposes potentially sensitive information from the response body, which could be a security concern.

 def handle_response(response)
-  raise "Operaton API Error #{response.status}: #{response.body}" unless response.success?
+  raise "Operaton API Error #{response.status}: #{response.reason_phrase}" unless response.success?

   response.body
 end

This change:

  • Avoids exposing potentially sensitive response body content
  • Uses reason_phrase for more appropriate error context
  • Maintains debugging capability without security risks
🧹 Nitpick comments (1)
lib/bas/utils/operaton/external_task_client.rb (1)

35-41: Consider adding parameter validation for fetch_and_lock method.

The method has good parameter defaults, but consider validating critical parameters to prevent runtime errors.

 def fetch_and_lock(topics_str, lock_duration: 10_000, max_tasks: 1, use_priority: true, variables: [])
+  raise ArgumentError, "topics_str cannot be nil or empty" if topics_str.nil? || (topics_str.respond_to?(:empty?) && topics_str.empty?)
+  raise ArgumentError, "lock_duration must be positive" if lock_duration <= 0
+  raise ArgumentError, "max_tasks must be positive" if max_tasks <= 0
+  
   post("/external-task/fetchAndLock",
        workerId: @worker_id,
        maxTasks: max_tasks,
        usePriority: use_priority,
        topics: build_topics_payload(topics_str, lock_duration, variables))
 end
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f97d13 and c2e08ca.

📒 Files selected for processing (2)
  • Gemfile (1 hunks)
  • lib/bas/utils/operaton/external_task_client.rb (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Ruby
Gemfile

[error] 18-18: Bundler error parsing Gemfile: no implicit conversion of Array into String. Incorrect syntax at line 18: 'gem gem "faraday", "~> 2.9"'.

🔇 Additional comments (4)
lib/bas/utils/operaton/external_task_client.rb (4)

9-20: Excellent documentation and class structure.

The class documentation is comprehensive and follows Ruby documentation conventions well. The example usage is particularly helpful for understanding the API.


21-33: Proper input validation and Faraday configuration.

The initialization method now includes proper input validation as suggested in past reviews. The Faraday connection setup is correctly configured for JSON handling.


67-76: Robust topic parsing with good flexibility.

The method handles both string and array inputs well, with proper trimming of whitespace. The implementation is clean and functional.


96-113: Comprehensive type mapping with proper Ruby type handling.

The type conversion logic correctly maps Ruby types to the expected API types. The handling of boolean types using TrueClass and FalseClass is particularly well done.

@juanhiginio juanhiginio requested a review from L-Zuluaga July 7, 2025 21:48
@juanhiginio juanhiginio merged commit 966bf19 into main Jul 7, 2025
3 checks passed
@juanhiginio juanhiginio deleted the operaton-client branch July 7, 2025 21:50
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.

4 participants