pz-cli 5.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (399) hide show
  1. pz_cli-5.0.0.dist-info/METADATA +51 -0
  2. pz_cli-5.0.0.dist-info/RECORD +399 -0
  3. pz_cli-5.0.0.dist-info/WHEEL +4 -0
  4. pz_cli-5.0.0.dist-info/entry_points.txt +5 -0
  5. pz_core/__init__.py +64 -0
  6. pz_core/__main__.py +7 -0
  7. pz_core/app.py +45 -0
  8. pz_core/assembly/__init__.py +17 -0
  9. pz_core/assembly/app_discovery.py +1240 -0
  10. pz_core/assembly/apps/__init__.py +25 -0
  11. pz_core/assembly/apps/compiler.py +824 -0
  12. pz_core/assembly/apps/providers.py +188 -0
  13. pz_core/assembly/cli/__init__.py +9 -0
  14. pz_core/assembly/cli/compiler.py +166 -0
  15. pz_core/assembly/diagnostics/__init__.py +21 -0
  16. pz_core/assembly/diagnostics/checks.py +257 -0
  17. pz_core/assembly/diagnostics/dev_sources.py +569 -0
  18. pz_core/assembly/events/__init__.py +5 -0
  19. pz_core/assembly/events/compiler.py +219 -0
  20. pz_core/assembly/extensions/__init__.py +5 -0
  21. pz_core/assembly/extensions/compiler.py +696 -0
  22. pz_core/assembly/infra/__init__.py +6 -0
  23. pz_core/assembly/infra/compiler.py +272 -0
  24. pz_core/assembly/lifecycle/__init__.py +5 -0
  25. pz_core/assembly/lifecycle/compiler.py +95 -0
  26. pz_core/assembly/middlewares/__init__.py +19 -0
  27. pz_core/assembly/middlewares/compiler.py +508 -0
  28. pz_core/assembly/project/__init__.py +7 -0
  29. pz_core/assembly/project/compiler.py +9 -0
  30. pz_core/assembly/project/context.py +17 -0
  31. pz_core/assembly/project/discovery.py +227 -0
  32. pz_core/assembly/resources/__init__.py +19 -0
  33. pz_core/assembly/resources/compiler.py +310 -0
  34. pz_core/assembly/resources/settings.py +129 -0
  35. pz_core/assembly/routes/__init__.py +7 -0
  36. pz_core/assembly/routes/compiler.py +400 -0
  37. pz_core/assembly/runtime_manifests/__init__.py +13 -0
  38. pz_core/assembly/runtime_manifests/compiler.py +159 -0
  39. pz_core/assembly/settings/__init__.py +17 -0
  40. pz_core/assembly/settings/compiler.py +786 -0
  41. pz_core/assembly/settings/host_project_overrides.py +82 -0
  42. pz_core/assembly/settings/host_runtime_endpoint.py +207 -0
  43. pz_core/authoring/__init__.py +79 -0
  44. pz_core/authoring/app_init_service.py +946 -0
  45. pz_core/authoring/app_versions.py +814 -0
  46. pz_core/authoring/cli.py +192 -0
  47. pz_core/authoring/commands.py +1810 -0
  48. pz_core/authoring/conflicts.py +180 -0
  49. pz_core/authoring/dev_bindings.py +916 -0
  50. pz_core/authoring/dev_git.py +1087 -0
  51. pz_core/authoring/dev_import.py +1061 -0
  52. pz_core/authoring/dev_manifest.py +522 -0
  53. pz_core/authoring/dev_sources.py +1638 -0
  54. pz_core/authoring/env_cli.py +454 -0
  55. pz_core/authoring/files.py +109 -0
  56. pz_core/authoring/ide_projection.py +1129 -0
  57. pz_core/authoring/naming.py +58 -0
  58. pz_core/authoring/official_dev_sources.py +432 -0
  59. pz_core/authoring/official_sources.json +156 -0
  60. pz_core/authoring/orchestration_service.py +558 -0
  61. pz_core/authoring/project_default.jsonc +53 -0
  62. pz_core/authoring/project_defaults.py +88 -0
  63. pz_core/authoring/project_metadata_service.py +199 -0
  64. pz_core/authoring/project_settings_checks.py +51 -0
  65. pz_core/authoring/project_settings_cli.py +299 -0
  66. pz_core/authoring/project_settings_service.py +1700 -0
  67. pz_core/authoring/project_state.py +399 -0
  68. pz_core/authoring/publish_git.py +423 -0
  69. pz_core/authoring/publish_lock.py +188 -0
  70. pz_core/authoring/publish_source.py +195 -0
  71. pz_core/authoring/release.py +1382 -0
  72. pz_core/authoring/repo_keys.py +29 -0
  73. pz_core/authoring/root_cli.py +28 -0
  74. pz_core/authoring/scaffold_service.py +325 -0
  75. pz_core/authoring/sync_service.py +787 -0
  76. pz_core/authoring/templates/app/__init__.py +1 -0
  77. pz_core/authoring/templates/app/api.py +25 -0
  78. pz_core/authoring/templates/app/apps.py +31 -0
  79. pz_core/authoring/templates/app/auth_package_init.py +14 -0
  80. pz_core/authoring/templates/app/auth_readme.py +29 -0
  81. pz_core/authoring/templates/app/configs_package_init.py +14 -0
  82. pz_core/authoring/templates/app/default_env.py +18 -0
  83. pz_core/authoring/templates/app/default_jsonc.py +25 -0
  84. pz_core/authoring/templates/app/locales_readme.py +25 -0
  85. pz_core/authoring/templates/app/migrations_readme.py +19 -0
  86. pz_core/authoring/templates/app/models.py +14 -0
  87. pz_core/authoring/templates/app/package_init.py +8 -0
  88. pz_core/authoring/templates/app/pages_base.py +161 -0
  89. pz_core/authoring/templates/app/pages_readme.py +25 -0
  90. pz_core/authoring/templates/app/public.py +31 -0
  91. pz_core/authoring/templates/app/pyproject.py +77 -0
  92. pz_core/authoring/templates/app/readme.py +74 -0
  93. pz_core/authoring/templates/app/settings.py +46 -0
  94. pz_core/authoring/templates/app/static_app_js.py +24 -0
  95. pz_core/authoring/templates/app/static_readme.py +31 -0
  96. pz_core/authoring/templates/app/template_config_page.py +23 -0
  97. pz_core/authoring/templates/app/template_index_html.py +28 -0
  98. pz_core/authoring/templates/app/templates_readme.py +32 -0
  99. pz_core/authoring/templates/app/urls.py +36 -0
  100. pz_core/authoring/templates/app/views.py +36 -0
  101. pz_core/authoring/templates/project/__init__.py +1 -0
  102. pz_core/authoring/templates/project/agents.py +51 -0
  103. pz_core/authoring/templates/project/apps_container_readme.py +37 -0
  104. pz_core/authoring/templates/project/main_py.py +59 -0
  105. pz_core/authoring/templates/project/project_env.py +19 -0
  106. pz_core/authoring/templates/project/pyproject.py +26 -0
  107. pz_core/authoring/templates/project/pz_env_env.py +65 -0
  108. pz_core/authoring/templates/project/pz_env_jsonc.py +69 -0
  109. pz_core/authoring/templates/project/pz_jsonc.py +12 -0
  110. pz_core/authoring/templates/project/readme.py +94 -0
  111. pz_core/authoring/templates/project/root_gitkeep.py +8 -0
  112. pz_core/authoring/templates/shared/__init__.py +5 -0
  113. pz_core/authoring/templates/shared/text.py +10 -0
  114. pz_core/authoring/venv_service.py +87 -0
  115. pz_core/authoring/workspace.py +167 -0
  116. pz_core/cli.py +291 -0
  117. pz_core/cli_options.py +74 -0
  118. pz_core/core/__init__.py +3 -0
  119. pz_core/core/errors/__init__.py +5 -0
  120. pz_core/core/errors/models.py +117 -0
  121. pz_core/core/events/__init__.py +5 -0
  122. pz_core/core/events/registry.py +54 -0
  123. pz_core/core/extensions/__init__.py +51 -0
  124. pz_core/core/extensions/registry.py +790 -0
  125. pz_core/core/health/__init__.py +6 -0
  126. pz_core/core/health/contracts.py +10 -0
  127. pz_core/core/middlewares/__init__.py +6 -0
  128. pz_core/core/middlewares/models.py +24 -0
  129. pz_core/core/routing/__init__.py +5 -0
  130. pz_core/core/routing/models.py +21 -0
  131. pz_core/core/settings_contracts.py +25 -0
  132. pz_core/docs/README.md +20 -0
  133. pz_core/docs/distribution-README.md +438 -0
  134. pz_core/docs/pz/345/221/275/344/273/244/346/200/273/350/247/210.md +1011 -0
  135. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/00-pz/346/236/266/346/236/204/346/200/273/347/272/262.md +240 -0
  136. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/01-/347/233/256/345/275/225/344/270/216/345/210/206/345/261/202/350/247/204/350/214/203.md +216 -0
  137. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/02-/345/214/205/344/270/216/345/210/206/345/217/221/350/247/204/350/214/203.md +403 -0
  138. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/03-App/346/234/200/345/260/217/345/255/220/345/214/205/350/247/204/350/214/203.md +571 -0
  139. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/04-Settings/344/270/216/351/205/215/347/275/256/350/247/204/350/214/203.md +1177 -0
  140. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/05-/350/265/204/346/272/220/344/270/216/350/277/220/350/241/214/347/233/256/345/275/225/350/247/204/350/214/203.md +575 -0
  141. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/06-/346/225/260/346/215/256/345/272/223/344/270/216/345/217/257/351/200/211/345/237/272/347/241/200/350/256/276/346/226/275/350/247/204/350/214/203.md +499 -0
  142. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/07-App/346/233/277/346/215/242/350/247/204/350/214/203.md +206 -0
  143. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/08-/345/271/263/345/217/260/347/272/247App/344/270/216/350/277/220/350/241/214/346/227/266/345/215/225/344/276/213/350/247/204/350/214/203.md +445 -0
  144. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/09-CLI/344/270/216Worker/345/205/245/345/217/243/350/247/204/350/214/203.md +950 -0
  145. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/10-/346/265/213/350/257/225/344/270/216/345/245/221/347/272/246/350/247/204/350/214/203.md +1001 -0
  146. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/11-/344/273/223/345/272/223/347/234/237/347/233/270/346/272/220/345/234/260/345/233/276.md +102 -0
  147. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/12-/346/236/204/345/273/272/344/270/216/345/217/221/345/270/203/346/243/200/346/237/245/346/270/205/345/215/225.md +171 -0
  148. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/13-/346/255/243/345/274/217Facade/346/200/273/350/241/250.md +402 -0
  149. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/14-/345/210/206/345/261/202/344/270/216/346/211/251/345/261/225/350/247/204/350/214/203.md +550 -0
  150. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/15-/345/255/220/345/214/205/345/274/200/345/217/221/344/275/277/347/224/250/346/211/213/345/206/214.md +1004 -0
  151. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/16-/346/211/251/345/261/225/347/202/271/346/255/243/345/274/217/345/215/217/350/256/256/346/270/205/345/215/225.md +352 -0
  152. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/17-pz.protocols.v1/346/255/243/345/274/217/345/215/217/350/256/256.md +266 -0
  153. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/18-/346/211/251/345/261/225/347/202/271/345/206/262/347/252/201/350/243/201/345/206/263/346/200/273/350/241/250.md +131 -0
  154. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/19-/351/224/231/350/257/257/347/240/201/344/270/216/350/257/212/346/226/255/345/215/217/350/256/256.md +176 -0
  155. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/20-/347/247/201/346/234/211/345/214/205/344/273/223/344/270/216/347/273/237/344/270/200/350/256/244/350/257/201/351/203/250/347/275/262/350/247/204/350/214/203.md +243 -0
  156. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/21-contrib/347/272/246/345/256/232/344/270/216Provider/346/216/245/345/205/245/350/247/204/350/214/203.md +365 -0
  157. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/22-/345/244/232/345/233/275/350/257/255/350/250/200/350/265/204/346/272/220/346/262/273/347/220/206/344/270/216/346/214/211/351/234/200/345/212/240/350/275/275/350/247/204/350/214/203.md +912 -0
  158. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/23-/351/246/226/345/261/217/345/261/225/347/244/272/344/270/216/351/246/226/345/270/247/347/250/263/345/256/232/350/247/204/350/214/203.md +269 -0
  159. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/24-pz/345/220/257/345/212/250/344/270/216/350/277/220/350/241/214/346/227/266/347/274/226/350/257/221/346/265/201/347/250/213.md +245 -0
  160. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/25-/351/235/242/345/220/221/345/257/271/350/261/241/345/274/200/345/217/221/350/247/204/350/214/203.md +300 -0
  161. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/README.md +98 -0
  162. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/00-legacy_core/346/240/207/345/207/206pip/345/214/205/345/214/226/351/207/215/346/236/204/346/200/273/347/272/262.md +1073 -0
  163. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/01-/347/233/256/345/275/225/344/270/216/345/210/206/345/261/202/351/207/215/346/236/204/346/211/247/350/241/214/346/226/271/346/241/210.md +224 -0
  164. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/02-/345/214/205/344/270/216/345/210/206/345/217/221/350/247/204/350/214/203-/345/220/253/345/216/206/345/217/262/345/217/243/345/276/204.md +671 -0
  165. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/13-/344/270/200/346/254/241/346/200/247/345/256/236/346/226/275/346/270/205/345/215/225.md +387 -0
  166. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/14-/345/255/220/345/214/205/351/200/202/351/205/215/346/224/271/351/200/240/346/270/205/345/215/225.md +592 -0
  167. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/15-infra/350/243/201/345/211/252/344/270/216/350/220/275/344/275/215/346/270/205/345/215/225.md +81 -0
  168. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/19-core/345/215/225/344/270/200/346/255/243/345/274/217/346/226/271/346/241/210/346/224/266/346/225/233/346/211/247/350/241/214/346/270/205/345/215/225.md +161 -0
  169. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/25-/345/215/217/350/256/256/345/210/260/346/272/220/347/240/201/345/267/256/350/267/235/346/270/205/345/215/225.md +377 -0
  170. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/26-cutover/345/256/214/345/267/245/346/243/200/346/237/245/346/270/205/345/215/225.md +117 -0
  171. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/29-/345/244/232/345/233/275/350/257/255/350/250/200/350/265/204/346/272/220/346/262/273/347/220/206/344/270/216/346/214/211/351/234/200/345/212/240/350/275/275/350/247/204/350/214/203-/345/220/253/350/277/201/347/247/273/347/255/226/347/225/245.md +956 -0
  172. pz_core/docs/pz/350/247/204/350/214/203/344/270/216/344/275/277/347/224/250/archive//344/270/255/351/227/264/346/200/201/99-/350/265/204/346/272/220/346/224/266/345/217/243/345/220/216/347/273/255TODO.md +84 -0
  173. pz_core/docs//345/217/221/347/211/210/345/211/215/346/270/205/345/215/225-4.0.11.md +84 -0
  174. pz_core/docs//346/226/260/346/211/213/346/214/207/345/215/227.md +422 -0
  175. pz_core/infra/__init__.py +17 -0
  176. pz_core/infra/db/__init__.py +23 -0
  177. pz_core/infra/db/contracts.py +73 -0
  178. pz_core/infra/health/__init__.py +5 -0
  179. pz_core/infra/health/contracts.py +8 -0
  180. pz_core/infra/kv/__init__.py +5 -0
  181. pz_core/infra/kv/contracts.py +17 -0
  182. pz_core/infra/observability/__init__.py +23 -0
  183. pz_core/infra/observability/contracts.py +142 -0
  184. pz_core/infra/resilience/__init__.py +5 -0
  185. pz_core/infra/resilience/contracts.py +17 -0
  186. pz_core/infra/resources/__init__.py +5 -0
  187. pz_core/infra/resources/contracts.py +16 -0
  188. pz_core/infra/settings/__init__.py +17 -0
  189. pz_core/infra/settings/models.py +81 -0
  190. pz_core/infra/storage/__init__.py +5 -0
  191. pz_core/infra/storage/ports.py +27 -0
  192. pz_core/project_root_commands.py +282 -0
  193. pz_core/project_runtime_cli.py +344 -0
  194. pz_core/project_sources.py +253 -0
  195. pz_core/pz_launcher.py +209 -0
  196. pz_core/root_cli.py +70 -0
  197. pz_core/runtime/__init__.py +229 -0
  198. pz_core/runtime/access.py +86 -0
  199. pz_core/runtime/adapters/__init__.py +5 -0
  200. pz_core/runtime/adapters/base.py +18 -0
  201. pz_core/runtime/asyncio_bridge.py +18 -0
  202. pz_core/runtime/bindings/__init__.py +5 -0
  203. pz_core/runtime/bindings/container.py +50 -0
  204. pz_core/runtime/cli/__init__.py +5 -0
  205. pz_core/runtime/cli/_args.py +67 -0
  206. pz_core/runtime/cli/app_commands.py +417 -0
  207. pz_core/runtime/cli/check.py +214 -0
  208. pz_core/runtime/cli/db.py +297 -0
  209. pz_core/runtime/cli/main.py +89 -0
  210. pz_core/runtime/cli/resources.py +280 -0
  211. pz_core/runtime/discovery.py +23 -0
  212. pz_core/runtime/environment_integrity.py +157 -0
  213. pz_core/runtime/errors.py +5 -0
  214. pz_core/runtime/events.py +87 -0
  215. pz_core/runtime/facades/__init__.py +38 -0
  216. pz_core/runtime/facades/_capabilities.py +46 -0
  217. pz_core/runtime/facades/cache.py +103 -0
  218. pz_core/runtime/facades/database.py +71 -0
  219. pz_core/runtime/facades/events.py +380 -0
  220. pz_core/runtime/facades/health.py +101 -0
  221. pz_core/runtime/facades/mail.py +121 -0
  222. pz_core/runtime/facades/observability.py +102 -0
  223. pz_core/runtime/facades/providers.py +75 -0
  224. pz_core/runtime/facades/resources.py +52 -0
  225. pz_core/runtime/facades/storage.py +296 -0
  226. pz_core/runtime/health/__init__.py +5 -0
  227. pz_core/runtime/health/service.py +102 -0
  228. pz_core/runtime/host.py +188 -0
  229. pz_core/runtime/host_runner.py +282 -0
  230. pz_core/runtime/http/__init__.py +20 -0
  231. pz_core/runtime/http/app.py +576 -0
  232. pz_core/runtime/http_timing.py +173 -0
  233. pz_core/runtime/invocation.py +29 -0
  234. pz_core/runtime/json_safe.py +47 -0
  235. pz_core/runtime/lifecycle/__init__.py +25 -0
  236. pz_core/runtime/lifecycle/manager.py +533 -0
  237. pz_core/runtime/plan.py +214 -0
  238. pz_core/runtime/plan_context.py +33 -0
  239. pz_core/runtime/plan_snapshot.py +177 -0
  240. pz_core/runtime/registries/__init__.py +27 -0
  241. pz_core/runtime/registries/capabilities.py +101 -0
  242. pz_core/runtime/registries/providers.py +396 -0
  243. pz_core/runtime/resource_assets.py +344 -0
  244. pz_core/runtime/run_cli.py +211 -0
  245. pz_core/runtime/settings.py +888 -0
  246. pz_core/runtime/worker/__init__.py +21 -0
  247. pz_core/runtime/worker/engine.py +921 -0
  248. pz_core/runtime/worker/runtime.py +25 -0
  249. pz_core/testing/__init__.py +15 -0
  250. pz_core/testing/doc_route_contracts.py +305 -0
  251. pz_core/utils/__init__.py +44 -0
  252. pz_core/utils/env.py +65 -0
  253. pz_core/utils/project_jsonc/__init__.py +29 -0
  254. pz_core/utils/project_jsonc/document.py +420 -0
  255. pz_core/utils/project_settings.py +99 -0
  256. pz_foundation/__init__.py +50 -0
  257. pz_foundation/_contracts.py +81 -0
  258. pz_foundation/_errors.py +34 -0
  259. pz_foundation/api.py +14 -0
  260. pz_foundation/apps.py +127 -0
  261. pz_foundation/auth/__init__.py +1 -0
  262. pz_foundation/cache_control.py +233 -0
  263. pz_foundation/cli/__init__.py +2 -0
  264. pz_foundation/cli/workers.py +565 -0
  265. pz_foundation/configs/__init__.py +0 -0
  266. pz_foundation/configs/default.env +15 -0
  267. pz_foundation/configs/default.jsonc +452 -0
  268. pz_foundation/db/__init__.py +94 -0
  269. pz_foundation/db/aerich_executor.py +664 -0
  270. pz_foundation/db/config.py +358 -0
  271. pz_foundation/db/connection_manager.py +689 -0
  272. pz_foundation/db/connection_probe.py +204 -0
  273. pz_foundation/db/database.py +1291 -0
  274. pz_foundation/db/deps.py +47 -0
  275. pz_foundation/db/lifecycle_status.py +85 -0
  276. pz_foundation/db/migrations.py +477 -0
  277. pz_foundation/db/mysql.py +57 -0
  278. pz_foundation/db/postgresql.py +409 -0
  279. pz_foundation/db/production_pool_fallback.py +143 -0
  280. pz_foundation/db/public.py +45 -0
  281. pz_foundation/db/session.py +369 -0
  282. pz_foundation/db/sqlite.py +15 -0
  283. pz_foundation/db/tortoise_manager.py +724 -0
  284. pz_foundation/db/tortoise_psycopg.py +148 -0
  285. pz_foundation/docs/README.md +18 -0
  286. pz_foundation/docs/distribution-README.md +319 -0
  287. pz_foundation/docs/infra/350/243/201/345/211/252/344/270/216/350/220/275/344/275/215/350/257/264/346/230/216.md +39 -0
  288. pz_foundation/docs//345/205/254/345/274/200/345/205/215/350/264/271/346/216/245/345/217/243/351/230/262/346/273/245/347/224/250/344/270/216/344/272/272/346/234/272/346/240/241/351/252/214.md +680 -0
  289. pz_foundation/docs//350/256/276/350/256/241/346/226/207/346/241/243.md +288 -0
  290. pz_foundation/docs//350/267/257/347/224/261/344/270/216URL/345/244/204/347/220/206/350/247/204/350/214/203.md +119 -0
  291. pz_foundation/health.py +105 -0
  292. pz_foundation/host/__init__.py +11 -0
  293. pz_foundation/host/builder.py +34 -0
  294. pz_foundation/host/cache_runtime.py +44 -0
  295. pz_foundation/host/db/__init__.py +17 -0
  296. pz_foundation/host/db/aerich_config.py +36 -0
  297. pz_foundation/host/db/config.py +106 -0
  298. pz_foundation/host/db/connection_manager.py +48 -0
  299. pz_foundation/host/db/deps.py +5 -0
  300. pz_foundation/host/db/orm_retry_patch.py +566 -0
  301. pz_foundation/host/db/request_adapter.py +325 -0
  302. pz_foundation/host/db/router.py +28 -0
  303. pz_foundation/host/db/session.py +284 -0
  304. pz_foundation/host/db/tortoise_manager.py +10 -0
  305. pz_foundation/host/idempotency.py +132 -0
  306. pz_foundation/host/lifespan.py +247 -0
  307. pz_foundation/host/redis_runtime.py +100 -0
  308. pz_foundation/host/web.py +790 -0
  309. pz_foundation/infra_provider.py +236 -0
  310. pz_foundation/kv/__init__.py +25 -0
  311. pz_foundation/kv/cache.py +1166 -0
  312. pz_foundation/kv/deps.py +84 -0
  313. pz_foundation/kv/public.py +25 -0
  314. pz_foundation/kv/redis_manager.py +1531 -0
  315. pz_foundation/lazy_exports.py +43 -0
  316. pz_foundation/lazy_imports.py +124 -0
  317. pz_foundation/lifecycle.py +392 -0
  318. pz_foundation/managed_workers.py +1117 -0
  319. pz_foundation/middlewares/__init__.py +26 -0
  320. pz_foundation/middlewares/_settings.py +250 -0
  321. pz_foundation/middlewares/analytics.py +124 -0
  322. pz_foundation/middlewares/cache_control.py +156 -0
  323. pz_foundation/middlewares/compression.py +202 -0
  324. pz_foundation/middlewares/cors.py +62 -0
  325. pz_foundation/middlewares/geo_country.py +44 -0
  326. pz_foundation/middlewares/inner_router.py +50 -0
  327. pz_foundation/middlewares/rate_limited/__init__.py +3 -0
  328. pz_foundation/middlewares/rate_limited/key_limiter.py +115 -0
  329. pz_foundation/middlewares/request_logging.py +104 -0
  330. pz_foundation/middlewares/route_owner.py +309 -0
  331. pz_foundation/middlewares/security_csrf.py +44 -0
  332. pz_foundation/middlewares/security_headers/__init__.py +4 -0
  333. pz_foundation/middlewares/security_headers/conflicts.py +44 -0
  334. pz_foundation/middlewares/security_headers/csp_nonce.py +200 -0
  335. pz_foundation/middlewares/security_headers/security_headers.py +44 -0
  336. pz_foundation/migrations/__init__.py +1 -0
  337. pz_foundation/migrations/pz_foundation/__init__.py +1 -0
  338. pz_foundation/models.py +22 -0
  339. pz_foundation/notifications/__init__.py +23 -0
  340. pz_foundation/notifications/email.py +542 -0
  341. pz_foundation/notifications/public.py +31 -0
  342. pz_foundation/observability/__init__.py +71 -0
  343. pz_foundation/observability/http.py +34 -0
  344. pz_foundation/observability/logger/__init__.py +49 -0
  345. pz_foundation/observability/logger/_bot_settings.py +126 -0
  346. pz_foundation/observability/logger/bot_message.py +592 -0
  347. pz_foundation/observability/logger/core.py +385 -0
  348. pz_foundation/observability/logger/delivery_audit.py +84 -0
  349. pz_foundation/observability/logger/feishu_bot.py +199 -0
  350. pz_foundation/observability/logger/telegram_bot.py +194 -0
  351. pz_foundation/observability/metrics.py +365 -0
  352. pz_foundation/observability/runtime.py +68 -0
  353. pz_foundation/public.py +405 -0
  354. pz_foundation/resources/__init__.py +12 -0
  355. pz_foundation/resources/builder.py +900 -0
  356. pz_foundation/resources/images.py +363 -0
  357. pz_foundation/root_cli.py +20 -0
  358. pz_foundation/routing/__init__.py +203 -0
  359. pz_foundation/routing/canonical.py +486 -0
  360. pz_foundation/routing/convertors.py +82 -0
  361. pz_foundation/routing/declarations.py +843 -0
  362. pz_foundation/routing/exports.py +148 -0
  363. pz_foundation/routing/loaders.py +138 -0
  364. pz_foundation/routing/manifest.py +215 -0
  365. pz_foundation/routing/manifest_provider.py +47 -0
  366. pz_foundation/routing/mounts.py +101 -0
  367. pz_foundation/routing/ordering.py +172 -0
  368. pz_foundation/routing/registry.py +133 -0
  369. pz_foundation/routing/utils.py +28 -0
  370. pz_foundation/runtime.py +234 -0
  371. pz_foundation/settings.py +253 -0
  372. pz_foundation/settings_normalization.py +130 -0
  373. pz_foundation/storage/__init__.py +25 -0
  374. pz_foundation/storage/local.py +209 -0
  375. pz_foundation/storage/public.py +106 -0
  376. pz_foundation/storage/s3.py +116 -0
  377. pz_foundation/storage/service.py +234 -0
  378. pz_foundation/urls.py +19 -0
  379. pz_foundation/utils/__init__.py +6 -0
  380. pz_foundation/utils/merge.py +160 -0
  381. pz_foundation/worker_replicas.py +55 -0
  382. pz_settings_center/__init__.py +5 -0
  383. pz_settings_center/api/__init__.py +5 -0
  384. pz_settings_center/api/runtime_overrides.py +360 -0
  385. pz_settings_center/apps.py +28 -0
  386. pz_settings_center/configs/__init__.py +0 -0
  387. pz_settings_center/configs/default.env +2 -0
  388. pz_settings_center/configs/default.jsonc +1 -0
  389. pz_settings_center/docs/01-settings_center/350/203/275/345/212/233/350/276/271/347/225/214.md +124 -0
  390. pz_settings_center/docs/README.md +12 -0
  391. pz_settings_center/docs/distribution-README.md +150 -0
  392. pz_settings_center/docs//350/256/276/350/256/241/346/226/207/346/241/243.md +48 -0
  393. pz_settings_center/integration_payload.py +18 -0
  394. pz_settings_center/project_helpers.py +405 -0
  395. pz_settings_center/public.py +139 -0
  396. pz_settings_center/routing_helpers.py +73 -0
  397. pz_settings_center/runtime_override_provider.py +61 -0
  398. pz_settings_center/typed_settings.py +324 -0
  399. pz_settings_center/urls.py +9 -0
@@ -0,0 +1,325 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from collections.abc import Iterable
5
+ from pathlib import Path
6
+
7
+ from fastapi import Request, Response
8
+ from starlette.requests import ClientDisconnect
9
+ from starlette.types import ASGIApp, Receive, Scope, Send
10
+
11
+ from pz_foundation.db import describe_foundation_database_binding, load_foundation_database_settings
12
+ from pz_foundation.db.lifecycle_status import connection_lifecycle_status
13
+ from pz_foundation.host.db.connection_manager import db_manager
14
+ from pz_foundation.host.db.session import DBConnectionUnavailable, DBRequestContext, db_session
15
+ from pz_foundation.db.tortoise_manager import tortoise_manager
16
+ from pz_foundation.observability import get_logger
17
+ import pz_settings_center.public as settings_center
18
+
19
+
20
+ def _root_value(path: tuple[str, ...], default: object) -> object:
21
+ current: object = settings_center.settings
22
+ for part in path:
23
+ if isinstance(current, dict):
24
+ current = current.get(part, default)
25
+ continue
26
+ current = getattr(current, part, default)
27
+ return current
28
+
29
+
30
+ def _read_root_string(*path: str, default: str) -> str:
31
+ try:
32
+ value = str(_root_value(tuple(path), default) or default).strip()
33
+ except Exception:
34
+ return default
35
+ return value or default
36
+
37
+
38
+ def _read_root_float(*path: str, default: float) -> float:
39
+ try:
40
+ return float(_root_value(tuple(path), default))
41
+ except Exception:
42
+ return float(default)
43
+
44
+
45
+ def _read_root_sequence(*path: str, default: tuple[str, ...] = ()) -> tuple[str, ...]:
46
+ try:
47
+ value = _root_value(tuple(path), default)
48
+ except Exception:
49
+ return tuple(default)
50
+ if isinstance(value, str):
51
+ return tuple(part.strip() for part in value.split(",") if part.strip()) or tuple(default)
52
+ if not isinstance(value, (list, tuple)):
53
+ return tuple(default)
54
+ return tuple(str(item).strip() for item in value if str(item).strip()) or tuple(default)
55
+
56
+
57
+ def _database_enabled(project_dir: str | Path | None = None) -> bool:
58
+ resolved_project_dir = None if project_dir is None else str(Path(project_dir).resolve())
59
+ status = describe_foundation_database_binding(project_dir=resolved_project_dir)
60
+ if status:
61
+ return bool(status.get("enabled", False))
62
+ return bool(load_foundation_database_settings(project_dir=resolved_project_dir).enabled)
63
+
64
+
65
+ class DBRequestScopeAdapter:
66
+ """Host-internal ASGI adapter for request-scoped DB routing."""
67
+
68
+ def __init__(self, app: ASGIApp, *, project_dir: str | Path | None = None) -> None:
69
+ self.app = app
70
+ self._logger = get_logger("pz.foundation.host.db.request_adapter")
71
+ database_settings = load_foundation_database_settings(project_dir=project_dir)
72
+ self.last_check_time = 0.0
73
+ self.check_interval = max(1.0, float(getattr(database_settings, "health_check_interval", 60.0) or 60.0))
74
+ self._recovery_task = None
75
+ self.read_write_paths = tuple(
76
+ self._normalize_prefixes(_read_root_sequence("DB_READ_WRITE_PATHS", default=()))
77
+ )
78
+ self.read_only_paths = tuple(
79
+ self._normalize_prefixes(_read_root_sequence("DB_READ_ONLY_PATHS", default=()))
80
+ )
81
+ default_api_prefix = _read_root_string("project", "api_v1_str", default="/api/v1")
82
+ self.skip_prefixes = tuple(
83
+ self._normalize_prefixes(
84
+ _read_root_sequence(
85
+ "DB_CONNECTION_SKIP_PREFIXES",
86
+ default=(
87
+ "/static/",
88
+ "/uploads/",
89
+ "/docs",
90
+ "/redoc",
91
+ "/openapi.json",
92
+ "/health",
93
+ "/live",
94
+ "/livez",
95
+ "/liveness",
96
+ "/ready",
97
+ "/readiness",
98
+ ),
99
+ )
100
+ )
101
+ )
102
+ self.skip_paths = tuple(
103
+ str(item).strip()
104
+ for item in _read_root_sequence("DB_CONNECTION_SKIP_PATHS", default=())
105
+ if str(item).strip()
106
+ )
107
+ self.route_header = _read_root_string("DB_ROUTE_HEADER", default="X-DB-Route")
108
+ self.force_write_header = _read_root_string("DB_FORCE_WRITE_HEADER", default="X-DB-Force-Write")
109
+ self.prefer_read_header = _read_root_string("DB_PREFER_READ_HEADER", default="X-DB-Prefer-Read")
110
+ self.route_query = _read_root_string("DB_ROUTE_QUERY", default="db_route")
111
+ self.force_write_query = _read_root_string("DB_FORCE_WRITE_QUERY", default="db_force_write")
112
+ self.prefer_read_query = _read_root_string("DB_PREFER_READ_QUERY", default="db_prefer_read")
113
+ self.readonly_methods = tuple(
114
+ str(item).strip().upper()
115
+ for item in _read_root_sequence("DB_READONLY_METHODS", default=("GET", "HEAD", "OPTIONS"))
116
+ if str(item).strip()
117
+ )
118
+ self.safe_methods = tuple(
119
+ str(item).strip().upper()
120
+ for item in _read_root_sequence("DB_SAFE_METHODS", default=("GET", "HEAD", "OPTIONS"))
121
+ if str(item).strip()
122
+ )
123
+ if not self.read_write_paths:
124
+ self.read_write_paths = (f"{default_api_prefix.rstrip('/')}/admin",)
125
+ self.database_enabled = _database_enabled(project_dir)
126
+
127
+ @staticmethod
128
+ def _normalize_prefixes(prefixes: Iterable[str]) -> tuple[str, ...]:
129
+ return tuple(str(item).strip() for item in prefixes if str(item).strip())
130
+
131
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
132
+ if scope.get("type") != "http" or not self.database_enabled:
133
+ await self.app(scope, receive, send)
134
+ return
135
+
136
+ request = Request(scope, receive=receive)
137
+ path = request.url.path or "/"
138
+ try:
139
+ if path in self.skip_paths or any(path.startswith(prefix) for prefix in self.skip_prefixes):
140
+ await self.app(scope, receive, send)
141
+ return
142
+ except Exception:
143
+ pass
144
+
145
+ await self._periodic_health_check()
146
+
147
+ context = self._build_request_context(request)
148
+ request.state.db_preference = context.preference
149
+ request.state.force_write_db = context.force_write
150
+ request.state.prefer_read_db = context.prefer_read
151
+ request.state.db_route_reason = context.reason
152
+ request.state.db_connection_alias = None
153
+ response_started = False
154
+ active_alias: str | None = None
155
+
156
+ async def send_wrapper(message):
157
+ nonlocal response_started
158
+ if message.get("type") == "http.response.start":
159
+ response_started = True
160
+ await send(message)
161
+
162
+ try:
163
+ async with db_session.request_scope(
164
+ context.preference,
165
+ force_write=context.force_write,
166
+ prefer_read=context.prefer_read,
167
+ reason=context.reason,
168
+ ) as active_alias:
169
+ request.state.db_connection_alias = active_alias
170
+ await self.app(scope, receive, send_wrapper)
171
+ except Exception as exc:
172
+ if (
173
+ active_alias == "read_only"
174
+ and not response_started
175
+ and request.method.upper() in set(self.safe_methods)
176
+ ):
177
+ self._logger.warning(
178
+ "Read-only DB request failed, retrying on default connection: %s",
179
+ exc,
180
+ exc_info=True,
181
+ )
182
+ request.state.db_preference = "write"
183
+ request.state.force_write_db = True
184
+ request.state.prefer_read_db = False
185
+ request.state.db_route_reason = f"{context.reason} fallback=default"
186
+ try:
187
+ async with db_session.request_scope(
188
+ "write",
189
+ force_write=True,
190
+ prefer_read=False,
191
+ reason=f"{context.reason} fallback=default",
192
+ ) as fallback_alias:
193
+ request.state.db_connection_alias = fallback_alias
194
+ await self.app(scope, receive, send_wrapper)
195
+ return
196
+ except Exception as retry_exc:
197
+ exc = retry_exc
198
+ if isinstance(exc, DBConnectionUnavailable):
199
+ if self._should_suppress_error_response(exc, response_started=response_started):
200
+ self._log_suppressed_downstream_error(exc, response_started=response_started)
201
+ return
202
+ self._logger.warning("DB lifecycle unavailable in request path: %s", exc)
203
+ await Response(content="Service Unavailable", status_code=503)(scope, receive, send)
204
+ return
205
+ if self._should_suppress_error_response(exc, response_started=response_started):
206
+ self._log_suppressed_downstream_error(exc, response_started=response_started)
207
+ return
208
+ self._logger.error("Downstream error in DB request adapter: %s", exc, exc_info=True)
209
+ try:
210
+ await Response(content="Internal Server Error", status_code=500)(scope, receive, send)
211
+ except Exception as response_exc:
212
+ if self._should_suppress_error_response(response_exc, response_started=response_started):
213
+ self._log_suppressed_downstream_error(response_exc, response_started=response_started)
214
+ return
215
+ raise
216
+
217
+ async def _periodic_health_check(self) -> None:
218
+ import time
219
+
220
+ now = time.time()
221
+ if self._startup_db_health_ready():
222
+ return
223
+
224
+ self._schedule_background_recovery()
225
+ if (now - self.last_check_time) < self.check_interval:
226
+ return
227
+ self.last_check_time = now
228
+ self._logger.debug("DB lifecycle is not ready on request path; background recovery has been scheduled")
229
+
230
+ def _schedule_background_recovery(self) -> None:
231
+ task = self._recovery_task
232
+ if task is not None and not bool(getattr(task, "done", lambda: True)()):
233
+ return
234
+
235
+ async def _recover() -> None:
236
+ try:
237
+ await db_manager.probe_and_reconnect(force=True)
238
+ except Exception:
239
+ self._logger.exception("DB lifecycle background recovery failed")
240
+
241
+ self._recovery_task = asyncio.create_task(_recover())
242
+
243
+ @staticmethod
244
+ def _startup_db_health_ready() -> bool:
245
+ return connection_lifecycle_status(tortoise_manager).default_ready
246
+
247
+ def _build_request_context(self, request: Request) -> DBRequestContext:
248
+ path = request.url.path or "/"
249
+ method = request.method.upper()
250
+ readonly_methods = set(self.readonly_methods)
251
+ safe_methods = set(self.safe_methods)
252
+ preference = "read_only" if method in readonly_methods else "write"
253
+ force_write = method not in safe_methods
254
+ prefer_read = preference == "read_only"
255
+
256
+ for prefix in self.read_write_paths:
257
+ if path.startswith(prefix):
258
+ preference = "write"
259
+ force_write = True
260
+ prefer_read = False
261
+ break
262
+ else:
263
+ for prefix in self.read_only_paths:
264
+ if path.startswith(prefix):
265
+ preference = "read_only"
266
+ force_write = False
267
+ prefer_read = True
268
+ break
269
+
270
+ override = (request.headers.get(self.route_header) or request.query_params.get(self.route_query) or "").lower()
271
+ if override in {"read", "read_only", "write"}:
272
+ preference = "read_only" if override in {"read", "read_only"} else "write"
273
+ prefer_read = preference == "read_only"
274
+ force_write = preference == "write"
275
+
276
+ force_override = request.headers.get(self.force_write_header) or request.query_params.get(self.force_write_query)
277
+ if force_override is not None and str(force_override).strip().lower() in {"1", "true", "yes", "on"}:
278
+ preference = "write"
279
+ force_write = True
280
+ prefer_read = False
281
+
282
+ prefer_override = request.headers.get(self.prefer_read_header) or request.query_params.get(self.prefer_read_query)
283
+ if prefer_override is not None and not force_write and str(prefer_override).strip().lower() in {"1", "true", "yes", "on"}:
284
+ preference = "read_only"
285
+ prefer_read = True
286
+
287
+ reason = f"{method} {path}"
288
+ if override:
289
+ reason += f" override={override}"
290
+ if force_write:
291
+ reason += " forced-write"
292
+ return DBRequestContext(
293
+ preference=preference,
294
+ force_write=force_write,
295
+ prefer_read=prefer_read,
296
+ reason=reason,
297
+ )
298
+
299
+ @staticmethod
300
+ def _should_suppress_error_response(exc: Exception, *, response_started: bool) -> bool:
301
+ if response_started:
302
+ return True
303
+ if isinstance(exc, ClientDisconnect):
304
+ return True
305
+ if isinstance(exc, RuntimeError):
306
+ detail = str(exc)
307
+ if "response already completed" in detail:
308
+ return True
309
+ return False
310
+
311
+ def _log_suppressed_downstream_error(self, exc: Exception, *, response_started: bool) -> None:
312
+ if isinstance(exc, ClientDisconnect):
313
+ self._logger.debug("Suppressed DB request adapter client disconnect")
314
+ return
315
+ if response_started or self._should_suppress_error_response(exc, response_started=response_started):
316
+ self._logger.debug("Suppressed DB request adapter downstream error after response lifecycle closed: %s", exc)
317
+ return
318
+ self._logger.warning("Suppressed DB request adapter downstream error: %s", exc)
319
+
320
+
321
+ def wrap_db_request_scope(app: ASGIApp, *, project_dir: str | Path | None = None) -> ASGIApp:
322
+ return DBRequestScopeAdapter(app, project_dir=project_dir)
323
+
324
+
325
+ __all__ = ["DBRequestScopeAdapter", "wrap_db_request_scope"]
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .session import get_active_connection_alias, get_request_context
6
+
7
+
8
+ class RequestScopedDBRouter:
9
+ """Route ORM reads through the active host request DB alias."""
10
+
11
+ @staticmethod
12
+ def _read_alias() -> str:
13
+ active_alias = get_active_connection_alias()
14
+ if active_alias in {"default", "read_only"}:
15
+ return active_alias
16
+ context = get_request_context()
17
+ if context.force_write:
18
+ return "default"
19
+ return "read_only" if context.should_use_read() else "default"
20
+
21
+ def db_for_read(self, _model: type[Any]) -> str:
22
+ return self._read_alias()
23
+
24
+ def db_for_write(self, _model: type[Any]) -> str:
25
+ return "default"
26
+
27
+
28
+ __all__ = ["RequestScopedDBRouter"]
@@ -0,0 +1,284 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from contextlib import asynccontextmanager
5
+ from contextvars import ContextVar, Token
6
+ from dataclasses import dataclass
7
+ from typing import Any, AsyncIterator, Awaitable, Callable, Literal, Optional, TypeVar
8
+
9
+ from pz_foundation.db.connection_manager import _is_pool_exhausted_error, _is_transient_db_error
10
+ from tortoise import connections
11
+
12
+ from pz_foundation.host.db.config import build_cluster_manager, build_tortoise_config
13
+ from pz_foundation.host.db.connection_manager import db_manager
14
+ from pz_foundation.host.db.tortoise_manager import tortoise_manager
15
+
16
+ try:
17
+ from tortoise.transactions import in_transaction as _tortoise_in_transaction
18
+ except Exception: # pragma: no cover
19
+ _tortoise_in_transaction = None # type: ignore[assignment]
20
+
21
+
22
+ def _cluster_factory():
23
+ return build_cluster_manager()
24
+
25
+
26
+ T = TypeVar("T")
27
+ TransactionFunc = Callable[[Any], Awaitable[T]]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class DBRequestContext:
32
+ preference: Literal["read_only", "write"] = "write"
33
+ force_write: bool = False
34
+ prefer_read: bool = False
35
+ reason: Optional[str] = None
36
+
37
+ def should_use_read(self) -> bool:
38
+ return not self.force_write and (self.preference == "read_only" or self.prefer_read)
39
+
40
+
41
+ class DBConnectionUnavailable(RuntimeError):
42
+ """Raised when a request would need a DB pool that is not lifecycle-ready."""
43
+
44
+
45
+ _DEFAULT_DB_CONTEXT = DBRequestContext()
46
+ _db_request_context: ContextVar[DBRequestContext] = ContextVar(
47
+ "pz_host_db_request_context",
48
+ default=_DEFAULT_DB_CONTEXT,
49
+ )
50
+ _active_db_connection_alias: ContextVar[str | None] = ContextVar(
51
+ "pz_host_active_db_connection_alias",
52
+ default=None,
53
+ )
54
+
55
+
56
+ def _normalize_preference(preference: str) -> Literal["read_only", "write"]:
57
+ if isinstance(preference, str) and preference.lower() in {"read", "read_only"}:
58
+ return "read_only"
59
+ return "write"
60
+
61
+
62
+ def get_request_context() -> DBRequestContext:
63
+ return _db_request_context.get()
64
+
65
+
66
+ def get_active_connection_alias() -> str | None:
67
+ return _active_db_connection_alias.get()
68
+
69
+
70
+ def push_request_context(
71
+ preference: str,
72
+ *,
73
+ force_write: bool = False,
74
+ prefer_read: bool = False,
75
+ reason: Optional[str] = None,
76
+ ) -> tuple[Token, DBRequestContext]:
77
+ context = DBRequestContext(
78
+ preference=_normalize_preference(preference),
79
+ force_write=force_write,
80
+ prefer_read=prefer_read,
81
+ reason=reason,
82
+ )
83
+ token = _db_request_context.set(context)
84
+ return token, context
85
+
86
+
87
+ def reset_request_context(token: Token) -> None:
88
+ _db_request_context.reset(token)
89
+
90
+
91
+ async def _ensure_connection_ready(connection_name: str) -> None:
92
+ if connection_name == "default":
93
+ if tortoise_manager.has_connection(connection_name):
94
+ tortoise_manager.get_connection(connection_name)
95
+ return
96
+ await db_manager.ensure_ready()
97
+ return
98
+ await tortoise_manager.ensure_initialized(
99
+ config_builder=build_tortoise_config,
100
+ cluster_factory=_cluster_factory,
101
+ )
102
+ tortoise_manager.get_connection(connection_name)
103
+
104
+
105
+ async def _reconnect(connection_name: str) -> None:
106
+ if connection_name == "default":
107
+ if tortoise_manager.has_connection(connection_name):
108
+ await tortoise_manager.reconnect(connection_name)
109
+ return
110
+ await db_manager.check_and_reconnect(force=True)
111
+ return
112
+ await tortoise_manager.reconnect(connection_name)
113
+
114
+
115
+ def _is_connection_closed(conn: Any) -> bool:
116
+ pool = getattr(conn, "_pool", None)
117
+ return bool(getattr(pool, "closed", False))
118
+
119
+
120
+ def _connection_is_hot_and_open(connection_name: str) -> bool:
121
+ try:
122
+ has_connection = getattr(tortoise_manager, "has_connection", None)
123
+ if callable(has_connection) and not bool(has_connection(connection_name)):
124
+ return False
125
+ conn = tortoise_manager.get_connection(connection_name)
126
+ if _is_connection_closed(conn):
127
+ return False
128
+ current_loop_id_getter = getattr(tortoise_manager, "_current_loop_id", None)
129
+ current_loop_id = current_loop_id_getter() if callable(current_loop_id_getter) else None
130
+ manager_loop_id = getattr(tortoise_manager, "_loop_id", None)
131
+ if current_loop_id is not None and manager_loop_id is not None and current_loop_id != manager_loop_id:
132
+ return False
133
+ pool_ready = getattr(tortoise_manager, "_connection_pool_ready", None)
134
+ if callable(pool_ready) and not bool(pool_ready(connection_name)):
135
+ return False
136
+ return True
137
+ except Exception:
138
+ return False
139
+
140
+
141
+ def _default_connection_is_hot_and_open() -> bool:
142
+ return _connection_is_hot_and_open("default")
143
+
144
+
145
+ def _resolve_active_connection(connection_name: str) -> Any | None:
146
+ try:
147
+ storage = connections._get_storage()
148
+ except Exception:
149
+ return None
150
+ return storage.get(connection_name)
151
+
152
+
153
+ def _build_transaction_context(connection_name: str, *args: Any, **kwargs: Any):
154
+ active_conn = _resolve_active_connection(connection_name)
155
+ if active_conn is not None:
156
+ tx_factory = getattr(active_conn, "in_transaction", None)
157
+ if tx_factory is not None:
158
+ return tx_factory()
159
+
160
+ if _tortoise_in_transaction is not None:
161
+ try:
162
+ return _tortoise_in_transaction(connection_name=connection_name, *args, **kwargs)
163
+ except RuntimeError as exc:
164
+ if "No TortoiseContext is currently active" not in str(exc):
165
+ raise
166
+
167
+ conn = tortoise_manager.get_connection(connection_name)
168
+ tx_factory = getattr(conn, "in_transaction", None)
169
+ if tx_factory is None:
170
+ @asynccontextmanager
171
+ async def _passthrough() -> AsyncIterator[Any]:
172
+ yield conn
173
+
174
+ return _passthrough()
175
+ return tx_factory()
176
+
177
+
178
+ @asynccontextmanager
179
+ async def in_transaction(connection_name: str = "default", *args: Any, **kwargs: Any) -> AsyncIterator[Any]:
180
+ max_retries = 3
181
+ tx_cm = None
182
+ tx = None
183
+
184
+ for attempt in range(max_retries):
185
+ await _ensure_connection_ready(connection_name)
186
+ tx_cm = _build_transaction_context(connection_name, *args, **kwargs)
187
+ try:
188
+ tx = await tx_cm.__aenter__()
189
+ break
190
+ except Exception as exc: # noqa: BLE001
191
+ if _is_pool_exhausted_error(exc) or not _is_transient_db_error(exc) or attempt == max_retries - 1:
192
+ raise
193
+ await _reconnect(connection_name)
194
+ else: # pragma: no cover
195
+ raise RuntimeError(f"failed to open transaction for connection '{connection_name}'")
196
+
197
+ try:
198
+ yield tx
199
+ except BaseException as exc:
200
+ suppress = await tx_cm.__aexit__(type(exc), exc, exc.__traceback__)
201
+ if not suppress:
202
+ raise
203
+ else:
204
+ await tx_cm.__aexit__(None, None, None)
205
+
206
+
207
+ class HostDBRequestSession:
208
+ async def _ensure_read_connection_available(self) -> bool:
209
+ return _connection_is_hot_and_open("read_only")
210
+
211
+ async def _ensure_write_connection_available(self) -> None:
212
+ if _default_connection_is_hot_and_open():
213
+ return
214
+ raise DBConnectionUnavailable("default database connection lifecycle is not ready")
215
+
216
+ @asynccontextmanager
217
+ async def _use_connection(self, connection_name: str) -> AsyncIterator[None]:
218
+ alias_token = _active_db_connection_alias.set(connection_name)
219
+ try:
220
+ conn = tortoise_manager.get_connection(connection_name)
221
+ token = connections.set(connection_name, conn)
222
+ try:
223
+ yield
224
+ finally:
225
+ connections.reset(token)
226
+ finally:
227
+ _active_db_connection_alias.reset(alias_token)
228
+
229
+ @asynccontextmanager
230
+ async def request_scope(
231
+ self,
232
+ preference: str,
233
+ *,
234
+ force_write: bool = False,
235
+ prefer_read: bool = False,
236
+ reason: Optional[str] = None,
237
+ ) -> AsyncIterator[str]:
238
+ token, context = push_request_context(
239
+ preference,
240
+ force_write=force_write,
241
+ prefer_read=prefer_read,
242
+ reason=reason,
243
+ )
244
+ try:
245
+ use_read = False
246
+ if not context.force_write:
247
+ use_read = context.should_use_read() and await self._ensure_read_connection_available()
248
+ connection_name = "read_only" if use_read else "default"
249
+ if connection_name == "default":
250
+ await self._ensure_write_connection_available()
251
+ async with self._use_connection(connection_name):
252
+ yield connection_name
253
+ finally:
254
+ reset_request_context(token)
255
+
256
+
257
+ async def run_in_transaction(
258
+ func: TransactionFunc[T],
259
+ *,
260
+ connection_name: str = "default",
261
+ **kwargs: Any,
262
+ ) -> T:
263
+ async with in_transaction(connection_name=connection_name, **kwargs) as conn:
264
+ return await func(conn)
265
+
266
+
267
+ write_transaction = in_transaction
268
+ db_session = HostDBRequestSession()
269
+ request_scope = db_session.request_scope
270
+
271
+
272
+ __all__ = [
273
+ "DBRequestContext",
274
+ "DBConnectionUnavailable",
275
+ "db_session",
276
+ "get_active_connection_alias",
277
+ "get_request_context",
278
+ "in_transaction",
279
+ "push_request_context",
280
+ "request_scope",
281
+ "reset_request_context",
282
+ "run_in_transaction",
283
+ "write_transaction",
284
+ ]
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from pz_foundation.db.tortoise_manager import (
4
+ ConfigBuilder,
5
+ ClusterFactory,
6
+ get_connection_status,
7
+ tortoise_manager,
8
+ )
9
+
10
+ __all__ = ["ConfigBuilder", "ClusterFactory", "get_connection_status", "tortoise_manager"]