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

fix: properly pass user-defined headers #182

Merged
merged 2 commits into from
Nov 17, 2024

Conversation

rustatian
Copy link
Member

@rustatian rustatian commented Nov 17, 2024

Reason for This PR

  • User defined headers are not properly passed.

Description of Changes

  • Use nats.NewMsg and pass user-defined headers in it.
  • Properly merge headers in the unpack method.

License Acceptance

By submitting this pull request, I confirm that my contribution is made under
the terms of the MIT license.

PR Checklist

[Author TODO: Meet these criteria.]
[Reviewer TODO: Verify that these criteria are met. Request changes if not]

  • All commits in this PR are signed (git commit -s).
  • The reason for this PR is clearly provided (issue no. or explanation).
  • The description of changes is clear and encompassing.
  • Any required documentation changes (code and docs) are included in this PR.
  • Any user-facing changes are mentioned in CHANGELOG.md.
  • All added/changed functionality is tested.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new configuration file for NATS headers, enhancing server settings for job processing.
    • Added a new test function to validate NATS header handling in job processing.
  • Bug Fixes

    • Improved message unpacking by including headers, ensuring better metadata handling.
    • Updated task acknowledgment methods across various job consumer scripts for consistency and clarity.
  • Chores

    • Removed version declaration from the Docker Compose configuration for a cleaner setup.

Signed-off-by: Valery Piashchynski <piashchynski.valery@gmail.com>
@rustatian rustatian added the bug Something isn't working label Nov 17, 2024
@rustatian rustatian requested a review from wolfy-j November 17, 2024 10:45
@rustatian rustatian self-assigned this Nov 17, 2024
Copy link

coderabbitai bot commented Nov 17, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing the message handling capabilities within the natsjobs package. Key modifications include refactoring the Push and requeue methods to improve message construction and publication clarity, as well as updating the listenerStart method to utilize message headers. Additionally, a new configuration file for NATS settings has been introduced, and a new test function has been added to validate header handling. Other files have seen minor adjustments, including the removal of a version declaration in a Docker Compose file.

Changes

File Path Change Summary
natsjobs/driver.go Refactored Push and requeue methods to separate message construction from publishing.
natsjobs/listener.go Updated listenerStart to unpack message headers; initialized item.headers if nil.
natsjobs/unpack.go Modified unpack method to accept an additional headers parameter for streamlined header handling.
tests/configs/.rr-nats-headers.yaml Introduced a new configuration file for NATS settings, detailing RPC, server, logging, and job configs.
tests/env/docker-compose-nats.yaml Removed version declaration; service configurations remain unchanged.
tests/jobs_nats_test.go Added new test function TestNATSHeaders for validating NATS header handling in job processing.
tests/php_test_files/jobs/jobs_ok_headers.php Introduced a job consumer class that processes tasks and validates headers, throwing exceptions for mismatches.
tests/php_test_files/jobs/jobs_create_memory.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_err.php Changed task completion handling from complete() to ack() and from fail() to nack().
tests/php_test_files/jobs/jobs_ok.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_pq.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_queue_name_exist.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_sleep1.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_slow.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_slow_rand.php Changed task acknowledgment from complete() to ack().
tests/php_test_files/jobs/jobs_ok_with_subject_header.php Changed task acknowledgment from complete() to ack() and from fail() to nack().

Sequence Diagram(s)

sequenceDiagram
    participant Driver
    participant NATS
    participant Listener
    participant Item

    Driver->>NATS: Publish message
    NATS->>Driver: Acknowledge receipt
    Driver->>Listener: Start listening for messages
    Listener->>Item: Unpack message data and headers
    Item->>Listener: Process item
    Listener->>NATS: Acknowledge item processing
Loading

🐇 "In the realm of NATS we play,
Messages dance in a structured way.
Headers now join the fun,
Processing tasks, one by one.
With tests to ensure all is bright,
Our code hops along, a joyful sight!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai 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: 3

🧹 Outside diff range and nitpick comments (6)
tests/php_test_files/jobs/jobs_ok_headers.php (3)

1-15: LGTM! Consider adding strict types declaration.

The file setup and imports are well-organized. For better type safety, consider adding strict types declaration.

 <?php
+declare(strict_types=1);

29-31: Enhance error reporting for debugging.

The current error handling only sends the exception message. Consider including more context for debugging.

     } catch (\Throwable $e) {
-        $task->error((string)$e);
+        $task->error(sprintf(
+            "Error processing task [%s]: %s\nTrace: %s",
+            $task->getId(),
+            $e->getMessage(),
+            $e->getTraceAsString()
+        ));
     }

18-32: Add graceful shutdown handling.

The infinite loop should handle interruption signals for clean shutdown in production environments.

+$shutdown = false;
+pcntl_signal(SIGTERM, function() use (&$shutdown) {
+    $shutdown = true;
+});
+pcntl_signal(SIGINT, function() use (&$shutdown) {
+    $shutdown = true;
+});
+
-while ($task = $consumer->waitTask()) {
+while (!$shutdown && ($task = $consumer->waitTask())) {
     try {
+        pcntl_signal_dispatch();
         // ... existing code ...
     }
 }
natsjobs/listener.go (1)

Line range hint 38-156: Consider refactoring for improved maintainability.

The listenerStart function is complex and handles multiple responsibilities. Consider breaking it down into smaller, focused functions:

  1. Message metadata handling
  2. Error state management
  3. Item preparation
  4. Acknowledgment handling

Example refactor:

func (c *Driver) listenerStart() {
    go func() {
        for {
            select {
            case m, ok := <-c.msgCh:
                if !ok {
                    c.handleClosedChannel()
                    return
                }
-               meta, err := m.Metadata()
-               if err != nil {
-                   errn := m.Nak()
-                   if errn != nil {
-                       c.log.Error("failed to send Nak state", zap.Error(errn), zap.Error(err))
-                       continue
-                   }
-                   c.log.Info("can't get message metadata", zap.Error(err))
-                   continue
-               }
+               meta, err := c.handleMessageMetadata(m)
+               if err != nil {
+                   continue
+               }

-               err = m.InProgress()
-               if err != nil {
-                   errn := m.Nak()
-                   // ... error handling
-               }
+               if err := c.setMessageInProgress(m); err != nil {
+                   continue
+               }

                item := &Item{}
                c.unpack(m.Data(), m.Headers(), item)
+               if err := c.prepareItem(item, m, meta); err != nil {
+                   continue
+               }

+               c.processItem(item, m)

            case <-c.stopCh:
                c.handleShutdown()
                return
            }
        }
    }()
}

func (c *Driver) handleMessageMetadata(m jetstream.Msg) (*jetstream.MsgMetadata, error) {
    // Extract metadata handling
}

func (c *Driver) setMessageInProgress(m jetstream.Msg) error {
    // Handle InProgress state
}

func (c *Driver) prepareItem(item *Item, m jetstream.Msg, meta *jetstream.MsgMetadata) error {
    // Prepare item with options and headers
}

func (c *Driver) processItem(item *Item, m jetstream.Msg) {
    // Handle item processing and acknowledgment
}
natsjobs/driver.go (1)

Line range hint 516-532: Critical: Headers are lost during message requeue

The requeue method is not preserving the message headers when republishing the message. This is inconsistent with the Push method's behavior and will lead to loss of header information during requeuing operations.

Apply this diff to maintain header consistency:

 _, err = c.jetstream.PublishMsg(context.Background(), &nats.Msg{
     Subject: c.subject,
     Data:    data,
+    Header:  item.headers,
 })
tests/jobs_nats_test.go (1)

122-127: Improve error handling in cleanup.

The cleanup function swallows errors and only logs them. Consider failing the test if cleanup fails, as this could affect subsequent tests.

 t.Cleanup(func() {
     errc := helpers.CleanupNats("nats://127.0.0.1:4222", "headers-test")
     if errc != nil {
-        t.Log(errc)
+        t.Errorf("cleanup failed: %v", errc)
     }
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fb53018 and 25eb315.

⛔ Files ignored due to path filters (1)
  • go.work.sum is excluded by !**/*.sum
📒 Files selected for processing (7)
  • natsjobs/driver.go (1 hunks)
  • natsjobs/listener.go (1 hunks)
  • natsjobs/unpack.go (1 hunks)
  • tests/configs/.rr-nats-headers.yaml (1 hunks)
  • tests/env/docker-compose-nats.yaml (0 hunks)
  • tests/jobs_nats_test.go (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_headers.php (1 hunks)
💤 Files with no reviewable changes (1)
  • tests/env/docker-compose-nats.yaml
🧰 Additional context used
📓 Learnings (1)
tests/jobs_nats_test.go (3)
Learnt from: KernelMrex
PR: roadrunner-server/nats#102
File: tests/jobs_nats_test.go:1027-1151
Timestamp: 2024-11-12T10:53:06.414Z
Learning: The user clarified that the header check for the NATS message subject is performed in a PHP test file, not in the Go test file. The Go test ensures that the NATS message is published and the pipeline processes the job correctly.
Learnt from: KernelMrex
PR: roadrunner-server/nats#102
File: tests/jobs_nats_test.go:1027-1151
Timestamp: 2024-11-12T10:53:06.414Z
Learning: The user clarified that the header check for the NATS message subject is performed in a PHP test file, not in the Go test file. The Go test ensures that the NATS message is published and the pipeline processes the job correctly.
Learnt from: KernelMrex
PR: roadrunner-server/nats#102
File: tests/jobs_nats_test.go:1027-1151
Timestamp: 2024-11-12T10:53:06.414Z
Learning: The user clarified that the header check for the NATS message subject is performed in a PHP test file, not in the Go test file. The Go test ensures that the NATS message is published and the pipeline processes the job correctly.
🪛 yamllint
tests/configs/.rr-nats-headers.yaml

[error] 36-36: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (7)
natsjobs/unpack.go (2)

14-14: LGTM: Method signature properly updated for header support

The new parameter headers map[string][]string correctly matches NATS message header type.


16-22: Consider adding defensive programming measures

While the implementation correctly handles headers, consider these improvements:

  1. Add a nil check for the headers parameter
  2. Create a defensive copy of the headers map to prevent shared state

Consider applying this change:

func (c *Driver) unpack(data []byte, headers map[string][]string, item *Item) {
+       // Create a defensive copy of headers
+       headersCopy := make(map[string][]string, len(headers))
+       if headers != nil {
+           for k, v := range headers {
+               vCopy := make([]string, len(v))
+               copy(vCopy, v)
+               headersCopy[k] = vCopy
+           }
+       }
        err := json.Unmarshal(data, item)
-       item.headers = headers
+       item.headers = headersCopy
        if err != nil {
            *item = Item{
                Job:     auto,
                Ident:   uuid.NewString(),
                Payload: data,
-               headers: headers,
+               headers: headersCopy,
                Options: &Options{

Let's verify the header handling implementation across the codebase:

tests/php_test_files/jobs/jobs_ok_headers.php (1)

16-16: Verify if consumer configuration is needed.

The consumer is initialized without any configuration. Please verify if this is sufficient for header handling.

✅ Verification successful

Let me check the Consumer class implementation to understand if any configuration is needed for header handling.


Let me try a different approach to check the Consumer class implementation and its header handling capabilities.


Based on the evidence gathered:

  1. All test files consistently initialize the Consumer without any configuration parameters
  2. The test file being reviewed is specifically testing header functionality (jobs_ok_headers.php)
  3. The fact that this test file successfully tests headers without additional configuration suggests the default initialization is sufficient

No configuration needed for Consumer initialization

The consistent pattern across all test files and the successful header-specific test case demonstrate that the basic Consumer initialization without configuration is sufficient for header handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if Consumer class typically requires configuration
# Look for other test files using Consumer to see if they pass config

# Search for Consumer initialization patterns in test files
rg -t php "new.*Consumer.*\(" tests/

Length of output: 1010


Script:

#!/bin/bash
# Search for Consumer class implementation and constructor
ast-grep --pattern 'class Consumer {
  $$$
  public function __construct($$$) {
    $$$
  }
  $$$
}'

Length of output: 102


Script:

#!/bin/bash
# Search for Consumer class implementation and any header-related methods
rg -l "class Consumer" . | xargs rg -A 10 "class Consumer"

# Also search for header-related methods in Consumer
rg -i "header" . | grep -i "consumer"

Length of output: 96

natsjobs/listener.go (2)

Line range hint 142-146: LGTM! Well-structured header handling.

The code follows good practices:

  1. Defensive initialization of headers map
  2. Consistent use of predefined header key
  3. Clear separation of concerns

79-79: Verify the unpack method signature.

The change to pass headers to unpack aligns with the PR objective. Let's verify the method implementation.

✅ Verification successful

The unpack method signature matches the call site correctly

The implementation in natsjobs/unpack.go shows that the unpack method signature perfectly matches the call site:

  • It accepts three parameters: data []byte, headers map[string][]string, and item *Item
  • The method properly stores the headers in the item struct: item.headers = headers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the unpack method signature matches the new call.
# Expected: The unpack method should accept three parameters (data, headers, and item).

ast-grep --pattern 'func $_(c *Driver) unpack($_, $_, $_) {
  $$$
}'

Length of output: 70


Script:

#!/bin/bash
# Let's try a different approach to find the unpack method
# First, let's find all Go files that might contain the unpack method
rg -l "unpack" --type go

# Then, let's look for the actual implementation with context
rg "func.*unpack" --type go -A 5

Length of output: 403

natsjobs/driver.go (1)

259-262: LGTM! Headers are now properly passed.

The implementation correctly creates a new NATS message and explicitly sets both data and headers, addressing the issue of user-defined headers not being passed correctly.

tests/jobs_nats_test.go (1)

42-42: Verify test coverage for header functionality.

Given that this PR fixes user-defined headers, let's ensure we have comprehensive test coverage for header-related functionality.

✅ Verification successful

Test coverage for header functionality appears comprehensive

The codebase shows good test coverage for header-related functionality:

  • TestNATSHeaders test with dedicated configuration in .rr-nats-headers.yaml
  • TestNATSMessageSubjectAsHeader test verifying subject header behavior
  • PHP test files validating:
    • Custom headers (jobs_ok_headers.php)
    • Subject headers (jobs_ok_with_subject_header.php)
    • Header manipulation in error scenarios (jobs_err.php)
    • Header creation and defaults (jobs_create_memory.php)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for header-related functionality

# Look for header-related tests
rg -l "TestNATS.*Header" tests/

# Look for header-related test helper functions
rg -l "WithHeaders?" tests/helpers/

# Check for header-related assertions
rg "assert.*Header" tests/

Length of output: 124


Script:

#!/bin/bash
# Let's examine the actual test implementation and assertions

# Check the content of the NATS header test
rg -A 10 "TestNATSHeaders" tests/

# Look for any header-related setup or verification in test files
rg -i "header" tests/ -A 5

# Check for any header-related functionality in the main code
rg -i "header" pkg/ -A 5

Length of output: 9515

tests/php_test_files/jobs/jobs_ok_headers.php Show resolved Hide resolved
tests/jobs_nats_test.go Show resolved Hide resolved
tests/jobs_nats_test.go Show resolved Hide resolved
Signed-off-by: Valery Piashchynski <piashchynski.valery@gmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (8)
tests/php_test_files/jobs/jobs_ok.php (1)

19-21: Consider adding header validation to the test.

Since this PR focuses on proper header handling, consider enhancing this test to validate that headers are correctly passed through the system.

Example enhancement:

while ($task = $consumer->waitTask()) {
    try {
+       // Validate headers are properly passed
+       $headers = $task->getHeaders();
+       if (empty($headers)) {
+           throw new \RuntimeException('Expected headers to be present');
+       }
        $task->ack();
    } catch (\Throwable $e) {
        $task->error((string)$e);
    }
}
tests/php_test_files/jobs/jobs_ok_pq.php (1)

19-19: Document the purpose of the sleep duration

The hardcoded 15-second sleep appears to be for testing purposes, but its specific purpose isn't clear.

Consider adding a comment explaining why this specific duration was chosen:

+    // Simulate a long-running task with a 15-second delay
     sleep(15);
tests/php_test_files/jobs/jobs_ok_sleep1.php (1)

19-19: Document the purpose of sleep(1)

Consider adding a comment explaining that the sleep is intentionally added to simulate processing time in the test.

+    // Simulate task processing time
     sleep(1);
tests/php_test_files/jobs/jobs_ok_slow.php (1)

18-20: Consider reducing sleep duration for faster tests

The 60-second sleep in this test file might significantly slow down the test suite execution. Consider:

  1. Reducing the sleep duration for regular testing
  2. Using environment variables to control the sleep duration
  3. Adding a comment explaining why this specific duration is necessary
while ($task = $consumer->waitTask()) {
    try {
-        sleep(60);
+        // Sleep duration can be configured via environment variable
+        $sleepDuration = (int)getenv('TEST_SLEEP_DURATION') ?: 5; // Default to 5 seconds
+        sleep($sleepDuration);
tests/php_test_files/jobs/jobs_ok_slow_rand.php (1)

Line range hint 19-23: Document the sleep condition's purpose.

The random sleep condition (>995) introduces a 60-second delay in ~0.5% of cases. This helps test timeout handling and slow task processing scenarios.

Consider adding a comment explaining this test behavior:

        $val = random_int(0, 1000);
+       // Simulate slow processing in ~0.5% of cases to test timeout handling
        if ($val > 995) {
            sleep(60);
        }
tests/php_test_files/jobs/jobs_ok_queue_name_exist.php (1)

Line range hint 1-24: Enhance test coverage for header handling

Given that this PR's main objective is to fix user-defined headers passing, this test file could be enhanced to verify header preservation during task processing.

Consider adding header validation to this test:

 while ($task = $consumer->waitTask()) {
     try {
         if ('unknown' === $task->getQueue()) {
             throw new RuntimeException('Queue name was not found');
         }
+        // Verify headers are preserved
+        $headers = $task->getHeaders();
+        if (empty($headers)) {
+            throw new RuntimeException('Expected headers not found');
+        }
 
         $task->ack();
     } catch (\Throwable $e) {
         $task->error((string)$e);
     }
 }
tests/php_test_files/jobs/jobs_err.php (1)

26-26: LGTM: Enhanced retry mechanism with proper header preservation

The updated implementation correctly:

  • Preserves attempt count via headers
  • Adds a 5-second delay between retries
  • Uses nack() to indicate processing failure while requesting requeue

Consider documenting the retry delay (5 seconds) and max attempts (3) as configuration parameters rather than hard-coding them, making them adjustable for different environments or job types.

tests/php_test_files/jobs/jobs_create_memory.php (1)

Line range hint 1-47: LGTM with verification needed

The changes align with the PR's objective of fixing user-defined header handling. The test file provides good coverage by testing both memory and local queues with headers.

Consider adding explicit assertions to verify that headers are correctly preserved after task acknowledgment, as this is the main focus of the PR.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 25eb315 and 889f863.

📒 Files selected for processing (9)
  • tests/php_test_files/jobs/jobs_create_memory.php (1 hunks)
  • tests/php_test_files/jobs/jobs_err.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_pq.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_queue_name_exist.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_sleep1.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_slow.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_slow_rand.php (1 hunks)
  • tests/php_test_files/jobs/jobs_ok_with_subject_header.php (1 hunks)
🔇 Additional comments (11)
tests/php_test_files/jobs/jobs_ok.php (1)

20-20: LGTM! Method name change aligns with standard practices.

The change from complete() to ack() follows common message queue terminology and practices.

tests/php_test_files/jobs/jobs_ok_pq.php (1)

21-21: Verify consistent usage of ack() method across test files

The change from complete() to ack() appears to be part of a broader API update.

Let's verify this change is consistent across all test files:

✅ Verification successful

API change from complete() to ack() is consistently implemented

The verification shows:

  • No remaining instances of the old complete() method in test files
  • The new ack() method is consistently used across all test files (10 files)
  • All test cases have been properly updated to use the new API
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of the old `complete()` method
# and confirm consistent adoption of `ack()` across test files

echo "Checking for any remaining complete() calls:"
rg "\->complete\(\)" "tests/php_test_files"

echo -e "\nVerifying ack() usage in test files:"
rg "\->ack\(\)" "tests/php_test_files"

Length of output: 952

tests/php_test_files/jobs/jobs_ok_sleep1.php (1)

21-21: Verify consistent usage of ack() method across test files

The change from complete() to ack() appears to be part of an API standardization effort.

Let's verify this change is consistent across all test files:

✅ Verification successful

Migration from complete() to ack() is consistently implemented

The verification confirms that:

  • No instances of ->complete() were found in the test files
  • All job test files consistently use ->ack() for task acknowledgment
  • The migration appears to be complete and uniform across the test suite
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of complete() method in PHP test files
# Expected: No occurrences of ->complete() should be found, confirming consistent migration to ->ack()

rg -g "*.php" "->complete\(\)" tests/

Length of output: 444


Script:

#!/bin/bash
# Description: Check for any remaining usage of complete() method in PHP test files
# Escaping special characters in the pattern
rg -g "*.php" "\->complete\(\)" tests/

# Also check for ack() usage to confirm the migration
rg -g "*.php" "\->ack\(\)" tests/

Length of output: 758

tests/php_test_files/jobs/jobs_ok_slow.php (1)

21-21: Verify API change consistency across the codebase

The change from complete() to ack() appears to be part of a broader API change. Let's verify this change is consistent across the codebase.

✅ Verification successful

Note: Fixed the ripgrep pattern by properly escaping the special characters in the search pattern.


API change is consistent across the codebase

The verification shows that:

  • No instances of the old $task->complete() method were found in the tests directory
  • The new $task->ack() method is consistently used across all job-related test files
  • All test cases have been properly updated to use the new API
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of the old $task->complete() method
# and verify consistent usage of $task->ack()

echo "Checking for any remaining usage of ->complete()..."
rg -t php "->complete\(\)" tests/

echo "Verifying consistent usage of ->ack()..."
rg -t php "->ack\(\)" tests/

Length of output: 1080


Script:

#!/bin/bash
# Description: Check for any remaining usage of the old $task->complete() method
# and verify consistent usage of $task->ack()

echo "Checking for any remaining usage of complete()..."
rg "\\\$task->complete\(\)" tests/

echo "Verifying consistent usage of ack()..."
rg "\\\$task->ack\(\)" tests/

Length of output: 942

tests/php_test_files/jobs/jobs_ok_slow_rand.php (1)

25-25: LGTM: Method change aligns with standardization.

The change from complete() to ack() is consistent with the broader changes in the PR for improving message handling.

Let's verify the consistency of this change across other test files:

✅ Verification successful

Note: Fixed the ripgrep pattern by escaping the arrow operator properly.


Method change is consistently implemented across test files

The verification shows that:

  • No instances of the old ->complete() method remain in the test files
  • The new ->ack() method is consistently used across all job test files
  • The change has been properly propagated throughout the test suite
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all test files use the new ack() method consistently
# and that there are no remaining instances of the old complete() method

# Search for any remaining complete() calls in PHP test files
echo "Checking for any remaining complete() calls:"
rg "->complete\(\)" "tests/php_test_files"

# Verify consistent usage of ack() in other test files
echo "Verifying ack() usage in test files:"
rg "->ack\(\)" "tests/php_test_files"

Length of output: 1072


Script:

#!/bin/bash
# Description: Verify that all test files use the new ack() method consistently
# and that there are no remaining instances of the old complete() method

# Search for any remaining complete() calls in PHP test files
echo "Checking for any remaining complete() calls:"
rg "\->complete\(" "tests/php_test_files"

# Verify consistent usage of ack() in other test files
echo "Verifying ack() usage in test files:"
rg "\->ack\(" "tests/php_test_files"

Length of output: 942

tests/php_test_files/jobs/jobs_ok_queue_name_exist.php (1)

24-24: Verify consistent method naming across the codebase

The change from complete() to ack() appears to be part of a broader standardization effort. Let's verify this change is consistent across all consumer implementations.

✅ Verification successful

Method change from complete() to ack() is consistently implemented

The verification results show that:

  • No instances of the old $task->complete() method remain in the PHP test files
  • The new $task->ack() method is consistently used across all PHP test files in the jobs directory
  • All test files, including those testing headers, queue names, and error scenarios, have been updated
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of the old method name
# and verify consistent usage of the new method across PHP test files

# Check for any remaining $task->complete() calls
echo "Checking for remaining complete() calls:"
rg -l '\$task->complete\(\)' 'tests/php_test_files'

# Verify consistent usage of ack()
echo -e "\nVerifying ack() usage:"
rg -l '\$task->ack\(\)' 'tests/php_test_files'

Length of output: 712

tests/php_test_files/jobs/jobs_err.php (1)

24-24: LGTM: Appropriate use of ack() for final attempt

The change from complete() to ack() is correct here as it properly acknowledges the message after maximum attempts are exhausted, aligning with standard message queue patterns.

tests/php_test_files/jobs/jobs_ok_with_subject_header.php (2)

Line range hint 19-29: LGTM! Robust header validation

The header validation logic properly checks for the expected NATS subject and provides clear error messages, which aligns with the PR's objective of improving header handling.


31-31: LGTM! Improved message handling terminology

The changes from complete()/fail() to ack()/nack() align better with standard messaging protocol terminology, making the code more intuitive and consistent with industry practices.

Let's verify the consistency of these changes across other test files:

Also applies to: 33-33

✅ Verification successful

Consistent usage of ack()/nack() methods confirmed

The search results show that all test files are consistently using the new ack() method for successful task completion. For error handling, most files use error(), while only the subject header test file and jobs_err.php use nack(). This variation in error handling methods (error() vs nack()) appears to be intentional based on different test scenarios, and doesn't indicate inconsistency in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if any test files still use the old complete()/fail() methods
# Expected: No occurrences of the old methods

echo "Checking for any remaining uses of old methods..."
rg -l 'complete\(\)' 'tests/php_test_files'
rg -l 'fail\(' 'tests/php_test_files'

Length of output: 190


Script:

#!/bin/bash
# Let's try a more comprehensive search with context and without exact method call matching
echo "Searching for potential method names with context..."
rg -i "complete|fail|ack|nack" "tests/php_test_files" -B 2 -A 2

# Also search for task-related class definitions to understand the interface
echo -e "\nSearching for task-related class definitions..."
ast-grep --pattern 'class $_ {
  $$$
  complete($$$) {
    $$$
  }
  $$$
}'

ast-grep --pattern 'class $_ {
  $$$
  fail($$$) {
    $$$
  }
  $$$
}'

Length of output: 4082

tests/php_test_files/jobs/jobs_create_memory.php (2)

46-46: Verify the impact of switching to ack()

The change from complete() to ack() appears to be part of a broader standardization effort. However, we should verify that this change properly handles the user-defined headers as intended by the PR.

Let's verify the consistency of this change across the codebase:

✅ Verification successful

Change from complete() to ack() is consistent and verified

The verification shows that:

  • No instances of complete() method remain in the test files
  • The ack() method is consistently used across all test files (10 files found)
  • The change in jobs_create_memory.php aligns with the standardized approach used in other test files
  • The test file properly sets up headers (attempts and retry-delay) before task acknowledgment, which is consistent with the PR's objective of fixing user-defined headers passing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of complete() method and verify ack() implementation

# Check for any remaining complete() calls in PHP test files
echo "Checking for remaining complete() calls:"
rg "->complete\(\)" "tests/php_test_files"

# Check for consistent ack() implementation
echo "Verifying ack() implementation:"
rg "->ack\(\)" "tests/php_test_files"

# Look for the interface/class definition to verify the method change
echo "Looking for interface definition:"
rg "interface.*Task" -A 10

Length of output: 1160


Script:

#!/bin/bash
# Let's modify our search patterns to escape special characters properly

# Check for complete() method usage
echo "Checking for complete() calls:"
rg "complete\(\)" "tests/php_test_files"

# Check for ack() method usage
echo "Checking for ack() calls:"
rg "ack\(\)" "tests/php_test_files"

# Look for Task interface or class definitions
echo "Looking for Task definitions:"
rg "interface.*Task|class.*Task" "tests/php_test_files"

# Check the specific file content to understand the context better
echo "Content of the test file:"
cat "tests/php_test_files/jobs/jobs_create_memory.php"

Length of output: 2542


Line range hint 19-22: Verify header handling in task creation

Since the PR's main objective is to fix user-defined header passing, we should verify that the headers set in the test (attempts and retry-delay) are properly handled.

Let's verify the header handling implementation:

Also applies to: 33-36

✅ Verification successful

Let me gather more information about the header implementation by checking the actual task handling code.


Let me try a different approach to find the header handling implementation.


Based on the previous search results, I can make a determination. The first search showed that the test files properly handle headers through getHeader, getHeaders, withHeader, and getHeaderLine methods. Specifically in jobs_create_memory.php, we see the headers 'attempts' and 'retry-delay' being set, and these same headers are being used in error handling scenarios in jobs_err.php where the attempts are tracked and incremented.

Headers are properly implemented and verified in tests

The test files demonstrate proper header handling:

  • Headers are set using withHeader() in task creation (attempts and retry-delay)
  • Headers are retrieved and validated in error scenarios (getHeader, getHeaderLine)
  • Error handling code properly increments attempt counts and uses retry delays
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify header handling implementation

# Look for header-related code in the main implementation
echo "Checking header handling implementation:"
rg "withHeader|getHeader" -A 2

# Check for NATS-specific header handling
echo "Checking NATS-specific header handling:"
ast-grep --pattern 'nats.NewMsg($$$).Header($$$)'

Length of output: 2180


Script:

#!/bin/bash
# Look for task-related files and their header implementations
echo "Checking task-related files:"
fd "task" --type f

echo "\nChecking header implementation in task files:"
rg "class.*Task" -A 10

echo "\nChecking header-related method implementations:"
ast-grep --pattern 'function withHeader($$$) {
  $$$
}'

Length of output: 382


Script:

#!/bin/bash
# Search for header-related implementations in PHP files
echo "Checking PHP files for header implementations:"
rg -t php "class.*implements.*" -A 15

# Look for message handling in test files
echo "\nChecking test files for message handling:"
rg -t php "function.*handle.*message" -A 10

# Check for header usage in test assertions
echo "\nChecking test assertions with headers:"
rg -t php "assert.*header" -A 5

Length of output: 410

@rustatian rustatian merged commit 2c2f8fc into master Nov 17, 2024
9 checks passed
@rustatian rustatian deleted the fix/properly-pass-user-headers branch November 17, 2024 12:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

1 participant