curlpro 0.19.0__py3-none-win_arm64.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 (356) hide show
  1. curlpro/__init__.py +149 -0
  2. curlpro/_completions.py +182 -0
  3. curlpro/_ffi.py +353 -0
  4. curlpro/_headers.py +245 -0
  5. curlpro/_kwargs.py +94 -0
  6. curlpro/aio.py +680 -0
  7. curlpro/audit.py +506 -0
  8. curlpro/browser/__init__.py +17 -0
  9. curlpro/browser/_ws.py +106 -0
  10. curlpro/browser/chrome.py +795 -0
  11. curlpro/browser/forward.py +178 -0
  12. curlpro/browser/handoff.py +151 -0
  13. curlpro/challenge.py +197 -0
  14. curlpro/cookies.py +381 -0
  15. curlpro/encoding.py +121 -0
  16. curlpro/errors.py +172 -0
  17. curlpro/expect.py +221 -0
  18. curlpro/fingerprint.py +291 -0
  19. curlpro/headers.py +106 -0
  20. curlpro/identity.py +158 -0
  21. curlpro/lib/curlpro.dll +0 -0
  22. curlpro/lib/curlpro.h +162 -0
  23. curlpro/page.py +278 -0
  24. curlpro/persona.py +288 -0
  25. curlpro/profiles/chrome-100-linux.json +85 -0
  26. curlpro/profiles/chrome-100-macos.json +85 -0
  27. curlpro/profiles/chrome-100-windows.json +110 -0
  28. curlpro/profiles/chrome-101-linux.json +85 -0
  29. curlpro/profiles/chrome-101-macos.json +85 -0
  30. curlpro/profiles/chrome-101-windows.json +110 -0
  31. curlpro/profiles/chrome-104-linux.json +85 -0
  32. curlpro/profiles/chrome-104-macos.json +85 -0
  33. curlpro/profiles/chrome-104-windows.json +110 -0
  34. curlpro/profiles/chrome-106-linux.json +85 -0
  35. curlpro/profiles/chrome-106-macos.json +85 -0
  36. curlpro/profiles/chrome-106-windows.json +85 -0
  37. curlpro/profiles/chrome-107-linux.json +85 -0
  38. curlpro/profiles/chrome-107-macos.json +85 -0
  39. curlpro/profiles/chrome-107-windows.json +114 -0
  40. curlpro/profiles/chrome-108-linux.json +85 -0
  41. curlpro/profiles/chrome-108-macos.json +85 -0
  42. curlpro/profiles/chrome-108-windows.json +85 -0
  43. curlpro/profiles/chrome-109-linux.json +85 -0
  44. curlpro/profiles/chrome-109-macos.json +85 -0
  45. curlpro/profiles/chrome-109-windows.json +85 -0
  46. curlpro/profiles/chrome-110-linux.json +85 -0
  47. curlpro/profiles/chrome-110-macos.json +85 -0
  48. curlpro/profiles/chrome-110-windows.json +113 -0
  49. curlpro/profiles/chrome-114-linux.json +85 -0
  50. curlpro/profiles/chrome-114-macos.json +85 -0
  51. curlpro/profiles/chrome-114-windows.json +85 -0
  52. curlpro/profiles/chrome-116-linux.json +85 -0
  53. curlpro/profiles/chrome-116-macos.json +85 -0
  54. curlpro/profiles/chrome-116-windows.json +117 -0
  55. curlpro/profiles/chrome-117-linux.json +85 -0
  56. curlpro/profiles/chrome-117-macos.json +85 -0
  57. curlpro/profiles/chrome-117-windows.json +85 -0
  58. curlpro/profiles/chrome-118-linux.json +393 -0
  59. curlpro/profiles/chrome-118-macos.json +85 -0
  60. curlpro/profiles/chrome-118-windows.json +85 -0
  61. curlpro/profiles/chrome-119-linux.json +396 -0
  62. curlpro/profiles/chrome-119-macos.json +396 -0
  63. curlpro/profiles/chrome-119-windows.json +85 -0
  64. curlpro/profiles/chrome-120-linux.json +393 -0
  65. curlpro/profiles/chrome-120-macos.json +396 -0
  66. curlpro/profiles/chrome-120-windows.json +85 -0
  67. curlpro/profiles/chrome-123-linux.json +85 -0
  68. curlpro/profiles/chrome-123-macos.json +393 -0
  69. curlpro/profiles/chrome-123-windows.json +85 -0
  70. curlpro/profiles/chrome-124-linux.json +89 -0
  71. curlpro/profiles/chrome-124-macos.json +399 -0
  72. curlpro/profiles/chrome-124-windows.json +89 -0
  73. curlpro/profiles/chrome-126-linux.json +89 -0
  74. curlpro/profiles/chrome-126-macos.json +89 -0
  75. curlpro/profiles/chrome-126-windows.json +89 -0
  76. curlpro/profiles/chrome-127-linux.json +89 -0
  77. curlpro/profiles/chrome-127-macos.json +89 -0
  78. curlpro/profiles/chrome-127-windows.json +89 -0
  79. curlpro/profiles/chrome-128-linux.json +89 -0
  80. curlpro/profiles/chrome-128-macos.json +89 -0
  81. curlpro/profiles/chrome-128-windows.json +89 -0
  82. curlpro/profiles/chrome-129-linux.json +89 -0
  83. curlpro/profiles/chrome-129-macos.json +89 -0
  84. curlpro/profiles/chrome-129-windows.json +89 -0
  85. curlpro/profiles/chrome-130-linux.json +89 -0
  86. curlpro/profiles/chrome-130-macos.json +89 -0
  87. curlpro/profiles/chrome-130-windows.json +89 -0
  88. curlpro/profiles/chrome-131-android.json +82 -0
  89. curlpro/profiles/chrome-131-linux.json +89 -0
  90. curlpro/profiles/chrome-131-macos.json +399 -0
  91. curlpro/profiles/chrome-131-windows.json +89 -0
  92. curlpro/profiles/chrome-132-linux.json +89 -0
  93. curlpro/profiles/chrome-132-macos.json +89 -0
  94. curlpro/profiles/chrome-132-windows.json +89 -0
  95. curlpro/profiles/chrome-133-linux.json +89 -0
  96. curlpro/profiles/chrome-133-macos.json +399 -0
  97. curlpro/profiles/chrome-133-windows.json +89 -0
  98. curlpro/profiles/chrome-134-linux.json +89 -0
  99. curlpro/profiles/chrome-134-macos.json +89 -0
  100. curlpro/profiles/chrome-134-windows.json +89 -0
  101. curlpro/profiles/chrome-135-linux.json +89 -0
  102. curlpro/profiles/chrome-135-macos.json +89 -0
  103. curlpro/profiles/chrome-135-windows.json +89 -0
  104. curlpro/profiles/chrome-136-linux.json +89 -0
  105. curlpro/profiles/chrome-136-macos.json +82 -0
  106. curlpro/profiles/chrome-136-windows.json +89 -0
  107. curlpro/profiles/chrome-137-linux.json +89 -0
  108. curlpro/profiles/chrome-137-macos.json +89 -0
  109. curlpro/profiles/chrome-137-windows.json +89 -0
  110. curlpro/profiles/chrome-138-linux.json +89 -0
  111. curlpro/profiles/chrome-138-macos.json +89 -0
  112. curlpro/profiles/chrome-138-windows.json +89 -0
  113. curlpro/profiles/chrome-139-linux.json +89 -0
  114. curlpro/profiles/chrome-139-macos.json +89 -0
  115. curlpro/profiles/chrome-139-windows.json +89 -0
  116. curlpro/profiles/chrome-140-linux.json +89 -0
  117. curlpro/profiles/chrome-140-macos.json +89 -0
  118. curlpro/profiles/chrome-140-windows.json +89 -0
  119. curlpro/profiles/chrome-141-linux.json +89 -0
  120. curlpro/profiles/chrome-141-macos.json +89 -0
  121. curlpro/profiles/chrome-141-windows.json +89 -0
  122. curlpro/profiles/chrome-142-linux.json +89 -0
  123. curlpro/profiles/chrome-142-macos.json +82 -0
  124. curlpro/profiles/chrome-142-windows.json +89 -0
  125. curlpro/profiles/chrome-143-linux.json +89 -0
  126. curlpro/profiles/chrome-143-macos.json +89 -0
  127. curlpro/profiles/chrome-143-windows.json +89 -0
  128. curlpro/profiles/chrome-144-linux.json +89 -0
  129. curlpro/profiles/chrome-144-macos.json +89 -0
  130. curlpro/profiles/chrome-144-windows.json +89 -0
  131. curlpro/profiles/chrome-145-linux.json +89 -0
  132. curlpro/profiles/chrome-145-macos.json +89 -0
  133. curlpro/profiles/chrome-145-windows.json +89 -0
  134. curlpro/profiles/chrome-146-linux.json +89 -0
  135. curlpro/profiles/chrome-146-macos.json +89 -0
  136. curlpro/profiles/chrome-146-windows.json +89 -0
  137. curlpro/profiles/chrome-147-linux.json +89 -0
  138. curlpro/profiles/chrome-147-macos.json +89 -0
  139. curlpro/profiles/chrome-147-windows.json +89 -0
  140. curlpro/profiles/chrome-148-linux.json +89 -0
  141. curlpro/profiles/chrome-148-macos.json +89 -0
  142. curlpro/profiles/chrome-148-windows.json +89 -0
  143. curlpro/profiles/chrome-149-linux.json +89 -0
  144. curlpro/profiles/chrome-149-macos.json +89 -0
  145. curlpro/profiles/chrome-149-windows.json +89 -0
  146. curlpro/profiles/chrome-150-linux.json +89 -0
  147. curlpro/profiles/chrome-150-macos.json +402 -0
  148. curlpro/profiles/chrome-150-windows.json +89 -0
  149. curlpro/profiles/chrome-151-linux.json +388 -0
  150. curlpro/profiles/chrome-151-macos.json +1523 -0
  151. curlpro/profiles/chrome-151-windows.json +1050 -0
  152. curlpro/profiles/chrome-152-android.json +572 -0
  153. curlpro/profiles/chrome-152-linux.json +388 -0
  154. curlpro/profiles/chrome-152-macos.json +1523 -0
  155. curlpro/profiles/chrome-152-windows.json +848 -0
  156. curlpro/profiles/chrome-153-linux.json +424 -0
  157. curlpro/profiles/chrome-153-macos.json +1940 -0
  158. curlpro/profiles/chrome-153-windows.json +1372 -0
  159. curlpro/profiles/chrome-154-linux.json +463 -0
  160. curlpro/profiles/chrome-154-macos.json +2114 -0
  161. curlpro/profiles/chrome-154-windows.json +1061 -0
  162. curlpro/profiles/chrome-155-linux.json +431 -0
  163. curlpro/profiles/chrome-155-macos.json +2082 -0
  164. curlpro/profiles/chrome-155-windows.json +1425 -0
  165. curlpro/profiles/chrome-156-linux.json +399 -0
  166. curlpro/profiles/chrome-156-macos.json +1542 -0
  167. curlpro/profiles/chrome-156-windows.json +862 -0
  168. curlpro/profiles/chrome-157-linux.json +351 -0
  169. curlpro/profiles/chrome-157-macos.json +732 -0
  170. curlpro/profiles/chrome-157-windows.json +489 -0
  171. curlpro/profiles/chrome-98-windows.json +404 -0
  172. curlpro/profiles/chrome-99-android.json +110 -0
  173. curlpro/profiles/chrome-99-windows.json +110 -0
  174. curlpro/profiles/edge-101-macos.json +85 -0
  175. curlpro/profiles/edge-101-windows.json +110 -0
  176. curlpro/profiles/edge-118-linux.json +393 -0
  177. curlpro/profiles/edge-119-linux.json +393 -0
  178. curlpro/profiles/edge-120-linux.json +396 -0
  179. curlpro/profiles/edge-122-macos.json +85 -0
  180. curlpro/profiles/edge-122-windows.json +85 -0
  181. curlpro/profiles/edge-127-macos.json +89 -0
  182. curlpro/profiles/edge-127-windows.json +89 -0
  183. curlpro/profiles/edge-131-macos.json +89 -0
  184. curlpro/profiles/edge-131-windows.json +89 -0
  185. curlpro/profiles/edge-134-macos.json +89 -0
  186. curlpro/profiles/edge-134-windows.json +89 -0
  187. curlpro/profiles/edge-135-macos.json +89 -0
  188. curlpro/profiles/edge-135-windows.json +89 -0
  189. curlpro/profiles/edge-136-macos.json +89 -0
  190. curlpro/profiles/edge-136-windows.json +89 -0
  191. curlpro/profiles/edge-137-macos.json +89 -0
  192. curlpro/profiles/edge-137-windows.json +89 -0
  193. curlpro/profiles/edge-138-macos.json +89 -0
  194. curlpro/profiles/edge-138-windows.json +89 -0
  195. curlpro/profiles/edge-139-macos.json +89 -0
  196. curlpro/profiles/edge-139-windows.json +89 -0
  197. curlpro/profiles/edge-140-macos.json +89 -0
  198. curlpro/profiles/edge-140-windows.json +89 -0
  199. curlpro/profiles/edge-141-macos.json +89 -0
  200. curlpro/profiles/edge-141-windows.json +89 -0
  201. curlpro/profiles/edge-142-macos.json +89 -0
  202. curlpro/profiles/edge-142-windows.json +89 -0
  203. curlpro/profiles/edge-143-macos.json +89 -0
  204. curlpro/profiles/edge-143-windows.json +89 -0
  205. curlpro/profiles/edge-144-macos.json +89 -0
  206. curlpro/profiles/edge-144-windows.json +89 -0
  207. curlpro/profiles/edge-145-macos.json +89 -0
  208. curlpro/profiles/edge-145-windows.json +89 -0
  209. curlpro/profiles/edge-146-macos.json +89 -0
  210. curlpro/profiles/edge-146-windows.json +89 -0
  211. curlpro/profiles/edge-147-macos.json +89 -0
  212. curlpro/profiles/edge-147-windows.json +89 -0
  213. curlpro/profiles/edge-148-macos.json +89 -0
  214. curlpro/profiles/edge-148-windows.json +89 -0
  215. curlpro/profiles/edge-153-windows.json +99 -0
  216. curlpro/profiles/edge-154-windows.json +106 -0
  217. curlpro/profiles/edge-156-windows.json +106 -0
  218. curlpro/profiles/edge-98-windows.json +110 -0
  219. curlpro/profiles/edge-99-windows.json +110 -0
  220. curlpro/profiles/firefox-133-linux.json +93 -0
  221. curlpro/profiles/firefox-133-macos.json +401 -0
  222. curlpro/profiles/firefox-133-windows.json +81 -0
  223. curlpro/profiles/firefox-135-linux.json +93 -0
  224. curlpro/profiles/firefox-135-macos.json +404 -0
  225. curlpro/profiles/firefox-135-windows.json +81 -0
  226. curlpro/profiles/firefox-136-linux.json +93 -0
  227. curlpro/profiles/firefox-136-macos.json +81 -0
  228. curlpro/profiles/firefox-136-windows.json +81 -0
  229. curlpro/profiles/firefox-139-linux.json +93 -0
  230. curlpro/profiles/firefox-139-macos.json +81 -0
  231. curlpro/profiles/firefox-139-windows.json +81 -0
  232. curlpro/profiles/firefox-142-linux.json +93 -0
  233. curlpro/profiles/firefox-142-macos.json +81 -0
  234. curlpro/profiles/firefox-142-windows.json +81 -0
  235. curlpro/profiles/firefox-143-linux.json +93 -0
  236. curlpro/profiles/firefox-143-macos.json +81 -0
  237. curlpro/profiles/firefox-143-windows.json +81 -0
  238. curlpro/profiles/firefox-144-linux.json +93 -0
  239. curlpro/profiles/firefox-144-macos.json +74 -0
  240. curlpro/profiles/firefox-144-windows.json +81 -0
  241. curlpro/profiles/firefox-145-linux.json +93 -0
  242. curlpro/profiles/firefox-145-macos.json +81 -0
  243. curlpro/profiles/firefox-145-windows.json +81 -0
  244. curlpro/profiles/firefox-146-linux.json +93 -0
  245. curlpro/profiles/firefox-146-macos.json +81 -0
  246. curlpro/profiles/firefox-146-windows.json +81 -0
  247. curlpro/profiles/firefox-147-linux.json +93 -0
  248. curlpro/profiles/firefox-147-macos.json +81 -0
  249. curlpro/profiles/firefox-147-windows.json +81 -0
  250. curlpro/profiles/firefox-148-linux.json +93 -0
  251. curlpro/profiles/firefox-148-macos.json +81 -0
  252. curlpro/profiles/firefox-148-windows.json +81 -0
  253. curlpro/profiles/firefox-149-linux.json +93 -0
  254. curlpro/profiles/firefox-149-macos.json +81 -0
  255. curlpro/profiles/firefox-149-windows.json +81 -0
  256. curlpro/profiles/firefox-150-linux.json +93 -0
  257. curlpro/profiles/firefox-150-macos.json +81 -0
  258. curlpro/profiles/firefox-150-windows.json +81 -0
  259. curlpro/profiles/firefox-151-linux.json +113 -0
  260. curlpro/profiles/firefox-151-macos.json +101 -0
  261. curlpro/profiles/firefox-151-windows.json +101 -0
  262. curlpro/profiles/firefox-155-windows.json +297 -0
  263. curlpro/profiles/firefox-156-windows.json +443 -0
  264. curlpro/profiles/firefox-157-windows.json +31 -0
  265. curlpro/profiles/firefox-158-windows.json +441 -0
  266. curlpro/profiles/firefox-159-windows.json +31 -0
  267. curlpro/profiles/okhttp-5.5-conscrypt.json +56 -0
  268. curlpro/profiles/okhttp-5.5-jvm.json +62 -0
  269. curlpro/profiles/opera-116-macos.json +89 -0
  270. curlpro/profiles/opera-116-windows.json +89 -0
  271. curlpro/profiles/opera-117-macos.json +89 -0
  272. curlpro/profiles/opera-117-windows.json +89 -0
  273. curlpro/profiles/opera-118-macos.json +89 -0
  274. curlpro/profiles/opera-118-windows.json +89 -0
  275. curlpro/profiles/opera-119-macos.json +89 -0
  276. curlpro/profiles/opera-119-windows.json +89 -0
  277. curlpro/profiles/opera-120-macos.json +89 -0
  278. curlpro/profiles/opera-120-windows.json +89 -0
  279. curlpro/profiles/opera-121-macos.json +89 -0
  280. curlpro/profiles/opera-121-windows.json +89 -0
  281. curlpro/profiles/opera-122-macos.json +89 -0
  282. curlpro/profiles/opera-122-windows.json +89 -0
  283. curlpro/profiles/opera-123-macos.json +89 -0
  284. curlpro/profiles/opera-123-windows.json +89 -0
  285. curlpro/profiles/opera-124-macos.json +89 -0
  286. curlpro/profiles/opera-124-windows.json +89 -0
  287. curlpro/profiles/opera-125-macos.json +89 -0
  288. curlpro/profiles/opera-125-windows.json +89 -0
  289. curlpro/profiles/opera-126-macos.json +89 -0
  290. curlpro/profiles/opera-126-windows.json +89 -0
  291. curlpro/profiles/opera-127-macos.json +89 -0
  292. curlpro/profiles/opera-127-windows.json +89 -0
  293. curlpro/profiles/opera-128-macos.json +89 -0
  294. curlpro/profiles/opera-128-windows.json +89 -0
  295. curlpro/profiles/opera-129-macos.json +89 -0
  296. curlpro/profiles/opera-129-windows.json +89 -0
  297. curlpro/profiles/opera-130-macos.json +89 -0
  298. curlpro/profiles/opera-130-windows.json +89 -0
  299. curlpro/profiles/opera-131-macos.json +89 -0
  300. curlpro/profiles/opera-131-windows.json +89 -0
  301. curlpro/profiles/opera-136-macos.json +94 -0
  302. curlpro/profiles/opera-136-windows.json +94 -0
  303. curlpro/profiles/opera-139-macos.json +106 -0
  304. curlpro/profiles/opera-139-windows.json +155 -0
  305. curlpro/profiles/safari-15.3-macos.json +260 -0
  306. curlpro/profiles/safari-15.5-macos.json +260 -0
  307. curlpro/profiles/safari-15.6.1-macos.json +135 -0
  308. curlpro/profiles/safari-16-macos.json +135 -0
  309. curlpro/profiles/safari-16.5-ios.json +135 -0
  310. curlpro/profiles/safari-16.5-macos.json +135 -0
  311. curlpro/profiles/safari-17-ios.json +140 -0
  312. curlpro/profiles/safari-17-macos.json +140 -0
  313. curlpro/profiles/safari-17.2.1-macos.json +123 -0
  314. curlpro/profiles/safari-17.4.1-ios.json +123 -0
  315. curlpro/profiles/safari-17.4.1-macos.json +135 -0
  316. curlpro/profiles/safari-17.5-macos.json +123 -0
  317. curlpro/profiles/safari-17.6-macos.json +123 -0
  318. curlpro/profiles/safari-18-ipados.json +132 -0
  319. curlpro/profiles/safari-18.0-ios.json +341 -0
  320. curlpro/profiles/safari-18.0-macos.json +125 -0
  321. curlpro/profiles/safari-18.1.1-ios.json +132 -0
  322. curlpro/profiles/safari-18.2-macos.json +132 -0
  323. curlpro/profiles/safari-18.3-macos.json +132 -0
  324. curlpro/profiles/safari-18.3.1-macos.json +132 -0
  325. curlpro/profiles/safari-18.4-ios.json +241 -0
  326. curlpro/profiles/safari-18.4-macos.json +153 -0
  327. curlpro/profiles/safari-18.5-macos.json +132 -0
  328. curlpro/profiles/safari-26-ios.json +378 -0
  329. curlpro/profiles/safari-26-ipados.json +132 -0
  330. curlpro/profiles/safari-26.0-macos.json +288 -0
  331. curlpro/profiles/safari-26.0.1-macos.json +285 -0
  332. curlpro/profiles/safari-26.1-macos.json +132 -0
  333. curlpro/profiles/safari-26.2-ios.json +132 -0
  334. curlpro/profiles/safari-26.2-ipados.json +132 -0
  335. curlpro/profiles/safari-26.2-macos.json +132 -0
  336. curlpro/profiles/safari-26.3-macos.json +132 -0
  337. curlpro/profiles/safari-26.4-macos.json +132 -0
  338. curlpro/profiles/safari-27-ios.json +131 -0
  339. curlpro/profiles/safari-27-macos.json +130 -0
  340. curlpro/profiles/tor-14-macos.json +386 -0
  341. curlpro/profiles/yandex-26.8-android.json +562 -0
  342. curlpro/profiles.py +346 -0
  343. curlpro/proxies.py +85 -0
  344. curlpro/py.typed +0 -0
  345. curlpro/requests.py +449 -0
  346. curlpro/session.py +1978 -0
  347. curlpro/solvers.py +293 -0
  348. curlpro/stream.py +170 -0
  349. curlpro/timeouts.py +45 -0
  350. curlpro/websocket.py +143 -0
  351. curlpro-0.19.0.dist-info/METADATA +207 -0
  352. curlpro-0.19.0.dist-info/RECORD +356 -0
  353. curlpro-0.19.0.dist-info/WHEEL +5 -0
  354. curlpro-0.19.0.dist-info/licenses/LICENSE +202 -0
  355. curlpro-0.19.0.dist-info/licenses/NOTICE +38 -0
  356. curlpro-0.19.0.dist-info/top_level.txt +1 -0
curlpro/__init__.py ADDED
@@ -0,0 +1,149 @@
1
+ """curlpro — an HTTP client with a browser's network fingerprint.
2
+
3
+ import curlpro
4
+
5
+ curlpro.load_profiles("profiles")
6
+ r = curlpro.get("https://example.com", impersonate="chrome-151-windows")
7
+ print(r.status, r.text[:200])
8
+
9
+ A profile can also be added at runtime, without waiting for a library
10
+ release::
11
+
12
+ curlpro.register_profile(json.load(open("chrome-152-windows.json")))
13
+
14
+ The library reproduces the network layer: the TLS ClientHello, HTTP/2 frames,
15
+ header order and case. The JavaScript fingerprint (canvas, WebGL, navigator)
16
+ belongs to the browser and is not covered here.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from . import errors
22
+ from .errors import (
23
+ ChallengeError,
24
+ ConfigurationError,
25
+ CORSError,
26
+ CurlProError,
27
+ HTTPError,
28
+ PermanentError,
29
+ ProfileCapabilityError,
30
+ ProxyAuthError,
31
+ ProxyError,
32
+ Timeout,
33
+ WebSocketClosed,
34
+ )
35
+ from ._headers import Headers
36
+ from ._kwargs import RequestKwargs
37
+ from .expect import Expect, ExpectationFailed
38
+ from .challenge import Challenge
39
+ from .identity import Identity
40
+ from . import solvers
41
+ from .solvers import BrowserSolver, Solution, SolveRequest
42
+ from .fingerprint import Fingerprint
43
+ from .audit import Finding, audit
44
+ from .persona import Persona, load_all
45
+ from .aio import AsyncSession, AsyncStreamResponse, AsyncWebSocket
46
+ from .cookies import Cookie, Cookies
47
+ from .session import (
48
+ DEFAULT_MAX_RESPONSE_SIZE,
49
+ CacheInfo,
50
+ Preflight,
51
+ Redirect,
52
+ Response,
53
+ Session,
54
+ delete,
55
+ get,
56
+ head,
57
+ options,
58
+ patch,
59
+ post,
60
+ put,
61
+ request,
62
+ )
63
+ from .profiles import (
64
+ Profile,
65
+ capabilities,
66
+ ensure_loaded,
67
+ get_profile,
68
+ library_version,
69
+ list_profiles,
70
+ load_profile_bundle,
71
+ load_profiles,
72
+ register_profile,
73
+ update_profiles,
74
+ )
75
+ from .page import Page, PageResource
76
+ from .stream import StreamResponse
77
+ from .websocket import WebSocket
78
+
79
+ __all__ = [
80
+ "AsyncSession",
81
+ "AsyncStreamResponse",
82
+ "AsyncWebSocket",
83
+ "BrowserSolver",
84
+ "CacheInfo",
85
+ "Challenge",
86
+ "ChallengeError",
87
+ "Cookie",
88
+ "Cookies",
89
+ "ConfigurationError",
90
+ "CORSError",
91
+ "CurlProError",
92
+ "DEFAULT_MAX_RESPONSE_SIZE",
93
+ "Expect",
94
+ "Finding",
95
+ "ExpectationFailed",
96
+ "Fingerprint",
97
+ "Page",
98
+ "PageResource",
99
+ "Persona",
100
+ "PermanentError",
101
+ "Preflight",
102
+ "ProfileCapabilityError",
103
+ "ProxyAuthError",
104
+ "ProxyError",
105
+ "Solution",
106
+ "SolveRequest",
107
+ "HTTPError",
108
+ "Identity",
109
+ "Headers",
110
+ "Redirect",
111
+ "RequestKwargs",
112
+ "Timeout",
113
+ "Profile",
114
+ "Response",
115
+ "Session",
116
+ "StreamResponse",
117
+ "WebSocket",
118
+ "WebSocketClosed",
119
+ "audit",
120
+ "errors",
121
+ "capabilities",
122
+ "delete",
123
+ "ensure_loaded",
124
+ "get",
125
+ "get_profile",
126
+ "head",
127
+ "library_version",
128
+ "list_profiles",
129
+ "load_all",
130
+ "load_profile_bundle",
131
+ "load_profiles",
132
+ "options",
133
+ "patch",
134
+ "post",
135
+ "put",
136
+ "register_profile",
137
+ "request",
138
+ "update_profiles",
139
+ "solvers",
140
+ ]
141
+
142
+ __version__ = "0.19.0"
143
+
144
+ try: # an installed distribution is the authority; a source checkout has none
145
+ from importlib.metadata import version as _dist_version
146
+
147
+ __version__ = _dist_version("curlpro")
148
+ except Exception: # pragma: no cover - not installed, keep the literal above
149
+ pass
@@ -0,0 +1,182 @@
1
+ """Collector of finished native calls.
2
+
3
+ An async request goes into a goroutine, and Python learns that it finished
4
+ from here. There is exactly one thread per process, no matter how many calls
5
+ are in flight: it waits inside the native part, where ctypes releases the
6
+ GIL, so the event loop keeps running.
7
+
8
+ The result itself is picked up by the event loop — that call is quick, just a
9
+ memory copy. Reaching into a loop from another thread is only allowed through
10
+ call_soon_threadsafe, and that is how the future is woken.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import threading
17
+ import time
18
+ from typing import Any
19
+
20
+ from ._ffi import _call, _lib, call_framed_out
21
+
22
+ # How long a single wait inside the native part lasts. Waking up four times a
23
+ # second while idle costs nothing, and the thread exits almost immediately
24
+ # once nobody uses it any more.
25
+ _WAIT_MS = 250
26
+
27
+
28
+ class Completions:
29
+ """The single per-process collector of results."""
30
+
31
+ def __init__(self) -> None:
32
+ self._lock = threading.Lock()
33
+ self._waiters: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Future]] = {}
34
+ # Results that arrived before their waiter: the work can finish
35
+ # between the start call and register — routine for a stream read,
36
+ # which takes microseconds.
37
+ self._ready: dict[int, tuple[Any, bytes]] = {}
38
+ self._thread: threading.Thread | None = None
39
+ self._stop = False
40
+
41
+ def register(self, request_id: int, future: asyncio.Future) -> None:
42
+ loop = asyncio.get_running_loop()
43
+ with self._lock:
44
+ done = self._ready.pop(request_id, None)
45
+ if done is not None:
46
+ # Registration happens on the event loop, so the future can
47
+ # be completed right here, without call_soon_threadsafe.
48
+ future.set_result(done)
49
+ return
50
+ self._waiters[request_id] = (loop, future)
51
+ if self._thread is None or not self._thread.is_alive():
52
+ self._stop = False
53
+ self._thread = threading.Thread(
54
+ target=self._reap, name="curlpro-completions", daemon=True
55
+ )
56
+ self._thread.start()
57
+
58
+ def forget(self, request_id: int) -> None:
59
+ """Drops the wait: the call was cancelled and nobody needs its result."""
60
+ with self._lock:
61
+ self._waiters.pop(request_id, None)
62
+ self._ready.pop(request_id, None)
63
+
64
+ def _reap(self) -> None:
65
+ # Results that could not be handed to their loop yet: a failure in
66
+ # call_soon_threadsafe leaves the result in the native registry, and
67
+ # the native queue does not announce it twice.
68
+ undelivered: list[tuple[asyncio.AbstractEventLoop, asyncio.Future, int]] = []
69
+ while True:
70
+ with self._lock:
71
+ if self._stop or not (self._waiters or self._ready or undelivered):
72
+ self._thread = None
73
+ return
74
+ # This thread is the only one that wakes the waiters: if it died,
75
+ # every request already registered would wait for ever — the
76
+ # next register restarts it, but there may be no next one. So no
77
+ # exception ends it. On free-threaded 3.14 every thread commits
78
+ # some 30 MB (measured: 128 plain threads, 3.8 GB against 42 MB
79
+ # with the GIL), and a machine near its commit limit raised
80
+ # MemoryError here and hung a test of 128 requests.
81
+ try:
82
+ while undelivered:
83
+ loop, future, rid = undelivered[0]
84
+ self._deliver(loop, future, rid)
85
+ undelivered.pop(0)
86
+ self._once(undelivered)
87
+ except Exception: # noqa: BLE001 — see above
88
+ time.sleep(0.05)
89
+
90
+ def _deliver(self, loop: asyncio.AbstractEventLoop, future: asyncio.Future, rid: int) -> None:
91
+ try:
92
+ loop.call_soon_threadsafe(_settle, future, rid)
93
+ except RuntimeError:
94
+ # The event loop is already closed — nobody to hand it to.
95
+ _take(rid)
96
+
97
+ def _once(self, undelivered: list) -> None:
98
+ """Waits for one finished call and hands it on."""
99
+ rid = int(_lib.curlpro_result_wait(_WAIT_MS))
100
+ if rid == 0:
101
+ return
102
+ with self._lock:
103
+ entry = self._waiters.pop(rid, None)
104
+ if entry is None:
105
+ # No waiter yet. Work is started and registered in two
106
+ # steps, and a fast one — reading a chunk of the body —
107
+ # can finish in between. The result is set aside for
108
+ # register to pick up.
109
+ #
110
+ # It used to be thrown away here, and such a call hung
111
+ # forever: 24 concurrent stream reads lost one of them.
112
+ #
113
+ # It is taken under the same lock: otherwise register
114
+ # slips between the check and the hand-off, and the
115
+ # waiter and its ready result never meet again.
116
+ #
117
+ # A cancelled result never lands here: cancelling removes
118
+ # the call from the native registry, leaving nothing to take.
119
+ done = _take(rid)
120
+ if done is not None:
121
+ self._ready[rid] = done
122
+ return
123
+ loop, future = entry
124
+ # Kept until handed over: if the hand-off fails, the next round
125
+ # tries it again rather than the waiter waiting for ever.
126
+ undelivered.append((loop, future, rid))
127
+ self._deliver(loop, future, rid)
128
+ undelivered.pop()
129
+
130
+
131
+ def _take(request_id: int) -> tuple[Any, bytes] | None:
132
+ try:
133
+ return call_framed_out("curlpro_result_take", request_id)
134
+ except Exception: # noqa: BLE001 — already taken, or the session is closed
135
+ return None
136
+
137
+
138
+ def _settle(future: asyncio.Future, request_id: int) -> None:
139
+ """Runs on the event loop: takes the result and wakes the waiter."""
140
+ if future.done(): # the task was cancelled while the result was on its way
141
+ _take(request_id)
142
+ return
143
+ try:
144
+ payload, content = call_framed_out("curlpro_result_take", request_id)
145
+ except BaseException as exc: # noqa: BLE001 — hand the error to the waiter
146
+ future.set_exception(exc)
147
+ return
148
+ future.set_result((payload, content))
149
+
150
+
151
+ #: One instance per process: the native ready queue is single too.
152
+ completions = Completions()
153
+
154
+
155
+ async def settle(started: dict, on_orphan: Any = None) -> tuple[Any, bytes]:
156
+ """Awaits the result of work already started: a request, a read, a receive.
157
+
158
+ Cancelling the task drops the wait and cancels the work natively. For a
159
+ request that frees the connection at once; for a stream read or a message
160
+ receive there is nothing to cancel — whatever was taken off the wire is
161
+ lost, which is why the stream or socket is closed after a cancellation.
162
+ """
163
+ request_id = int(started["request"])
164
+ loop = asyncio.get_running_loop()
165
+ future: asyncio.Future = loop.create_future()
166
+ completions.register(request_id, future)
167
+ try:
168
+ return await future
169
+ except asyncio.CancelledError:
170
+ completions.forget(request_id)
171
+ _call("curlpro_request_cancel", request_id)
172
+ # A cancellation can land after the result arrived and before the
173
+ # task resumed (asyncio.timeout, a TaskGroup sibling failing). The
174
+ # native call is gone then, and cancelling it frees nothing: an opened
175
+ # stream or socket would stay open for good. The caller's closer gets it.
176
+ if (on_orphan is not None and future.done() and not future.cancelled()
177
+ and future.exception() is None):
178
+ try:
179
+ on_orphan(future.result())
180
+ except Exception: # noqa: BLE001 — the cancellation is what propagates
181
+ pass
182
+ raise
curlpro/_ffi.py ADDED
@@ -0,0 +1,353 @@
1
+ """Loading the native library and calling it through ctypes.
2
+
3
+ Every export returns a char* holding a JSON envelope
4
+ ``{"ok":…, "error":…, "code":…, "data":…}``. That string is allocated in C and
5
+ must be released with ``curlpro_free`` or it leaks. :func:`_call` does the
6
+ releasing, which is why no pointer ever escapes this module.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ctypes
12
+ import json
13
+ import os
14
+ import platform
15
+ import threading
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ # The exceptions live in curlpro.errors; the names stay importable from here
20
+ # because code written before 0.12 imported them from this module.
21
+ from .errors import ( # noqa: F401
22
+ ConfigurationError,
23
+ CORSError,
24
+ CurlProError,
25
+ HTTPError,
26
+ PermanentError,
27
+ ProfileCapabilityError,
28
+ ProxyAuthError,
29
+ ProxyError,
30
+ Timeout,
31
+ WebSocketClosed,
32
+ )
33
+
34
+
35
+
36
+ #: Error codes that map to a class of their own. Everything else arrives as a
37
+ #: plain CurlProError with its code attached.
38
+ _BY_CODE = {
39
+ "ws_closed": WebSocketClosed,
40
+ "timeout": Timeout,
41
+ "profile_capability": ProfileCapabilityError,
42
+ "configuration": ConfigurationError,
43
+ "proxy": ProxyError,
44
+ "proxy_auth": ProxyAuthError,
45
+ "proxy_closed": ProxyError,
46
+ "cors": CORSError,
47
+ }
48
+
49
+
50
+ def _raise(envelope: dict, name: str) -> None:
51
+ code = envelope.get("code")
52
+ message = envelope.get("error") or f"{name}: unknown error"
53
+ cls = _BY_CODE.get(code, CurlProError)
54
+ if issubclass(cls, (ProxyError, CORSError)):
55
+ # The native side attaches the error's fields beside its code; the
56
+ # class takes them by name, so an unknown one is a loud mistake here
57
+ # rather than a silently missing attribute.
58
+ raise cls(message, code, **(envelope.get("details") or {}))
59
+ raise cls(message, code)
60
+
61
+
62
+ def _library_name() -> str:
63
+ system = platform.system()
64
+ if system == "Windows":
65
+ return "curlpro.dll"
66
+ if system == "Darwin":
67
+ return "libcurlpro.dylib"
68
+ return "libcurlpro.so"
69
+
70
+
71
+ def _candidates() -> list[Path]:
72
+ """Where the library is looked for, from an explicit path to a source build."""
73
+ name = _library_name()
74
+ out: list[Path] = []
75
+ if env := os.environ.get("CURLPRO_LIBRARY"):
76
+ out.append(Path(env))
77
+ here = Path(__file__).resolve().parent
78
+ out.append(here / "lib" / name) # packed into the wheel
79
+ out.append(here.parent.parent / "dist" / name) # a build from the repository
80
+ return out
81
+
82
+
83
+ def _load() -> ctypes.CDLL:
84
+ tried = []
85
+ for path in _candidates():
86
+ if path.is_file():
87
+ return ctypes.CDLL(str(path))
88
+ tried.append(str(path))
89
+ raise CurlProError(
90
+ "native library not found. Looked in:\n "
91
+ + "\n ".join(tried)
92
+ + "\nBuild it: CGO_ENABLED=1 go build -buildmode=c-shared -o dist/"
93
+ + _library_name()
94
+ + " ./lib\n"
95
+ + "(cgo needs a C compiler; without CGO_ENABLED=1 the build fails with\n"
96
+ + "\"build constraints exclude all Go files\", which names neither)\n"
97
+ + "or point CURLPRO_LIBRARY at an existing build"
98
+ )
99
+
100
+
101
+ _lib = _load()
102
+
103
+ _lib.curlpro_free.argtypes = [ctypes.c_void_p]
104
+ _lib.curlpro_free.restype = None
105
+
106
+ for _name, _args in (
107
+ ("curlpro_version", []),
108
+ ("curlpro_profiles_list", []),
109
+ ("curlpro_profile_capabilities", [ctypes.c_char_p]),
110
+ ("curlpro_profile_get", [ctypes.c_char_p]),
111
+ ("curlpro_profiles_load_dir", [ctypes.c_char_p]),
112
+ ("curlpro_profiles_load_bundle", [ctypes.c_char_p, ctypes.c_char_p]),
113
+ ("curlpro_profile_register", [ctypes.c_char_p]),
114
+ ("curlpro_session_new", [ctypes.c_char_p]),
115
+ ("curlpro_session_close", [ctypes.c_longlong]),
116
+ (
117
+ "curlpro_request",
118
+ [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int)],
119
+ ),
120
+ (
121
+ "curlpro_stream_open",
122
+ [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int)],
123
+ ),
124
+ ("curlpro_stream_close", [ctypes.c_longlong]),
125
+ ("curlpro_stream_error", [ctypes.c_longlong]),
126
+ ("curlpro_session_undo_cookies", [ctypes.c_longlong, ctypes.c_char_p]),
127
+ ("curlpro_ws_connect", [ctypes.c_longlong, ctypes.c_char_p]),
128
+ (
129
+ "curlpro_ws_send",
130
+ [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_int)],
131
+ ),
132
+ ("curlpro_ws_recv", [ctypes.c_longlong, ctypes.POINTER(ctypes.c_int)]),
133
+ ("curlpro_ws_close", [ctypes.c_longlong, ctypes.c_int, ctypes.c_char_p]),
134
+ ("curlpro_session_set_header", [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_char_p]),
135
+ ("curlpro_session_remove_header", [ctypes.c_longlong, ctypes.c_char_p]),
136
+ ("curlpro_session_suppress_header", [ctypes.c_longlong, ctypes.c_char_p]),
137
+ ("curlpro_session_set_page", [ctypes.c_longlong, ctypes.c_char_p]),
138
+ ("curlpro_session_set_top_level", [ctypes.c_longlong, ctypes.c_char_p]),
139
+ ("curlpro_session_cache_info", [ctypes.c_longlong]),
140
+ ("curlpro_session_clear_cache", [ctypes.c_longlong]),
141
+ ("curlpro_session_reset_headers", [ctypes.c_longlong]),
142
+ ("curlpro_session_headers", [ctypes.c_longlong]),
143
+ ("curlpro_session_cookies", [ctypes.c_longlong]),
144
+ ("curlpro_session_fingerprint", [ctypes.c_longlong, ctypes.c_char_p]),
145
+ ("curlpro_session_preview", [ctypes.c_longlong, ctypes.c_char_p]),
146
+ ("curlpro_session_set_cookies", [ctypes.c_longlong, ctypes.c_char_p]),
147
+ ("curlpro_session_clear_cookies", [ctypes.c_longlong]),
148
+ ("curlpro_request_start", [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int]),
149
+ ("curlpro_stream_open_start", [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int]),
150
+ ("curlpro_stream_read_start", [ctypes.c_longlong, ctypes.c_int]),
151
+ ("curlpro_ws_connect_start", [ctypes.c_longlong, ctypes.c_char_p]),
152
+ ("curlpro_ws_send_start", [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int]),
153
+ ("curlpro_ws_recv_start", [ctypes.c_longlong]),
154
+ ("curlpro_result_take", [ctypes.c_longlong, ctypes.POINTER(ctypes.c_int)]),
155
+ ("curlpro_request_cancel", [ctypes.c_longlong]),
156
+ ("curlpro_debug_counts", []),
157
+ ):
158
+ try:
159
+ _fn = getattr(_lib, _name)
160
+ except AttributeError:
161
+ raise CurlProError(
162
+ f"the library exports no {_name}: it was built from an older revision.\n"
163
+ f"Rebuild it: .\\build.ps1 (writes to dist/)"
164
+ ) from None
165
+ _fn.argtypes = _args
166
+ # c_void_p and not c_char_p: ctypes converts c_char_p into bytes and
167
+ # loses the original pointer, which curlpro_free needs.
168
+ _fn.restype = ctypes.c_void_p
169
+
170
+ # Waiting for completions and counting in-flight calls return numbers, not
171
+ # pointers. ctypes performs the blocking wait with the GIL released, and the
172
+ # async path stands on that: the collector thread waits without blocking the
173
+ # event loop.
174
+ _lib.curlpro_result_wait.argtypes = [ctypes.c_int]
175
+ _lib.curlpro_result_wait.restype = ctypes.c_longlong
176
+ _lib.curlpro_async_pending.argtypes = []
177
+ _lib.curlpro_async_pending.restype = ctypes.c_longlong
178
+
179
+ # read returns a byte count, not a pointer: the caller owns the buffer.
180
+ _lib.curlpro_stream_read.argtypes = [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int]
181
+ _lib.curlpro_stream_read.restype = ctypes.c_int
182
+
183
+
184
+ #: One read buffer per thread, reused: a fresh zeroed 64 KiB buffer per chunk
185
+ #: and a double copy out of it cost a third of the Python side's time.
186
+ _read_buffers = threading.local()
187
+
188
+
189
+ def stream_read(stream_id: int, size: int) -> bytes:
190
+ """Reads up to size bytes. An empty result means the body ended."""
191
+ buf = getattr(_read_buffers, "buf", None)
192
+ if buf is None or len(buf) < size:
193
+ buf = ctypes.create_string_buffer(size)
194
+ _read_buffers.buf = buf
195
+ n = _lib.curlpro_stream_read(stream_id, buf, size)
196
+ if n < 0:
197
+ # The read stored its error natively; raise it as what it is — a
198
+ # Timeout, a proxy failure — rather than a bare message with no code.
199
+ _call("curlpro_stream_error", stream_id)
200
+ raise CurlProError("stream read failed")
201
+ return ctypes.string_at(buf, n)
202
+
203
+
204
+ def _call(name: str, *args: Any) -> Any:
205
+ """Calls an export, unwraps the envelope and frees the C string."""
206
+ ptr = getattr(_lib, name)(*args)
207
+ if not ptr:
208
+ raise CurlProError(f"{name}: the native side returned NULL")
209
+ try:
210
+ raw = ctypes.string_at(ptr).decode("utf-8")
211
+ finally:
212
+ _lib.curlpro_free(ptr)
213
+
214
+ envelope = json.loads(raw)
215
+ if not envelope.get("ok"):
216
+ _raise(envelope, name)
217
+ return envelope.get("data")
218
+
219
+
220
+ # Minimum version of the native part: major and minor. Raise it together
221
+ # with lib/curlpro.go whenever Python starts depending on a new export or field.
222
+ REQUIRED_VERSION = (0, 28)
223
+
224
+
225
+ def _check_version() -> None:
226
+ """Checks the library version against what this Python expects.
227
+
228
+ Without the check a mismatch is silent: both sides tolerate unknown JSON
229
+ fields, so an older library quietly ignores new options — the request
230
+ goes out without them, and that looks like a logic bug rather than a
231
+ stale build.
232
+ """
233
+ raw = _call("curlpro_version").get("version", "")
234
+ try:
235
+ got = tuple(int(p) for p in raw.split(".")[:2])
236
+ except ValueError:
237
+ raise CurlProError(f"the library reported an unreadable version {raw!r}") from None
238
+
239
+ if got < REQUIRED_VERSION:
240
+ want = ".".join(str(p) for p in REQUIRED_VERSION)
241
+ raise CurlProError(
242
+ f"library version {raw} is older than the required {want}.x, "
243
+ f"so some options would be silently ignored.\n"
244
+ f"Rebuild it: .\\build.ps1 (writes to dist/)"
245
+ )
246
+
247
+
248
+ _check_version()
249
+
250
+
251
+ # Request and response bodies travel as binary, separate from the JSON.
252
+ #
253
+ # As a string inside JSON they were not merely copied one extra time:
254
+ # arbitrary bytes are not valid UTF-8, so the response was corrupted — 10,000
255
+ # random bytes came back as 18,502 after the round trip.
256
+ #
257
+ # Frame layout: [uint32 LE JSON length][JSON][raw body].
258
+ _HEADER = 4
259
+
260
+
261
+ #: The frame length is a C int on the native side.
262
+ _MAX_FRAME = 2**31 - 1
263
+
264
+
265
+ #: The request frame's encoder: compact, and fed only the fields that are set.
266
+ #: The native side reads a missing field and a null alike, and half a GET's
267
+ #: fields are None: dropping them and the spaces cut the frame from 492 bytes
268
+ #: to 176, and the time to write it here and to read it on the other side.
269
+ #: Not encode(), which a caller's json_body goes through: that one is the
270
+ #: body on the wire, and its spelling is the caller's to rely on.
271
+ _FRAME_JSON = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"))
272
+
273
+
274
+ def _frame(meta: Any, body: bytes = b"") -> bytes:
275
+ if type(meta) is dict:
276
+ meta = {k: v for k, v in meta.items() if v is not None}
277
+ js = _FRAME_JSON.encode(meta).encode("utf-8")
278
+ if _HEADER + len(js) + len(body) > _MAX_FRAME:
279
+ # ctypes would truncate the length silently and the native side would
280
+ # read a different body than the one given.
281
+ raise CurlProError(
282
+ f"a request body of {len(body)} bytes does not fit one call (the limit is 2 GiB): "
283
+ "send it with body_file=, which streams it from disk", "too_large")
284
+ return len(js).to_bytes(_HEADER, "little") + js + body
285
+
286
+
287
+ def _take(name: str, ptr: Any, n: int) -> tuple[Any, bytes]:
288
+ """Reads a native frame straight into its two parts.
289
+
290
+ Copying the whole frame and slicing the body out of it copied a large
291
+ body twice; reading by offset copies it once (a 50 MiB body: 41 ms down
292
+ to 23 ms, and on the async path that time is the event loop's)."""
293
+ if n < _HEADER:
294
+ raise CurlProError(f"{name}: frame is shorter than its header ({n} bytes)")
295
+ meta_len = int.from_bytes(ctypes.string_at(ptr, _HEADER), "little")
296
+ if _HEADER + meta_len > n:
297
+ raise CurlProError(f"{name}: JSON length ({meta_len}) runs past the frame ({n})")
298
+ address = ctypes.cast(ptr, ctypes.c_void_p).value or 0
299
+ envelope = json.loads(ctypes.string_at(address + _HEADER, meta_len))
300
+ if not envelope.get("ok"):
301
+ _raise(envelope, name)
302
+ body_len = n - _HEADER - meta_len
303
+ body = ctypes.string_at(address + _HEADER + meta_len, body_len) if body_len else b""
304
+ return envelope.get("data"), body
305
+
306
+
307
+ def _unframe(name: str, raw: bytes) -> tuple[Any, bytes]:
308
+ if len(raw) < _HEADER:
309
+ raise CurlProError(f"{name}: frame is shorter than its header ({len(raw)} bytes)")
310
+ meta_len = int.from_bytes(raw[:_HEADER], "little")
311
+ envelope = json.loads(raw[_HEADER : _HEADER + meta_len])
312
+ if not envelope.get("ok"):
313
+ _raise(envelope, name)
314
+ return envelope.get("data"), raw[_HEADER + meta_len :]
315
+
316
+
317
+ def call_framed(name: str, *args: Any, body: bytes = b"", meta: Any) -> tuple[Any, bytes]:
318
+ """Calls an export with frames and returns (data, body)."""
319
+ payload = _frame(meta, body)
320
+ out_len = ctypes.c_int(0)
321
+ ptr = getattr(_lib, name)(*args, payload, len(payload), ctypes.byref(out_len))
322
+ if not ptr:
323
+ raise CurlProError(f"{name}: the native side returned NULL")
324
+ try:
325
+ return _take(name, ptr, out_len.value)
326
+ finally:
327
+ _lib.curlpro_free(ptr)
328
+
329
+
330
+ def call_with_frame(name: str, *args: Any, body: bytes = b"", meta: Any) -> Any:
331
+ """A frame going in, a plain JSON envelope coming back.
332
+
333
+ This is how an async request starts: the body goes out as a frame, and
334
+ all that returns is the request number — there is no response yet.
335
+ """
336
+ payload = _frame(meta, body)
337
+ return _call(name, *args, payload, len(payload))
338
+
339
+
340
+ def call_framed_out(name: str, *args: Any) -> tuple[Any, bytes]:
341
+ """Like call_framed but without an input frame — for recv-style calls."""
342
+ out_len = ctypes.c_int(0)
343
+ ptr = getattr(_lib, name)(*args, ctypes.byref(out_len))
344
+ if not ptr:
345
+ raise CurlProError(f"{name}: the native side returned NULL")
346
+ try:
347
+ return _take(name, ptr, out_len.value)
348
+ finally:
349
+ _lib.curlpro_free(ptr)
350
+
351
+
352
+ def encode(obj: Any) -> bytes:
353
+ return json.dumps(obj, ensure_ascii=False).encode("utf-8")