Skip to content

Commit

Permalink
Revert "[ENG-4005] Proxy backend requests on '/' to the frontend (#3300
Browse files Browse the repository at this point in the history
…)" (#4614)

This reverts commit 438b31f.
  • Loading branch information
masenf authored Jan 10, 2025
1 parent fe9c020 commit 427d7c5
Show file tree
Hide file tree
Showing 12 changed files with 15 additions and 782 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/integration_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,6 @@ jobs:
run: |
poetry run reflex export --backend-only
- name: Check run --backend-only before init for counter example
env:
WAIT_FOR_LISTENING_PORT_ARGS: --path ping
run: |
poetry run bash scripts/integration.sh ./reflex-examples/counter dev 8001 --backend-only --backend-port 8001
- name: Init Website for counter example
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/integration_tests_wsl.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ jobs:
shell: wsl-bash {0}
run: |
export TELEMETRY_ENABLED=false
export WAIT_FOR_LISTENING_PORT_ARGS="--path ping"
dos2unix scripts/integration.sh
poetry run bash scripts/integration.sh ./reflex-examples/counter dev 8001 --backend-only --backend-port 8001
- name: Init Website for counter example
Expand Down
575 changes: 5 additions & 570 deletions poetry.lock

Large diffs are not rendered by default.

5 changes: 0 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ setuptools = ">=75.0"
httpx = ">=0.25.1,<1.0"
twine = ">=4.0.0,<7.0"
tomlkit = ">=0.12.4,<1.0"
asgiproxy = { version = "==0.1.1", optional = true }
lazy_loader = ">=0.4"
reflex-chakra = ">=0.6.0"
typing_extensions = ">=4.6.0"
Expand All @@ -73,14 +72,10 @@ selenium = ">=4.11.0,<5.0"
pytest-benchmark = ">=4.0.0,<6.0"
playwright = ">=1.46.0"
pytest-playwright = ">=0.5.1"
asgiproxy = "==0.1.1"

[tool.poetry.scripts]
reflex = "reflex.reflex:cli"

[tool.poetry.extras]
proxy = ["asgiproxy"]

[build-system]
requires = ["poetry-core>=1.5.1"]
build-backend = "poetry.core.masonry.api"
Expand Down
6 changes: 0 additions & 6 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,12 +332,6 @@ def __post_init__(self):

self.register_lifespan_task(windows_hot_reload_lifespan_hack)

# Enable proxying to frontend server.
if not environment.REFLEX_BACKEND_ONLY.get():
from reflex.proxy import proxy_middleware

self.register_lifespan_task(proxy_middleware)

def _enable_state(self) -> None:
"""Enable state for the app."""
if not self.state:
Expand Down
5 changes: 0 additions & 5 deletions reflex/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@

from typing_extensions import Annotated, get_type_hints

from reflex.utils.console import set_log_level
from reflex.utils.exceptions import ConfigError, EnvironmentVarValueError
from reflex.utils.types import GenericType, is_union, value_inside_optional

Expand Down Expand Up @@ -600,7 +599,6 @@ class Config(Base):
class Config:
"""Pydantic config for the config."""

use_enum_values = False
validate_assignment = True

# The name of the app (should match the name of the app directory).
Expand Down Expand Up @@ -720,9 +718,6 @@ def __init__(self, *args, **kwargs):
self._non_default_attributes.update(kwargs)
self._replace_defaults(**kwargs)

# Set the log level for this process
set_log_level(self.loglevel)

if (
self.state_manager_mode == constants.StateManagerMode.REDIS
and not self.redis_url
Expand Down
119 changes: 0 additions & 119 deletions reflex/proxy.py

This file was deleted.

21 changes: 5 additions & 16 deletions reflex/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
import reflex.utils.prerequisites
import reflex.utils.processes
from reflex.config import environment
from reflex.proxy import proxy_middleware
from reflex.state import (
BaseState,
StateManager,
Expand Down Expand Up @@ -299,9 +298,6 @@ def _initialize_app(self):
self.state_manager = StateManagerRedis.create(self.app_instance.state)
else:
self.state_manager = self.app_instance._state_manager
# Disable proxy for app harness tests.
if proxy_middleware in self.app_instance.lifespan_tasks:
self.app_instance.lifespan_tasks.remove(proxy_middleware)

def _reload_state_module(self):
"""Reload the rx.State module to avoid conflict when reloading."""
Expand Down Expand Up @@ -369,12 +365,9 @@ async def _reset_backend_state_manager(self):
def _start_frontend(self):
# Set up the frontend.
with chdir(self.app_path):
backend_host, backend_port = self._poll_for_servers().getsockname()
config = reflex.config.get_config()
config.backend_port = backend_port
config.api_url = "http://{0}:{1}".format(
backend_host,
backend_port,
*self._poll_for_servers().getsockname(),
)
reflex.utils.build.setup_frontend(self.app_path)

Expand All @@ -399,7 +392,6 @@ def _wait_frontend(self):
self.frontend_url = m.group(1)
config = reflex.config.get_config()
config.deploy_url = self.frontend_url
config.frontend_port = int(self.frontend_url.rpartition(":")[2])
break
if self.frontend_url is None:
raise RuntimeError("Frontend did not start")
Expand Down Expand Up @@ -923,20 +915,17 @@ def _run_frontend(self):
root=web_root,
error_page_map=error_page_map,
) as self.frontend_server:
config = reflex.config.get_config()
config.frontend_port = self.frontend_server.server_address[1]
self.frontend_url = f"http://localhost:{config.frontend_port}"
self.frontend_url = "http://localhost:{1}".format(
*self.frontend_server.socket.getsockname()
)
self.frontend_server.serve_forever()

def _start_frontend(self):
# Set up the frontend.
with chdir(self.app_path):
backend_host, backend_port = self._poll_for_servers().getsockname()
config = reflex.config.get_config()
config.backend_port = backend_port
config.api_url = "http://{0}:{1}".format(
backend_host,
backend_port,
*self._poll_for_servers().getsockname(),
)
reflex.reflex.export(
zipping=False,
Expand Down
7 changes: 1 addition & 6 deletions reflex/utils/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from __future__ import annotations

import os

from rich.console import Console
from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
from rich.prompt import Prompt
Expand All @@ -14,7 +12,7 @@
_console = Console()

# The current log level.
_LOG_LEVEL = LogLevel.DEFAULT
_LOG_LEVEL = LogLevel.INFO

# Deprecated features who's warning has been printed.
_EMITTED_DEPRECATION_WARNINGS = set()
Expand Down Expand Up @@ -63,9 +61,6 @@ def set_log_level(log_level: LogLevel):
raise ValueError(f"Invalid log level: {log_level}") from ae

global _LOG_LEVEL
if log_level != _LOG_LEVEL:
# Set the loglevel persistently for subprocesses
os.environ["LOGLEVEL"] = log_level.value
_LOG_LEVEL = log_level


Expand Down
2 changes: 1 addition & 1 deletion scripts/integration.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ if [ -f /proc/$pid/winpid ]; then
echo "Windows detected, passing winpid $pid to port waiter"
fi

python scripts/wait_for_listening_port.py $check_ports --timeout=900 --server-pid "$pid" $WAIT_FOR_LISTENING_PORT_ARGS
python scripts/wait_for_listening_port.py $check_ports --timeout=900 --server-pid "$pid"
52 changes: 2 additions & 50 deletions scripts/wait_for_listening_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Tuple

import httpx

# psutil is already a dependency of Reflex itself - so it's OK to use
import psutil

Expand All @@ -25,7 +23,6 @@ def _pid_exists(pid):
return pid in psutil.pids()


# Not really used anymore now that we actually check the HTTP response.
def _wait_for_port(port, server_pid, timeout) -> Tuple[bool, str]:
start = time.time()
print(f"Waiting for up to {timeout} seconds for port {port} to start listening.") # noqa: T201
Expand All @@ -44,70 +41,25 @@ def _wait_for_port(port, server_pid, timeout) -> Tuple[bool, str]:
time.sleep(5)


def _wait_for_http_response(port, server_pid, timeout, path) -> Tuple[bool, str, str]:
start = time.time()
if path[0] != "/":
# This is a hack for passing the path on windows without a leading slash
# which mangles it https://stackoverflow.com/a/49013604
path = "/" + path
url = f"http://localhost:{port}{path}"
print(f"Waiting for up to {timeout} seconds for {url} to return HTTP response.") # noqa: T201
while True:
try:
if not _pid_exists(server_pid):
return False, f"Server PID {server_pid} is not running.", ""
response = httpx.get(url, timeout=0.5)
response.raise_for_status()
return (
True,
f"{url} returned response after {time.time() - start} seconds",
response.text,
)
except Exception as exc: # noqa: PERF203
if time.time() - start > timeout:
return (
False,
f"{url} still returning errors after {timeout} seconds: {exc!r}.",
"",
)
time.sleep(5)


def main():
"""Wait for ports to start listening."""
parser = argparse.ArgumentParser(description="Wait for ports to start listening.")
parser.add_argument("port", type=int, nargs="+")
parser.add_argument("--timeout", type=int, required=True)
parser.add_argument("--server-pid", type=int)
parser.add_argument("--path", type=str, default="/")
args = parser.parse_args()
start = time.time()
executor = ThreadPoolExecutor(max_workers=len(args.port))
futures = [
executor.submit(
_wait_for_http_response,
p,
args.server_pid,
args.timeout,
args.path,
)
executor.submit(_wait_for_port, p, args.server_pid, args.timeout)
for p in args.port
]
base_content = None
for f in as_completed(futures):
ok, msg, content = f.result()
ok, msg = f.result()
if ok:
print(f"OK: {msg}") # noqa: T201
if base_content is None:
base_content = content
else:
assert (
content == base_content
), f"HTTP responses are not equal {content!r} != {base_content!r}."
else:
print(f"FAIL: {msg}") # noqa: T201
exit(1)
print(f"OK: All HTTP responses are equal after {time.time() - start} sec.") # noqa: T201


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/init-test/in_docker_test_script.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ source ~/venv/bin/activate
pip install -U pip

echo "Installing reflex from local repo code"
pip install '/reflex-repo[proxy]'
pip install /reflex-repo

redis-server &

Expand Down

0 comments on commit 427d7c5

Please sign in to comment.