neutralino-python 0.1.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 (521) hide show
  1. neutralino/__init__.py +88 -0
  2. neutralino/_catalog.py +297 -0
  3. neutralino/_data/LICENSE.neutralino-js-client +21 -0
  4. neutralino/_data/LICENSE.neutralinojs +1066 -0
  5. neutralino/_data/docs/cli.md +315 -0
  6. neutralino/_data/docs/custom-components.md +107 -0
  7. neutralino/_data/docs/custom-frontends.md +80 -0
  8. neutralino/_data/docs/desktop-helpers.md +296 -0
  9. neutralino/_data/docs/guide.md +131 -0
  10. neutralino/_data/docs/llms-full.txt +3921 -0
  11. neutralino/_data/docs/llms.txt +43 -0
  12. neutralino/_data/docs/manifests/components.json +20128 -0
  13. neutralino/_data/docs/manifests/examples.json +52 -0
  14. neutralino/_data/docs/manifests/native.json +3024 -0
  15. neutralino/_data/docs/manifests/schema.json +43 -0
  16. neutralino/_data/docs/manual-checklist.md +189 -0
  17. neutralino/_data/docs/packaging.md +252 -0
  18. neutralino/_data/docs/performance.md +15 -0
  19. neutralino/_data/docs/platforms.md +15 -0
  20. neutralino/_data/docs/reference/components.md +1685 -0
  21. neutralino/_data/docs/reference/native.md +148 -0
  22. neutralino/_data/docs/security.md +60 -0
  23. neutralino/_data/docs/ui.md +249 -0
  24. neutralino/_data/docs/updates.md +366 -0
  25. neutralino/_data/examples/README.md +6 -0
  26. neutralino/_data/examples/crud/README.md +36 -0
  27. neutralino/_data/examples/crud/app.py +243 -0
  28. neutralino/_data/examples/dashboard/README.md +36 -0
  29. neutralino/_data/examples/dashboard/app.py +367 -0
  30. neutralino/_data/examples/editor/README.md +35 -0
  31. neutralino/_data/examples/editor/app.py +190 -0
  32. neutralino/_data/examples/file-manager/README.md +40 -0
  33. neutralino/_data/examples/file-manager/app.py +120 -0
  34. neutralino/_data/examples/file-manager/frontend/index.html +20 -0
  35. neutralino/_data/examples/file-manager/frontend/main.js +55 -0
  36. neutralino/_data/examples/file-manager/frontend/neutralino.js +1 -0
  37. neutralino/_data/examples/file-manager/frontend/python-bridge.d.ts +207 -0
  38. neutralino/_data/examples/file-manager/frontend/python-bridge.mjs +854 -0
  39. neutralino/_data/examples/file-manager/frontend/style.css +4 -0
  40. neutralino/_data/examples/hybrid/README.md +48 -0
  41. neutralino/_data/examples/hybrid/app.py +80 -0
  42. neutralino/_data/examples/hybrid/components/counter.mjs +37 -0
  43. neutralino/_data/examples/hybrid/components/widget.mjs +23 -0
  44. neutralino/_data/examples/hybrid/styles.css +21 -0
  45. neutralino/_data/examples/hybrid/widget/package.json +20 -0
  46. neutralino/_data/examples/hybrid/widget/src/Widget.jsx +25 -0
  47. neutralino/_data/examples/hybrid/widget/vite.config.mjs +19 -0
  48. neutralino/_data/examples/monitor/README.md +36 -0
  49. neutralino/_data/examples/monitor/app.py +375 -0
  50. neutralino/_data/examples/react/README.md +90 -0
  51. neutralino/_data/examples/react/app.py +68 -0
  52. neutralino/_data/examples/react/frontend/.gitignore +5 -0
  53. neutralino/_data/examples/react/frontend/index.html +17 -0
  54. neutralino/_data/examples/react/frontend/package-lock.json +1232 -0
  55. neutralino/_data/examples/react/frontend/package.json +25 -0
  56. neutralino/_data/examples/react/frontend/scripts/prepare-bridge.mjs +49 -0
  57. neutralino/_data/examples/react/frontend/src/App.tsx +157 -0
  58. neutralino/_data/examples/react/frontend/src/backend.ts +21 -0
  59. neutralino/_data/examples/react/frontend/src/calls.test.ts +206 -0
  60. neutralino/_data/examples/react/frontend/src/calls.ts +306 -0
  61. neutralino/_data/examples/react/frontend/src/globals.d.ts +14 -0
  62. neutralino/_data/examples/react/frontend/src/hooks.ts +45 -0
  63. neutralino/_data/examples/react/frontend/src/main.tsx +13 -0
  64. neutralino/_data/examples/react/frontend/src/styles.css +11 -0
  65. neutralino/_data/examples/react/frontend/tsconfig.json +18 -0
  66. neutralino/_data/examples/react/frontend/vite.config.ts +9 -0
  67. neutralino/_data/examples/settings/README.md +38 -0
  68. neutralino/_data/examples/settings/app.py +440 -0
  69. neutralino/_data/examples/updater/.gitignore +2 -0
  70. neutralino/_data/examples/updater/README.md +82 -0
  71. neutralino/_data/examples/updater/app.py +160 -0
  72. neutralino/_data/examples/updater/app.toml +21 -0
  73. neutralino/_data/examples/updater/demo.py +107 -0
  74. neutralino/_data/examples/updater/requirements.txt +2 -0
  75. neutralino/_data/examples/updater/sources/github-private.toml +21 -0
  76. neutralino/_data/examples/updater/sources/github-public.toml +21 -0
  77. neutralino/_data/examples/vanilla/README.md +35 -0
  78. neutralino/_data/examples/vanilla/app.py +46 -0
  79. neutralino/_data/examples/vanilla/frontend/index.html +17 -0
  80. neutralino/_data/examples/vanilla/frontend/main.js +29 -0
  81. neutralino/_data/examples/vanilla/frontend/neutralino.js +1 -0
  82. neutralino/_data/examples/vanilla/frontend/python-bridge.d.ts +207 -0
  83. neutralino/_data/examples/vanilla/frontend/python-bridge.mjs +854 -0
  84. neutralino/_data/examples/vanilla/frontend/style.css +4 -0
  85. neutralino/_data/explorer/app.py +1328 -0
  86. neutralino/_data/explorer/catalogue.json +48179 -0
  87. neutralino/_data/explorer/explorer_previews.py +247 -0
  88. neutralino/_data/explorer/sources/native/always_on_top.py +55 -0
  89. neutralino/_data/explorer/sources/native/binary.py +125 -0
  90. neutralino/_data/explorer/sources/native/borderless.py +99 -0
  91. neutralino/_data/explorer/sources/native/broadcast.py +90 -0
  92. neutralino/_data/explorer/sources/native/config.py +78 -0
  93. neutralino/_data/explorer/sources/native/controls.py +140 -0
  94. neutralino/_data/explorer/sources/native/directory.py +163 -0
  95. neutralino/_data/explorer/sources/native/displays.py +75 -0
  96. neutralino/_data/explorer/sources/native/env.py +98 -0
  97. neutralino/_data/explorer/sources/native/events.py +124 -0
  98. neutralino/_data/explorer/sources/native/exec_command.py +79 -0
  99. neutralino/_data/explorer/sources/native/folder.py +70 -0
  100. neutralino/_data/explorer/sources/native/icon_badge.py +101 -0
  101. neutralino/_data/explorer/sources/native/image.py +119 -0
  102. neutralino/_data/explorer/sources/native/lifecycle.py +99 -0
  103. neutralino/_data/explorer/sources/native/locale.py +70 -0
  104. neutralino/_data/explorer/sources/native/main_menu.py +103 -0
  105. neutralino/_data/explorer/sources/native/message_box.py +101 -0
  106. neutralino/_data/explorer/sources/native/mouse.py +70 -0
  107. neutralino/_data/explorer/sources/native/multi_window.py +134 -0
  108. neutralino/_data/explorer/sources/native/notification.py +74 -0
  109. neutralino/_data/explorer/sources/native/open_external.py +81 -0
  110. neutralino/_data/explorer/sources/native/open_file.py +102 -0
  111. neutralino/_data/explorer/sources/native/paths.py +77 -0
  112. neutralino/_data/explorer/sources/native/print_snapshot.py +84 -0
  113. neutralino/_data/explorer/sources/native/read_write.py +192 -0
  114. neutralino/_data/explorer/sources/native/resources.py +110 -0
  115. neutralino/_data/explorer/sources/native/save_file.py +101 -0
  116. neutralino/_data/explorer/sources/native/server_mount.py +106 -0
  117. neutralino/_data/explorer/sources/native/sound.py +84 -0
  118. neutralino/_data/explorer/sources/native/spawn_process.py +128 -0
  119. neutralino/_data/explorer/sources/native/states.py +122 -0
  120. neutralino/_data/explorer/sources/native/stats_permissions.py +147 -0
  121. neutralino/_data/explorer/sources/native/storage.py +108 -0
  122. neutralino/_data/explorer/sources/native/system_info.py +115 -0
  123. neutralino/_data/explorer/sources/native/text.py +133 -0
  124. neutralino/_data/explorer/sources/native/trash.py +98 -0
  125. neutralino/_data/explorer/sources/native/tray.py +109 -0
  126. neutralino/_data/explorer/sources/native/watcher.py +167 -0
  127. neutralino/_data/explorer/sources/patterns/content_blocks.py +119 -0
  128. neutralino/_data/explorer/sources/patterns/dynamic_dashboard.py +121 -0
  129. neutralino/_data/explorer/sources/patterns/dynamic_form.py +120 -0
  130. neutralino/_data/explorer/sources/patterns/dynamic_table.py +109 -0
  131. neutralino/_data/explorer/sources/patterns/error_reporting.mjs +24 -0
  132. neutralino/_data/explorer/sources/patterns/error_reporting.py +124 -0
  133. neutralino/_data/explorer/sources/patterns/errors_timeouts.py +108 -0
  134. neutralino/_data/explorer/sources/patterns/feature_flags.py +99 -0
  135. neutralino/_data/explorer/sources/patterns/file_drop.py +126 -0
  136. neutralino/_data/explorer/sources/patterns/http_from_python.py +152 -0
  137. neutralino/_data/explorer/sources/patterns/keyboard_shortcuts.py +153 -0
  138. neutralino/_data/explorer/sources/patterns/live_config_reload.py +160 -0
  139. neutralino/_data/explorer/sources/patterns/logging.py +184 -0
  140. neutralino/_data/explorer/sources/patterns/long_tasks.py +121 -0
  141. neutralino/_data/explorer/sources/patterns/multi_window_sync.py +68 -0
  142. neutralino/_data/explorer/sources/patterns/navigation_from_backend.py +109 -0
  143. neutralino/_data/explorer/sources/patterns/onboarding.py +123 -0
  144. neutralino/_data/explorer/sources/patterns/optimistic_updates.py +89 -0
  145. neutralino/_data/explorer/sources/patterns/persistence.py +114 -0
  146. neutralino/_data/explorer/sources/patterns/python_calls_page.mjs +10 -0
  147. neutralino/_data/explorer/sources/patterns/python_calls_page.py +64 -0
  148. neutralino/_data/explorer/sources/patterns/python_push.py +84 -0
  149. neutralino/_data/explorer/sources/patterns/recurring_events.py +114 -0
  150. neutralino/_data/explorer/sources/patterns/roles_permissions.py +104 -0
  151. neutralino/_data/explorer/sources/patterns/scheduled_jobs.py +194 -0
  152. neutralino/_data/explorer/sources/patterns/settings_page.py +165 -0
  153. neutralino/_data/explorer/sources/patterns/sqlite.py +181 -0
  154. neutralino/_data/explorer/sources/patterns/streaming.py +102 -0
  155. neutralino/_data/explorer/sources/patterns/texts_i18n.py +81 -0
  156. neutralino/_data/explorer/sources/patterns/theme_from_backend.py +86 -0
  157. neutralino/_data/explorer/sources/patterns/updater.py +232 -0
  158. neutralino/_data/explorer/sources/workspace/calendar/app.py +547 -0
  159. neutralino/_data/explorer/sources/workspace/customers/app.py +467 -0
  160. neutralino/_data/explorer/sources/workspace/dashboard/README.md +36 -0
  161. neutralino/_data/explorer/sources/workspace/dashboard/app.py +367 -0
  162. neutralino/_data/explorer/sources/workspace/documents/app.py +511 -0
  163. neutralino/_data/explorer/sources/workspace/inbox/app.py +439 -0
  164. neutralino/_data/explorer/sources/workspace/orders/app.py +491 -0
  165. neutralino/_data/explorer/sources/workspace/reports/app.py +386 -0
  166. neutralino/_data/explorer/sources/workspace/settings/README.md +38 -0
  167. neutralino/_data/explorer/sources/workspace/settings/app.py +440 -0
  168. neutralino/_data/explorer/sources/workspace/system/README.md +36 -0
  169. neutralino/_data/explorer/sources/workspace/system/app.py +375 -0
  170. neutralino/_data/explorer/sources/workspace/tasks/app.py +462 -0
  171. neutralino/_data/renderer/LICENSES/@babel__runtime@7.29.17/LICENSE +22 -0
  172. neutralino/_data/renderer/LICENSES/@codemirror__autocomplete@6.20.4/LICENSE +21 -0
  173. neutralino/_data/renderer/LICENSES/@codemirror__commands@6.11.2/LICENSE +21 -0
  174. neutralino/_data/renderer/LICENSES/@codemirror__lang-css@6.3.1/LICENSE +21 -0
  175. neutralino/_data/renderer/LICENSES/@codemirror__lang-html@6.4.12/LICENSE +21 -0
  176. neutralino/_data/renderer/LICENSES/@codemirror__lang-javascript@6.2.5/LICENSE +21 -0
  177. neutralino/_data/renderer/LICENSES/@codemirror__lang-json@6.0.2/LICENSE +21 -0
  178. neutralino/_data/renderer/LICENSES/@codemirror__lang-markdown@6.5.3/LICENSE +21 -0
  179. neutralino/_data/renderer/LICENSES/@codemirror__lang-python@6.2.1/LICENSE +21 -0
  180. neutralino/_data/renderer/LICENSES/@codemirror__lang-sql@6.10.0/LICENSE +21 -0
  181. neutralino/_data/renderer/LICENSES/@codemirror__lang-yaml@6.1.3/LICENSE +21 -0
  182. neutralino/_data/renderer/LICENSES/@codemirror__language@6.13.1/LICENSE +21 -0
  183. neutralino/_data/renderer/LICENSES/@codemirror__search@6.7.3/LICENSE +21 -0
  184. neutralino/_data/renderer/LICENSES/@codemirror__state@6.7.6/LICENSE +21 -0
  185. neutralino/_data/renderer/LICENSES/@codemirror__view@6.44.2/LICENSE +21 -0
  186. neutralino/_data/renderer/LICENSES/@dnd-kit__accessibility@3.1.1/LICENSE +21 -0
  187. neutralino/_data/renderer/LICENSES/@dnd-kit__core@6.3.1/LICENSE +21 -0
  188. neutralino/_data/renderer/LICENSES/@dnd-kit__sortable@10.0.0/LICENSE +21 -0
  189. neutralino/_data/renderer/LICENSES/@dnd-kit__utilities@3.2.2/LICENSE +21 -0
  190. neutralino/_data/renderer/LICENSES/@emoji-mart__data@1.2.1/LICENSE +21 -0
  191. neutralino/_data/renderer/LICENSES/@floating-ui__core@1.8.0/LICENSE +20 -0
  192. neutralino/_data/renderer/LICENSES/@floating-ui__dom@1.8.0/LICENSE +20 -0
  193. neutralino/_data/renderer/LICENSES/@floating-ui__react-dom@2.1.9/LICENSE +20 -0
  194. neutralino/_data/renderer/LICENSES/@floating-ui__react@0.27.20/LICENSE +20 -0
  195. neutralino/_data/renderer/LICENSES/@floating-ui__utils@0.2.12/LICENSE +20 -0
  196. neutralino/_data/renderer/LICENSES/@lezer__common@1.5.7/LICENSE +21 -0
  197. neutralino/_data/renderer/LICENSES/@lezer__css@1.3.9/LICENSE +21 -0
  198. neutralino/_data/renderer/LICENSES/@lezer__highlight@1.2.5/LICENSE +21 -0
  199. neutralino/_data/renderer/LICENSES/@lezer__html@1.3.13/LICENSE +21 -0
  200. neutralino/_data/renderer/LICENSES/@lezer__javascript@1.5.7/LICENSE +21 -0
  201. neutralino/_data/renderer/LICENSES/@lezer__json@1.0.3/LICENSE +21 -0
  202. neutralino/_data/renderer/LICENSES/@lezer__lr@1.4.13/LICENSE +21 -0
  203. neutralino/_data/renderer/LICENSES/@lezer__markdown@1.8.3/LICENSE +21 -0
  204. neutralino/_data/renderer/LICENSES/@lezer__python@1.1.21/LICENSE +21 -0
  205. neutralino/_data/renderer/LICENSES/@lezer__yaml@1.0.4/LICENSE +21 -0
  206. neutralino/_data/renderer/LICENSES/@mantine__carousel@9.8.3/LICENSE +21 -0
  207. neutralino/_data/renderer/LICENSES/@mantine__charts@9.8.3/LICENSE +21 -0
  208. neutralino/_data/renderer/LICENSES/@mantine__code-highlight@9.8.3/LICENSE +21 -0
  209. neutralino/_data/renderer/LICENSES/@mantine__core@9.8.3/LICENSE +21 -0
  210. neutralino/_data/renderer/LICENSES/@mantine__dates@9.8.3/LICENSE +21 -0
  211. neutralino/_data/renderer/LICENSES/@mantine__dropzone@9.8.3/LICENSE +21 -0
  212. neutralino/_data/renderer/LICENSES/@mantine__emoji@9.8.3/LICENSE +21 -0
  213. neutralino/_data/renderer/LICENSES/@mantine__hooks@9.8.3/LICENSE +21 -0
  214. neutralino/_data/renderer/LICENSES/@mantine__lightbox@9.8.3/LICENSE +21 -0
  215. neutralino/_data/renderer/LICENSES/@mantine__notifications@9.8.3/LICENSE +21 -0
  216. neutralino/_data/renderer/LICENSES/@mantine__nprogress@9.8.3/LICENSE +21 -0
  217. neutralino/_data/renderer/LICENSES/@mantine__schedule@9.8.3/LICENSE +21 -0
  218. neutralino/_data/renderer/LICENSES/@mantine__spotlight@9.8.3/LICENSE +21 -0
  219. neutralino/_data/renderer/LICENSES/@mantine__store@9.8.3/LICENSE +21 -0
  220. neutralino/_data/renderer/LICENSES/@mantine__tiptap@9.8.3/LICENSE +21 -0
  221. neutralino/_data/renderer/LICENSES/@marijn__find-cluster-break@1.0.4/LICENSE +21 -0
  222. neutralino/_data/renderer/LICENSES/@reduxjs__toolkit@2.16.0/LICENSE +21 -0
  223. neutralino/_data/renderer/LICENSES/@tabler__icons-react@3.55.0/LICENSE +21 -0
  224. neutralino/_data/renderer/LICENSES/@tanstack__react-virtual@3.14.32/LICENSE +21 -0
  225. neutralino/_data/renderer/LICENSES/@tanstack__virtual-core@3.19.17/LICENSE +21 -0
  226. neutralino/_data/renderer/LICENSES/@tiptap__core@3.35.1/LICENSE.md +21 -0
  227. neutralino/_data/renderer/LICENSES/@tiptap__extension-blockquote@3.35.1/LICENSE.md +21 -0
  228. neutralino/_data/renderer/LICENSES/@tiptap__extension-bold@3.35.1/LICENSE.md +21 -0
  229. neutralino/_data/renderer/LICENSES/@tiptap__extension-code-block@3.35.1/LICENSE.md +21 -0
  230. neutralino/_data/renderer/LICENSES/@tiptap__extension-code@3.35.1/LICENSE.md +21 -0
  231. neutralino/_data/renderer/LICENSES/@tiptap__extension-document@3.35.1/LICENSE.md +21 -0
  232. neutralino/_data/renderer/LICENSES/@tiptap__extension-hard-break@3.35.1/LICENSE.md +21 -0
  233. neutralino/_data/renderer/LICENSES/@tiptap__extension-heading@3.35.1/LICENSE.md +21 -0
  234. neutralino/_data/renderer/LICENSES/@tiptap__extension-horizontal-rule@3.35.1/LICENSE.md +21 -0
  235. neutralino/_data/renderer/LICENSES/@tiptap__extension-italic@3.35.1/LICENSE.md +21 -0
  236. neutralino/_data/renderer/LICENSES/@tiptap__extension-link@3.35.1/LICENSE.md +21 -0
  237. neutralino/_data/renderer/LICENSES/@tiptap__extension-list@3.35.1/LICENSE.md +21 -0
  238. neutralino/_data/renderer/LICENSES/@tiptap__extension-paragraph@3.35.1/LICENSE.md +21 -0
  239. neutralino/_data/renderer/LICENSES/@tiptap__extension-strike@3.35.1/LICENSE.md +21 -0
  240. neutralino/_data/renderer/LICENSES/@tiptap__extension-text@3.35.1/LICENSE.md +21 -0
  241. neutralino/_data/renderer/LICENSES/@tiptap__extension-underline@3.35.1/LICENSE.md +21 -0
  242. neutralino/_data/renderer/LICENSES/@tiptap__extensions@3.35.1/LICENSE.md +21 -0
  243. neutralino/_data/renderer/LICENSES/@tiptap__react@3.35.1/LICENSE.md +21 -0
  244. neutralino/_data/renderer/LICENSES/@tiptap__starter-kit@3.35.1/LICENSE.md +21 -0
  245. neutralino/_data/renderer/LICENSES/attr-accept@4.0.1/LICENSE +22 -0
  246. neutralino/_data/renderer/LICENSES/clsx@2.1.1/license +9 -0
  247. neutralino/_data/renderer/LICENSES/crelt@1.0.7/LICENSE +19 -0
  248. neutralino/_data/renderer/LICENSES/d3-array@3.2.5/LICENSE +13 -0
  249. neutralino/_data/renderer/LICENSES/d3-color@3.1.1/LICENSE +13 -0
  250. neutralino/_data/renderer/LICENSES/d3-format@3.1.3/LICENSE +13 -0
  251. neutralino/_data/renderer/LICENSES/d3-interpolate@3.0.2/LICENSE +13 -0
  252. neutralino/_data/renderer/LICENSES/d3-path@3.1.1/LICENSE +13 -0
  253. neutralino/_data/renderer/LICENSES/d3-scale@4.0.3/LICENSE +13 -0
  254. neutralino/_data/renderer/LICENSES/d3-shape@3.2.1/LICENSE +13 -0
  255. neutralino/_data/renderer/LICENSES/d3-time-format@4.1.1/LICENSE +13 -0
  256. neutralino/_data/renderer/LICENSES/d3-time@3.1.1/LICENSE +13 -0
  257. neutralino/_data/renderer/LICENSES/dayjs@1.11.23/LICENSE +21 -0
  258. neutralino/_data/renderer/LICENSES/decimal.js-light@2.5.1/LICENCE.md +23 -0
  259. neutralino/_data/renderer/LICENSES/diff@9.0.0/LICENSE +29 -0
  260. neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE +202 -0
  261. neutralino/_data/renderer/LICENSES/dompurify@3.5.1/LICENSE-MPL +373 -0
  262. neutralino/_data/renderer/LICENSES/embla-carousel-react@8.6.0/MIT-embla-carousel.txt +21 -0
  263. neutralino/_data/renderer/LICENSES/embla-carousel-reactive-utils@8.6.0/MIT-embla-carousel.txt +21 -0
  264. neutralino/_data/renderer/LICENSES/embla-carousel@8.6.0/MIT-embla-carousel.txt +21 -0
  265. neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/LICENSE +21 -0
  266. neutralino/_data/renderer/LICENSES/es-toolkit@1.53.2/NOTICE +39 -0
  267. neutralino/_data/renderer/LICENSES/eventemitter3@5.0.4/LICENSE +21 -0
  268. neutralino/_data/renderer/LICENSES/fast-equals@5.4.7/LICENSE +21 -0
  269. neutralino/_data/renderer/LICENSES/file-selector@5.0.3/LICENSE +21 -0
  270. neutralino/_data/renderer/LICENSES/get-nonce@1.0.1/LICENSE +21 -0
  271. neutralino/_data/renderer/LICENSES/immer@11.2.14/LICENSE +21 -0
  272. neutralino/_data/renderer/LICENSES/linkifyjs@4.4.0/LICENSE +19 -0
  273. neutralino/_data/renderer/LICENSES/marked@18.4.0/LICENSE +44 -0
  274. neutralino/_data/renderer/LICENSES/neutralino.js@6.11.0/LICENSE +21 -0
  275. neutralino/_data/renderer/LICENSES/orderedmap@2.1.1/LICENSE +19 -0
  276. neutralino/_data/renderer/LICENSES/packages.json +1838 -0
  277. neutralino/_data/renderer/LICENSES/prosemirror-commands@1.7.2/LICENSE +19 -0
  278. neutralino/_data/renderer/LICENSES/prosemirror-dropcursor@1.8.4/LICENSE +19 -0
  279. neutralino/_data/renderer/LICENSES/prosemirror-gapcursor@1.4.1/LICENSE +19 -0
  280. neutralino/_data/renderer/LICENSES/prosemirror-history@1.5.2/LICENSE +19 -0
  281. neutralino/_data/renderer/LICENSES/prosemirror-keymap@1.2.3/LICENSE +19 -0
  282. neutralino/_data/renderer/LICENSES/prosemirror-model@1.25.13/LICENSE +19 -0
  283. neutralino/_data/renderer/LICENSES/prosemirror-schema-list@1.6.1/LICENSE +19 -0
  284. neutralino/_data/renderer/LICENSES/prosemirror-state@1.4.4/LICENSE +19 -0
  285. neutralino/_data/renderer/LICENSES/prosemirror-transform@1.12.7/LICENSE +19 -0
  286. neutralino/_data/renderer/LICENSES/prosemirror-view@1.44.0/LICENSE +19 -0
  287. neutralino/_data/renderer/LICENSES/react-dom@19.3.1/LICENSE +21 -0
  288. neutralino/_data/renderer/LICENSES/react-dropzone@20.1.4/LICENSE +22 -0
  289. neutralino/_data/renderer/LICENSES/react-is@19.3.1/LICENSE +21 -0
  290. neutralino/_data/renderer/LICENSES/react-number-format@5.4.5/LICENSE +21 -0
  291. neutralino/_data/renderer/LICENSES/react-redux@9.3.1/LICENSE.md +21 -0
  292. neutralino/_data/renderer/LICENSES/react-remove-scroll-bar@2.3.8/MIT-react-remove-scroll-bar.txt +21 -0
  293. neutralino/_data/renderer/LICENSES/react-remove-scroll@2.7.2/LICENSE +21 -0
  294. neutralino/_data/renderer/LICENSES/react-style-singleton@2.2.3/LICENSE +21 -0
  295. neutralino/_data/renderer/LICENSES/react-transition-group@4.4.5/LICENSE +30 -0
  296. neutralino/_data/renderer/LICENSES/react@19.3.1/LICENSE +21 -0
  297. neutralino/_data/renderer/LICENSES/recharts@3.11.3/LICENSE +22 -0
  298. neutralino/_data/renderer/LICENSES/redux-thunk@3.1.0/LICENSE.md +21 -0
  299. neutralino/_data/renderer/LICENSES/redux@5.0.1/LICENSE.md +21 -0
  300. neutralino/_data/renderer/LICENSES/reselect@5.2.0/LICENSE +21 -0
  301. neutralino/_data/renderer/LICENSES/rolldown@1.3.4/LICENSE +25 -0
  302. neutralino/_data/renderer/LICENSES/rope-sequence@1.3.4/LICENSE +19 -0
  303. neutralino/_data/renderer/LICENSES/rrule@2.8.1/LICENCE +65 -0
  304. neutralino/_data/renderer/LICENSES/scheduler@0.28.0/LICENSE +21 -0
  305. neutralino/_data/renderer/LICENSES/style-mod@4.1.5/LICENSE +19 -0
  306. neutralino/_data/renderer/LICENSES/tiny-invariant@1.3.3/LICENSE +21 -0
  307. neutralino/_data/renderer/LICENSES/tslib@2.9.1/LICENSE.txt +12 -0
  308. neutralino/_data/renderer/LICENSES/use-callback-ref@1.3.3/LICENSE +21 -0
  309. neutralino/_data/renderer/LICENSES/use-sidecar@1.1.3/LICENSE +21 -0
  310. neutralino/_data/renderer/LICENSES/use-sync-external-store@1.7.0/LICENSE +21 -0
  311. neutralino/_data/renderer/LICENSES/victory-vendor@38.1.1/LICENSE.txt +150 -0
  312. neutralino/_data/renderer/LICENSES/vite@8.4.1/LICENSE.md +2320 -0
  313. neutralino/_data/renderer/LICENSES/w3c-keyname@2.2.8/LICENSE +19 -0
  314. neutralino/_data/renderer/assets/IconGripVertical-BlJrWVuo.js +1 -0
  315. neutralino/_data/renderer/assets/carousel-D1j1SkWR.css +1 -0
  316. neutralino/_data/renderer/assets/carousel-DniHwTLK.js +1 -0
  317. neutralino/_data/renderer/assets/chunk-CCkLOSkX.css +1 -0
  318. neutralino/_data/renderer/assets/chunk-Du0h7lB-.js +9 -0
  319. neutralino/_data/renderer/assets/codehighlight-CCe_blv1.js +10 -0
  320. neutralino/_data/renderer/assets/codehighlight-THJMNDh8.css +1 -0
  321. neutralino/_data/renderer/assets/codemirror-CinrNxVJ.js +2 -0
  322. neutralino/_data/renderer/assets/css-CMUk25uq.js +1 -0
  323. neutralino/_data/renderer/assets/dist-70Le0T2N.js +1 -0
  324. neutralino/_data/renderer/assets/dist-BCHbQlae.js +11 -0
  325. neutralino/_data/renderer/assets/dist-BXts23GT.js +1 -0
  326. neutralino/_data/renderer/assets/dist-D2RX2UgP.js +23 -0
  327. neutralino/_data/renderer/assets/dist-DikJK2lp.js +1 -0
  328. neutralino/_data/renderer/assets/dist-acbbRM1z.js +1 -0
  329. neutralino/_data/renderer/assets/dnd-DaaaVala.js +5 -0
  330. neutralino/_data/renderer/assets/dropzone-CeqF5SZx.js +1 -0
  331. neutralino/_data/renderer/assets/dropzone-aPCBPjDN.css +1 -0
  332. neutralino/_data/renderer/assets/embla-carousel-react.esm-CbyYjwMN.js +1 -0
  333. neutralino/_data/renderer/assets/emoji-BfRPfoVw.js +1 -0
  334. neutralino/_data/renderer/assets/emoji-DV8OzU1E.css +1 -0
  335. neutralino/_data/renderer/assets/esm-C5ZYjSBQ.js +82 -0
  336. neutralino/_data/renderer/assets/highlight-CB6hGb5A.js +3 -0
  337. neutralino/_data/renderer/assets/highlight-Dlb5DJwL.css +1 -0
  338. neutralino/_data/renderer/assets/html-Dad3kwIa.js +1 -0
  339. neutralino/_data/renderer/assets/icon-chunk-X3Kr0nh-.js +1 -0
  340. neutralino/_data/renderer/assets/index-CU0HB-J7.js +69 -0
  341. neutralino/_data/renderer/assets/index-TWpF4Lef.css +1 -0
  342. neutralino/_data/renderer/assets/javascript-BQb8vpw3.js +1 -0
  343. neutralino/_data/renderer/assets/json-BCFmxlML.js +1 -0
  344. neutralino/_data/renderer/assets/lightbox-BHtgbsUV.js +1 -0
  345. neutralino/_data/renderer/assets/lightbox-BzKDpkAD.css +1 -0
  346. neutralino/_data/renderer/assets/markdown-DSuAylvy.js +5 -0
  347. neutralino/_data/renderer/assets/markdown-DjaNWMgH.js +77 -0
  348. neutralino/_data/renderer/assets/python-pdbIAveZ.js +9 -0
  349. neutralino/_data/renderer/assets/richtext-DIAsHMuK.css +1 -0
  350. neutralino/_data/renderer/assets/richtext-Z6fG9G2_.js +137 -0
  351. neutralino/_data/renderer/assets/spotlight-Ccstaz1-.css +1 -0
  352. neutralino/_data/renderer/assets/spotlight-knlyJw_A.js +1 -0
  353. neutralino/_data/renderer/assets/sql-DLoQFEde.js +2 -0
  354. neutralino/_data/renderer/assets/with-selector-BOM9_OlN.js +1 -0
  355. neutralino/_data/renderer/assets/yaml-BJNzokSe.js +1 -0
  356. neutralino/_data/renderer/index.html +22 -0
  357. neutralino/_data/renderer/manifest.json +202 -0
  358. neutralino/_data/renderer/neutralino.js +1 -0
  359. neutralino/_data/renderer/shared/mantine-core.mjs +5 -0
  360. neutralino/_data/renderer/shared/mantine-hooks.mjs +5 -0
  361. neutralino/_data/renderer/shared/react-dom-client.mjs +5 -0
  362. neutralino/_data/renderer/shared/react-dom.mjs +6 -0
  363. neutralino/_data/renderer/shared/react-jsx-runtime.mjs +5 -0
  364. neutralino/_data/renderer/shared/react.mjs +6 -0
  365. neutralino/_data/skills/README.md +6 -0
  366. neutralino/_data/skills/neutralino-app-patterns/SKILL.md +101 -0
  367. neutralino/_data/skills/neutralino-app-patterns/references/dashboards-and-background-work.md +55 -0
  368. neutralino/_data/skills/neutralino-app-patterns/references/storage-and-settings.md +57 -0
  369. neutralino/_data/skills/neutralino-app-patterns/references/tables-and-crud.md +81 -0
  370. neutralino/_data/skills/neutralino-frontend/SKILL.md +121 -0
  371. neutralino/_data/skills/neutralino-frontend/references/bridge.md +63 -0
  372. neutralino/_data/skills/neutralino-frontend/references/custom-components.md +84 -0
  373. neutralino/_data/skills/neutralino-frontend/references/frameworks.md +61 -0
  374. neutralino/_data/skills/neutralino-maintenance/SKILL.md +85 -0
  375. neutralino/_data/skills/neutralino-maintenance/references/platforms-and-gates.md +35 -0
  376. neutralino/_data/skills/neutralino-maintenance/references/records.md +38 -0
  377. neutralino/_data/skills/neutralino-maintenance/references/review-process.md +36 -0
  378. neutralino/_data/skills/neutralino-native/SKILL.md +107 -0
  379. neutralino/_data/skills/neutralino-native/references/api-conventions.md +72 -0
  380. neutralino/_data/skills/neutralino-native/references/desktop-helpers.md +53 -0
  381. neutralino/_data/skills/neutralino-native/references/permissions-windows.md +53 -0
  382. neutralino/_data/skills/neutralino-packaging/SKILL.md +99 -0
  383. neutralino/_data/skills/neutralino-packaging/references/build-layout.md +51 -0
  384. neutralino/_data/skills/neutralino-packaging/references/managed-install.md +59 -0
  385. neutralino/_data/skills/neutralino-packaging/references/templates-and-config.md +63 -0
  386. neutralino/_data/skills/neutralino-python/SKILL.md +109 -0
  387. neutralino/_data/skills/neutralino-python/references/architecture.md +53 -0
  388. neutralino/_data/skills/neutralino-python/references/cli.md +60 -0
  389. neutralino/_data/skills/neutralino-python/references/platforms-security.md +44 -0
  390. neutralino/_data/skills/neutralino-rpc/SKILL.md +114 -0
  391. neutralino/_data/skills/neutralino-rpc/references/errors-and-limits.md +44 -0
  392. neutralino/_data/skills/neutralino-rpc/references/expose-and-context.md +74 -0
  393. neutralino/_data/skills/neutralino-rpc/references/streams-and-cancellation.md +53 -0
  394. neutralino/_data/skills/neutralino-ui/SKILL.md +115 -0
  395. neutralino/_data/skills/neutralino-ui/references/components-and-tree.md +74 -0
  396. neutralino/_data/skills/neutralino-ui/references/state-forms-events.md +85 -0
  397. neutralino/_data/skills/neutralino-ui/references/themes-profiles-assets.md +105 -0
  398. neutralino/_data/skills/neutralino-updates/SKILL.md +94 -0
  399. neutralino/_data/skills/neutralino-updates/references/config-and-api.md +80 -0
  400. neutralino/_data/skills/neutralino-updates/references/releases-and-install.md +77 -0
  401. neutralino/_data/skills/neutralino-updates/references/security-rollback.md +48 -0
  402. neutralino/_data/ui/contracts.json +32927 -0
  403. neutralino/_data/ui/emoji.json +1 -0
  404. neutralino/_data/upstream-lock.json +97 -0
  405. neutralino/_managed.py +1099 -0
  406. neutralino/_paths.py +220 -0
  407. neutralino/_platform.py +150 -0
  408. neutralino/_scaffold.py +344 -0
  409. neutralino/api/_base.py +99 -0
  410. neutralino/api/_custom.py +1350 -0
  411. neutralino/api/_dec.py +21 -0
  412. neutralino/api/_enc.py +80 -0
  413. neutralino/api/app.py +119 -0
  414. neutralino/api/clipboard.py +101 -0
  415. neutralino/api/computer.py +261 -0
  416. neutralino/api/custom.py +36 -0
  417. neutralino/api/debug.py +41 -0
  418. neutralino/api/extensions.py +57 -0
  419. neutralino/api/filesystem.py +633 -0
  420. neutralino/api/net.py +22 -0
  421. neutralino/api/os.py +508 -0
  422. neutralino/api/resources.py +124 -0
  423. neutralino/api/server.py +66 -0
  424. neutralino/api/storage.py +98 -0
  425. neutralino/api/types.py +342 -0
  426. neutralino/api/updater.py +22 -0
  427. neutralino/api/window.py +397 -0
  428. neutralino/application.py +1260 -0
  429. neutralino/bundle.py +187 -0
  430. neutralino/cli.py +629 -0
  431. neutralino/client.py +496 -0
  432. neutralino/config.py +671 -0
  433. neutralino/devtools.py +1973 -0
  434. neutralino/errors.py +142 -0
  435. neutralino/events.py +579 -0
  436. neutralino/execution.py +293 -0
  437. neutralino/extension.py +134 -0
  438. neutralino/frontend/python-bridge.d.ts +207 -0
  439. neutralino/frontend/python-bridge.mjs +854 -0
  440. neutralino/protocol.py +456 -0
  441. neutralino/py.typed +0 -0
  442. neutralino/rpc.py +1625 -0
  443. neutralino/runtime.py +591 -0
  444. neutralino/supervisor.py +866 -0
  445. neutralino/sync_client.py +376 -0
  446. neutralino/templates/default/app.py +32 -0
  447. neutralino/templates/default/frontend/app.js +28 -0
  448. neutralino/templates/default/frontend/index.html +26 -0
  449. neutralino/templates/default/frontend/neutralino.js +1 -0
  450. neutralino/templates/default/frontend/styles.css +8 -0
  451. neutralino/templates/default/gitignore.txt +3 -0
  452. neutralino/templates/default/neutralino.config.json +25 -0
  453. neutralino/templates/hybrid/README.md +17 -0
  454. neutralino/templates/hybrid/app.py +49 -0
  455. neutralino/templates/hybrid/components/counter.mjs +37 -0
  456. neutralino/templates/hybrid/styles.css +21 -0
  457. neutralino/templates/python-ui/README.md +15 -0
  458. neutralino/templates/python-ui/app.py +44 -0
  459. neutralino/templates/python-ui/gitignore.txt +3 -0
  460. neutralino/templates/python-ui/requirements.txt +4 -0
  461. neutralino/templates/react/README.md +28 -0
  462. neutralino/templates/react/app.py +52 -0
  463. neutralino/templates/react/components/widget.mjs +23 -0
  464. neutralino/templates/react/widget/package.json +20 -0
  465. neutralino/templates/react/widget/src/Widget.jsx +25 -0
  466. neutralino/templates/react/widget/vite.config.mjs +19 -0
  467. neutralino/transport.py +661 -0
  468. neutralino/types.py +93 -0
  469. neutralino/ui/__init__.py +139 -0
  470. neutralino/ui/_app.py +1529 -0
  471. neutralino/ui/_assets.py +407 -0
  472. neutralino/ui/_bases.py +1210 -0
  473. neutralino/ui/_behaviours.py +1066 -0
  474. neutralino/ui/_charts.py +732 -0
  475. neutralino/ui/_component.py +882 -0
  476. neutralino/ui/_dates.py +168 -0
  477. neutralino/ui/_desktop.py +879 -0
  478. neutralino/ui/_events.py +192 -0
  479. neutralino/ui/_filters.py +427 -0
  480. neutralino/ui/_forms.py +282 -0
  481. neutralino/ui/_protocol.py +201 -0
  482. neutralino/ui/_schedule.py +543 -0
  483. neutralino/ui/_security.py +106 -0
  484. neutralino/ui/_session.py +969 -0
  485. neutralino/ui/_state.py +199 -0
  486. neutralino/ui/_tables.py +256 -0
  487. neutralino/ui/_theme.py +154 -0
  488. neutralino/ui/blocks/__init__.py +19 -0
  489. neutralino/ui/blocks/_data.py +2239 -0
  490. neutralino/ui/blocks/_interactive.py +622 -0
  491. neutralino/ui/blocks/_layout.py +2967 -0
  492. neutralino/ui/components/__init__.py +81 -0
  493. neutralino/ui/components/_dates.py +879 -0
  494. neutralino/ui/components/_editors.py +217 -0
  495. neutralino/ui/components/_extensions.py +790 -0
  496. neutralino/ui/components/_extras.py +303 -0
  497. neutralino/ui/components/_generated.py +30565 -0
  498. neutralino/ui/components/_types.py +17 -0
  499. neutralino/ui/schema.py +824 -0
  500. neutralino/ui/validators.py +362 -0
  501. neutralino/updates/__init__.py +96 -0
  502. neutralino/updates/_http.py +320 -0
  503. neutralino/updates/_layout.py +762 -0
  504. neutralino/updates/archive.py +216 -0
  505. neutralino/updates/config.py +256 -0
  506. neutralino/updates/errors.py +97 -0
  507. neutralino/updates/install.sh.in +201 -0
  508. neutralino/updates/launcher.py +18 -0
  509. neutralino/updates/manager.py +808 -0
  510. neutralino/updates/manifest.py +196 -0
  511. neutralino/updates/release.py +314 -0
  512. neutralino/updates/semver.py +84 -0
  513. neutralino/updates/sources.py +392 -0
  514. neutralino/windows.py +316 -0
  515. neutralino_python-0.1.0.dist-info/METADATA +121 -0
  516. neutralino_python-0.1.0.dist-info/RECORD +521 -0
  517. neutralino_python-0.1.0.dist-info/WHEEL +4 -0
  518. neutralino_python-0.1.0.dist-info/entry_points.txt +3 -0
  519. neutralino_python-0.1.0.dist-info/licenses/LICENSE +21 -0
  520. neutralino_python-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +16 -0
  521. neutralino_python-0.1.0.dist-info/licenses/src/neutralino/_data/renderer/LICENSES/packages.json +1838 -0
neutralino/rpc.py ADDED
@@ -0,0 +1,1625 @@
1
+ """SDK RPC protocol v1 between web frontends and the Python backend.
2
+
3
+ Carried inside ordinary Neutralino events named ``neutralino.sdk.rpc.v1``:
4
+
5
+ * frontend -> backend: ``Neutralino.extensions.dispatch(backendId, EVENT, msg)``
6
+ (delivered to this extension connection only);
7
+ * backend -> frontend: native ``app.broadcast(EVENT, msg)`` (delivered to app
8
+ connections only - verified in P00 - and filtered by ``to`` on the page).
9
+
10
+ Broadcasts are not confidential and peer ids are routing labels, not
11
+ credentials: every page of the runtime is in the same trust domain
12
+ (specs/05, ADR-006). Only explicitly registered functions are callable.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import contextlib
19
+ import inspect
20
+ import logging
21
+ import math
22
+ import re
23
+ import secrets
24
+ import threading
25
+ import time
26
+ import types
27
+ import typing
28
+ from collections import OrderedDict
29
+ from collections.abc import AsyncGenerator, AsyncIterator, Callable, Coroutine, Mapping, Sequence
30
+ from dataclasses import dataclass, field
31
+ from typing import TYPE_CHECKING, Any, Final, TypeGuard, TypeVar, cast
32
+
33
+ from .errors import QueueFullError, RpcError, UnsupportedError, ValidationError
34
+ from .events import Event
35
+ from .execution import ExecutionEngine, HandlerKind, classify_handler
36
+ from .protocol import check_json, dumps, redact_reason
37
+
38
+ if TYPE_CHECKING:
39
+ from .client import AsyncClient
40
+
41
+ __all__ = [
42
+ "RPC_EVENT",
43
+ "MethodInfo",
44
+ "Registry",
45
+ "RpcContext",
46
+ "RpcEndpoint",
47
+ "RpcLimits",
48
+ "validate_message",
49
+ ]
50
+
51
+ log = logging.getLogger("neutralino.rpc")
52
+ T = TypeVar("T")
53
+
54
+ RPC_EVENT: Final = "neutralino.sdk.rpc.v1"
55
+ KINDS: Final = frozenset(
56
+ {
57
+ "hello",
58
+ "welcome",
59
+ "request",
60
+ "notify",
61
+ "result",
62
+ "error",
63
+ "chunk",
64
+ "progress",
65
+ "credit",
66
+ "cancel",
67
+ "bye",
68
+ "discover",
69
+ }
70
+ )
71
+ ERROR_CODES: Final = frozenset(
72
+ {
73
+ "METHOD_NOT_FOUND",
74
+ "INVALID_PARAMS",
75
+ "BUSY",
76
+ "TIMEOUT",
77
+ "CANCELLED",
78
+ "PROTOCOL_ERROR",
79
+ "INTERNAL_ERROR",
80
+ "DISCONNECTED",
81
+ "UNSUPPORTED",
82
+ "STREAM_OVERFLOW",
83
+ }
84
+ )
85
+ NAME_RE: Final = re.compile(r"^[A-Za-z_][A-Za-z0-9_.\-]{0,127}$")
86
+ ID_RE: Final = re.compile(r"^[A-Za-z0-9_.:\-]{1,128}$")
87
+ CODE_RE: Final = re.compile(r"^[A-Z][A-Z0-9_]{0,63}$")
88
+ CAPABILITIES: Final = ("rpc", "stream", "progress", "cancel", "discover", "reverse")
89
+
90
+ _ENVELOPE = {"v", "kind", "session", "generation", "from", "to", "id"}
91
+ _PAYLOAD: dict[str, set[str]] = {
92
+ "hello": {"capabilities"},
93
+ "welcome": {"capabilities"},
94
+ "request": {"method", "params", "stream", "credit"},
95
+ "notify": {"method", "params"},
96
+ "result": {"value"},
97
+ "error": {"error"},
98
+ "chunk": {"seq", "value"},
99
+ "progress": {"seq", "value"},
100
+ "credit": {"count"},
101
+ "cancel": {"reason"},
102
+ "bye": {"reason"},
103
+ "discover": set(),
104
+ }
105
+
106
+
107
+ # ------------------------------------------------------------------ limits
108
+ @dataclass(frozen=True)
109
+ class RpcLimits:
110
+ """RPC bounds (specs/05 defaults). Durations in seconds."""
111
+
112
+ initial_credit: int = 16
113
+ max_credit: int = 64
114
+ max_chunk_bytes: int = 256 * 1024
115
+ max_message_bytes: int = 4 * 1024 * 1024
116
+ max_active_per_peer: int = 32
117
+ max_pending_calls: int = 64
118
+ max_peers: int = 64
119
+ call_timeout: float = 30.0
120
+ stream_idle_timeout: float = 30.0
121
+ handshake_timeout: float = 15.0
122
+ progress_per_second: float = 10.0
123
+ replay_size: int = 1024
124
+ replay_ttl: float = 60.0
125
+ inbox: int = 4096
126
+ max_send_queue: int = 8192
127
+ max_json_depth: int = 64
128
+
129
+ def __post_init__(self) -> None:
130
+ if not 1 <= self.initial_credit <= self.max_credit <= 64:
131
+ raise ValueError("need 1 <= initial_credit <= max_credit <= 64")
132
+
133
+
134
+ # -------------------------------------------------------------- validation
135
+ def u16len(s: str) -> int:
136
+ """String length in UTF-16 code units, the unit JavaScript's .length uses
137
+ (a lone surrogate counts as one unit; validation rejects it separately)."""
138
+ return len(s.encode("utf-16-le", "surrogatepass")) // 2
139
+
140
+
141
+ def truncate_u16(s: str, limit: int) -> str:
142
+ """Cut ``s`` to at most ``limit`` UTF-16 code units without splitting a pair."""
143
+ if u16len(s) <= limit:
144
+ return s
145
+ out = s[:limit]
146
+ while u16len(out) > limit:
147
+ out = out[:-1]
148
+ return out
149
+
150
+
151
+ def _is_int(v: Any) -> TypeGuard[int]:
152
+ return isinstance(v, int) and not isinstance(v, bool)
153
+
154
+
155
+ def _json_int(v: Any) -> int | None:
156
+ """An integer as JavaScript sees JSON: an int or an integral float (``1.0``,
157
+ ``-0.0``), which JSON.parse cannot tell apart from ``1``/``0``. Booleans,
158
+ fractions and non-finite numbers are not integers."""
159
+ if _is_int(v):
160
+ return v
161
+ if isinstance(v, float) and v.is_integer():
162
+ return int(v)
163
+ return None
164
+
165
+
166
+ _INT_FIELDS = ("v", "seq", "count", "credit")
167
+
168
+
169
+ def validate_message(m: Any, limits: RpcLimits | None = None) -> dict[str, Any]:
170
+ """Strictly validate one RPC v1 message; raise ValidationError otherwise."""
171
+ lim = limits or RpcLimits()
172
+ if not isinstance(m, dict):
173
+ raise ValidationError("rpc message must be an object")
174
+ msg = cast(dict[str, Any], m)
175
+ # Same verdict as the JS validator: integral floats are integers. Normalise
176
+ # them to int (on a copy) so the rest of the endpoint only sees ints.
177
+ floats = [k for k in _INT_FIELDS if isinstance(msg.get(k), float)]
178
+ if floats:
179
+ msg = dict(msg)
180
+ for k in floats:
181
+ as_int = _json_int(msg[k])
182
+ if as_int is not None:
183
+ msg[k] = as_int
184
+ v = msg.get("v")
185
+ if not _is_int(v) or v != 1:
186
+ raise ValidationError("unsupported rpc protocol version")
187
+ kind = msg.get("kind")
188
+ if not isinstance(kind, str) or kind not in KINDS:
189
+ raise ValidationError("unknown rpc kind")
190
+ extra = set(msg) - _ENVELOPE - _PAYLOAD[kind]
191
+ if extra:
192
+ raise ValidationError(f"unexpected fields in {kind}: {sorted(extra)}")
193
+ for key in ("from", "to", "id"):
194
+ val = msg.get(key)
195
+ if not isinstance(val, str) or not ID_RE.fullmatch(val):
196
+ raise ValidationError(f"invalid {key}")
197
+ if kind == "hello":
198
+ if msg.get("session") is not None or (
199
+ "generation" in msg and msg["generation"] is not None
200
+ ):
201
+ raise ValidationError("hello must not carry a session")
202
+ else:
203
+ for key in ("session", "generation"):
204
+ val = msg.get(key)
205
+ if not isinstance(val, str) or not ID_RE.fullmatch(val):
206
+ raise ValidationError(f"invalid {key}")
207
+ if kind in ("hello", "welcome"):
208
+ caps = msg.get("capabilities")
209
+ if (
210
+ not isinstance(caps, list)
211
+ or len(cast(list[Any], caps)) > 32
212
+ or not all(isinstance(c, str) and u16len(c) <= 64 for c in cast(list[Any], caps))
213
+ ):
214
+ raise ValidationError("invalid capabilities")
215
+ if kind in ("request", "notify"):
216
+ method = msg.get("method")
217
+ if not isinstance(method, str) or not NAME_RE.fullmatch(method):
218
+ raise ValidationError("invalid method name")
219
+ params = msg.get("params")
220
+ if params is not None and not isinstance(params, dict):
221
+ raise ValidationError("params must be an object or null")
222
+ if kind == "request":
223
+ stream = msg.get("stream")
224
+ if not isinstance(stream, bool):
225
+ raise ValidationError("request.stream must be a boolean")
226
+ if stream:
227
+ credit = msg.get("credit")
228
+ if not _is_int(credit) or not 1 <= credit <= lim.max_credit:
229
+ raise ValidationError("invalid initial credit")
230
+ elif "credit" in msg:
231
+ raise ValidationError("credit only allowed for streams")
232
+ if kind in ("chunk", "progress"):
233
+ seq = msg.get("seq")
234
+ if not _is_int(seq) or seq < 0 or "value" not in msg:
235
+ raise ValidationError(f"invalid {kind}")
236
+ if kind == "result" and "value" not in msg:
237
+ raise ValidationError("result needs a value (null for none)")
238
+ if kind == "error":
239
+ err = msg.get("error")
240
+ if not isinstance(err, dict):
241
+ raise ValidationError("invalid error object")
242
+ e = cast(dict[str, Any], err)
243
+ if set(e) - {"code", "message", "details"}:
244
+ raise ValidationError("unexpected error fields")
245
+ if not isinstance(e.get("code"), str) or not CODE_RE.fullmatch(e["code"]):
246
+ raise ValidationError("invalid error code")
247
+ if not isinstance(e.get("message"), str) or u16len(e["message"]) > 4096:
248
+ raise ValidationError("invalid error message")
249
+ if kind == "credit":
250
+ count = msg.get("count")
251
+ if not _is_int(count) or not 1 <= count <= lim.max_credit:
252
+ raise ValidationError("invalid credit count")
253
+ if kind in ("cancel", "bye"):
254
+ reason = msg.get("reason")
255
+ if reason is not None and (not isinstance(reason, str) or u16len(reason) > 256):
256
+ raise ValidationError("invalid reason")
257
+ check_json(msg, max_depth=lim.max_json_depth, safe_integers=True)
258
+ try:
259
+ size = len(dumps(msg).encode())
260
+ except UnicodeEncodeError:
261
+ raise ValidationError("rpc message contains a lone UTF-16 surrogate") from None
262
+ if size > lim.max_message_bytes:
263
+ raise ValidationError("rpc message too large")
264
+ return msg
265
+
266
+
267
+ def _json_equal(a: Any, b: Any) -> bool:
268
+ """Equality as JSON sees it: true/false are not the numbers 1/0."""
269
+ if isinstance(a, bool) or isinstance(b, bool):
270
+ return isinstance(a, bool) and isinstance(b, bool) and a is b
271
+ return bool(a == b)
272
+
273
+
274
+ # ---------------------------------------------------- tiny schema validator
275
+ _SCHEMA_KEYS = {
276
+ "type",
277
+ "properties",
278
+ "required",
279
+ "additionalProperties",
280
+ "items",
281
+ "enum",
282
+ "description",
283
+ "minimum",
284
+ "maximum",
285
+ "minLength",
286
+ "maxLength",
287
+ "default",
288
+ }
289
+ _TYPES: dict[str, tuple[type, ...]] = {
290
+ "object": (dict,),
291
+ "array": (list,),
292
+ "string": (str,),
293
+ "number": (int, float),
294
+ "integer": (int,),
295
+ "boolean": (bool,),
296
+ "null": (type(None),),
297
+ }
298
+
299
+
300
+ def check_schema(schema: Any, path: str = "schema") -> None:
301
+ """Accept a small JSON Schema subset; reject anything else loudly."""
302
+ if not isinstance(schema, dict):
303
+ raise ValidationError(f"{path} must be an object")
304
+ s = cast(dict[str, Any], schema)
305
+ unknown = set(s) - _SCHEMA_KEYS
306
+ if unknown:
307
+ raise ValidationError(f"{path}: unsupported keywords {sorted(unknown)}")
308
+ t = s.get("type")
309
+ types_: list[Any] = cast(list[Any], t) if isinstance(t, list) else [t] if t is not None else []
310
+ for tt in types_:
311
+ if tt not in _TYPES:
312
+ raise ValidationError(f"{path}: unsupported type {tt!r}")
313
+ for k, sub in cast(dict[str, Any], s.get("properties", {})).items():
314
+ check_schema(sub, f"{path}.properties.{k}")
315
+ if "items" in s:
316
+ check_schema(s["items"], f"{path}.items")
317
+ check_json(s, max_depth=32)
318
+
319
+
320
+ def _type_ok(value: Any, t: str) -> bool:
321
+ if t in ("integer", "number") and isinstance(value, bool):
322
+ return False
323
+ if t == "number" and isinstance(value, float) and not math.isfinite(value):
324
+ return False
325
+ return isinstance(value, _TYPES[t])
326
+
327
+
328
+ def validate_value(schema: Mapping[str, Any], value: Any, path: str = "params") -> None:
329
+ t = schema.get("type")
330
+ if t is not None:
331
+ options = cast(list[str], t) if isinstance(t, list) else [cast(str, t)]
332
+ if not any(_type_ok(value, o) for o in options):
333
+ raise RpcError("INVALID_PARAMS", f"{path}: expected {'|'.join(options)}")
334
+ if "enum" in schema and not any(_json_equal(value, e) for e in schema["enum"]):
335
+ raise RpcError("INVALID_PARAMS", f"{path}: not an allowed value")
336
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
337
+ if "minimum" in schema and value < schema["minimum"]:
338
+ raise RpcError("INVALID_PARAMS", f"{path}: below minimum")
339
+ if "maximum" in schema and value > schema["maximum"]:
340
+ raise RpcError("INVALID_PARAMS", f"{path}: above maximum")
341
+ if isinstance(value, str):
342
+ if "minLength" in schema and len(value) < schema["minLength"]:
343
+ raise RpcError("INVALID_PARAMS", f"{path}: too short")
344
+ if "maxLength" in schema and len(value) > schema["maxLength"]:
345
+ raise RpcError("INVALID_PARAMS", f"{path}: too long")
346
+ if isinstance(value, dict):
347
+ obj = cast(dict[str, Any], value)
348
+ props = cast(dict[str, Any], schema.get("properties", {}))
349
+ for req in cast(list[str], schema.get("required", [])):
350
+ if req not in obj:
351
+ raise RpcError("INVALID_PARAMS", f"{path}: missing {req!r}")
352
+ if schema.get("additionalProperties") is False:
353
+ extra = set(obj) - set(props)
354
+ if extra:
355
+ raise RpcError("INVALID_PARAMS", f"{path}: unexpected {sorted(extra)}")
356
+ for k, sub in props.items():
357
+ if k in obj:
358
+ validate_value(sub, obj[k], f"{path}.{k}")
359
+ if isinstance(value, list) and "items" in schema:
360
+ for i, item in enumerate(cast(list[Any], value)):
361
+ validate_value(schema["items"], item, f"{path}[{i}]")
362
+
363
+
364
+ _ANNOTATION_TYPES: dict[Any, str] = {
365
+ str: "string",
366
+ int: "integer",
367
+ float: "number",
368
+ bool: "boolean",
369
+ list: "array",
370
+ dict: "object",
371
+ type(None): "null",
372
+ }
373
+
374
+
375
+ def _annotation_schema(annotation: Any) -> dict[str, Any] | None:
376
+ """Best-effort schema from a type annotation; None = no type check."""
377
+ if annotation in _ANNOTATION_TYPES:
378
+ return {"type": _ANNOTATION_TYPES[annotation]}
379
+ origin = typing.get_origin(annotation)
380
+ if origin in (list, Sequence):
381
+ return {"type": "array"}
382
+ if origin in (dict, Mapping):
383
+ return {"type": "object"}
384
+ if origin in (typing.Union, types.UnionType):
385
+ parts = [_annotation_schema(a) for a in typing.get_args(annotation)]
386
+ if all(p is not None and isinstance(p.get("type"), str) for p in parts):
387
+ return {"type": [cast(dict[str, Any], p)["type"] for p in parts]}
388
+ return None
389
+
390
+
391
+ # ---------------------------------------------------------------- registry
392
+ @dataclass(frozen=True)
393
+ class MethodInfo:
394
+ """Discovery metadata. Never contains code, paths or environment."""
395
+
396
+ name: str
397
+ stream: bool
398
+ params: list[str]
399
+ required: list[str]
400
+ schema: dict[str, Any] | None
401
+ description: str | None
402
+
403
+ def to_json(self) -> dict[str, Any]:
404
+ return {
405
+ "name": self.name,
406
+ "stream": self.stream,
407
+ "params": self.params,
408
+ "required": self.required,
409
+ "schema": self.schema,
410
+ "description": self.description,
411
+ }
412
+
413
+
414
+ @dataclass
415
+ class _Method:
416
+ name: str
417
+ fn: Callable[..., Any]
418
+ kind: str
419
+ stream: bool
420
+ schema: dict[str, Any] | None
421
+ derived: dict[str, dict[str, Any]]
422
+ params: list[str]
423
+ required: list[str]
424
+ accepts_ctx: bool
425
+ varkw: bool
426
+ description: str | None
427
+ timeout: float | None
428
+
429
+ def info(self) -> MethodInfo:
430
+ return MethodInfo(
431
+ self.name,
432
+ self.stream,
433
+ list(self.params),
434
+ list(self.required),
435
+ self.schema,
436
+ self.description,
437
+ )
438
+
439
+
440
+ class Registry:
441
+ """Explicitly registered callable functions (thread-safe)."""
442
+
443
+ def __init__(self) -> None:
444
+ self._methods: dict[str, _Method] = {}
445
+ self._lock = threading.Lock()
446
+
447
+ def register(
448
+ self,
449
+ name: str,
450
+ fn: Callable[..., Any],
451
+ *,
452
+ stream: bool = False,
453
+ schema: Mapping[str, Any] | None = None,
454
+ description: str | None = None,
455
+ timeout: float | None = None,
456
+ ) -> Callable[[], None]:
457
+ """Register ``fn`` as ``name``; returns an unregister function."""
458
+ if not isinstance(cast(object, name), str) or not NAME_RE.fullmatch(name):
459
+ raise ValidationError(f"invalid RPC method name {name!r}")
460
+ if not callable(fn):
461
+ raise ValidationError("handler must be callable")
462
+ kind = classify_handler(fn)
463
+ is_gen = kind in (HandlerKind.ASYNC_GEN, HandlerKind.SYNC_GEN)
464
+ if stream and not is_gen:
465
+ raise ValidationError(f"{name}: stream=True needs a generator or async generator")
466
+ if is_gen and not stream:
467
+ raise ValidationError(f"{name}: generator handlers must be registered with stream=True")
468
+ sig = inspect.signature(fn)
469
+ try:
470
+ hints = typing.get_type_hints(fn)
471
+ except Exception: # unresolved forward references: no type checks
472
+ hints = {}
473
+ params: list[str] = []
474
+ required: list[str] = []
475
+ derived: dict[str, dict[str, Any]] = {}
476
+ accepts_ctx = False
477
+ varkw = False
478
+ for p in sig.parameters.values():
479
+ if p.name == "ctx":
480
+ accepts_ctx = True
481
+ continue
482
+ if p.kind is inspect.Parameter.VAR_KEYWORD:
483
+ varkw = True
484
+ continue
485
+ if p.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.POSITIONAL_ONLY):
486
+ raise ValidationError(f"{name}: RPC handlers take named parameters only")
487
+ params.append(p.name)
488
+ if p.default is inspect.Parameter.empty:
489
+ required.append(p.name)
490
+ sch = _annotation_schema(hints.get(p.name, p.annotation))
491
+ if sch is not None:
492
+ derived[p.name] = sch
493
+ schema_d: dict[str, Any] | None = None
494
+ if schema is not None:
495
+ schema_d = dict(schema)
496
+ check_schema(schema_d)
497
+ if schema_d.get("type", "object") != "object":
498
+ raise ValidationError(f"{name}: params schema must describe an object")
499
+ with self._lock:
500
+ if name in self._methods:
501
+ raise ValidationError(f"RPC method {name!r} is already registered")
502
+ self._methods[name] = _Method(
503
+ name,
504
+ fn,
505
+ kind,
506
+ stream,
507
+ schema_d,
508
+ derived,
509
+ params,
510
+ required,
511
+ accepts_ctx,
512
+ varkw,
513
+ description,
514
+ timeout,
515
+ )
516
+
517
+ def unregister() -> None:
518
+ with self._lock:
519
+ if self._methods.get(name) is not None and self._methods[name].fn is fn:
520
+ del self._methods[name]
521
+
522
+ return unregister
523
+
524
+ def get(self, name: str) -> _Method | None:
525
+ with self._lock:
526
+ return self._methods.get(name)
527
+
528
+ def names(self) -> list[str]:
529
+ with self._lock:
530
+ return sorted(self._methods)
531
+
532
+ def discover(self) -> list[MethodInfo]:
533
+ with self._lock:
534
+ return [m.info() for _, m in sorted(self._methods.items())]
535
+
536
+ def bind(self, method: _Method, params: dict[str, Any] | None) -> dict[str, Any]:
537
+ """Validate ``params`` for ``method``; raise RpcError(INVALID_PARAMS)."""
538
+ args = dict(params or {})
539
+ if "ctx" in args:
540
+ raise RpcError("INVALID_PARAMS", "'ctx' is reserved")
541
+ if method.schema is not None:
542
+ validate_value(method.schema, args)
543
+ unknown = set(args) - set(method.params)
544
+ if unknown and not method.varkw:
545
+ raise RpcError("INVALID_PARAMS", f"unknown parameters {sorted(unknown)}")
546
+ missing = [r for r in method.required if r not in args]
547
+ if missing:
548
+ raise RpcError("INVALID_PARAMS", f"missing parameters {missing}")
549
+ for k, sch in method.derived.items():
550
+ if k in args:
551
+ validate_value(sch, args[k], k)
552
+ return args
553
+
554
+
555
+ # ----------------------------------------------------------------- context
556
+ class RpcContext:
557
+ """Per-call context. Declare a parameter named ``ctx`` to receive it."""
558
+
559
+ def __init__(
560
+ self,
561
+ endpoint: RpcEndpoint,
562
+ peer: str,
563
+ request_id: str,
564
+ method: str,
565
+ loop: asyncio.AbstractEventLoop,
566
+ ) -> None:
567
+ self._endpoint = endpoint
568
+ self.peer = peer
569
+ self.request_id = request_id
570
+ self.method = method
571
+ self._loop = loop
572
+ self._cancel_async = asyncio.Event()
573
+ self._cancel_flag = threading.Event()
574
+ self._progress_cb: Callable[[Any], None] | None = None
575
+ # Progress from worker threads is coalesced before it reaches the loop:
576
+ # at most one flush is scheduled, carrying the latest value (RPC-8).
577
+ self._progress_lock = threading.Lock()
578
+ self._progress_latest: Any = None
579
+ self._progress_scheduled = False
580
+ self._return_value: Any = None
581
+
582
+ @property
583
+ def client(self) -> AsyncClient:
584
+ """Native client of the session this call arrived on (use from async code)."""
585
+ return self._endpoint.client
586
+
587
+ @property
588
+ def window(self) -> str:
589
+ """Extension id of the session (identifies the window)."""
590
+ return self._endpoint.client.extension_id
591
+
592
+ @property
593
+ def cancelled(self) -> bool:
594
+ return self._cancel_flag.is_set()
595
+
596
+ async def wait_cancelled(self) -> None:
597
+ await self._cancel_async.wait()
598
+
599
+ def _cancel(self) -> None:
600
+ self._cancel_flag.set()
601
+ self._cancel_async.set()
602
+
603
+ def progress(
604
+ self,
605
+ value: Mapping[str, Any] | Any = None,
606
+ *,
607
+ message: str | None = None,
608
+ current: float | None = None,
609
+ total: float | None = None,
610
+ unit: str | None = None,
611
+ ) -> None:
612
+ """Report progress (thread-safe; rate-limited and coalesced)."""
613
+ if value is None:
614
+ value = {
615
+ k: v
616
+ for k, v in (
617
+ ("message", message),
618
+ ("current", current),
619
+ ("total", total),
620
+ ("unit", unit),
621
+ )
622
+ if v is not None
623
+ }
624
+ cb = self._progress_cb
625
+ if cb is None:
626
+ return
627
+ if self._on_loop():
628
+ cb(value)
629
+ return
630
+ # From a worker thread: a tight loop may call this thousands of times a
631
+ # second. One callback per call would flood the event loop (starving
632
+ # every other call); keep only the latest value and one pending flush.
633
+ with self._progress_lock:
634
+ self._progress_latest = value
635
+ if self._progress_scheduled:
636
+ return
637
+ self._progress_scheduled = True
638
+ try:
639
+ self._loop.call_soon_threadsafe(self._flush_progress)
640
+ except RuntimeError: # loop closed: the call is over
641
+ with self._progress_lock:
642
+ self._progress_scheduled = False
643
+
644
+ def _flush_progress(self) -> None:
645
+ with self._progress_lock:
646
+ value = self._progress_latest
647
+ self._progress_scheduled = False
648
+ cb = self._progress_cb
649
+ if cb is not None:
650
+ cb(value)
651
+
652
+ def set_result(self, value: Any) -> None:
653
+ """Set the terminal metadata of a *stream* call (the ``value`` of its
654
+ final ``result``; default ``null``). A sync generator's ``return``
655
+ value does the same; async generators cannot return a value, so they
656
+ call this before finishing."""
657
+ self._return_value = value
658
+
659
+ def _on_loop(self) -> bool:
660
+ try:
661
+ return asyncio.get_running_loop() is self._loop
662
+ except RuntimeError:
663
+ return False
664
+
665
+ def run(self, coro: Coroutine[Any, Any, T], timeout: float | None = None) -> T:
666
+ """From a *sync* handler thread: run ``coro`` on the session loop and wait."""
667
+ if self._on_loop():
668
+ coro.close()
669
+ raise RuntimeError("ctx.run() is for sync handlers; await the coroutine instead")
670
+ return asyncio.run_coroutine_threadsafe(coro, self._loop).result(timeout)
671
+
672
+
673
+ # ------------------------------------------------------------ peer & ops
674
+ class _ReplayCache:
675
+ def __init__(self, size: int, ttl: float) -> None:
676
+ self.size = size
677
+ self.ttl = ttl
678
+ self._ids: OrderedDict[str, float] = OrderedDict()
679
+
680
+ def seen(self, rid: str) -> bool:
681
+ now = time.monotonic()
682
+ while self._ids:
683
+ _, t = next(iter(self._ids.items()))
684
+ if now - t > self.ttl or len(self._ids) > self.size:
685
+ self._ids.popitem(last=False)
686
+ else:
687
+ break
688
+ return rid in self._ids
689
+
690
+ def add(self, rid: str) -> None:
691
+ self._ids[rid] = time.monotonic()
692
+ while len(self._ids) > self.size:
693
+ self._ids.popitem(last=False)
694
+
695
+
696
+ @dataclass
697
+ class _Incoming:
698
+ """A call this endpoint executes for a peer."""
699
+
700
+ id: str
701
+ method: str
702
+ ctx: RpcContext
703
+ task: asyncio.Task[None] | None = None
704
+ stream: bool = False
705
+ credit: int = 0
706
+ credit_event: asyncio.Event = field(default_factory=asyncio.Event)
707
+ terminal: bool = False
708
+ progress_seq: int = 0
709
+ progress_pending: Any = None
710
+ progress_has_pending: bool = False
711
+ progress_last: float = 0.0
712
+ progress_timer: asyncio.TimerHandle | None = None
713
+
714
+
715
+ @dataclass
716
+ class _Outgoing:
717
+ """A call this endpoint made to a peer."""
718
+
719
+ id: str
720
+ method: str
721
+ future: asyncio.Future[Any]
722
+ stream: bool = False
723
+ queue: asyncio.Queue[tuple[str, Any]] | None = None
724
+ seq: int = 0
725
+ progress_seq: int = 0
726
+ on_progress: Callable[[Any], Any] | None = None
727
+ terminal: bool = False
728
+
729
+
730
+ @dataclass
731
+ class Peer:
732
+ """A frontend page that completed the handshake."""
733
+
734
+ id: str
735
+ generation: str
736
+ capabilities: list[str]
737
+ hello_id: str
738
+ connected_at: float = field(default_factory=time.monotonic)
739
+ incoming: dict[str, _Incoming] = field(default_factory=dict[str, _Incoming])
740
+ outgoing: dict[str, _Outgoing] = field(default_factory=dict[str, _Outgoing])
741
+ replay: _ReplayCache = field(default_factory=lambda: _ReplayCache(1024, 60.0))
742
+ alive: bool = True
743
+
744
+
745
+ def _error_payload(err: BaseException) -> dict[str, Any]:
746
+ if isinstance(err, RpcError):
747
+ out: dict[str, Any] = {
748
+ "code": err.code if CODE_RE.fullmatch(err.code) else "INTERNAL_ERROR",
749
+ "message": truncate_u16(err.message, 4096),
750
+ }
751
+ if err.details is not None:
752
+ try:
753
+ check_json(err.details, max_depth=16, safe_integers=True)
754
+ out["details"] = err.details
755
+ except ValidationError:
756
+ pass
757
+ return out
758
+ if isinstance(err, asyncio.CancelledError):
759
+ return {"code": "CANCELLED", "message": "cancelled"}
760
+ # SDK deadlines arrive here as RpcError("TIMEOUT"); a TimeoutError the
761
+ # handler raised itself is an internal failure like any other exception.
762
+ return {"code": "INTERNAL_ERROR", "message": "internal error"}
763
+
764
+
765
+ class RpcStream:
766
+ """Async iterator over a page stream; ``result`` is set when it completes.
767
+
768
+ Leaving the loop early does not by itself stop the page (the handle keeps
769
+ the iterator alive): use ``async with`` or call :meth:`aclose`, which
770
+ cancels the stream and frees its slot.
771
+ """
772
+
773
+ def __init__(self) -> None:
774
+ self.result: Any = None
775
+ self._gen: AsyncGenerator[Any] | None = None
776
+
777
+ def __aiter__(self) -> AsyncIterator[Any]:
778
+ assert self._gen is not None
779
+ return self._gen
780
+
781
+ async def aclose(self) -> None:
782
+ """Stop consuming: sends ``cancel`` if the stream is still running."""
783
+ if self._gen is not None:
784
+ await self._gen.aclose()
785
+
786
+ async def __aenter__(self) -> RpcStream:
787
+ return self
788
+
789
+ async def __aexit__(self, *exc: object) -> None:
790
+ await self.aclose()
791
+
792
+
793
+ # ---------------------------------------------------------------- endpoint
794
+ class RpcEndpoint:
795
+ """RPC v1 endpoint for one runtime session (one AsyncClient)."""
796
+
797
+ def __init__(
798
+ self,
799
+ client: AsyncClient,
800
+ registry: Registry,
801
+ *,
802
+ limits: RpcLimits | None = None,
803
+ engine: ExecutionEngine | None = None,
804
+ ) -> None:
805
+ self.client = client
806
+ self.registry = registry
807
+ self.limits = limits or RpcLimits()
808
+ self.engine = engine or ExecutionEngine()
809
+ self._own_engine = engine is None
810
+ self.session = "s-" + secrets.token_urlsafe(12)
811
+ self.backend_id = client.extension_id
812
+ self.peers: dict[str, Peer] = {}
813
+ self._ready_waiters: list[asyncio.Future[Peer]] = []
814
+ self._send_queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue(
815
+ self.limits.max_send_queue
816
+ )
817
+ self._sender: asyncio.Task[None] | None = None
818
+ self._inflight = asyncio.Semaphore(16)
819
+ self._tasks: set[asyncio.Task[Any]] = set()
820
+ self._started = False
821
+ self._closed = False
822
+ self._unknown_session_notice: OrderedDict[str, float] = OrderedDict()
823
+ self._notice_times: list[float] = []
824
+ self._prev_on_error: Any = None
825
+ self.stats = {"received": 0, "rejected": 0, "sent": 0, "send_errors": 0}
826
+ self.on_peer: Callable[[Peer, str], None] | None = None
827
+ # Opt-in call observer (debugging tools such as the Explorer's RPC log):
828
+ # called on the loop once per finished call, see _observe. None: no cost.
829
+ self.observer: Callable[[dict[str, Any]], None] | None = None
830
+
831
+ def _observe(
832
+ self,
833
+ direction: str,
834
+ kind: str,
835
+ method: str,
836
+ params: Any,
837
+ started: float,
838
+ failure: BaseException | None,
839
+ ) -> None:
840
+ """Report one finished call to ``observer``: ``direction`` "in" (the page
841
+ called Python) or "out" (Python called the page), ``kind`` "request" or
842
+ "notify", the method, the raw ``params`` (may hold secrets: an observer
843
+ must redact before keeping them), ``duration`` in seconds and ``error``
844
+ (None, an RPC error code or the exception type name)."""
845
+ observer = self.observer
846
+ if observer is None:
847
+ return
848
+ error = None
849
+ if failure is not None:
850
+ error = failure.code if isinstance(failure, RpcError) else type(failure).__name__
851
+ record = {
852
+ "direction": direction,
853
+ "kind": kind,
854
+ "method": method,
855
+ "params": params,
856
+ "duration": time.monotonic() - started if started else 0.0,
857
+ "error": error,
858
+ }
859
+ try:
860
+ observer(record)
861
+ except Exception:
862
+ log.exception("RPC observer failed")
863
+
864
+ # --------------------------------------------------------- lifecycle
865
+ def start(self) -> None:
866
+ if self._started:
867
+ return
868
+ self._started = True
869
+ self._sub = self.client.events.on(RPC_EVENT, self._on_event, queue_size=self.limits.inbox)
870
+ self._sub_disc = self.client.events.on("appClientDisconnect", self._on_app_disconnect)
871
+ self._sender = asyncio.get_running_loop().create_task(self._send_loop())
872
+ self._prev_on_error = self.client.events.on_error
873
+ self.client.events.on_error = self._on_event_error
874
+
875
+ def _on_event_error(self, sub: Any, err: BaseException) -> None:
876
+ if (
877
+ sub is getattr(self, "_sub", None)
878
+ and isinstance(err, QueueFullError)
879
+ and not self._closed
880
+ ):
881
+ # The inbox overflowed (a flood). Shed load: drop every peer (their
882
+ # calls fail DISCONNECTED, pages re-handshake) and listen again.
883
+ log.error(
884
+ "RPC inbox overflowed (%s); peers dropped, inbox re-opened", type(err).__name__
885
+ )
886
+ for peer in list(self.peers.values()):
887
+ self._drop_peer(peer, "DISCONNECTED")
888
+ self._sub = self.client.events.on(
889
+ RPC_EVENT, self._on_event, queue_size=self.limits.inbox
890
+ )
891
+ prev = self._prev_on_error
892
+ if prev is not None:
893
+ prev(sub, err)
894
+
895
+ async def close(self, reason: str = "backend closing") -> list[str]:
896
+ """Send bye to every peer, cancel work, fail calls. Returns still-running
897
+ sync handler labels (uncooperative)."""
898
+ if self._closed:
899
+ return []
900
+ self._closed = True
901
+ for peer in list(self.peers.values()):
902
+ if not self.client.closed:
903
+ self._enqueue(peer, "bye", secrets.token_hex(8), {"reason": reason})
904
+ self._drop_peer(peer, "DISCONNECTED")
905
+ if self._sender is not None:
906
+ try:
907
+ self._send_queue.put_nowait(None)
908
+ except asyncio.QueueFull:
909
+ self._sender.cancel()
910
+ await asyncio.wait({self._sender}, timeout=2.0)
911
+ if not self._sender.done():
912
+ self._sender.cancel()
913
+ grace = self.client.limits.shutdown_grace
914
+ tasks = [t for t in self._tasks if not t.done()]
915
+ for t in tasks:
916
+ t.cancel()
917
+ stuck: list[str] = []
918
+ if tasks:
919
+ _, pending = await asyncio.wait(tasks, timeout=grace)
920
+ stuck = sorted(t.get_name() for t in pending)
921
+ if stuck:
922
+ log.warning("RPC handlers ignored cancellation at close: %s", stuck)
923
+ if self._started:
924
+ self._sub.unsubscribe()
925
+ self._sub_disc.unsubscribe()
926
+ if self._own_engine:
927
+ stuck += await self.engine.shutdown(grace)
928
+ return stuck
929
+
930
+ def _spawn(self, coro: Coroutine[Any, Any, Any], name: str | None = None) -> asyncio.Task[Any]:
931
+ task = asyncio.get_running_loop().create_task(coro, name=name)
932
+ self._tasks.add(task)
933
+ task.add_done_callback(self._tasks.discard)
934
+ return task
935
+
936
+ # ------------------------------------------------------------ sending
937
+ def _envelope(
938
+ self, peer: Peer | None, kind: str, rid: str, to: str, generation: str | None
939
+ ) -> dict[str, Any]:
940
+ return {
941
+ "v": 1,
942
+ "kind": kind,
943
+ "session": self.session,
944
+ "generation": generation
945
+ if generation is not None
946
+ else (peer.generation if peer else None),
947
+ "from": self.backend_id,
948
+ "to": to,
949
+ "id": rid,
950
+ }
951
+
952
+ def _enqueue(
953
+ self,
954
+ peer: Peer | None,
955
+ kind: str,
956
+ rid: str,
957
+ fields: dict[str, Any],
958
+ *,
959
+ to: str | None = None,
960
+ generation: str | None = None,
961
+ ) -> None:
962
+ target = to if to is not None else (peer.id if peer else "")
963
+ msg = {**self._envelope(peer, kind, rid, target, generation), **fields}
964
+ try:
965
+ self._send_queue.put_nowait(msg)
966
+ except asyncio.QueueFull:
967
+ log.error(
968
+ "RPC send queue full (%d); dropping peer %s", self.limits.max_send_queue, target
969
+ )
970
+ if peer is not None:
971
+ self._drop_peer(peer, "DISCONNECTED")
972
+
973
+ async def _send_loop(self) -> None:
974
+ while True:
975
+ msg = await self._send_queue.get()
976
+ if msg is None:
977
+ return
978
+ await self._inflight.acquire()
979
+ self._spawn(self._send_one(msg))
980
+
981
+ async def _send_one(self, msg: dict[str, Any]) -> None:
982
+ try:
983
+ await self.client.app.broadcast(RPC_EVENT, msg)
984
+ self.stats["sent"] += 1
985
+ except Exception as e:
986
+ self.stats["send_errors"] += 1
987
+ log.error("RPC send of %s failed: %s", msg.get("kind"), type(e).__name__)
988
+ kind = msg.get("kind")
989
+ if kind == "chunk":
990
+ # The stream has a gap now: end it here (once) and stop the producer.
991
+ peer = self.peers.get(msg.get("to", ""))
992
+ inc = peer.incoming.get(msg.get("id", "")) if peer else None
993
+ if inc is not None and not inc.terminal:
994
+ inc.terminal = True
995
+ inc.ctx._cancel() # pyright: ignore[reportPrivateUsage]
996
+ if inc.task is not None:
997
+ inc.task.cancel()
998
+ if kind in ("result", "chunk"):
999
+ # Tell the caller instead of letting it wait for its deadline. A
1000
+ # failed progress message is not worth failing the call over.
1001
+ fail = {
1002
+ **{k: msg[k] for k in ("v", "session", "generation", "from", "to", "id")},
1003
+ "kind": "error",
1004
+ "error": {
1005
+ "code": "INTERNAL_ERROR",
1006
+ "message": f"could not deliver {kind}: {type(e).__name__}",
1007
+ },
1008
+ }
1009
+ with contextlib.suppress(Exception):
1010
+ await self.client.app.broadcast(RPC_EVENT, fail)
1011
+ finally:
1012
+ self._inflight.release()
1013
+
1014
+ # ---------------------------------------------------------- receiving
1015
+ async def _on_app_disconnect(self, ev: Event) -> None:
1016
+ if ev.data == 0:
1017
+ for peer in list(self.peers.values()):
1018
+ self._drop_peer(peer, "DISCONNECTED")
1019
+
1020
+ async def _on_event(self, ev: Event) -> None:
1021
+ self.stats["received"] += 1
1022
+ if self._closed:
1023
+ # close() has started: no new peers (a late hello retry) and no work.
1024
+ self.stats["rejected"] += 1
1025
+ return
1026
+ try:
1027
+ msg = validate_message(ev.data, self.limits)
1028
+ except ValidationError as e:
1029
+ self.stats["rejected"] += 1
1030
+ log.debug("rejected rpc message: %s", redact_reason(e))
1031
+ return
1032
+ if msg["to"] != self.backend_id:
1033
+ self.stats["rejected"] += 1
1034
+ return
1035
+ kind = msg["kind"]
1036
+ if kind == "hello":
1037
+ self._on_hello(msg)
1038
+ return
1039
+ peer = self.peers.get(msg["from"])
1040
+ if peer is None or msg["session"] != self.session or msg["generation"] != peer.generation:
1041
+ self.stats["rejected"] += 1
1042
+ self._notice_unknown_session(msg)
1043
+ return
1044
+ handler = {
1045
+ "request": self._on_request,
1046
+ "notify": self._on_notify,
1047
+ "discover": self._on_discover,
1048
+ "cancel": self._on_cancel,
1049
+ "credit": self._on_credit,
1050
+ "result": self._on_terminal,
1051
+ "error": self._on_terminal,
1052
+ "chunk": self._on_chunk,
1053
+ "progress": self._on_progress,
1054
+ "bye": self._on_bye,
1055
+ "welcome": self._on_stray,
1056
+ }[kind]
1057
+ handler(peer, msg)
1058
+
1059
+ def _notice_unknown_session(self, msg: dict[str, Any]) -> None:
1060
+ # A page from before a backend restart: tell it once (per 5 s) to re-handshake.
1061
+ now = time.monotonic()
1062
+ if now - self._unknown_session_notice.get(msg["from"], 0.0) < 5.0:
1063
+ return
1064
+ self._notice_times = [t for t in self._notice_times if now - t < 1.0]
1065
+ if len(self._notice_times) >= 20:
1066
+ return # global cap: a flood of forged ids cannot amplify into broadcasts
1067
+ self._notice_times.append(now)
1068
+ self._unknown_session_notice[msg["from"]] = now
1069
+ self._unknown_session_notice.move_to_end(msg["from"])
1070
+ while len(self._unknown_session_notice) > 256:
1071
+ self._unknown_session_notice.popitem(last=False)
1072
+ self._enqueue(
1073
+ None,
1074
+ "bye",
1075
+ secrets.token_hex(8),
1076
+ {"reason": "unknown session"},
1077
+ to=msg["from"],
1078
+ generation=msg.get("generation") or "none",
1079
+ )
1080
+
1081
+ def _on_stray(self, peer: Peer, msg: dict[str, Any]) -> None:
1082
+ self.stats["rejected"] += 1
1083
+
1084
+ def _on_hello(self, msg: dict[str, Any]) -> None:
1085
+ pid = msg["from"]
1086
+ existing = self.peers.get(pid)
1087
+ if existing is not None and existing.hello_id == msg["id"]:
1088
+ # Retried hello: answer idempotently, replay nothing.
1089
+ self._enqueue(existing, "welcome", msg["id"], {"capabilities": list(CAPABILITIES)})
1090
+ return
1091
+ if existing is not None:
1092
+ self._drop_peer(existing, "DISCONNECTED")
1093
+ if len(self.peers) >= self.limits.max_peers:
1094
+ idle = [p for p in self.peers.values() if not p.incoming and not p.outgoing]
1095
+ if idle:
1096
+ oldest = min(idle, key=lambda p: p.connected_at)
1097
+ log.warning("peer limit reached; evicting idle peer %s", oldest.id)
1098
+ self._enqueue(oldest, "bye", secrets.token_hex(8), {"reason": "evicted"})
1099
+ self._drop_peer(oldest, "DISCONNECTED")
1100
+ else:
1101
+ log.warning("rejecting hello: %d busy peers connected", len(self.peers))
1102
+ self._enqueue(
1103
+ None,
1104
+ "bye",
1105
+ secrets.token_hex(8),
1106
+ {"reason": "too many peers"},
1107
+ to=pid,
1108
+ generation="none",
1109
+ )
1110
+ return
1111
+ peer = Peer(pid, "g-" + secrets.token_urlsafe(9), list(msg["capabilities"]), msg["id"])
1112
+ peer.replay = _ReplayCache(self.limits.replay_size, self.limits.replay_ttl)
1113
+ self.peers[pid] = peer
1114
+ self._enqueue(peer, "welcome", msg["id"], {"capabilities": list(CAPABILITIES)})
1115
+ for w in self._ready_waiters:
1116
+ if not w.done():
1117
+ w.set_result(peer)
1118
+ self._ready_waiters.clear()
1119
+ if self.on_peer:
1120
+ self.on_peer(peer, "ready")
1121
+
1122
+ def _on_bye(self, peer: Peer, msg: dict[str, Any]) -> None:
1123
+ self._drop_peer(peer, "DISCONNECTED")
1124
+
1125
+ def _drop_peer(self, peer: Peer, code: str) -> None:
1126
+ if not peer.alive:
1127
+ return
1128
+ peer.alive = False
1129
+ self.peers.pop(peer.id, None)
1130
+ for inc in list(peer.incoming.values()):
1131
+ inc.terminal = True
1132
+ inc.ctx._cancel() # pyright: ignore[reportPrivateUsage]
1133
+ if inc.task is not None:
1134
+ inc.task.cancel()
1135
+ for out in list(peer.outgoing.values()):
1136
+ self._fail_outgoing(out, RpcError(code, "peer disconnected"))
1137
+ peer.incoming.clear()
1138
+ peer.outgoing.clear()
1139
+ if self.on_peer:
1140
+ self.on_peer(peer, "gone")
1141
+
1142
+ # ----------------------------------------------- incoming: execution
1143
+ def _admit(self, peer: Peer, msg: dict[str, Any], reply: bool) -> bool:
1144
+ rid = msg["id"]
1145
+ if rid in peer.incoming or peer.replay.seen(rid):
1146
+ log.debug("duplicate request id ignored")
1147
+ self.stats["rejected"] += 1
1148
+ return False
1149
+ if len(peer.incoming) >= self.limits.max_active_per_peer:
1150
+ if reply:
1151
+ self._enqueue(
1152
+ peer,
1153
+ "error",
1154
+ rid,
1155
+ {"error": {"code": "BUSY", "message": "too many active calls"}},
1156
+ )
1157
+ peer.replay.add(rid)
1158
+ return False
1159
+ return True
1160
+
1161
+ def _on_request(self, peer: Peer, msg: dict[str, Any]) -> None:
1162
+ if not self._admit(peer, msg, reply=True):
1163
+ return
1164
+ ctx = RpcContext(self, peer.id, msg["id"], msg["method"], asyncio.get_running_loop())
1165
+ inc = _Incoming(
1166
+ msg["id"], msg["method"], ctx, stream=msg["stream"], credit=msg.get("credit", 0)
1167
+ )
1168
+ peer.incoming[inc.id] = inc
1169
+ ctx._progress_cb = lambda v: self._progress_out(peer, inc, v) # pyright: ignore[reportPrivateUsage]
1170
+ inc.task = self._spawn(
1171
+ self._execute(peer, inc, msg), name=f"rpc:{peer.id}:{inc.id}:{msg['method']}"
1172
+ )
1173
+
1174
+ def _on_notify(self, peer: Peer, msg: dict[str, Any]) -> None:
1175
+ if not self._admit(peer, msg, reply=False):
1176
+ return
1177
+ ctx = RpcContext(self, peer.id, msg["id"], msg["method"], asyncio.get_running_loop())
1178
+ inc = _Incoming(msg["id"], msg["method"], ctx)
1179
+ peer.incoming[inc.id] = inc
1180
+ inc.task = self._spawn(
1181
+ self._execute(peer, inc, msg, reply=False),
1182
+ name=f"rpc-notify:{peer.id}:{inc.id}:{msg['method']}",
1183
+ )
1184
+
1185
+ def _on_discover(self, peer: Peer, msg: dict[str, Any]) -> None:
1186
+ if not self._admit(peer, msg, reply=True):
1187
+ return
1188
+ peer.replay.add(msg["id"])
1189
+ value = [m.to_json() for m in self.registry.discover()]
1190
+ self._enqueue(peer, "result", msg["id"], {"value": value})
1191
+
1192
+ async def _execute(
1193
+ self, peer: Peer, inc: _Incoming, msg: dict[str, Any], reply: bool = True
1194
+ ) -> None:
1195
+ started = time.monotonic() if self.observer is not None else 0.0
1196
+ failure: BaseException | None = None
1197
+ try:
1198
+ method = self.registry.get(msg["method"])
1199
+ if method is None:
1200
+ raise RpcError("METHOD_NOT_FOUND", f"no method {msg['method']!r}")
1201
+ if method.stream != inc.stream and reply:
1202
+ raise RpcError("UNSUPPORTED", "stream mode does not match the registration")
1203
+ if method.stream and not reply:
1204
+ raise RpcError("UNSUPPORTED", "a stream method cannot be notified")
1205
+ kwargs = self.registry.bind(method, msg.get("params"))
1206
+ if method.accepts_ctx:
1207
+ kwargs["ctx"] = inc.ctx
1208
+ timeout = method.timeout or self.limits.call_timeout
1209
+ if inc.stream:
1210
+ item_timeout = method.timeout or self.limits.stream_idle_timeout
1211
+ await self._run_stream(peer, inc, method, kwargs, item_timeout)
1212
+ else:
1213
+ label = f"{peer.id}:{inc.id}:{method.name}"
1214
+ deadline = asyncio.timeout(timeout)
1215
+ try:
1216
+ async with deadline:
1217
+ value = await self.engine.call(label, method.fn, kwargs)
1218
+ except TimeoutError:
1219
+ if not deadline.expired():
1220
+ raise # the handler's own TimeoutError, not our deadline
1221
+ inc.ctx._cancel() # pyright: ignore[reportPrivateUsage]
1222
+ raise RpcError(
1223
+ "TIMEOUT", f"handler did not finish within {timeout:g}s"
1224
+ ) from None
1225
+ if reply:
1226
+ self._send_result(peer, inc, value)
1227
+ except asyncio.CancelledError:
1228
+ failure = RpcError("CANCELLED", "cancelled")
1229
+ if reply and not inc.terminal and peer.alive:
1230
+ self._send_terminal_error(peer, inc, failure)
1231
+ except BaseException as e:
1232
+ failure = e
1233
+ if not isinstance(e, RpcError):
1234
+ log.exception("RPC handler %s raised", msg["method"])
1235
+ if reply and not inc.terminal and peer.alive:
1236
+ self._send_terminal_error(peer, inc, e)
1237
+ elif not reply and not isinstance(e, RpcError):
1238
+ pass
1239
+ if isinstance(e, (KeyboardInterrupt, SystemExit)):
1240
+ raise
1241
+ finally:
1242
+ inc.terminal = True
1243
+ if inc.progress_timer is not None:
1244
+ inc.progress_timer.cancel()
1245
+ peer.incoming.pop(inc.id, None)
1246
+ peer.replay.add(inc.id)
1247
+ if self.observer is not None:
1248
+ kind = "request" if reply else "notify"
1249
+ self._observe("in", kind, msg["method"], msg.get("params"), started, failure)
1250
+
1251
+ def _send_result(self, peer: Peer, inc: _Incoming, value: Any) -> None:
1252
+ if inc.terminal or not peer.alive:
1253
+ return
1254
+ try:
1255
+ check_json(value, max_depth=self.limits.max_json_depth, safe_integers=True)
1256
+ except ValidationError as e:
1257
+ raise RpcError("INTERNAL_ERROR", f"result is not JSON: {e}") from None
1258
+ if len(dumps(value).encode()) > self.limits.max_message_bytes - 1024:
1259
+ raise RpcError(
1260
+ "INTERNAL_ERROR",
1261
+ f"result exceeds the {self.limits.max_message_bytes}-byte RPC limit",
1262
+ )
1263
+ self._final_progress(peer, inc)
1264
+ inc.terminal = True
1265
+ self._enqueue(peer, "result", inc.id, {"value": value})
1266
+
1267
+ def _final_progress(self, peer: Peer, inc: _Incoming) -> None:
1268
+ """Coalescing may hold back the latest progress; deliver it before the
1269
+ terminal message instead of dropping it."""
1270
+ if inc.progress_timer is not None:
1271
+ inc.progress_timer.cancel()
1272
+ inc.progress_timer = None
1273
+ if inc.progress_has_pending:
1274
+ self._flush_progress(peer, inc)
1275
+
1276
+ def _send_terminal_error(self, peer: Peer, inc: _Incoming, err: BaseException) -> None:
1277
+ if inc.terminal:
1278
+ return
1279
+ self._final_progress(peer, inc)
1280
+ inc.terminal = True
1281
+ self._enqueue(peer, "error", inc.id, {"error": _error_payload(err)})
1282
+
1283
+ async def _run_stream(
1284
+ self,
1285
+ peer: Peer,
1286
+ inc: _Incoming,
1287
+ method: _Method,
1288
+ kwargs: dict[str, Any],
1289
+ item_timeout: float,
1290
+ ) -> None:
1291
+ """Pull items from the handler and send them as credit allows.
1292
+
1293
+ Producing each item is bounded by ``item_timeout`` (the method's
1294
+ ``timeout`` or ``stream_idle_timeout``); waiting for consumer credit is
1295
+ bounded by ``stream_idle_timeout``.
1296
+ """
1297
+ label = f"{peer.id}:{inc.id}:{method.name}"
1298
+ it = self.engine.iterate(label, method.fn, kwargs, inc.ctx)
1299
+ seq = 0
1300
+ try:
1301
+ while True:
1302
+ try:
1303
+ item = await asyncio.wait_for(anext(it), item_timeout)
1304
+ except StopAsyncIteration:
1305
+ break
1306
+ except TimeoutError:
1307
+ inc.ctx._cancel() # pyright: ignore[reportPrivateUsage]
1308
+ raise RpcError(
1309
+ "TIMEOUT", f"stream produced no item within {item_timeout:g}s"
1310
+ ) from None
1311
+ try:
1312
+ check_json(item, max_depth=self.limits.max_json_depth, safe_integers=True)
1313
+ except ValidationError as e:
1314
+ raise RpcError("INTERNAL_ERROR", f"stream item is not JSON: {e}") from None
1315
+ if len(dumps(item).encode()) > self.limits.max_chunk_bytes:
1316
+ raise RpcError("STREAM_OVERFLOW", "stream item exceeds max chunk size")
1317
+ while inc.credit <= 0:
1318
+ inc.credit_event.clear()
1319
+ try:
1320
+ await asyncio.wait_for(
1321
+ inc.credit_event.wait(), self.limits.stream_idle_timeout
1322
+ )
1323
+ except TimeoutError:
1324
+ raise RpcError("TIMEOUT", "consumer granted no credit") from None
1325
+ if inc.terminal or not peer.alive:
1326
+ return
1327
+ inc.credit -= 1
1328
+ self._enqueue(peer, "chunk", inc.id, {"seq": seq, "value": item})
1329
+ seq += 1
1330
+ finally:
1331
+ aclose = getattr(it, "aclose", None)
1332
+ if aclose is not None:
1333
+ with contextlib.suppress(BaseException):
1334
+ await aclose()
1335
+ self._send_result(peer, inc, inc.ctx._return_value) # pyright: ignore[reportPrivateUsage]
1336
+
1337
+ def _on_credit(self, peer: Peer, msg: dict[str, Any]) -> None:
1338
+ inc = peer.incoming.get(msg["id"])
1339
+ if inc is None or not inc.stream:
1340
+ return
1341
+ inc.credit = min(self.limits.max_credit, inc.credit + msg["count"])
1342
+ inc.credit_event.set()
1343
+
1344
+ def _on_cancel(self, peer: Peer, msg: dict[str, Any]) -> None:
1345
+ inc = peer.incoming.get(msg["id"])
1346
+ if inc is None:
1347
+ return
1348
+ inc.ctx._cancel() # pyright: ignore[reportPrivateUsage]
1349
+ if inc.task is not None and not inc.task.done():
1350
+ inc.task.cancel()
1351
+
1352
+ def _progress_out(self, peer: Peer, inc: _Incoming, value: Any) -> None:
1353
+ if inc.terminal or not peer.alive:
1354
+ return
1355
+ try:
1356
+ check_json(value, max_depth=8, safe_integers=True)
1357
+ except ValidationError:
1358
+ log.warning("progress value is not JSON; dropped")
1359
+ return
1360
+ interval = 1.0 / self.limits.progress_per_second
1361
+ now = time.monotonic()
1362
+ inc.progress_pending = value
1363
+ inc.progress_has_pending = True
1364
+ if now - inc.progress_last >= interval:
1365
+ self._flush_progress(peer, inc)
1366
+ elif inc.progress_timer is None:
1367
+ delay = interval - (now - inc.progress_last)
1368
+ inc.progress_timer = asyncio.get_running_loop().call_later(
1369
+ delay, self._flush_progress, peer, inc
1370
+ )
1371
+
1372
+ def _flush_progress(self, peer: Peer, inc: _Incoming) -> None:
1373
+ inc.progress_timer = None
1374
+ if inc.terminal or not inc.progress_has_pending or not peer.alive:
1375
+ return
1376
+ inc.progress_has_pending = False
1377
+ inc.progress_last = time.monotonic()
1378
+ self._enqueue(
1379
+ peer, "progress", inc.id, {"seq": inc.progress_seq, "value": inc.progress_pending}
1380
+ )
1381
+ inc.progress_seq += 1
1382
+
1383
+ # ------------------------------------------------ outgoing: reverse
1384
+ def ready_peers(self) -> list[str]:
1385
+ return [p.id for p in self.peers.values() if p.alive]
1386
+
1387
+ async def wait_for_peer(self, timeout: float | None = None) -> str:
1388
+ if self.peers:
1389
+ return next(iter(self.peers))
1390
+ fut: asyncio.Future[Peer] = asyncio.get_running_loop().create_future()
1391
+ self._ready_waiters.append(fut)
1392
+ try:
1393
+ peer = await asyncio.wait_for(fut, timeout or self.limits.handshake_timeout)
1394
+ finally:
1395
+ with contextlib.suppress(ValueError):
1396
+ self._ready_waiters.remove(fut)
1397
+ return peer.id
1398
+
1399
+ def _pick(self, peer: str | None) -> Peer:
1400
+ if peer is not None:
1401
+ p = self.peers.get(peer)
1402
+ if p is None:
1403
+ raise RpcError("DISCONNECTED", f"peer {peer!r} is not connected")
1404
+ return p
1405
+ alive = list(self.peers.values())
1406
+ if len(alive) == 1:
1407
+ return alive[0]
1408
+ if not alive:
1409
+ raise RpcError("DISCONNECTED", "no frontend peer is connected")
1410
+ raise UnsupportedError("several frontend peers are connected; pass peer=")
1411
+
1412
+ def _new_outgoing(
1413
+ self, p: Peer, method: str, stream: bool, on_progress: Callable[[Any], Any] | None
1414
+ ) -> _Outgoing:
1415
+ if len(p.outgoing) >= self.limits.max_pending_calls:
1416
+ raise RpcError("BUSY", "too many pending calls to this peer")
1417
+ if not NAME_RE.fullmatch(method):
1418
+ raise ValidationError(f"invalid method name {method!r}")
1419
+ out = _Outgoing(
1420
+ "r-" + secrets.token_urlsafe(12),
1421
+ method,
1422
+ asyncio.get_running_loop().create_future(),
1423
+ stream=stream,
1424
+ queue=asyncio.Queue() if stream else None,
1425
+ on_progress=on_progress,
1426
+ )
1427
+ out.future.add_done_callback(lambda f: f.cancelled() or f.exception())
1428
+ p.outgoing[out.id] = out
1429
+ return out
1430
+
1431
+ async def invoke(
1432
+ self,
1433
+ method: str,
1434
+ params: Mapping[str, Any] | None = None,
1435
+ *,
1436
+ peer: str | None = None,
1437
+ timeout: float | None = None,
1438
+ on_progress: Callable[[Any], Any] | None = None,
1439
+ ) -> Any:
1440
+ """Call a function the frontend registered with ``backend.register``."""
1441
+ p = self._pick(peer)
1442
+ payload = None if params is None else dict(params)
1443
+ check_json(payload, max_depth=self.limits.max_json_depth, safe_integers=True)
1444
+ out = self._new_outgoing(p, method, False, on_progress)
1445
+ self._enqueue(p, "request", out.id, {"method": method, "params": payload, "stream": False})
1446
+ started = time.monotonic() if self.observer is not None else 0.0
1447
+ failure: BaseException | None = None
1448
+ try:
1449
+ return await asyncio.wait_for(
1450
+ asyncio.shield(out.future), timeout or self.limits.call_timeout
1451
+ )
1452
+ except TimeoutError:
1453
+ self._cancel_outgoing(p, out, "timeout")
1454
+ failure = RpcError("TIMEOUT", f"frontend call {method} timed out")
1455
+ raise failure from None
1456
+ except asyncio.CancelledError as e:
1457
+ failure = e
1458
+ self._cancel_outgoing(p, out, "cancelled")
1459
+ raise
1460
+ except BaseException as e:
1461
+ failure = e
1462
+ raise
1463
+ finally:
1464
+ p.outgoing.pop(out.id, None)
1465
+ if self.observer is not None:
1466
+ self._observe("out", "request", method, payload, started, failure)
1467
+
1468
+ async def notify(
1469
+ self, method: str, params: Mapping[str, Any] | None = None, *, peer: str | None = None
1470
+ ) -> None:
1471
+ p = self._pick(peer)
1472
+ payload = None if params is None else dict(params)
1473
+ check_json(payload, max_depth=self.limits.max_json_depth, safe_integers=True)
1474
+ if not NAME_RE.fullmatch(method):
1475
+ raise ValidationError(f"invalid method name {method!r}")
1476
+ self._enqueue(
1477
+ p, "notify", "n-" + secrets.token_urlsafe(12), {"method": method, "params": payload}
1478
+ )
1479
+ if self.observer is not None:
1480
+ self._observe("out", "notify", method, payload, 0.0, None)
1481
+
1482
+ async def discover(
1483
+ self, *, peer: str | None = None, timeout: float | None = None
1484
+ ) -> list[dict[str, Any]]:
1485
+ p = self._pick(peer)
1486
+ out = self._new_outgoing(p, "discover", False, None)
1487
+ self._enqueue(p, "discover", out.id, {})
1488
+ try:
1489
+ return await asyncio.wait_for(
1490
+ asyncio.shield(out.future), timeout or self.limits.call_timeout
1491
+ )
1492
+ except TimeoutError:
1493
+ raise RpcError("TIMEOUT", "discover timed out") from None
1494
+ finally:
1495
+ p.outgoing.pop(out.id, None)
1496
+
1497
+ def stream(
1498
+ self,
1499
+ method: str,
1500
+ params: Mapping[str, Any] | None = None,
1501
+ *,
1502
+ peer: str | None = None,
1503
+ timeout: float | None = None,
1504
+ ) -> RpcStream:
1505
+ """Consume a stream the frontend registered (``register(name, fn,
1506
+ {stream: true})``). After the ``async for`` loop ends, ``.result`` holds
1507
+ the terminal ``result`` value (always ``None`` for page streams today).
1508
+ Use ``async with app.frontend.stream(...) as s`` (or ``await
1509
+ s.aclose()``) when the loop may be left early."""
1510
+ handle = RpcStream()
1511
+ handle._gen = self._stream_gen(handle, method, params, peer, timeout) # pyright: ignore[reportPrivateUsage]
1512
+ return handle
1513
+
1514
+ async def _stream_gen(
1515
+ self,
1516
+ handle: RpcStream,
1517
+ method: str,
1518
+ params: Mapping[str, Any] | None,
1519
+ peer: str | None,
1520
+ timeout: float | None,
1521
+ ) -> AsyncGenerator[Any]:
1522
+ p = self._pick(peer)
1523
+ payload = None if params is None else dict(params)
1524
+ check_json(payload, max_depth=self.limits.max_json_depth, safe_integers=True)
1525
+ out = self._new_outgoing(p, method, True, None)
1526
+ self._enqueue(
1527
+ p,
1528
+ "request",
1529
+ out.id,
1530
+ {
1531
+ "method": method,
1532
+ "params": payload,
1533
+ "stream": True,
1534
+ "credit": self.limits.initial_credit,
1535
+ },
1536
+ )
1537
+ idle = timeout or self.limits.stream_idle_timeout
1538
+ assert out.queue is not None
1539
+ batch = max(1, self.limits.initial_credit // 2)
1540
+ consumed = 0
1541
+ try:
1542
+ while True:
1543
+ try:
1544
+ kind, value = await asyncio.wait_for(out.queue.get(), idle)
1545
+ except TimeoutError:
1546
+ self._cancel_outgoing(p, out, "idle timeout")
1547
+ raise RpcError("TIMEOUT", "stream idle timeout") from None
1548
+ if kind == "chunk":
1549
+ yield value
1550
+ consumed += 1
1551
+ if not out.terminal and p.alive and consumed >= batch:
1552
+ self._enqueue(p, "credit", out.id, {"count": consumed})
1553
+ consumed = 0
1554
+ continue
1555
+ if kind == "error":
1556
+ raise value
1557
+ handle.result = value
1558
+ return
1559
+ finally:
1560
+ if not out.terminal:
1561
+ self._cancel_outgoing(p, out, "consumer stopped")
1562
+ p.outgoing.pop(out.id, None)
1563
+
1564
+ def _cancel_outgoing(self, p: Peer, out: _Outgoing, reason: str) -> None:
1565
+ if out.terminal:
1566
+ return
1567
+ out.terminal = True
1568
+ if p.alive:
1569
+ self._enqueue(p, "cancel", out.id, {"reason": reason})
1570
+
1571
+ def _fail_outgoing(self, out: _Outgoing, err: RpcError) -> None:
1572
+ if out.terminal and out.future.done():
1573
+ return
1574
+ out.terminal = True
1575
+ if not out.future.done():
1576
+ out.future.set_exception(err)
1577
+ if out.queue is not None:
1578
+ out.queue.put_nowait(("error", err))
1579
+
1580
+ def _on_terminal(self, peer: Peer, msg: dict[str, Any]) -> None:
1581
+ out = peer.outgoing.get(msg["id"])
1582
+ if out is None or out.terminal:
1583
+ return # late or duplicate terminal: first one wins
1584
+ out.terminal = True
1585
+ if msg["kind"] == "result":
1586
+ if not out.future.done():
1587
+ out.future.set_result(msg["value"])
1588
+ if out.queue is not None:
1589
+ out.queue.put_nowait(("result", msg["value"]))
1590
+ else:
1591
+ e = msg["error"]
1592
+ err = RpcError(e["code"], e["message"], e.get("details"))
1593
+ if not out.future.done():
1594
+ out.future.set_exception(err)
1595
+ if out.queue is not None:
1596
+ out.queue.put_nowait(("error", err))
1597
+
1598
+ def _on_chunk(self, peer: Peer, msg: dict[str, Any]) -> None:
1599
+ out = peer.outgoing.get(msg["id"])
1600
+ if out is None or out.terminal:
1601
+ return
1602
+ if not out.stream or msg["seq"] != out.seq:
1603
+ self._fail_outgoing(out, RpcError("PROTOCOL_ERROR", "chunk sequence violated"))
1604
+ self._enqueue(peer, "cancel", out.id, {"reason": "protocol error"})
1605
+ return
1606
+ out.seq += 1
1607
+ assert out.queue is not None
1608
+ if out.queue.qsize() >= self.limits.max_credit:
1609
+ self._fail_outgoing(out, RpcError("STREAM_OVERFLOW", "peer ignored credit"))
1610
+ self._enqueue(peer, "cancel", out.id, {"reason": "overflow"})
1611
+ return
1612
+ out.queue.put_nowait(("chunk", msg["value"]))
1613
+
1614
+ def _on_progress(self, peer: Peer, msg: dict[str, Any]) -> None:
1615
+ out = peer.outgoing.get(msg["id"])
1616
+ # Progress is advisory and coalesced: a gap (a lost or skipped update)
1617
+ # is tolerated; only stale or duplicate sequence numbers are ignored.
1618
+ if out is None or out.terminal or msg["seq"] < out.progress_seq:
1619
+ return
1620
+ out.progress_seq = msg["seq"] + 1
1621
+ if out.on_progress is not None:
1622
+ try:
1623
+ out.on_progress(msg["value"])
1624
+ except Exception:
1625
+ log.exception("progress callback failed")