kreuzberg 4.0.0.rc1 → 4.0.0.rc2

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 (342) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +14 -8
  3. data/.rspec +3 -3
  4. data/.rubocop.yaml +1 -534
  5. data/.rubocop.yml +538 -0
  6. data/Gemfile +8 -9
  7. data/Gemfile.lock +9 -109
  8. data/README.md +426 -421
  9. data/Rakefile +25 -25
  10. data/Steepfile +47 -47
  11. data/examples/async_patterns.rb +341 -340
  12. data/ext/kreuzberg_rb/extconf.rb +45 -35
  13. data/ext/kreuzberg_rb/native/Cargo.lock +6535 -0
  14. data/ext/kreuzberg_rb/native/Cargo.toml +44 -36
  15. data/ext/kreuzberg_rb/native/README.md +425 -425
  16. data/ext/kreuzberg_rb/native/build.rs +15 -17
  17. data/ext/kreuzberg_rb/native/include/ieeefp.h +11 -11
  18. data/ext/kreuzberg_rb/native/include/msvc_compat/strings.h +14 -14
  19. data/ext/kreuzberg_rb/native/include/strings.h +20 -20
  20. data/ext/kreuzberg_rb/native/include/unistd.h +47 -47
  21. data/ext/kreuzberg_rb/native/src/lib.rs +2998 -2939
  22. data/extconf.rb +28 -28
  23. data/kreuzberg.gemspec +148 -105
  24. data/lib/kreuzberg/api_proxy.rb +142 -142
  25. data/lib/kreuzberg/cache_api.rb +46 -45
  26. data/lib/kreuzberg/cli.rb +55 -55
  27. data/lib/kreuzberg/cli_proxy.rb +127 -127
  28. data/lib/kreuzberg/config.rb +691 -684
  29. data/lib/kreuzberg/error_context.rb +32 -0
  30. data/lib/kreuzberg/errors.rb +118 -50
  31. data/lib/kreuzberg/extraction_api.rb +85 -84
  32. data/lib/kreuzberg/mcp_proxy.rb +186 -186
  33. data/lib/kreuzberg/ocr_backend_protocol.rb +113 -113
  34. data/lib/kreuzberg/post_processor_protocol.rb +86 -86
  35. data/lib/kreuzberg/result.rb +216 -216
  36. data/lib/kreuzberg/setup_lib_path.rb +80 -79
  37. data/lib/kreuzberg/validator_protocol.rb +89 -89
  38. data/lib/kreuzberg/version.rb +5 -5
  39. data/lib/kreuzberg.rb +103 -82
  40. data/sig/kreuzberg/internal.rbs +184 -184
  41. data/sig/kreuzberg.rbs +520 -468
  42. data/spec/binding/cache_spec.rb +227 -227
  43. data/spec/binding/cli_proxy_spec.rb +85 -87
  44. data/spec/binding/cli_spec.rb +55 -54
  45. data/spec/binding/config_spec.rb +345 -345
  46. data/spec/binding/config_validation_spec.rb +283 -283
  47. data/spec/binding/error_handling_spec.rb +213 -213
  48. data/spec/binding/errors_spec.rb +66 -66
  49. data/spec/binding/plugins/ocr_backend_spec.rb +307 -307
  50. data/spec/binding/plugins/postprocessor_spec.rb +269 -269
  51. data/spec/binding/plugins/validator_spec.rb +274 -274
  52. data/spec/fixtures/config.toml +39 -39
  53. data/spec/fixtures/config.yaml +41 -42
  54. data/spec/fixtures/invalid_config.toml +4 -4
  55. data/spec/smoke/package_spec.rb +178 -178
  56. data/spec/spec_helper.rb +42 -42
  57. data/vendor/kreuzberg/Cargo.toml +204 -134
  58. data/vendor/kreuzberg/README.md +175 -175
  59. data/vendor/kreuzberg/benches/otel_overhead.rs +48 -0
  60. data/vendor/kreuzberg/build.rs +474 -460
  61. data/vendor/kreuzberg/src/api/error.rs +81 -81
  62. data/vendor/kreuzberg/src/api/handlers.rs +199 -199
  63. data/vendor/kreuzberg/src/api/mod.rs +79 -79
  64. data/vendor/kreuzberg/src/api/server.rs +353 -353
  65. data/vendor/kreuzberg/src/api/types.rs +170 -170
  66. data/vendor/kreuzberg/src/cache/mod.rs +1167 -1143
  67. data/vendor/kreuzberg/src/chunking/mod.rs +677 -677
  68. data/vendor/kreuzberg/src/core/batch_mode.rs +95 -35
  69. data/vendor/kreuzberg/src/core/config.rs +1032 -1032
  70. data/vendor/kreuzberg/src/core/extractor.rs +1024 -903
  71. data/vendor/kreuzberg/src/core/io.rs +329 -327
  72. data/vendor/kreuzberg/src/core/mime.rs +605 -615
  73. data/vendor/kreuzberg/src/core/mod.rs +45 -42
  74. data/vendor/kreuzberg/src/core/pipeline.rs +984 -906
  75. data/vendor/kreuzberg/src/embeddings.rs +432 -323
  76. data/vendor/kreuzberg/src/error.rs +431 -431
  77. data/vendor/kreuzberg/src/extraction/archive.rs +954 -954
  78. data/vendor/kreuzberg/src/extraction/docx.rs +40 -40
  79. data/vendor/kreuzberg/src/extraction/email.rs +854 -854
  80. data/vendor/kreuzberg/src/extraction/excel.rs +688 -688
  81. data/vendor/kreuzberg/src/extraction/html.rs +553 -553
  82. data/vendor/kreuzberg/src/extraction/image.rs +368 -368
  83. data/vendor/kreuzberg/src/extraction/libreoffice.rs +563 -564
  84. data/vendor/kreuzberg/src/extraction/markdown.rs +213 -0
  85. data/vendor/kreuzberg/src/extraction/mod.rs +81 -77
  86. data/vendor/kreuzberg/src/extraction/office_metadata/app_properties.rs +398 -398
  87. data/vendor/kreuzberg/src/extraction/office_metadata/core_properties.rs +247 -247
  88. data/vendor/kreuzberg/src/extraction/office_metadata/custom_properties.rs +240 -240
  89. data/vendor/kreuzberg/src/extraction/office_metadata/mod.rs +130 -128
  90. data/vendor/kreuzberg/src/extraction/office_metadata/odt_properties.rs +287 -0
  91. data/vendor/kreuzberg/src/extraction/pptx.rs +3000 -3000
  92. data/vendor/kreuzberg/src/extraction/structured.rs +490 -490
  93. data/vendor/kreuzberg/src/extraction/table.rs +328 -328
  94. data/vendor/kreuzberg/src/extraction/text.rs +269 -269
  95. data/vendor/kreuzberg/src/extraction/xml.rs +333 -333
  96. data/vendor/kreuzberg/src/extractors/archive.rs +446 -425
  97. data/vendor/kreuzberg/src/extractors/bibtex.rs +469 -0
  98. data/vendor/kreuzberg/src/extractors/docbook.rs +502 -0
  99. data/vendor/kreuzberg/src/extractors/docx.rs +367 -479
  100. data/vendor/kreuzberg/src/extractors/email.rs +143 -129
  101. data/vendor/kreuzberg/src/extractors/epub.rs +707 -0
  102. data/vendor/kreuzberg/src/extractors/excel.rs +343 -344
  103. data/vendor/kreuzberg/src/extractors/fictionbook.rs +491 -0
  104. data/vendor/kreuzberg/src/extractors/fictionbook.rs.backup2 +738 -0
  105. data/vendor/kreuzberg/src/extractors/html.rs +393 -410
  106. data/vendor/kreuzberg/src/extractors/image.rs +198 -195
  107. data/vendor/kreuzberg/src/extractors/jats.rs +1051 -0
  108. data/vendor/kreuzberg/src/extractors/jupyter.rs +367 -0
  109. data/vendor/kreuzberg/src/extractors/latex.rs +652 -0
  110. data/vendor/kreuzberg/src/extractors/markdown.rs +700 -0
  111. data/vendor/kreuzberg/src/extractors/mod.rs +365 -268
  112. data/vendor/kreuzberg/src/extractors/odt.rs +628 -0
  113. data/vendor/kreuzberg/src/extractors/opml.rs +634 -0
  114. data/vendor/kreuzberg/src/extractors/orgmode.rs +528 -0
  115. data/vendor/kreuzberg/src/extractors/pdf.rs +493 -496
  116. data/vendor/kreuzberg/src/extractors/pptx.rs +248 -234
  117. data/vendor/kreuzberg/src/extractors/rst.rs +576 -0
  118. data/vendor/kreuzberg/src/extractors/rtf.rs +810 -0
  119. data/vendor/kreuzberg/src/extractors/security.rs +484 -0
  120. data/vendor/kreuzberg/src/extractors/security_tests.rs +367 -0
  121. data/vendor/kreuzberg/src/extractors/structured.rs +140 -126
  122. data/vendor/kreuzberg/src/extractors/text.rs +260 -242
  123. data/vendor/kreuzberg/src/extractors/typst.rs +650 -0
  124. data/vendor/kreuzberg/src/extractors/xml.rs +135 -128
  125. data/vendor/kreuzberg/src/image/dpi.rs +164 -164
  126. data/vendor/kreuzberg/src/image/mod.rs +6 -6
  127. data/vendor/kreuzberg/src/image/preprocessing.rs +417 -417
  128. data/vendor/kreuzberg/src/image/resize.rs +89 -89
  129. data/vendor/kreuzberg/src/keywords/config.rs +154 -154
  130. data/vendor/kreuzberg/src/keywords/mod.rs +237 -237
  131. data/vendor/kreuzberg/src/keywords/processor.rs +267 -267
  132. data/vendor/kreuzberg/src/keywords/rake.rs +293 -294
  133. data/vendor/kreuzberg/src/keywords/types.rs +68 -68
  134. data/vendor/kreuzberg/src/keywords/yake.rs +163 -163
  135. data/vendor/kreuzberg/src/language_detection/mod.rs +942 -942
  136. data/vendor/kreuzberg/src/lib.rs +105 -102
  137. data/vendor/kreuzberg/src/mcp/mod.rs +32 -32
  138. data/vendor/kreuzberg/src/mcp/server.rs +1968 -1966
  139. data/vendor/kreuzberg/src/ocr/cache.rs +469 -469
  140. data/vendor/kreuzberg/src/ocr/error.rs +37 -37
  141. data/vendor/kreuzberg/src/ocr/hocr.rs +216 -216
  142. data/vendor/kreuzberg/src/ocr/mod.rs +58 -58
  143. data/vendor/kreuzberg/src/ocr/processor.rs +863 -847
  144. data/vendor/kreuzberg/src/ocr/table/mod.rs +4 -4
  145. data/vendor/kreuzberg/src/ocr/table/tsv_parser.rs +144 -144
  146. data/vendor/kreuzberg/src/ocr/tesseract_backend.rs +450 -450
  147. data/vendor/kreuzberg/src/ocr/types.rs +393 -393
  148. data/vendor/kreuzberg/src/ocr/utils.rs +47 -47
  149. data/vendor/kreuzberg/src/ocr/validation.rs +206 -206
  150. data/vendor/kreuzberg/src/panic_context.rs +154 -0
  151. data/vendor/kreuzberg/src/pdf/error.rs +122 -122
  152. data/vendor/kreuzberg/src/pdf/images.rs +139 -139
  153. data/vendor/kreuzberg/src/pdf/metadata.rs +346 -346
  154. data/vendor/kreuzberg/src/pdf/mod.rs +50 -50
  155. data/vendor/kreuzberg/src/pdf/rendering.rs +369 -369
  156. data/vendor/kreuzberg/src/pdf/table.rs +393 -420
  157. data/vendor/kreuzberg/src/pdf/text.rs +158 -161
  158. data/vendor/kreuzberg/src/plugins/extractor.rs +1013 -1010
  159. data/vendor/kreuzberg/src/plugins/mod.rs +209 -209
  160. data/vendor/kreuzberg/src/plugins/ocr.rs +620 -629
  161. data/vendor/kreuzberg/src/plugins/processor.rs +642 -641
  162. data/vendor/kreuzberg/src/plugins/registry.rs +1337 -1324
  163. data/vendor/kreuzberg/src/plugins/traits.rs +258 -258
  164. data/vendor/kreuzberg/src/plugins/validator.rs +956 -955
  165. data/vendor/kreuzberg/src/stopwords/mod.rs +1470 -1470
  166. data/vendor/kreuzberg/src/text/mod.rs +19 -19
  167. data/vendor/kreuzberg/src/text/quality.rs +697 -697
  168. data/vendor/kreuzberg/src/text/string_utils.rs +217 -217
  169. data/vendor/kreuzberg/src/text/token_reduction/cjk_utils.rs +164 -164
  170. data/vendor/kreuzberg/src/text/token_reduction/config.rs +100 -100
  171. data/vendor/kreuzberg/src/text/token_reduction/core.rs +796 -796
  172. data/vendor/kreuzberg/src/text/token_reduction/filters.rs +902 -902
  173. data/vendor/kreuzberg/src/text/token_reduction/mod.rs +160 -160
  174. data/vendor/kreuzberg/src/text/token_reduction/semantic.rs +619 -619
  175. data/vendor/kreuzberg/src/text/token_reduction/simd_text.rs +147 -147
  176. data/vendor/kreuzberg/src/types.rs +903 -873
  177. data/vendor/kreuzberg/src/utils/mod.rs +17 -17
  178. data/vendor/kreuzberg/src/utils/quality.rs +959 -959
  179. data/vendor/kreuzberg/src/utils/string_utils.rs +381 -381
  180. data/vendor/kreuzberg/stopwords/af_stopwords.json +53 -53
  181. data/vendor/kreuzberg/stopwords/ar_stopwords.json +482 -482
  182. data/vendor/kreuzberg/stopwords/bg_stopwords.json +261 -261
  183. data/vendor/kreuzberg/stopwords/bn_stopwords.json +400 -400
  184. data/vendor/kreuzberg/stopwords/br_stopwords.json +1205 -1205
  185. data/vendor/kreuzberg/stopwords/ca_stopwords.json +280 -280
  186. data/vendor/kreuzberg/stopwords/cs_stopwords.json +425 -425
  187. data/vendor/kreuzberg/stopwords/da_stopwords.json +172 -172
  188. data/vendor/kreuzberg/stopwords/de_stopwords.json +622 -622
  189. data/vendor/kreuzberg/stopwords/el_stopwords.json +849 -849
  190. data/vendor/kreuzberg/stopwords/en_stopwords.json +1300 -1300
  191. data/vendor/kreuzberg/stopwords/eo_stopwords.json +175 -175
  192. data/vendor/kreuzberg/stopwords/es_stopwords.json +734 -734
  193. data/vendor/kreuzberg/stopwords/et_stopwords.json +37 -37
  194. data/vendor/kreuzberg/stopwords/eu_stopwords.json +100 -100
  195. data/vendor/kreuzberg/stopwords/fa_stopwords.json +801 -801
  196. data/vendor/kreuzberg/stopwords/fi_stopwords.json +849 -849
  197. data/vendor/kreuzberg/stopwords/fr_stopwords.json +693 -693
  198. data/vendor/kreuzberg/stopwords/ga_stopwords.json +111 -111
  199. data/vendor/kreuzberg/stopwords/gl_stopwords.json +162 -162
  200. data/vendor/kreuzberg/stopwords/gu_stopwords.json +226 -226
  201. data/vendor/kreuzberg/stopwords/ha_stopwords.json +41 -41
  202. data/vendor/kreuzberg/stopwords/he_stopwords.json +196 -196
  203. data/vendor/kreuzberg/stopwords/hi_stopwords.json +227 -227
  204. data/vendor/kreuzberg/stopwords/hr_stopwords.json +181 -181
  205. data/vendor/kreuzberg/stopwords/hu_stopwords.json +791 -791
  206. data/vendor/kreuzberg/stopwords/hy_stopwords.json +47 -47
  207. data/vendor/kreuzberg/stopwords/id_stopwords.json +760 -760
  208. data/vendor/kreuzberg/stopwords/it_stopwords.json +634 -634
  209. data/vendor/kreuzberg/stopwords/ja_stopwords.json +136 -136
  210. data/vendor/kreuzberg/stopwords/kn_stopwords.json +84 -84
  211. data/vendor/kreuzberg/stopwords/ko_stopwords.json +681 -681
  212. data/vendor/kreuzberg/stopwords/ku_stopwords.json +64 -64
  213. data/vendor/kreuzberg/stopwords/la_stopwords.json +51 -51
  214. data/vendor/kreuzberg/stopwords/lt_stopwords.json +476 -476
  215. data/vendor/kreuzberg/stopwords/lv_stopwords.json +163 -163
  216. data/vendor/kreuzberg/stopwords/ml_stopwords.json +1 -1
  217. data/vendor/kreuzberg/stopwords/mr_stopwords.json +101 -101
  218. data/vendor/kreuzberg/stopwords/ms_stopwords.json +477 -477
  219. data/vendor/kreuzberg/stopwords/ne_stopwords.json +490 -490
  220. data/vendor/kreuzberg/stopwords/nl_stopwords.json +415 -415
  221. data/vendor/kreuzberg/stopwords/no_stopwords.json +223 -223
  222. data/vendor/kreuzberg/stopwords/pl_stopwords.json +331 -331
  223. data/vendor/kreuzberg/stopwords/pt_stopwords.json +562 -562
  224. data/vendor/kreuzberg/stopwords/ro_stopwords.json +436 -436
  225. data/vendor/kreuzberg/stopwords/ru_stopwords.json +561 -561
  226. data/vendor/kreuzberg/stopwords/si_stopwords.json +193 -193
  227. data/vendor/kreuzberg/stopwords/sk_stopwords.json +420 -420
  228. data/vendor/kreuzberg/stopwords/sl_stopwords.json +448 -448
  229. data/vendor/kreuzberg/stopwords/so_stopwords.json +32 -32
  230. data/vendor/kreuzberg/stopwords/st_stopwords.json +33 -33
  231. data/vendor/kreuzberg/stopwords/sv_stopwords.json +420 -420
  232. data/vendor/kreuzberg/stopwords/sw_stopwords.json +76 -76
  233. data/vendor/kreuzberg/stopwords/ta_stopwords.json +129 -129
  234. data/vendor/kreuzberg/stopwords/te_stopwords.json +54 -54
  235. data/vendor/kreuzberg/stopwords/th_stopwords.json +118 -118
  236. data/vendor/kreuzberg/stopwords/tl_stopwords.json +149 -149
  237. data/vendor/kreuzberg/stopwords/tr_stopwords.json +506 -506
  238. data/vendor/kreuzberg/stopwords/uk_stopwords.json +75 -75
  239. data/vendor/kreuzberg/stopwords/ur_stopwords.json +519 -519
  240. data/vendor/kreuzberg/stopwords/vi_stopwords.json +647 -647
  241. data/vendor/kreuzberg/stopwords/yo_stopwords.json +62 -62
  242. data/vendor/kreuzberg/stopwords/zh_stopwords.json +796 -796
  243. data/vendor/kreuzberg/stopwords/zu_stopwords.json +31 -31
  244. data/vendor/kreuzberg/tests/api_extract_multipart.rs +52 -0
  245. data/vendor/kreuzberg/tests/api_tests.rs +966 -966
  246. data/vendor/kreuzberg/tests/archive_integration.rs +543 -543
  247. data/vendor/kreuzberg/tests/batch_orchestration.rs +556 -542
  248. data/vendor/kreuzberg/tests/batch_processing.rs +316 -304
  249. data/vendor/kreuzberg/tests/bibtex_parity_test.rs +421 -0
  250. data/vendor/kreuzberg/tests/concurrency_stress.rs +525 -509
  251. data/vendor/kreuzberg/tests/config_features.rs +598 -580
  252. data/vendor/kreuzberg/tests/config_loading_tests.rs +415 -439
  253. data/vendor/kreuzberg/tests/core_integration.rs +510 -493
  254. data/vendor/kreuzberg/tests/csv_integration.rs +414 -424
  255. data/vendor/kreuzberg/tests/docbook_extractor_tests.rs +498 -0
  256. data/vendor/kreuzberg/tests/docx_metadata_extraction_test.rs +122 -124
  257. data/vendor/kreuzberg/tests/docx_vs_pandoc_comparison.rs +370 -0
  258. data/vendor/kreuzberg/tests/email_integration.rs +325 -325
  259. data/vendor/kreuzberg/tests/epub_native_extractor_tests.rs +275 -0
  260. data/vendor/kreuzberg/tests/error_handling.rs +393 -393
  261. data/vendor/kreuzberg/tests/fictionbook_extractor_tests.rs +228 -0
  262. data/vendor/kreuzberg/tests/format_integration.rs +159 -159
  263. data/vendor/kreuzberg/tests/helpers/mod.rs +142 -142
  264. data/vendor/kreuzberg/tests/html_table_test.rs +551 -0
  265. data/vendor/kreuzberg/tests/image_integration.rs +253 -253
  266. data/vendor/kreuzberg/tests/instrumentation_test.rs +139 -0
  267. data/vendor/kreuzberg/tests/jats_extractor_tests.rs +639 -0
  268. data/vendor/kreuzberg/tests/jupyter_extractor_tests.rs +704 -0
  269. data/vendor/kreuzberg/tests/keywords_integration.rs +479 -479
  270. data/vendor/kreuzberg/tests/keywords_quality.rs +509 -509
  271. data/vendor/kreuzberg/tests/latex_extractor_tests.rs +496 -0
  272. data/vendor/kreuzberg/tests/markdown_extractor_tests.rs +490 -0
  273. data/vendor/kreuzberg/tests/mime_detection.rs +428 -428
  274. data/vendor/kreuzberg/tests/ocr_configuration.rs +510 -510
  275. data/vendor/kreuzberg/tests/ocr_errors.rs +676 -676
  276. data/vendor/kreuzberg/tests/ocr_quality.rs +627 -627
  277. data/vendor/kreuzberg/tests/ocr_stress.rs +469 -469
  278. data/vendor/kreuzberg/tests/odt_extractor_tests.rs +695 -0
  279. data/vendor/kreuzberg/tests/opml_extractor_tests.rs +616 -0
  280. data/vendor/kreuzberg/tests/orgmode_extractor_tests.rs +822 -0
  281. data/vendor/kreuzberg/tests/pdf_integration.rs +43 -43
  282. data/vendor/kreuzberg/tests/pipeline_integration.rs +1411 -1412
  283. data/vendor/kreuzberg/tests/plugin_ocr_backend_test.rs +771 -771
  284. data/vendor/kreuzberg/tests/plugin_postprocessor_test.rs +560 -561
  285. data/vendor/kreuzberg/tests/plugin_system.rs +921 -921
  286. data/vendor/kreuzberg/tests/plugin_validator_test.rs +783 -783
  287. data/vendor/kreuzberg/tests/registry_integration_tests.rs +586 -607
  288. data/vendor/kreuzberg/tests/rst_extractor_tests.rs +692 -0
  289. data/vendor/kreuzberg/tests/rtf_extractor_tests.rs +776 -0
  290. data/vendor/kreuzberg/tests/security_validation.rs +415 -404
  291. data/vendor/kreuzberg/tests/stopwords_integration_test.rs +888 -888
  292. data/vendor/kreuzberg/tests/test_fastembed.rs +609 -609
  293. data/vendor/kreuzberg/tests/typst_behavioral_tests.rs +1259 -0
  294. data/vendor/kreuzberg/tests/typst_extractor_tests.rs +647 -0
  295. data/vendor/kreuzberg/tests/xlsx_metadata_extraction_test.rs +87 -87
  296. data/vendor/rb-sys/.cargo-ok +1 -0
  297. data/vendor/rb-sys/.cargo_vcs_info.json +6 -0
  298. data/vendor/rb-sys/Cargo.lock +393 -0
  299. data/vendor/rb-sys/Cargo.toml +70 -0
  300. data/vendor/rb-sys/Cargo.toml.orig +57 -0
  301. data/vendor/rb-sys/LICENSE-APACHE +190 -0
  302. data/vendor/rb-sys/LICENSE-MIT +21 -0
  303. data/vendor/rb-sys/bin/release.sh +21 -0
  304. data/vendor/rb-sys/build/features.rs +108 -0
  305. data/vendor/rb-sys/build/main.rs +246 -0
  306. data/vendor/rb-sys/build/stable_api_config.rs +153 -0
  307. data/vendor/rb-sys/build/version.rs +48 -0
  308. data/vendor/rb-sys/readme.md +36 -0
  309. data/vendor/rb-sys/src/bindings.rs +21 -0
  310. data/vendor/rb-sys/src/hidden.rs +11 -0
  311. data/vendor/rb-sys/src/lib.rs +34 -0
  312. data/vendor/rb-sys/src/macros.rs +371 -0
  313. data/vendor/rb-sys/src/memory.rs +53 -0
  314. data/vendor/rb-sys/src/ruby_abi_version.rs +38 -0
  315. data/vendor/rb-sys/src/special_consts.rs +31 -0
  316. data/vendor/rb-sys/src/stable_api/compiled.c +179 -0
  317. data/vendor/rb-sys/src/stable_api/compiled.rs +257 -0
  318. data/vendor/rb-sys/src/stable_api/ruby_2_6.rs +316 -0
  319. data/vendor/rb-sys/src/stable_api/ruby_2_7.rs +316 -0
  320. data/vendor/rb-sys/src/stable_api/ruby_3_0.rs +324 -0
  321. data/vendor/rb-sys/src/stable_api/ruby_3_1.rs +317 -0
  322. data/vendor/rb-sys/src/stable_api/ruby_3_2.rs +315 -0
  323. data/vendor/rb-sys/src/stable_api/ruby_3_3.rs +326 -0
  324. data/vendor/rb-sys/src/stable_api/ruby_3_4.rs +327 -0
  325. data/vendor/rb-sys/src/stable_api.rs +261 -0
  326. data/vendor/rb-sys/src/symbol.rs +31 -0
  327. data/vendor/rb-sys/src/tracking_allocator.rs +332 -0
  328. data/vendor/rb-sys/src/utils.rs +89 -0
  329. data/vendor/rb-sys/src/value_type.rs +7 -0
  330. metadata +90 -95
  331. data/pkg/kreuzberg-4.0.0.rc1.gem +0 -0
  332. data/spec/examples.txt +0 -104
  333. data/vendor/kreuzberg/src/bin/profile_extract.rs +0 -455
  334. data/vendor/kreuzberg/src/extraction/pandoc/batch.rs +0 -275
  335. data/vendor/kreuzberg/src/extraction/pandoc/mime_types.rs +0 -178
  336. data/vendor/kreuzberg/src/extraction/pandoc/mod.rs +0 -491
  337. data/vendor/kreuzberg/src/extraction/pandoc/server.rs +0 -496
  338. data/vendor/kreuzberg/src/extraction/pandoc/subprocess.rs +0 -1188
  339. data/vendor/kreuzberg/src/extraction/pandoc/version.rs +0 -162
  340. data/vendor/kreuzberg/src/extractors/pandoc.rs +0 -201
  341. data/vendor/kreuzberg/tests/chunking_offset_demo.rs +0 -92
  342. data/vendor/kreuzberg/tests/pandoc_integration.rs +0 -503
@@ -1,903 +1,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::{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
- /// Global Tokio runtime for synchronous operations.
30
- ///
31
- /// This runtime is lazily initialized on first use and shared across all sync wrappers.
32
- /// Using a global runtime instead of creating one per call provides 100x+ performance improvement.
33
- ///
34
- /// # Safety
35
- ///
36
- /// The `.expect()` here is justified because:
37
- /// 1. Runtime creation can only fail due to system resource exhaustion (OOM, thread limit)
38
- /// 2. If runtime creation fails, the process is already in a critical state
39
- /// 3. This is a one-time initialization - if it fails, nothing will work
40
- /// 4. Better to fail fast than return errors from every sync operation
41
- static GLOBAL_RUNTIME: Lazy<tokio::runtime::Runtime> = Lazy::new(|| {
42
- tokio::runtime::Builder::new_multi_thread()
43
- .enable_all()
44
- .build()
45
- .expect("Failed to create global Tokio runtime - system may be out of resources")
46
- });
47
-
48
- /// Get an extractor from the registry.
49
- ///
50
- /// This function acquires the registry read lock and retrieves the appropriate
51
- /// extractor for the given MIME type.
52
- ///
53
- /// # Performance
54
- ///
55
- /// RwLock read + HashMap lookup is ~100ns, fast enough without caching.
56
- /// Removed thread-local cache to avoid Tokio work-stealing scheduler issues.
57
- fn get_extractor(mime_type: &str) -> Result<Arc<dyn DocumentExtractor>> {
58
- let registry = crate::plugins::registry::get_document_extractor_registry();
59
- let registry_read = registry
60
- .read()
61
- .map_err(|e| KreuzbergError::Other(format!("Document extractor registry lock poisoned: {}", e)))?;
62
- registry_read.get(mime_type)
63
- }
64
-
65
- /// Extract content from a file.
66
- ///
67
- /// This is the main entry point for file-based extraction. It performs the following steps:
68
- /// 1. Check cache for existing result (if caching enabled)
69
- /// 2. Detect or validate MIME type
70
- /// 3. Select appropriate extractor from registry
71
- /// 4. Extract content
72
- /// 5. Run post-processing pipeline
73
- /// 6. Store result in cache (if caching enabled)
74
- ///
75
- /// # Arguments
76
- ///
77
- /// * `path` - Path to the file to extract
78
- /// * `mime_type` - Optional MIME type override. If None, will be auto-detected
79
- /// * `config` - Extraction configuration
80
- ///
81
- /// # Returns
82
- ///
83
- /// An `ExtractionResult` containing the extracted content and metadata.
84
- ///
85
- /// # Errors
86
- ///
87
- /// Returns `KreuzbergError::Validation` if the file doesn't exist or path is invalid.
88
- /// Returns `KreuzbergError::UnsupportedFormat` if MIME type is not supported.
89
- /// Returns `KreuzbergError::Io` for file I/O errors (these always bubble up).
90
- ///
91
- /// # Example
92
- ///
93
- /// ```rust,no_run
94
- /// use kreuzberg::core::extractor::extract_file;
95
- /// use kreuzberg::core::config::ExtractionConfig;
96
- ///
97
- /// # async fn example() -> kreuzberg::Result<()> {
98
- /// let config = ExtractionConfig::default();
99
- /// let result = extract_file("document.pdf", None, &config).await?;
100
- /// println!("Content: {}", result.content);
101
- /// # Ok(())
102
- /// # }
103
- /// ```
104
- pub async fn extract_file(
105
- path: impl AsRef<Path>,
106
- mime_type: Option<&str>,
107
- config: &ExtractionConfig,
108
- ) -> Result<ExtractionResult> {
109
- use crate::core::{io, mime};
110
-
111
- let path = path.as_ref();
112
-
113
- io::validate_file_exists(path)?;
114
-
115
- let detected_mime = mime::detect_or_validate(Some(path), mime_type)?;
116
-
117
- match detected_mime.as_str() {
118
- #[cfg(feature = "office")]
119
- LEGACY_WORD_MIME_TYPE => {
120
- let original_bytes = tokio::fs::read(path).await?;
121
- let conversion = convert_doc_to_docx(&original_bytes).await?;
122
- let mut result =
123
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
124
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
125
- return Ok(result);
126
- }
127
- #[cfg(not(feature = "office"))]
128
- LEGACY_WORD_MIME_TYPE => {
129
- return Err(KreuzbergError::UnsupportedFormat(
130
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
131
- ));
132
- }
133
- #[cfg(feature = "office")]
134
- LEGACY_POWERPOINT_MIME_TYPE => {
135
- let original_bytes = tokio::fs::read(path).await?;
136
- let conversion = convert_ppt_to_pptx(&original_bytes).await?;
137
- let mut result =
138
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
139
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
140
- return Ok(result);
141
- }
142
- #[cfg(not(feature = "office"))]
143
- LEGACY_POWERPOINT_MIME_TYPE => {
144
- return Err(KreuzbergError::UnsupportedFormat(
145
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
146
- ));
147
- }
148
- _ => {}
149
- }
150
-
151
- extract_file_with_extractor(path, &detected_mime, config).await
152
- }
153
-
154
- /// Extract content from a byte array.
155
- pub async fn extract_bytes(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
156
- use crate::core::mime;
157
-
158
- let validated_mime = mime::validate_mime_type(mime_type)?;
159
-
160
- match validated_mime.as_str() {
161
- #[cfg(feature = "office")]
162
- LEGACY_WORD_MIME_TYPE => {
163
- let conversion = convert_doc_to_docx(content).await?;
164
- let mut result =
165
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
166
- apply_libreoffice_metadata(&mut result, LEGACY_WORD_MIME_TYPE, &conversion);
167
- return Ok(result);
168
- }
169
- #[cfg(not(feature = "office"))]
170
- LEGACY_WORD_MIME_TYPE => {
171
- return Err(KreuzbergError::UnsupportedFormat(
172
- "Legacy Word conversion requires the `office` feature or LibreOffice support".to_string(),
173
- ));
174
- }
175
- #[cfg(feature = "office")]
176
- LEGACY_POWERPOINT_MIME_TYPE => {
177
- let conversion = convert_ppt_to_pptx(content).await?;
178
- let mut result =
179
- extract_bytes_with_extractor(&conversion.converted_bytes, &conversion.target_mime, config).await?;
180
- apply_libreoffice_metadata(&mut result, LEGACY_POWERPOINT_MIME_TYPE, &conversion);
181
- return Ok(result);
182
- }
183
- #[cfg(not(feature = "office"))]
184
- LEGACY_POWERPOINT_MIME_TYPE => {
185
- return Err(KreuzbergError::UnsupportedFormat(
186
- "Legacy PowerPoint conversion requires the `office` feature or LibreOffice support".to_string(),
187
- ));
188
- }
189
- _ => {}
190
- }
191
-
192
- extract_bytes_with_extractor(content, &validated_mime, config).await
193
- }
194
-
195
- /// Extract content from multiple files concurrently.
196
- ///
197
- /// This function processes multiple files in parallel, automatically managing
198
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
199
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
200
- /// to `num_cpus * 2`.
201
- ///
202
- /// # Arguments
203
- ///
204
- /// * `paths` - Vector of file paths to extract
205
- /// * `config` - Extraction configuration
206
- ///
207
- /// # Returns
208
- ///
209
- /// A vector of `ExtractionResult` in the same order as the input paths.
210
- ///
211
- /// # Errors
212
- ///
213
- /// Individual file errors are captured in the result metadata. System errors
214
- /// (IO, RuntimeError equivalents) will bubble up and fail the entire batch.
215
- pub async fn batch_extract_file(
216
- paths: Vec<impl AsRef<Path>>,
217
- config: &ExtractionConfig,
218
- ) -> Result<Vec<ExtractionResult>> {
219
- use std::sync::Arc;
220
- use tokio::sync::Semaphore;
221
- use tokio::task::JoinSet;
222
-
223
- if paths.is_empty() {
224
- return Ok(vec![]);
225
- }
226
-
227
- let config = Arc::new(config.clone());
228
-
229
- let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
230
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
231
-
232
- let mut tasks = JoinSet::new();
233
-
234
- for (index, path) in paths.into_iter().enumerate() {
235
- let path_buf = path.as_ref().to_path_buf();
236
- let config_clone = Arc::clone(&config);
237
- let semaphore_clone = Arc::clone(&semaphore);
238
-
239
- tasks.spawn(async move {
240
- let _permit = semaphore_clone.acquire().await.unwrap();
241
- let result =
242
- crate::core::batch_mode::with_batch_mode(async { extract_file(&path_buf, None, &config_clone).await })
243
- .await;
244
- (index, result)
245
- });
246
- }
247
-
248
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
249
-
250
- while let Some(task_result) = tasks.join_next().await {
251
- match task_result {
252
- Ok((index, Ok(result))) => {
253
- results[index] = Some(result);
254
- }
255
- Ok((index, Err(e))) => {
256
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
257
- if matches!(e, KreuzbergError::Io(_)) {
258
- return Err(e);
259
- }
260
-
261
- use crate::types::{ErrorMetadata, Metadata};
262
- let metadata = Metadata {
263
- error: Some(ErrorMetadata {
264
- error_type: format!("{:?}", e),
265
- message: e.to_string(),
266
- }),
267
- ..Default::default()
268
- };
269
-
270
- results[index] = Some(ExtractionResult {
271
- content: format!("Error: {}", e),
272
- mime_type: "text/plain".to_string(),
273
- metadata,
274
- tables: vec![],
275
- detected_languages: None,
276
- chunks: None,
277
- images: None,
278
- });
279
- }
280
- Err(join_err) => {
281
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
282
- }
283
- }
284
- }
285
-
286
- #[allow(clippy::unwrap_used)]
287
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
288
- }
289
-
290
- /// Extract content from multiple byte arrays concurrently.
291
- ///
292
- /// This function processes multiple byte arrays in parallel, automatically managing
293
- /// concurrency to prevent resource exhaustion. The concurrency limit can be
294
- /// configured via `ExtractionConfig::max_concurrent_extractions` or defaults
295
- /// to `num_cpus * 2`.
296
- ///
297
- /// # Arguments
298
- ///
299
- /// * `contents` - Vector of (bytes, mime_type) tuples
300
- /// * `config` - Extraction configuration
301
- ///
302
- /// # Returns
303
- ///
304
- /// A vector of `ExtractionResult` in the same order as the input.
305
- pub async fn batch_extract_bytes(
306
- contents: Vec<(&[u8], &str)>,
307
- config: &ExtractionConfig,
308
- ) -> Result<Vec<ExtractionResult>> {
309
- use std::sync::Arc;
310
- use tokio::sync::Semaphore;
311
- use tokio::task::JoinSet;
312
-
313
- if contents.is_empty() {
314
- return Ok(vec![]);
315
- }
316
-
317
- let batch_config = config.clone();
318
- let config = Arc::new(batch_config);
319
-
320
- let max_concurrent = config.max_concurrent_extractions.unwrap_or_else(|| num_cpus::get() * 2);
321
- let semaphore = Arc::new(Semaphore::new(max_concurrent));
322
-
323
- let owned_contents: Vec<(Vec<u8>, String)> = contents
324
- .into_iter()
325
- .map(|(bytes, mime)| (bytes.to_vec(), mime.to_string()))
326
- .collect();
327
-
328
- let mut tasks = JoinSet::new();
329
-
330
- for (index, (bytes, mime_type)) in owned_contents.into_iter().enumerate() {
331
- let config_clone = Arc::clone(&config);
332
- let semaphore_clone = Arc::clone(&semaphore);
333
-
334
- tasks.spawn(async move {
335
- let _permit = semaphore_clone.acquire().await.unwrap();
336
- let result = crate::core::batch_mode::with_batch_mode(async {
337
- extract_bytes(&bytes, &mime_type, &config_clone).await
338
- })
339
- .await;
340
- (index, result)
341
- });
342
- }
343
-
344
- let mut results: Vec<Option<ExtractionResult>> = vec![None; tasks.len()];
345
-
346
- while let Some(task_result) = tasks.join_next().await {
347
- match task_result {
348
- Ok((index, Ok(result))) => {
349
- results[index] = Some(result);
350
- }
351
- Ok((index, Err(e))) => {
352
- // OSError/RuntimeError must bubble up - system errors need user reports ~keep
353
- if matches!(e, KreuzbergError::Io(_)) {
354
- return Err(e);
355
- }
356
-
357
- use crate::types::{ErrorMetadata, Metadata};
358
- let metadata = Metadata {
359
- error: Some(ErrorMetadata {
360
- error_type: format!("{:?}", e),
361
- message: e.to_string(),
362
- }),
363
- ..Default::default()
364
- };
365
-
366
- results[index] = Some(ExtractionResult {
367
- content: format!("Error: {}", e),
368
- mime_type: "text/plain".to_string(),
369
- metadata,
370
- tables: vec![],
371
- detected_languages: None,
372
- chunks: None,
373
- images: None,
374
- });
375
- }
376
- Err(join_err) => {
377
- return Err(KreuzbergError::Other(format!("Task panicked: {}", join_err)));
378
- }
379
- }
380
- }
381
-
382
- #[allow(clippy::unwrap_used)]
383
- Ok(results.into_iter().map(|r| r.unwrap()).collect())
384
- }
385
-
386
- /// Synchronous wrapper for `extract_file`.
387
- ///
388
- /// This is a convenience function that blocks the current thread until extraction completes.
389
- /// For async code, use `extract_file` directly.
390
- ///
391
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
392
- /// a new runtime per call. Always uses the global runtime to avoid nested runtime issues.
393
- pub fn extract_file_sync(
394
- path: impl AsRef<Path>,
395
- mime_type: Option<&str>,
396
- config: &ExtractionConfig,
397
- ) -> Result<ExtractionResult> {
398
- GLOBAL_RUNTIME.block_on(extract_file(path, mime_type, config))
399
- }
400
-
401
- /// Synchronous wrapper for `extract_bytes`.
402
- ///
403
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
404
- /// a new runtime per call.
405
- pub fn extract_bytes_sync(content: &[u8], mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
406
- GLOBAL_RUNTIME.block_on(extract_bytes(content, mime_type, config))
407
- }
408
-
409
- /// Synchronous wrapper for `batch_extract_file`.
410
- ///
411
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
412
- /// a new runtime per call.
413
- pub fn batch_extract_file_sync(
414
- paths: Vec<impl AsRef<Path>>,
415
- config: &ExtractionConfig,
416
- ) -> Result<Vec<ExtractionResult>> {
417
- GLOBAL_RUNTIME.block_on(batch_extract_file(paths, config))
418
- }
419
-
420
- /// Synchronous wrapper for `batch_extract_bytes`.
421
- ///
422
- /// Uses the global Tokio runtime for 100x+ performance improvement over creating
423
- /// a new runtime per call.
424
- pub fn batch_extract_bytes_sync(
425
- contents: Vec<(&[u8], &str)>,
426
- config: &ExtractionConfig,
427
- ) -> Result<Vec<ExtractionResult>> {
428
- GLOBAL_RUNTIME.block_on(batch_extract_bytes(contents, config))
429
- }
430
-
431
- async fn extract_file_with_extractor(
432
- path: &Path,
433
- mime_type: &str,
434
- config: &ExtractionConfig,
435
- ) -> Result<ExtractionResult> {
436
- crate::extractors::ensure_initialized()?;
437
-
438
- let extractor = get_extractor(mime_type)?;
439
- let mut result = extractor.extract_file(path, mime_type, config).await?;
440
- result = crate::core::pipeline::run_pipeline(result, config).await?;
441
- Ok(result)
442
- }
443
-
444
- async fn extract_bytes_with_extractor(
445
- content: &[u8],
446
- mime_type: &str,
447
- config: &ExtractionConfig,
448
- ) -> Result<ExtractionResult> {
449
- crate::extractors::ensure_initialized()?;
450
-
451
- let extractor = get_extractor(mime_type)?;
452
- let mut result = extractor.extract_bytes(content, mime_type, config).await?;
453
- result = crate::core::pipeline::run_pipeline(result, config).await?;
454
- Ok(result)
455
- }
456
-
457
- #[cfg(feature = "office")]
458
- fn apply_libreoffice_metadata(
459
- result: &mut ExtractionResult,
460
- legacy_mime: &str,
461
- conversion: &LibreOfficeConversionResult,
462
- ) {
463
- result.mime_type = legacy_mime.to_string();
464
- result.metadata.additional.insert(
465
- "libreoffice_conversion".to_string(),
466
- json!({
467
- "converter": "libreoffice",
468
- "original_format": conversion.original_format,
469
- "target_format": conversion.target_format,
470
- "target_mime": conversion.target_mime,
471
- }),
472
- );
473
- }
474
-
475
- #[cfg(test)]
476
- mod tests {
477
- use super::*;
478
- use serial_test::serial;
479
- use std::fs::File;
480
- use std::io::Write;
481
- use tempfile::tempdir;
482
-
483
- #[tokio::test]
484
- async fn test_extract_file_basic() {
485
- let dir = tempdir().unwrap();
486
- let file_path = dir.path().join("test.txt");
487
- let mut file = File::create(&file_path).unwrap();
488
- file.write_all(b"Hello, world!").unwrap();
489
-
490
- let config = ExtractionConfig::default();
491
- let result = extract_file(&file_path, None, &config).await;
492
-
493
- assert!(result.is_ok());
494
- let result = result.unwrap();
495
- assert_eq!(result.content, "Hello, world!");
496
- assert_eq!(result.mime_type, "text/plain");
497
- }
498
-
499
- #[tokio::test]
500
- async fn test_extract_file_with_mime_override() {
501
- let dir = tempdir().unwrap();
502
- let file_path = dir.path().join("test.dat");
503
- let mut file = File::create(&file_path).unwrap();
504
- file.write_all(b"test content").unwrap();
505
-
506
- let config = ExtractionConfig::default();
507
- let result = extract_file(&file_path, Some("text/plain"), &config).await;
508
-
509
- assert!(result.is_ok());
510
- let result = result.unwrap();
511
- assert_eq!(result.mime_type, "text/plain");
512
- }
513
-
514
- #[tokio::test]
515
- async fn test_extract_file_nonexistent() {
516
- let config = ExtractionConfig::default();
517
- let result = extract_file("/nonexistent/file.txt", None, &config).await;
518
- assert!(result.is_err());
519
- }
520
-
521
- #[tokio::test]
522
- async fn test_extract_bytes_basic() {
523
- let config = ExtractionConfig::default();
524
- let result = extract_bytes(b"test content", "text/plain", &config).await;
525
-
526
- assert!(result.is_ok());
527
- let result = result.unwrap();
528
- assert_eq!(result.content, "test content");
529
- assert_eq!(result.mime_type, "text/plain");
530
- }
531
-
532
- #[tokio::test]
533
- async fn test_extract_bytes_invalid_mime() {
534
- let config = ExtractionConfig::default();
535
- let result = extract_bytes(b"test", "invalid/mime", &config).await;
536
- assert!(result.is_err());
537
- }
538
-
539
- #[tokio::test]
540
- async fn test_batch_extract_file() {
541
- let dir = tempdir().unwrap();
542
-
543
- let file1 = dir.path().join("test1.txt");
544
- let file2 = dir.path().join("test2.txt");
545
-
546
- File::create(&file1).unwrap().write_all(b"content 1").unwrap();
547
- File::create(&file2).unwrap().write_all(b"content 2").unwrap();
548
-
549
- let config = ExtractionConfig::default();
550
- let paths = vec![file1, file2];
551
- let results = batch_extract_file(paths, &config).await;
552
-
553
- assert!(results.is_ok());
554
- let results = results.unwrap();
555
- assert_eq!(results.len(), 2);
556
- assert_eq!(results[0].content, "content 1");
557
- assert_eq!(results[1].content, "content 2");
558
- }
559
-
560
- #[tokio::test]
561
- async fn test_batch_extract_file_empty() {
562
- let config = ExtractionConfig::default();
563
- let paths: Vec<std::path::PathBuf> = vec![];
564
- let results = batch_extract_file(paths, &config).await;
565
-
566
- assert!(results.is_ok());
567
- assert_eq!(results.unwrap().len(), 0);
568
- }
569
-
570
- #[tokio::test]
571
- async fn test_batch_extract_bytes() {
572
- let config = ExtractionConfig::default();
573
- let contents = vec![
574
- (b"content 1".as_slice(), "text/plain"),
575
- (b"content 2".as_slice(), "text/plain"),
576
- ];
577
- let results = batch_extract_bytes(contents, &config).await;
578
-
579
- assert!(results.is_ok());
580
- let results = results.unwrap();
581
- assert_eq!(results.len(), 2);
582
- assert_eq!(results[0].content, "content 1");
583
- assert_eq!(results[1].content, "content 2");
584
- }
585
-
586
- #[test]
587
- fn test_sync_wrappers() {
588
- let dir = tempdir().unwrap();
589
- let file_path = dir.path().join("test.txt");
590
- File::create(&file_path).unwrap().write_all(b"sync test").unwrap();
591
-
592
- let config = ExtractionConfig::default();
593
-
594
- let result = extract_file_sync(&file_path, None, &config);
595
- assert!(result.is_ok());
596
- assert_eq!(result.unwrap().content, "sync test");
597
-
598
- let result = extract_bytes_sync(b"test", "text/plain", &config);
599
- assert!(result.is_ok());
600
- }
601
-
602
- #[tokio::test]
603
- async fn test_extractor_cache() {
604
- let config = ExtractionConfig::default();
605
-
606
- let result1 = extract_bytes(b"test 1", "text/plain", &config).await;
607
- assert!(result1.is_ok());
608
-
609
- let result2 = extract_bytes(b"test 2", "text/plain", &config).await;
610
- assert!(result2.is_ok());
611
-
612
- assert_eq!(result1.unwrap().content, "test 1");
613
- assert_eq!(result2.unwrap().content, "test 2");
614
-
615
- let result3 = extract_bytes(b"# test 3", "text/markdown", &config).await;
616
- assert!(result3.is_ok());
617
- }
618
-
619
- #[tokio::test]
620
- async fn test_extract_file_empty() {
621
- let dir = tempdir().unwrap();
622
- let file_path = dir.path().join("empty.txt");
623
- File::create(&file_path).unwrap();
624
-
625
- let config = ExtractionConfig::default();
626
- let result = extract_file(&file_path, None, &config).await;
627
-
628
- assert!(result.is_ok());
629
- let result = result.unwrap();
630
- assert_eq!(result.content, "");
631
- }
632
-
633
- #[tokio::test]
634
- async fn test_extract_bytes_empty() {
635
- let config = ExtractionConfig::default();
636
- let result = extract_bytes(b"", "text/plain", &config).await;
637
-
638
- assert!(result.is_ok());
639
- let result = result.unwrap();
640
- assert_eq!(result.content, "");
641
- }
642
-
643
- #[tokio::test]
644
- async fn test_extract_file_whitespace_only() {
645
- let dir = tempdir().unwrap();
646
- let file_path = dir.path().join("whitespace.txt");
647
- File::create(&file_path).unwrap().write_all(b" \n\t \n ").unwrap();
648
-
649
- let config = ExtractionConfig::default();
650
- let result = extract_file(&file_path, None, &config).await;
651
-
652
- assert!(result.is_ok());
653
- }
654
-
655
- #[tokio::test]
656
- async fn test_extract_file_very_long_path() {
657
- let dir = tempdir().unwrap();
658
- let long_name = "a".repeat(200);
659
- let file_path = dir.path().join(format!("{}.txt", long_name));
660
-
661
- if let Ok(mut f) = File::create(&file_path) {
662
- f.write_all(b"content").unwrap();
663
- let config = ExtractionConfig::default();
664
- let result = extract_file(&file_path, None, &config).await;
665
- assert!(result.is_ok() || result.is_err());
666
- }
667
- }
668
-
669
- #[tokio::test]
670
- async fn test_extract_file_special_characters_in_path() {
671
- let dir = tempdir().unwrap();
672
- let file_path = dir.path().join("test with spaces & symbols!.txt");
673
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
674
-
675
- let config = ExtractionConfig::default();
676
- let result = extract_file(&file_path, None, &config).await;
677
-
678
- assert!(result.is_ok());
679
- assert_eq!(result.unwrap().content, "content");
680
- }
681
-
682
- #[tokio::test]
683
- async fn test_extract_file_unicode_filename() {
684
- let dir = tempdir().unwrap();
685
- let file_path = dir.path().join("测试文件名.txt");
686
- File::create(&file_path).unwrap().write_all(b"content").unwrap();
687
-
688
- let config = ExtractionConfig::default();
689
- let result = extract_file(&file_path, None, &config).await;
690
-
691
- assert!(result.is_ok());
692
- }
693
-
694
- #[tokio::test]
695
- async fn test_extract_bytes_unsupported_mime() {
696
- let config = ExtractionConfig::default();
697
- let result = extract_bytes(b"test", "application/x-unknown-format", &config).await;
698
-
699
- assert!(result.is_err());
700
- assert!(matches!(result.unwrap_err(), KreuzbergError::UnsupportedFormat(_)));
701
- }
702
-
703
- #[tokio::test]
704
- async fn test_batch_extract_file_with_errors() {
705
- let dir = tempdir().unwrap();
706
-
707
- let valid_file = dir.path().join("valid.txt");
708
- File::create(&valid_file).unwrap().write_all(b"valid content").unwrap();
709
-
710
- let invalid_file = dir.path().join("nonexistent.txt");
711
-
712
- let config = ExtractionConfig::default();
713
- let paths = vec![valid_file, invalid_file];
714
- let results = batch_extract_file(paths, &config).await;
715
-
716
- assert!(results.is_ok());
717
- let results = results.unwrap();
718
- assert_eq!(results.len(), 2);
719
- assert_eq!(results[0].content, "valid content");
720
- assert!(results[1].metadata.error.is_some());
721
- }
722
-
723
- #[tokio::test]
724
- async fn test_batch_extract_bytes_mixed_valid_invalid() {
725
- let config = ExtractionConfig::default();
726
- let contents = vec![
727
- (b"valid 1".as_slice(), "text/plain"),
728
- (b"invalid".as_slice(), "invalid/mime"),
729
- (b"valid 2".as_slice(), "text/plain"),
730
- ];
731
- let results = batch_extract_bytes(contents, &config).await;
732
-
733
- assert!(results.is_ok());
734
- let results = results.unwrap();
735
- assert_eq!(results.len(), 3);
736
- assert_eq!(results[0].content, "valid 1");
737
- assert!(results[1].metadata.error.is_some());
738
- assert_eq!(results[2].content, "valid 2");
739
- }
740
-
741
- #[tokio::test]
742
- async fn test_batch_extract_bytes_all_invalid() {
743
- let config = ExtractionConfig::default();
744
- let contents = vec![
745
- (b"test 1".as_slice(), "invalid/mime1"),
746
- (b"test 2".as_slice(), "invalid/mime2"),
747
- ];
748
- let results = batch_extract_bytes(contents, &config).await;
749
-
750
- assert!(results.is_ok());
751
- let results = results.unwrap();
752
- assert_eq!(results.len(), 2);
753
- assert!(results[0].metadata.error.is_some());
754
- assert!(results[1].metadata.error.is_some());
755
- }
756
-
757
- #[tokio::test]
758
- async fn test_extract_bytes_very_large() {
759
- let large_content = vec![b'a'; 10_000_000];
760
- let config = ExtractionConfig::default();
761
- let result = extract_bytes(&large_content, "text/plain", &config).await;
762
-
763
- assert!(result.is_ok());
764
- let result = result.unwrap();
765
- assert_eq!(result.content.len(), 10_000_000);
766
- }
767
-
768
- #[tokio::test]
769
- async fn test_batch_extract_large_count() {
770
- let dir = tempdir().unwrap();
771
- let mut paths = Vec::new();
772
-
773
- for i in 0..100 {
774
- let file_path = dir.path().join(format!("file{}.txt", i));
775
- File::create(&file_path)
776
- .unwrap()
777
- .write_all(format!("content {}", i).as_bytes())
778
- .unwrap();
779
- paths.push(file_path);
780
- }
781
-
782
- let config = ExtractionConfig::default();
783
- let results = batch_extract_file(paths, &config).await;
784
-
785
- assert!(results.is_ok());
786
- let results = results.unwrap();
787
- assert_eq!(results.len(), 100);
788
-
789
- for (i, result) in results.iter().enumerate() {
790
- assert_eq!(result.content, format!("content {}", i));
791
- }
792
- }
793
-
794
- #[tokio::test]
795
- async fn test_extract_file_mime_detection_fallback() {
796
- let dir = tempdir().unwrap();
797
- let file_path = dir.path().join("testfile");
798
- File::create(&file_path)
799
- .unwrap()
800
- .write_all(b"plain text content")
801
- .unwrap();
802
-
803
- let config = ExtractionConfig::default();
804
- let result = extract_file(&file_path, None, &config).await;
805
-
806
- assert!(result.is_ok() || result.is_err());
807
- }
808
-
809
- #[tokio::test]
810
- async fn test_extract_file_wrong_mime_override() {
811
- let dir = tempdir().unwrap();
812
- let file_path = dir.path().join("test.txt");
813
- File::create(&file_path).unwrap().write_all(b"plain text").unwrap();
814
-
815
- let config = ExtractionConfig::default();
816
- let result = extract_file(&file_path, Some("application/pdf"), &config).await;
817
-
818
- assert!(result.is_err() || result.is_ok());
819
- }
820
-
821
- #[test]
822
- fn test_sync_wrapper_nonexistent_file() {
823
- let config = ExtractionConfig::default();
824
- let result = extract_file_sync("/nonexistent/path.txt", None, &config);
825
-
826
- assert!(result.is_err());
827
- assert!(matches!(result.unwrap_err(), KreuzbergError::Validation { .. }));
828
- }
829
-
830
- #[test]
831
- fn test_sync_wrapper_batch_empty() {
832
- let config = ExtractionConfig::default();
833
- let paths: Vec<std::path::PathBuf> = vec![];
834
- let results = batch_extract_file_sync(paths, &config);
835
-
836
- assert!(results.is_ok());
837
- assert_eq!(results.unwrap().len(), 0);
838
- }
839
-
840
- #[test]
841
- fn test_sync_wrapper_batch_bytes_empty() {
842
- let config = ExtractionConfig::default();
843
- let contents: Vec<(&[u8], &str)> = vec![];
844
- let results = batch_extract_bytes_sync(contents, &config);
845
-
846
- assert!(results.is_ok());
847
- assert_eq!(results.unwrap().len(), 0);
848
- }
849
-
850
- #[tokio::test]
851
- async fn test_concurrent_extractions_same_mime() {
852
- use tokio::task::JoinSet;
853
-
854
- let config = Arc::new(ExtractionConfig::default());
855
- let mut tasks = JoinSet::new();
856
-
857
- for i in 0..50 {
858
- let config_clone = Arc::clone(&config);
859
- tasks.spawn(async move {
860
- let content = format!("test content {}", i);
861
- extract_bytes(content.as_bytes(), "text/plain", &config_clone).await
862
- });
863
- }
864
-
865
- let mut success_count = 0;
866
- while let Some(task_result) = tasks.join_next().await {
867
- if let Ok(Ok(_)) = task_result {
868
- success_count += 1;
869
- }
870
- }
871
-
872
- assert_eq!(success_count, 50);
873
- }
874
-
875
- #[serial]
876
- #[tokio::test]
877
- async fn test_concurrent_extractions_different_mimes() {
878
- use tokio::task::JoinSet;
879
-
880
- let config = Arc::new(ExtractionConfig::default());
881
- let mut tasks = JoinSet::new();
882
-
883
- let mime_types = ["text/plain", "text/markdown"];
884
-
885
- for i in 0..30 {
886
- let config_clone = Arc::clone(&config);
887
- let mime = mime_types[i % mime_types.len()];
888
- tasks.spawn(async move {
889
- let content = format!("test {}", i);
890
- extract_bytes(content.as_bytes(), mime, &config_clone).await
891
- });
892
- }
893
-
894
- let mut success_count = 0;
895
- while let Some(task_result) = tasks.join_next().await {
896
- if let Ok(Ok(_)) = task_result {
897
- success_count += 1;
898
- }
899
- }
900
-
901
- assert_eq!(success_count, 30);
902
- }
903
- }
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
+ }