Open juntao opened 1 year ago
Flows summarize
Hello, I am a code review bot on flows.network. Here are my reviews of code commits in this PR.
This pull request introduces a number of changes to the fluvio-smartengine
crate, with some focused on code refactoring, implementing new features, renaming items for consistency, and relocating files to improve organization. The primary changes relate to the introduction of the wasmedge-engine
feature, SimpleTransformImpl
struct and related traits, support for initialization functions in the wasmedge/common
module, and code reorganization for transform unit tests.
Potential issues include but are not limited to:
Cargo.toml
file.RecordsMemory
and RecordsCallBack
.Important findings to consider are:
wasmtime-engine
and wasmedge-engine
features simultaneously.fluvio-socket
in the Cargo.lock
file.Overall, this pull request makes several key improvements to the fluvio-smartengine
crate, addressing both code quality and the addition of new engine features. Careful attention should be paid to potential issues and ensuring that tests and documentation are updated to reflect the changes in the codebase.
This patch aims to make the public API clear and initializes the work for the wasmedge_engine
feature. The key changes to note are:
wasmtime-engine
and wasmedge-engine
are introduced in Cargo.toml
. Later on, it's expected that only one WASM runtime can be chosen at a time.config.rs
is added, which introduces SmartModuleInitialData
, SmartModuleConfig
, SmartModuleConfigBuilder
, and their implementations.SmartModuleConfig
and SmartModuleInitialData
is extracted from engine.rs
to the new config.rs
file.wasmedge_engine/mod.rs
is added, which introduces SmartEngine
, SmartModuleChainBuilder
, and SmartModuleChainInstance
for wasmedge_engine
.lib.rs
, a TODO comment is added for a future check which ensures that not both wasmedge_engine
and wasmtime_engine
features are enabled simultaneously.Potential problems:
wasmedge_engine
and wasmtime_engine
features in the future. This may lead to unintended behavior if both these features are enabled simultaneously.wasmedge-engine
feature isn't fully implemented yet; the added structures and functions in wasmedge_engine/mod.rs
contain todo!()
blocks. More work is needed for completion, so using this feature in its current state may lead to issues.This patch implements a filter transform in the fluvio-smartengine
crate. The key changes include:
instance
, memory
, transforms
, and init
inside the wasmedge_engine
folder.SmartModuleInstance
struct to manage the filter transform instance.Cargo.toml
and Cargo.lock
to include the necessary dependencies including wasmedge-sdk
and wasmedge-macro
.SmartModuleTransform
trait to handle transformations.SmartEngine
struct to support the new transform.initialize
method to create a SmartModuleChainInstance
.Potential problems:
import
and module
objects in the SmartModuleInstanceContext::instantiate()
function, as they are both intentionally leaked using std::mem::forget
.Clone
trait is possibly unnecessary for the RecordsMemory
struct but has been implemented.Possible areas for improvements:
import
and module
objects should be investigated further and improved if possible.DowncastableTransform
trait could be reviewed and possibly removed or simplified if possible.Summary:
common.rs
for WasmInstance
, WasmFn
, SmartModuleTransform
, and DowncastableTransform
traits, and SimpleTransformImpl
struct. src
folder to src/engine
folder, such as config.rs
, engine.rs
, error.rs
, fixture.rs
, init.rs
, metrics.rs
, and so on.SmartEngine
struct as SmartEngineImp
. initialize_imp
function for initializing SmartModuleChainInstanceImp
. Potential Problems:
instance.rs
has been shortened, and some parts are missing.Summary of key changes:
pub(crate)
.Potential problems:
pub
keyword from the struct fields and renaming features in the Cargo.toml file, there may be potential compatibility issues with the existing codebase.This patch primarily moves the wasmtime_engine
module to a different location in the crate fluvio-smartengine
. The key changes are as follows:
wasmtime_engine
module is moved from crates/fluvio-smartengine/src/engine
to a new nested module in the same directory.mod.rs
file is updated to reflect this move, changing the usage of the wasmtime_engine
module.engine
directory to the new wasmtime_engine
module.Potential problems:
This patch modifies the features section and their dependencies in the Cargo.toml file for the fluvio-smartengine crate. The key changes are as follows:
The 'wasi' feature is changed to include "wasmtime-engine" as a dependency, in addition to the existing "wasmtime-wasi" and "engine".
The 'wasmtime-engine' feature is modified to only depend on "wasmtime", with the dependency on "wasmtime-wasi" removed.
Potential problems:
This GitHub patch renames the module wasmtime_engine
to wasmtime
. The key changes are as follows:
Rename the module: All instances of wasmtime_engine
are replaced with wasmtime
. This includes renaming the directory and references to the module in the code.
Update import statements: Various import statements are modified to use the new module name wasmtime
instead of wasmtime_engine
.
Since this patch only changes the module name and updates the relevant import statements, there are no potential problems introduced by the changed code. It is a straightforward module renaming and refactoring patch.
This patch introduces several key changes to the fluvio-smartengine
crate:
wasmtime
subdirectory. The primary modules affected are engine
, init
, instance
, and memory
among others.mod.rs
file in the engine
module has been modified to import the modules from the wasmtime
directory.wasmtime/mod.rs
has been created, consolidating the module imports and addressing the organizational changes in the engine
module.RecordsCallBack
and copy_memory_to_instance
functions.Overall, the changes seem to focus on code structure and organization. There are no added features or major adjustments to the code itself. The primary potential issue with this patch is that the changes may affect the build process or crate's functionality in unforeseen ways. To ensure that the crate still builds and operates as expected, it is essential to run tests, verify the build process, and ensure that all modules are still correctly referenced.
Possible issues:
This patch focuses on adding support for initialization functions in the wasmedge/common
module.
Key changes:
engine
feature flag in Cargo.toml
, which includes both wasmtime-engine
and wasmedge-engine
.crates/fluvio-smartengine/src/engine/common.rs
. This includes:
INIT_FN_NAME
: A constant representing the initialization function name "init"
SmartModuleInit
and its associated methods, which are the main components for handling module initializationcrates/fluvio-smartengine/src/engine/wasmedge/init.rs
as the functionality is now moved to the common module.instance.rs
to use the new implementation in the common module.mod.rs
to use the updated SmartModuleInit
implementation.Potential problems:
instance.rs
using std::mem::forget
could lead to memory leaks or unexpected issues if not properly managed.wasmtime
and wasmedge
engines, especially if both are used together.The key changes in the given GitHub patch are:
SmartModuleInstance
in the engine/common.rs
module.SmartModuleInstance
in the engine/wasmedge/instance.rs
module by importing and using the common SmartModuleInstance
.params
to the SmartEngineImp
struct.initialize_imp
function signature and usage to reflect the new changes.Potential problems:
initialize_imp
function's code is duplicated both in engine/mod.rs
and engine/wasmedge/mod.rs
.SmartEngineImp
and SmartEngine
.params()
function in the WasmInstance
trait.To summarize, this patch introduces a new common SmartModuleInstance
, modifies existing module instances to use the new common instance, and updates function signatures and usage accordingly. Some potential issues to look out for include insufficient test adjustments, code duplication, and discrepancies between implementations.
Summary of key changes:
Potential problems:
This patch includes changes to the fluvio-smartengine crate for the WasmEdge engine, with a substantial refactoring of the codebase. The key changes are as follows:
imp.rs
and init.rs
files, and merging their contents into instance.rs
.common.rs
file to reorder the import statements for better readability.WasmInstance
trait for WasmedgeInstance
and the WasmFn
trait for WasmedgeFn
.RecordsMemory
and RecordsCallBack
in a new memory.rs
file.Potential problems:
RecordsMemory
and RecordsCallBack
might have issues with the memory management of the engine.imp.rs
and init.rs
files might lead to a loss of functionality or breaking changes if there are any dependencies on these files that are not addressed in the new implementation.common.rs
file might introduce breaking changes if there are unresolved dependencies.Summary of key changes:
wasmedge
transforms:
a. array_map.rs
- Tests the array_map transform.
b. filter_map.rs
- Tests the filter_map transform.
c. map.rs
- Tests the map transform.filter.rs
.get_transform
function in the common.rs
file to use a match
statement instead of .ok_or_else
handling.Potential problems:
#[ignore]
attribute, so they will not run by default during testing, which might hide test failures. If you want these tests to run during normal test execution, you should remove the #[ignore]
attribute.mod.rs
file, which could potentially cause issues with certain tools or editors. It is recommended to add a newline at the end of the file.Summary of key changes in this patch:
aggregate.rs
file is created containing tests and implementation for the aggregate transform.common.rs
include the addition of the AggregateTransform
struct along with its try_instantiate
and process
methods. Code for instantiation and data processing in aggregate transform is added as well. A new constant AGGREGATE_FN_NAME
is introduced and set to "aggregate"
.mod.rs
adds a new module import for aggregate
.Potential problems to investigate:
aggregate.rs
have the #[ignore]
attribute which means those tests won't be run, allowing undetected bugs in the added functionality. It is recommended to carefully analyze the necessity of ignoring these tests.This patch contains changes across three files, mainly focused on implementing and utilizing the WasmEdge engine within the SmartEngine.
Key changes:
mod.rs
to a new module imp.rs
inside the wasmedge
engine. imp.rs
contains methods for initializing and processing the SmartModuleChainInstanceImp.mod.rs
file now only contains public API imports from imp.rs
, along with imports of the other existing modules (instance, memory, and transforms).Potential issues:
Vec
might not be the most efficient way for performance under large operation queues. However, as the code is already implementing the split_last_mut()
and try_into()
methods for handling input mutations, it might be an acceptable balance for now.This patch refactors the wasmtime-related code in the Fluvio smart engine. The major changes include:
crates/fluvio-smartengine/src/engine/wasmtime/engine.rs
file and moved its contents to the more general crates/fluvio-smartengine/src/engine/wasmtime/imp.rs
file.SmartEngineImp
in crates/fluvio-smartengine/src/engine/wasmtime/imp.rs
as a new implementation.crates/fluvio-smartengine/src/engine/mod.rs
to use the new implementation for wasmtime.memory.rs
to handle memory-related operations in wasmtime.Potential issues:
This patch renames the WasmTime
struct and related types, variables, and functions to follow proper naming conventions with Wasmtime
.
Key changes:
WasmTimeInstance
to WasmtimeInstance
.WasmTimeContext
to WasmtimeContext
.WasmTimeFn
to WasmtimeFn
.WasmTimeFn::call
to WasmtimeFn::call
.Potential problems:
This patch moves the transform unit tests to a common directory, and mostly involves file relocation and renaming. It also adds a check to compile with an error if both "wasmedge-engine" and "wasmtime-engine" features are enabled at the same time.
Key changes:
init.rs
and mod.rs
in the "common" directoryCargo.toml
to include the changesPotential problems:
This patch is renaming the Wasmedge
prefix to WasmEdge
throughout the codebase for consistency reasons. The key changes are as follows:
Renamed the following module names:
WasmedgeFn
to WasmEdgeFn
WasmedgeInstance
to WasmEdgeInstance
WasmedgeContext
to WasmEdgeContext
Updated type aliases and structural changes to maintain consistency with the new names:
Potential Problems:
To address these potential problems, a thorough review of the entire codebase must be done to ensure all instances of the old names are replaced with the new names. In addition, any documentation or comments should be updated accordingly.
Hello, I am a code review bot on flows.network. Here are my reviews of changed source code files in this PR.
Cargo.lock
As the code is quite long, here's a summary of what I found broken down into categories:
General review:
Minor issues:
There is a missing space after the
version
attribute in the following package entries:These entries should look like this:
There are multiple entries for different versions of some packages:
It's better to use one version of a package to avoid conflicts and potential issues in your project. To resolve this, consider removing the older versions and adjusting your source code accordingly.
As for the rest of the code, there are no significant issues that need immediate attention. Given that the extracted code snippet is a Cargo.lock file and not actual source code, no more in-depth analysis seems to be necessary.
The patch introduces the following key changes:
Added new packages and their dependencies:
Introduced the dependency of the existing package on the newly added packages:
The addition of these new packages and dependencies broadens the functionality of the project by including packages related to the WebAssembly system (wasmedge-*), Rust code bindings (bindgen), C-style expressions parsing (cexpr), and more.
crates/fluvio-smartengine/Cargo.toml
Overall, the source code is clean and well-organized, though it is truncated and thus might be missing some essential parts. Here are a few observations and suggestions for potential improvements:
[documentation]
field to the[package]
section. This field is critical for new users who want to understand how to use the Fluvio SmartEngine library. Including a direct link to the documentation site in theCargo.toml
file makes it easier for developers to access it.Example:
[features]
section. Each feature should have a brief description in the form of comments, explaining its purpose and how it contributes to the package.Example:
[dependencies]
section, ensure consistent formatting for readability. Some dependencies include comments, while others do not. Also, "workspace = true" is used for most dependencies, except "wasmedge-sdk", which should be kept consistent as well.Eg.: Add a comment to the
wasmedge-sdk
dependency to maintain consistency:Other than these minor improvements, the source code appears well structured and organized, and it adheres to good practices in dependency management, feature flag usage, and consistent formatting.
The key changes in this patch are:
The
[features]
section has been updated:engine = ["wasmtime-engine", "wasmedge-engine"]
is added to include both Wasmtime and WasmEdge engines.engine
feature has been added as a dependency to thewasi
feature. Now,wasi = ["wasmtime-wasi", "wasmtime-engine", "engine"]
.wasmtime-engine = ["wasmtime"]
for Wasmtime engine.wasmedge-engine = ["wasmedge-sdk"]
for WasmEdge engine.A comment
# Use the Clone trait
has been added before thewasmedge-sdk
dependency in the[dependencies]
section. This comment highlights that theClone
trait is being used for the WasmEdge SDK dependency.Other aspects of the code remain the same, and the patch focuses on enhancing the engine features and their dependencies, leading to cleaner and more modular management of the engines.
crates/fluvio-smartengine/src/engine/common.rs
Overall, the code seems to be well-wrapped, and no critical problems could be found considering the part that we have. However, there are a few suggestions and observations that can be made:
Code Documentation: Add comments to your code to explain what each function and struct does. This will make the code more readable and maintainable.
Error handling: In the
create_transform
function, the error handling could be improved. The code currently checks each type of transform function one by one, and if none of them matches, it returns theUnknownSmartModule
error (else block). You can refactor this part to make it more elegant and avoid duplicating the error handling for each case.Reusability and Modularity: Make sure that the code is structured in a way that allows flexible modification and extension easily.
Unnecessary Visibility: There's a
#[cfg(test)]
mark with a#[allow(clippy::borrowed_box)]
attribute for thetransform
function. This can be a sign of an issue in the design if such code is required. Consider rethinking this part of the code if it is required to expose an internal component for tests.Code formatting: Make sure that the code is well-formatted and follows a consistent coding style. This will make the code easier to read and maintain.
Please note that since the code might be truncated, the evaluation is only based on the provided code snippet. There might be some other issues or improvements that can be suggested when reviewing the complete codebase.
This patch introduces several key changes:
It defines new traits
WasmInstance
,WasmFn
, andSmartModuleTransform
. These traits describe the behavior of WebAssembly instances, WebAssembly functions, and SmartModule transformations, respectively.It implements a new struct
SimpleTransform
that can perform simple SmartModule transformations based on a provided WebAssembly function. TheSimpleTransform
struct works with the WasmInstance trait and is generic over a concrete implementation of theWasmFn
trait.It adds a method
create_transform
that attempts to create aSimpleTransform
instance for a given WebAssembly instance by trying various function names such as "filter", "map", "filter_map", and "array_map".It adds a new struct
SmartModuleInit
that wraps a WebAssembly function to initialize SmartModules. This struct provides a methodinitialize
to call the wrapped initialization function.It introduces a new struct
SmartModuleInstance
which combines a WebAssembly instance, a SmartModule transformation, and an optional SmartModule initialization function. This struct provides methods for processing input data and initializing the SmartModule.Overall, the patch aims to improve code organization, abstraction, and modularity. It allows for better interoperability between WebAssembly instances, functions, and SmartModule transformations.
crates/fluvio-smartengine/src/engine/mod.rs
Overall, the code is well-formatted and looks clean. However, I spotted a few points of improvement:
Add documentation/comments: Some of the structs and functions are missing comments explaining their functionality which makes it difficult to understand the code at a glance. Make sure to include comments/documentation wherever necessary.
In
SmartModuleChainBuilder
, there is a hard-coded error message that may not be relevant as the check is commented out:Remember to resolve the TODO and uncomment the check when it's relevant.
WasmSlice
andVersion
type aliases are used for in this code snippet, as they are not utilized in the provided code. You may want to either use them in the code or remove them if they are not necessary.Consider splitting the source code into smaller modules. As there are multiple structs and much functionality implemented in the main source file, it may be beneficial to have separate modules for each functionality, like
smart_engine
,smart_module_chain_builder
, andsmart_module_chain_instance
.The code uses
cfg_if
to conditionally import and use different engine implementations (Wasmer and WasmEdge). Make sure to include the following dependencies in theCargo.toml
file to usecfg_if
.This should give you an overall review of the code and some suggestions for improvement.
The key changes in the provided patch are:
SmartEngine
along with its implementation, which represents the WASM engine and is derived fromClone
. It has a single method,new()
, for creating a new instance of theSmartEngine
.SmartModuleChainBuilder
with a default implementation, which is responsible for building the SmartModule chain. It comprises methods likeadd_smart_module
to add a SmartModule to the chain andinitialize
to initialize it.SmartModuleChainInstance
representing an instance of the SmartModule chain along with itsDebug
implementation. It has a methodprocess
to process a single record through all the SmartModules in the chain.wasmtime-engine
andwasmedge-engine
:Overall, the update adds structs and functionality to create a SmartEngine, build a SmartModule chain, and process records through the chain for different engine configurations.
crates/fluvio-smartengine/src/engine/wasmedge/instance.rs
Here is a code review of the given source code, mentioning potential issues and suggestions for improvements:
Error handling
get_fn
function, the function name lookup error is silently consumed and returnsNone
. It might be better to return aResult<Option<Self::Func>, HostFuncError>
so that the caller can handle errors properly.Synchronization
WasmedgeInstance
uses an internalArc<RecordsCallBack>
for shared record access. However, it is not clear ifget
,set
, andclear
methods of RecordsCallback are thread-safe. If not, consider adding synchronization mechanisms (e.g., Mutex, RwLock) to make it thread-safe.Code documentation:
Lifetime management
instantiate
function, there is a use ofstd::mem::forget
to avoid droppingimport
andmodule
. Please note that usingstd::mem::forget
may cause memory leaks. To resolve this, you can try to manage their lifetimes properly or utilize other mechanisms, such asArc
orRc
, to keep shared references.Code readability:
write_input
function, improve the formatting for thedebug!
macro to be consistent with other debug macros in the code.Overall, the code looks good but can benefit from a few minor improvements for better maintainability and performance.
This patch provides various adjustments to the original source code. Key changes include:
The patch mainly serves as a reiteration of the existing code with minor adjustments. No new issues or improvements have been introduced. The previous code review suggestions still apply for potential improvements in error handling, synchronization, code documentation, lifetime management, and code readability.
crates/fluvio-smartengine/src/engine/wasmedge/memory.rs
Here are a few observations and potential problems:
Use of
unwrap()
: There are a couple of usages ofunwrap()
in the code, which might lead to unexpected panics if theResult
has anErr
value or theOption
isNone
. It's recommended to use more idiomatic error handling using?
instead.Potential issues with naming: The naming of the struct
RecordsCallBack
isn't consistent with the function names from the related moduleRecordsMemory
. To maintain uniformity, you can consider renamingRecordsCallBack
to something likeRecordsMemoryHandler
.Functions can be more modular: Functions like
copy_memory_to_instance
perform more than one task, making them less modular. To make the code more maintainable and easier to debug, it’d be better to break them into smaller reusable functions.Missing documentation: There isn't enough documentation in the form of comments for the structs and some functions. Going forward, adding more documentation would enhance the code's readability and help other developers understand the code better without having to dig through the entire implementation.
Unused commented-out constants:
They should be either removed or used if needed.
Overall, apart from the mentioned concerns, the code seems to compile and run as expected. Making the implied changes would result in better-quality, maintainable and readable code.
The provided patch primarily retains the original source code without any significant changes. Here's a summary of the existing code:
It imports the necessary modules and defines main constants (
ALLOC_FN
andMEMORY
) used in the code.The
copy_memory_to_instance
function copies a byte array into an instance’s linear memory and returns the resulting offset relative to the module's memory.It defines a
RecordsMemory
struct, which holdsptr
,len
, andmemory
properties. Theclone
attribute is set to the struct, and acopy_memory_from
function is implemented, which reads data from the memory and returns aResult
with a byte vector.The
RecordsCallBack
struct definition is provided, creating a wrapper around aMutex<Option<RecordsMemory>>
. It has helper methods that allow creating a newRecordsCallBack
, setting and clearing the internalRecordsMemory
, and getting the current value.Overall, the patch maintains the previous code but does not address the concerns or recommendations mentioned in the previous response.
crates/fluvio-smartengine/src/engine/wasmedge/mod.rs
The source code seems to be clean and well-organized. However, I have a few minor suggestions that could improve the code quality:
In the
initialize_imp
function, you havelet mut store = Store::new().expect("Failed to create WasmEdge store");
. However, it looks likestore
is not mutated anywhere in the function. You can remove themut
keyword:It would be helpful to add comments throughout the codebase to describe what each function does and, if necessary, the inner workings of any complex code. For example, you could add comments to the
process
function in theSmartModuleChainInstanceImp
struct to make it clear what's happening inside the function.Instead of using
Result
, you could consider creating a custom error type for your module. It could help with debugging and make your error handling more explicit.In some places, the naming could be more descriptive to provide a better understanding of the variables and types being used. For example, instead of
SmartEngineImp
, you might consider renaming the type toSmartEngineImpl
to better align with the common Rust convention of using "Impl" for implementations. Similarly, think about renaming variables likectx
tocontext
, providing more context.?
operator instead of unwrapping withexpect
:In some places, like creating the
Executor
andStore
, the code usesexpect
to unwrap the result. This could cause the program to panic if any issues arise. Instead of usingexpect
, consider using the?
operator to propagate the error:Keep in mind that you need to change the function signature to support the error type returned by
Executor::new
andStore::new
.Overall, the code looks good, and with these minor suggestions, it can be improved.
The patch provided introduces a new implementation for the WasmEdge engine, along with the use of several modules (
instance
,memory
, andtransforms
). Key changes in the implementation include:Creation of the
SmartEngineImp
struct, which is used to instantiate a new instance of theSmartEngineImp
type.initialize_imp
function: Takes aSmartModuleChainBuilder
and a reference toSmartEngineImp
as input and returns aResult
containing aSmartModuleChainInstanceImp
. It initializes aWasmedgeContext
using the WasmEdge executor and iterates over each smart module in the builder, instantiating aWasmedgeInstance
and initializing it with the appropriate configuration parameters.SmartModuleChainInstanceImp
struct: Contains theWasmedgeContext
and a vector ofSmartModuleInstance
. It has a method calledprocess
, which takes aSmartModuleInput
and a reference toSmartModuleChainMetrics
as parameters. The method sequentially processes data through each smart module instance in the chain.The output of one smart module is transformed and passed as input to the next smart module in the chain. If any errors are encountered, a partial output is returned. The output of the last smart module is added to the output of the entire chain.
crates/fluvio-smartengine/src/engine/wasmedge/transforms/filter.rs
Here are some observations after reviewing the source code:
Missing documentation: The code would benefit from more comments and explanations of what each test is supposed to test or verify. This would make it easier for future developers to understand the intent and expectations of each test.
Test naming: Some of your tests begin with
test_
(liketest_filter()
) while others don't (like#[test] fn test_filter_with_init_invalid_param()
). It would be best to keep the naming convention consistent throughout the tests.#[ignore]
attributes: It seems that some tests are marked with#[ignore]
, which means these tests will not be executed when you runcargo test
. If these tests are meant to be run, you should remove the#[ignore]
attribute. If they are intentionally ignored and should not be run in normal test execution, it would be helpful to add a comment explaining why these tests are ignored.Magic strings/numbers: There are a few instances of hard-coded strings and numbers in the tests like
Record::new("hello world")
orRecord::new("apple")
oroutput.successes.len(), 0
. These would be better as constants or variables with meaningful names at the top of the testing module, so it's clear what they represent and they can be easily reused or updated as needed.Repeated code: Both
test_filter()
andtest_filter_with_init_ok()
tests use similar code for processing input records and asserting the success count. If you find yourself using the same code in multiple tests, consider refactoring the code into helper functions to enhance code reuse and maintainability.Overall, the code appears to be functional and does perform tests on the engine's capabilities. However, improvements can be made in terms of commenting, consistent naming and formatting, and refactoring some parts of the test code to make it more maintainable and reusable.
The key changes in this patch are as follows:
Added a new testing module (
#[cfg(test)] mod test
) with test functions.Imported necessary dependencies, including
SmartEngine
,SmartModuleChainBuilder
,SmartModuleConfig
, andSmartModuleInput
.Defined constants
SM_FILTER
andSM_FILTER_INIT
representing module strings.Created and used a new
test_filter()
function that initializes theSmartEngine
, creates instances ofSmartModuleChainBuilder
, and processes input records. The test checks for the expected length of the output successes.Added two test functions with
#[ignore]
attribute:test_filter_with_init_invalid_param()
andtest_filter_with_init_ok()
. Both tests validate the behavior ofSmartModuleChainBuilder
initialization and input processing with specific parameters.The
test_filter_with_init_ok()
function checks multiple scenarios, including processing input records with different parameters and validates the success counts after processing.crates/fluvio-smartengine/src/engine/wasmedge/transforms/mod.rs
As the given code snippet is incomplete and provides only a module declaration, it is not possible to identify potential issues in the actual code. To provide appropriate suggestions, please present more of the source code to be reviewed.
The patch introduced a single line of code which adds a module called
filter
. This change creates a new module inside the current package or project, allowing for better organization and separation of code. The actual logic to be included in the filter module is not provided in this snippet.crates/fluvio-smartengine/src/engine/wasmtime/engine.rs
The code is overall well-written, and it seems to follow best practices. However, there are a few observations and recommendations:
Code documentation and comments
///
) should be added for public types and functions.Error handling
SmartEngineImp::new()
function, there is anexpect("Config is static")
call after creating a new engine. Usingexpect()
implies that there might be a case where it could panic. Instead, it would be better to propagate the error using the?
operator and return aResult<Self>
from the function.Tests coverage
test
module. However, it's recommended to expand the test coverage to cover more scenarios and edge cases to ensure the code works as expected.Using
cfg_attr
#[allow(clippy::new_without_default)]
, you can conditionally apply this attribute:This way, the attribute will only be applied when running Clippy, and it won't affect other tools and regular compilation.
This patch includes the following key changes:
SmartEngine
toSmartEngineImp
.Debug
implementation forSmartEngine
andSmartModuleChainInstance
.SmartModuleChainBuilder
struct and its associated methods, moving theinitialize
method outside the struct, now calledinitialize_imp
.initialize_imp
function to directly takesuper::SmartModuleChainBuilder
andSmartEngineImp
as arguments and return aResult<SmartModuleChainInstance>
.initialize_imp
function signature and extracted theinner
property for the createdSmartModuleChainInstance
.These changes simplify the code and make it more straightforward for users to work with.
crates/fluvio-smartengine/src/engine/wasmtime/imp.rs
Overall, the code looks clean and well-organized. Here are some suggestions on potential improvements and issues:
WasmTimeFn
andWasmTimeContext
struct definitions, consider adding the#[derive(Debug)]
attribute to automatically derive a default implementation of theDebug
trait. This will enable easier debugging, if necessary.WasmTimeInstance
struct, consider storing a reference toWasmTimeContext
instead of the actual context struct. This way, the same context could be reused across multipleWasmTimeInstance
s, and you avoid unnecessary clones.In the
get_fn
method, there is anor_else
statement that attempts to call thetyped
method with the same parameters. This code doesn't seem to be useful and may lead to the same errors being returned. Consider removing theor_else
block unless it has a specific purpose.In the
read_output
method, theunwrap_or_default
method is used. If there is an issue retrieving the data, this method returns an emptyVec
. Instead of hiding the error, consider returning a proper error message if something goes wrong.write_input
andread_output
method signatures include theSelf::Context
type with a mutable reference. If you plan to use the Context across multiple threads or need thread-safety guarantees, consider using a Mutex or RwLock from thestd::sync
module.Please note that without complete context on how this code is being used, these suggestions may need to be modified or may not apply to your specific use case.
This patch introduces two structs,
WasmTimeInstance
andWasmTimeContext
along with a type aliasWasmTimeFn
, which represents a typed Wasm function with a specific signature.The
WasmTimeInstance
struct holds information about a Wasm instance, such as anInstance
, a reference-countedRecordsCallBack
(usingArc
), aSmartModuleExtraParams
, and a version number.The
WasmTimeContext
struct stores awasmtime::Store
, which is used for interacting with Wasm functions.Key changes in the patch include:
WasmInstance
trait forWasmTimeInstance
. This adds methods likeget_fn
,write_input
,read_output
, andparams
to the struct.WasmFn
trait forWasmTimeFn
, enabling thecall
method to be used on it along with a mutable reference to aWasmTimeContext
.The code primarily focuses on defining data structures for the Wasm instance and context, implementing traits for them, and providing methods for working with Wasm functions, handling input/output, and managing extra parameters.
crates/fluvio-smartengine/src/engine/wasmtime/instance.rs
Below are some potential issues and suggestions in the provided code:
Missing documentation: Add documentation to describe the purpose and functionality of each struct and function in the code. This is helpful for other developers to understand the code.
Clippy warning: In the function
transform(&self)
, remove the#[allow(clippy::borrowed_box)]
attribute, and instead, return a reference to the trait object itself:RecordsMemory::copy_memory_from()
function returns aResult
, but inSmartModuleInstanceContext::read_output()
, it is not properly handled:Instead of silently using an empty Vec, consider propagating the error:
SmartModuleInstanceContext::instantiate()
function, the message says "creating WasmModuleInstance", but it is actually creating aSmartModuleInstanceContext
. Update the debug message to reflect the actual operation:Unclear naming: The struct
RecordsCallBack
could be renamed to a more descriptive name likeRecordsBuffer
to explain its purpose better.Better encapsulation: The functions
get()
,set()
andclear()
inRecordsCallBack
could be markedpub(crate)
since they are only used within the crate. This will help with better encapsulation.Mutex usage: Using
Mutex
can potentially block the execution, and in environments like async code, this might cause issues. If this code is planned to be used in an async environment, consider usingasync-std
ortokio
mutexes.Error types: Use custom error types and
thiserror
crate to have more readable and actionable errors, instead of using generic errors likeError::new()
,anyhow::bail!
.Input checks: Verify that the input values passed to the functions are valid. For example, in the
RecordsMemory
struct, check for negative values forptr
andlen
.Unit tests: Include unit tests to verify the functionality of the code.
After addressing these issues, the reviewed code would be more efficient, maintainable, and comprehensible to developers.
In the provided patch, the visibility of the
copy_memory_from()
function within theRecordsMemory
struct has been changed from private (implicitly) to public. This change allows other modules or structs outside of theRecordsMemory
struct to directly call thecopy_memory_from()
function to copy memory from a given context (store).crates/fluvio-smartengine/src/engine/wasmtime/mod.rs
In the provided source code snippet, there doesn't seem to be any obvious issues, such as syntax errors or bad practices. However, to better evaluate the overall quality and functionality of the code, a more extensive code snippet would be needed. Regardless, there are a couple of general suggestions that can be made based on what is provided:
Documentation: Although the code seems to be properly structured, it lacks documentation. Adding comments and inline documentation, especially for public-facing functions and modules, will improve the code's maintainability and make it more user-friendly.
Specific module re-exports: The last line re-exports several items from the
engine
module. It might be useful to add comments/documentation to explain why these are re-exported or what their purpose is in the scope of the current module.Unit tests: Obviously, the code snippet provided does not include any unit tests. Ensuring that your code is accompanied by comprehensive testing will increase its long-term reliability and stability.
Code organization: Group the
pub(crate)
exports together and thepub use
together for the sake of organization and easier readability.Remember that without a full context or functionality of the code, it is quite difficult to provide more specific or detailed feedback. Nonetheless, these general suggestions will hopefully be helpful in improving the quality of your Rust code.
A summary of the key changes in the provided patch:
imp
has been added as apub(crate)
module.engine
module have been updated:SmartEngine
,SmartModuleChainBuilder
, andSmartModuleChainInstance
.SmartEngineImp
,initialize_imp
, andSmartModuleChainInstanceImp
.These changes suggest a potential refactoring of the code, possibly introducing a new implementation or changing the public-facing API within this module.
crates/fluvio-smartengine/src/engine/wasmtime/transforms/aggregate.rs
The provided code overall looks good in terms of structure and readability. However, there are a few potential problems that could be addressed or improved:
Missing comments/Documentation: The code lacks documentation and comments on functions and structs. Adding documentation could make it easier for others to understand the purpose of these functions and structs.
Error messages: In general, it's a good idea to make error messages as informative as possible. In the
test_aggregate_ok
andtest_aggregate_with_initial
tests, theexpect
calls could have more descriptive error messages for better debugging.The
#[ignore]
attributes in tests: The#[ignore]
attribute on both test cases indicates that these tests are ignored when runningcargo test
. If the reason for this is temporary, it should be mentioned in a comment. If not, consider enabling these tests to ensure that testing is complete.Magic numbers in tests: In the test functions
test_aggregate_ok
andtest_aggregate_with_initial
, there are several magic numbers for array lengths and expected values. Consider defining constants or using descriptive variable names for these values to make the tests more maintainable and easier to read.Error Handling: In the
process
function forSmartModuleTransform
, the returned Result is only checked if its less than 0. Even though it's mentioned that if an error occurs, the value should be less than 0, there might be cases where some functions might return an unexpected positive value, which might get overlooked by the current check.Use references instead of cloning: The
.clone()
function is called onself.accumulator
in theprocess
function of theSmartModuleTransform
implementation. It might be more efficient to use references orCow
(Clone on Write) to avoid unnecessary cloning of the accumulator data.In summary, adding comments and documentation, using more descriptive error messages, enabling ignored tests, defining constants for magic numbers, improving error handling, and considering more efficient accumulator usage could improve the code quality.
The key change in the provided patch is the addition of the
.inner
field access:This change ensures that the chain's inner structure is accessed and assigned to
chain
after the initialization process.crates/fluvio-smartengine/src/engine/wasmtime/transforms/array_map.rs
The code provided is a Rust test module for testing the
array_map
feature in a smart module chain. Here are my observations and recommendations:In the imports section, it would be better to group crate imports together and separate them from the others to improve code organization.
Updated version:
The test function
test_array_map
is annotated with#[ignore]
, causing the test runner to skip it by default. If this test should be executed normally, you should remove the#[ignore]
. Alternatively, if there's a valid temporary reason for ignoring this specific test, adding a comment explaining the reason would be helpful.The array elements being mapped are hard-coded. If these are expected to change, it would be better to define them as constants or read them from a configuration file.
The test module should test more scenarios to validate the functionality, such as testing empty input, invalid input, and different expected outputs. Multiple test functions can be created to cover various cases.
One more thing to consider is error handling in case the test modules fail. In this specific case, using
expect()
is reasonable because it provides a clear error message in the resulting panic. However, creating custom error types and error handling strategies can help produce more informative errors with better context.Overall, the code looks well-written, and the concerns are mostly related to organization, readability, and test coverage. With some minor improvements mentioned above, the code should be more maintainable and easier to understand.
In this patch, a single line change was made within the
test_array_map
function:The
chain
variable assignment was updated. Previously, there was a small issue where the assignment didn't include the.inner
attribute, which was required to accesschain
's inner value to perform further operations on it. The patch fixes this by appending.inner
at the end of the expression:Previous code:
Updated code:
This change ensures that the
chain
variable contains the correct value, which enables further operations and assertions to be performed as intended in the test function.crates/fluvio-smartengine/src/engine/wasmtime/transforms/filter.rs
The source code appears to be a set of test cases for a module dealing with smart module chains and filtering. Overall, the code seems well organized, but there are a few improvements that could be made. Here's a list of potential issues and suggestions:
use std::{convert::TryFrom};
is not required as it is already imported in the lineuse fluvio_smartmodule::{dataplane::smartmodule::{SmartModuleInput}, Record,};
.assert!
for checking if the value is equal to true, andassert_eq!
for comparisons.#[ignore]
attribute.Other than these minor issues, the code seems well-structured and easy to understand. I see no major issues with the test cases. However, as the code is part of a test module, it's essential to review the production code being tested to ensure that it does not have any problems or vulnerabilities.
The key changes in this patch involve modifying instances of
.expect("failed to build chain")
to include the.inner
field as part of the chain object creation:In the
test_filter
test case, the following lines have been updated:Similarly, in the
test_filter_with_init_ok
test case, the same modification is made:In both cases, the changes ensure that the chain objects are created with the
.inner
attribute while maintaining the original error handling using.expect()
.crates/fluvio-smartengine/src/engine/wasmtime/transforms/filter_map.rs
The code looks decent, but there are some improvements that can be made. Here are my observations:
Instead of using raw string references like in
const SM_FILTER_MAP: &str = "fluvio_smartmodule_filter_map";
, you may consider either creating a constant in a relevant module or using an enum structure to represent the available wasm modules. This will make your code more maintainable and less prone to typos or hard-to-find bugs.The
unwrap()
calls in the test are unlikely to cause problems since it's a test environment. However, consider replacing them withexpect()
to provide more context on the type of error in case of a panic.The test is marked with
#[ignore]
. If it's a valid test and doesn't require any preconditions to run, consider removing that attribute to include it in your regular test suite.It could be helpful to add comments explaining the purpose of the test and the expected behavior of the filter_map function. This will make it easier for others to understand the codebase.
The test function is called
test_filter_map()
, which is descriptive enough. However, you may consider following a more consistent test naming convention, such astest_<module_name>_<function_name>_<behavior_under_test>
or any other convention that suits your project. This will make it easier to identify relevant tests for specific scenarios or modules.Consider using an IDE or a linter to help evaluate your code. These tools can help you find potential issues, such as incorrect imports or unused variables, more easily during development.
Finally, although you mentioned the code is truncated, It's essential to ensure that all necessary imports and relevant constants are included at the beginning of the source file to ensure it compiles and runs correctly.
The key change in this patch is the addition of
.inner
after theexpect("failed to build chain")
call. This change is made to extract theinner
field from theSmartModuleChain
struct, allowing the following code to access and process the data inside theinner
field.crates/fluvio-smartengine/src/engine/wasmtime/transforms/map.rs
Overall, the code appears to be well-written and follows Rust's best practices. Here are a few observations and suggestions:
Consider adding comments to the code, especially for the test function and the constants used in it. This would help others understand the purpose of the test and the meaning of the constants.
The
use std::{convert::TryFrom};
import line contains only one item. It may be simplified touse std::convert::TryFrom;
.It would be helpful to add a brief description about the ignored test
test_map()
, explaining why it is ignored and under what conditions it should be enabled. You can do this using comments or even better, by adding a message to the#[ignore]
attribute, like so:engine
is used to initialize the chain. Still, it is not evident howSmartEngine
andSmartModuleChainBuilder
are related. Consider adding some comments to explain the relationship between them and their purpose in the test function.SmartModuleConfig
in the following code:Consider setting any needed configuration options using the builder methods. If all the default values are needed for the test, then it's fine to use it as is. However, if there are any specific configuration options relevant to the test, make sure to set them using the builder.
Use more descriptive variable names. Instead of
input
, use something likeinput_records
to make it clear that it is a collection of records you are providing as input. And the same goes foroutput
->output_records
.In the assertion of successes:
The comment ("one record passed") might be misleading, as the assertion checks that there are two successes, not one. Please revise the comment to accurately reflect the reality.
These are suggestions to improve code comprehension, and they would not affect the functionality of the script. The code provided looks functional and well-structured as it is.
The key change in this patch is the addition of
.inner
to the result of thechain_builder.initialize()
method when initializing thechain
variable. This change unwraps the inner value of thechain
after initializing it with the givenSmartEngine
. This update allows access to the inner chain structure for subsequent testing and assertions.cc https://github.com/xxchan/fluvio/pull/1