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,1010 +1,1013 @@
1
- //! Document extractor plugin trait.
2
- //!
3
- //! This module defines the trait for implementing custom document extractors.
4
-
5
- use crate::Result;
6
- use crate::core::config::ExtractionConfig;
7
- use crate::plugins::Plugin;
8
- use crate::types::ExtractionResult;
9
- use async_trait::async_trait;
10
- use std::path::Path;
11
- use std::sync::Arc;
12
-
13
- /// Trait for document extractor plugins.
14
- ///
15
- /// Implement this trait to add support for new document formats or to override
16
- /// built-in extraction behavior with custom logic.
17
- ///
18
- /// # Priority System
19
- ///
20
- /// When multiple extractors support the same MIME type, the registry selects
21
- /// the extractor with the highest priority value. Use this to:
22
- /// - Override built-in extractors (priority > 50)
23
- /// - Provide fallback extractors (priority < 50)
24
- /// - Implement specialized extractors for specific use cases
25
- ///
26
- /// Default priority is 50.
27
- ///
28
- /// # Thread Safety
29
- ///
30
- /// Extractors must be thread-safe (`Send + Sync`) to support concurrent extraction.
31
- ///
32
- /// # Example
33
- ///
34
- /// ```rust
35
- /// use kreuzberg::plugins::{Plugin, DocumentExtractor};
36
- /// use kreuzberg::{Result, ExtractionConfig};
37
- /// use kreuzberg::types::{ExtractionResult, Metadata};
38
- /// use async_trait::async_trait;
39
- /// use std::path::Path;
40
- ///
41
- /// /// Custom PDF extractor with premium features
42
- /// struct PremiumPdfExtractor;
43
- ///
44
- /// impl Plugin for PremiumPdfExtractor {
45
- /// fn name(&self) -> &str { "premium-pdf" }
46
- /// fn version(&self) -> String { "2.0.0".to_string() }
47
- /// fn initialize(&self) -> Result<()> { Ok(()) }
48
- /// fn shutdown(&self) -> Result<()> { Ok(()) }
49
- /// }
50
- ///
51
- /// #[async_trait]
52
- /// impl DocumentExtractor for PremiumPdfExtractor {
53
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
54
- /// -> Result<ExtractionResult> {
55
- /// // Premium extraction logic with better accuracy
56
- /// Ok(ExtractionResult {
57
- /// content: "Premium extracted content".to_string(),
58
- /// mime_type: mime_type.to_string(),
59
- /// metadata: Metadata::default(),
60
- /// tables: vec![],
61
- /// detected_languages: None,
62
- /// chunks: None,
63
- /// images: None,
64
- /// })
65
- /// }
66
- ///
67
- /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
68
- /// -> Result<ExtractionResult> {
69
- /// let bytes = std::fs::read(path)?;
70
- /// self.extract_bytes(&bytes, mime_type, config).await
71
- /// }
72
- ///
73
- /// fn supported_mime_types(&self) -> &[&str] {
74
- /// &["application/pdf"]
75
- /// }
76
- ///
77
- /// fn priority(&self) -> i32 {
78
- /// 100 // Higher than default (50) - will be preferred
79
- /// }
80
- /// }
81
- /// ```
82
- #[async_trait]
83
- pub trait DocumentExtractor: Plugin {
84
- /// Extract content from a byte array.
85
- ///
86
- /// This is the core extraction method that processes in-memory document data.
87
- ///
88
- /// # Arguments
89
- ///
90
- /// * `content` - Raw document bytes
91
- /// * `mime_type` - MIME type of the document (already validated)
92
- /// * `config` - Extraction configuration
93
- ///
94
- /// # Returns
95
- ///
96
- /// An `ExtractionResult` containing the extracted content, metadata, and tables.
97
- ///
98
- /// # Errors
99
- ///
100
- /// - `KreuzbergError::Parsing` - Document parsing failed
101
- /// - `KreuzbergError::Validation` - Invalid document structure
102
- /// - `KreuzbergError::Io` - I/O errors (these always bubble up)
103
- /// - `KreuzbergError::MissingDependency` - Required dependency not available
104
- ///
105
- /// # Example
106
- ///
107
- /// ```rust,no_run
108
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
109
- /// # use kreuzberg::{Result, ExtractionConfig};
110
- /// # use kreuzberg::types::{ExtractionResult, Metadata};
111
- /// # use async_trait::async_trait;
112
- /// # use std::path::Path;
113
- /// # struct MyExtractor;
114
- /// # impl Plugin for MyExtractor {
115
- /// # fn name(&self) -> &str { "my-extractor" }
116
- /// # fn version(&self) -> String { "1.0.0".to_string() }
117
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
118
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
119
- /// # }
120
- /// # #[async_trait]
121
- /// # impl DocumentExtractor for MyExtractor {
122
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
123
- /// # fn priority(&self) -> i32 { 50 }
124
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
125
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
126
- /// -> Result<ExtractionResult> {
127
- /// // Parse document
128
- /// let text = String::from_utf8_lossy(content).to_string();
129
- ///
130
- /// // Extract metadata
131
- /// let mut metadata = Metadata::default();
132
- /// metadata.additional.insert("byte_count".to_string(), serde_json::json!(content.len()));
133
- ///
134
- /// Ok(ExtractionResult {
135
- /// content: text,
136
- /// mime_type: mime_type.to_string(),
137
- /// metadata,
138
- /// tables: vec![],
139
- /// detected_languages: None,
140
- /// chunks: None,
141
- /// images: None,
142
- /// })
143
- /// }
144
- /// # }
145
- /// ```
146
- async fn extract_bytes(
147
- &self,
148
- content: &[u8],
149
- mime_type: &str,
150
- config: &ExtractionConfig,
151
- ) -> Result<ExtractionResult>;
152
-
153
- /// Extract content from a file.
154
- ///
155
- /// Default implementation reads the file and calls `extract_bytes`.
156
- /// Override for custom file handling, streaming, or memory optimizations.
157
- ///
158
- /// # Arguments
159
- ///
160
- /// * `path` - Path to the document file
161
- /// * `mime_type` - MIME type of the document (already validated)
162
- /// * `config` - Extraction configuration
163
- ///
164
- /// # Errors
165
- ///
166
- /// Same as `extract_bytes`, plus file I/O errors.
167
- ///
168
- /// # Example - Custom File Handling
169
- ///
170
- /// ```rust,no_run
171
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
172
- /// # use kreuzberg::{Result, ExtractionResult, ExtractionConfig};
173
- /// # use kreuzberg::types::Metadata;
174
- /// # use async_trait::async_trait;
175
- /// # use std::path::Path;
176
- /// # struct StreamingExtractor;
177
- /// # impl Plugin for StreamingExtractor {
178
- /// # fn name(&self) -> &str { "streaming" }
179
- /// # fn version(&self) -> String { "1.0.0".to_string() }
180
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
181
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
182
- /// # }
183
- /// # #[async_trait]
184
- /// # impl DocumentExtractor for StreamingExtractor {
185
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
186
- /// # fn priority(&self) -> i32 { 50 }
187
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
188
- /// /// Override for memory-efficient streaming extraction
189
- /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
190
- /// -> Result<ExtractionResult> {
191
- /// // Stream large files instead of loading entirely into memory
192
- /// let mut content = String::new();
193
- ///
194
- /// // Use buffered reader for streaming
195
- /// use std::io::{BufRead, BufReader};
196
- /// let file = std::fs::File::open(path)?;
197
- /// let reader = BufReader::new(file);
198
- ///
199
- /// for line in reader.lines() {
200
- /// content.push_str(&line?);
201
- /// content.push('\n');
202
- /// }
203
- ///
204
- /// Ok(ExtractionResult {
205
- /// content,
206
- /// mime_type: mime_type.to_string(),
207
- /// metadata: Metadata::default(),
208
- /// tables: vec![],
209
- /// detected_languages: None,
210
- /// chunks: None,
211
- /// images: None,
212
- /// })
213
- /// }
214
- /// # }
215
- /// ```
216
- async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
217
- use crate::core::io;
218
- let bytes = io::read_file_async(path).await?;
219
- self.extract_bytes(&bytes, mime_type, config).await
220
- }
221
-
222
- /// Get the list of MIME types supported by this extractor.
223
- ///
224
- /// Can include exact MIME types and prefix patterns:
225
- /// - Exact: `"application/pdf"`, `"text/plain"`
226
- /// - Prefix: `"image/*"` (matches any image type)
227
- ///
228
- /// # Returns
229
- ///
230
- /// A slice of MIME type strings.
231
- ///
232
- /// # Example
233
- ///
234
- /// ```rust
235
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
236
- /// # use kreuzberg::Result;
237
- /// # use async_trait::async_trait;
238
- /// # use std::path::Path;
239
- /// # struct MultiFormatExtractor;
240
- /// # impl Plugin for MultiFormatExtractor {
241
- /// # fn name(&self) -> &str { "multi-format" }
242
- /// # fn version(&self) -> String { "1.0.0".to_string() }
243
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
244
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
245
- /// # }
246
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
247
- /// # #[async_trait]
248
- /// # impl DocumentExtractor for MultiFormatExtractor {
249
- /// # fn priority(&self) -> i32 { 50 }
250
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
251
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
252
- /// fn supported_mime_types(&self) -> &[&str] {
253
- /// &[
254
- /// "text/plain",
255
- /// "text/markdown",
256
- /// "application/json",
257
- /// "application/xml",
258
- /// "text/html",
259
- /// ]
260
- /// }
261
- /// # }
262
- /// ```
263
- fn supported_mime_types(&self) -> &[&str];
264
-
265
- /// Get the priority of this extractor.
266
- ///
267
- /// Higher priority extractors are preferred when multiple extractors
268
- /// support the same MIME type.
269
- ///
270
- /// # Priority Guidelines
271
- ///
272
- /// - **0-25**: Fallback/low-quality extractors
273
- /// - **26-49**: Alternative extractors
274
- /// - **50**: Default priority (built-in extractors)
275
- /// - **51-75**: Premium/enhanced extractors
276
- /// - **76-100**: Specialized/high-priority extractors
277
- ///
278
- /// # Returns
279
- ///
280
- /// Priority value (default: 50)
281
- ///
282
- /// # Example
283
- ///
284
- /// ```rust
285
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
286
- /// # use kreuzberg::Result;
287
- /// # use async_trait::async_trait;
288
- /// # use std::path::Path;
289
- /// # struct FallbackExtractor;
290
- /// # impl Plugin for FallbackExtractor {
291
- /// # fn name(&self) -> &str { "fallback" }
292
- /// # fn version(&self) -> String { "1.0.0".to_string() }
293
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
294
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
295
- /// # }
296
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
297
- /// # #[async_trait]
298
- /// # impl DocumentExtractor for FallbackExtractor {
299
- /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
300
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
301
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
302
- /// fn priority(&self) -> i32 {
303
- /// 10 // Low priority - only used as fallback
304
- /// }
305
- /// # }
306
- /// ```
307
- fn priority(&self) -> i32 {
308
- 50
309
- }
310
-
311
- /// Optional: Check if this extractor can handle a specific file.
312
- ///
313
- /// Allows for more sophisticated detection beyond MIME types.
314
- /// Defaults to `true` (rely on MIME type matching).
315
- ///
316
- /// # Arguments
317
- ///
318
- /// * `path` - Path to the file to check
319
- /// * `mime_type` - Detected MIME type
320
- ///
321
- /// # Returns
322
- ///
323
- /// `true` if the extractor can handle this file, `false` otherwise.
324
- ///
325
- /// # Example
326
- ///
327
- /// ```rust,no_run
328
- /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
329
- /// # use kreuzberg::Result;
330
- /// # use async_trait::async_trait;
331
- /// # use std::path::Path;
332
- /// # struct SmartExtractor;
333
- /// # impl Plugin for SmartExtractor {
334
- /// # fn name(&self) -> &str { "smart" }
335
- /// # fn version(&self) -> String { "1.0.0".to_string() }
336
- /// # fn initialize(&self) -> Result<()> { Ok(()) }
337
- /// # fn shutdown(&self) -> Result<()> { Ok(()) }
338
- /// # }
339
- /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
340
- /// # #[async_trait]
341
- /// # impl DocumentExtractor for SmartExtractor {
342
- /// # fn supported_mime_types(&self) -> &[&str] { &["application/pdf"] }
343
- /// # fn priority(&self) -> i32 { 50 }
344
- /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
345
- /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
346
- /// /// Only handle PDFs that are searchable (have text layer)
347
- /// fn can_handle(&self, path: &Path, mime_type: &str) -> bool {
348
- /// if mime_type != "application/pdf" {
349
- /// return false;
350
- /// }
351
- ///
352
- /// // Check if PDF has text layer (simplified example)
353
- /// // In real implementation, analyze PDF structure here
354
- /// let _ = path; // Use path for PDF analysis
355
- /// true // Simplified - always accept
356
- /// }
357
- /// # }
358
- /// ```
359
- fn can_handle(&self, _path: &Path, _mime_type: &str) -> bool {
360
- true
361
- }
362
- }
363
-
364
- // Public registration APIs
365
-
366
- /// Register a document extractor with the global registry.
367
- ///
368
- /// The extractor will be registered for all MIME types it supports and will be
369
- /// available for document extraction. The extractor's `name()` method is used as
370
- /// the registration name.
371
- ///
372
- /// # Arguments
373
- ///
374
- /// * `extractor` - The extractor implementation wrapped in Arc
375
- ///
376
- /// # Returns
377
- ///
378
- /// - `Ok(())` if registration succeeded
379
- /// - `Err(...)` if validation failed or initialization failed
380
- ///
381
- /// # Errors
382
- ///
383
- /// - `KreuzbergError::Validation` - Invalid extractor name (empty or contains whitespace)
384
- /// - Any error from the extractor's `initialize()` method
385
- ///
386
- /// # Example
387
- ///
388
- /// ```rust
389
- /// use kreuzberg::plugins::{Plugin, DocumentExtractor, register_extractor};
390
- /// use kreuzberg::{Result, ExtractionConfig};
391
- /// use kreuzberg::types::{ExtractionResult, Metadata};
392
- /// use async_trait::async_trait;
393
- /// use std::sync::Arc;
394
- /// use std::path::Path;
395
- ///
396
- /// struct CustomExtractor;
397
- ///
398
- /// impl Plugin for CustomExtractor {
399
- /// fn name(&self) -> &str { "custom-extractor" }
400
- /// fn version(&self) -> String { "1.0.0".to_string() }
401
- /// fn initialize(&self) -> Result<()> { Ok(()) }
402
- /// fn shutdown(&self) -> Result<()> { Ok(()) }
403
- /// }
404
- ///
405
- /// #[async_trait]
406
- /// impl DocumentExtractor for CustomExtractor {
407
- /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, _: &ExtractionConfig)
408
- /// -> Result<ExtractionResult> {
409
- /// Ok(ExtractionResult {
410
- /// content: String::from_utf8_lossy(content).to_string(),
411
- /// mime_type: mime_type.to_string(),
412
- /// metadata: Metadata::default(),
413
- /// tables: vec![],
414
- /// detected_languages: None,
415
- /// chunks: None,
416
- /// images: None,
417
- /// })
418
- /// }
419
- ///
420
- /// fn supported_mime_types(&self) -> &[&str] {
421
- /// &["text/custom"]
422
- /// }
423
- /// }
424
- ///
425
- /// # tokio_test::block_on(async {
426
- /// let extractor = Arc::new(CustomExtractor);
427
- /// register_extractor(extractor)?;
428
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
429
- /// # });
430
- /// ```
431
- pub fn register_extractor(extractor: Arc<dyn DocumentExtractor>) -> crate::Result<()> {
432
- use crate::plugins::registry::get_document_extractor_registry;
433
-
434
- let registry = get_document_extractor_registry();
435
- let mut registry = registry
436
- .write()
437
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
438
-
439
- registry.register(extractor)
440
- }
441
-
442
- /// Unregister a document extractor by name.
443
- ///
444
- /// Removes the extractor from the global registry and calls its `shutdown()` method.
445
- ///
446
- /// # Arguments
447
- ///
448
- /// * `name` - Name of the extractor to unregister
449
- ///
450
- /// # Returns
451
- ///
452
- /// - `Ok(())` if the extractor was unregistered or didn't exist
453
- /// - `Err(...)` if the shutdown method failed
454
- ///
455
- /// # Example
456
- ///
457
- /// ```rust
458
- /// use kreuzberg::plugins::unregister_extractor;
459
- ///
460
- /// # tokio_test::block_on(async {
461
- /// unregister_extractor("custom-extractor")?;
462
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
463
- /// # });
464
- /// ```
465
- pub fn unregister_extractor(name: &str) -> crate::Result<()> {
466
- use crate::plugins::registry::get_document_extractor_registry;
467
-
468
- let registry = get_document_extractor_registry();
469
- let mut registry = registry
470
- .write()
471
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
472
-
473
- registry.remove(name)
474
- }
475
-
476
- /// List all registered extractors.
477
- ///
478
- /// Returns the names of all extractors currently registered in the global registry.
479
- ///
480
- /// # Returns
481
- ///
482
- /// A vector of extractor names.
483
- ///
484
- /// # Example
485
- ///
486
- /// ```rust
487
- /// use kreuzberg::plugins::list_extractors;
488
- ///
489
- /// # tokio_test::block_on(async {
490
- /// let extractors = list_extractors()?;
491
- /// for name in extractors {
492
- /// println!("Registered extractor: {}", name);
493
- /// }
494
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
495
- /// # });
496
- /// ```
497
- pub fn list_extractors() -> crate::Result<Vec<String>> {
498
- use crate::plugins::registry::get_document_extractor_registry;
499
-
500
- let registry = get_document_extractor_registry();
501
- let registry = registry
502
- .read()
503
- .expect("~keep Failed to acquire read lock on extractor registry"); // ~keep
504
-
505
- Ok(registry.list())
506
- }
507
-
508
- /// Clear all extractors from the global registry.
509
- ///
510
- /// Removes all extractors and calls their `shutdown()` methods.
511
- ///
512
- /// # Returns
513
- ///
514
- /// - `Ok(())` if all extractors were cleared successfully
515
- /// - `Err(...)` if any shutdown method failed
516
- ///
517
- /// # Example
518
- ///
519
- /// ```rust
520
- /// use kreuzberg::plugins::clear_extractors;
521
- ///
522
- /// # tokio_test::block_on(async {
523
- /// clear_extractors()?;
524
- /// # Ok::<(), kreuzberg::KreuzbergError>(())
525
- /// # });
526
- /// ```
527
- pub fn clear_extractors() -> crate::Result<()> {
528
- use crate::plugins::registry::get_document_extractor_registry;
529
-
530
- let registry = get_document_extractor_registry();
531
- let mut registry = registry
532
- .write()
533
- .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
534
-
535
- registry.shutdown_all()
536
- }
537
-
538
- #[cfg(test)]
539
- mod tests {
540
- use super::*;
541
-
542
- struct MockExtractor {
543
- mime_types: Vec<&'static str>,
544
- priority: i32,
545
- }
546
-
547
- impl Plugin for MockExtractor {
548
- fn name(&self) -> &str {
549
- "mock-extractor"
550
- }
551
-
552
- fn version(&self) -> String {
553
- "1.0.0".to_string()
554
- }
555
-
556
- fn initialize(&self) -> Result<()> {
557
- Ok(())
558
- }
559
-
560
- fn shutdown(&self) -> Result<()> {
561
- Ok(())
562
- }
563
- }
564
-
565
- #[async_trait]
566
- impl DocumentExtractor for MockExtractor {
567
- async fn extract_bytes(
568
- &self,
569
- content: &[u8],
570
- mime_type: &str,
571
- _config: &ExtractionConfig,
572
- ) -> Result<ExtractionResult> {
573
- Ok(ExtractionResult {
574
- content: String::from_utf8_lossy(content).to_string(),
575
- mime_type: mime_type.to_string(),
576
- metadata: crate::types::Metadata::default(),
577
- tables: vec![],
578
- detected_languages: None,
579
- chunks: None,
580
- images: None,
581
- })
582
- }
583
-
584
- fn supported_mime_types(&self) -> &[&str] {
585
- &self.mime_types
586
- }
587
-
588
- fn priority(&self) -> i32 {
589
- self.priority
590
- }
591
- }
592
-
593
- #[tokio::test]
594
- async fn test_document_extractor_extract_bytes() {
595
- let extractor = MockExtractor {
596
- mime_types: vec!["text/plain"],
597
- priority: 50,
598
- };
599
-
600
- let config = ExtractionConfig::default();
601
- let result = extractor
602
- .extract_bytes(b"test content", "text/plain", &config)
603
- .await
604
- .unwrap();
605
-
606
- assert_eq!(result.content, "test content");
607
- assert_eq!(result.mime_type, "text/plain");
608
- }
609
-
610
- #[test]
611
- fn test_document_extractor_supported_mime_types() {
612
- let extractor = MockExtractor {
613
- mime_types: vec!["text/plain", "text/markdown"],
614
- priority: 50,
615
- };
616
-
617
- let supported = extractor.supported_mime_types();
618
- assert_eq!(supported.len(), 2);
619
- assert!(supported.contains(&"text/plain"));
620
- assert!(supported.contains(&"text/markdown"));
621
- }
622
-
623
- #[test]
624
- fn test_document_extractor_priority() {
625
- let low_priority = MockExtractor {
626
- mime_types: vec!["text/plain"],
627
- priority: 10,
628
- };
629
-
630
- let high_priority = MockExtractor {
631
- mime_types: vec!["text/plain"],
632
- priority: 100,
633
- };
634
-
635
- assert_eq!(low_priority.priority(), 10);
636
- assert_eq!(high_priority.priority(), 100);
637
- }
638
-
639
- #[test]
640
- fn test_document_extractor_can_handle_default() {
641
- let extractor = MockExtractor {
642
- mime_types: vec!["text/plain"],
643
- priority: 50,
644
- };
645
-
646
- use std::path::PathBuf;
647
- let path = PathBuf::from("test.txt");
648
-
649
- assert!(extractor.can_handle(&path, "text/plain"));
650
- assert!(extractor.can_handle(&path, "application/pdf"));
651
- }
652
-
653
- #[tokio::test]
654
- async fn test_document_extractor_extract_file_default_impl() {
655
- use std::io::Write;
656
- use tempfile::NamedTempFile;
657
-
658
- let extractor = MockExtractor {
659
- mime_types: vec!["text/plain"],
660
- priority: 50,
661
- };
662
-
663
- let mut temp_file = NamedTempFile::new().unwrap();
664
- temp_file.write_all(b"file content").unwrap();
665
- let path = temp_file.path();
666
-
667
- let config = ExtractionConfig::default();
668
- let result = extractor.extract_file(path, "text/plain", &config).await.unwrap();
669
-
670
- assert_eq!(result.content, "file content");
671
- assert_eq!(result.mime_type, "text/plain");
672
- }
673
-
674
- #[tokio::test]
675
- async fn test_document_extractor_empty_content() {
676
- let extractor = MockExtractor {
677
- mime_types: vec!["text/plain"],
678
- priority: 50,
679
- };
680
-
681
- let config = ExtractionConfig::default();
682
- let result = extractor.extract_bytes(b"", "text/plain", &config).await.unwrap();
683
-
684
- assert_eq!(result.content, "");
685
- assert_eq!(result.mime_type, "text/plain");
686
- }
687
-
688
- #[tokio::test]
689
- async fn test_document_extractor_non_utf8_content() {
690
- let extractor = MockExtractor {
691
- mime_types: vec!["text/plain"],
692
- priority: 50,
693
- };
694
-
695
- let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
696
- let config = ExtractionConfig::default();
697
- let result = extractor
698
- .extract_bytes(&invalid_utf8, "text/plain", &config)
699
- .await
700
- .unwrap();
701
-
702
- assert!(!result.content.is_empty());
703
- }
704
-
705
- #[test]
706
- fn test_document_extractor_plugin_interface() {
707
- let extractor = MockExtractor {
708
- mime_types: vec!["text/plain"],
709
- priority: 50,
710
- };
711
-
712
- assert_eq!(extractor.name(), "mock-extractor");
713
- assert_eq!(extractor.version(), "1.0.0");
714
- assert!(extractor.initialize().is_ok());
715
- assert!(extractor.shutdown().is_ok());
716
- }
717
-
718
- #[test]
719
- fn test_document_extractor_default_priority() {
720
- struct DefaultPriorityExtractor;
721
-
722
- impl Plugin for DefaultPriorityExtractor {
723
- fn name(&self) -> &str {
724
- "default"
725
- }
726
- fn version(&self) -> String {
727
- "1.0.0".to_string()
728
- }
729
- fn initialize(&self) -> Result<()> {
730
- Ok(())
731
- }
732
- fn shutdown(&self) -> Result<()> {
733
- Ok(())
734
- }
735
- }
736
-
737
- #[async_trait]
738
- impl DocumentExtractor for DefaultPriorityExtractor {
739
- async fn extract_bytes(
740
- &self,
741
- _content: &[u8],
742
- _mime_type: &str,
743
- _config: &ExtractionConfig,
744
- ) -> Result<ExtractionResult> {
745
- Ok(ExtractionResult {
746
- content: String::new(),
747
- mime_type: String::new(),
748
- metadata: crate::types::Metadata::default(),
749
- tables: vec![],
750
- detected_languages: None,
751
- chunks: None,
752
- images: None,
753
- })
754
- }
755
-
756
- fn supported_mime_types(&self) -> &[&str] {
757
- &["text/plain"]
758
- }
759
- }
760
-
761
- let extractor = DefaultPriorityExtractor;
762
- assert_eq!(extractor.priority(), 50);
763
- }
764
-
765
- #[test]
766
- fn test_document_extractor_empty_mime_types() {
767
- let extractor = MockExtractor {
768
- mime_types: vec![],
769
- priority: 50,
770
- };
771
-
772
- assert_eq!(extractor.supported_mime_types().len(), 0);
773
- }
774
-
775
- #[test]
776
- fn test_document_extractor_wildcard_mime_types() {
777
- let extractor = MockExtractor {
778
- mime_types: vec!["text/*", "image/*"],
779
- priority: 50,
780
- };
781
-
782
- let supported = extractor.supported_mime_types();
783
- assert_eq!(supported.len(), 2);
784
- assert!(supported.contains(&"text/*"));
785
- assert!(supported.contains(&"image/*"));
786
- }
787
-
788
- #[test]
789
- fn test_document_extractor_priority_ranges() {
790
- let fallback = MockExtractor {
791
- mime_types: vec!["text/plain"],
792
- priority: 10,
793
- };
794
- let alternative = MockExtractor {
795
- mime_types: vec!["text/plain"],
796
- priority: 40,
797
- };
798
- let default = MockExtractor {
799
- mime_types: vec!["text/plain"],
800
- priority: 50,
801
- };
802
- let premium = MockExtractor {
803
- mime_types: vec!["text/plain"],
804
- priority: 75,
805
- };
806
- let specialized = MockExtractor {
807
- mime_types: vec!["text/plain"],
808
- priority: 100,
809
- };
810
-
811
- assert!(fallback.priority() < alternative.priority());
812
- assert!(alternative.priority() < default.priority());
813
- assert!(default.priority() < premium.priority());
814
- assert!(premium.priority() < specialized.priority());
815
- }
816
-
817
- #[tokio::test]
818
- async fn test_document_extractor_preserves_mime_type() {
819
- let extractor = MockExtractor {
820
- mime_types: vec!["application/json"],
821
- priority: 50,
822
- };
823
-
824
- let config = ExtractionConfig::default();
825
- let result = extractor
826
- .extract_bytes(b"{\"key\":\"value\"}", "application/json", &config)
827
- .await
828
- .unwrap();
829
-
830
- assert_eq!(result.mime_type, "application/json");
831
- }
832
-
833
- // Tests for public registration APIs
834
-
835
- #[test]
836
- fn test_register_extractor() {
837
- use std::sync::Arc;
838
-
839
- let extractor = Arc::new(MockExtractor {
840
- mime_types: vec!["text/test-register"],
841
- priority: 50,
842
- });
843
- let result = super::register_extractor(extractor);
844
- assert!(result.is_ok());
845
-
846
- let _ = super::unregister_extractor("mock-extractor");
847
- }
848
-
849
- #[test]
850
- fn test_unregister_extractor() {
851
- use std::sync::Arc;
852
-
853
- let extractor = Arc::new(MockExtractor {
854
- mime_types: vec!["text/test-unregister"],
855
- priority: 50,
856
- });
857
- super::register_extractor(extractor).unwrap();
858
-
859
- let result = super::unregister_extractor("mock-extractor");
860
- assert!(result.is_ok());
861
- }
862
-
863
- #[test]
864
- fn test_unregister_nonexistent_extractor() {
865
- let result = super::unregister_extractor("nonexistent-extractor-xyz");
866
- assert!(result.is_ok());
867
- }
868
-
869
- #[test]
870
- fn test_list_extractors() {
871
- use std::sync::Arc;
872
-
873
- super::clear_extractors().unwrap();
874
-
875
- let extractor1 = Arc::new(MockExtractor {
876
- mime_types: vec!["text/test-list-1"],
877
- priority: 50,
878
- });
879
- let extractor2 = Arc::new(MockExtractor {
880
- mime_types: vec!["text/test-list-2"],
881
- priority: 51,
882
- });
883
-
884
- let list_before = super::list_extractors().unwrap();
885
- assert_eq!(list_before.len(), 0);
886
-
887
- super::register_extractor(extractor1).unwrap();
888
- super::register_extractor(extractor2).unwrap();
889
-
890
- let list = super::list_extractors().unwrap();
891
- // Both extractors have the same name, so only one will be registered
892
- assert_eq!(list.len(), 1);
893
- assert!(list.contains(&"mock-extractor".to_string()));
894
-
895
- super::unregister_extractor("mock-extractor").unwrap();
896
- }
897
-
898
- #[test]
899
- fn test_clear_extractors() {
900
- use std::sync::Arc;
901
-
902
- super::clear_extractors().unwrap();
903
-
904
- let extractor1 = Arc::new(MockExtractor {
905
- mime_types: vec!["text/test-clear-1"],
906
- priority: 50,
907
- });
908
- let extractor2 = Arc::new(MockExtractor {
909
- mime_types: vec!["text/test-clear-2"],
910
- priority: 51,
911
- });
912
-
913
- super::register_extractor(extractor1).unwrap();
914
- super::register_extractor(extractor2).unwrap();
915
-
916
- let result = super::clear_extractors();
917
- assert!(result.is_ok());
918
-
919
- let list = super::list_extractors().unwrap();
920
- assert_eq!(list.len(), 0);
921
- }
922
-
923
- #[test]
924
- fn test_register_extractor_with_invalid_name() {
925
- use std::sync::Arc;
926
-
927
- struct InvalidNameExtractor;
928
- impl Plugin for InvalidNameExtractor {
929
- fn name(&self) -> &str {
930
- "invalid name with spaces"
931
- }
932
- fn version(&self) -> String {
933
- "1.0.0".to_string()
934
- }
935
- fn initialize(&self) -> Result<()> {
936
- Ok(())
937
- }
938
- fn shutdown(&self) -> Result<()> {
939
- Ok(())
940
- }
941
- }
942
-
943
- #[async_trait]
944
- impl DocumentExtractor for InvalidNameExtractor {
945
- async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
946
- Ok(ExtractionResult {
947
- content: String::new(),
948
- mime_type: String::new(),
949
- metadata: crate::types::Metadata::default(),
950
- tables: vec![],
951
- detected_languages: None,
952
- chunks: None,
953
- images: None,
954
- })
955
- }
956
-
957
- fn supported_mime_types(&self) -> &[&str] {
958
- &["text/plain"]
959
- }
960
- }
961
-
962
- let extractor = Arc::new(InvalidNameExtractor);
963
- let result = super::register_extractor(extractor);
964
- assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
965
- }
966
-
967
- #[test]
968
- fn test_register_extractor_with_empty_name() {
969
- use std::sync::Arc;
970
-
971
- struct EmptyNameExtractor;
972
- impl Plugin for EmptyNameExtractor {
973
- fn name(&self) -> &str {
974
- ""
975
- }
976
- fn version(&self) -> String {
977
- "1.0.0".to_string()
978
- }
979
- fn initialize(&self) -> Result<()> {
980
- Ok(())
981
- }
982
- fn shutdown(&self) -> Result<()> {
983
- Ok(())
984
- }
985
- }
986
-
987
- #[async_trait]
988
- impl DocumentExtractor for EmptyNameExtractor {
989
- async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
990
- Ok(ExtractionResult {
991
- content: String::new(),
992
- mime_type: String::new(),
993
- metadata: crate::types::Metadata::default(),
994
- tables: vec![],
995
- detected_languages: None,
996
- chunks: None,
997
- images: None,
998
- })
999
- }
1000
-
1001
- fn supported_mime_types(&self) -> &[&str] {
1002
- &["text/plain"]
1003
- }
1004
- }
1005
-
1006
- let extractor = Arc::new(EmptyNameExtractor);
1007
- let result = super::register_extractor(extractor);
1008
- assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
1009
- }
1010
- }
1
+ //! Document extractor plugin trait.
2
+ //!
3
+ //! This module defines the trait for implementing custom document extractors.
4
+
5
+ use crate::Result;
6
+ use crate::core::config::ExtractionConfig;
7
+ use crate::plugins::Plugin;
8
+ use crate::types::ExtractionResult;
9
+ use async_trait::async_trait;
10
+ use std::path::Path;
11
+ use std::sync::Arc;
12
+
13
+ /// Trait for document extractor plugins.
14
+ ///
15
+ /// Implement this trait to add support for new document formats or to override
16
+ /// built-in extraction behavior with custom logic.
17
+ ///
18
+ /// # Priority System
19
+ ///
20
+ /// When multiple extractors support the same MIME type, the registry selects
21
+ /// the extractor with the highest priority value. Use this to:
22
+ /// - Override built-in extractors (priority > 50)
23
+ /// - Provide fallback extractors (priority < 50)
24
+ /// - Implement specialized extractors for specific use cases
25
+ ///
26
+ /// Default priority is 50.
27
+ ///
28
+ /// # Thread Safety
29
+ ///
30
+ /// Extractors must be thread-safe (`Send + Sync`) to support concurrent extraction.
31
+ ///
32
+ /// # Example
33
+ ///
34
+ /// ```rust
35
+ /// use kreuzberg::plugins::{Plugin, DocumentExtractor};
36
+ /// use kreuzberg::{Result, ExtractionConfig};
37
+ /// use kreuzberg::types::{ExtractionResult, Metadata};
38
+ /// use async_trait::async_trait;
39
+ /// use std::path::Path;
40
+ ///
41
+ /// /// Custom PDF extractor with premium features
42
+ /// struct PremiumPdfExtractor;
43
+ ///
44
+ /// impl Plugin for PremiumPdfExtractor {
45
+ /// fn name(&self) -> &str { "premium-pdf" }
46
+ /// fn version(&self) -> String { "2.0.0".to_string() }
47
+ /// fn initialize(&self) -> Result<()> { Ok(()) }
48
+ /// fn shutdown(&self) -> Result<()> { Ok(()) }
49
+ /// }
50
+ ///
51
+ /// #[async_trait]
52
+ /// impl DocumentExtractor for PremiumPdfExtractor {
53
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
54
+ /// -> Result<ExtractionResult> {
55
+ /// // Premium extraction logic with better accuracy
56
+ /// Ok(ExtractionResult {
57
+ /// content: "Premium extracted content".to_string(),
58
+ /// mime_type: mime_type.to_string(),
59
+ /// metadata: Metadata::default(),
60
+ /// tables: vec![],
61
+ /// detected_languages: None,
62
+ /// chunks: None,
63
+ /// images: None,
64
+ /// })
65
+ /// }
66
+ ///
67
+ /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
68
+ /// -> Result<ExtractionResult> {
69
+ /// let bytes = std::fs::read(path)?;
70
+ /// self.extract_bytes(&bytes, mime_type, config).await
71
+ /// }
72
+ ///
73
+ /// fn supported_mime_types(&self) -> &[&str] {
74
+ /// &["application/pdf"]
75
+ /// }
76
+ ///
77
+ /// fn priority(&self) -> i32 {
78
+ /// 100 // Higher than default (50) - will be preferred
79
+ /// }
80
+ /// }
81
+ /// ```
82
+ #[async_trait]
83
+ pub trait DocumentExtractor: Plugin {
84
+ /// Extract content from a byte array.
85
+ ///
86
+ /// This is the core extraction method that processes in-memory document data.
87
+ ///
88
+ /// # Arguments
89
+ ///
90
+ /// * `content` - Raw document bytes
91
+ /// * `mime_type` - MIME type of the document (already validated)
92
+ /// * `config` - Extraction configuration
93
+ ///
94
+ /// # Returns
95
+ ///
96
+ /// An `ExtractionResult` containing the extracted content, metadata, and tables.
97
+ ///
98
+ /// # Errors
99
+ ///
100
+ /// - `KreuzbergError::Parsing` - Document parsing failed
101
+ /// - `KreuzbergError::Validation` - Invalid document structure
102
+ /// - `KreuzbergError::Io` - I/O errors (these always bubble up)
103
+ /// - `KreuzbergError::MissingDependency` - Required dependency not available
104
+ ///
105
+ /// # Example
106
+ ///
107
+ /// ```rust,no_run
108
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
109
+ /// # use kreuzberg::{Result, ExtractionConfig};
110
+ /// # use kreuzberg::types::{ExtractionResult, Metadata};
111
+ /// # use async_trait::async_trait;
112
+ /// # use std::path::Path;
113
+ /// # struct MyExtractor;
114
+ /// # impl Plugin for MyExtractor {
115
+ /// # fn name(&self) -> &str { "my-extractor" }
116
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
117
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
118
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
119
+ /// # }
120
+ /// # #[async_trait]
121
+ /// # impl DocumentExtractor for MyExtractor {
122
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
123
+ /// # fn priority(&self) -> i32 { 50 }
124
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
125
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)
126
+ /// -> Result<ExtractionResult> {
127
+ /// // Parse document
128
+ /// let text = String::from_utf8_lossy(content).to_string();
129
+ ///
130
+ /// // Extract metadata
131
+ /// let mut metadata = Metadata::default();
132
+ /// metadata.additional.insert("byte_count".to_string(), serde_json::json!(content.len()));
133
+ ///
134
+ /// Ok(ExtractionResult {
135
+ /// content: text,
136
+ /// mime_type: mime_type.to_string(),
137
+ /// metadata,
138
+ /// tables: vec![],
139
+ /// detected_languages: None,
140
+ /// chunks: None,
141
+ /// images: None,
142
+ /// })
143
+ /// }
144
+ /// # }
145
+ /// ```
146
+ async fn extract_bytes(
147
+ &self,
148
+ content: &[u8],
149
+ mime_type: &str,
150
+ config: &ExtractionConfig,
151
+ ) -> Result<ExtractionResult>;
152
+
153
+ /// Extract content from a file.
154
+ ///
155
+ /// Default implementation reads the file and calls `extract_bytes`.
156
+ /// Override for custom file handling, streaming, or memory optimizations.
157
+ ///
158
+ /// # Arguments
159
+ ///
160
+ /// * `path` - Path to the document file
161
+ /// * `mime_type` - MIME type of the document (already validated)
162
+ /// * `config` - Extraction configuration
163
+ ///
164
+ /// # Errors
165
+ ///
166
+ /// Same as `extract_bytes`, plus file I/O errors.
167
+ ///
168
+ /// # Example - Custom File Handling
169
+ ///
170
+ /// ```rust,no_run
171
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
172
+ /// # use kreuzberg::{Result, ExtractionResult, ExtractionConfig};
173
+ /// # use kreuzberg::types::Metadata;
174
+ /// # use async_trait::async_trait;
175
+ /// # use std::path::Path;
176
+ /// # struct StreamingExtractor;
177
+ /// # impl Plugin for StreamingExtractor {
178
+ /// # fn name(&self) -> &str { "streaming" }
179
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
180
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
181
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
182
+ /// # }
183
+ /// # #[async_trait]
184
+ /// # impl DocumentExtractor for StreamingExtractor {
185
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
186
+ /// # fn priority(&self) -> i32 { 50 }
187
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
188
+ /// /// Override for memory-efficient streaming extraction
189
+ /// async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig)
190
+ /// -> Result<ExtractionResult> {
191
+ /// // Stream large files instead of loading entirely into memory
192
+ /// let mut content = String::new();
193
+ ///
194
+ /// // Use buffered reader for streaming
195
+ /// use std::io::{BufRead, BufReader};
196
+ /// let file = std::fs::File::open(path)?;
197
+ /// let reader = BufReader::new(file);
198
+ ///
199
+ /// for line in reader.lines() {
200
+ /// content.push_str(&line?);
201
+ /// content.push('\n');
202
+ /// }
203
+ ///
204
+ /// Ok(ExtractionResult {
205
+ /// content,
206
+ /// mime_type: mime_type.to_string(),
207
+ /// metadata: Metadata::default(),
208
+ /// tables: vec![],
209
+ /// detected_languages: None,
210
+ /// chunks: None,
211
+ /// images: None,
212
+ /// })
213
+ /// }
214
+ /// # }
215
+ /// ```
216
+ async fn extract_file(&self, path: &Path, mime_type: &str, config: &ExtractionConfig) -> Result<ExtractionResult> {
217
+ use crate::core::io;
218
+ let bytes = io::read_file_async(path).await?;
219
+ self.extract_bytes(&bytes, mime_type, config).await
220
+ }
221
+
222
+ /// Get the list of MIME types supported by this extractor.
223
+ ///
224
+ /// Can include exact MIME types and prefix patterns:
225
+ /// - Exact: `"application/pdf"`, `"text/plain"`
226
+ /// - Prefix: `"image/*"` (matches any image type)
227
+ ///
228
+ /// # Returns
229
+ ///
230
+ /// A slice of MIME type strings.
231
+ ///
232
+ /// # Example
233
+ ///
234
+ /// ```rust
235
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
236
+ /// # use kreuzberg::Result;
237
+ /// # use async_trait::async_trait;
238
+ /// # use std::path::Path;
239
+ /// # struct MultiFormatExtractor;
240
+ /// # impl Plugin for MultiFormatExtractor {
241
+ /// # fn name(&self) -> &str { "multi-format" }
242
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
243
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
244
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
245
+ /// # }
246
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
247
+ /// # #[async_trait]
248
+ /// # impl DocumentExtractor for MultiFormatExtractor {
249
+ /// # fn priority(&self) -> i32 { 50 }
250
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
251
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
252
+ /// fn supported_mime_types(&self) -> &[&str] {
253
+ /// &[
254
+ /// "text/plain",
255
+ /// "text/markdown",
256
+ /// "application/json",
257
+ /// "application/xml",
258
+ /// "text/html",
259
+ /// ]
260
+ /// }
261
+ /// # }
262
+ /// ```
263
+ fn supported_mime_types(&self) -> &[&str];
264
+
265
+ /// Get the priority of this extractor.
266
+ ///
267
+ /// Higher priority extractors are preferred when multiple extractors
268
+ /// support the same MIME type.
269
+ ///
270
+ /// # Priority Guidelines
271
+ ///
272
+ /// - **0-25**: Fallback/low-quality extractors
273
+ /// - **26-49**: Alternative extractors
274
+ /// - **50**: Default priority (built-in extractors)
275
+ /// - **51-75**: Premium/enhanced extractors
276
+ /// - **76-100**: Specialized/high-priority extractors
277
+ ///
278
+ /// # Returns
279
+ ///
280
+ /// Priority value (default: 50)
281
+ ///
282
+ /// # Example
283
+ ///
284
+ /// ```rust
285
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
286
+ /// # use kreuzberg::Result;
287
+ /// # use async_trait::async_trait;
288
+ /// # use std::path::Path;
289
+ /// # struct FallbackExtractor;
290
+ /// # impl Plugin for FallbackExtractor {
291
+ /// # fn name(&self) -> &str { "fallback" }
292
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
293
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
294
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
295
+ /// # }
296
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
297
+ /// # #[async_trait]
298
+ /// # impl DocumentExtractor for FallbackExtractor {
299
+ /// # fn supported_mime_types(&self) -> &[&str] { &["text/plain"] }
300
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
301
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
302
+ /// fn priority(&self) -> i32 {
303
+ /// 10 // Low priority - only used as fallback
304
+ /// }
305
+ /// # }
306
+ /// ```
307
+ fn priority(&self) -> i32 {
308
+ 50
309
+ }
310
+
311
+ /// Optional: Check if this extractor can handle a specific file.
312
+ ///
313
+ /// Allows for more sophisticated detection beyond MIME types.
314
+ /// Defaults to `true` (rely on MIME type matching).
315
+ ///
316
+ /// # Arguments
317
+ ///
318
+ /// * `path` - Path to the file to check
319
+ /// * `mime_type` - Detected MIME type
320
+ ///
321
+ /// # Returns
322
+ ///
323
+ /// `true` if the extractor can handle this file, `false` otherwise.
324
+ ///
325
+ /// # Example
326
+ ///
327
+ /// ```rust,no_run
328
+ /// # use kreuzberg::plugins::{Plugin, DocumentExtractor};
329
+ /// # use kreuzberg::Result;
330
+ /// # use async_trait::async_trait;
331
+ /// # use std::path::Path;
332
+ /// # struct SmartExtractor;
333
+ /// # impl Plugin for SmartExtractor {
334
+ /// # fn name(&self) -> &str { "smart" }
335
+ /// # fn version(&self) -> String { "1.0.0".to_string() }
336
+ /// # fn initialize(&self) -> Result<()> { Ok(()) }
337
+ /// # fn shutdown(&self) -> Result<()> { Ok(()) }
338
+ /// # }
339
+ /// # use kreuzberg::{ExtractionResult, ExtractionConfig};
340
+ /// # #[async_trait]
341
+ /// # impl DocumentExtractor for SmartExtractor {
342
+ /// # fn supported_mime_types(&self) -> &[&str] { &["application/pdf"] }
343
+ /// # fn priority(&self) -> i32 { 50 }
344
+ /// # async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
345
+ /// # async fn extract_file(&self, _: &Path, _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> { todo!() }
346
+ /// /// Only handle PDFs that are searchable (have text layer)
347
+ /// fn can_handle(&self, path: &Path, mime_type: &str) -> bool {
348
+ /// if mime_type != "application/pdf" {
349
+ /// return false;
350
+ /// }
351
+ ///
352
+ /// // Check if PDF has text layer (simplified example)
353
+ /// // In real implementation, analyze PDF structure here
354
+ /// let _ = path; // Use path for PDF analysis
355
+ /// true // Simplified - always accept
356
+ /// }
357
+ /// # }
358
+ /// ```
359
+ fn can_handle(&self, _path: &Path, _mime_type: &str) -> bool {
360
+ true
361
+ }
362
+ }
363
+
364
+ /// Register a document extractor with the global registry.
365
+ ///
366
+ /// The extractor will be registered for all MIME types it supports and will be
367
+ /// available for document extraction. The extractor's `name()` method is used as
368
+ /// the registration name.
369
+ ///
370
+ /// # Arguments
371
+ ///
372
+ /// * `extractor` - The extractor implementation wrapped in Arc
373
+ ///
374
+ /// # Returns
375
+ ///
376
+ /// - `Ok(())` if registration succeeded
377
+ /// - `Err(...)` if validation failed or initialization failed
378
+ ///
379
+ /// # Errors
380
+ ///
381
+ /// - `KreuzbergError::Validation` - Invalid extractor name (empty or contains whitespace)
382
+ /// - Any error from the extractor's `initialize()` method
383
+ ///
384
+ /// # Example
385
+ ///
386
+ /// ```rust
387
+ /// use kreuzberg::plugins::{Plugin, DocumentExtractor, register_extractor};
388
+ /// use kreuzberg::{Result, ExtractionConfig};
389
+ /// use kreuzberg::types::{ExtractionResult, Metadata};
390
+ /// use async_trait::async_trait;
391
+ /// use std::sync::Arc;
392
+ /// use std::path::Path;
393
+ ///
394
+ /// struct CustomExtractor;
395
+ ///
396
+ /// impl Plugin for CustomExtractor {
397
+ /// fn name(&self) -> &str { "custom-extractor" }
398
+ /// fn version(&self) -> String { "1.0.0".to_string() }
399
+ /// fn initialize(&self) -> Result<()> { Ok(()) }
400
+ /// fn shutdown(&self) -> Result<()> { Ok(()) }
401
+ /// }
402
+ ///
403
+ /// #[async_trait]
404
+ /// impl DocumentExtractor for CustomExtractor {
405
+ /// async fn extract_bytes(&self, content: &[u8], mime_type: &str, _: &ExtractionConfig)
406
+ /// -> Result<ExtractionResult> {
407
+ /// Ok(ExtractionResult {
408
+ /// content: String::from_utf8_lossy(content).to_string(),
409
+ /// mime_type: mime_type.to_string(),
410
+ /// metadata: Metadata::default(),
411
+ /// tables: vec![],
412
+ /// detected_languages: None,
413
+ /// chunks: None,
414
+ /// images: None,
415
+ /// })
416
+ /// }
417
+ ///
418
+ /// fn supported_mime_types(&self) -> &[&str] {
419
+ /// &["text/custom"]
420
+ /// }
421
+ /// }
422
+ ///
423
+ /// # tokio_test::block_on(async {
424
+ /// let extractor = Arc::new(CustomExtractor);
425
+ /// register_extractor(extractor)?;
426
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
427
+ /// # });
428
+ /// ```
429
+ pub fn register_extractor(extractor: Arc<dyn DocumentExtractor>) -> crate::Result<()> {
430
+ use crate::plugins::registry::get_document_extractor_registry;
431
+
432
+ let registry = get_document_extractor_registry();
433
+ let mut registry = registry
434
+ .write()
435
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
436
+
437
+ registry.register(extractor)
438
+ }
439
+
440
+ /// Unregister a document extractor by name.
441
+ ///
442
+ /// Removes the extractor from the global registry and calls its `shutdown()` method.
443
+ ///
444
+ /// # Arguments
445
+ ///
446
+ /// * `name` - Name of the extractor to unregister
447
+ ///
448
+ /// # Returns
449
+ ///
450
+ /// - `Ok(())` if the extractor was unregistered or didn't exist
451
+ /// - `Err(...)` if the shutdown method failed
452
+ ///
453
+ /// # Example
454
+ ///
455
+ /// ```rust
456
+ /// use kreuzberg::plugins::unregister_extractor;
457
+ ///
458
+ /// # tokio_test::block_on(async {
459
+ /// unregister_extractor("custom-extractor")?;
460
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
461
+ /// # });
462
+ /// ```
463
+ pub fn unregister_extractor(name: &str) -> crate::Result<()> {
464
+ use crate::plugins::registry::get_document_extractor_registry;
465
+
466
+ let registry = get_document_extractor_registry();
467
+ let mut registry = registry
468
+ .write()
469
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
470
+
471
+ registry.remove(name)
472
+ }
473
+
474
+ /// List all registered extractors.
475
+ ///
476
+ /// Returns the names of all extractors currently registered in the global registry.
477
+ ///
478
+ /// # Returns
479
+ ///
480
+ /// A vector of extractor names.
481
+ ///
482
+ /// # Example
483
+ ///
484
+ /// ```rust
485
+ /// use kreuzberg::plugins::list_extractors;
486
+ ///
487
+ /// # tokio_test::block_on(async {
488
+ /// let extractors = list_extractors()?;
489
+ /// for name in extractors {
490
+ /// println!("Registered extractor: {}", name);
491
+ /// }
492
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
493
+ /// # });
494
+ /// ```
495
+ pub fn list_extractors() -> crate::Result<Vec<String>> {
496
+ use crate::plugins::registry::get_document_extractor_registry;
497
+
498
+ let registry = get_document_extractor_registry();
499
+ let registry = registry
500
+ .read()
501
+ .expect("~keep Failed to acquire read lock on extractor registry"); // ~keep
502
+
503
+ Ok(registry.list())
504
+ }
505
+
506
+ /// Clear all extractors from the global registry.
507
+ ///
508
+ /// Removes all extractors and calls their `shutdown()` methods.
509
+ ///
510
+ /// # Returns
511
+ ///
512
+ /// - `Ok(())` if all extractors were cleared successfully
513
+ /// - `Err(...)` if any shutdown method failed
514
+ ///
515
+ /// # Example
516
+ ///
517
+ /// ```rust
518
+ /// use kreuzberg::plugins::clear_extractors;
519
+ ///
520
+ /// # tokio_test::block_on(async {
521
+ /// clear_extractors()?;
522
+ /// # Ok::<(), kreuzberg::KreuzbergError>(())
523
+ /// # });
524
+ /// ```
525
+ pub fn clear_extractors() -> crate::Result<()> {
526
+ use crate::plugins::registry::get_document_extractor_registry;
527
+
528
+ let registry = get_document_extractor_registry();
529
+ let mut registry = registry
530
+ .write()
531
+ .expect("~keep Failed to acquire write lock on extractor registry"); // ~keep
532
+
533
+ registry.shutdown_all()
534
+ }
535
+
536
+ #[cfg(test)]
537
+ mod tests {
538
+ use super::*;
539
+ use serial_test::serial;
540
+
541
+ struct MockExtractor {
542
+ mime_types: Vec<&'static str>,
543
+ priority: i32,
544
+ }
545
+
546
+ impl Plugin for MockExtractor {
547
+ fn name(&self) -> &str {
548
+ "mock-extractor"
549
+ }
550
+
551
+ fn version(&self) -> String {
552
+ "1.0.0".to_string()
553
+ }
554
+
555
+ fn initialize(&self) -> Result<()> {
556
+ Ok(())
557
+ }
558
+
559
+ fn shutdown(&self) -> Result<()> {
560
+ Ok(())
561
+ }
562
+ }
563
+
564
+ #[async_trait]
565
+ impl DocumentExtractor for MockExtractor {
566
+ async fn extract_bytes(
567
+ &self,
568
+ content: &[u8],
569
+ mime_type: &str,
570
+ _config: &ExtractionConfig,
571
+ ) -> Result<ExtractionResult> {
572
+ Ok(ExtractionResult {
573
+ content: String::from_utf8_lossy(content).to_string(),
574
+ mime_type: mime_type.to_string(),
575
+ metadata: crate::types::Metadata::default(),
576
+ tables: vec![],
577
+ detected_languages: None,
578
+ chunks: None,
579
+ images: None,
580
+ })
581
+ }
582
+
583
+ fn supported_mime_types(&self) -> &[&str] {
584
+ &self.mime_types
585
+ }
586
+
587
+ fn priority(&self) -> i32 {
588
+ self.priority
589
+ }
590
+ }
591
+
592
+ #[tokio::test]
593
+ async fn test_document_extractor_extract_bytes() {
594
+ let extractor = MockExtractor {
595
+ mime_types: vec!["text/plain"],
596
+ priority: 50,
597
+ };
598
+
599
+ let config = ExtractionConfig::default();
600
+ let result = extractor
601
+ .extract_bytes(b"test content", "text/plain", &config)
602
+ .await
603
+ .unwrap();
604
+
605
+ assert_eq!(result.content, "test content");
606
+ assert_eq!(result.mime_type, "text/plain");
607
+ }
608
+
609
+ #[test]
610
+ fn test_document_extractor_supported_mime_types() {
611
+ let extractor = MockExtractor {
612
+ mime_types: vec!["text/plain", "text/markdown"],
613
+ priority: 50,
614
+ };
615
+
616
+ let supported = extractor.supported_mime_types();
617
+ assert_eq!(supported.len(), 2);
618
+ assert!(supported.contains(&"text/plain"));
619
+ assert!(supported.contains(&"text/markdown"));
620
+ }
621
+
622
+ #[test]
623
+ fn test_document_extractor_priority() {
624
+ let low_priority = MockExtractor {
625
+ mime_types: vec!["text/plain"],
626
+ priority: 10,
627
+ };
628
+
629
+ let high_priority = MockExtractor {
630
+ mime_types: vec!["text/plain"],
631
+ priority: 100,
632
+ };
633
+
634
+ assert_eq!(low_priority.priority(), 10);
635
+ assert_eq!(high_priority.priority(), 100);
636
+ }
637
+
638
+ #[test]
639
+ fn test_document_extractor_can_handle_default() {
640
+ let extractor = MockExtractor {
641
+ mime_types: vec!["text/plain"],
642
+ priority: 50,
643
+ };
644
+
645
+ use std::path::PathBuf;
646
+ let path = PathBuf::from("test.txt");
647
+
648
+ assert!(extractor.can_handle(&path, "text/plain"));
649
+ assert!(extractor.can_handle(&path, "application/pdf"));
650
+ }
651
+
652
+ #[tokio::test]
653
+ async fn test_document_extractor_extract_file_default_impl() {
654
+ use std::io::Write;
655
+ use tempfile::NamedTempFile;
656
+
657
+ let extractor = MockExtractor {
658
+ mime_types: vec!["text/plain"],
659
+ priority: 50,
660
+ };
661
+
662
+ let mut temp_file = NamedTempFile::new().unwrap();
663
+ temp_file.write_all(b"file content").unwrap();
664
+ let path = temp_file.path();
665
+
666
+ let config = ExtractionConfig::default();
667
+ let result = extractor.extract_file(path, "text/plain", &config).await.unwrap();
668
+
669
+ assert_eq!(result.content, "file content");
670
+ assert_eq!(result.mime_type, "text/plain");
671
+ }
672
+
673
+ #[tokio::test]
674
+ async fn test_document_extractor_empty_content() {
675
+ let extractor = MockExtractor {
676
+ mime_types: vec!["text/plain"],
677
+ priority: 50,
678
+ };
679
+
680
+ let config = ExtractionConfig::default();
681
+ let result = extractor.extract_bytes(b"", "text/plain", &config).await.unwrap();
682
+
683
+ assert_eq!(result.content, "");
684
+ assert_eq!(result.mime_type, "text/plain");
685
+ }
686
+
687
+ #[tokio::test]
688
+ async fn test_document_extractor_non_utf8_content() {
689
+ let extractor = MockExtractor {
690
+ mime_types: vec!["text/plain"],
691
+ priority: 50,
692
+ };
693
+
694
+ let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];
695
+ let config = ExtractionConfig::default();
696
+ let result = extractor
697
+ .extract_bytes(&invalid_utf8, "text/plain", &config)
698
+ .await
699
+ .unwrap();
700
+
701
+ assert!(!result.content.is_empty());
702
+ }
703
+
704
+ #[test]
705
+ fn test_document_extractor_plugin_interface() {
706
+ let extractor = MockExtractor {
707
+ mime_types: vec!["text/plain"],
708
+ priority: 50,
709
+ };
710
+
711
+ assert_eq!(extractor.name(), "mock-extractor");
712
+ assert_eq!(extractor.version(), "1.0.0");
713
+ assert!(extractor.initialize().is_ok());
714
+ assert!(extractor.shutdown().is_ok());
715
+ }
716
+
717
+ #[test]
718
+ fn test_document_extractor_default_priority() {
719
+ struct DefaultPriorityExtractor;
720
+
721
+ impl Plugin for DefaultPriorityExtractor {
722
+ fn name(&self) -> &str {
723
+ "default"
724
+ }
725
+ fn version(&self) -> String {
726
+ "1.0.0".to_string()
727
+ }
728
+ fn initialize(&self) -> Result<()> {
729
+ Ok(())
730
+ }
731
+ fn shutdown(&self) -> Result<()> {
732
+ Ok(())
733
+ }
734
+ }
735
+
736
+ #[async_trait]
737
+ impl DocumentExtractor for DefaultPriorityExtractor {
738
+ async fn extract_bytes(
739
+ &self,
740
+ _content: &[u8],
741
+ _mime_type: &str,
742
+ _config: &ExtractionConfig,
743
+ ) -> Result<ExtractionResult> {
744
+ Ok(ExtractionResult {
745
+ content: String::new(),
746
+ mime_type: String::new(),
747
+ metadata: crate::types::Metadata::default(),
748
+ tables: vec![],
749
+ detected_languages: None,
750
+ chunks: None,
751
+ images: None,
752
+ })
753
+ }
754
+
755
+ fn supported_mime_types(&self) -> &[&str] {
756
+ &["text/plain"]
757
+ }
758
+ }
759
+
760
+ let extractor = DefaultPriorityExtractor;
761
+ assert_eq!(extractor.priority(), 50);
762
+ }
763
+
764
+ #[test]
765
+ fn test_document_extractor_empty_mime_types() {
766
+ let extractor = MockExtractor {
767
+ mime_types: vec![],
768
+ priority: 50,
769
+ };
770
+
771
+ assert_eq!(extractor.supported_mime_types().len(), 0);
772
+ }
773
+
774
+ #[test]
775
+ fn test_document_extractor_wildcard_mime_types() {
776
+ let extractor = MockExtractor {
777
+ mime_types: vec!["text/*", "image/*"],
778
+ priority: 50,
779
+ };
780
+
781
+ let supported = extractor.supported_mime_types();
782
+ assert_eq!(supported.len(), 2);
783
+ assert!(supported.contains(&"text/*"));
784
+ assert!(supported.contains(&"image/*"));
785
+ }
786
+
787
+ #[test]
788
+ fn test_document_extractor_priority_ranges() {
789
+ let fallback = MockExtractor {
790
+ mime_types: vec!["text/plain"],
791
+ priority: 10,
792
+ };
793
+ let alternative = MockExtractor {
794
+ mime_types: vec!["text/plain"],
795
+ priority: 40,
796
+ };
797
+ let default = MockExtractor {
798
+ mime_types: vec!["text/plain"],
799
+ priority: 50,
800
+ };
801
+ let premium = MockExtractor {
802
+ mime_types: vec!["text/plain"],
803
+ priority: 75,
804
+ };
805
+ let specialized = MockExtractor {
806
+ mime_types: vec!["text/plain"],
807
+ priority: 100,
808
+ };
809
+
810
+ assert!(fallback.priority() < alternative.priority());
811
+ assert!(alternative.priority() < default.priority());
812
+ assert!(default.priority() < premium.priority());
813
+ assert!(premium.priority() < specialized.priority());
814
+ }
815
+
816
+ #[tokio::test]
817
+ async fn test_document_extractor_preserves_mime_type() {
818
+ let extractor = MockExtractor {
819
+ mime_types: vec!["application/json"],
820
+ priority: 50,
821
+ };
822
+
823
+ let config = ExtractionConfig::default();
824
+ let result = extractor
825
+ .extract_bytes(b"{\"key\":\"value\"}", "application/json", &config)
826
+ .await
827
+ .unwrap();
828
+
829
+ assert_eq!(result.mime_type, "application/json");
830
+ }
831
+
832
+ #[test]
833
+ #[serial]
834
+ fn test_register_extractor() {
835
+ use std::sync::Arc;
836
+
837
+ let extractor = Arc::new(MockExtractor {
838
+ mime_types: vec!["text/test-register"],
839
+ priority: 50,
840
+ });
841
+ let result = super::register_extractor(extractor);
842
+ assert!(result.is_ok());
843
+
844
+ let _ = super::unregister_extractor("mock-extractor");
845
+ }
846
+
847
+ #[test]
848
+ #[serial]
849
+ fn test_unregister_extractor() {
850
+ use std::sync::Arc;
851
+
852
+ let extractor = Arc::new(MockExtractor {
853
+ mime_types: vec!["text/test-unregister"],
854
+ priority: 50,
855
+ });
856
+ super::register_extractor(extractor).unwrap();
857
+
858
+ let result = super::unregister_extractor("mock-extractor");
859
+ assert!(result.is_ok());
860
+ }
861
+
862
+ #[test]
863
+ #[serial]
864
+ fn test_unregister_nonexistent_extractor() {
865
+ let result = super::unregister_extractor("nonexistent-extractor-xyz");
866
+ assert!(result.is_ok());
867
+ }
868
+
869
+ #[test]
870
+ #[serial]
871
+ fn test_list_extractors() {
872
+ use std::sync::Arc;
873
+
874
+ super::clear_extractors().unwrap();
875
+
876
+ let extractor1 = Arc::new(MockExtractor {
877
+ mime_types: vec!["text/test-list-1"],
878
+ priority: 50,
879
+ });
880
+ let extractor2 = Arc::new(MockExtractor {
881
+ mime_types: vec!["text/test-list-2"],
882
+ priority: 51,
883
+ });
884
+
885
+ let list_before = super::list_extractors().unwrap();
886
+ assert_eq!(list_before.len(), 0);
887
+
888
+ super::register_extractor(extractor1).unwrap();
889
+ super::register_extractor(extractor2).unwrap();
890
+
891
+ let list = super::list_extractors().unwrap();
892
+ assert_eq!(list.len(), 1);
893
+ assert!(list.contains(&"mock-extractor".to_string()));
894
+
895
+ super::unregister_extractor("mock-extractor").unwrap();
896
+ }
897
+
898
+ #[test]
899
+ #[serial]
900
+ fn test_clear_extractors() {
901
+ use std::sync::Arc;
902
+
903
+ super::clear_extractors().unwrap();
904
+
905
+ let extractor1 = Arc::new(MockExtractor {
906
+ mime_types: vec!["text/test-clear-1"],
907
+ priority: 50,
908
+ });
909
+ let extractor2 = Arc::new(MockExtractor {
910
+ mime_types: vec!["text/test-clear-2"],
911
+ priority: 51,
912
+ });
913
+
914
+ super::register_extractor(extractor1).unwrap();
915
+ super::register_extractor(extractor2).unwrap();
916
+
917
+ let result = super::clear_extractors();
918
+ assert!(result.is_ok());
919
+
920
+ let list = super::list_extractors().unwrap();
921
+ assert_eq!(list.len(), 0);
922
+ }
923
+
924
+ #[test]
925
+ #[serial]
926
+ fn test_register_extractor_with_invalid_name() {
927
+ use std::sync::Arc;
928
+
929
+ struct InvalidNameExtractor;
930
+ impl Plugin for InvalidNameExtractor {
931
+ fn name(&self) -> &str {
932
+ "invalid name with spaces"
933
+ }
934
+ fn version(&self) -> String {
935
+ "1.0.0".to_string()
936
+ }
937
+ fn initialize(&self) -> Result<()> {
938
+ Ok(())
939
+ }
940
+ fn shutdown(&self) -> Result<()> {
941
+ Ok(())
942
+ }
943
+ }
944
+
945
+ #[async_trait]
946
+ impl DocumentExtractor for InvalidNameExtractor {
947
+ async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
948
+ Ok(ExtractionResult {
949
+ content: String::new(),
950
+ mime_type: String::new(),
951
+ metadata: crate::types::Metadata::default(),
952
+ tables: vec![],
953
+ detected_languages: None,
954
+ chunks: None,
955
+ images: None,
956
+ })
957
+ }
958
+
959
+ fn supported_mime_types(&self) -> &[&str] {
960
+ &["text/plain"]
961
+ }
962
+ }
963
+
964
+ let extractor = Arc::new(InvalidNameExtractor);
965
+ let result = super::register_extractor(extractor);
966
+ assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
967
+ }
968
+
969
+ #[test]
970
+ #[serial]
971
+ fn test_register_extractor_with_empty_name() {
972
+ use std::sync::Arc;
973
+
974
+ struct EmptyNameExtractor;
975
+ impl Plugin for EmptyNameExtractor {
976
+ fn name(&self) -> &str {
977
+ ""
978
+ }
979
+ fn version(&self) -> String {
980
+ "1.0.0".to_string()
981
+ }
982
+ fn initialize(&self) -> Result<()> {
983
+ Ok(())
984
+ }
985
+ fn shutdown(&self) -> Result<()> {
986
+ Ok(())
987
+ }
988
+ }
989
+
990
+ #[async_trait]
991
+ impl DocumentExtractor for EmptyNameExtractor {
992
+ async fn extract_bytes(&self, _: &[u8], _: &str, _: &ExtractionConfig) -> Result<ExtractionResult> {
993
+ Ok(ExtractionResult {
994
+ content: String::new(),
995
+ mime_type: String::new(),
996
+ metadata: crate::types::Metadata::default(),
997
+ tables: vec![],
998
+ detected_languages: None,
999
+ chunks: None,
1000
+ images: None,
1001
+ })
1002
+ }
1003
+
1004
+ fn supported_mime_types(&self) -> &[&str] {
1005
+ &["text/plain"]
1006
+ }
1007
+ }
1008
+
1009
+ let extractor = Arc::new(EmptyNameExtractor);
1010
+ let result = super::register_extractor(extractor);
1011
+ assert!(matches!(result, Err(crate::KreuzbergError::Validation { .. })));
1012
+ }
1013
+ }