exec.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. """Everything regarding execution of the built app."""
  2. from __future__ import annotations
  3. import hashlib
  4. import importlib.util
  5. import json
  6. import os
  7. import platform
  8. import re
  9. import subprocess
  10. import sys
  11. from collections.abc import Sequence
  12. from pathlib import Path
  13. from typing import Any
  14. from urllib.parse import urljoin
  15. import psutil
  16. from reflex import constants
  17. from reflex.config import environment, get_config
  18. from reflex.constants.base import LogLevel
  19. from reflex.utils import console, path_ops
  20. from reflex.utils.decorator import once
  21. from reflex.utils.prerequisites import get_web_dir
  22. # For uvicorn windows bug fix (#2335)
  23. frontend_process = None
  24. def detect_package_change(json_file_path: Path) -> str:
  25. """Calculates the SHA-256 hash of a JSON file and returns it as a hexadecimal string.
  26. Args:
  27. json_file_path: The path to the JSON file to be hashed.
  28. Returns:
  29. str: The SHA-256 hash of the JSON file as a hexadecimal string.
  30. Example:
  31. >>> detect_package_change("package.json")
  32. 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2'
  33. """
  34. with json_file_path.open("r") as file:
  35. json_data = json.load(file)
  36. # Calculate the hash
  37. json_string = json.dumps(json_data, sort_keys=True)
  38. hash_object = hashlib.sha256(json_string.encode())
  39. return hash_object.hexdigest()
  40. def kill(proc_pid: int):
  41. """Kills a process and all its child processes.
  42. Args:
  43. proc_pid (int): The process ID of the process to be killed.
  44. Example:
  45. >>> kill(1234)
  46. """
  47. process = psutil.Process(proc_pid)
  48. for proc in process.children(recursive=True):
  49. proc.kill()
  50. process.kill()
  51. def notify_backend():
  52. """Output a string notifying where the backend is running."""
  53. console.print(
  54. f"Backend running at: [bold green]http://0.0.0.0:{get_config().backend_port}[/bold green]"
  55. )
  56. # run_process_and_launch_url is assumed to be used
  57. # only to launch the frontend
  58. # If this is not the case, might have to change the logic
  59. def run_process_and_launch_url(
  60. run_command: list[str | None], backend_present: bool = True
  61. ):
  62. """Run the process and launch the URL.
  63. Args:
  64. run_command: The command to run.
  65. backend_present: Whether the backend is present.
  66. """
  67. from reflex.utils import processes
  68. json_file_path = get_web_dir() / constants.PackageJson.PATH
  69. last_hash = detect_package_change(json_file_path)
  70. process = None
  71. first_run = True
  72. while True:
  73. if process is None:
  74. kwargs: dict[str, Any] = {
  75. "env": {
  76. **os.environ,
  77. "NO_COLOR": "1",
  78. }
  79. }
  80. if constants.IS_WINDOWS and backend_present:
  81. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  82. process = processes.new_process(
  83. run_command,
  84. cwd=get_web_dir(),
  85. shell=constants.IS_WINDOWS,
  86. **kwargs,
  87. )
  88. global frontend_process
  89. frontend_process = process
  90. if process.stdout:
  91. for line in processes.stream_logs("Starting frontend", process):
  92. match = re.search(constants.ReactRouter.FRONTEND_LISTENING_REGEX, line)
  93. if match:
  94. if first_run:
  95. url = match.group(1)
  96. if get_config().frontend_path != "":
  97. url = urljoin(url, get_config().frontend_path)
  98. console.print(
  99. f"App running at: [bold green]{url}[/bold green]{' (Frontend-only mode)' if not backend_present else ''}"
  100. )
  101. if backend_present:
  102. notify_backend()
  103. first_run = False
  104. else:
  105. console.print("New packages detected: Updating app...")
  106. else:
  107. if any(
  108. x in line for x in ("bin executable does not exist on disk",)
  109. ):
  110. console.error(
  111. "Try setting `REFLEX_USE_NPM=1` and re-running `reflex init` and `reflex run` to use npm instead of bun:\n"
  112. "`REFLEX_USE_NPM=1 reflex init`\n"
  113. "`REFLEX_USE_NPM=1 reflex run`"
  114. )
  115. new_hash = detect_package_change(json_file_path)
  116. if new_hash != last_hash:
  117. last_hash = new_hash
  118. kill(process.pid)
  119. process = None
  120. break # for line in process.stdout
  121. if process is not None:
  122. break # while True
  123. def run_frontend(root: Path, port: str, backend_present: bool = True):
  124. """Run the frontend.
  125. Args:
  126. root: The root path of the project.
  127. port: The port to run the frontend on.
  128. backend_present: Whether the backend is present.
  129. """
  130. from reflex.utils import prerequisites
  131. # validate dependencies before run
  132. prerequisites.validate_frontend_dependencies(init=False)
  133. # Run the frontend in development mode.
  134. console.rule("[bold green]App Running")
  135. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  136. run_process_and_launch_url(
  137. [
  138. *prerequisites.get_js_package_executor(raise_on_none=True)[0],
  139. "run",
  140. "dev",
  141. ],
  142. backend_present,
  143. )
  144. def run_frontend_prod(root: Path, port: str, backend_present: bool = True):
  145. """Run the frontend.
  146. Args:
  147. root: The root path of the project (to keep same API as run_frontend).
  148. port: The port to run the frontend on.
  149. backend_present: Whether the backend is present.
  150. """
  151. from reflex.utils import prerequisites
  152. # Set the port.
  153. os.environ["PORT"] = str(get_config().frontend_port if port is None else port)
  154. # validate dependencies before run
  155. prerequisites.validate_frontend_dependencies(init=False)
  156. # Run the frontend in production mode.
  157. console.rule("[bold green]App Running")
  158. run_process_and_launch_url(
  159. [*prerequisites.get_js_package_executor(raise_on_none=True)[0], "run", "prod"],
  160. backend_present,
  161. )
  162. @once
  163. def _warn_user_about_uvicorn():
  164. console.warn(
  165. "Using Uvicorn for backend as it is installed. This behavior will change in 0.8.0 to use Granian by default."
  166. )
  167. def should_use_granian():
  168. """Whether to use Granian for backend.
  169. Returns:
  170. True if Granian should be used.
  171. """
  172. if environment.REFLEX_USE_GRANIAN.is_set():
  173. return environment.REFLEX_USE_GRANIAN.get()
  174. if (
  175. importlib.util.find_spec("uvicorn") is None
  176. or importlib.util.find_spec("gunicorn") is None
  177. ):
  178. return True
  179. _warn_user_about_uvicorn()
  180. return False
  181. def get_app_module():
  182. """Get the app module for the backend.
  183. Returns:
  184. The app module for the backend.
  185. """
  186. return get_config().module
  187. def get_app_instance():
  188. """Get the app module for the backend.
  189. Returns:
  190. The app module for the backend.
  191. """
  192. return f"{get_app_module()}:{constants.CompileVars.APP}"
  193. def get_app_file() -> Path:
  194. """Get the app file for the backend.
  195. Returns:
  196. The app file for the backend.
  197. Raises:
  198. ImportError: If the app module is not found.
  199. """
  200. current_working_dir = str(Path.cwd())
  201. if current_working_dir not in sys.path:
  202. # Add the current working directory to sys.path
  203. sys.path.insert(0, current_working_dir)
  204. module_spec = importlib.util.find_spec(get_app_module())
  205. if module_spec is None:
  206. raise ImportError(
  207. f"Module {get_app_module()} not found. Make sure the module is installed."
  208. )
  209. file_name = module_spec.origin
  210. if file_name is None:
  211. raise ImportError(
  212. f"Module {get_app_module()} not found. Make sure the module is installed."
  213. )
  214. return Path(file_name).resolve()
  215. def get_app_instance_from_file() -> str:
  216. """Get the app module for the backend.
  217. Returns:
  218. The app module for the backend.
  219. """
  220. return f"{get_app_file()}:{constants.CompileVars.APP}"
  221. def run_backend(
  222. host: str,
  223. port: int,
  224. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  225. frontend_present: bool = False,
  226. ):
  227. """Run the backend.
  228. Args:
  229. host: The app host
  230. port: The app port
  231. loglevel: The log level.
  232. frontend_present: Whether the frontend is present.
  233. """
  234. web_dir = get_web_dir()
  235. # Create a .nocompile file to skip compile for backend.
  236. if web_dir.exists():
  237. (web_dir / constants.NOCOMPILE_FILE).touch()
  238. if not frontend_present:
  239. notify_backend()
  240. # Run the backend in development mode.
  241. if should_use_granian():
  242. run_granian_backend(host, port, loglevel)
  243. else:
  244. run_uvicorn_backend(host, port, loglevel)
  245. def get_reload_paths() -> Sequence[Path]:
  246. """Get the reload paths for the backend.
  247. Returns:
  248. The reload paths for the backend.
  249. """
  250. config = get_config()
  251. reload_paths = [Path(config.app_name).parent]
  252. if config.app_module is not None and config.app_module.__file__:
  253. module_path = Path(config.app_module.__file__).resolve().parent
  254. while module_path.parent.name and any(
  255. sibling_file.name == "__init__.py"
  256. for sibling_file in module_path.parent.iterdir()
  257. ):
  258. # go up a level to find dir without `__init__.py`
  259. module_path = module_path.parent
  260. reload_paths = [module_path]
  261. include_dirs = tuple(
  262. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  263. )
  264. exclude_dirs = tuple(
  265. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  266. )
  267. def is_excluded_by_default(path: Path) -> bool:
  268. if path.is_dir():
  269. if path.name.startswith("."):
  270. # exclude hidden directories
  271. return True
  272. if path.name.startswith("__"):
  273. # ignore things like __pycache__
  274. return True
  275. return path.name in (".gitignore", "uploaded_files")
  276. reload_paths = (
  277. tuple(
  278. path.absolute()
  279. for dir in reload_paths
  280. for path in dir.iterdir()
  281. if not is_excluded_by_default(path)
  282. )
  283. + include_dirs
  284. )
  285. if exclude_dirs:
  286. reload_paths = tuple(
  287. path
  288. for path in reload_paths
  289. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  290. )
  291. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  292. return reload_paths
  293. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  294. """Run the backend in development mode using Uvicorn.
  295. Args:
  296. host: The app host
  297. port: The app port
  298. loglevel: The log level.
  299. """
  300. import uvicorn
  301. uvicorn.run(
  302. app=f"{get_app_instance()}",
  303. factory=True,
  304. host=host,
  305. port=port,
  306. log_level=loglevel.value,
  307. reload=True,
  308. reload_dirs=list(map(str, get_reload_paths())),
  309. reload_delay=0.1,
  310. )
  311. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  312. """Run the backend in development mode using Granian.
  313. Args:
  314. host: The app host
  315. port: The app port
  316. loglevel: The log level.
  317. """
  318. console.debug("Using Granian for backend")
  319. from granian.constants import Interfaces
  320. from granian.log import LogLevels
  321. from granian.server import MPServer as Granian
  322. Granian(
  323. target=get_app_instance_from_file(),
  324. factory=True,
  325. address=host,
  326. port=port,
  327. interface=Interfaces.ASGI,
  328. log_level=LogLevels(loglevel.value),
  329. reload=True,
  330. reload_paths=get_reload_paths(),
  331. reload_ignore_worker_failure=True,
  332. reload_tick=100,
  333. workers_kill_timeout=2,
  334. ).serve()
  335. def _deprecate_asgi_config(
  336. config_name: str,
  337. reason: str = "",
  338. ):
  339. console.deprecate(
  340. f"config.{config_name}",
  341. reason=reason,
  342. deprecation_version="0.7.9",
  343. removal_version="0.8.0",
  344. )
  345. @once
  346. def _get_backend_workers():
  347. from reflex.utils import processes
  348. config = get_config()
  349. gunicorn_workers = config.gunicorn_workers or 0
  350. if config.gunicorn_workers is not None:
  351. _deprecate_asgi_config(
  352. "gunicorn_workers",
  353. "If you're using Granian, use GRANIAN_WORKERS instead.",
  354. )
  355. return gunicorn_workers if gunicorn_workers else processes.get_num_workers()
  356. @once
  357. def _get_backend_timeout():
  358. config = get_config()
  359. timeout = config.timeout or 120
  360. if config.timeout is not None:
  361. _deprecate_asgi_config(
  362. "timeout",
  363. "If you're using Granian, use GRANIAN_WORKERS_LIFETIME instead.",
  364. )
  365. return timeout
  366. @once
  367. def _get_backend_max_requests():
  368. config = get_config()
  369. gunicorn_max_requests = config.gunicorn_max_requests or 120
  370. if config.gunicorn_max_requests is not None:
  371. _deprecate_asgi_config("gunicorn_max_requests")
  372. return gunicorn_max_requests
  373. @once
  374. def _get_backend_max_requests_jitter():
  375. config = get_config()
  376. gunicorn_max_requests_jitter = config.gunicorn_max_requests_jitter or 25
  377. if config.gunicorn_max_requests_jitter is not None:
  378. _deprecate_asgi_config("gunicorn_max_requests_jitter")
  379. return gunicorn_max_requests_jitter
  380. def run_backend_prod(
  381. host: str,
  382. port: int,
  383. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  384. frontend_present: bool = False,
  385. ):
  386. """Run the backend.
  387. Args:
  388. host: The app host
  389. port: The app port
  390. loglevel: The log level.
  391. frontend_present: Whether the frontend is present.
  392. """
  393. if not frontend_present:
  394. notify_backend()
  395. if should_use_granian():
  396. run_granian_backend_prod(host, port, loglevel)
  397. else:
  398. run_uvicorn_backend_prod(host, port, loglevel)
  399. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  400. """Run the backend in production mode using Uvicorn.
  401. Args:
  402. host: The app host
  403. port: The app port
  404. loglevel: The log level.
  405. """
  406. from reflex.utils import processes
  407. config = get_config()
  408. app_module = get_app_instance()
  409. command = (
  410. [
  411. "uvicorn",
  412. *(
  413. (
  414. "--limit-max-requests",
  415. str(max_requessts),
  416. )
  417. if (
  418. (max_requessts := _get_backend_max_requests()) is not None
  419. and max_requessts > 0
  420. )
  421. else ()
  422. ),
  423. *(
  424. ("--timeout-keep-alive", str(timeout))
  425. if (timeout := _get_backend_timeout()) is not None
  426. else ()
  427. ),
  428. *("--host", host),
  429. *("--port", str(port)),
  430. *("--workers", str(_get_backend_workers())),
  431. "--factory",
  432. app_module,
  433. ]
  434. if constants.IS_WINDOWS
  435. else [
  436. "gunicorn",
  437. *("--worker-class", config.gunicorn_worker_class),
  438. *(
  439. (
  440. "--max-requests",
  441. str(max_requessts),
  442. )
  443. if (
  444. (max_requessts := _get_backend_max_requests()) is not None
  445. and max_requessts > 0
  446. )
  447. else ()
  448. ),
  449. *(
  450. (
  451. "--max-requests-jitter",
  452. str(max_requessts_jitter),
  453. )
  454. if (
  455. (max_requessts_jitter := _get_backend_max_requests_jitter())
  456. is not None
  457. and max_requessts_jitter > 0
  458. )
  459. else ()
  460. ),
  461. "--preload",
  462. *(
  463. ("--timeout", str(timeout))
  464. if (timeout := _get_backend_timeout()) is not None
  465. else ()
  466. ),
  467. *("--bind", f"{host}:{port}"),
  468. *("--threads", str(_get_backend_workers())),
  469. f"{app_module}()",
  470. ]
  471. )
  472. command += [
  473. *("--log-level", loglevel.value),
  474. ]
  475. processes.new_process(
  476. command,
  477. run=True,
  478. show_logs=True,
  479. env={
  480. environment.REFLEX_SKIP_COMPILE.name: "true"
  481. }, # skip compile for prod backend
  482. )
  483. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  484. """Run the backend in production mode using Granian.
  485. Args:
  486. host: The app host
  487. port: The app port
  488. loglevel: The log level.
  489. """
  490. from reflex.utils import processes
  491. try:
  492. from granian.constants import Interfaces
  493. command = [
  494. "granian",
  495. *("--workers", str(_get_backend_workers())),
  496. *("--log-level", "critical"),
  497. *("--host", host),
  498. *("--port", str(port)),
  499. *("--interface", str(Interfaces.ASGI)),
  500. *("--factory", get_app_instance_from_file()),
  501. ]
  502. processes.new_process(
  503. command,
  504. run=True,
  505. show_logs=True,
  506. env={
  507. environment.REFLEX_SKIP_COMPILE.name: "true"
  508. }, # skip compile for prod backend
  509. )
  510. except ImportError:
  511. console.error(
  512. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  513. )
  514. def output_system_info():
  515. """Show system information if the loglevel is in DEBUG."""
  516. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  517. return
  518. from reflex.utils import prerequisites
  519. config = get_config()
  520. try:
  521. config_file = sys.modules[config.__module__].__file__
  522. except Exception:
  523. config_file = None
  524. console.rule("System Info")
  525. console.debug(f"Config file: {config_file!r}")
  526. console.debug(f"Config: {config}")
  527. dependencies = [
  528. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  529. f"[Node {prerequisites.get_node_version()} (Minimum: {constants.Node.MIN_VERSION}) (PATH:{path_ops.get_node_path()})]",
  530. ]
  531. system = platform.system()
  532. dependencies.append(
  533. f"[Bun {prerequisites.get_bun_version()} (Minimum: {constants.Bun.MIN_VERSION}) (PATH: {path_ops.get_bun_path()})]"
  534. )
  535. if system == "Linux":
  536. os_version = platform.freedesktop_os_release().get("PRETTY_NAME", "Unknown")
  537. else:
  538. os_version = platform.version()
  539. dependencies.append(f"[OS {platform.system()} {os_version}]")
  540. for dep in dependencies:
  541. console.debug(f"{dep}")
  542. console.debug(
  543. f"Using package installer at: {prerequisites.get_nodejs_compatible_package_managers(raise_on_none=False)}"
  544. )
  545. console.debug(
  546. f"Using package executer at: {prerequisites.get_js_package_executor(raise_on_none=False)}"
  547. )
  548. if system != "Windows":
  549. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  550. def is_testing_env() -> bool:
  551. """Whether the app is running in a testing environment.
  552. Returns:
  553. True if the app is running in under pytest.
  554. """
  555. return constants.PYTEST_CURRENT_TEST in os.environ
  556. def is_in_app_harness() -> bool:
  557. """Whether the app is running in the app harness.
  558. Returns:
  559. True if the app is running in the app harness.
  560. """
  561. return constants.APP_HARNESS_FLAG in os.environ
  562. def is_prod_mode() -> bool:
  563. """Check if the app is running in production mode.
  564. Returns:
  565. True if the app is running in production mode or False if running in dev mode.
  566. """
  567. current_mode = environment.REFLEX_ENV_MODE.get()
  568. return current_mode == constants.Env.PROD
  569. def get_compile_context() -> constants.CompileContext:
  570. """Check if the app is compiled for deploy.
  571. Returns:
  572. Whether the app is being compiled for deploy.
  573. """
  574. return environment.REFLEX_COMPILE_CONTEXT.get()