kreuzberg 4.0.0.rc2 → 4.0.1

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 (446) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -14
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -1
  5. data/.rubocop.yml +543 -538
  6. data/Gemfile +8 -8
  7. data/Gemfile.lock +194 -6
  8. data/README.md +391 -426
  9. data/Rakefile +34 -25
  10. data/Steepfile +51 -47
  11. data/examples/async_patterns.rb +283 -341
  12. data/ext/kreuzberg_rb/extconf.rb +65 -45
  13. data/ext/kreuzberg_rb/native/.cargo/config.toml +23 -0
  14. data/ext/kreuzberg_rb/native/Cargo.lock +7619 -6535
  15. data/ext/kreuzberg_rb/native/Cargo.toml +75 -44
  16. data/ext/kreuzberg_rb/native/README.md +425 -425
  17. data/ext/kreuzberg_rb/native/build.rs +15 -15
  18. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  19. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  20. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  21. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  22. data/ext/kreuzberg_rb/native/src/lib.rs +3802 -2998
  23. data/extconf.rb +60 -28
  24. data/kreuzberg.gemspec +199 -148
  25. data/lib/kreuzberg/api_proxy.rb +126 -142
  26. data/lib/kreuzberg/cache_api.rb +67 -46
  27. data/lib/kreuzberg/cli.rb +47 -55
  28. data/lib/kreuzberg/cli_proxy.rb +117 -127
  29. data/lib/kreuzberg/config.rb +936 -691
  30. data/lib/kreuzberg/error_context.rb +136 -32
  31. data/lib/kreuzberg/errors.rb +116 -118
  32. data/lib/kreuzberg/extraction_api.rb +313 -85
  33. data/lib/kreuzberg/mcp_proxy.rb +177 -186
  34. data/lib/kreuzberg/ocr_backend_protocol.rb +40 -113
  35. data/lib/kreuzberg/post_processor_protocol.rb +15 -86
  36. data/lib/kreuzberg/result.rb +334 -216
  37. data/lib/kreuzberg/setup_lib_path.rb +99 -80
  38. data/lib/kreuzberg/types.rb +170 -0
  39. data/lib/kreuzberg/validator_protocol.rb +16 -89
  40. data/lib/kreuzberg/version.rb +5 -5
  41. data/lib/kreuzberg.rb +96 -103
  42. data/lib/libpdfium.so +0 -0
  43. data/sig/kreuzberg/internal.rbs +184 -184
  44. data/sig/kreuzberg.rbs +561 -520
  45. data/spec/binding/async_operations_spec.rb +473 -0
  46. data/spec/binding/batch_operations_spec.rb +595 -0
  47. data/spec/binding/batch_spec.rb +359 -0
  48. data/spec/binding/cache_spec.rb +227 -227
  49. data/spec/binding/cli_proxy_spec.rb +85 -85
  50. data/spec/binding/cli_spec.rb +55 -55
  51. data/spec/binding/config_result_spec.rb +377 -0
  52. data/spec/binding/config_spec.rb +419 -345
  53. data/spec/binding/config_validation_spec.rb +377 -283
  54. data/spec/binding/embeddings_spec.rb +816 -0
  55. data/spec/binding/error_handling_spec.rb +399 -213
  56. data/spec/binding/error_recovery_spec.rb +488 -0
  57. data/spec/binding/errors_spec.rb +66 -66
  58. data/spec/binding/font_config_spec.rb +220 -0
  59. data/spec/binding/images_spec.rb +738 -0
  60. data/spec/binding/keywords_extraction_spec.rb +600 -0
  61. data/spec/binding/metadata_types_spec.rb +1228 -0
  62. data/spec/binding/pages_extraction_spec.rb +471 -0
  63. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  64. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  65. data/spec/binding/plugins/validator_spec.rb +273 -274
  66. data/spec/binding/tables_spec.rb +641 -0
  67. data/spec/fixtures/config.toml +38 -39
  68. data/spec/fixtures/config.yaml +41 -41
  69. data/spec/fixtures/invalid_config.toml +3 -4
  70. data/spec/smoke/package_spec.rb +177 -178
  71. data/spec/spec_helper.rb +40 -42
  72. data/spec/unit/config/chunking_config_spec.rb +213 -0
  73. data/spec/unit/config/embedding_config_spec.rb +343 -0
  74. data/spec/unit/config/extraction_config_spec.rb +438 -0
  75. data/spec/unit/config/font_config_spec.rb +285 -0
  76. data/spec/unit/config/hierarchy_config_spec.rb +314 -0
  77. data/spec/unit/config/image_extraction_config_spec.rb +209 -0
  78. data/spec/unit/config/image_preprocessing_config_spec.rb +249 -0
  79. data/spec/unit/config/keyword_config_spec.rb +229 -0
  80. data/spec/unit/config/language_detection_config_spec.rb +258 -0
  81. data/spec/unit/config/ocr_config_spec.rb +171 -0
  82. data/spec/unit/config/page_config_spec.rb +221 -0
  83. data/spec/unit/config/pdf_config_spec.rb +267 -0
  84. data/spec/unit/config/postprocessor_config_spec.rb +290 -0
  85. data/spec/unit/config/tesseract_config_spec.rb +181 -0
  86. data/spec/unit/config/token_reduction_config_spec.rb +251 -0
  87. data/test/metadata_types_test.rb +959 -0
  88. data/vendor/Cargo.toml +61 -0
  89. data/vendor/kreuzberg/Cargo.toml +259 -204
  90. data/vendor/kreuzberg/README.md +263 -175
  91. data/vendor/kreuzberg/build.rs +782 -474
  92. data/vendor/kreuzberg/examples/bench_fixes.rs +71 -0
  93. data/vendor/kreuzberg/examples/test_pdfium_fork.rs +62 -0
  94. data/vendor/kreuzberg/src/api/error.rs +81 -81
  95. data/vendor/kreuzberg/src/api/handlers.rs +320 -199
  96. data/vendor/kreuzberg/src/api/mod.rs +94 -79
  97. data/vendor/kreuzberg/src/api/server.rs +518 -353
  98. data/vendor/kreuzberg/src/api/types.rs +206 -170
  99. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1167
  100. data/vendor/kreuzberg/src/chunking/mod.rs +2303 -677
  101. data/vendor/kreuzberg/src/chunking/processor.rs +219 -0
  102. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -95
  103. data/vendor/kreuzberg/src/core/batch_optimizations.rs +385 -0
  104. data/vendor/kreuzberg/src/core/config.rs +1914 -1032
  105. data/vendor/kreuzberg/src/core/config_validation.rs +949 -0
  106. data/vendor/kreuzberg/src/core/extractor.rs +1200 -1024
  107. data/vendor/kreuzberg/src/core/formats.rs +235 -0
  108. data/vendor/kreuzberg/src/core/io.rs +329 -329
  109. data/vendor/kreuzberg/src/core/mime.rs +605 -605
  110. data/vendor/kreuzberg/src/core/mod.rs +61 -45
  111. data/vendor/kreuzberg/src/core/pipeline.rs +1223 -984
  112. data/vendor/kreuzberg/src/core/server_config.rs +1220 -0
  113. data/vendor/kreuzberg/src/embeddings.rs +471 -432
  114. data/vendor/kreuzberg/src/error.rs +431 -431
  115. data/vendor/kreuzberg/src/extraction/archive.rs +959 -954
  116. data/vendor/kreuzberg/src/extraction/capacity.rs +263 -0
  117. data/vendor/kreuzberg/src/extraction/docx.rs +404 -40
  118. data/vendor/kreuzberg/src/extraction/email.rs +855 -854
  119. data/vendor/kreuzberg/src/extraction/excel.rs +697 -688
  120. data/vendor/kreuzberg/src/extraction/html.rs +1830 -553
  121. data/vendor/kreuzberg/src/extraction/image.rs +492 -368
  122. data/vendor/kreuzberg/src/extraction/libreoffice.rs +574 -563
  123. data/vendor/kreuzberg/src/extraction/markdown.rs +216 -213
  124. data/vendor/kreuzberg/src/extraction/mod.rs +93 -81
  125. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  126. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  127. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  128. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -130
  129. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +284 -287
  130. data/vendor/kreuzberg/src/extraction/pptx.rs +3102 -3000
  131. data/vendor/kreuzberg/src/extraction/structured.rs +491 -490
  132. data/vendor/kreuzberg/src/extraction/table.rs +329 -328
  133. data/vendor/kreuzberg/src/extraction/text.rs +277 -269
  134. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  135. data/vendor/kreuzberg/src/extractors/archive.rs +447 -446
  136. data/vendor/kreuzberg/src/extractors/bibtex.rs +470 -469
  137. data/vendor/kreuzberg/src/extractors/docbook.rs +504 -502
  138. data/vendor/kreuzberg/src/extractors/docx.rs +400 -367
  139. data/vendor/kreuzberg/src/extractors/email.rs +157 -143
  140. data/vendor/kreuzberg/src/extractors/epub.rs +696 -707
  141. data/vendor/kreuzberg/src/extractors/excel.rs +385 -343
  142. data/vendor/kreuzberg/src/extractors/fictionbook.rs +492 -491
  143. data/vendor/kreuzberg/src/extractors/html.rs +419 -393
  144. data/vendor/kreuzberg/src/extractors/image.rs +219 -198
  145. data/vendor/kreuzberg/src/extractors/jats.rs +1054 -1051
  146. data/vendor/kreuzberg/src/extractors/jupyter.rs +368 -367
  147. data/vendor/kreuzberg/src/extractors/latex.rs +653 -652
  148. data/vendor/kreuzberg/src/extractors/markdown.rs +701 -700
  149. data/vendor/kreuzberg/src/extractors/mod.rs +429 -365
  150. data/vendor/kreuzberg/src/extractors/odt.rs +628 -628
  151. data/vendor/kreuzberg/src/extractors/opml.rs +635 -634
  152. data/vendor/kreuzberg/src/extractors/orgmode.rs +529 -528
  153. data/vendor/kreuzberg/src/extractors/pdf.rs +761 -493
  154. data/vendor/kreuzberg/src/extractors/pptx.rs +279 -248
  155. data/vendor/kreuzberg/src/extractors/rst.rs +577 -576
  156. data/vendor/kreuzberg/src/extractors/rtf.rs +809 -810
  157. data/vendor/kreuzberg/src/extractors/security.rs +484 -484
  158. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -367
  159. data/vendor/kreuzberg/src/extractors/structured.rs +142 -140
  160. data/vendor/kreuzberg/src/extractors/text.rs +265 -260
  161. data/vendor/kreuzberg/src/extractors/typst.rs +651 -650
  162. data/vendor/kreuzberg/src/extractors/xml.rs +147 -135
  163. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  164. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  165. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  166. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  167. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  168. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  169. data/vendor/kreuzberg/src/keywords/processor.rs +275 -267
  170. data/vendor/kreuzberg/src/keywords/rake.rs +293 -293
  171. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  172. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  173. data/vendor/kreuzberg/src/language_detection/mod.rs +985 -942
  174. data/vendor/kreuzberg/src/language_detection/processor.rs +218 -0
  175. data/vendor/kreuzberg/src/lib.rs +114 -105
  176. data/vendor/kreuzberg/src/mcp/mod.rs +35 -32
  177. data/vendor/kreuzberg/src/mcp/server.rs +2090 -1968
  178. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  179. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  180. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  181. data/vendor/kreuzberg/src/ocr/language_registry.rs +520 -0
  182. data/vendor/kreuzberg/src/ocr/mod.rs +60 -58
  183. data/vendor/kreuzberg/src/ocr/processor.rs +858 -863
  184. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  185. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  186. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +456 -450
  187. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  188. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  189. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  190. data/vendor/kreuzberg/src/panic_context.rs +154 -154
  191. data/vendor/kreuzberg/src/pdf/bindings.rs +306 -0
  192. data/vendor/kreuzberg/src/pdf/bundled.rs +408 -0
  193. data/vendor/kreuzberg/src/pdf/error.rs +214 -122
  194. data/vendor/kreuzberg/src/pdf/fonts.rs +358 -0
  195. data/vendor/kreuzberg/src/pdf/hierarchy.rs +903 -0
  196. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  197. data/vendor/kreuzberg/src/pdf/metadata.rs +509 -346
  198. data/vendor/kreuzberg/src/pdf/mod.rs +81 -50
  199. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -369
  200. data/vendor/kreuzberg/src/pdf/table.rs +417 -393
  201. data/vendor/kreuzberg/src/pdf/text.rs +553 -158
  202. data/vendor/kreuzberg/src/plugins/extractor.rs +1042 -1013
  203. data/vendor/kreuzberg/src/plugins/mod.rs +212 -209
  204. data/vendor/kreuzberg/src/plugins/ocr.rs +637 -620
  205. data/vendor/kreuzberg/src/plugins/processor.rs +650 -642
  206. data/vendor/kreuzberg/src/plugins/registry.rs +1339 -1337
  207. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  208. data/vendor/kreuzberg/src/plugins/validator.rs +967 -956
  209. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  210. data/vendor/kreuzberg/src/text/mod.rs +27 -19
  211. data/vendor/kreuzberg/src/text/quality.rs +710 -697
  212. data/vendor/kreuzberg/src/text/quality_processor.rs +231 -0
  213. data/vendor/kreuzberg/src/text/string_utils.rs +229 -217
  214. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  215. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  216. data/vendor/kreuzberg/src/text/token_reduction/core.rs +832 -796
  217. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +923 -902
  218. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  219. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  220. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +148 -147
  221. data/vendor/kreuzberg/src/text/utf8_validation.rs +193 -0
  222. data/vendor/kreuzberg/src/types.rs +1713 -903
  223. data/vendor/kreuzberg/src/utils/mod.rs +31 -17
  224. data/vendor/kreuzberg/src/utils/pool.rs +503 -0
  225. data/vendor/kreuzberg/src/utils/pool_sizing.rs +364 -0
  226. data/vendor/kreuzberg/src/utils/quality.rs +968 -959
  227. data/vendor/kreuzberg/src/utils/string_pool.rs +761 -0
  228. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  229. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  230. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  231. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  232. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  233. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  234. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  235. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  236. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  237. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  238. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  239. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  240. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  241. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  242. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  243. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  244. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  245. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  246. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  247. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  248. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  249. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  250. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  251. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  252. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  253. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  254. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  255. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  256. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  257. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  258. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  259. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  260. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  261. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  262. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  263. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  264. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  265. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  266. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  267. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  268. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  269. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  270. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  271. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  272. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  273. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  274. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  275. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  276. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  277. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  278. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  279. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  280. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  281. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  282. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  283. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  284. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  285. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  286. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  287. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  288. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  289. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  290. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  291. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  292. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  293. data/vendor/kreuzberg/tests/api_embed.rs +360 -0
  294. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -52
  295. data/vendor/kreuzberg/tests/api_large_pdf_extraction.rs +471 -0
  296. data/vendor/kreuzberg/tests/api_large_pdf_extraction_diagnostics.rs +289 -0
  297. data/vendor/kreuzberg/tests/api_tests.rs +1472 -966
  298. data/vendor/kreuzberg/tests/archive_integration.rs +545 -543
  299. data/vendor/kreuzberg/tests/batch_orchestration.rs +587 -556
  300. data/vendor/kreuzberg/tests/batch_pooling_benchmark.rs +154 -0
  301. data/vendor/kreuzberg/tests/batch_processing.rs +328 -316
  302. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -421
  303. data/vendor/kreuzberg/tests/concurrency_stress.rs +541 -525
  304. data/vendor/kreuzberg/tests/config_features.rs +612 -598
  305. data/vendor/kreuzberg/tests/config_integration_test.rs +753 -0
  306. data/vendor/kreuzberg/tests/config_loading_tests.rs +416 -415
  307. data/vendor/kreuzberg/tests/core_integration.rs +519 -510
  308. data/vendor/kreuzberg/tests/csv_integration.rs +414 -414
  309. data/vendor/kreuzberg/tests/data/hierarchy_ground_truth.json +294 -0
  310. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +500 -498
  311. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -122
  312. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -370
  313. data/vendor/kreuzberg/tests/email_integration.rs +327 -325
  314. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -275
  315. data/vendor/kreuzberg/tests/error_handling.rs +402 -393
  316. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -228
  317. data/vendor/kreuzberg/tests/format_integration.rs +165 -159
  318. data/vendor/kreuzberg/tests/helpers/mod.rs +202 -142
  319. data/vendor/kreuzberg/tests/html_table_test.rs +551 -551
  320. data/vendor/kreuzberg/tests/image_integration.rs +255 -253
  321. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -139
  322. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -639
  323. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -704
  324. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  325. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  326. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -496
  327. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -490
  328. data/vendor/kreuzberg/tests/mime_detection.rs +429 -428
  329. data/vendor/kreuzberg/tests/ocr_configuration.rs +514 -510
  330. data/vendor/kreuzberg/tests/ocr_errors.rs +698 -676
  331. data/vendor/kreuzberg/tests/ocr_language_registry.rs +191 -0
  332. data/vendor/kreuzberg/tests/ocr_quality.rs +629 -627
  333. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  334. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +674 -695
  335. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -616
  336. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -822
  337. data/vendor/kreuzberg/tests/page_markers.rs +297 -0
  338. data/vendor/kreuzberg/tests/pdf_hierarchy_detection.rs +301 -0
  339. data/vendor/kreuzberg/tests/pdf_hierarchy_quality.rs +589 -0
  340. data/vendor/kreuzberg/tests/pdf_integration.rs +45 -43
  341. data/vendor/kreuzberg/tests/pdf_ocr_triggering.rs +301 -0
  342. data/vendor/kreuzberg/tests/pdf_text_merging.rs +475 -0
  343. data/vendor/kreuzberg/tests/pdfium_linking.rs +340 -0
  344. data/vendor/kreuzberg/tests/pipeline_integration.rs +1446 -1411
  345. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +776 -771
  346. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +577 -560
  347. data/vendor/kreuzberg/tests/plugin_system.rs +927 -921
  348. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  349. data/vendor/kreuzberg/tests/registry_integration_tests.rs +587 -586
  350. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +694 -692
  351. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +775 -776
  352. data/vendor/kreuzberg/tests/security_validation.rs +416 -415
  353. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  354. data/vendor/kreuzberg/tests/test_fastembed.rs +631 -609
  355. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1260 -1259
  356. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +648 -647
  357. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  358. data/vendor/kreuzberg-ffi/Cargo.toml +67 -0
  359. data/vendor/kreuzberg-ffi/README.md +851 -0
  360. data/vendor/kreuzberg-ffi/benches/result_view_benchmark.rs +227 -0
  361. data/vendor/kreuzberg-ffi/build.rs +168 -0
  362. data/vendor/kreuzberg-ffi/cbindgen.toml +37 -0
  363. data/vendor/kreuzberg-ffi/kreuzberg-ffi.pc.in +12 -0
  364. data/vendor/kreuzberg-ffi/kreuzberg.h +3012 -0
  365. data/vendor/kreuzberg-ffi/src/batch_streaming.rs +588 -0
  366. data/vendor/kreuzberg-ffi/src/config.rs +1341 -0
  367. data/vendor/kreuzberg-ffi/src/error.rs +901 -0
  368. data/vendor/kreuzberg-ffi/src/extraction.rs +555 -0
  369. data/vendor/kreuzberg-ffi/src/helpers.rs +879 -0
  370. data/vendor/kreuzberg-ffi/src/lib.rs +977 -0
  371. data/vendor/kreuzberg-ffi/src/memory.rs +493 -0
  372. data/vendor/kreuzberg-ffi/src/mime.rs +329 -0
  373. data/vendor/kreuzberg-ffi/src/panic_shield.rs +265 -0
  374. data/vendor/kreuzberg-ffi/src/plugins/document_extractor.rs +442 -0
  375. data/vendor/kreuzberg-ffi/src/plugins/mod.rs +14 -0
  376. data/vendor/kreuzberg-ffi/src/plugins/ocr_backend.rs +628 -0
  377. data/vendor/kreuzberg-ffi/src/plugins/post_processor.rs +438 -0
  378. data/vendor/kreuzberg-ffi/src/plugins/validator.rs +329 -0
  379. data/vendor/kreuzberg-ffi/src/result.rs +510 -0
  380. data/vendor/kreuzberg-ffi/src/result_pool.rs +639 -0
  381. data/vendor/kreuzberg-ffi/src/result_view.rs +773 -0
  382. data/vendor/kreuzberg-ffi/src/string_intern.rs +568 -0
  383. data/vendor/kreuzberg-ffi/src/types.rs +363 -0
  384. data/vendor/kreuzberg-ffi/src/util.rs +210 -0
  385. data/vendor/kreuzberg-ffi/src/validation.rs +848 -0
  386. data/vendor/kreuzberg-ffi/tests.disabled/README.md +48 -0
  387. data/vendor/kreuzberg-ffi/tests.disabled/config_loading_tests.rs +299 -0
  388. data/vendor/kreuzberg-ffi/tests.disabled/config_tests.rs +346 -0
  389. data/vendor/kreuzberg-ffi/tests.disabled/extractor_tests.rs +232 -0
  390. data/vendor/kreuzberg-ffi/tests.disabled/plugin_registration_tests.rs +470 -0
  391. data/vendor/kreuzberg-tesseract/.commitlintrc.json +13 -0
  392. data/vendor/kreuzberg-tesseract/.crate-ignore +2 -0
  393. data/vendor/kreuzberg-tesseract/Cargo.lock +2933 -0
  394. data/vendor/kreuzberg-tesseract/Cargo.toml +57 -0
  395. data/vendor/{rb-sys/LICENSE-MIT → kreuzberg-tesseract/LICENSE} +22 -21
  396. data/vendor/kreuzberg-tesseract/README.md +399 -0
  397. data/vendor/kreuzberg-tesseract/build.rs +1127 -0
  398. data/vendor/kreuzberg-tesseract/patches/README.md +71 -0
  399. data/vendor/kreuzberg-tesseract/patches/tesseract.diff +199 -0
  400. data/vendor/kreuzberg-tesseract/src/api.rs +1371 -0
  401. data/vendor/kreuzberg-tesseract/src/choice_iterator.rs +77 -0
  402. data/vendor/kreuzberg-tesseract/src/enums.rs +297 -0
  403. data/vendor/kreuzberg-tesseract/src/error.rs +81 -0
  404. data/vendor/kreuzberg-tesseract/src/lib.rs +145 -0
  405. data/vendor/kreuzberg-tesseract/src/monitor.rs +57 -0
  406. data/vendor/kreuzberg-tesseract/src/mutable_iterator.rs +197 -0
  407. data/vendor/kreuzberg-tesseract/src/page_iterator.rs +253 -0
  408. data/vendor/kreuzberg-tesseract/src/result_iterator.rs +286 -0
  409. data/vendor/kreuzberg-tesseract/src/result_renderer.rs +183 -0
  410. data/vendor/kreuzberg-tesseract/tests/integration_test.rs +211 -0
  411. metadata +196 -45
  412. data/vendor/kreuzberg/benches/otel_overhead.rs +0 -48
  413. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +0 -738
  414. data/vendor/rb-sys/.cargo-ok +0 -1
  415. data/vendor/rb-sys/.cargo_vcs_info.json +0 -6
  416. data/vendor/rb-sys/Cargo.lock +0 -393
  417. data/vendor/rb-sys/Cargo.toml +0 -70
  418. data/vendor/rb-sys/Cargo.toml.orig +0 -57
  419. data/vendor/rb-sys/LICENSE-APACHE +0 -190
  420. data/vendor/rb-sys/bin/release.sh +0 -21
  421. data/vendor/rb-sys/build/features.rs +0 -108
  422. data/vendor/rb-sys/build/main.rs +0 -246
  423. data/vendor/rb-sys/build/stable_api_config.rs +0 -153
  424. data/vendor/rb-sys/build/version.rs +0 -48
  425. data/vendor/rb-sys/readme.md +0 -36
  426. data/vendor/rb-sys/src/bindings.rs +0 -21
  427. data/vendor/rb-sys/src/hidden.rs +0 -11
  428. data/vendor/rb-sys/src/lib.rs +0 -34
  429. data/vendor/rb-sys/src/macros.rs +0 -371
  430. data/vendor/rb-sys/src/memory.rs +0 -53
  431. data/vendor/rb-sys/src/ruby_abi_version.rs +0 -38
  432. data/vendor/rb-sys/src/special_consts.rs +0 -31
  433. data/vendor/rb-sys/src/stable_api/compiled.c +0 -179
  434. data/vendor/rb-sys/src/stable_api/compiled.rs +0 -257
  435. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +0 -316
  436. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +0 -316
  437. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +0 -324
  438. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +0 -317
  439. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +0 -315
  440. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +0 -326
  441. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +0 -327
  442. data/vendor/rb-sys/src/stable_api.rs +0 -261
  443. data/vendor/rb-sys/src/symbol.rs +0 -31
  444. data/vendor/rb-sys/src/tracking_allocator.rs +0 -332
  445. data/vendor/rb-sys/src/utils.rs +0 -89
  446. data/vendor/rb-sys/src/value_type.rs +0 -7
@@ -1,1024 +1,1200 @@
1
- //! Main extraction entry points.
2
- //!
3
- //! This module provides the primary API for extracting content from files and byte arrays.
4
- //! It orchestrates the entire extraction pipeline: cache checking, MIME detection,
5
- //! extractor selection, extraction, post-processing, and cache storage.
6
- //!
7
- //! # Functions
8
- //!
9
- //! - [`extract_file`] - Extract content from a file path
10
- //! - [`extract_bytes`] - Extract content from a byte array
11
- //! - [`batch_extract_file`] - Extract content from multiple files concurrently
12
- //! - [`batch_extract_bytes`] - Extract content from multiple byte arrays concurrently
13
-
14
- use crate::core::config::ExtractionConfig;
15
- use crate::core::mime::{LEGACY_POWERPOINT_MIME_TYPE, LEGACY_WORD_MIME_TYPE};
16
- #[cfg(feature = "office")]
17
- use crate::extraction::libreoffice::{convert_doc_to_docx, convert_ppt_to_pptx};
18
- use crate::plugins::DocumentExtractor;
19
- use crate::types::ExtractionResult;
20
- #[cfg(feature = "office")]
21
- use crate::types::LibreOfficeConversionResult;
22
- use crate::{KreuzbergError, Result};
23
- use once_cell::sync::Lazy;
24
- #[cfg(feature = "office")]
25
- use serde_json::json;
26
- use std::path::Path;
27
- use std::sync::Arc;
28
-
29
- /// Record error information in the current OpenTelemetry span.
30
- ///
31
- /// This function records error details in the current span when the `otel` feature is enabled.
32
- /// It marks the span with `otel.status_code=ERROR` and adds error type and message fields.
33
- ///
34
- /// # Arguments
35
- ///
36
- /// * `error` - The error to record in the span
37
- ///
38
- /// # Example
39
- ///
40
- /// ```rust,ignore
41
- /// let result = extract_file("doc.pdf", None, &config).await;
42
- /// #[cfg(feature = "otel")]
43
- /// if let Err(ref e) = result {
44
- /// record_error(e);
45
- /// }
46
- /// result
47
- /// ```
48
- #[cfg(feature = "otel")]
49
- fn record_error(error: &KreuzbergError) {
50
- let span = tracing::Span::current();
51
- span.record("otel.status_code", "ERROR");
52
- span.record("error.type", format!("{:?}", error));
53
- span.record("error.message", error.to_string());
54
- }
55
-
56
- /// Sanitize a file path to return only the filename.
57
- ///
58
- /// This function extracts the filename from a path to avoid recording
59
- /// potentially sensitive full file paths in telemetry data.
60
- ///
61
- /// # Arguments
62
- ///
63
- /// * `path` - The path to sanitize
64
- ///
65
- /// # Returns
66
- ///
67
- /// The filename as a string, or "unknown" if extraction fails
68
- ///
69
- /// # Security
70
- ///
71
- /// This prevents PII (personally identifiable information) from appearing in
72
- /// traces by only recording filenames instead of full paths.
73
- ///
74
- /// # Example
75
- ///
76
- /// ```rust,ignore
77
- /// let path = Path::new("/home/user/documents/secret.pdf");
78
- /// assert_eq!(sanitize_path(path), "secret.pdf");
79
- /// ```
80
- #[cfg(feature = "otel")]
81
- fn sanitize_path(path: &Path) -> String {
82
- path.file_name()
83
- .and_then(|n| n.to_str())
84
- .unwrap_or("unknown")
85
- .to_string()
86
- }
87
-
88
- /// Global Tokio runtime for synchronous operations.
89
- ///
90
- /// This runtime is lazily initialized on first use and shared across all sync wrappers.
91
- /// Using a global runtime instead of creating one per call provides 100x+ performance improvement.
92
- ///
93
- /// # Safety
94
- ///
95
- /// The `.expect()` here is justified because:
96
- /// 1. Runtime creation can only fail due to system resource exhaustion (OOM, thread limit)
97
- /// 2. If runtime creation fails, the process is already in a critical state
98
- /// 3. This is a one-time initialization - if it fails, nothing will work
99
- /// 4. Better to fail fast than return errors from every sync operation
100
- static GLOBAL_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
101
- tokio::runtime::Builder::new_multi_thread()
102
- .enable_all()
103
- .build()
104
- .expect("Failed to create global Tokio runtime - system may be out of resources")
105
- });
106
-
107
- /// Get an extractor from the registry.
108
- ///
109
- /// This function acquires the registry read lock and retrieves the appropriate
110
- /// extractor for the given MIME type.
111
- ///
112
- /// # Performance
113
- ///
114
- /// RwLock read + HashMap lookup is ~100ns, fast enough without caching.
115
- /// Removed thread-local cache to avoid Tokio work-stealing scheduler issues.
116
- fn get_extractor(mime_type: &str) -> Result<Arc<dyn DocumentExtractor>> {
117
- let registry = crate::plugins::registry::get_document_extractor_registry();
118
- let registry_read = registry
119
- .read()
120
- .map_err(|e| KreuzbergError::Other(format!("Document extractor registry lock poisoned: {}", e)))?;
121
- registry_read.get(mime_type)
122
- }
123
-
124
- /// Extract content from a file.
125
- ///
126
- /// This is the main entry point for file-based extraction. It performs the following steps:
127
- /// 1. Check cache for existing result (if caching enabled)
128
- /// 2. Detect or validate MIME type
129
- /// 3. Select appropriate extractor from registry
130
- /// 4. Extract content
131
- /// 5. Run post-processing pipeline
132
- /// 6. Store result in cache (if caching enabled)
133
- ///
134
- /// # Arguments
135
- ///
136
- /// * `path` - Path to the file to extract
137
- /// * `mime_type` - Optional MIME type override. If None, will be auto-detected
138
- /// * `config` - Extraction configuration
139
- ///
140
- /// # Returns
141
- ///
142
- /// An `ExtractionResult` containing the extracted content and metadata.
143
- ///
144
- /// # Errors
145
- ///
146
- /// Returns `KreuzbergError::Validation` if the file doesn't exist or path is invalid.
147
- /// Returns `KreuzbergError::UnsupportedFormat` if MIME type is not supported.
148
- /// Returns `KreuzbergError::Io` for file I/O errors (these always bubble up).
149
- ///
150
- /// # Example
151
- ///
152
- /// ```rust,no_run
153
- /// use kreuzberg::core::extractor::extract_file;
154
- /// use kreuzberg::core::config::ExtractionConfig;
155
- ///
156
- /// # async fn example() -> kreuzberg::Result<()> {
157
- /// let config = ExtractionConfig::default();
158
- /// let result = extract_file("document.pdf", None, &config).await?;
159
- /// println!("Content: {}", result.content);
160
- /// # Ok(())
161
- /// # }
162
- /// ```
163
- #[cfg_attr(feature = "otel", tracing::instrument(
164
- skip(config, path),
165
- fields(
166
- extraction.filename = tracing::field::Empty,
167
- )
168
- ))]
169
- pub async fn extract_file(
170
- path: impl AsRef<Path>,
171
- mime_type: Option<&str>,
172
- config: &ExtractionConfig,
173
- ) -> Result<ExtractionResult> {
174
- use crate::core::{io, mime};
175
-
176
- let path = path.as_ref();
177
-
178
- #[cfg(feature = "otel")]
179
- {
180
- let span = tracing::Span::current();
181
- span.record("extraction.filename", sanitize_path(path));
182
- }
183
-
184
- let result = async {
185
- io::validate_file_exists(path)?;
186
-
187
- let detected_mime = mime::detect_or_validate(Some(path), mime_type)?;
188
-
189
- match detected_mime.as_str() {
190
- #[cfg(feature = "office")]
191
- LEGACY_WORD_MIME_TYPE => {
192
- let original_bytes = tokio::fs::read(path).await?;
193
- let conversion = convert_doc_to_docx(&original_bytes).await?;
194
- let mut result =
195
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
196
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
197
- return Ok(result);
198
- }
199
- #[cfg(not(feature = "office"))]
200
- LEGACY_WORD_MIME_TYPE => {
201
- return Err(KreuzbergError::UnsupportedFormat(
202
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
203
- ));
204
- }
205
- #[cfg(feature = "office")]
206
- LEGACY_POWERPOINT_MIME_TYPE => {
207
- let original_bytes = tokio::fs::read(path).await?;
208
- let conversion = convert_ppt_to_pptx(&original_bytes).await?;
209
- let mut result =
210
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
211
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
212
- return Ok(result);
213
- }
214
- #[cfg(not(feature = "office"))]
215
- LEGACY_POWERPOINT_MIME_TYPE => {
216
- return Err(KreuzbergError::UnsupportedFormat(
217
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
218
- ));
219
- }
220
- _ => {}
221
- }
222
-
223
- extract_file_with_extractor(path, &detected_mime, config).await
224
- }
225
- .await;
226
-
227
- #[cfg(feature = "otel")]
228
- if let Err(ref e) = result {
229
- record_error(e);
230
- }
231
-
232
- result
233
- }
234
-
235
- /// Extract content from a byte array.
236
- #[cfg_attr(feature = "otel", tracing::instrument(
237
- skip(config, content),
238
- fields(
239
- extraction.mime_type = mime_type,
240
- extraction.size_bytes = content.len(),
241
- )
242
- ))]
243
- pub async fn extract_bytes(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
244
- use crate::core::mime;
245
-
246
- let result = async {
247
- let validated_mime = mime::validate_mime_type(mime_type)?;
248
-
249
- match validated_mime.as_str() {
250
- #[cfg(feature = "office")]
251
- LEGACY_WORD_MIME_TYPE => {
252
- let conversion = convert_doc_to_docx(content).await?;
253
- let mut result =
254
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
255
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
256
- return Ok(result);
257
- }
258
- #[cfg(not(feature = "office"))]
259
- LEGACY_WORD_MIME_TYPE => {
260
- return Err(KreuzbergError::UnsupportedFormat(
261
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
262
- ));
263
- }
264
- #[cfg(feature = "office")]
265
- LEGACY_POWERPOINT_MIME_TYPE => {
266
- let conversion = convert_ppt_to_pptx(content).await?;
267
- let mut result =
268
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
269
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
270
- return Ok(result);
271
- }
272
- #[cfg(not(feature = "office"))]
273
- LEGACY_POWERPOINT_MIME_TYPE => {
274
- return Err(KreuzbergError::UnsupportedFormat(
275
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
276
- ));
277
- }
278
- _ => {}
279
- }
280
-
281
- extract_bytes_with_extractor(content, &validated_mime, config).await
282
- }
283
- .await;
284
-
285
- #[cfg(feature = "otel")]
286
- if let Err(ref e) = result {
287
- record_error(e);
288
- }
289
-
290
- result
291
- }
292
-
293
- /// Extract content from multiple files concurrently.
294
- ///
295
- /// This function processes multiple files in parallel, automatically managing
296
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
297
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
298
- /// to `num_cpus * 2`.
299
- ///
300
- /// # Arguments
301
- ///
302
- /// * `paths` - Vector of file paths to extract
303
- /// * `config` - Extraction configuration
304
- ///
305
- /// # Returns
306
- ///
307
- /// A vector of `ExtractionResult` in the same order as the input paths.
308
- ///
309
- /// # Errors
310
- ///
311
- /// Individual file errors are captured in the result metadata. System errors
312
- /// (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
313
- #[cfg_attr(feature = "otel", tracing::instrument(
314
- skip(config, paths),
315
- fields(
316
- extraction.batch_size = paths.len(),
317
- )
318
- ))]
319
- #[cfg(feature = "tokio-runtime")]
320
- pub async fn batch_extract_file(
321
- paths: Vec<impl AsRef<Path>>,
322
- config: &ExtractionConfig,
323
- ) -> Result<Vec<ExtractionResult>> {
324
- use std::sync::Arc;
325
- use tokio::sync::Semaphore;
326
- use tokio::task::JoinSet;
327
-
328
- if paths.is_empty() {
329
- return Ok(vec![]);
330
- }
331
-
332
- let config = Arc::new(config.clone());
333
-
334
- let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
335
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
336
-
337
- let mut tasks = JoinSet::new();
338
-
339
- for (index, path) in paths.into_iter().enumerate() {
340
- let path_buf = path.as_ref().to_path_buf();
341
- let config_clone = Arc::clone(&config);
342
- let semaphore_clone = Arc::clone(&semaphore);
343
-
344
- tasks.spawn(async move {
345
- let _permit = semaphore_clone.acquire().await.unwrap();
346
- let result =
347
- crate::core::batch_mode::with_batch_mode(async { extract_file(&path_buf, None, &config_clone).await })
348
- .await;
349
- (index, result)
350
- });
351
- }
352
-
353
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
354
-
355
- while let Some(task_result) = tasks.join_next().await {
356
- match task_result {
357
- Ok((index, Ok(result))) => {
358
- results[index] = Some(result);
359
- }
360
- Ok((index, Err(e))) => {
361
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
362
- if matches!(e, KreuzbergError::Io(_)) {
363
- return Err(e);
364
- }
365
-
366
- use crate::types::{ErrorMetadata, Metadata};
367
- let metadata = Metadata {
368
- error: Some(ErrorMetadata {
369
- error_type: format!("{:?}", e),
370
- message: e.to_string(),
371
- }),
372
- ..Default::default()
373
- };
374
-
375
- results[index] = Some(ExtractionResult {
376
- content: format!("Error: {}", e),
377
- mime_type: "text/plain".to_string(),
378
- metadata,
379
- tables: vec![],
380
- detected_languages: None,
381
- chunks: None,
382
- images: None,
383
- });
384
- }
385
- Err(join_err) => {
386
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
387
- }
388
- }
389
- }
390
-
391
- #[allow(clippy::unwrap_used)]
392
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
393
- }
394
-
395
- /// Extract content from multiple byte arrays concurrently.
396
- ///
397
- /// This function processes multiple byte arrays in parallel, automatically managing
398
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
399
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
400
- /// to `num_cpus * 2`.
401
- ///
402
- /// # Arguments
403
- ///
404
- /// * `contents` - Vector of (bytes, mime_type) tuples
405
- /// * `config` - Extraction configuration
406
- ///
407
- /// # Returns
408
- ///
409
- /// A vector of `ExtractionResult` in the same order as the input.
410
- #[cfg_attr(feature = "otel", tracing::instrument(
411
- skip(config, contents),
412
- fields(
413
- extraction.batch_size = contents.len(),
414
- )
415
- ))]
416
- #[cfg(feature = "tokio-runtime")]
417
- pub async fn batch_extract_bytes(
418
- contents: Vec<(&[u8], &str)>,
419
- config: &ExtractionConfig,
420
- ) -> Result<Vec<ExtractionResult>> {
421
- use std::sync::Arc;
422
- use tokio::sync::Semaphore;
423
- use tokio::task::JoinSet;
424
-
425
- if contents.is_empty() {
426
- return Ok(vec![]);
427
- }
428
-
429
- let batch_config = config.clone();
430
- let config = Arc::new(batch_config);
431
-
432
- let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
433
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
434
-
435
- let owned_contents: Vec<(Vec<u8>, String)> = contents
436
- .into_iter()
437
- .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
438
- .collect();
439
-
440
- let mut tasks = JoinSet::new();
441
-
442
- for (index, (bytes, mime_type)) in owned_contents.into_iter().enumerate() {
443
- let config_clone = Arc::clone(&config);
444
- let semaphore_clone = Arc::clone(&semaphore);
445
-
446
- tasks.spawn(async move {
447
- let _permit = semaphore_clone.acquire().await.unwrap();
448
- let result = crate::core::batch_mode::with_batch_mode(async {
449
- extract_bytes(&bytes, &mime_type, &config_clone).await
450
- })
451
- .await;
452
- (index, result)
453
- });
454
- }
455
-
456
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
457
-
458
- while let Some(task_result) = tasks.join_next().await {
459
- match task_result {
460
- Ok((index, Ok(result))) => {
461
- results[index] = Some(result);
462
- }
463
- Ok((index, Err(e))) => {
464
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
465
- if matches!(e, KreuzbergError::Io(_)) {
466
- return Err(e);
467
- }
468
-
469
- use crate::types::{ErrorMetadata, Metadata};
470
- let metadata = Metadata {
471
- error: Some(ErrorMetadata {
472
- error_type: format!("{:?}", e),
473
- message: e.to_string(),
474
- }),
475
- ..Default::default()
476
- };
477
-
478
- results[index] = Some(ExtractionResult {
479
- content: format!("Error: {}", e),
480
- mime_type: "text/plain".to_string(),
481
- metadata,
482
- tables: vec![],
483
- detected_languages: None,
484
- chunks: None,
485
- images: None,
486
- });
487
- }
488
- Err(join_err) => {
489
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
490
- }
491
- }
492
- }
493
-
494
- #[allow(clippy::unwrap_used)]
495
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
496
- }
497
-
498
- /// Synchronous wrapper for `extract_file`.
499
- ///
500
- /// This is a convenience function that blocks the current thread until extraction completes.
501
- /// For async code, use `extract_file` directly.
502
- ///
503
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
504
- /// a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
505
- pub fn extract_file_sync(
506
- path: impl AsRef<Path>,
507
- mime_type: Option<&str>,
508
- config: &ExtractionConfig,
509
- ) -> Result<ExtractionResult> {
510
- GLOBAL_RUNTIME.block_on(extract_file(path, mime_type, config))
511
- }
512
-
513
- /// Synchronous wrapper for `extract_bytes`.
514
- ///
515
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
516
- /// a new runtime per call.
517
- pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
518
- GLOBAL_RUNTIME.block_on(extract_bytes(content, mime_type, config))
519
- }
520
-
521
- /// Synchronous wrapper for `batch_extract_file`.
522
- ///
523
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
524
- /// a new runtime per call.
525
- pub fn batch_extract_file_sync(
526
- paths: Vec<impl AsRef<Path>>,
527
- config: &ExtractionConfig,
528
- ) -> Result<Vec<ExtractionResult>> {
529
- GLOBAL_RUNTIME.block_on(batch_extract_file(paths, config))
530
- }
531
-
532
- /// Synchronous wrapper for `batch_extract_bytes`.
533
- ///
534
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
535
- /// a new runtime per call.
536
- pub fn batch_extract_bytes_sync(
537
- contents: Vec<(&[u8], &str)>,
538
- config: &ExtractionConfig,
539
- ) -> Result<Vec<ExtractionResult>> {
540
- GLOBAL_RUNTIME.block_on(batch_extract_bytes(contents, config))
541
- }
542
-
543
- async fn extract_file_with_extractor(
544
- path: &Path,
545
- mime_type: &str,
546
- config: &ExtractionConfig,
547
- ) -> Result<ExtractionResult> {
548
- crate::extractors::ensure_initialized()?;
549
-
550
- let extractor = get_extractor(mime_type)?;
551
- let mut result = extractor.extract_file(path, mime_type, config).await?;
552
- result = crate::core::pipeline::run_pipeline(result, config).await?;
553
- Ok(result)
554
- }
555
-
556
- async fn extract_bytes_with_extractor(
557
- content: &[u8],
558
- mime_type: &str,
559
- config: &ExtractionConfig,
560
- ) -> Result<ExtractionResult> {
561
- crate::extractors::ensure_initialized()?;
562
-
563
- let extractor = get_extractor(mime_type)?;
564
- let mut result = extractor.extract_bytes(content, mime_type, config).await?;
565
- result = crate::core::pipeline::run_pipeline(result, config).await?;
566
- Ok(result)
567
- }
568
-
569
- #[cfg(feature = "office")]
570
- fn apply_libreoffice_metadata(
571
- result: &mut ExtractionResult,
572
- legacy_mime: &str,
573
- conversion: &LibreOfficeConversionResult,
574
- ) {
575
- result.mime_type = legacy_mime.to_string();
576
- result.metadata.additional.insert(
577
- "libreoffice_conversion".to_string(),
578
- json!({
579
- "converter": "libreoffice",
580
- "original_format": conversion.original_format,
581
- "target_format": conversion.target_format,
582
- "target_mime": conversion.target_mime,
583
- }),
584
- );
585
- }
586
-
587
- #[cfg(test)]
588
- mod tests {
589
- use super::*;
590
- use serial_test::serial;
591
- use std::fs::File;
592
- use std::io::Write;
593
- use tempfile::tempdir;
594
-
595
- fn assert_text_content(actual: &str, expected: &str) {
596
- assert_eq!(actual.trim_end_matches('\n'), expected);
597
- }
598
-
599
- #[tokio::test]
600
- async fn test_extract_file_basic() {
601
- let dir = tempdir().unwrap();
602
- let file_path = dir.path().join("test.txt");
603
- let mut file = File::create(&file_path).unwrap();
604
- file.write_all(b"Hello, world!").unwrap();
605
-
606
- let config = ExtractionConfig::default();
607
- let result = extract_file(&file_path, None, &config).await;
608
-
609
- assert!(result.is_ok());
610
- let result = result.unwrap();
611
- assert_text_content(&result.content, "Hello, world!");
612
- assert_eq!(result.mime_type, "text/plain");
613
- }
614
-
615
- #[tokio::test]
616
- async fn test_extract_file_with_mime_override() {
617
- let dir = tempdir().unwrap();
618
- let file_path = dir.path().join("test.dat");
619
- let mut file = File::create(&file_path).unwrap();
620
- file.write_all(b"test content").unwrap();
621
-
622
- let config = ExtractionConfig::default();
623
- let result = extract_file(&file_path, Some("text/plain"), &config).await;
624
-
625
- assert!(result.is_ok());
626
- let result = result.unwrap();
627
- assert_eq!(result.mime_type, "text/plain");
628
- }
629
-
630
- #[tokio::test]
631
- async fn test_extract_file_nonexistent() {
632
- let config = ExtractionConfig::default();
633
- let result = extract_file("/nonexistent/file.txt", None, &config).await;
634
- assert!(result.is_err());
635
- }
636
-
637
- #[tokio::test]
638
- async fn test_extract_bytes_basic() {
639
- let config = ExtractionConfig::default();
640
- let result = extract_bytes(b"test content", "text/plain", &config).await;
641
-
642
- assert!(result.is_ok());
643
- let result = result.unwrap();
644
- assert_text_content(&result.content, "test content");
645
- assert_eq!(result.mime_type, "text/plain");
646
- }
647
-
648
- #[tokio::test]
649
- async fn test_extract_bytes_invalid_mime() {
650
- let config = ExtractionConfig::default();
651
- let result = extract_bytes(b"test", "invalid/mime", &config).await;
652
- assert!(result.is_err());
653
- }
654
-
655
- #[tokio::test]
656
- async fn test_batch_extract_file() {
657
- let dir = tempdir().unwrap();
658
-
659
- let file1 = dir.path().join("test1.txt");
660
- let file2 = dir.path().join("test2.txt");
661
-
662
- File::create(&file1).unwrap().write_all(b"content 1").unwrap();
663
- File::create(&file2).unwrap().write_all(b"content 2").unwrap();
664
-
665
- let config = ExtractionConfig::default();
666
- let paths = vec![file1, file2];
667
- let results = batch_extract_file(paths, &config).await;
668
-
669
- assert!(results.is_ok());
670
- let results = results.unwrap();
671
- assert_eq!(results.len(), 2);
672
- assert_text_content(&results[0].content, "content 1");
673
- assert_text_content(&results[1].content, "content 2");
674
- }
675
-
676
- #[tokio::test]
677
- async fn test_batch_extract_file_empty() {
678
- let config = ExtractionConfig::default();
679
- let paths: Vec<std::path::PathBuf> = vec![];
680
- let results = batch_extract_file(paths, &config).await;
681
-
682
- assert!(results.is_ok());
683
- assert_eq!(results.unwrap().len(), 0);
684
- }
685
-
686
- #[tokio::test]
687
- async fn test_batch_extract_bytes() {
688
- let config = ExtractionConfig::default();
689
- let contents = vec![
690
- (b"content 1".as_slice(), "text/plain"),
691
- (b"content 2".as_slice(), "text/plain"),
692
- ];
693
- let results = batch_extract_bytes(contents, &config).await;
694
-
695
- assert!(results.is_ok());
696
- let results = results.unwrap();
697
- assert_eq!(results.len(), 2);
698
- assert_text_content(&results[0].content, "content 1");
699
- assert_text_content(&results[1].content, "content 2");
700
- }
701
-
702
- #[test]
703
- fn test_sync_wrappers() {
704
- let dir = tempdir().unwrap();
705
- let file_path = dir.path().join("test.txt");
706
- File::create(&file_path).unwrap().write_all(b"sync test").unwrap();
707
-
708
- let config = ExtractionConfig::default();
709
-
710
- let result = extract_file_sync(&file_path, None, &config);
711
- assert!(result.is_ok());
712
- let result = result.unwrap();
713
- assert_text_content(&result.content, "sync test");
714
-
715
- let result = extract_bytes_sync(b"test", "text/plain", &config);
716
- assert!(result.is_ok());
717
- }
718
-
719
- #[tokio::test]
720
- async fn test_extractor_cache() {
721
- let config = ExtractionConfig::default();
722
-
723
- let result1 = extract_bytes(b"test 1", "text/plain", &config).await;
724
- assert!(result1.is_ok());
725
- let result1 = result1.unwrap();
726
-
727
- let result2 = extract_bytes(b"test 2", "text/plain", &config).await;
728
- assert!(result2.is_ok());
729
- let result2 = result2.unwrap();
730
-
731
- assert_text_content(&result1.content, "test 1");
732
- assert_text_content(&result2.content, "test 2");
733
-
734
- let result3 = extract_bytes(b"# test 3", "text/markdown", &config).await;
735
- assert!(result3.is_ok());
736
- }
737
-
738
- #[tokio::test]
739
- async fn test_extract_file_empty() {
740
- let dir = tempdir().unwrap();
741
- let file_path = dir.path().join("empty.txt");
742
- File::create(&file_path).unwrap();
743
-
744
- let config = ExtractionConfig::default();
745
- let result = extract_file(&file_path, None, &config).await;
746
-
747
- assert!(result.is_ok());
748
- let result = result.unwrap();
749
- assert_eq!(result.content, "");
750
- }
751
-
752
- #[tokio::test]
753
- async fn test_extract_bytes_empty() {
754
- let config = ExtractionConfig::default();
755
- let result = extract_bytes(b"", "text/plain", &config).await;
756
-
757
- assert!(result.is_ok());
758
- let result = result.unwrap();
759
- assert_eq!(result.content, "");
760
- }
761
-
762
- #[tokio::test]
763
- async fn test_extract_file_whitespace_only() {
764
- let dir = tempdir().unwrap();
765
- let file_path = dir.path().join("whitespace.txt");
766
- File::create(&file_path).unwrap().write_all(b" \n\t \n ").unwrap();
767
-
768
- let config = ExtractionConfig::default();
769
- let result = extract_file(&file_path, None, &config).await;
770
-
771
- assert!(result.is_ok());
772
- }
773
-
774
- #[tokio::test]
775
- async fn test_extract_file_very_long_path() {
776
- let dir = tempdir().unwrap();
777
- let long_name = "a".repeat(200);
778
- let file_path = dir.path().join(format!("{}.txt", long_name));
779
-
780
- if let Ok(mut f) = File::create(&file_path) {
781
- f.write_all(b"content").unwrap();
782
- let config = ExtractionConfig::default();
783
- let result = extract_file(&file_path, None, &config).await;
784
- assert!(result.is_ok() || result.is_err());
785
- }
786
- }
787
-
788
- #[tokio::test]
789
- async fn test_extract_file_special_characters_in_path() {
790
- let dir = tempdir().unwrap();
791
- let file_path = dir.path().join("test with spaces & symbols!.txt");
792
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
793
-
794
- let config = ExtractionConfig::default();
795
- let result = extract_file(&file_path, None, &config).await;
796
-
797
- assert!(result.is_ok());
798
- let result = result.unwrap();
799
- assert_text_content(&result.content, "content");
800
- }
801
-
802
- #[tokio::test]
803
- async fn test_extract_file_unicode_filename() {
804
- let dir = tempdir().unwrap();
805
- let file_path = dir.path().join("测试文件名.txt");
806
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
807
-
808
- let config = ExtractionConfig::default();
809
- let result = extract_file(&file_path, None, &config).await;
810
-
811
- assert!(result.is_ok());
812
- }
813
-
814
- #[tokio::test]
815
- async fn test_extract_bytes_unsupported_mime() {
816
- let config = ExtractionConfig::default();
817
- let result = extract_bytes(b"test", "application/x-unknown-format", &config).await;
818
-
819
- assert!(result.is_err());
820
- assert!(matches!(result.unwrap_err(), KreuzbergError::UnsupportedFormat(_)));
821
- }
822
-
823
- #[tokio::test]
824
- async fn test_batch_extract_file_with_errors() {
825
- let dir = tempdir().unwrap();
826
-
827
- let valid_file = dir.path().join("valid.txt");
828
- File::create(&valid_file).unwrap().write_all(b"valid content").unwrap();
829
-
830
- let invalid_file = dir.path().join("nonexistent.txt");
831
-
832
- let config = ExtractionConfig::default();
833
- let paths = vec![valid_file, invalid_file];
834
- let results = batch_extract_file(paths, &config).await;
835
-
836
- assert!(results.is_ok());
837
- let results = results.unwrap();
838
- assert_eq!(results.len(), 2);
839
- assert_text_content(&results[0].content, "valid content");
840
- assert!(results[1].metadata.error.is_some());
841
- }
842
-
843
- #[tokio::test]
844
- async fn test_batch_extract_bytes_mixed_valid_invalid() {
845
- let config = ExtractionConfig::default();
846
- let contents = vec![
847
- (b"valid 1".as_slice(), "text/plain"),
848
- (b"invalid".as_slice(), "invalid/mime"),
849
- (b"valid 2".as_slice(), "text/plain"),
850
- ];
851
- let results = batch_extract_bytes(contents, &config).await;
852
-
853
- assert!(results.is_ok());
854
- let results = results.unwrap();
855
- assert_eq!(results.len(), 3);
856
- assert_text_content(&results[0].content, "valid 1");
857
- assert!(results[1].metadata.error.is_some());
858
- assert_text_content(&results[2].content, "valid 2");
859
- }
860
-
861
- #[tokio::test]
862
- async fn test_batch_extract_bytes_all_invalid() {
863
- let config = ExtractionConfig::default();
864
- let contents = vec![
865
- (b"test 1".as_slice(), "invalid/mime1"),
866
- (b"test 2".as_slice(), "invalid/mime2"),
867
- ];
868
- let results = batch_extract_bytes(contents, &config).await;
869
-
870
- assert!(results.is_ok());
871
- let results = results.unwrap();
872
- assert_eq!(results.len(), 2);
873
- assert!(results[0].metadata.error.is_some());
874
- assert!(results[1].metadata.error.is_some());
875
- }
876
-
877
- #[tokio::test]
878
- async fn test_extract_bytes_very_large() {
879
- let large_content = vec![b'a'; 10_000_000];
880
- let config = ExtractionConfig::default();
881
- let result = extract_bytes(&large_content, "text/plain", &config).await;
882
-
883
- assert!(result.is_ok());
884
- let result = result.unwrap();
885
- let trimmed_len = result.content.trim_end_matches('\n').len();
886
- assert_eq!(trimmed_len, 10_000_000);
887
- }
888
-
889
- #[tokio::test]
890
- async fn test_batch_extract_large_count() {
891
- let dir = tempdir().unwrap();
892
- let mut paths = Vec::new();
893
-
894
- for i in 0..100 {
895
- let file_path = dir.path().join(format!("file{}.txt", i));
896
- File::create(&file_path)
897
- .unwrap()
898
- .write_all(format!("content {}", i).as_bytes())
899
- .unwrap();
900
- paths.push(file_path);
901
- }
902
-
903
- let config = ExtractionConfig::default();
904
- let results = batch_extract_file(paths, &config).await;
905
-
906
- assert!(results.is_ok());
907
- let results = results.unwrap();
908
- assert_eq!(results.len(), 100);
909
-
910
- for (i, result) in results.iter().enumerate() {
911
- assert_text_content(&result.content, &format!("content {}", i));
912
- }
913
- }
914
-
915
- #[tokio::test]
916
- async fn test_extract_file_mime_detection_fallback() {
917
- let dir = tempdir().unwrap();
918
- let file_path = dir.path().join("testfile");
919
- File::create(&file_path)
920
- .unwrap()
921
- .write_all(b"plain text content")
922
- .unwrap();
923
-
924
- let config = ExtractionConfig::default();
925
- let result = extract_file(&file_path, None, &config).await;
926
-
927
- assert!(result.is_ok() || result.is_err());
928
- }
929
-
930
- #[tokio::test]
931
- async fn test_extract_file_wrong_mime_override() {
932
- let dir = tempdir().unwrap();
933
- let file_path = dir.path().join("test.txt");
934
- File::create(&file_path).unwrap().write_all(b"plain text").unwrap();
935
-
936
- let config = ExtractionConfig::default();
937
- let result = extract_file(&file_path, Some("application/pdf"), &config).await;
938
-
939
- assert!(result.is_err() || result.is_ok());
940
- }
941
-
942
- #[test]
943
- fn test_sync_wrapper_nonexistent_file() {
944
- let config = ExtractionConfig::default();
945
- let result = extract_file_sync("/nonexistent/path.txt", None, &config);
946
-
947
- assert!(result.is_err());
948
- assert!(matches!(result.unwrap_err(), KreuzbergError::Validation { .. }));
949
- }
950
-
951
- #[test]
952
- fn test_sync_wrapper_batch_empty() {
953
- let config = ExtractionConfig::default();
954
- let paths: Vec<std::path::PathBuf> = vec![];
955
- let results = batch_extract_file_sync(paths, &config);
956
-
957
- assert!(results.is_ok());
958
- assert_eq!(results.unwrap().len(), 0);
959
- }
960
-
961
- #[test]
962
- fn test_sync_wrapper_batch_bytes_empty() {
963
- let config = ExtractionConfig::default();
964
- let contents: Vec<(&[u8], &str)> = vec![];
965
- let results = batch_extract_bytes_sync(contents, &config);
966
-
967
- assert!(results.is_ok());
968
- assert_eq!(results.unwrap().len(), 0);
969
- }
970
-
971
- #[tokio::test]
972
- async fn test_concurrent_extractions_same_mime() {
973
- use tokio::task::JoinSet;
974
-
975
- let config = Arc::new(ExtractionConfig::default());
976
- let mut tasks = JoinSet::new();
977
-
978
- for i in 0..50 {
979
- let config_clone = Arc::clone(&config);
980
- tasks.spawn(async move {
981
- let content = format!("test content {}", i);
982
- extract_bytes(content.as_bytes(), "text/plain", &config_clone).await
983
- });
984
- }
985
-
986
- let mut success_count = 0;
987
- while let Some(task_result) = tasks.join_next().await {
988
- if let Ok(Ok(_)) = task_result {
989
- success_count += 1;
990
- }
991
- }
992
-
993
- assert_eq!(success_count, 50);
994
- }
995
-
996
- #[serial]
997
- #[tokio::test]
998
- async fn test_concurrent_extractions_different_mimes() {
999
- use tokio::task::JoinSet;
1000
-
1001
- let config = Arc::new(ExtractionConfig::default());
1002
- let mut tasks = JoinSet::new();
1003
-
1004
- let mime_types = ["text/plain", "text/markdown"];
1005
-
1006
- for i in 0..30 {
1007
- let config_clone = Arc::clone(&config);
1008
- let mime = mime_types[i % mime_types.len()];
1009
- tasks.spawn(async move {
1010
- let content = format!("test {}", i);
1011
- extract_bytes(content.as_bytes(), mime, &config_clone).await
1012
- });
1013
- }
1014
-
1015
- let mut success_count = 0;
1016
- while let Some(task_result) = tasks.join_next().await {
1017
- if let Ok(Ok(_)) = task_result {
1018
- success_count += 1;
1019
- }
1020
- }
1021
-
1022
- assert_eq!(success_count, 30);
1023
- }
1024
- }
1
+ //! Main extraction entry points.
2
+ //!
3
+ //! This module provides the primary API for extracting content from files and byte arrays.
4
+ //! It orchestrates the entire extraction pipeline: cache checking, MIME detection,
5
+ //! extractor selection, extraction, post-processing, and cache storage.
6
+ //!
7
+ //! # Functions
8
+ //!
9
+ //! - [`extract_file`] - Extract content from a file path
10
+ //! - [`extract_bytes`] - Extract content from a byte array
11
+ //! - [`batch_extract_file`] - Extract content from multiple files concurrently
12
+ //! - [`batch_extract_bytes`] - Extract content from multiple byte arrays concurrently
13
+
14
+ use crate::core::config::ExtractionConfig;
15
+ use crate::core::mime::{LEGACY_POWERPOINT_MIME_TYPE, LEGACY_WORD_MIME_TYPE};
16
+ #[cfg(feature = "office")]
17
+ use crate::extraction::libreoffice::{convert_doc_to_docx, convert_ppt_to_pptx};
18
+ use crate::plugins::DocumentExtractor;
19
+ use crate::types::ExtractionResult;
20
+ #[cfg(feature = "office")]
21
+ use crate::types::LibreOfficeConversionResult;
22
+ use crate::utils::{PoolSizeHint, estimate_pool_size, intern_mime_type};
23
+ use crate::{KreuzbergError, Result};
24
+ #[cfg(feature = "tokio-runtime")]
25
+ use once_cell::sync::Lazy;
26
+ #[cfg(feature = "office")]
27
+ use serde_json::json;
28
+ use std::path::Path;
29
+ use std::sync::Arc;
30
+
31
+ /// Record error information in the current OpenTelemetry span.
32
+ ///
33
+ /// This function records error details in the current span when the `otel` feature is enabled.
34
+ /// It marks the span with `otel.status_code=ERROR` and adds error type and message fields.
35
+ ///
36
+ /// # Arguments
37
+ ///
38
+ /// * `error` - The error to record in the span
39
+ ///
40
+ /// # Example
41
+ ///
42
+ /// ```rust,ignore
43
+ /// let result = extract_file("doc.pdf", None, &config).await;
44
+ /// #[cfg(feature = "otel")]
45
+ /// if let Err(ref e) = result {
46
+ /// record_error(e);
47
+ /// }
48
+ /// result
49
+ /// ```
50
+ #[cfg(feature = "otel")]
51
+ fn record_error(error: &KreuzbergError) {
52
+ let span = tracing::Span::current();
53
+ span.record("otel.status_code", "ERROR");
54
+ span.record("error.type", format!("{:?}", error));
55
+ span.record("error.message", error.to_string());
56
+ }
57
+
58
+ /// Sanitize a file path to return only the filename.
59
+ ///
60
+ /// This function extracts the filename from a path to avoid recording
61
+ /// potentially sensitive full file paths in telemetry data.
62
+ ///
63
+ /// # Arguments
64
+ ///
65
+ /// * `path` - The path to sanitize
66
+ ///
67
+ /// # Returns
68
+ ///
69
+ /// The filename as a string, or "unknown" if extraction fails
70
+ ///
71
+ /// # Security
72
+ ///
73
+ /// This prevents PII (personally identifiable information) from appearing in
74
+ /// traces by only recording filenames instead of full paths.
75
+ ///
76
+ /// # Example
77
+ ///
78
+ /// ```rust,ignore
79
+ /// let path = Path::new("/home/user/documents/secret.pdf");
80
+ /// assert_eq!(sanitize_path(path), "secret.pdf");
81
+ /// ```
82
+ #[cfg(feature = "otel")]
83
+ fn sanitize_path(path: &Path) -> String {
84
+ path.file_name()
85
+ .and_then(|n| n.to_str())
86
+ .unwrap_or("unknown")
87
+ .to_string()
88
+ }
89
+
90
+ /// Global Tokio runtime for synchronous operations.
91
+ ///
92
+ /// This runtime is lazily initialized on first use and shared across all sync wrappers.
93
+ /// Using a global runtime instead of creating one per call provides 100x+ performance improvement.
94
+ ///
95
+ /// # Safety
96
+ ///
97
+ /// The `.expect()` here is justified because:
98
+ /// 1. Runtime creation can only fail due to system resource exhaustion (OOM, thread limit)
99
+ /// 2. If runtime creation fails, the process is already in a critical state
100
+ /// 3. This is a one-time initialization - if it fails, nothing will work
101
+ /// 4. Better to fail fast than return errors from every sync operation
102
+ ///
103
+ /// # Availability
104
+ ///
105
+ /// This static is only available when the `tokio-runtime` feature is enabled.
106
+ /// For WASM targets, use the truly synchronous extraction functions instead.
107
+ #[cfg(feature = "tokio-runtime")]
108
+ static GLOBAL_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
109
+ tokio::runtime::Builder::new_multi_thread()
110
+ .enable_all()
111
+ .build()
112
+ .expect("Failed to create global Tokio runtime - system may be out of resources")
113
+ });
114
+
115
+ /// Get an extractor from the registry.
116
+ ///
117
+ /// This function acquires the registry read lock and retrieves the appropriate
118
+ /// extractor for the given MIME type.
119
+ ///
120
+ /// # Performance
121
+ ///
122
+ /// RwLock read + HashMap lookup is ~100ns, fast enough without caching.
123
+ /// Removed thread-local cache to avoid Tokio work-stealing scheduler issues.
124
+ fn get_extractor(mime_type: &str) -> Result<Arc<dyn DocumentExtractor>> {
125
+ let registry = crate::plugins::registry::get_document_extractor_registry();
126
+ let registry_read = registry
127
+ .read()
128
+ .map_err(|e| KreuzbergError::Other(format!("Document extractor registry lock poisoned: {}", e)))?;
129
+ registry_read.get(mime_type)
130
+ }
131
+
132
+ /// Get optimal pool sizing hint for a document.
133
+ ///
134
+ /// This function calculates recommended pool sizes based on the document's
135
+ /// file size and MIME type. The hint can be used to create appropriately
136
+ /// sized thread pools for extraction, reducing memory waste from over-allocation.
137
+ ///
138
+ /// # Arguments
139
+ ///
140
+ /// * `file_size` - The size of the file in bytes
141
+ /// * `mime_type` - The MIME type of the document
142
+ ///
143
+ /// # Returns
144
+ ///
145
+ /// A `PoolSizeHint` with recommended pool configurations
146
+ ///
147
+ /// # Example
148
+ ///
149
+ /// ```rust,ignore
150
+ /// use kreuzberg::core::extractor::get_pool_sizing_hint;
151
+ ///
152
+ /// let hint = get_pool_sizing_hint(5_000_000, "application/pdf");
153
+ /// println!("Recommended string buffers: {}", hint.string_buffer_count);
154
+ /// ```
155
+ #[inline]
156
+ pub fn get_pool_sizing_hint(file_size: u64, mime_type: &str) -> PoolSizeHint {
157
+ estimate_pool_size(file_size, mime_type)
158
+ }
159
+
160
+ /// Extract content from a file.
161
+ ///
162
+ /// This is the main entry point for file-based extraction. It performs the following steps:
163
+ /// 1. Check cache for existing result (if caching enabled)
164
+ /// 2. Detect or validate MIME type
165
+ /// 3. Select appropriate extractor from registry
166
+ /// 4. Extract content
167
+ /// 5. Run post-processing pipeline
168
+ /// 6. Store result in cache (if caching enabled)
169
+ ///
170
+ /// # Arguments
171
+ ///
172
+ /// * `path` - Path to the file to extract
173
+ /// * `mime_type` - Optional MIME type override. If None, will be auto-detected
174
+ /// * `config` - Extraction configuration
175
+ ///
176
+ /// # Returns
177
+ ///
178
+ /// An `ExtractionResult` containing the extracted content and metadata.
179
+ ///
180
+ /// # Errors
181
+ ///
182
+ /// Returns `KreuzbergError::Validation` if the file doesn't exist or path is invalid.
183
+ /// Returns `KreuzbergError::UnsupportedFormat` if MIME type is not supported.
184
+ /// Returns `KreuzbergError::Io` for file I/O errors (these always bubble up).
185
+ ///
186
+ /// # Example
187
+ ///
188
+ /// ```rust,no_run
189
+ /// use kreuzberg::core::extractor::extract_file;
190
+ /// use kreuzberg::core::config::ExtractionConfig;
191
+ ///
192
+ /// # async fn example() -> kreuzberg::Result<()> {
193
+ /// let config = ExtractionConfig::default();
194
+ /// let result = extract_file("document.pdf", None, &config).await?;
195
+ /// println!("Content: {}", result.content);
196
+ /// # Ok(())
197
+ /// # }
198
+ /// ```
199
+ #[cfg_attr(feature = "otel", tracing::instrument(
200
+ skip(config, path),
201
+ fields(
202
+ extraction.filename = tracing::field::Empty,
203
+ )
204
+ ))]
205
+ pub async fn extract_file(
206
+ path: impl AsRef<Path>,
207
+ mime_type: Option<&str>,
208
+ config: &ExtractionConfig,
209
+ ) -> Result<ExtractionResult> {
210
+ use crate::core::{io, mime};
211
+
212
+ let path = path.as_ref();
213
+
214
+ #[cfg(feature = "otel")]
215
+ {
216
+ let span = tracing::Span::current();
217
+ span.record("extraction.filename", sanitize_path(path));
218
+ }
219
+
220
+ let result = async {
221
+ io::validate_file_exists(path)?;
222
+
223
+ let detected_mime = mime::detect_or_validate(Some(path), mime_type)?;
224
+
225
+ match detected_mime.as_str() {
226
+ #[cfg(feature = "office")]
227
+ LEGACY_WORD_MIME_TYPE => {
228
+ let original_bytes = tokio::fs::read(path).await?;
229
+ let conversion = convert_doc_to_docx(&original_bytes).await?;
230
+ let mut result =
231
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
232
+ apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
233
+ return Ok(result);
234
+ }
235
+ #[cfg(not(feature = "office"))]
236
+ LEGACY_WORD_MIME_TYPE => {
237
+ return Err(KreuzbergError::UnsupportedFormat(
238
+ "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
239
+ ));
240
+ }
241
+ #[cfg(feature = "office")]
242
+ LEGACY_POWERPOINT_MIME_TYPE => {
243
+ let original_bytes = tokio::fs::read(path).await?;
244
+ let conversion = convert_ppt_to_pptx(&original_bytes).await?;
245
+ let mut result =
246
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
247
+ apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
248
+ return Ok(result);
249
+ }
250
+ #[cfg(not(feature = "office"))]
251
+ LEGACY_POWERPOINT_MIME_TYPE => {
252
+ return Err(KreuzbergError::UnsupportedFormat(
253
+ "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
254
+ ));
255
+ }
256
+ _ => {}
257
+ }
258
+
259
+ extract_file_with_extractor(path, &detected_mime, config).await
260
+ }
261
+ .await;
262
+
263
+ #[cfg(feature = "otel")]
264
+ if let Err(ref e) = result {
265
+ record_error(e);
266
+ }
267
+
268
+ result
269
+ }
270
+
271
+ /// Extract content from a byte array.
272
+ #[cfg_attr(feature = "otel", tracing::instrument(
273
+ skip(config, content),
274
+ fields(
275
+ extraction.mime_type = mime_type,
276
+ extraction.size_bytes = content.len(),
277
+ )
278
+ ))]
279
+ pub async fn extract_bytes(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
280
+ use crate::core::mime;
281
+
282
+ let result = async {
283
+ let validated_mime = mime::validate_mime_type(mime_type)?;
284
+
285
+ match validated_mime.as_str() {
286
+ #[cfg(feature = "office")]
287
+ LEGACY_WORD_MIME_TYPE => {
288
+ let conversion = convert_doc_to_docx(content).await?;
289
+ let mut result =
290
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
291
+ apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
292
+ return Ok(result);
293
+ }
294
+ #[cfg(not(feature = "office"))]
295
+ LEGACY_WORD_MIME_TYPE => {
296
+ return Err(KreuzbergError::UnsupportedFormat(
297
+ "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
298
+ ));
299
+ }
300
+ #[cfg(feature = "office")]
301
+ LEGACY_POWERPOINT_MIME_TYPE => {
302
+ let conversion = convert_ppt_to_pptx(content).await?;
303
+ let mut result =
304
+ extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
305
+ apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
306
+ return Ok(result);
307
+ }
308
+ #[cfg(not(feature = "office"))]
309
+ LEGACY_POWERPOINT_MIME_TYPE => {
310
+ return Err(KreuzbergError::UnsupportedFormat(
311
+ "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
312
+ ));
313
+ }
314
+ _ => {}
315
+ }
316
+
317
+ extract_bytes_with_extractor(content, &validated_mime, config).await
318
+ }
319
+ .await;
320
+
321
+ #[cfg(feature = "otel")]
322
+ if let Err(ref e) = result {
323
+ record_error(e);
324
+ }
325
+
326
+ result
327
+ }
328
+
329
+ /// Extract content from multiple files concurrently.
330
+ ///
331
+ /// This function processes multiple files in parallel, automatically managing
332
+ /// concurrency to prevent resource exhaustion. The concurrency limit can be
333
+ /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
334
+ /// to `num_cpus * 2`.
335
+ ///
336
+ /// # Arguments
337
+ ///
338
+ /// * `paths` - Vector of file paths to extract
339
+ /// * `config` - Extraction configuration
340
+ ///
341
+ /// # Returns
342
+ ///
343
+ /// A vector of `ExtractionResult` in the same order as the input paths.
344
+ ///
345
+ /// # Errors
346
+ ///
347
+ /// Individual file errors are captured in the result metadata. System errors
348
+ /// (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
349
+ #[cfg(feature = "tokio-runtime")]
350
+ #[cfg_attr(feature = "otel", tracing::instrument(
351
+ skip(config, paths),
352
+ fields(
353
+ extraction.batch_size = paths.len(),
354
+ )
355
+ ))]
356
+ pub async fn batch_extract_file(
357
+ paths: Vec<impl AsRef<Path>>,
358
+ config: &ExtractionConfig,
359
+ ) -> Result<Vec<ExtractionResult>> {
360
+ use std::sync::Arc;
361
+ use tokio::sync::Semaphore;
362
+ use tokio::task::JoinSet;
363
+
364
+ if paths.is_empty() {
365
+ return Ok(vec![]);
366
+ }
367
+
368
+ let config = Arc::new(config.clone());
369
+
370
+ let max_concurrent = config
371
+ .max_concurrent_extractions
372
+ .unwrap_or_else(|| (num_cpus::get() as f64 * 1.5).ceil() as usize);
373
+ let semaphore = Arc::new(Semaphore::new(max_concurrent));
374
+
375
+ let mut tasks = JoinSet::new();
376
+
377
+ for (index, path) in paths.into_iter().enumerate() {
378
+ let path_buf = path.as_ref().to_path_buf();
379
+ let config_clone = Arc::clone(&config);
380
+ let semaphore_clone = Arc::clone(&semaphore);
381
+
382
+ tasks.spawn(async move {
383
+ let _permit = semaphore_clone.acquire().await.unwrap();
384
+ let result =
385
+ crate::core::batch_mode::with_batch_mode(async { extract_file(&path_buf, None, &config_clone).await })
386
+ .await;
387
+ (index, result)
388
+ });
389
+ }
390
+
391
+ let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
392
+
393
+ while let Some(task_result) = tasks.join_next().await {
394
+ match task_result {
395
+ Ok((index, Ok(result))) => {
396
+ results[index] = Some(result);
397
+ }
398
+ Ok((index, Err(e))) => {
399
+ // All errors (including Io) should create error results
400
+ // instead of causing early return that abandons running tasks
401
+ use crate::types::{ErrorMetadata, Metadata};
402
+ let metadata = Metadata {
403
+ error: Some(ErrorMetadata {
404
+ error_type: format!("{:?}", e),
405
+ message: e.to_string(),
406
+ }),
407
+ ..Default::default()
408
+ };
409
+
410
+ results[index] = Some(ExtractionResult {
411
+ content: format!("Error: {}", e),
412
+ mime_type: "text/plain".to_string(),
413
+ metadata,
414
+ tables: vec![],
415
+ detected_languages: None,
416
+ chunks: None,
417
+ images: None,
418
+ pages: None,
419
+ });
420
+ }
421
+ Err(join_err) => {
422
+ return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
423
+ }
424
+ }
425
+ }
426
+
427
+ #[allow(clippy::unwrap_used)]
428
+ Ok(results.into_iter().map(|r| r.unwrap()).collect())
429
+ }
430
+
431
+ /// Extract content from multiple byte arrays concurrently.
432
+ ///
433
+ /// This function processes multiple byte arrays in parallel, automatically managing
434
+ /// concurrency to prevent resource exhaustion. The concurrency limit can be
435
+ /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
436
+ /// to `num_cpus * 2`.
437
+ ///
438
+ /// # Arguments
439
+ ///
440
+ /// * `contents` - Vector of (bytes, mime_type) tuples
441
+ /// * `config` - Extraction configuration
442
+ ///
443
+ /// # Returns
444
+ ///
445
+ /// A vector of `ExtractionResult` in the same order as the input.
446
+ #[cfg(feature = "tokio-runtime")]
447
+ #[cfg_attr(feature = "otel", tracing::instrument(
448
+ skip(config, contents),
449
+ fields(
450
+ extraction.batch_size = contents.len(),
451
+ )
452
+ ))]
453
+ pub async fn batch_extract_bytes(
454
+ contents: Vec<(Vec<u8>, String)>,
455
+ config: &ExtractionConfig,
456
+ ) -> Result<Vec<ExtractionResult>> {
457
+ use std::sync::Arc;
458
+ use tokio::sync::Semaphore;
459
+ use tokio::task::JoinSet;
460
+
461
+ if contents.is_empty() {
462
+ return Ok(vec![]);
463
+ }
464
+
465
+ let batch_config = config.clone();
466
+ let config = Arc::new(batch_config);
467
+
468
+ let max_concurrent = config
469
+ .max_concurrent_extractions
470
+ .unwrap_or_else(|| (num_cpus::get() as f64 * 1.5).ceil() as usize);
471
+ let semaphore = Arc::new(Semaphore::new(max_concurrent));
472
+
473
+ let mut tasks = JoinSet::new();
474
+
475
+ for (index, (bytes, mime_type)) in contents.into_iter().enumerate() {
476
+ let config_clone = Arc::clone(&config);
477
+ let semaphore_clone = Arc::clone(&semaphore);
478
+
479
+ tasks.spawn(async move {
480
+ let _permit = semaphore_clone.acquire().await.unwrap();
481
+ let result = crate::core::batch_mode::with_batch_mode(async {
482
+ extract_bytes(&bytes, &mime_type, &config_clone).await
483
+ })
484
+ .await;
485
+ (index, result)
486
+ });
487
+ }
488
+
489
+ let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
490
+
491
+ while let Some(task_result) = tasks.join_next().await {
492
+ match task_result {
493
+ Ok((index, Ok(result))) => {
494
+ results[index] = Some(result);
495
+ }
496
+ Ok((index, Err(e))) => {
497
+ // All errors (including Io) should create error results
498
+ // instead of causing early return that abandons running tasks
499
+ use crate::types::{ErrorMetadata, Metadata};
500
+ let metadata = Metadata {
501
+ error: Some(ErrorMetadata {
502
+ error_type: format!("{:?}", e),
503
+ message: e.to_string(),
504
+ }),
505
+ ..Default::default()
506
+ };
507
+
508
+ results[index] = Some(ExtractionResult {
509
+ content: format!("Error: {}", e),
510
+ mime_type: "text/plain".to_string(),
511
+ metadata,
512
+ tables: vec![],
513
+ detected_languages: None,
514
+ chunks: None,
515
+ images: None,
516
+ pages: None,
517
+ });
518
+ }
519
+ Err(join_err) => {
520
+ return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
521
+ }
522
+ }
523
+ }
524
+
525
+ #[allow(clippy::unwrap_used)]
526
+ Ok(results.into_iter().map(|r| r.unwrap()).collect())
527
+ }
528
+
529
+ /// Synchronous wrapper for `extract_file`.
530
+ ///
531
+ /// This is a convenience function that blocks the current thread until extraction completes.
532
+ /// For async code, use `extract_file` directly.
533
+ ///
534
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
535
+ /// a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
536
+ ///
537
+ /// This function is only available with the `tokio-runtime` feature. For WASM targets,
538
+ /// use a truly synchronous extraction approach instead.
539
+ #[cfg(feature = "tokio-runtime")]
540
+ pub fn extract_file_sync(
541
+ path: impl AsRef<Path>,
542
+ mime_type: Option<&str>,
543
+ config: &ExtractionConfig,
544
+ ) -> Result<ExtractionResult> {
545
+ GLOBAL_RUNTIME.block_on(extract_file(path, mime_type, config))
546
+ }
547
+
548
+ /// Synchronous wrapper for `extract_bytes`.
549
+ ///
550
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
551
+ /// a new runtime per call.
552
+ ///
553
+ /// With the `tokio-runtime` feature, this blocks the current thread using the global
554
+ /// Tokio runtime. Without it (WASM), this calls a truly synchronous implementation.
555
+ #[cfg(feature = "tokio-runtime")]
556
+ pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
557
+ GLOBAL_RUNTIME.block_on(extract_bytes(content, mime_type, config))
558
+ }
559
+
560
+ /// Synchronous wrapper for `extract_bytes` (WASM-compatible version).
561
+ ///
562
+ /// This is a truly synchronous implementation without tokio runtime dependency.
563
+ /// It calls `extract_bytes_sync_impl()` to perform the extraction.
564
+ #[cfg(not(feature = "tokio-runtime"))]
565
+ pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
566
+ extract_bytes_sync_impl(content.to_vec(), Some(mime_type.to_string()), Some(config.clone()))
567
+ }
568
+
569
+ /// Synchronous wrapper for `batch_extract_file`.
570
+ ///
571
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
572
+ /// a new runtime per call.
573
+ ///
574
+ /// This function is only available with the `tokio-runtime` feature. For WASM targets,
575
+ /// use a truly synchronous extraction approach instead.
576
+ #[cfg(feature = "tokio-runtime")]
577
+ pub fn batch_extract_file_sync(
578
+ paths: Vec<impl AsRef<Path>>,
579
+ config: &ExtractionConfig,
580
+ ) -> Result<Vec<ExtractionResult>> {
581
+ GLOBAL_RUNTIME.block_on(batch_extract_file(paths, config))
582
+ }
583
+
584
+ /// Synchronous wrapper for `batch_extract_bytes`.
585
+ ///
586
+ /// Uses the global Tokio runtime for 100x+ performance improvement over creating
587
+ /// a new runtime per call.
588
+ ///
589
+ /// With the `tokio-runtime` feature, this blocks the current thread using the global
590
+ /// Tokio runtime. Without it (WASM), this calls a truly synchronous implementation
591
+ /// that iterates through items and calls `extract_bytes_sync()`.
592
+ #[cfg(feature = "tokio-runtime")]
593
+ pub fn batch_extract_bytes_sync(
594
+ contents: Vec<(Vec<u8>, String)>,
595
+ config: &ExtractionConfig,
596
+ ) -> Result<Vec<ExtractionResult>> {
597
+ GLOBAL_RUNTIME.block_on(batch_extract_bytes(contents, config))
598
+ }
599
+
600
+ /// Synchronous wrapper for `batch_extract_bytes` (WASM-compatible version).
601
+ ///
602
+ /// This is a truly synchronous implementation that iterates through items
603
+ /// and calls `extract_bytes_sync()` for each.
604
+ #[cfg(not(feature = "tokio-runtime"))]
605
+ pub fn batch_extract_bytes_sync(
606
+ contents: Vec<(Vec<u8>, String)>,
607
+ config: &ExtractionConfig,
608
+ ) -> Result<Vec<ExtractionResult>> {
609
+ let mut results = Vec::with_capacity(contents.len());
610
+ for (content, mime_type) in contents {
611
+ let result = extract_bytes_sync(&content, &mime_type, config);
612
+ results.push(result.unwrap_or_else(|e| {
613
+ use crate::types::{ErrorMetadata, Metadata};
614
+ ExtractionResult {
615
+ content: format!("Error: {}", e),
616
+ mime_type: pool_mime_type("text/plain"),
617
+ metadata: Metadata {
618
+ error: Some(ErrorMetadata {
619
+ error_type: format!("{:?}", e),
620
+ message: e.to_string(),
621
+ }),
622
+ ..Default::default()
623
+ },
624
+ tables: vec![],
625
+ detected_languages: None,
626
+ chunks: None,
627
+ images: None,
628
+ pages: None,
629
+ }
630
+ }));
631
+ }
632
+ Ok(results)
633
+ }
634
+
635
+ /// Synchronous extraction implementation for WASM compatibility.
636
+ ///
637
+ /// This function performs extraction without requiring a tokio runtime.
638
+ /// It calls the sync extractor methods directly.
639
+ ///
640
+ /// # Arguments
641
+ ///
642
+ /// * `content` - The byte content to extract
643
+ /// * `mime_type` - Optional MIME type to validate/use
644
+ /// * `config` - Optional extraction configuration
645
+ ///
646
+ /// # Returns
647
+ ///
648
+ /// An `ExtractionResult` or a `KreuzbergError`
649
+ ///
650
+ /// # Implementation Notes
651
+ ///
652
+ /// This is called when the `tokio-runtime` feature is disabled.
653
+ /// It replicates the logic of `extract_bytes` but uses synchronous extractor methods.
654
+ #[cfg(not(feature = "tokio-runtime"))]
655
+ fn extract_bytes_sync_impl(
656
+ content: Vec<u8>,
657
+ mime_type: Option<String>,
658
+ config: Option<ExtractionConfig>,
659
+ ) -> Result<ExtractionResult> {
660
+ use crate::core::mime;
661
+
662
+ let config = config.unwrap_or_default();
663
+
664
+ let validated_mime = if let Some(mime) = mime_type {
665
+ mime::validate_mime_type(&mime)?
666
+ } else {
667
+ return Err(KreuzbergError::Validation {
668
+ message: "MIME type is required for synchronous extraction".to_string(),
669
+ source: None,
670
+ });
671
+ };
672
+
673
+ crate::extractors::ensure_initialized()?;
674
+
675
+ let extractor = get_extractor(&validated_mime)?;
676
+
677
+ let sync_extractor = extractor.as_sync_extractor().ok_or_else(|| {
678
+ KreuzbergError::UnsupportedFormat(format!(
679
+ "Extractor for '{}' does not support synchronous extraction",
680
+ validated_mime
681
+ ))
682
+ })?;
683
+
684
+ let mut result = sync_extractor.extract_sync(&content, &validated_mime, &config)?;
685
+
686
+ result = crate::core::pipeline::run_pipeline_sync(result, &config)?;
687
+
688
+ Ok(result)
689
+ }
690
+
691
+ async fn extract_file_with_extractor(
692
+ path: &Path,
693
+ mime_type: &str,
694
+ config: &ExtractionConfig,
695
+ ) -> Result<ExtractionResult> {
696
+ crate::extractors::ensure_initialized()?;
697
+
698
+ let extractor = get_extractor(mime_type)?;
699
+ let mut result = extractor.extract_file(path, mime_type, config).await?;
700
+ result = crate::core::pipeline::run_pipeline(result, config).await?;
701
+ Ok(result)
702
+ }
703
+
704
+ async fn extract_bytes_with_extractor(
705
+ content: &[u8],
706
+ mime_type: &str,
707
+ config: &ExtractionConfig,
708
+ ) -> Result<ExtractionResult> {
709
+ crate::extractors::ensure_initialized()?;
710
+
711
+ let extractor = get_extractor(mime_type)?;
712
+ let mut result = extractor.extract_bytes(content, mime_type, config).await?;
713
+ result = crate::core::pipeline::run_pipeline(result, config).await?;
714
+ Ok(result)
715
+ }
716
+
717
+ /// Convert a MIME type string to a pooled String for efficient deduplication.
718
+ ///
719
+ /// This function uses the string interning pool to reduce memory allocations
720
+ /// for repeatedly used MIME types (e.g., "application/pdf" appears thousands of times
721
+ /// in batch processing). The interned string is converted to an owned String to satisfy
722
+ /// the ExtractionResult::mime_type field type.
723
+ ///
724
+ /// # Performance
725
+ ///
726
+ /// For pre-interned MIME types (all common types), this is O(1) pointer dereference.
727
+ /// For unknown MIME types, this allocates once per unique type and caches the result.
728
+ #[allow(dead_code)]
729
+ fn pool_mime_type(mime_type: &str) -> String {
730
+ intern_mime_type(mime_type).to_string()
731
+ }
732
+
733
+ #[cfg(feature = "office")]
734
+ fn apply_libreoffice_metadata(
735
+ result: &mut ExtractionResult,
736
+ legacy_mime: &str,
737
+ conversion: &LibreOfficeConversionResult,
738
+ ) {
739
+ result.mime_type = pool_mime_type(legacy_mime);
740
+ result.metadata.additional.insert(
741
+ "libreoffice_conversion".to_string(),
742
+ json!({
743
+ "converter": "libreoffice",
744
+ "original_format": conversion.original_format,
745
+ "target_format": conversion.target_format,
746
+ "target_mime": conversion.target_mime,
747
+ }),
748
+ );
749
+ }
750
+
751
+ #[cfg(test)]
752
+ mod tests {
753
+ use super::*;
754
+ use serial_test::serial;
755
+ use std::fs::File;
756
+ use std::io::Write;
757
+ use tempfile::tempdir;
758
+
759
+ fn assert_text_content(actual: &str, expected: &str) {
760
+ assert_eq!(actual.trim_end_matches('\n'), expected);
761
+ }
762
+
763
+ #[tokio::test]
764
+ async fn test_extract_file_basic() {
765
+ let dir = tempdir().unwrap();
766
+ let file_path = dir.path().join("test.txt");
767
+ let mut file = File::create(&file_path).unwrap();
768
+ file.write_all(b"Hello, world!").unwrap();
769
+
770
+ let config = ExtractionConfig::default();
771
+ let result = extract_file(&file_path, None, &config).await;
772
+
773
+ assert!(result.is_ok());
774
+ let result = result.unwrap();
775
+ assert_text_content(&result.content, "Hello, world!");
776
+ assert_eq!(result.mime_type, "text/plain");
777
+ }
778
+
779
+ #[tokio::test]
780
+ async fn test_extract_file_with_mime_override() {
781
+ let dir = tempdir().unwrap();
782
+ let file_path = dir.path().join("test.dat");
783
+ let mut file = File::create(&file_path).unwrap();
784
+ file.write_all(b"test content").unwrap();
785
+
786
+ let config = ExtractionConfig::default();
787
+ let result = extract_file(&file_path, Some("text/plain"), &config).await;
788
+
789
+ assert!(result.is_ok());
790
+ let result = result.unwrap();
791
+ assert_eq!(result.mime_type, "text/plain");
792
+ }
793
+
794
+ #[tokio::test]
795
+ async fn test_extract_file_nonexistent() {
796
+ let config = ExtractionConfig::default();
797
+ let result = extract_file("/nonexistent/file.txt", None, &config).await;
798
+ assert!(result.is_err());
799
+ }
800
+
801
+ #[tokio::test]
802
+ async fn test_extract_bytes_basic() {
803
+ let config = ExtractionConfig::default();
804
+ let result = extract_bytes(b"test content", "text/plain", &config).await;
805
+
806
+ assert!(result.is_ok());
807
+ let result = result.unwrap();
808
+ assert_text_content(&result.content, "test content");
809
+ assert_eq!(result.mime_type, "text/plain");
810
+ }
811
+
812
+ #[tokio::test]
813
+ async fn test_extract_bytes_invalid_mime() {
814
+ let config = ExtractionConfig::default();
815
+ let result = extract_bytes(b"test", "invalid/mime", &config).await;
816
+ assert!(result.is_err());
817
+ }
818
+
819
+ #[tokio::test]
820
+ async fn test_batch_extract_file() {
821
+ let dir = tempdir().unwrap();
822
+
823
+ let file1 = dir.path().join("test1.txt");
824
+ let file2 = dir.path().join("test2.txt");
825
+
826
+ File::create(&file1).unwrap().write_all(b"content 1").unwrap();
827
+ File::create(&file2).unwrap().write_all(b"content 2").unwrap();
828
+
829
+ let config = ExtractionConfig::default();
830
+ let paths = vec![file1, file2];
831
+ let results = batch_extract_file(paths, &config).await;
832
+
833
+ assert!(results.is_ok());
834
+ let results = results.unwrap();
835
+ assert_eq!(results.len(), 2);
836
+ assert_text_content(&results[0].content, "content 1");
837
+ assert_text_content(&results[1].content, "content 2");
838
+ }
839
+
840
+ #[tokio::test]
841
+ async fn test_batch_extract_file_empty() {
842
+ let config = ExtractionConfig::default();
843
+ let paths: Vec<std::path::PathBuf> = vec![];
844
+ let results = batch_extract_file(paths, &config).await;
845
+
846
+ assert!(results.is_ok());
847
+ assert_eq!(results.unwrap().len(), 0);
848
+ }
849
+
850
+ #[tokio::test]
851
+ async fn test_batch_extract_bytes() {
852
+ let config = ExtractionConfig::default();
853
+ let contents = vec![
854
+ (b"content 1".as_slice(), "text/plain"),
855
+ (b"content 2".as_slice(), "text/plain"),
856
+ ];
857
+ let owned_contents: Vec<(Vec<u8>, String)> = contents
858
+ .into_iter()
859
+ .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
860
+ .collect();
861
+ let results = batch_extract_bytes(owned_contents, &config).await;
862
+
863
+ assert!(results.is_ok());
864
+ let results = results.unwrap();
865
+ assert_eq!(results.len(), 2);
866
+ assert_text_content(&results[0].content, "content 1");
867
+ assert_text_content(&results[1].content, "content 2");
868
+ }
869
+
870
+ #[test]
871
+ fn test_sync_wrappers() {
872
+ let dir = tempdir().unwrap();
873
+ let file_path = dir.path().join("test.txt");
874
+ File::create(&file_path).unwrap().write_all(b"sync test").unwrap();
875
+
876
+ let config = ExtractionConfig::default();
877
+
878
+ let result = extract_file_sync(&file_path, None, &config);
879
+ assert!(result.is_ok());
880
+ let result = result.unwrap();
881
+ assert_text_content(&result.content, "sync test");
882
+
883
+ let result = extract_bytes_sync(b"test", "text/plain", &config);
884
+ assert!(result.is_ok());
885
+ }
886
+
887
+ #[tokio::test]
888
+ async fn test_extractor_cache() {
889
+ let config = ExtractionConfig::default();
890
+
891
+ let result1 = extract_bytes(b"test 1", "text/plain", &config).await;
892
+ assert!(result1.is_ok());
893
+ let result1 = result1.unwrap();
894
+
895
+ let result2 = extract_bytes(b"test 2", "text/plain", &config).await;
896
+ assert!(result2.is_ok());
897
+ let result2 = result2.unwrap();
898
+
899
+ assert_text_content(&result1.content, "test 1");
900
+ assert_text_content(&result2.content, "test 2");
901
+
902
+ let result3 = extract_bytes(b"# test 3", "text/markdown", &config).await;
903
+ assert!(result3.is_ok());
904
+ }
905
+
906
+ #[tokio::test]
907
+ async fn test_extract_file_empty() {
908
+ let dir = tempdir().unwrap();
909
+ let file_path = dir.path().join("empty.txt");
910
+ File::create(&file_path).unwrap();
911
+
912
+ let config = ExtractionConfig::default();
913
+ let result = extract_file(&file_path, None, &config).await;
914
+
915
+ assert!(result.is_ok());
916
+ let result = result.unwrap();
917
+ assert_eq!(result.content, "");
918
+ }
919
+
920
+ #[tokio::test]
921
+ async fn test_extract_bytes_empty() {
922
+ let config = ExtractionConfig::default();
923
+ let result = extract_bytes(b"", "text/plain", &config).await;
924
+
925
+ assert!(result.is_ok());
926
+ let result = result.unwrap();
927
+ assert_eq!(result.content, "");
928
+ }
929
+
930
+ #[tokio::test]
931
+ async fn test_extract_file_whitespace_only() {
932
+ let dir = tempdir().unwrap();
933
+ let file_path = dir.path().join("whitespace.txt");
934
+ File::create(&file_path).unwrap().write_all(b" \n\t \n ").unwrap();
935
+
936
+ let config = ExtractionConfig::default();
937
+ let result = extract_file(&file_path, None, &config).await;
938
+
939
+ assert!(result.is_ok());
940
+ }
941
+
942
+ #[tokio::test]
943
+ async fn test_extract_file_very_long_path() {
944
+ let dir = tempdir().unwrap();
945
+ let long_name = "a".repeat(200);
946
+ let file_path = dir.path().join(format!("{}.txt", long_name));
947
+
948
+ if let Ok(mut f) = File::create(&file_path) {
949
+ f.write_all(b"content").unwrap();
950
+ let config = ExtractionConfig::default();
951
+ let result = extract_file(&file_path, None, &config).await;
952
+ assert!(result.is_ok() || result.is_err());
953
+ }
954
+ }
955
+
956
+ #[tokio::test]
957
+ async fn test_extract_file_special_characters_in_path() {
958
+ let dir = tempdir().unwrap();
959
+ let file_path = dir.path().join("test with spaces & symbols!.txt");
960
+ File::create(&file_path).unwrap().write_all(b"content").unwrap();
961
+
962
+ let config = ExtractionConfig::default();
963
+ let result = extract_file(&file_path, None, &config).await;
964
+
965
+ assert!(result.is_ok());
966
+ let result = result.unwrap();
967
+ assert_text_content(&result.content, "content");
968
+ }
969
+
970
+ #[tokio::test]
971
+ async fn test_extract_file_unicode_filename() {
972
+ let dir = tempdir().unwrap();
973
+ let file_path = dir.path().join("测试文件名.txt");
974
+ File::create(&file_path).unwrap().write_all(b"content").unwrap();
975
+
976
+ let config = ExtractionConfig::default();
977
+ let result = extract_file(&file_path, None, &config).await;
978
+
979
+ assert!(result.is_ok());
980
+ }
981
+
982
+ #[tokio::test]
983
+ async fn test_extract_bytes_unsupported_mime() {
984
+ let config = ExtractionConfig::default();
985
+ let result = extract_bytes(b"test", "application/x-unknown-format", &config).await;
986
+
987
+ assert!(result.is_err());
988
+ assert!(matches!(result.unwrap_err(), KreuzbergError::UnsupportedFormat(_)));
989
+ }
990
+
991
+ #[tokio::test]
992
+ async fn test_batch_extract_file_with_errors() {
993
+ let dir = tempdir().unwrap();
994
+
995
+ let valid_file = dir.path().join("valid.txt");
996
+ File::create(&valid_file).unwrap().write_all(b"valid content").unwrap();
997
+
998
+ let invalid_file = dir.path().join("nonexistent.txt");
999
+
1000
+ let config = ExtractionConfig::default();
1001
+ let paths = vec![valid_file, invalid_file];
1002
+ let results = batch_extract_file(paths, &config).await;
1003
+
1004
+ assert!(results.is_ok());
1005
+ let results = results.unwrap();
1006
+ assert_eq!(results.len(), 2);
1007
+ assert_text_content(&results[0].content, "valid content");
1008
+ assert!(results[1].metadata.error.is_some());
1009
+ }
1010
+
1011
+ #[tokio::test]
1012
+ async fn test_batch_extract_bytes_mixed_valid_invalid() {
1013
+ let config = ExtractionConfig::default();
1014
+ let contents = vec![
1015
+ (b"valid 1".as_slice(), "text/plain"),
1016
+ (b"invalid".as_slice(), "invalid/mime"),
1017
+ (b"valid 2".as_slice(), "text/plain"),
1018
+ ];
1019
+ let owned_contents: Vec<(Vec<u8>, String)> = contents
1020
+ .into_iter()
1021
+ .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
1022
+ .collect();
1023
+ let results = batch_extract_bytes(owned_contents, &config).await;
1024
+
1025
+ assert!(results.is_ok());
1026
+ let results = results.unwrap();
1027
+ assert_eq!(results.len(), 3);
1028
+ assert_text_content(&results[0].content, "valid 1");
1029
+ assert!(results[1].metadata.error.is_some());
1030
+ assert_text_content(&results[2].content, "valid 2");
1031
+ }
1032
+
1033
+ #[tokio::test]
1034
+ async fn test_batch_extract_bytes_all_invalid() {
1035
+ let config = ExtractionConfig::default();
1036
+ let contents = vec![
1037
+ (b"test 1".as_slice(), "invalid/mime1"),
1038
+ (b"test 2".as_slice(), "invalid/mime2"),
1039
+ ];
1040
+ let owned_contents: Vec<(Vec<u8>, String)> = contents
1041
+ .into_iter()
1042
+ .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
1043
+ .collect();
1044
+ let results = batch_extract_bytes(owned_contents, &config).await;
1045
+
1046
+ assert!(results.is_ok());
1047
+ let results = results.unwrap();
1048
+ assert_eq!(results.len(), 2);
1049
+ assert!(results[0].metadata.error.is_some());
1050
+ assert!(results[1].metadata.error.is_some());
1051
+ }
1052
+
1053
+ #[tokio::test]
1054
+ async fn test_extract_bytes_very_large() {
1055
+ let large_content = vec![b'a'; 10_000_000];
1056
+ let config = ExtractionConfig::default();
1057
+ let result = extract_bytes(&large_content, "text/plain", &config).await;
1058
+
1059
+ assert!(result.is_ok());
1060
+ let result = result.unwrap();
1061
+ let trimmed_len = result.content.trim_end_matches('\n').len();
1062
+ assert_eq!(trimmed_len, 10_000_000);
1063
+ }
1064
+
1065
+ #[tokio::test]
1066
+ async fn test_batch_extract_large_count() {
1067
+ let dir = tempdir().unwrap();
1068
+ let mut paths = Vec::new();
1069
+
1070
+ for i in 0..100 {
1071
+ let file_path = dir.path().join(format!("file{}.txt", i));
1072
+ File::create(&file_path)
1073
+ .unwrap()
1074
+ .write_all(format!("content {}", i).as_bytes())
1075
+ .unwrap();
1076
+ paths.push(file_path);
1077
+ }
1078
+
1079
+ let config = ExtractionConfig::default();
1080
+ let results = batch_extract_file(paths, &config).await;
1081
+
1082
+ assert!(results.is_ok());
1083
+ let results = results.unwrap();
1084
+ assert_eq!(results.len(), 100);
1085
+
1086
+ for (i, result) in results.iter().enumerate() {
1087
+ assert_text_content(&result.content, &format!("content {}", i));
1088
+ }
1089
+ }
1090
+
1091
+ #[tokio::test]
1092
+ async fn test_extract_file_mime_detection_fallback() {
1093
+ let dir = tempdir().unwrap();
1094
+ let file_path = dir.path().join("testfile");
1095
+ File::create(&file_path)
1096
+ .unwrap()
1097
+ .write_all(b"plain text content")
1098
+ .unwrap();
1099
+
1100
+ let config = ExtractionConfig::default();
1101
+ let result = extract_file(&file_path, None, &config).await;
1102
+
1103
+ assert!(result.is_ok() || result.is_err());
1104
+ }
1105
+
1106
+ #[tokio::test]
1107
+ async fn test_extract_file_wrong_mime_override() {
1108
+ let dir = tempdir().unwrap();
1109
+ let file_path = dir.path().join("test.txt");
1110
+ File::create(&file_path).unwrap().write_all(b"plain text").unwrap();
1111
+
1112
+ let config = ExtractionConfig::default();
1113
+ let result = extract_file(&file_path, Some("application/pdf"), &config).await;
1114
+
1115
+ assert!(result.is_err() || result.is_ok());
1116
+ }
1117
+
1118
+ #[test]
1119
+ fn test_sync_wrapper_nonexistent_file() {
1120
+ let config = ExtractionConfig::default();
1121
+ let result = extract_file_sync("/nonexistent/path.txt", None, &config);
1122
+
1123
+ assert!(result.is_err());
1124
+ assert!(matches!(result.unwrap_err(), KreuzbergError::Validation { .. }));
1125
+ }
1126
+
1127
+ #[test]
1128
+ fn test_sync_wrapper_batch_empty() {
1129
+ let config = ExtractionConfig::default();
1130
+ let paths: Vec<std::path::PathBuf> = vec![];
1131
+ let results = batch_extract_file_sync(paths, &config);
1132
+
1133
+ assert!(results.is_ok());
1134
+ assert_eq!(results.unwrap().len(), 0);
1135
+ }
1136
+
1137
+ #[test]
1138
+ fn test_sync_wrapper_batch_bytes_empty() {
1139
+ let config = ExtractionConfig::default();
1140
+ let contents: Vec<(Vec<u8>, String)> = vec![];
1141
+ let results = batch_extract_bytes_sync(contents, &config);
1142
+
1143
+ assert!(results.is_ok());
1144
+ assert_eq!(results.unwrap().len(), 0);
1145
+ }
1146
+
1147
+ #[tokio::test]
1148
+ async fn test_concurrent_extractions_same_mime() {
1149
+ use tokio::task::JoinSet;
1150
+
1151
+ let config = Arc::new(ExtractionConfig::default());
1152
+ let mut tasks = JoinSet::new();
1153
+
1154
+ for i in 0..50 {
1155
+ let config_clone = Arc::clone(&config);
1156
+ tasks.spawn(async move {
1157
+ let content = format!("test content {}", i);
1158
+ extract_bytes(content.as_bytes(), "text/plain", &config_clone).await
1159
+ });
1160
+ }
1161
+
1162
+ let mut success_count = 0;
1163
+ while let Some(task_result) = tasks.join_next().await {
1164
+ if let Ok(Ok(_)) = task_result {
1165
+ success_count += 1;
1166
+ }
1167
+ }
1168
+
1169
+ assert_eq!(success_count, 50);
1170
+ }
1171
+
1172
+ #[serial]
1173
+ #[tokio::test]
1174
+ async fn test_concurrent_extractions_different_mimes() {
1175
+ use tokio::task::JoinSet;
1176
+
1177
+ let config = Arc::new(ExtractionConfig::default());
1178
+ let mut tasks = JoinSet::new();
1179
+
1180
+ let mime_types = ["text/plain", "text/markdown"];
1181
+
1182
+ for i in 0..30 {
1183
+ let config_clone = Arc::clone(&config);
1184
+ let mime = mime_types[i % mime_types.len()];
1185
+ tasks.spawn(async move {
1186
+ let content = format!("test {}", i);
1187
+ extract_bytes(content.as_bytes(), mime, &config_clone).await
1188
+ });
1189
+ }
1190
+
1191
+ let mut success_count = 0;
1192
+ while let Some(task_result) = tasks.join_next().await {
1193
+ if let Ok(Ok(_)) = task_result {
1194
+ success_count += 1;
1195
+ }
1196
+ }
1197
+
1198
+ assert_eq!(success_count, 30);
1199
+ }
1200
+ }