exec.py 19 KB

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