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

CLI 2024: Re-add command line interface #549

Merged
merged 6 commits into from
Jan 18, 2025
Merged

CLI 2024: Re-add command line interface #549

merged 6 commits into from
Jan 18, 2025

Conversation

amotl
Copy link
Collaborator

@amotl amotl commented Oct 25, 2024

About

The CLI interface got lost. This patch intends to bring it back.

After refactoring, the CLI module is living at responder.ext.cli now.

Setup

From now on, the CLI interface is optional, and its docopt-ng dependency needs to be installed explicitly.

pip install --upgrade 'responder[cli]'

Usage

The feature will also sport a dedicated documentation page now, see preview at Responder CLI.

Software Tests

Previously, the CLI module apparently had no software tests. Now, the two major subcommand operations build vs. run are covered, mostly on their happy paths.

Copy link

coderabbitai bot commented Oct 25, 2024

Warning

Rate limit exceeded

@amotl has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 939e673 and 6aaad8e.

⛔ Files ignored due to path filters (1)
  • .github/workflows/test.yaml is excluded by !**/*.yaml
📒 Files selected for processing (6)
  • responder/__init__.py (1 hunks)
  • responder/api.py (2 hunks)
  • responder/ext/cli.py (1 hunks)
  • responder/util/cmd.py (1 hunks)
  • setup.py (2 hunks)
  • tests/test_cli.py (1 hunks)

Walkthrough

The changes in this pull request involve updates to the Responder framework's package configuration, installation instructions, and documentation. Key modifications include the addition of a console script entry point in setup.py, enhancements to the README.md for installation commands, and the introduction of a new CLI section in the documentation. Additionally, several test cases have been added to validate CLI commands, and new utility functions have been introduced for server management and dynamic module loading.

Changes

File Change Summary
setup.py Added entry_points for console script and extras_require for cli.
README.md Updated installation commands and added a new command for CLI and GraphQL support.
tests/test_cli.py Enhanced with new tests for CLI commands and added a module-level docstring.
docs/source/cli.rst Added detailed instructions for using the Responder CLI, including launching applications and building JavaScript apps.
docs/source/index.rst Introduced a new entry for the CLI guide in the documentation's table of contents.
examples/helloworld.py Added an example HTTP service with a simple asynchronous route handler.
responder/api.py Modified serve method to manage logging configuration and simplify uvicorn.run invocation.
responder/util/cmd.py Introduced classes ResponderProgram and ResponderServer for command execution and server management.
responder/util/python.py Added functions for loading targets and modules dynamically.
tests/util.py Introduced utility functions for generating random ports and waiting for server responses.
.gitignore Updated to ignore coverage report files.
responder/__init__.py Added a module-level docstring describing the Responder framework.
responder/ext/cli.py Introduced a new CLI with commands for running the server and building assets.

Possibly related PRs

  • Chore: Format code using Ruff, and fix linter errors #531: The changes in this PR involve modifications to the setup.py file, specifically related to the extras_require dictionary and the addition of an entry point, which directly relates to the changes made in the main PR that also modifies setup.py for similar purposes.
  • CI: Run link checker and build documentation as GHA workflow #557: This PR updates the README.md file to enhance installation instructions, which aligns with the main PR's changes to the README.md for installation commands, indicating a focus on improving user guidance for package installation.

Suggested labels

ci and infrastructure

Suggested reviewers

  • kennethreitz
  • tabotkevin

Poem

🐇 In the meadow, changes bloom,
Responder's CLI finds its room.
With commands to run and build with glee,
A rabbit hops, "Oh, come see!"
Installation made simple, clear as day,
Let's greet the world, hip-hip-hooray! 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

setup.py Outdated
@@ -20,7 +20,9 @@
required = [
"aiofiles",
"apispec>=1.0.0b1",
"asgiref",
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

What's asgiref for in this context? Can it be removed?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed again.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Does anyone know why this would be needed?

@amotl amotl changed the title CLI build command CLI build command (2024) Oct 25, 2024
@amotl amotl marked this pull request as ready for review October 25, 2024 23:03
coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl force-pushed the bring-back-cli branch 3 times, most recently from 2b58380 to 5be3422 Compare October 26, 2024 01:59
coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl force-pushed the bring-back-cli branch 2 times, most recently from 6b69a75 to 703720b Compare October 26, 2024 13:37
coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl force-pushed the bring-back-cli branch 2 times, most recently from f724117 to e61876a Compare October 26, 2024 19:19
@amotl amotl changed the title CLI build command (2024) CLI: Re-add command line subsystem (2024) Oct 26, 2024
@amotl amotl changed the title CLI: Re-add command line subsystem (2024) CLI: Re-add command line interface (2024) Oct 26, 2024
coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl mentioned this pull request Oct 27, 2024
coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl added feature New feature or request qa and testing Quality assurance and software testing documentation Documentation: Content and Infrastructure labels Oct 27, 2024
coderabbitai[bot]

This comment was marked as resolved.

@amotl amotl force-pushed the bring-back-cli branch 2 times, most recently from d4b7544 to d6133ce Compare October 28, 2024 08:58
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (4)
tests/util.py (2)

59-101: Consider adding debug logging for error cases.

While the error handling is robust, adding debug logs for specific error cases would aid in troubleshooting.

Consider this enhancement:

             if error_number in transient_socket_error_numbers():
+                logger.debug(f"Ignoring transient error {error_number} while connecting to {endpoint}")
                 pass

             # Unexpected error.
             else:
+                logger.debug(f"Encountered unexpected error {error_number} while connecting to {endpoint}")
                 raise RuntimeError(
                     f"Unexpected error while connecting to {endpoint}: {error_number}"
                 )

103-135: Consider adding debug logging for consistency with wait_server_tcp.

For consistency with wait_server_tcp, consider adding similar debug logging.

Consider this enhancement:

     url = f"{protocol}://{host}:{port}/"
+    logger.debug(f"Waiting for endpoint: {url}")
     for attempt in range(1, attempts + 1):
         try:
             requests.get(url, timeout=delay / 2)  # Shorter timeout for connection
             break
         except requests.exceptions.RequestException:
+            logger.debug(f"Connection attempt {attempt}/{attempts} failed for {url}")
             if attempt < attempts:  # Don't sleep on last attempt
                 time.sleep(delay)
responder/ext/cli.py (1)

33-46: Consider reorganizing imports for better readability.

The imports could be better organized following the common pattern: standard library, third-party packages, and local imports, each group separated by a blank line.

-import logging
-import platform
-import subprocess
-import sys
-import typing as t
-from pathlib import Path
-
-import docopt
-
-from responder.__version__ import __version__
-from responder.util.python import InvalidTarget, load_target

+import logging
+import platform
+import subprocess
+import sys
+import typing as t
+from pathlib import Path
+
+import docopt
+
+from responder.__version__ import __version__
+from responder.util.python import InvalidTarget, load_target
responder/util/cmd.py (1)

170-198: Consider closing socket explicitly in wait_until_ready.

The socket connection test uses a context manager, but it's good practice to explicitly close the socket to ensure immediate resource release, especially in a loop.

-            try:
-                with socket.create_connection(
-                    ("localhost", self.port), timeout=request_timeout
-                ):
-                    return True
+            sock = None
+            try:
+                sock = socket.create_connection(
+                    ("localhost", self.port), timeout=request_timeout
+                )
+                return True
             except (
                 socket.timeout,
                 ConnectionRefusedError,
                 socket.gaierror,
                 OSError,
             ) as ex:
                 logger.debug(f"Server not ready yet: {ex}")
                 time.sleep(delay)
+            finally:
+                if sock:
+                    sock.close()
🛑 Comments failed to post (3)
tests/util.py (1)

21-34: 🛠️ Refactor suggestion

Consider enhancing error handling for socket operations.

While the implementation is solid, it could benefit from more specific error handling.

Consider this enhancement:

 def random_port() -> int:
     sock = socket.socket()
     try:
         sock.bind(("", 0))
         return sock.getsockname()[1]
+    except socket.error as e:
+        raise RuntimeError(f"Failed to allocate random port: {e}") from e
     finally:
         sock.close()
📝 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.

def random_port() -> int:
    """
    Return a random available port by binding to port 0.

    Returns:
        int: An available port number that can be used for testing.
    """
    sock = socket.socket()
    try:
        sock.bind(("", 0))
        return sock.getsockname()[1]
    except socket.error as e:
        raise RuntimeError(f"Failed to allocate random port: {e}") from e
    finally:
        sock.close()
responder/ext/cli.py (1)

106-111: 🛠️ Refactor suggestion

Consider using a custom exception for CLI errors.

Instead of raising a generic ValueError, consider creating a custom exception like CLIError that better represents the domain-specific error condition. This would make it easier to handle CLI-specific errors differently from other value errors.

+class CLIError(Exception):
+    """Raised when CLI encounters an error condition."""
+    pass

-            raise ValueError(
+            raise CLIError(
                 f"{ex}. "
                 "Use either a Python module entrypoint specification, "
                 "a filesystem path, or a remote URL. "
                 "See also https://responder.kennethreitz.org/cli.html."
             ) from ex

Committable suggestion was skipped due to low confidence.

responder/util/cmd.py (1)

25-40: 🛠️ Refactor suggestion

Consider caching the program path.

The path() method searches PATH on every call. Consider caching the result to improve performance.

 class ResponderProgram:
+    _cached_path = None
+
     @staticmethod
     def path():
+        if ResponderProgram._cached_path is not None:
+            return ResponderProgram._cached_path
+
         name = "responder"
         if sys.platform == "win32":
             name = "responder.exe"
         program = shutil.which(name)
         if program is None:
             paths = os.environ.get("PATH", "").split(os.pathsep)
             raise RuntimeError(
                 f"Could not find '{name}' executable in PATH. "
                 f"Please ensure Responder is installed correctly. "
                 f"Searched in: {', '.join(paths)}"
             )
         logger.debug(f"Found responder program: {program}")
+        ResponderProgram._cached_path = program
         return program

Committable suggestion was skipped due to low confidence.

Copy link
Collaborator Author

@amotl amotl left a comment

Choose a reason for hiding this comment

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

A few more comments from a self-review.

Comment on lines +6 to +8
Commands:
run Start the application server
build Build frontend assets using npm
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@kennethreitz: Now after learning it, I think the second subcommand responder build is debatable. Did you keep and/or evolve it within Dyne, @tabotkevin?

amotl and others added 3 commits January 18, 2025 21:11
The `debug` argument no longer exists. Let's adjust the `log_level` to
`debug` instead.
Install: pip install 'responder[cli]'

The CLI is an optional subsystem from now on.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
setup.py (1)

Line range hint 122-141: Consider line length compliance.

The test requirements line exceeds the 90-character limit.

-        "test": ["flask", "mypy", "pytest", "pytest-cov", "pytest-mock", "pytest-rerunfailures"],
+        "test": [
+            "flask",
+            "mypy",
+            "pytest",
+            "pytest-cov",
+            "pytest-mock",
+            "pytest-rerunfailures",
+        ],
🧰 Tools
🪛 Ruff (0.8.2)

141-141: Line too long (97 > 90)

(E501)

responder/util/cmd.py (4)

26-41: Consider caching the responder path.

The path() method searches PATH on every call. Consider caching the result to improve performance.

 class ResponderProgram:
+    _cached_path = None
+
     @staticmethod
     def path():
+        if ResponderProgram._cached_path is not None:
+            return ResponderProgram._cached_path
+
         name = "responder"
         if sys.platform == "win32":
             name = "responder.exe"
         program = shutil.which(name)
         if program is None:
             paths = os.environ.get("PATH", "").split(os.pathsep)
             raise RuntimeError(
                 f"Could not find '{name}' executable in PATH. "
                 f"Please install Responder with 'pip install --upgrade responder[cli]'. "
                 f"Searched in: {', '.join(paths)}"
             )
         logger.debug(f"Found responder program: {program}")
+        ResponderProgram._cached_path = program
         return program

137-142: Add process synchronization.

The process management between run() and stop() methods could have race conditions. Consider adding a lock:

 def __init__(self, target: str, port: int = 5042, limit_max_requests: int = None):
     # ... existing code ...
     self.daemon = True
+    self._process_lock = threading.Lock()

 def run(self):
     # ... command setup ...
+    with self._process_lock:
         self.process = subprocess.Popen(
             command,
             env=env,
             universal_newlines=True,
         )
         self.process.wait()

 def stop(self):
+    with self._process_lock:
         if self.process and self.process.poll() is None:
             self.process.terminate()

171-204: Improve server readiness detection error handling.

The wait_until_ready method could benefit from more detailed error reporting:

     def wait_until_ready(self, timeout=30, request_timeout=1, delay=0.1) -> bool:
         start_time = time.time()
+        last_error = None
         while time.time() - start_time < timeout:
             if not self.is_running():
                 if self.process is None:
                     logger.error("Server process was never started")
                 else:
                     returncode = self.process.poll()
                     logger.error("Server process exited with code: %d", returncode)
                 return False
             try:
                 with socket.create_connection(
                     ("localhost", self.port), timeout=request_timeout
                 ):
                     return True
             except (socket.timeout, ConnectionRefusedError, socket.gaierror, OSError) as ex:
+                last_error = ex
                 logger.debug(f"Server not ready yet: {ex}")
                 time.sleep(delay)
+        logger.error("Server failed to start within %d seconds. Last error: %s", timeout, last_error)
         return False

94-121: Consider adding port availability check.

The server initialization could check if the port is available before starting:

     def __init__(self, target: str, port: int = 5042, limit_max_requests: int = None):
         # ... validation code ...
         if not isinstance(port, int) or port < 1:
             raise ValueError("Port must be a positive integer")
+        # Check if port is available
+        try:
+            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+                s.bind(('localhost', port))
+        except OSError:
+            raise ValueError(f"Port {port} is already in use")
responder/ext/cli.py (1)

63-84: Consider enhancing build feedback.

The build command implementation is secure and robust. Consider adding progress indicators:

 try:
+    logger.info("Starting frontend asset build...")
     # # S603, S607 are addressed by validating the target directory.
     subprocess.check_call(  # noqa: S603, S607
         [npm_cmd, "run", "build"],
         cwd=target_path,
         timeout=300,
     )
+    logger.info("Frontend asset build completed successfully")
 except FileNotFoundError:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4b7544 and 8e4fab2.

⛔ Files ignored due to path filters (2)
  • .github/workflows/test.yaml is excluded by !**/*.yaml
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (13)
  • .gitignore (1 hunks)
  • README.md (1 hunks)
  • docs/source/cli.rst (1 hunks)
  • docs/source/index.rst (1 hunks)
  • examples/helloworld.py (1 hunks)
  • responder/__init__.py (1 hunks)
  • responder/api.py (1 hunks)
  • responder/ext/cli.py (1 hunks)
  • responder/util/cmd.py (1 hunks)
  • responder/util/python.py (1 hunks)
  • setup.py (2 hunks)
  • tests/test_cli.py (1 hunks)
  • tests/util.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • responder/init.py
  • .gitignore
  • docs/source/index.rst
  • examples/helloworld.py
  • responder/api.py
  • docs/source/cli.rst
  • README.md
🧰 Additional context used
📓 Learnings (4)
tests/util.py (2)
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/util.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the `wait_server_tcp` function in `tests/util.py`, include all relevant socket error numbers that represent transient errors to handle cross-platform differences and ensure robust error handling.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/util.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the `tests/util.py` file, when handling socket errors in the `wait_server_tcp` function, include Windows-specific error code `10035` (WSAEWOULDBLOCK) along with `errno.ECONNREFUSED` and `errno.ETIMEDOUT` to properly handle expected socket errors on Windows systems.
responder/ext/cli.py (2)
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/ext/cli.py:99-101
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder framework, error checking for API loading is already implemented within the `load_target` function in `responder/util/python.py`. Additional error handling in the CLI is unnecessary.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/cli.py:76-78
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In `responder/cli.py`, the `load_target()` function already includes error handling for API server initialization, handling import errors and attribute errors when loading the target module and its properties. Therefore, additional error handling in the `cli()` function after calling `load_target()` is unnecessary.
tests/test_cli.py (5)
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:153-159
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder codebase (Python), the `wait_server_tcp` function in `tests/util.py` already implements error checking based on socket error numbers. Avoid suggesting additional error handling for socket errors in tests that use this function, such as `test_cli_run` in `tests/test_cli.py`.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:153-159
Timestamp: 2024-11-12T09:17:41.000Z
Learning: Programming suggestions derived from inline comments may not be applicable or practical; avoid providing such suggestions in future reviews.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:67-86
Timestamp: 2024-11-12T09:17:41.000Z
Learning: Input validation for the `responder_build` function is already handled in `cli.py`, so we should avoid adding duplicate validation in `tests/test_cli.py`.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: When testing server startup in scenarios where only a single request is allowed before the server shuts down, avoid relying on specific log messages or sending probing HTTP requests. Instead, check if the server's port is open to confirm readiness.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:148-148
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In tests where the server is configured to self-terminate after processing a single request, using an HTTP-based probing mechanism to check server readiness is not feasible, as it would consume the single allowed request and cause the test to fail. In such cases, using a fixed sleep duration is acceptable.
responder/util/cmd.py (4)
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:34-63
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder project, a timeout for the `responder build` command is already implemented in `responder/ext/cli.py`, so adding a timeout in `ResponderProgram.build` in `responder/util/cmd.py` is unnecessary.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:34-63
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In `responder/util/cmd.py`, the `build` method doesn't need to capture `stdout` and `stderr` from the subprocess because `npm` output is already forwarded to the terminal.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:102-123
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the test suite, the function `wait_server_tcp` in `tests/util.py` provides server readiness detection.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: When using the `ResponderServer` class in tests, intermittent stalling may occur on CI/GitHub Actions; further investigation is needed to resolve this issue.
🪛 Ruff (0.8.2)
setup.py

141-141: Line too long (97 > 90)

(E501)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Full: Python pypy3.10 on windows-latest
🔇 Additional comments (19)
tests/util.py (5)

1-6: LGTM! Well-documented module purpose.

The module docstring clearly explains the purpose and functionality of the utility functions.


21-33: LGTM! Clean implementation of random port allocation.

The function properly handles socket cleanup using a try-finally block and provides clear documentation.


36-56: LGTM! Robust cross-platform error handling.

The function effectively handles both Unix and Windows socket error codes, with clear documentation and proper use of @lru_cache.


59-100: LGTM! Comprehensive server readiness checking.

The implementation includes:

  • Proper timeout handling
  • Socket error handling for cross-platform compatibility
  • Clear error messages

103-135: LGTM! Well-structured HTTP server checking.

The implementation includes:

  • Proper timeout and delay configuration
  • Clear error messages with attempt counts
  • Efficient request handling
responder/util/python.py (3)

13-23: LGTM! Well-defined custom exception.

The InvalidTarget exception includes clear documentation about its purpose and usage scenarios.


25-92: LGTM! Comprehensive target loading implementation.

The function includes:

  • Thorough input validation
  • Clear error messages
  • Proper attribute checking
  • Comprehensive error handling

94-133: LGTM! Robust module loading with proper cleanup.

The implementation includes:

  • File extension validation
  • Unique module naming using UUID
  • Proper cleanup in sys.modules
  • Specific error handling for different scenarios
setup.py (1)

117-117: LGTM! Proper CLI entry point configuration.

The entry point correctly maps the responder command to the CLI implementation.

tests/test_cli.py (5)

1-14: LGTM! Clear test module documentation.

The module docstring effectively documents:

  • Test coverage scope
  • Requirements
  • Expected application behavior

36-46: LGTM! Environment-configurable timeouts.

Good practice to make timeouts configurable via environment variables for CI/CD flexibility.


113-135: LGTM! Comprehensive build error testing.

The parameterized test effectively covers various invalid JSON scenarios with clear test IDs.


153-159: LGTM! Well-documented flaky test configuration.

The comment clearly explains:

  • Why the test is marked as flaky
  • Platform-specific error codes
  • Expected error messages

194-212: LGTM! Thorough server lifecycle verification.

The implementation effectively:

  • Defines expected lifecycle messages
  • Verifies message order
  • Provides clear failure messages
responder/util/cmd.py (1)

1-18: Well-documented security considerations!

The security documentation clearly outlines the key security measures for subprocess usage, and the imports are well-organized.

responder/ext/cli.py (4)

1-46: Well-structured documentation and imports!

The docstring is comprehensive and follows best practices, with clear sections for commands, usage, options, arguments, and examples. Import organization is clean and logical.


48-61: Clean implementation with proper type hints!

The CLI function is well-structured with clear documentation and appropriate type hints.


85-114: Robust implementation with proper validation!

The run command implementation includes thorough validation and error handling. The use of load_target for API loading is appropriate as it already includes comprehensive error handling.


117-127: Simple and effective logging configuration!

The logging setup is straightforward and meets the current needs of the application.

@amotl amotl changed the title CLI: Re-add command line interface (2024) CLI 2024: Re-add command line interface Jan 18, 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: 0

🧹 Nitpick comments (2)
responder/util/cmd.py (1)

22-25: Consider enhancing the class docstring.

The current docstring could be more descriptive by including:

  • The purpose of the class beyond just providing the path
  • Available methods and their high-level functionality
  • Usage examples
 class ResponderProgram:
     """
-    Provide full path to the `responder` program.
+    Utility class for managing Responder program execution.
+
+    This class provides methods for:
+    - Locating the responder executable in PATH
+    - Building frontend assets using npm
+
+    Example:
+        >>> program_path = ResponderProgram.path()
+        >>> build_status = ResponderProgram.build(Path("app_dir"))
     """
responder/ext/cli.py (1)

63-86: Consider adding build progress feedback.

While the build command implementation is secure and handles errors well, it could benefit from more user feedback:

  1. Log when build starts
  2. Log when build completes successfully
 if build:
     target_path = Path(target).resolve() if target else Path.cwd()
     if not target_path.is_dir() or not (target_path / "package.json").exists():
         logger.error(f"Invalid target directory or missing package.json: {target_path}")
         sys.exit(1)
     npm_cmd = "npm.cmd" if platform.system() == "Windows" else "npm"
     try:
+        logger.info("Starting frontend asset build")
         # S603, S607 are addressed by validating the target directory.
         subprocess.check_call(  # noqa: S603, S607
             [npm_cmd, "run", "build"],
             cwd=target_path,
             timeout=300,
         )
+        logger.info("Frontend asset build completed successfully")
     except FileNotFoundError:
         logger.error("npm not found. Please install Node.js and npm.")
         sys.exit(1)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 484dddd and 939e673.

⛔ Files ignored due to path filters (1)
  • .github/workflows/test.yaml is excluded by !**/*.yaml
📒 Files selected for processing (6)
  • responder/__init__.py (1 hunks)
  • responder/api.py (2 hunks)
  • responder/ext/cli.py (1 hunks)
  • responder/util/cmd.py (1 hunks)
  • setup.py (2 hunks)
  • tests/test_cli.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • responder/init.py
  • responder/api.py
  • setup.py
🧰 Additional context used
📓 Learnings (3)
responder/ext/cli.py (2)
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/ext/cli.py:99-101
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder framework, error checking for API loading is already implemented within the `load_target` function in `responder/util/python.py`. Additional error handling in the CLI is unnecessary.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/cli.py:76-78
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In `responder/cli.py`, the `load_target()` function already includes error handling for API server initialization, handling import errors and attribute errors when loading the target module and its properties. Therefore, additional error handling in the `cli()` function after calling `load_target()` is unnecessary.
tests/test_cli.py (5)
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:153-159
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder codebase (Python), the `wait_server_tcp` function in `tests/util.py` already implements error checking based on socket error numbers. Avoid suggesting additional error handling for socket errors in tests that use this function, such as `test_cli_run` in `tests/test_cli.py`.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:153-159
Timestamp: 2024-11-12T09:17:41.000Z
Learning: Programming suggestions derived from inline comments may not be applicable or practical; avoid providing such suggestions in future reviews.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:67-86
Timestamp: 2024-11-12T09:17:41.000Z
Learning: Input validation for the `responder_build` function is already handled in `cli.py`, so we should avoid adding duplicate validation in `tests/test_cli.py`.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: When testing server startup in scenarios where only a single request is allowed before the server shuts down, avoid relying on specific log messages or sending probing HTTP requests. Instead, check if the server's port is open to confirm readiness.
Learnt from: amotl
PR: kennethreitz/responder#549
File: tests/test_cli.py:148-148
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In tests where the server is configured to self-terminate after processing a single request, using an HTTP-based probing mechanism to check server readiness is not feasible, as it would consume the single allowed request and cause the test to fail. In such cases, using a fixed sleep duration is acceptable.
responder/util/cmd.py (4)
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:34-63
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the Responder project, a timeout for the `responder build` command is already implemented in `responder/ext/cli.py`, so adding a timeout in `ResponderProgram.build` in `responder/util/cmd.py` is unnecessary.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:34-63
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In `responder/util/cmd.py`, the `build` method doesn't need to capture `stdout` and `stderr` from the subprocess because `npm` output is already forwarded to the terminal.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:102-123
Timestamp: 2024-11-12T09:17:41.000Z
Learning: In the test suite, the function `wait_server_tcp` in `tests/util.py` provides server readiness detection.
Learnt from: amotl
PR: kennethreitz/responder#549
File: responder/util/cmd.py:0-0
Timestamp: 2024-11-12T09:17:41.000Z
Learning: When using the `ResponderServer` class in tests, intermittent stalling may occur on CI/GitHub Actions; further investigation is needed to resolve this issue.
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Full: Python pypy3.10 on windows-latest
  • GitHub Check: Full: Python 3.13 on windows-latest
  • GitHub Check: Full: Python 3.12 on windows-latest
  • GitHub Check: Full: Python 3.9 on windows-latest
  • GitHub Check: Full: Python 3.8 on windows-latest
  • GitHub Check: Full: Python 3.6 on windows-latest
  • GitHub Check: Full: Python 3.13 on macos-latest
  • GitHub Check: Full: Python 3.12 on macos-latest
  • GitHub Check: Full: Python 3.9 on macos-latest
  • GitHub Check: Full: Python 3.8 on macos-latest
  • GitHub Check: Full: Python 3.7 on macos-13
  • GitHub Check: Full: Python pypy3.10 on ubuntu-20.04
🔇 Additional comments (19)
responder/util/cmd.py (7)

1-20: Well-documented security considerations!

The security comments clearly explain the rationale behind the noqa directives and outline the security measures taken for subprocess usage.


27-42: Excellent implementation of the path method!

The implementation includes:

  • Proper caching using @functools.lru_cache
  • Platform-specific executable name handling
  • Informative error message with installation instructions and searched paths

44-73: Well-structured build method with comprehensive validation!

The implementation includes:

  • Thorough input validation
  • Well-documented API with Args, Returns, and Raises sections
  • Clear error messages

76-131: Excellent class design and initialization!

The implementation includes:

  • Comprehensive docstring with description, args, and examples
  • Thorough input validation
  • Port availability check
  • Proper signal handler setup
  • Thread safety with process lock

132-153: Well-implemented run method with proper environment handling!

The implementation includes:

  • Correct command construction
  • Environment preservation
  • Thread-safe process management

155-187: Robust process termination implementation!

The implementation includes:

  • Protection against multiple stop attempts
  • Graceful shutdown with timeout
  • Proper signal handling
  • Informative logging

189-234: Comprehensive server status monitoring!

The implementation includes:

  • Detailed server readiness checking
  • Proper error handling and logging
  • Process status verification

However, since intermittent stalling occurs on CI/GitHub Actions, consider adding more detailed logging about the process state during the readiness check:

responder/ext/cli.py (3)

1-44: Well-structured docstring and imports!

The docstring provides comprehensive documentation with clear sections for commands, usage, options, and examples. The imports are well-organized and necessary for the functionality.


87-116: LGTM! Proper error handling for the run command.

The run command implementation:

  1. Validates required target argument
  2. Handles limit_max_requests validation
  3. Uses load_target for API initialization
  4. Includes proper error handling

119-129: LGTM! Simple but effective logging configuration.

The logging setup includes all necessary components (timestamp, logger name, level, message) and adjusts the log level based on debug mode.

tests/test_cli.py (9)

1-34: LGTM! Clear test documentation and dependencies.

The module docstring clearly outlines:

  1. Test coverage for each CLI command
  2. Requirements and dependencies
  3. Expected application behavior

36-47: LGTM! Environment-configurable test settings.

Test timeouts and delays are:

  1. Configurable via environment variables
  2. Have reasonable default values
  3. Include clear comments explaining their purpose

49-64: LGTM! Clear version test implementation.

The test:

  1. Executes the version command
  2. Handles subprocess errors
  3. Verifies the output matches package version

67-86: LGTM! Well-documented build helper function.

The helper function:

  1. Has clear type hints
  2. Includes comprehensive docstring
  3. Returns captured output for verification

88-101: LGTM! Clear success case test.

The test:

  1. Creates a valid package.json
  2. Verifies build output

103-111: LGTM! Error case handling for missing package.json.

The test verifies the appropriate error message when package.json is missing.


113-151: LGTM! Comprehensive invalid JSON test cases.

The parameterized test:

  1. Covers various JSON error scenarios
  2. Has clear test case identifiers
  3. Verifies appropriate error messages

153-159: LGTM! Well-documented flaky test configuration.

The test:

  1. Is marked as flaky with retries
  2. Documents platform-specific error codes

160-212: LGTM! Robust server test implementation.

The test:

  1. Uses proper server setup and cleanup
  2. Verifies HTTP response
  3. Checks server lifecycle messages in order

Note: This appears to be the first integration test for Responder, including its CLI interface, end-to-end.

@amotl amotl merged commit 1b63d29 into main Jan 18, 2025
36 checks passed
@amotl amotl deleted the bring-back-cli branch January 18, 2025 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Documentation: Content and Infrastructure feature New feature or request qa and testing Quality assurance and software testing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants