Skip to content

Conversation

@Hemil36
Copy link
Contributor

@Hemil36 Hemil36 commented Sep 11, 2025

Fixes : #506
This pull request updates the logic for starting the FastAPI development server in the _start_fastapi_service function to support both Windows and non-Windows platforms. The most important change is the introduction of platform-specific commands to ensure compatibility.

Platform compatibility improvements:

  • Updated _start_fastapi_service in backend/app/utils/microservice.py to use a different command for Windows—running uvicorn directly instead of fastapi dev—to properly start the FastAPI app across operating systems.
  • Added a log statement to provide visibility into the exact command being executed when starting the service.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of background service startup across platforms, ensuring the app restores its working directory after startup or on failure to prevent side effects.
  • Chores

    • Enhanced startup logging with the executed command, process ID, and service URL; more consistent non-blocking startup behavior and clearer logs for troubleshooting.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 11, 2025

Walkthrough

Start-up logic for the FastAPI/sync microservice was revised to use OS-specific commands (Windows uses uvicorn with host 127.0.0.1:8001 and --reload), introduce host/port variables, log the exact command/PID/URL, remove a debug print, preserve non-blocking subprocess.Popen startup, and ensure original CWD is restored on success or error.

Changes

Cohort / File(s) Summary
Microservice startup & sync helpers
backend/app/utils/microservice.py
- start_fastapi_service now sets host/port, selects an OS-specific command (Windows: uvicorn main:app --host 127.0.0.1 --port 8001 --reload; non-Windows: existing dev command on port 8001), logs the full command before execution, starts the process non-blocking with subprocess.Popen, logs PID and service URL, and restores original CWD on success or error.
- Removed debug print of Python executable; preserved non-blocking startup and error-path CWD restoration.
- Minor path/venv and working-directory handling adjustments remain limited to start logic.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Microservice as microservice.py
  participant OS as subprocess / shell
  participant FastAPI as Service

  Caller->>Microservice: request start (dev/frozen/fastapi)
  Microservice->>Microservice: resolve paths, venv (if dev), host/port
  Microservice->>Microservice: pick OS-specific command (uvicorn on Windows)
  Microservice->>OS: Popen(cmd..., cwd=target_dir, ...)
  Microservice->>Microservice: logger.info(command), logger.info(PID/URL)
  OS-->>FastAPI: process starts (non-blocking)
  Microservice->>Microservice: restore original CWD (success/error)
  Microservice-->>Caller: return process handle / info
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bug

Pre-merge checks (3 passed)

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix: update FastAPI command for Windows compatibility" succinctly and accurately summarizes the PR's primary change—adjusting the FastAPI/uvicorn startup command to support Windows—matching the raw summary and PR objectives without extraneous noise.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

Poem

I hop and nudge the startup log tonight,
uvicorn on Windows, dev on other light.
PID and URL in tidy rows,
CWD returns where it grows.
A rabbit cheers — the service runs just right. 🐇✨


📜 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 7f67e8d and 7be0480.

📒 Files selected for processing (1)
  • backend/app/utils/microservice.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/app/utils/microservice.py
⏰ 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). (2)
  • GitHub Check: Tauri Tests
  • GitHub Check: Backend Tests
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
backend/app/utils/microservice.py (2)

242-242: Log the args list instead of a space-joined string.

Safer and clearer for paths with spaces; also avoids unnecessary string building.

-        logger.info(f"Executing command: {' '.join(cmd)}")
+        logger.info("Executing command: %s", cmd)

245-245: Optional: avoid chdir by using Popen(cwd=...).

Keeps the function side-effect free and removes the need to restore cwd.

-        process = subprocess.Popen(cmd)
+        process = subprocess.Popen(cmd, cwd=str(service_path))

Additionally remove the os.chdir(service_path) and the subsequent restore. For example:

# Outside the selected range; illustrative:
original_cwd = os.getcwd()  # remove
os.chdir(service_path)      # remove
...
os.chdir(original_cwd)      # remove
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b10b16 and 1a1cecd.

📒 Files selected for processing (1)
  • backend/app/utils/microservice.py (1 hunks)
⏰ 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: Tauri Tests
🔇 Additional comments (1)
backend/app/utils/microservice.py (1)

235-237: No action required — uvicorn present in sync-microservice requirements.

uvicorn==0.35.0 and fastapi==0.116.1 are declared in sync-microservice/requirements.txt (also present in backend/requirements.txt).

@Hemil36 Hemil36 marked this pull request as draft September 11, 2025 08:54
@Hemil36 Hemil36 marked this pull request as ready for review September 11, 2025 09:17
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (3)
backend/app/utils/microservice.py (3)

257-261: Add --host and reuse port var for non-Windows for parity and least exposure.

Explicitly bind to 127.0.0.1 (as in Windows branch) and reuse the host/port vars.

-            cmd = [str(python_executable), "-m", "fastapi", "dev", "--port", "8001"]
+            cmd = [
+                str(python_executable),
+                "-m",
+                "fastapi",
+                "dev",
+                "--host",
+                host,
+                "--port",
+                port,
+            ]

82-88: Same stdout/stderr pipe issue in frozen mode.

Inherit stdio or silence; don’t leave pipes unread.

-        process = subprocess.Popen(
-            [str(sync_executable)],
-            stdout=subprocess.PIPE,
-            stderr=subprocess.PIPE,
-            text=True,
-            cwd=str(sync_dir),  # Set working directory to sync service directory
-        )
+        process = subprocess.Popen([str(sync_executable)], cwd=str(sync_dir))

264-266: Don’t pipe stdout/stderr without consumers; risk of deadlock/blocking.

The child can block when pipe buffers fill. Inherit parent stdio (default) or use DEVNULL.

-        process = subprocess.Popen(
-            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
-        )
+        process = subprocess.Popen(cmd, cwd=str(service_path))
🧹 Nitpick comments (4)
backend/app/utils/microservice.py (4)

235-237: Avoid process-wide chdir; pass cwd to Popen instead.

Reduces side effects and race potential in multi-threaded contexts.

-        original_cwd = os.getcwd()
-        os.chdir(service_path)
+        # Launch with cwd set in Popen to avoid global chdir
@@
-        # Restore original working directory
-
-        os.chdir(original_cwd)
+        # cwd provided via Popen; no restoration needed
@@
-        # Restore original working directory in case of error
-
-        try:
-            os.chdir(original_cwd)
-        except Exception:
-            pass
+        # No global cwd change to revert

Also applies to: 268-271, 280-284


272-274: Log dynamic URL using host/port variables.

Keeps logs consistent if config changes.

-        logger.info("Service should be available at http://localhost:8001")
+        logger.info(f"Service should be available at http://{host}:{port}")

262-266: Optional: verify service readiness before returning True.

Consider a short retry loop to check the port is open/alive; avoids false “started” signals if the child crashes immediately.

Example (outside this hunk):

import socket, time

def _wait_for_port(host: str, port: int, timeout_s: int = 10) -> bool:
    deadline = time.time() + timeout_s
    while time.time() < deadline:
        with socket.socket() as s:
            s.settimeout(0.5)
            if s.connect_ex((host, port)) == 0:
                return True
        time.sleep(0.2)
    return False

Then call _wait_for_port(host, int(port)) and log success/failure.

Also applies to: 272-275


136-141: Proceeding after failed dependency install may just defer failure.

If requirements installation fails, consider surfacing failure early or at least warn with actionable hint (e.g., “ensure fastapi[standard] or uvicorn is installed”).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1a1cecd and 7f67e8d.

📒 Files selected for processing (1)
  • backend/app/utils/microservice.py (6 hunks)
⏰ 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: Tauri Tests
🔇 Additional comments (3)
backend/app/utils/microservice.py (3)

242-256: Windows path: Good switch to uvicorn with localhost and reload.

This addresses the Windows incompatibility and aligns dev ergonomics.


182-190: Venv Python resolution looks correct across OSes.


139-141: Verified: FastAPI (>=0.100) and uvicorn present in requirements

requirements file /home/jailuser/git/sync-microservice/requirements.txt contains fastapi==0.116.1, fastapi-cli==0.0.8, fastapi-cloud-cli==0.1.5, uvicorn==0.35.0, watchfiles==1.1.0 — no changes required.

@rahulharpal1603 rahulharpal1603 merged commit d71a3e7 into AOSSIE-Org:main Sep 12, 2025
5 checks passed
@rahulharpal1603
Copy link
Contributor

Thank you @Hemil36!

@Hemil36 Hemil36 deleted the Sync-microservice-windows-issue branch September 22, 2025 06:15
@rahulharpal1603 rahulharpal1603 added bug Something isn't working backend labels Sep 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Sync Microservice Fails to Start on Windows

2 participants