Skip to content

Commit

Permalink
first
Browse files Browse the repository at this point in the history
  • Loading branch information
sjud committed Feb 25, 2024
1 parent c16189f commit 4ee4d05
Show file tree
Hide file tree
Showing 45 changed files with 1,522 additions and 0 deletions.
3 changes: 3 additions & 0 deletions examples/mpmc_nginx/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
*/target
.vscode
34 changes: 34 additions & 0 deletions examples/mpmc_nginx/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Nginx Multiple Server Multiple Client Example
This example shows how multiple clients can communicate with multiple servers while being shared over a single domain i.e localhost:80 using nginx as a reverse proxy.

### How to run this example
```sh
./run.sh
```
Or

```sh
./run_linux.sh
```

<br>
This will boot up nginx via it's docker image mapped to port 80, and the four servers. App-1, App-2, Shared-Server-1, Shared-Server-2.
<br>
App-1, And App-2 are SSR rendering leptos servers.
<br>
If you go to localhost (you'll get App-1), and localhost/app2 (you'll get app2).
<br>
The two shared servers can be communicated with via actions and local resources, or resources (if using CSR).
<br>
`create_resource` Won't work, as expected, when trying to communicate to different servers. It will instead try to run the server function on the server you are serving your server side rendered content from. This will cause errors if your server function relies on state that is not present.
<br>
When you are done with this example, run

```sh
./kill.sh
```

Casting ctrl-c multiple times won't close all the open programs.

### Do you have feedback on this example?
@sjud on discord for any thoughts, clarifications or improvements. Thanks.
13 changes: 13 additions & 0 deletions examples/mpmc_nginx/app-1/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Generated by Cargo
# will have compiled files and executables
/target/
pkg

# These are backup files generated by rustfmt
**/*.rs.bk

# node e2e test tools and outputs
node_modules/
test-results/
end2end/playwright-report/
playwright/.cache/
120 changes: 120 additions & 0 deletions examples/mpmc_nginx/app-1/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
[package]
name = "app-1"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
console_error_panic_hook = "0.1"
leptos_meta = { version = "0.6" }
leptos_router = { version = "0.6" }
tower = { version = "0.4", optional = true }
tower-http = { version = "0.5", features = ["fs","trace"], optional = true }
wasm-bindgen = "=0.2.89"
thiserror = "1"
tracing = { version = "0.1", optional = true }

http = "1"

axum = {version = "0.7",optional=true}
leptos = "0.6"
leptos_axum = {version = "0.6",optional=true}
tokio = { version = "1", features = ["rt-multi-thread"], optional = true}
shared-server = {path = "../shared-server",default-features = false}
shared-server-2 = {path = "../shared-server-2",default-features = false}
tracing-subscriber = {version="0.3.18",features=["env-filter"]}

# 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"

[features]
hydrate = [
"leptos/hydrate",
"leptos_meta/hydrate",
"leptos_router/hydrate",
"shared-server/hydrate",
"shared-server-2/hydrate"
]
ssr = [
"shared-server/ssr",
"shared-server-2/ssr",
"dep:axum",
"dep:tokio",
"dep:tower",
"dep:tower-http",
"dep:leptos_axum",
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
"dep:tracing",
]



[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "app-1"

# 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"

# 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.
# we're listening inside of a docker container, so we need to set 0.0.0.0 to let it be accessed from outside the container.
site-addr = "127.0.0.1:3000"

# The port to use for automatic reload monitoring
reload-port = 3004

# [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"

# The browserlist query used for optimizing the CSS.
browserquery = "defaults"

# Set by cargo-leptos watch when building with that tool. Controls whether autoreload JS will be included in the head
watch = false

# 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"
21 changes: 21 additions & 0 deletions examples/mpmc_nginx/app-1/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

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 OR COPYRIGHT HOLDERS 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.
86 changes: 86 additions & 0 deletions examples/mpmc_nginx/app-1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<picture>
<source srcset="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_Solid_White.svg" media="(prefers-color-scheme: dark)">
<img src="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_RGB.svg" alt="Leptos Logo">
</picture>

# Leptos Axum Starter Template

This is a template for use with the [Leptos](https://github.com/leptos-rs/leptos) web framework and the [cargo-leptos](https://github.com/akesson/cargo-leptos) tool using [Axum](https://github.com/tokio-rs/axum).

## Creating your template repo

If you don't have `cargo-leptos` installed you can install it with

```bash
cargo install cargo-leptos
```

Then run
```bash
cargo leptos new --git leptos-rs/start-axum
```

to generate a new project template.

```bash
cd app-1
```

to go to your newly created project.
Feel free to explore the project structure, but the best place to start with your application code is in `src/app.rs`.
Addtionally, Cargo.toml may need updating as new versions of the dependencies are released, especially if things are not working after a `cargo update`.

## Running your project

```bash
cargo leptos watch
```

## Installing Additional Tools

By default, `cargo-leptos` uses `nightly` Rust, `cargo-generate`, and `sass`. If you run into any trouble, you may need to install one or more of these tools.

1. `rustup toolchain install nightly --allow-downgrade` - make sure you have Rust nightly
2. `rustup target add wasm32-unknown-unknown` - add the ability to compile Rust to WebAssembly
3. `cargo install cargo-generate` - install `cargo-generate` binary (should be installed automatically in future)
4. `npm install -g sass` - install `dart-sass` (should be optional in future

## Compiling for Release
```bash
cargo leptos build --release
```

Will generate your server binary in target/server/release and your site package in target/site

## Testing Your Project
```bash
cargo leptos end-to-end
```

```bash
cargo leptos end-to-end --release
```

Cargo-leptos uses Playwright as the end-to-end test tool.
Tests are located in end2end/tests directory.

## Executing a Server on a Remote Machine Without the Toolchain
After running a `cargo leptos build --release` the minimum files needed are:

1. The server binary located in `target/server/release`
2. The `site` directory and all files within located in `target/site`

Copy these files to your remote server. The directory structure should be:
```text
app-1
site/
```
Set the following environment variables (updating for your project as needed):
```text
LEPTOS_OUTPUT_NAME="app-1"
LEPTOS_SITE_ROOT="site"
LEPTOS_SITE_PKG_DIR="pkg"
LEPTOS_SITE_ADDR="127.0.0.1:3000"
LEPTOS_RELOAD_PORT="3001"
```
Finally, run the server binary.
Binary file added examples/mpmc_nginx/app-1/public/favicon.ico
Binary file not shown.
79 changes: 79 additions & 0 deletions examples/mpmc_nginx/app-1/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use crate::error_template::{AppError, ErrorTemplate};
use leptos::*;
use leptos_meta::*;
use leptos_router::*;

#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();

view! {


// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
<Stylesheet id="leptos" href="/pkg/app-1.css"/>

// sets the document title
<Title text="Welcome to Leptos"/>

// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
</Routes>
</main>
</Router>
}
}

/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
use shared_server::SharedServerFunction;
use shared_server_2::SharedServerFunction2;

// A local resource will wait for the client to load before attempting to initialize.
let hello_1 = create_local_resource(move || (), |_| shared_server::shared_server_function());
// this won't work : let hello_1 = create_resource(move || (), |_| shared_server::shared_server_function());
// A resource is initialized on the rendering server when using SSR.

let hello_1_action = Action::<SharedServerFunction,_>::server();
let hello_2_action = Action::<SharedServerFunction2,_>::server();

let value_1 = create_rw_signal(String::from("waiting for update from shared server."));
let value_2 = create_rw_signal(String::from("waiting for update from shared server 2."));

//let hello_2 = create_resource(move || (), shared_server_2::shared_server_function);
create_effect(move|_|{if let Some(Ok(msg)) = hello_1_action.value().get(){value_1.set(msg)}});
create_effect(move|_|{if let Some(Ok(msg)) = hello_2_action.value().get(){value_2.set(msg)}});

view! {
<h1> App 1</h1>
<div>Suspense</div>
<Suspense fallback=move || view! { <p>"Loading (Suspense Fallback)..."</p> }>
{move || {
hello_1.get().map(|data| match data {
Err(_) => view! { <pre>"Error"</pre> }.into_view(),
Ok(hello) => hello.into_view(),
})
}
}
</Suspense>
<div> action response from server 1 </div>
<button on:click=move|_|hello_1_action.dispatch(SharedServerFunction{})>request from shared server 1</button>
{move || value_1.get()}
<div> action response from server 2 </div>
<button on:click=move|_|hello_2_action.dispatch(SharedServerFunction2{})>request from shared server 2</button>
{move || value_2.get()}
}
}
Loading

0 comments on commit 4ee4d05

Please sign in to comment.