-
-
Notifications
You must be signed in to change notification settings - Fork 689
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Sam
committed
Dec 9, 2024
1 parent
775bea4
commit 5cbd769
Showing
21 changed files
with
1,397 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Generated by Cargo | ||
# will have compiled files and executables | ||
debug/ | ||
target/ | ||
|
||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries | ||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html | ||
Cargo.lock | ||
|
||
# These are backup files generated by rustfmt | ||
**/*.rs.bk | ||
|
||
# MSVC Windows builds of rustc generate these, which store debugging information | ||
*.pdb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
[package] | ||
name = "leptos-hexagonal-design" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[lib] | ||
crate-type = ["cdylib", "rlib"] | ||
|
||
[dependencies] | ||
leptos = { version = "0.7.0" } | ||
leptos_router = { version = "0.7.0" } | ||
axum = { version = "0.7", optional = true } | ||
console_error_panic_hook = "0.1" | ||
leptos_axum = { version = "0.7.0", optional = true } | ||
leptos_meta = { version = "0.7.0" } | ||
tokio = { version = "1", features = ["rt-multi-thread"], optional = true } | ||
tower = { version = "0.4", optional = true } | ||
tower-http = { version = "0.5", features = ["fs"], optional = true } | ||
wasm-bindgen = "=0.2.99" | ||
thiserror = "1" | ||
tracing = { version = "0.1", optional = true } | ||
http = "1" | ||
mockall = "0.13.1" | ||
cfg-if = "1.0.0" | ||
serde = "1.0.215" | ||
pin-project-lite = "0.2.15" | ||
|
||
[features] | ||
config_1 = [] | ||
hydrate = ["leptos/hydrate"] | ||
ssr = [ | ||
"dep:axum", | ||
"dep:tokio", | ||
"dep:tower", | ||
"dep:tower-http", | ||
"dep:leptos_axum", | ||
"leptos/ssr", | ||
"leptos_meta/ssr", | ||
"leptos_router/ssr", | ||
"dep:tracing", | ||
] | ||
|
||
# Defines a size-optimized profile for the WASM bundle in release mode | ||
[profile.wasm-release] | ||
inherits = "release" | ||
opt-level = 'z' | ||
lto = true | ||
codegen-units = 1 | ||
panic = "abort" | ||
|
||
[package.metadata.leptos] | ||
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name | ||
output-name = "leptos-hexagonal-design" | ||
|
||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup. | ||
site-root = "target/site" | ||
|
||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written | ||
# Defaults to pkg | ||
site-pkg-dir = "pkg" | ||
|
||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css | ||
style-file = "style/main.scss" | ||
# Assets source dir. All files found here will be copied and synchronized to site-root. | ||
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir. | ||
# | ||
# Optional. Env: LEPTOS_ASSETS_DIR. | ||
assets-dir = "public" | ||
|
||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup. | ||
site-addr = "127.0.0.1:3000" | ||
|
||
# The port to use for automatic reload monitoring | ||
reload-port = 3001 | ||
|
||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir. | ||
# [Windows] for non-WSL use "npx.cmd playwright test" | ||
# This binary name can be checked in Powershell with Get-Command npx | ||
end2end-cmd = "npx playwright test" | ||
end2end-dir = "end2end" | ||
|
||
# The browserlist query used for optimizing the CSS. | ||
browserquery = "defaults" | ||
|
||
# The environment Leptos will run in, usually either "DEV" or "PROD" | ||
env = "DEV" | ||
|
||
# The features to use when compiling the bin target | ||
# | ||
# Optional. Can be over-ridden with the command line parameter --bin-features | ||
bin-features = ["ssr"] | ||
|
||
# If the --no-default-features flag should be used when compiling the bin target | ||
# | ||
# Optional. Defaults to false. | ||
bin-default-features = false | ||
|
||
# The features to use when compiling the lib target | ||
# | ||
# Optional. Can be over-ridden with the command line parameter --lib-features | ||
lib-features = ["hydrate"] | ||
|
||
# If the --no-default-features flag should be used when compiling the lib target | ||
# | ||
# Optional. Defaults to false. | ||
lib-default-features = false | ||
|
||
# The profile to use for the lib target when compiling for release | ||
# | ||
# Optional. Defaults to "release". | ||
lib-profile-release = "wasm-release" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
This is free and unencumbered software released into the public domain. | ||
|
||
Anyone is free to copy, modify, publish, use, compile, sell, or | ||
distribute this software, either in source code form or as a compiled | ||
binary, for any purpose, commercial or non-commercial, and by any | ||
means. | ||
|
||
In jurisdictions that recognize copyright laws, the author or authors | ||
of this software dedicate any and all copyright interest in the | ||
software to the public domain. We make this dedication for the benefit | ||
of the public at large and to the detriment of our heirs and | ||
successors. We intend this dedication to be an overt act of | ||
relinquishment in perpetuity of all present and future rights to this | ||
software under copyright law. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | ||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
For more information, please refer to <https://unlicense.org> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
### Leptos Hexagonal Design | ||
|
||
This Blog Post / Github Repository is about applying principles of hexagonal design | ||
- Isolating Business Logic from Sub Domains | ||
- Decoupling design to improve flexibility and testablity | ||
- Applying the principles hierachically so that sub domains which talk to external services also implement also implement hexagonal architecture | ||
|
||
|
||
There are specific constraints that guide our design decisions | ||
|
||
- Server Functions Can't be Generic | ||
- Boxed Traits Objects Have overhead, so we only want to use as much generic code as possible avoid Trait Objects | ||
|
||
The way this works is we define the functionality of our program in the main domain (i.e the business problem and processes our app is trying to solve / proceduralize). We then create sub domains and external services, although they are represented the same. External services are usually the end nodes of your app's architectural graph. Our main application builds it's service layout using configuration flags. | ||
|
||
```rust | ||
pub fn config() -> MainAppHandlerAlias { | ||
cfg_if::cfg_if! { | ||
if #[cfg(feature="open_ai_wrapper")] { | ||
fn server_handler_config_1() -> MainAppHandler< | ||
AuthService<PostgresDb, Redis>, | ||
AiMessageGen<PostgresDb,OpenAiWrapper>, | ||
> { | ||
MainAppHandler::new_with_postgres_and_redis_open_ai() | ||
} | ||
server_handler_config_1() | ||
} else { | ||
fn server_handler_config_2() -> MainAppHandler< | ||
AuthService<MySql, MemCache>, | ||
OtherAiMessageGen<MySql,HuggingFaceWrapper>, | ||
> { | ||
MainAppHandler::new_with_my_sql_memcache_hugging_face() | ||
} | ||
server_handler_config_2() | ||
} | ||
} | ||
} | ||
|
||
``` | ||
|
||
And we pass in our handler which implements a trait | ||
|
||
```rust | ||
pub trait HandlerServerFn { | ||
pub fn server_fn_1_inner(&self); | ||
} | ||
impl<S,S2> HandlerServerFn for MainAppHandler<S:SubDomain1Trait,S2:SubDomain2Trait> { | ||
pub fn server_fn_1_inner(&self) { | ||
// do thing | ||
} | ||
} | ||
``` | ||
|
||
in our main fn we produce our applications service graph and pass it to our leptos router. | ||
|
||
```rust | ||
main () { | ||
let leptos_options = conf.leptos_options; | ||
let routes = generate_route_list(crate::app::App); | ||
// our feature flag based config function. | ||
let handler = config(); | ||
let handler_c = handler.clone(); | ||
// we implement FromRef<ServerState> for LeptosOptions | ||
let server_state = ServerState { | ||
handler, | ||
leptos_options: leptos_options.clone(), | ||
}; | ||
let app = Router::new() | ||
.leptos_routes_with_context( | ||
&server_state, | ||
routes, | ||
// We pass in the MainAppHandler struct as context so we can fetch it anywhere context is available on the server. | ||
// This includes in middleware we define on server functions (see middleware.rs) | ||
move || provide_context(handler_c.clone()), | ||
{ | ||
let leptos_options = leptos_options.clone(); | ||
move || shell(leptos_options.clone()) | ||
}, | ||
) | ||
.fallback(leptos_axum::file_and_error_handler::< | ||
ServerState<HandlerStructAlias>, | ||
_, | ||
>(shell)) | ||
.with_state(server_state); | ||
} | ||
``` | ||
|
||
and then in our server functions | ||
|
||
```rust | ||
#[server] | ||
pub async fn server_fn_1() -> Result<(),ServerFnError> { | ||
// we type alias every variation of our services we plan on configuring. The alternative is using Box<dyn Trait> which isn't bad - just slower. | ||
Ok(expect_context::<MainAppHandlerAlias>().server_fn_1_inner()) | ||
} | ||
``` | ||
|
||
And then we can mock and service trait in any combination like so | ||
|
||
```rust | ||
#[tokio::test] | ||
pub async fn test_subdomain_1_with_mocks() -> Result<(), Box<dyn Error>> { | ||
let mut mock_external_service_1 = MockExternalServiceTrait1::new(); | ||
mock_external_service_1 | ||
.expect_external_service_1_method() | ||
.returning(|| { | ||
println!("Mock external service 1"); | ||
Ok(ExternalService1Data) | ||
}); | ||
let mut mock_external_service_2 = MockExternalServiceTrait2::new(); | ||
mock_external_service_2 | ||
.expect_external_service_2_method() | ||
.returning(|| { | ||
println!("Mock external service 2"); | ||
Ok(ExternalService2Data) | ||
}); | ||
let real_subdomain_1_with_mock_externals = SubDomainStruct1 { | ||
external_service_1: mock_external_service_1, | ||
external_service_2: mock_external_service_2, | ||
}; | ||
let data = real_subdomain_1_with_mock_externals | ||
.sub_domain_1_method() | ||
.await?; | ||
assert_eq!(data, SubDomain1Data); | ||
Ok(()) | ||
} | ||
``` | ||
|
||
|
||
Check out the code in the repository for a working example. | ||
|
||
Run the tests with | ||
|
||
` cargo test --features ssr ` | ||
and otherwise run | ||
` cargo leptos serve ` | ||
and navigate to `127.0.0.1:3000` | ||
|
||
here's a picture | ||
|
||
|
||
![alt text](leptos_hexagonal_architecture.png) |
Oops, something went wrong.