1
0

exec.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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 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.is_set():
  167. return environment.REFLEX_USE_GRANIAN.get()
  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. return get_config().module
  181. def get_app_instance():
  182. """Get the app module for the backend.
  183. Returns:
  184. The app module for the backend.
  185. """
  186. return f"{get_app_module()}:{constants.CompileVars.APP}"
  187. def get_app_file() -> Path:
  188. """Get the app file for the backend.
  189. Returns:
  190. The app file for the backend.
  191. Raises:
  192. ImportError: If the app module is not found.
  193. """
  194. current_working_dir = str(Path.cwd())
  195. if current_working_dir not in sys.path:
  196. # Add the current working directory to sys.path
  197. sys.path.insert(0, current_working_dir)
  198. module_spec = importlib.util.find_spec(get_app_module())
  199. if module_spec is None:
  200. raise ImportError(
  201. f"Module {get_app_module()} not found. Make sure the module is installed."
  202. )
  203. file_name = module_spec.origin
  204. if file_name is None:
  205. raise ImportError(
  206. f"Module {get_app_module()} not found. Make sure the module is installed."
  207. )
  208. return Path(file_name).resolve()
  209. def get_app_instance_from_file() -> str:
  210. """Get the app module for the backend.
  211. Returns:
  212. The app module for the backend.
  213. """
  214. return f"{get_app_file()}:{constants.CompileVars.APP}"
  215. def run_backend(
  216. host: str,
  217. port: int,
  218. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  219. frontend_present: bool = False,
  220. ):
  221. """Run the backend.
  222. Args:
  223. host: The app host
  224. port: The app port
  225. loglevel: The log level.
  226. frontend_present: Whether the frontend is present.
  227. """
  228. web_dir = get_web_dir()
  229. # Create a .nocompile file to skip compile for backend.
  230. if web_dir.exists():
  231. (web_dir / constants.NOCOMPILE_FILE).touch()
  232. if not frontend_present:
  233. notify_backend()
  234. # Run the backend in development mode.
  235. if should_use_granian():
  236. run_granian_backend(host, port, loglevel)
  237. else:
  238. run_uvicorn_backend(host, port, loglevel)
  239. def get_reload_paths() -> Sequence[Path]:
  240. """Get the reload paths for the backend.
  241. Returns:
  242. The reload paths for the backend.
  243. """
  244. config = get_config()
  245. reload_paths = [Path(config.app_name).parent]
  246. if config.app_module is not None and config.app_module.__file__:
  247. module_path = Path(config.app_module.__file__).resolve().parent
  248. while module_path.parent.name and any(
  249. sibling_file.name == "__init__.py"
  250. for sibling_file in module_path.parent.iterdir()
  251. ):
  252. # go up a level to find dir without `__init__.py`
  253. module_path = module_path.parent
  254. reload_paths = [module_path]
  255. include_dirs = tuple(
  256. map(Path.absolute, environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS.get())
  257. )
  258. exclude_dirs = tuple(
  259. map(Path.absolute, environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS.get())
  260. )
  261. def is_excluded_by_default(path: Path) -> bool:
  262. if path.is_dir():
  263. if path.name.startswith("."):
  264. # exclude hidden directories
  265. return True
  266. if path.name.startswith("__"):
  267. # ignore things like __pycache__
  268. return True
  269. return path.name in (".gitignore", "uploaded_files")
  270. reload_paths = (
  271. tuple(
  272. path.absolute()
  273. for dir in reload_paths
  274. for path in dir.iterdir()
  275. if not is_excluded_by_default(path)
  276. )
  277. + include_dirs
  278. )
  279. if exclude_dirs:
  280. reload_paths = tuple(
  281. path
  282. for path in reload_paths
  283. if all(not path.samefile(exclude) for exclude in exclude_dirs)
  284. )
  285. console.debug(f"Reload paths: {list(map(str, reload_paths))}")
  286. return reload_paths
  287. def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):
  288. """Run the backend in development mode using Uvicorn.
  289. Args:
  290. host: The app host
  291. port: The app port
  292. loglevel: The log level.
  293. """
  294. import uvicorn
  295. uvicorn.run(
  296. app=f"{get_app_instance()}",
  297. factory=True,
  298. host=host,
  299. port=port,
  300. log_level=loglevel.value,
  301. reload=True,
  302. reload_dirs=list(map(str, get_reload_paths())),
  303. reload_delay=0.1,
  304. )
  305. def run_granian_backend(host: str, port: int, loglevel: LogLevel):
  306. """Run the backend in development mode using Granian.
  307. Args:
  308. host: The app host
  309. port: The app port
  310. loglevel: The log level.
  311. """
  312. console.debug("Using Granian for backend")
  313. if environment.REFLEX_STRICT_HOT_RELOAD.get():
  314. import multiprocessing
  315. multiprocessing.set_start_method("spawn", force=True)
  316. from granian.constants import Interfaces
  317. from granian.log import LogLevels
  318. from granian.server import MPServer as Granian
  319. Granian(
  320. target=get_app_instance_from_file(),
  321. factory=True,
  322. address=host,
  323. port=port,
  324. interface=Interfaces.ASGI,
  325. log_level=LogLevels(loglevel.value),
  326. reload=True,
  327. reload_paths=get_reload_paths(),
  328. reload_ignore_worker_failure=True,
  329. reload_tick=100,
  330. workers_kill_timeout=2,
  331. ).serve()
  332. def _deprecate_asgi_config(
  333. config_name: str,
  334. reason: str = "",
  335. ):
  336. console.deprecate(
  337. f"config.{config_name}",
  338. reason=reason,
  339. deprecation_version="0.7.9",
  340. removal_version="0.8.0",
  341. )
  342. @once
  343. def _get_backend_workers():
  344. from reflex.utils import processes
  345. config = get_config()
  346. gunicorn_workers = config.gunicorn_workers or 0
  347. if config.gunicorn_workers is not None:
  348. _deprecate_asgi_config(
  349. "gunicorn_workers",
  350. "If you're using Granian, use GRANIAN_WORKERS instead.",
  351. )
  352. return gunicorn_workers if gunicorn_workers else processes.get_num_workers()
  353. @once
  354. def _get_backend_timeout():
  355. config = get_config()
  356. timeout = config.timeout or 120
  357. if config.timeout is not None:
  358. _deprecate_asgi_config(
  359. "timeout",
  360. "If you're using Granian, use GRANIAN_WORKERS_LIFETIME instead.",
  361. )
  362. return timeout
  363. @once
  364. def _get_backend_max_requests():
  365. config = get_config()
  366. gunicorn_max_requests = config.gunicorn_max_requests or 120
  367. if config.gunicorn_max_requests is not None:
  368. _deprecate_asgi_config("gunicorn_max_requests")
  369. return gunicorn_max_requests
  370. @once
  371. def _get_backend_max_requests_jitter():
  372. config = get_config()
  373. gunicorn_max_requests_jitter = config.gunicorn_max_requests_jitter or 25
  374. if config.gunicorn_max_requests_jitter is not None:
  375. _deprecate_asgi_config("gunicorn_max_requests_jitter")
  376. return gunicorn_max_requests_jitter
  377. def run_backend_prod(
  378. host: str,
  379. port: int,
  380. loglevel: constants.LogLevel = constants.LogLevel.ERROR,
  381. frontend_present: bool = False,
  382. ):
  383. """Run the backend.
  384. Args:
  385. host: The app host
  386. port: The app port
  387. loglevel: The log level.
  388. frontend_present: Whether the frontend is present.
  389. """
  390. if not frontend_present:
  391. notify_backend()
  392. if should_use_granian():
  393. run_granian_backend_prod(host, port, loglevel)
  394. else:
  395. run_uvicorn_backend_prod(host, port, loglevel)
  396. def run_uvicorn_backend_prod(host: str, port: int, loglevel: LogLevel):
  397. """Run the backend in production mode using Uvicorn.
  398. Args:
  399. host: The app host
  400. port: The app port
  401. loglevel: The log level.
  402. """
  403. from reflex.utils import processes
  404. config = get_config()
  405. app_module = get_app_instance()
  406. command = (
  407. [
  408. "uvicorn",
  409. *(
  410. (
  411. "--limit-max-requests",
  412. str(max_requessts),
  413. )
  414. if (
  415. (max_requessts := _get_backend_max_requests()) is not None
  416. and max_requessts > 0
  417. )
  418. else ()
  419. ),
  420. *(
  421. ("--timeout-keep-alive", str(timeout))
  422. if (timeout := _get_backend_timeout()) is not None
  423. else ()
  424. ),
  425. *("--host", host),
  426. *("--port", str(port)),
  427. *("--workers", str(_get_backend_workers())),
  428. "--factory",
  429. app_module,
  430. ]
  431. if constants.IS_WINDOWS
  432. else [
  433. "gunicorn",
  434. *("--worker-class", config.gunicorn_worker_class),
  435. *(
  436. (
  437. "--max-requests",
  438. str(max_requessts),
  439. )
  440. if (
  441. (max_requessts := _get_backend_max_requests()) is not None
  442. and max_requessts > 0
  443. )
  444. else ()
  445. ),
  446. *(
  447. (
  448. "--max-requests-jitter",
  449. str(max_requessts_jitter),
  450. )
  451. if (
  452. (max_requessts_jitter := _get_backend_max_requests_jitter())
  453. is not None
  454. and max_requessts_jitter > 0
  455. )
  456. else ()
  457. ),
  458. "--preload",
  459. *(
  460. ("--timeout", str(timeout))
  461. if (timeout := _get_backend_timeout()) is not None
  462. else ()
  463. ),
  464. *("--bind", f"{host}:{port}"),
  465. *("--threads", str(_get_backend_workers())),
  466. f"{app_module}()",
  467. ]
  468. )
  469. command += [
  470. *("--log-level", loglevel.value),
  471. ]
  472. processes.new_process(
  473. command,
  474. run=True,
  475. show_logs=True,
  476. env={
  477. environment.REFLEX_SKIP_COMPILE.name: "true"
  478. }, # skip compile for prod backend
  479. )
  480. def run_granian_backend_prod(host: str, port: int, loglevel: LogLevel):
  481. """Run the backend in production mode using Granian.
  482. Args:
  483. host: The app host
  484. port: The app port
  485. loglevel: The log level.
  486. """
  487. from reflex.utils import processes
  488. try:
  489. from granian.constants import Interfaces
  490. command = [
  491. "granian",
  492. *("--workers", str(_get_backend_workers())),
  493. *("--log-level", "critical"),
  494. *("--host", host),
  495. *("--port", str(port)),
  496. *("--interface", str(Interfaces.ASGI)),
  497. *("--factory", get_app_instance_from_file()),
  498. ]
  499. processes.new_process(
  500. command,
  501. run=True,
  502. show_logs=True,
  503. env={
  504. environment.REFLEX_SKIP_COMPILE.name: "true"
  505. }, # skip compile for prod backend
  506. )
  507. except ImportError:
  508. console.error(
  509. 'InstallError: REFLEX_USE_GRANIAN is set but `granian` is not installed. (run `pip install "granian[reload]>=1.6.0"`)'
  510. )
  511. def output_system_info():
  512. """Show system information if the loglevel is in DEBUG."""
  513. if console._LOG_LEVEL > constants.LogLevel.DEBUG:
  514. return
  515. from reflex.utils import prerequisites
  516. config = get_config()
  517. try:
  518. config_file = sys.modules[config.__module__].__file__
  519. except Exception:
  520. config_file = None
  521. console.rule("System Info")
  522. console.debug(f"Config file: {config_file!r}")
  523. console.debug(f"Config: {config}")
  524. dependencies = [
  525. f"[Reflex {constants.Reflex.VERSION} with Python {platform.python_version()} (PATH: {sys.executable})]",
  526. f"[Node {prerequisites.get_node_version()} (Minimum: {constants.Node.MIN_VERSION}) (PATH:{path_ops.get_node_path()})]",
  527. ]
  528. system = platform.system()
  529. dependencies.append(
  530. f"[Bun {prerequisites.get_bun_version()} (Minimum: {constants.Bun.MIN_VERSION}) (PATH: {path_ops.get_bun_path()})]"
  531. )
  532. if system == "Linux":
  533. os_version = platform.freedesktop_os_release().get("PRETTY_NAME", "Unknown")
  534. else:
  535. os_version = platform.version()
  536. dependencies.append(f"[OS {platform.system()} {os_version}]")
  537. for dep in dependencies:
  538. console.debug(f"{dep}")
  539. console.debug(
  540. f"Using package installer at: {prerequisites.get_nodejs_compatible_package_managers(raise_on_none=False)}"
  541. )
  542. console.debug(
  543. f"Using package executer at: {prerequisites.get_js_package_executor(raise_on_none=False)}"
  544. )
  545. if system != "Windows":
  546. console.debug(f"Unzip path: {path_ops.which('unzip')}")
  547. def is_testing_env() -> bool:
  548. """Whether the app is running in a testing environment.
  549. Returns:
  550. True if the app is running in under pytest.
  551. """
  552. return constants.PYTEST_CURRENT_TEST in os.environ
  553. def is_in_app_harness() -> bool:
  554. """Whether the app is running in the app harness.
  555. Returns:
  556. True if the app is running in the app harness.
  557. """
  558. return constants.APP_HARNESS_FLAG in os.environ
  559. def is_prod_mode() -> bool:
  560. """Check if the app is running in production mode.
  561. Returns:
  562. True if the app is running in production mode or False if running in dev mode.
  563. """
  564. current_mode = environment.REFLEX_ENV_MODE.get()
  565. return current_mode == constants.Env.PROD
  566. def get_compile_context() -> constants.CompileContext:
  567. """Check if the app is compiled for deploy.
  568. Returns:
  569. Whether the app is being compiled for deploy.
  570. """
  571. return environment.REFLEX_COMPILE_CONTEXT.get()