{"data":{"slug":"github-xberg-io-xberg-ai-rulez-skills-plugin-architecture-patterns-0a1709c80e5c","title":"Plugin Architecture & Registration","summary":"Define and register plugin types for document extraction, processing, and validation in a plugin architecture.","url":"https:\/\/skillshunter.net\/skills\/github-xberg-io-xberg-ai-rulez-skills-plugin-architecture-patterns-0a1709c80e5c","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-xberg-io-xberg-ai-rulez-skills-plugin-architecture-patterns-0a1709c80e5c","markdown_url":"https:\/\/skillshunter.net\/skills\/github-xberg-io-xberg-ai-rulez-skills-plugin-architecture-patterns-0a1709c80e5c.md","download_url":"https:\/\/skillshunter.net\/skills\/github-xberg-io-xberg-ai-rulez-skills-plugin-architecture-patterns-0a1709c80e5c\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Plugins must implement `Send + Sync` and use the two-arm `cfg_attr` form for `async_trait` to ensure compatibility across platforms.","instructions":"---\ntype: Playbook\ntitle: Plugin Architecture Patterns\ndescription: \"Change plugin traits, typed registries, lifecycle or Alef Python bridges.\"\npaths:\n  - \"crates\/xberg\/src\/plugins\/**\"\n  - \"crates\/xberg-py\/src\/**\"\nx-ai-rulez:\n  kind: skill\n  id: plugin-architecture-patterns\n  metadata:\n    priority: critical\n    name: plugin-architecture-patterns\n---\n\n# Plugin Architecture & Registration\n\n## Plugin Types\n\n| Type | Trait | Location |\n| --- | --- | --- |\n| Document extractor (binding-facing) | `DocumentExtractor: Plugin` | `plugins\/extractor\/trait.rs` |\n| Document extractor (in-crate) | `InternalDocumentExtractor: Plugin` | `plugins\/extractor\/trait.rs` |\n| OCR backend | `OcrBackend: Plugin` | `plugins\/ocr.rs` (a file, not a directory) |\n| Post processor | `PostProcessor: Plugin` | `plugins\/processor\/trait.rs` |\n| Validator | `Validator: Plugin` | `plugins\/validator\/trait.rs` |\n| Embedding backend | `EmbeddingBackend: Plugin` | `plugins\/embedding.rs` |\n| Reranker backend | `RerankerBackend: Plugin` | `plugins\/reranker.rs` |\n| Tokenizer backend | `TokenizerBackend: Plugin` | `plugins\/tokenizer.rs` |\n| Renderer | `Renderer: Plugin` | `plugins\/renderer.rs` |\n\n`Plugin` (`plugins\/traits.rs`) is `Send + Sync` and requires `name()`; `version()`,\n`initialize()`, `shutdown()`, `description()`, and `author()` have defaults. There is no\n`'static` trait bound; registry-owned `Arc<dyn Trait>` supplies the necessary lifetime.\n\n## Native Rust extractors implement `InternalDocumentExtractor`\n\n`DocumentExtractor` is the binding-facing surface. In-crate extractors implement\n`InternalDocumentExtractor` and get `DocumentExtractor` from a blanket impl. Implementing\n`DocumentExtractor` directly in this crate is the wrong layer.\n\n```rust\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\nimpl InternalDocumentExtractor for MyExtractor {\n    async fn extract_content(&self, content: &[u8], mime_type: &str, config: &ExtractionConfig)\n        -> Result<InternalDocument> { \/* ... *\/ }\n\n    fn supported_mime_types(&self) -> &[&str] { &[\"application\/x-custom\"] }\n    fn priority(&self) -> i32 { 50 }\n}\n```\n\n`extract_path` has a default that reads the file and delegates to `extract_content` (and\nerrors without `tokio-runtime`).\n\nAlways use the two-arm `cfg_attr` form for `async_trait`. A bare `#[async_trait]` does not\nmatch the trait declaration on `wasm32`.\n\nThe public trait has exactly four items \u2014 `extract`, `supported_mime_types`, `priority`,\n`can_handle`. There is no `as_sync_extractor`; writing one is a compile error. WASM sync\nsupport is the separate `SyncExtractor` trait \u2014 see `wasm-constraints`.\n\n## Priority System\n\n| Range | Use |\n| --- | --- |\n| 0-25 | Fallback\/low-quality |\n| 26-49 | Alternative extractors |\n| **50** | **Default (built-in)** |\n| 51-75 | Premium\/enhanced |\n| 76-100 | Specialized\/high-priority |\n\nThe registry selects the **highest priority** extractor for each MIME type. The ranges are\nconventions over an unclamped `i32`; negative and values above 100 are representable. Equal\nMIME and priority is a collision: the later registration replaces the earlier entry and\nwarns. Give competing plugins distinct priorities.\n\n## Registration\n\n```rust\n\/\/ crates\/xberg\/src\/extractors\/mod.rs -> register_default_extractors()\nlet registry = get_document_extractor_registry();\nlet mut registry = registry.write();\nregistry.register(Arc::new(MyExtractor::new()))?;\n```\n\nFeature-gate optional formats:\n\n```rust\n#[cfg(feature = \"office\")]\n{\n    registry.register(Arc::new(DocxExtractor::new()))?;\n    registry.register(Arc::new(PptxExtractor::new()))?;\n}\n```\n\n## PostProcessor Pattern\n\n```rust\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\nimpl PostProcessor for MyProcessor {\n    async fn process(&self, result: &mut ExtractedDocument, config: &ExtractionConfig)\n        -> Result<()> {\n        result.content = process_content(&result.content);\n        Ok(())\n    }\n    fn processing_stage(&self) -> ProcessingStage { ProcessingStage::Middle }\n}\n```\n\nThe enum is `ProcessingStage` and the accessor is `processing_stage()`. Stages:\n`Early` (default) \u2192 `Middle` \u2192 `Late`. `process` takes `&mut ExtractedDocument`, not an owned\nresult.\n\n## Critical Rules\n\n1. All plugins **MUST be `Send + Sync`** \u2014 `Plugin` requires it.\n2. In-crate extractors implement `InternalDocumentExtractor`, never `DocumentExtractor`.\n3. Use the two-arm `cfg_attr` `async_trait` form on every plugin trait impl.\n4. Feature-gate optional formats with `#[cfg(feature = \"...\")]` at the registration site.\n5. Initialization is lazy via `ensure_initialized()` (`extractors\/mod.rs`), called before first extraction.\n6. Plugin names are kebab-case (e.g. `\"pdf-extractor\"`).\n7. A new extractor struct needs `#[cfg_attr(alef, alef(skip))]` or the binding regen aborts \u2014 see\n   `alef-generated-bindings`.\n\n## Registry and lifecycle invariants\n\n- Eight plugin types have eight process-global typed registries in `plugins\/registry\/mod.rs`.\n  There is no universal `PluginRegistry`.\n- Registries use `Arc<parking_lot::RwLock<_>>`. Their guards are not poisoned and\n  `.read()`\/`.write()` return guards directly.\n- Extractor lookup is `HashMap<mime, BTreeMap<priority, entry>>`: exact MIME lookup is\n  constant-time on the outer map; wildcard-family lookup scans registered MIME keys.\n- Registration calls `initialize()` and rejects a plugin whose initialization fails.\n  Registries support register, remove, clear, and `shutdown_all`; there is no hot reload.\n- All eight plugin types can be registered from language bindings. Plugin interfaces are\n  public APIs, so breaking changes follow the public compatibility policy.\n- Return errors rather than panicking. Test lifecycle, collision\/replacement, concurrent\n  access, and failure paths with test doubles; use real backends for integration coverage.\n  No dispatch-overhead benchmark exists unless one is explicitly added.\n\n## Alef-generated Python bridge\n\nThe Python bridge is generated into `crates\/xberg-py\/src\/lib.rs`; there is no hand-written\n`plugins.rs`. Change Alef\/configuration and regenerate rather than editing the bridge.\n\n- PyO3 0.29 uses `Python::attach`. Async host calls enter Python from\n  `tokio::task::spawn_blocking` and propagate the caller's `contextvars` context.\n- Cache frequently accessed host data such as plugin names in Rust fields so infallible\n  methods do not need repeated GIL acquisition. Do not assume `allow_threads` is in use.\n- Every trait method return crosses the bridge through native extraction or JSON fallback.\n  Crossing types therefore need `Serialize + Deserialize + Default`, including unit enums.\n- Host exceptions become `XbergError::Other` with plugin and method context; the original\n  Python exception type and traceback are not retained. Infallible methods can only warn and\n  return `Default::default()`, so a default may indicate bridge failure rather than real data.\n- Rust-side extractor plugin failures may use `XbergError::Plugin`, which is fallback-eligible;\n  do not assume Python bridge errors have the same fallback behavior.\n- Validate the Python protocol at registration. Do not quote GIL overhead without a current\n  benchmark.\n","use_cases":["Register a custom document extractor for a specific MIME type","Implement a post processor to modify extracted content","Register an OCR backend for image-based document extraction"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/xberg-io\/xberg\/blob\/ffbf7971796a126fc52f6bb8fb40418772071f61\/.ai-rulez\/skills\/plugin-architecture-patterns\/SKILL.md","source_commit":"ffbf7971796a126fc52f6bb8fb40418772071f61","license":null,"version":null,"listing_approved_at":"2026-11-16","created_at":"2026-11-15T13:39:59.000000Z","updated_at":"2026-11-16T05:16:54.000000Z","seo_title":"Plugin Architecture Patterns","seo_description":"Learn how to implement and register plugin types for document extraction, processing, and validation in a plugin architecture.","seo_keywords":["plugin architecture patterns","document extractor registration","post processor implementation","OCR backend registration","plugin lifecycle management"]}}