exec.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. from reflex.utils.terminal import colored
  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. "Backend running at: "
  55. + colored(
  56. f"http://0.0.0.0:{get_config().backend_port}", "green", attrs=("bold",)
  57. )
  58. )
  59. # run_process_and_launch_url is assumed to be used
  60. # only to launch the frontend
  61. # If this is not the case, might have to change the logic
  62. def run_process_and_launch_url(
  63. run_command: list[str | None], backend_present: bool = True
  64. ):
  65. """Run the process and launch the URL.
  66. Args:
  67. run_command: The command to run.
  68. backend_present: Whether the backend is present.
  69. """
  70. from reflex.utils import processes
  71. json_file_path = get_web_dir() / constants.PackageJson.PATH
  72. last_hash = detect_package_change(json_file_path)
  73. process = None
  74. first_run = True
  75. while True:
  76. if process is None:
  77. kwargs = {}
  78. if constants.IS_WINDOWS and backend_present:
  79. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  80. process = processes.new_process(
  81. run_command,
  82. cwd=get_web_dir(),
  83. shell=constants.IS_WINDOWS,
  84. **kwargs,
  85. )
  86. global frontend_process
  87. frontend_process = process
  88. if process.stdout:
  89. for line in processes.stream_logs("Starting frontend", process):
  90. match = re.search(constants.Next.FRONTEND_LISTENING_REGEX, line)
  91. if match:
  92. if first_run:
  93. url = match.group(1)
  94. if get_config().frontend_path != "":
  95. url = urljoin(url, get_config().frontend_path)
  96. console.print(
  97. "App running at: "
  98. + colored(url, "green", attrs=("bold",))
  99. + (" (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("App Running", color="green")
  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("App Running", color="green")
  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. # When we eventually switch to Granian by default, we should enable this warning.
  165. if False:
  166. console.warn(
  167. "Using Uvicorn for backend as it is installed. This behavior will change in 0.8.0 to use Granian by default."
  168. )
  169. def should_use_granian():
  170. """Whether to use Granian for backend.
  171. Returns:
  172. True if Granian should be used.
  173. """
  174. if environment.REFLEX_USE_GRANIAN.get():
  175. return True
  176. if (
  177. importlib.util.find_spec("uvicorn") is None
  178. or importlib.util.find_spec("gunicorn") is None
  179. ):
  180. return True
  181. _warn_user_about_uvicorn()
  182. return False
  183. def get_app_module():
  184. """Get the app module for the backend.
  185. Returns:
  186. The app module for the backend.
  187. """
  188. config = get_config()
  189. return f"{config.module}:{constants.CompileVars.APP}"
  190. def run_backend(
  191. host: str,
  192. port: int,
  193. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  194. frontend_present: bool = False,
  195. ):
  196. """Run the backend.
  197. Args:
  198. host: The app host
  199. port: The app port
  200. loglevel: The log level.
  201. frontend_present: Whether the frontend is present.
  202. """
  203. web_dir = get_web_dir()
  204. # Create a .nocompile file to skip compile for backend.
  205. if web_dir.exists():
  206. (web_dir / constants.NOCOMPILE_FILE).touch()
  207. if not frontend_present:
  208. notify_backend()
  209. # Run the backend in development mode.
  210. if should_use_granian():
  211. run_granian_backend(host, port, loglevel)
  212. else:
  213. run_uvicorn_backend(host, port, loglevel)
  214. def get_reload_paths() -> Sequence[Path]:
  215. """Get the reload paths for the backend.
  216. Returns:
  217. The reload paths for the backend.
  218. """
  219. config = get_config()
  220. reload_paths = [Path(config.app_name).parent]
  221. if config.app_module is not None and config.app_module.__file__:
  222. module_path = Path(config.app_module.__file__).resolve().parent
  223. while module_path.parent.name and any(
  224. sibling_file.name == "__init__.py"
  225. for sibling_file in module_path.parent.iterdir()
  226. ):
  227. # go up a level to find dir without `__init__.py`
  228. module_path = module_path.parent
  229. reload_paths = [module_path]
  230. include_dirs = tuple(
  231. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  232. )
  233. exclude_dirs = tuple(
  234. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  235. )
  236. def is_excluded_by_default(path: Path) -> bool:
  237. if path.is_dir():
  238. if path.name.startswith("."):
  239. # exclude hidden directories
  240. return True
  241. if path.name.startswith("__"):
  242. # ignore things like __pycache__
  243. return True
  244. return path.name in (".gitignore", "uploaded_files")
  245. reload_paths = (
  246. tuple(
  247. path.absolute()
  248. for dir in reload_paths
  249. for path in dir.iterdir()
  250. if not is_excluded_by_default(path)
  251. )
  252. + include_dirs
  253. )
  254. if exclude_dirs:
  255. reload_paths = tuple(
  256. path
  257. for path in reload_paths
  258. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  259. )
  260. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  261. return reload_paths
  262. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  263. """Run the backend in development mode using Uvicorn.
  264. Args:
  265. host: The app host
  266. port: The app port
  267. loglevel: The log level.
  268. """
  269. import uvicorn
  270. uvicorn.run(
  271. app=f"{get_app_module()}",
  272. factory=True,
  273. host=host,
  274. port=port,
  275. log_level=loglevel.value,
  276. reload=True,
  277. reload_dirs=list(map(str, get_reload_paths())),
  278. )
  279. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  280. """Run the backend in development mode using Granian.
  281. Args:
  282. host: The app host
  283. port: The app port
  284. loglevel: The log level.
  285. """
  286. console.debug("Using Granian for backend")
  287. from granian.constants import Interfaces
  288. from granian.log import LogLevels
  289. from granian.server import MPServer as Granian
  290. Granian(
  291. target=get_app_module(),
  292. factory=True,
  293. address=host,
  294. port=port,
  295. interface=Interfaces.ASGI,
  296. log_level=LogLevels(loglevel.value),
  297. reload=True,
  298. reload_paths=get_reload_paths(),
  299. ).serve()
  300. def _deprecate_asgi_config(
  301. config_name: str,
  302. reason: str = "",
  303. ):
  304. # When we eventually switch to Granian by default, we should enable this deprecation.
  305. if False:
  306. console.deprecate(
  307. f"config.{config_name}",
  308. reason=reason,
  309. deprecation_version="0.7.5",
  310. removal_version="0.8.0",
  311. )
  312. @once
  313. def _get_backend_workers():
  314. from reflex.utils import processes
  315. config = get_config()
  316. gunicorn_workers = config.gunicorn_workers or 0
  317. if config.gunicorn_workers is not None:
  318. _deprecate_asgi_config(
  319. "gunicorn_workers",
  320. "If you're using Granian, use GRANIAN_WORKERS instead.",
  321. )
  322. return gunicorn_workers if gunicorn_workers else processes.get_num_workers()
  323. @once
  324. def _get_backend_timeout():
  325. config = get_config()
  326. timeout = config.timeout or 120
  327. if config.timeout is not None:
  328. _deprecate_asgi_config(
  329. "timeout",
  330. "If you're using Granian, use GRANIAN_WORKERS_LIFETIME instead.",
  331. )
  332. return timeout
  333. @once
  334. def _get_backend_max_requests():
  335. config = get_config()
  336. gunicorn_max_requests = config.gunicorn_max_requests or 120
  337. if config.gunicorn_max_requests is not None:
  338. _deprecate_asgi_config("gunicorn_max_requests")
  339. return gunicorn_max_requests
  340. @once
  341. def _get_backend_max_requests_jitter():
  342. config = get_config()
  343. gunicorn_max_requests_jitter = config.gunicorn_max_requests_jitter or 25
  344. if config.gunicorn_max_requests_jitter is not None:
  345. _deprecate_asgi_config("gunicorn_max_requests_jitter")
  346. return gunicorn_max_requests_jitter
  347. def run_backend_prod(
  348. host: str,
  349. port: int,
  350. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  351. frontend_present: bool = False,
  352. ):
  353. """Run the backend.
  354. Args:
  355. host: The app host
  356. port: The app port
  357. loglevel: The log level.
  358. frontend_present: Whether the frontend is present.
  359. """
  360. if not frontend_present:
  361. notify_backend()
  362. if should_use_granian():
  363. run_granian_backend_prod(host, port, loglevel)
  364. else:
  365. run_uvicorn_backend_prod(host, port, loglevel)
  366. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  367. """Run the backend in production mode using Uvicorn.
  368. Args:
  369. host: The app host
  370. port: The app port
  371. loglevel: The log level.
  372. """
  373. from reflex.utils import processes
  374. config = get_config()
  375. app_module = get_app_module()
  376. command = (
  377. [
  378. "uvicorn",
  379. *(
  380. (
  381. "--limit-max-requests",
  382. str(max_requessts),
  383. )
  384. if (
  385. (max_requessts := _get_backend_max_requests()) is not None
  386. and max_requessts > 0
  387. )
  388. else ()
  389. ),
  390. *(
  391. ("--timeout-keep-alive", str(timeout))
  392. if (timeout := _get_backend_timeout()) is not None
  393. else ()
  394. ),
  395. *("--host", host),
  396. *("--port", str(port)),
  397. *("--workers", str(_get_backend_workers())),
  398. "--factory",
  399. app_module,
  400. ]
  401. if constants.IS_WINDOWS
  402. else [
  403. "gunicorn",
  404. *("--worker-class", config.gunicorn_worker_class),
  405. *(
  406. (
  407. "--max-requests",
  408. str(max_requessts),
  409. )
  410. if (
  411. (max_requessts := _get_backend_max_requests()) is not None
  412. and max_requessts > 0
  413. )
  414. else ()
  415. ),
  416. *(
  417. (
  418. "--max-requests-jitter",
  419. str(max_requessts_jitter),
  420. )
  421. if (
  422. (max_requessts_jitter := _get_backend_max_requests_jitter())
  423. is not None
  424. and max_requessts_jitter > 0
  425. )
  426. else ()
  427. ),
  428. "--preload",
  429. *(
  430. ("--timeout", str(timeout))
  431. if (timeout := _get_backend_timeout()) is not None
  432. else ()
  433. ),
  434. *("--bind", f"{host}:{port}"),
  435. *("--threads", str(_get_backend_workers())),
  436. f"{app_module}()",
  437. ]
  438. )
  439. command += [
  440. *("--log-level", loglevel.value),
  441. ]
  442. processes.new_process(
  443. command,
  444. run=True,
  445. show_logs=True,
  446. env={
  447. environment.REFLEX_SKIP_COMPILE.name: "true"
  448. }, # skip compile for prod backend
  449. )
  450. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  451. """Run the backend in production mode using Granian.
  452. Args:
  453. host: The app host
  454. port: The app port
  455. loglevel: The log level.
  456. """
  457. from reflex.utils import processes
  458. try:
  459. from granian.constants import Interfaces
  460. command = [
  461. "granian",
  462. *("--workers", str(_get_backend_workers())),
  463. *("--log-level", "critical"),
  464. *("--host", host),
  465. *("--port", str(port)),
  466. *("--interface", str(Interfaces.ASGI)),
  467. *("--factory", get_app_module()),
  468. ]
  469. processes.new_process(
  470. command,
  471. run=True,
  472. show_logs=True,
  473. env={
  474. environment.REFLEX_SKIP_COMPILE.name: "true"
  475. }, # skip compile for prod backend
  476. )
  477. except ImportError:
  478. console.error(
  479. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  480. )
  481. def output_system_info():
  482. """Show system information if the loglevel is in DEBUG."""
  483. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  484. return
  485. from reflex.utils import prerequisites
  486. config = get_config()
  487. try:
  488. config_file = sys.modules[config.__module__].__file__
  489. except Exception:
  490. config_file = None
  491. console.rule("System Info")
  492. console.debug(f"Config file: {config_file!r}")
  493. console.debug(f"Config: {config}")
  494. dependencies = [
  495. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  496. f"[Node {prerequisites.get_node_version()} (Expected: {constants.Node.VERSION}) (PATH:{path_ops.get_node_path()})]",
  497. ]
  498. system = platform.system()
  499. dependencies.append(
  500. f"[Bun {prerequisites.get_bun_version()} (Expected: {constants.Bun.VERSION}) (PATH: {path_ops.get_bun_path()})]"
  501. )
  502. if system == "Linux":
  503. import distro # pyright: ignore[reportMissingImports]
  504. os_version = distro.name(pretty=True)
  505. else:
  506. os_version = platform.version()
  507. dependencies.append(f"[OS {platform.system()} {os_version}]")
  508. for dep in dependencies:
  509. console.debug(f"{dep}")
  510. console.debug(
  511. f"Using package installer at: {prerequisites.get_nodejs_compatible_package_managers(raise_on_none=False)}"
  512. )
  513. console.debug(
  514. f"Using package executer at: {prerequisites.get_js_package_executor(raise_on_none=False)}"
  515. )
  516. if system != "Windows":
  517. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  518. def is_testing_env() -> bool:
  519. """Whether the app is running in a testing environment.
  520. Returns:
  521. True if the app is running in under pytest.
  522. """
  523. return constants.PYTEST_CURRENT_TEST in os.environ
  524. def is_in_app_harness() -> bool:
  525. """Whether the app is running in the app harness.
  526. Returns:
  527. True if the app is running in the app harness.
  528. """
  529. return constants.APP_HARNESS_FLAG in os.environ
  530. def is_prod_mode() -> bool:
  531. """Check if the app is running in production mode.
  532. Returns:
  533. True if the app is running in production mode or False if running in dev mode.
  534. """
  535. current_mode = environment.REFLEX_ENV_MODE.get()
  536. return current_mode == constants.Env.PROD
  537. def get_compile_context() -> constants.CompileContext:
  538. """Check if the app is compiled for deploy.
  539. Returns:
  540. Whether the app is being compiled for deploy.
  541. """
  542. return environment.REFLEX_COMPILE_CONTEXT.get()