Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Plugins Support with WebAssembly #2056

Draft
wants to merge 127 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
127 commits
Select commit Hold shift + click to select a range
ce31fe2
Plugins System: Multiple squashed commits
AmmarAbouZor Jun 14, 2024
65be020
Plugins: Parser Client Defs & Macro (in progress)
AmmarAbouZor Jul 10, 2024
94c0ffe
Plugins: Parser Client Exports & Macro (in progress)
AmmarAbouZor Jul 11, 2024
ab0f282
Plugin: Fixes & Adjustments to Parser Plugin Client
AmmarAbouZor Jul 12, 2024
ec5c19a
Parser Plugin Macro: Insure Parser trait in scope
AmmarAbouZor Jul 15, 2024
1390d65
Integration tests for parser export macro
AmmarAbouZor Jul 15, 2024
4d365c4
Plugins API: Add build check for enabled features
AmmarAbouZor Jul 15, 2024
80c1da8
Integration tests for parser export macro
AmmarAbouZor Jul 15, 2024
39ee2d3
Plugins API: Add warning for internal module + renaming.
AmmarAbouZor Jul 15, 2024
092a2fb
Plugins API: Adding logging functionality
AmmarAbouZor Jul 15, 2024
c19a15e
Plugins API: Adding logging functionality
AmmarAbouZor Jul 16, 2024
080435c
Plugins API: Adding logging functionality
AmmarAbouZor Jul 16, 2024
a8346f5
Plugins API: Adding logging functionality
AmmarAbouZor Jul 16, 2024
266aa2a
Plugins API: Adding logging functionality
AmmarAbouZor Jul 16, 2024
1d3a905
Plugins API: Adding logging functionality
AmmarAbouZor Jul 17, 2024
3b30d1a
Parser Plugin: Send collection of results as default
AmmarAbouZor Jul 17, 2024
3963c2d
Plugin API Docs: Configurations & Improvements
AmmarAbouZor Jul 17, 2024
8a4715e
Plugin API: Docs & Example for export parser macro
AmmarAbouZor Jul 18, 2024
b496298
Plugin API Parser: Small fixes for export macro
AmmarAbouZor Jul 18, 2024
6fa5ee1
Plugins: Use Add method on host & Clippy Fixes
AmmarAbouZor Jul 26, 2024
330e99a
Plugins: Rename host library to `Plugins_host`
AmmarAbouZor Jul 30, 2024
1efd2c4
Plugins: Improve documentation for Parser trait
AmmarAbouZor Jul 31, 2024
f7218dd
Plugins API: Bytesource WIT & Bindings & Macro
AmmarAbouZor Jul 31, 2024
48dd637
Plugins Parser: Integration tests fixes
AmmarAbouZor Jul 31, 2024
4dace50
Plugin Bytesource: Add integration tests
AmmarAbouZor Jul 31, 2024
12219ec
Plugins API: Insure tests run with all features
AmmarAbouZor Jul 31, 2024
e763db4
Plugins: Provide 'File Source' Plugin as example
AmmarAbouZor Jul 31, 2024
99a0c4b
Plugins: Refactoring & Cleaning up
AmmarAbouZor Aug 1, 2024
696d506
Plugins Host: Implementing Bytesource & Refactoring
AmmarAbouZor Aug 1, 2024
4f06e25
Plugins: Remove Seek form trait bound of ByteSource
AmmarAbouZor Aug 1, 2024
c94da3f
Plugins: Basic integration of ByteSource in host
AmmarAbouZor Aug 1, 2024
8e2d593
Plugins API: Add Input Source definitions
AmmarAbouZor Aug 2, 2024
8b3d30a
Plugins Host: Create Bytesource & Parser Adjustments
AmmarAbouZor Aug 2, 2024
c0695cd
Plugins: Implement Read method on Bytesource Host
AmmarAbouZor Aug 2, 2024
36dcc3f
Plugins: Remove Sync bound from ByteSource Trait
AmmarAbouZor Aug 2, 2024
7387d4e
Plugins Source Guest: Add missing export macro
AmmarAbouZor Aug 5, 2024
6ffc42a
Plugins Source Guest: Use uninitialized buffer
AmmarAbouZor Aug 5, 2024
ce25f63
Plugin: Add missing indexer CLI command
AmmarAbouZor Nov 7, 2024
82271eb
Plugins Parser: Adjustment according to master
AmmarAbouZor Nov 7, 2024
488f3aa
Plugins: Use dependencies from workspace
AmmarAbouZor Nov 7, 2024
3034403
Plugins: Add temporary basic benchmarks
AmmarAbouZor Nov 8, 2024
b58deb5
Plugins: Benchmark for parser plugin
AmmarAbouZor Nov 8, 2024
0254285
Plugin: Adjustments and comments due to benchmarks
AmmarAbouZor Nov 8, 2024
cd9fde8
Plugins: Add benchmark for compiling plugins
AmmarAbouZor Nov 11, 2024
ea4a3ef
Plugins Parser: Improve handling plugins' errors
AmmarAbouZor Nov 11, 2024
1da6d69
Plugins Parser: Remove method `parsing_with_add`
AmmarAbouZor Nov 11, 2024
a646a6a
Plugin Parser: Add invariant & security tests
AmmarAbouZor Nov 13, 2024
e6f55f3
Plugin Bytesource: Add invariant & security tests
AmmarAbouZor Nov 13, 2024
b6fe883
Plugins: String parser example & Improvement on Source
AmmarAbouZor Nov 15, 2024
4714179
Plugins: String parser errors on invalid UTF-8
AmmarAbouZor Nov 15, 2024
ef8502d
Plugins Parser: Multiple columns in parsed message
AmmarAbouZor Nov 25, 2024
ea0c6fb
Plugins API: Add Custom Configurations Schema
AmmarAbouZor Nov 28, 2024
1dbdc3d
Plugins: Custom configs for string parser plugin
AmmarAbouZor Nov 28, 2024
49541b8
Plugins custom configurations on host
AmmarAbouZor Nov 28, 2024
fb14b4e
Plugins: Deliver config schemas on host & Refactor
AmmarAbouZor Nov 29, 2024
534d878
Plugins: Custom configurations for byte-source API
AmmarAbouZor Nov 29, 2024
27e0a6e
Plugins: Custom configs for file source example
AmmarAbouZor Nov 29, 2024
45c3985
Plugins: Custom configuration on byte-source host
AmmarAbouZor Nov 29, 2024
23c4a60
Plugins API: Add missing documentation warning
AmmarAbouZor Dec 2, 2024
3553a4a
Create Plugins Manger + Integration in unbound session
AmmarAbouZor Dec 2, 2024
9aece0e
Plugins Manger Inside unbound session temporally
AmmarAbouZor Dec 3, 2024
036abdc
Plugins: Add version to parser API
AmmarAbouZor Dec 3, 2024
f43606c
Plugins: Add version to byte-source API
AmmarAbouZor Dec 3, 2024
c53f22c
Plugins host: Plugins version support
AmmarAbouZor Dec 3, 2024
e493564
Plugins Parser: Render options on plugins API
AmmarAbouZor Dec 3, 2024
9e75dcc
Plugins Parser: Support for render options on host
AmmarAbouZor Dec 3, 2024
eb29efc
Plugins: Version & Render options for examples
AmmarAbouZor Dec 4, 2024
01eed59
Plugin Manger: Loading ... (in progress)
AmmarAbouZor Dec 4, 2024
8448a28
Plugin Manager: Loading ... (in progress)
AmmarAbouZor Dec 4, 2024
9b72324
Plugin Manager: Loading ... (in progress)
AmmarAbouZor Dec 5, 2024
6b94045
Plugin Manager: Loading ... (in progress)
AmmarAbouZor Dec 5, 2024
34861b4
Plugin Manager: Loading for bytesource
AmmarAbouZor Dec 5, 2024
dd7c2aa
Plugins Manger: Loading method in rust bindings
AmmarAbouZor Dec 5, 2024
7c9c632
Plugins Integrations in ts bindings
AmmarAbouZor Dec 6, 2024
30d28c9
Plugins Manager: Integrations front end
AmmarAbouZor Dec 12, 2024
2ea1f83
Plugins Service in client & Wire up with core
AmmarAbouZor Dec 13, 2024
598a838
Plugins Manager: Basic UI implementation.
AmmarAbouZor Dec 13, 2024
fa45a79
Plugins: Use types on typescript for plugins
AmmarAbouZor Dec 16, 2024
fd0f94e
Plugins: Create Byte-Source structure in platform
AmmarAbouZor Dec 16, 2024
973fe00
Plugin: Build & Integrate plugin parser in platform
AmmarAbouZor Dec 17, 2024
5c0911c
Plugins: Integration into sessions (in progress)
AmmarAbouZor Dec 17, 2024
bcfc88d
Plugins UI: Placeholder for parser configurations
AmmarAbouZor Dec 18, 2024
fda8ce8
Plugins UI: Parser with streams (in progress)
AmmarAbouZor Dec 18, 2024
e7d4221
Plugins UI: Configuration Schemas (in progress)
AmmarAbouZor Dec 18, 2024
1139df9
Plugins UI: Integrating config schema in UI
AmmarAbouZor Dec 19, 2024
67ed968
Plugins UI: Save config value to their entry
AmmarAbouZor Dec 19, 2024
e641021
Plugin UI: Add basic renderer for plugins.
AmmarAbouZor Dec 19, 2024
e121414
Plugins: Finish integrating plugin in system (prototyping)
AmmarAbouZor Dec 19, 2024
59e68b1
Plugins: UI Fix binding & Extend Example Plugins
AmmarAbouZor Dec 20, 2024
28945f8
Merge branch 'master' into plugins_support
AmmarAbouZor Jan 7, 2025
4f85206
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 7, 2025
a71ea6a
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 8, 2025
a971c5e
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 8, 2025
57a8927
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 8, 2025
fab4a8a
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 8, 2025
b54aca1
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 9, 2025
8532801
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 9, 2025
212003b
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 9, 2025
8e1b4b2
Plugins: Adjustments after merging BinCode...
AmmarAbouZor Jan 10, 2025
28a8953
Plugins: Update wasmtime & wit-bindgen.
AmmarAbouZor Jan 10, 2025
f8af289
Plugins Parser: Temp changes to run benchmarks.
AmmarAbouZor Jan 13, 2025
3f6611a
Plugins: Extend config items in string parser
AmmarAbouZor Jan 13, 2025
b48bcca
Plugins UI: Add config renderer for numbers.
AmmarAbouZor Jan 13, 2025
d929421
Plugins UI: Add config renderer for dropdown.
AmmarAbouZor Jan 13, 2025
d826adb
Plugins Configs: Add paths UI & Adjustments.
AmmarAbouZor Jan 13, 2025
477c946
Plugins Configs: Separate files and dirs & Tooltips
AmmarAbouZor Jan 14, 2025
d441a15
Plugins: Extend render options & Their UI Implementation
AmmarAbouZor Jan 15, 2025
1546966
Plugins: Add render options to string parser.
AmmarAbouZor Jan 15, 2025
4939419
Plugins Parser: UI Integration with files (in progress)
AmmarAbouZor Jan 16, 2025
02b5c9c
Plugins Parser: UI Integration with files (done)
AmmarAbouZor Jan 17, 2025
1b85cdb
Plugins: Parser on all stream formats.
AmmarAbouZor Jan 17, 2025
0f268de
Plugins: Search results & Todos & Cleanup
AmmarAbouZor Jan 17, 2025
67f5058
Plugins: Fix warnings.
AmmarAbouZor Jan 17, 2025
f7cdab4
Plugins: Split WIT into three packages & Fixes
AmmarAbouZor Jan 21, 2025
2eac9b0
Plugins: API Documentations & Cleanup
AmmarAbouZor Jan 23, 2025
f2ac717
Plugins: Apply changes for shared types in host.
AmmarAbouZor Jan 23, 2025
955723d
Plugins: Functions for retrieving configuration values
AmmarAbouZor Jan 23, 2025
2434293
Plugins: Owning variant for some config getter functions.
AmmarAbouZor Jan 24, 2025
43e56c2
Plugins: Move example to root directory.
AmmarAbouZor Jan 24, 2025
026b72f
Plugins: Export only needed logging functions.
AmmarAbouZor Jan 24, 2025
e399436
Plugins: Adding DLT parser plugin.
AmmarAbouZor Jan 27, 2025
7ee8572
Merge branch 'master' into plugins_support
AmmarAbouZor Feb 5, 2025
1c947d0
Plugins: Fixes after merging master.
AmmarAbouZor Feb 5, 2025
799ddc1
Plugins: Configuration default values on plugins side
AmmarAbouZor Feb 5, 2025
a463d19
Plugins: Configs default values on host.
AmmarAbouZor Feb 6, 2025
3dc3202
Plugins: README for plugin development.
AmmarAbouZor Feb 7, 2025
833cf90
Plugins: Resolve TODOs & Refactoring & Documentation.
AmmarAbouZor Feb 7, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,562 changes: 1,545 additions & 17 deletions application/apps/indexer/Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions application/apps/indexer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ members = [
"indexer_cli",
"merging",
"parsers",
"plugins_host",
"processor",
"session",
"sources",
Expand Down Expand Up @@ -39,6 +40,8 @@ tempfile = "3.14"
env_logger = "0.11"
walkdir = "2.5"
envvars = "0.1"
anyhow = "1.0"
toml = "0.8"

## Development Dependencies ##
# Support for `html_reports` needs running the benchmarks via `cargo-criterion` tool.
Expand Down
26 changes: 26 additions & 0 deletions application/apps/indexer/indexer_cli/src/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,28 @@ pub(crate) async fn handle_interactive_session(input: Option<PathBuf>) {
session.observe(uuid, stypes::ObserveOptions::file(file_path.clone(), stypes::FileFormat::Binary, stypes::ParserType::Dlt(dlt_parser_settings))).expect("observe failed");
println!("dlt session was destroyed");
}
Some(Command::Plugin) => {
println!("plugin command received");
const PLUGIN_PATH_ENV: &str = "WASM_PLUGIN_PATH";

// Delivering the plugins info via env variables is good enough since this
// tool is going to be deprecated soon.
let plugin_path = match std::env::var(PLUGIN_PATH_ENV) {
Ok(path) => path,
Err(err) => panic!("Retrieving plugin path environment variable failed.\n\
Please set the plugin path via the environment variable {PLUGIN_PATH_ENV}.\n\
Err {err}") ,
};
start = Instant::now();
let uuid = Uuid::new_v4();
let file_path = input.clone().expect("input must be present");
let proto_plugin_path = PathBuf::from(plugin_path);

//NOTE: plugins configuration aren't delivered here.
let plugin_configs = Vec::new();
let plugin_parser_settings = stypes::PluginParserSettings::new(proto_plugin_path, Default::default() ,plugin_configs);
session.observe(uuid, stypes::ObserveOptions::file(file_path, stypes::FileFormat::Binary, stypes::ParserType::Plugin(plugin_parser_settings))).expect("observe failed");
}
Some(Command::Grab) => {
println!("grab command received");
start = Instant::now();
Expand Down Expand Up @@ -142,6 +164,7 @@ enum Command {
Dlt,
Grab,
Udp,
Plugin,
Stop,
Help,
}
Expand All @@ -159,6 +182,9 @@ async fn collect_user_input(tx: mpsc::UnboundedSender<Command>) -> JoinHandle<()
"dlt" => {
tx.send(Command::Dlt).expect("send failed");
}
"plugin" => {
tx.send(Command::Plugin).expect("send failed");
}
"stop" => {
tx.send(Command::Stop).expect("send failed");
break;
Expand Down
2 changes: 2 additions & 0 deletions application/apps/indexer/parsers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ extern crate log;

#[derive(Error, Debug)]
pub enum Error {
#[error("Unrecoverable error, cannot continue: {0}")]
Unrecoverable(String),
#[error("Parse error: {0}")]
Parse(String),
#[error("Incomplete, not enough data for a message")]
Expand Down
2 changes: 2 additions & 0 deletions application/apps/indexer/plugins_api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
**/target
Cargo.lock
36 changes: 36 additions & 0 deletions application/apps/indexer/plugins_api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[workspace]

[package]
name = "plugins_api"
version = "0.1.0"
edition = "2021"

[dependencies]
log = "0.4"
wit-bindgen = "0.37"

[dev-dependencies]
trybuild = "1.0"

[features]
default = []
parser =[]
bytesource = []

[[test]]
name = "parser"
required-features = ["parser"]

[[test]]
name = "bytesource"
required-features = ["bytesource"]

[package.metadata.docs.rs]
# Activate all features when generating the code on docs.rs
all-features = true
# Activate the banner on docs explaining that the items is only available
# with specific feature
rustdoc-args = ["--cfg", "docsrs"]

[package.metadata.component]
target = { path = "wit" }
14 changes: 14 additions & 0 deletions application/apps/indexer/plugins_api/open_docs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/bash

# This script generate the tests in matching conditions to the specification inside
# `Cargo.toml` file to match the generated docs on `docs.rs` once the crate is published
#
# * We add the flag `docsrs` that is available on nightly rust to get the hint about which
# type is available with which feature.
#
# * `all-features` flag to generate the documentation for the all available features.
#
# * `no-deps` and `workspace` to build docs for the libs defined in workspace only without
# their external dependencies

RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --workspace --all-features --open
229 changes: 229 additions & 0 deletions application/apps/indexer/plugins_api/src/bytesource/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
//! Provides types, methods and macros to write plugins that provide byte source functionality

use crate::shared_types::{ConfigItem, ConfigSchemaItem, InitError, Version};

#[doc(hidden)]
pub mod __internal_bindings {
wit_bindgen::generate!({
path: "wit/v0.1.0",
world: "chipmunk:bytesource/bytesource",
with: {
"chipmunk:shared/[email protected]": crate::logging,
"chipmunk:shared/[email protected]": crate::shared_types,
},
// Export macro is used withing the exported `bytesource_export!` macro and must be public
pub_export_macro: true,
// Bindings for export macro must be set, because it won't be called from withing the
// same module where `generate!` is called
default_bindings_module: "$crate::bytesource::__internal_bindings",
});
}

// External exports for users
pub use __internal_bindings::chipmunk::bytesource::bytesource_types::{SourceConfig, SourceError};

/// Trait representing a bytesource for Chipmunk plugins. Types that need to be
/// exported as bytesource plugins for use within Chipmunk must implement this trait.
pub trait ByteSource {
/// Provides the current semantic version of the plugin.
///
/// # Note
/// This version is for the plugin only and is different from the plugin's API version.
///
/// # Returns
/// A `Version` object representing the current version of the plugin.
fn get_version() -> Version;

/// Provides the schemas for the configurations required by the plugin, which
/// must be specified by the users.
///
/// These schemas define the expected structure, types, and constraints
/// for plugin-specific configurations. The values of these configurations
/// will be passed to the [`ByteSource::create()`] method for initializing the byte source.
///
/// # Returns
///
/// A `Vec` of [`ConfigSchemaItem`] objects, where each item represents
/// a schema for a specific plugin configuration.
fn get_config_schemas() -> Vec<ConfigSchemaItem>;

/// Creates an instance of the bytesource. This method initializes the bytesource,
/// configuring it with the provided settings and preparing it to provide bytes to Chipmunk.
///
/// # Parameters
///
/// * `general_configs` - General configurations that apply to all bytesource plugins.
/// * `plugins_configs` - Plugin-specific configurations, with their schemas provided
/// in [`ByteSource::get_config_schemas()`] method.
///
/// # Returns
///
/// A `Result` containing an instance of the implementing type on success, or an `InitError` on failure.
fn create(
general_configs: SourceConfig,
plugins_configs: Vec<ConfigItem>,
) -> Result<Self, InitError>
where
Self: Sized;

/// Reads and returns a specified number of bytes.
///
/// # Parameters
///
/// * `len` - The minimum number of bytes to read. The returned vector's length will be at least this value.
///
/// # Returns
///
/// A `Result` containing a vector of bytes on success, or a `SourceError` on failure.
fn read(&mut self, len: usize) -> Result<Vec<u8>, SourceError>;
}

#[macro_export]
/// Registers the provided type as bytesource plugin to use within Chipmunk
///
/// The type must implement the [`ByteSource`] trait.
///
/// # Examples
///
/// ```
/// # use plugins_api::bytesource::{ByteSource, SourceConfig, SourceError};
/// # use plugins_api::bytesource_export;
/// # use plugins_api::shared_types::{Version, ConfigSchemaItem, ConfigItem, InitError};
///
/// struct CustomByteSoruce;
///
/// impl ByteSource for CustomByteSoruce {
/// // ... //
/// # fn get_version() -> Version {
/// # Version::new(0, 1, 0)
/// # }
/// # fn get_config_schemas() -> Vec<ConfigSchemaItem> {
/// # vec![]
/// # }
/// #
/// # fn create(
/// # _general_configs: SourceConfig,
/// # _plugins_configs: Vec<ConfigItem>,
/// # ) -> Result<Self, InitError>
/// # where
/// # Self: Sized,
/// # {
/// # Ok(Self)
/// # }
/// #
/// # fn read(&mut self, _len: usize) -> Result<Vec<u8>, SourceError> {
/// # Ok(vec![])
/// # }
/// }
///
/// bytesource_export!(CustomByteSoruce);
/// ```
macro_rules! bytesource_export {
($par:ty) => {
// Define bytesource instance as static field to make it reachable from
// within read function of ByteSource trait
static mut BYTESOURCE: ::std::option::Option<$par> = ::std::option::Option::None;

// Define logger as static field to use it with macro initialization
use $crate::__PluginLogSend;
use $crate::__PluginLogger;
static LOGGER: __PluginLogger<__PluginLogSend> = __PluginLogger {
sender: __PluginLogSend,
};

// Name intentionally lengthened to avoid conflict with user's own types
struct InternalPluginByteSourceGuest;

impl $crate::bytesource::__internal_bindings::exports::chipmunk::bytesource::byte_source::Guest
for InternalPluginByteSourceGuest
{
/// Provides the current semantic version of the plugin.
/// This version is for the plugin only and is different from the plugin's API version.
fn get_version() -> $crate::shared_types::Version {
<$par as $crate::bytesource::ByteSource>::get_version()
}
/// Provides the schemas for the configurations needed by the plugin to
/// be specified by the users.
fn get_config_schemas() -> ::std::vec::Vec<$crate::shared_types::ConfigSchemaItem> {
<$par as $crate::bytesource::ByteSource>::get_config_schemas()
}

/// Initialize the bytesource with the given configurations
fn init(
general_configs: $crate::bytesource::SourceConfig,
plugin_configs: ::std::vec::Vec<$crate::shared_types::ConfigItem>,
) -> ::std::result::Result<(), $crate::shared_types::InitError> {
// Logger initialization
let level = $crate::log::__Level::from(general_configs.log_level);
$crate::log::__set_logger(&LOGGER)
.map(|()| $crate::log::__set_max_level(level.to_level_filter()))
.expect("Logger can be set on initialization only");

// Initializing the given bytesource
let source = <$par as $crate::bytesource::ByteSource>::create(
general_configs,
plugin_configs,
)?;
// SAFETY: Initializing the bytesource happens once only on the host
unsafe {
BYTESOURCE = ::std::option::Option::Some(source);
}

Ok(())
}

/// Reads more bytes returning a list of bytes with the given length if possible
fn read(
len: u64,
) -> ::std::result::Result<::std::vec::Vec<u8>, $crate::bytesource::SourceError> {
use $crate::bytesource::ByteSource;
// SAFETY: Bytesource host implements read trait, which takes a mutable reference
// to self when called. Therefor it's not possible to have multiple references on
// the static bytesource instance here at once.
//TODO AAZ: Measure the impact on this unsafe function and provide explanation for
// suppressing the warning here.
#[allow(static_mut_refs)]
let source =
unsafe { BYTESOURCE.as_mut().expect("Bytesource already initialized") };
source.read(len as usize)
}
}

// Call the generated export macro from wit-bindgen
$crate::bytesource::__internal_bindings::export!(InternalPluginByteSourceGuest);
};
}

// This module is used for quick feedback while developing the macro by commenting out the cfg
// attribute. After developing is done the attribute should be put back so this module won't be
// compiled in all real use cases;
#[cfg(test)]
mod prototyping {
struct Dummy;

impl crate::bytesource::ByteSource for Dummy {
fn get_version() -> crate::shared_types::Version {
todo!()
}

fn get_config_schemas() -> Vec<crate::shared_types::ConfigSchemaItem> {
todo!()
}

fn create(
_general_configs: crate::bytesource::SourceConfig,
_plugins_configs: Vec<crate::shared_types::ConfigItem>,
) -> Result<Self, crate::bytesource::InitError>
where
Self: Sized,
{
todo!()
}

fn read(&mut self, _len: usize) -> Result<Vec<u8>, crate::bytesource::SourceError> {
todo!()
}
}

bytesource_export!(Dummy);
}
Loading