From fb7849c010d728b3136607c4ea348059ac5ef7e7 Mon Sep 17 00:00:00 2001 From: Jean-Gabriel Gill-Couture Date: Wed, 2 Jul 2025 23:13:08 -0400 Subject: [PATCH] feat: Add sample leptos webapp as example --- examples/lamp/auth/kubeconfig | 19 ++ examples/lamp/php/Dockerfile | 18 ++ examples/lamp/php/docker-php.ini | 16 ++ examples/rust/src/main.rs | 5 +- examples/rust/webapp/.gitignore | 14 ++ examples/rust/webapp/Cargo.toml | 93 ++++++++ examples/rust/webapp/Dockerfile.harmony | 10 + examples/rust/webapp/LICENSE | 24 +++ examples/rust/webapp/README.md | 72 +++++++ examples/rust/webapp/assets/favicon.ico | Bin 0 -> 15406 bytes .../rust/webapp/end2end/package-lock.json | 112 ++++++++++ examples/rust/webapp/end2end/package.json | 15 ++ .../rust/webapp/end2end/playwright.config.ts | 104 +++++++++ .../rust/webapp/end2end/tests/example.spec.ts | 9 + examples/rust/webapp/end2end/tsconfig.json | 109 ++++++++++ examples/rust/webapp/src/app.rs | 66 ++++++ examples/rust/webapp/src/lib.rs | 9 + examples/rust/webapp/src/main.rs | 88 ++++++++ examples/rust/webapp/style/main.scss | 4 + harmony/src/modules/application/rust.rs | 204 +++++++++++++++++- 20 files changed, 988 insertions(+), 3 deletions(-) create mode 100644 examples/lamp/auth/kubeconfig create mode 100644 examples/lamp/php/Dockerfile create mode 100644 examples/lamp/php/docker-php.ini create mode 100644 examples/rust/webapp/.gitignore create mode 100644 examples/rust/webapp/Cargo.toml create mode 100644 examples/rust/webapp/Dockerfile.harmony create mode 100644 examples/rust/webapp/LICENSE create mode 100644 examples/rust/webapp/README.md create mode 100644 examples/rust/webapp/assets/favicon.ico create mode 100644 examples/rust/webapp/end2end/package-lock.json create mode 100644 examples/rust/webapp/end2end/package.json create mode 100644 examples/rust/webapp/end2end/playwright.config.ts create mode 100644 examples/rust/webapp/end2end/tests/example.spec.ts create mode 100644 examples/rust/webapp/end2end/tsconfig.json create mode 100644 examples/rust/webapp/src/app.rs create mode 100644 examples/rust/webapp/src/lib.rs create mode 100644 examples/rust/webapp/src/main.rs create mode 100644 examples/rust/webapp/style/main.scss diff --git a/examples/lamp/auth/kubeconfig b/examples/lamp/auth/kubeconfig new file mode 100644 index 0000000..9c35782 --- /dev/null +++ b/examples/lamp/auth/kubeconfig @@ -0,0 +1,19 @@ +apiVersion: v1 +clusters: +- cluster: + certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJlRENDQVIyZ0F3SUJBZ0lCQURBS0JnZ3Foa2pPUFFRREFqQWpNU0V3SHdZRFZRUUREQmhyTTNNdGMyVnkKZG1WeUxXTmhRREUzTkRZM01qYzROell3SGhjTk1qVXdOVEE0TVRneE1URTJXaGNOTXpVd05UQTJNVGd4TVRFMgpXakFqTVNFd0h3WURWUVFEREJock0zTXRjMlZ5ZG1WeUxXTmhRREUzTkRZM01qYzROell3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFUdm8rYjhqbmZmeHpTWlBvdWt0MUdWQStBcE9nRTRsd3pXd0tLVU1LdTMKemdLYUJnTDJrdmkxRnZEZGlMZ0RhcUJENmYzYTVQWWd4QWViZXA2Nk5odmRvMEl3UURBT0JnTlZIUThCQWY4RQpCQU1DQXFRd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZEJnTlZIUTRFRmdRVWZSS1ByVlZmZ3VrQmhQQWJZMmEwCkNiYkFnenN3Q2dZSUtvWkl6ajBFQXdJRFNRQXdSZ0loQU5yeFFXaWowektuOTRJeXpjMnRPNTQ5Wnk0YlpSU3kKQllNeVRWT3I1QWREQWlFQWhrWW8zdDFiMFhwLzg4Tkt0cVRCY0V4NGtrZ24za0FBWXEweTRUTXU5QW89Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K + server: https://0.0.0.0:40437 + name: k3d-harmony +contexts: +- context: + cluster: k3d-harmony + user: admin@k3d-harmony + name: k3d-harmony +current-context: k3d-harmony +kind: Config +prefer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TVNFd0h3WURWUVFEREJock0zTXRZMnhwWlc1MExXTmhRREUzTkRZM01qYzROell3V1RBVEJnY3Foa2pPClBRSUJCZ2dxaGtqT1BRTUJCd05DQUFRQVQ0VXkvbm5YVjhmN2xtSTEwTHk1NjNmOStBL0VOeUYyWGVlVnFKNVQKVENCaVNncERIZ09ncE82MEZrMVdhRkRJWmZYcU9RTWI0Q1hjT2wrSVJyWS9vMEl3UURBT0JnTlZIUThCQWY4RQpCQU1DQXFRd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZEJnTlZIUTRFRmdRVU9TR2RRZGh5UUg5ZkF0QzBiZURRCjFROWIyamN3Q2dZSUtvWkl6ajBFQXdJRFNBQXdSUUlnZEVYS0RBcjNlT0QzYWI0ZXZHMzgvbHplMEpoTXJIOFoKR25EUTRob2NncnNDSVFEejZFbGZtNWYvL0x1akdUUEFQT3BpR293SFFoMEI4Mk9kbFlMcDN3SEt3QT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K + client-key-data: LS0tLS1CRUdJTiBFQyBQUklWQVRFIEtFWS0tLS0tCk1IY0NBUUVFSU1zVUt1MXVBZ0k5VWR1ek9Jc2VvRjRFNGwvMlMzYnJhRlVvTGtuWXpwbGZvQW9HQ0NxR1NNNDkKQXdFSG9VUURRZ0FFTkNjSGRvMTQwRkpxc25sWlNJWHU0dExSV05VNm53YXFwWkZ6VWN5Z3J2SmlkRkFObWIvRgpmVFlYSlVmT3ZTanB1YnRoQTBQOVRyVFZubHlReGVQM2NnPT0KLS0tLS1FTkQgRUMgUFJJVkFURSBLRVktLS0tLQo= diff --git a/examples/lamp/php/Dockerfile b/examples/lamp/php/Dockerfile new file mode 100644 index 0000000..df5f4fa --- /dev/null +++ b/examples/lamp/php/Dockerfile @@ -0,0 +1,18 @@ +FROM php:8.4-apache +ENV PHP_MEMORY_LIMIT=256M +ENV PHP_MAX_EXECUTION_TIME=30 +ENV PHP_ERROR_REPORTING="E_ERROR | E_WARNING | E_PARSE" +RUN apt-get update && apt-get install -y --no-install-recommends libfreetype6-dev libjpeg62-turbo-dev libpng-dev libzip-dev unzip && apt-get clean && rm -rf /var/lib/apt/lists/* +RUN docker-php-ext-configure gd --with-freetype --with-jpeg && docker-php-ext-install -j$(nproc) gd mysqli pdo_mysql zip opcache +RUN sed -i 's/VirtualHost \*:80/VirtualHost *:8080/' /etc/apache2/sites-available/000-default.conf && \ + sed -i 's/^Listen 80$/Listen 8080/' /etc/apache2/ports.conf +RUN mkdir -p /usr/local/etc/php/conf.d/ +COPY docker-php.ini /usr/local/etc/php/conf.d/docker-php.ini +RUN a2enmod headers && a2enmod rewrite && sed -i 's/ServerTokens OS/ServerTokens Prod/' /etc/apache2/conf-enabled/security.conf && sed -i 's/ServerSignature On/ServerSignature Off/' /etc/apache2/conf-enabled/security.conf +RUN echo 'PassEnv MYSQL_PASSWORD' >> /etc/apache2/sites-available/000-default.conf && echo 'PassEnv MYSQL_USER' >> /etc/apache2/sites-available/000-default.conf && echo 'PassEnv MYSQL_HOST' >> /etc/apache2/sites-available/000-default.conf +RUN groupadd -g 1000 appuser && useradd -u 1000 -g appuser -m -s /bin/bash appuser && chown -R appuser:appuser /var/www/html +WORKDIR /var/www/html +COPY . /var/www/html +RUN chown -R appuser:appuser /var/www/html +EXPOSE 8080/tcp +CMD apache2-foreground \ No newline at end of file diff --git a/examples/lamp/php/docker-php.ini b/examples/lamp/php/docker-php.ini new file mode 100644 index 0000000..3745ad5 --- /dev/null +++ b/examples/lamp/php/docker-php.ini @@ -0,0 +1,16 @@ + +memory_limit = ${PHP_MEMORY_LIMIT} +max_execution_time = ${PHP_MAX_EXECUTION_TIME} +error_reporting = ${PHP_ERROR_REPORTING} +display_errors = Off +log_errors = On +error_log = /dev/stderr +date.timezone = UTC + +; Opcache configuration for production +opcache.enable=1 +opcache.memory_consumption=128 +opcache.interned_strings_buffer=8 +opcache.max_accelerated_files=4000 +opcache.revalidate_freq=2 +opcache.fast_shutdown=1 diff --git a/examples/rust/src/main.rs b/examples/rust/src/main.rs index 15d35f1..4575c5f 100644 --- a/examples/rust/src/main.rs +++ b/examples/rust/src/main.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::{path::PathBuf, sync::Arc}; use harmony::{ inventory::Inventory, @@ -11,7 +11,8 @@ use harmony::{ async fn main() { env_logger::init(); let application = RustWebapp { - name: "Example Harmony Rust Webapp".to_string(), + name: "harmony-example-rust-webapp".to_string(), + project_root: PathBuf::from("./examples/rust/webapp"), }; let app = RustWebappScore { name: "Example Rust Webapp".to_string(), diff --git a/examples/rust/webapp/.gitignore b/examples/rust/webapp/.gitignore new file mode 100644 index 0000000..6985cf1 --- /dev/null +++ b/examples/rust/webapp/.gitignore @@ -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 diff --git a/examples/rust/webapp/Cargo.toml b/examples/rust/webapp/Cargo.toml new file mode 100644 index 0000000..5a60ede --- /dev/null +++ b/examples/rust/webapp/Cargo.toml @@ -0,0 +1,93 @@ +[package] +name = "webapp" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[workspace] + +[dependencies] +actix-files = { version = "0.6", optional = true } +actix-web = { version = "4", optional = true, features = ["macros"] } +console_error_panic_hook = "0.1" +http = { version = "1.0.0", optional = true } +leptos = { version = "0.7.0" } +leptos_meta = { version = "0.7.0" } +leptos_actix = { version = "0.7.0", optional = true } +leptos_router = { version = "0.7.0" } +wasm-bindgen = "=0.2.100" + +[features] +csr = ["leptos/csr"] +hydrate = ["leptos/hydrate"] +ssr = [ + "dep:actix-files", + "dep:actix-web", + "dep:leptos_actix", + "leptos/ssr", + "leptos_meta/ssr", + "leptos_router/ssr", +] + +# 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 = "webapp" +# 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 //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 = "assets" +# 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" diff --git a/examples/rust/webapp/Dockerfile.harmony b/examples/rust/webapp/Dockerfile.harmony new file mode 100644 index 0000000..63f781c --- /dev/null +++ b/examples/rust/webapp/Dockerfile.harmony @@ -0,0 +1,10 @@ +FROM rust:latest as builder +RUN rustup target add wasm32-unknown-unknown +WORKDIR /app +COPY . . +RUN cargo build --release --locked +FROM debian:bullseye-slim +RUN groupadd -r appgroup && useradd -r -s /bin/false -g appgroup appuser +COPY --from=builder /app/target/release/harmony-example-rust-webapp /usr/local/bin/harmony-example-rust-webapp +USER appuser +CMD /usr/local/bin/harmony-example-rust-webapp \ No newline at end of file diff --git a/examples/rust/webapp/LICENSE b/examples/rust/webapp/LICENSE new file mode 100644 index 0000000..fdddb29 --- /dev/null +++ b/examples/rust/webapp/LICENSE @@ -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 diff --git a/examples/rust/webapp/README.md b/examples/rust/webapp/README.md new file mode 100644 index 0000000..99ecfcb --- /dev/null +++ b/examples/rust/webapp/README.md @@ -0,0 +1,72 @@ + + + Leptos Logo + + +# Leptos 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. + +## Creating your template repo + +If you don't have `cargo-leptos` installed you can install it with + +`cargo install cargo-leptos --locked` + +Then run + +`cargo leptos new --git leptos-rs/start-actix` + +to generate a new project template (you will be prompted to enter a project name). + +`cd {projectname}` + +to go to your newly created project. + +Of course, you should explore around the project structure, but the best place to start with your application code is in `src/app.rs`. + +## Running your project + +`cargo leptos watch` +By default, you can access your local project at `http://localhost:3000` + +## 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) + +## 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 +leptos_start +site/ +``` +Set the following environment variables (updating for your project as needed): +```sh +export LEPTOS_OUTPUT_NAME="leptos_start" +export LEPTOS_SITE_ROOT="site" +export LEPTOS_SITE_PKG_DIR="pkg" +export LEPTOS_SITE_ADDR="127.0.0.1:3000" +export LEPTOS_RELOAD_PORT="3001" +``` +Finally, run the server binary. + +## Notes about CSR and Trunk: +Although it is not recommended, you can also run your project without server integration using the feature `csr` and `trunk serve`: + +`trunk serve --open --features csr` + +This may be useful for integrating external tools which require a static site, e.g. `tauri`. + +## Licensing + +This template itself is released under the Unlicense. You should replace the LICENSE for your own application with an appropriate license if you plan to release it publicly. diff --git a/examples/rust/webapp/assets/favicon.ico b/examples/rust/webapp/assets/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..2ba8527cb12f5f28f331b8d361eef560492d4c77 GIT binary patch literal 15406 zcmeHOd3aPs5`TblWD*3D%tXPJ#q(n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", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.12.tgz", + "integrity": "sha512-eWLDGF/FOSPtAvEqeRAQ4C8LSA7M1I7i0ky1I8U7kD1J5ITyW3AsRhQrKVoWf5pFKZ2kILsEGJhsI9r93PYnOw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.44.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.44.1.tgz", + "integrity": "sha512-qr/0UJ5CFAtloI3avF95Y0L1xQo6r3LQArLIg/z/PoGJ6xa+EwzrwO5lpNr/09STxdHuUoP2mvuELJS+hLdtgg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.44.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=16" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.44.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.44.1.tgz", + "integrity": "sha512-wh0JWtYTrhv1+OSsLPgFzGzt67Y7BE/ZS3jEqgGBlp2ppp1ZDj8c+9IARNW4dwf1poq5MgHreEM2KV/GuR4cFA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/typescript": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", + "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/examples/rust/webapp/end2end/package.json b/examples/rust/webapp/end2end/package.json new file mode 100644 index 0000000..a80ac59 --- /dev/null +++ b/examples/rust/webapp/end2end/package.json @@ -0,0 +1,15 @@ +{ + "name": "end2end", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": {}, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "@playwright/test": "^1.44.1", + "@types/node": "^20.12.12", + "typescript": "^5.4.5" + } +} diff --git a/examples/rust/webapp/end2end/playwright.config.ts b/examples/rust/webapp/end2end/playwright.config.ts new file mode 100644 index 0000000..f4c3483 --- /dev/null +++ b/examples/rust/webapp/end2end/playwright.config.ts @@ -0,0 +1,104 @@ +import { devices, defineConfig } from "@playwright/test"; + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ +// require('dotenv').config(); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: "./tests", + /* Maximum time one test can run for. */ + timeout: 30 * 1000, + expect: { + /** + * Maximum time expect() should wait for the condition to be met. + * For example in `await expect(locator).toHaveText();` + */ + timeout: 5000, + }, + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: "html", + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */ + actionTimeout: 0, + /* Base URL to use in actions like `await page.goto('/')`. */ + // baseURL: 'http://localhost:3000', + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: "on-first-retry", + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { + ...devices["Desktop Chrome"], + }, + }, + + { + name: "firefox", + use: { + ...devices["Desktop Firefox"], + }, + }, + + { + name: "webkit", + use: { + ...devices["Desktop Safari"], + }, + }, + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { + // ...devices['Pixel 5'], + // }, + // }, + // { + // name: 'Mobile Safari', + // use: { + // ...devices['iPhone 12'], + // }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { + // channel: 'msedge', + // }, + // }, + // { + // name: 'Google Chrome', + // use: { + // channel: 'chrome', + // }, + // }, + ], + + /* Folder for test artifacts such as screenshots, videos, traces, etc. */ + // outputDir: 'test-results/', + + /* Run your local dev server before starting the tests */ + // webServer: { + // command: 'npm run start', + // port: 3000, + // }, +}); diff --git a/examples/rust/webapp/end2end/tests/example.spec.ts b/examples/rust/webapp/end2end/tests/example.spec.ts new file mode 100644 index 0000000..a461f35 --- /dev/null +++ b/examples/rust/webapp/end2end/tests/example.spec.ts @@ -0,0 +1,9 @@ +import { test, expect } from "@playwright/test"; + +test("homepage has title and links to intro page", async ({ page }) => { + await page.goto("http://localhost:3000/"); + + await expect(page).toHaveTitle("Welcome to Leptos"); + + await expect(page.locator("h1")).toHaveText("Welcome to Leptos!"); +}); diff --git a/examples/rust/webapp/end2end/tsconfig.json b/examples/rust/webapp/end2end/tsconfig.json new file mode 100644 index 0000000..e075f97 --- /dev/null +++ b/examples/rust/webapp/end2end/tsconfig.json @@ -0,0 +1,109 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} diff --git a/examples/rust/webapp/src/app.rs b/examples/rust/webapp/src/app.rs new file mode 100644 index 0000000..6baa388 --- /dev/null +++ b/examples/rust/webapp/src/app.rs @@ -0,0 +1,66 @@ +use leptos::prelude::*; +use leptos_meta::{provide_meta_context, Stylesheet, Title}; +use leptos_router::{ + components::{Route, Router, Routes}, + StaticSegment, WildcardSegment, +}; + +#[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 + // id=leptos means cargo-leptos will hot-reload this stylesheet + + + // sets the document title + + + // content for this welcome page + <Router> + <main> + <Routes fallback=move || "Not found."> + <Route path=StaticSegment("") view=HomePage/> + <Route path=WildcardSegment("any") view=NotFound/> + </Routes> + </main> + </Router> + } +} + +/// Renders the home page of your application. +#[component] +fn HomePage() -> impl IntoView { + // Creates a reactive value to update the button + let count = RwSignal::new(0); + let on_click = move |_| *count.write() += 1; + + view! { + <h1>"Welcome to Leptos!"</h1> + <button on:click=on_click>"Click Me: " {count}</button> + } +} + +/// 404 - Not Found +#[component] +fn NotFound() -> impl IntoView { + // set an HTTP status code 404 + // this is feature gated because it can only be done during + // initial server-side rendering + // if you navigate to the 404 page subsequently, the status + // code will not be set because there is not a new HTTP request + // to the server + #[cfg(feature = "ssr")] + { + // this can be done inline because it's synchronous + // if it were async, we'd use a server function + let resp = expect_context::<leptos_actix::ResponseOptions>(); + resp.set_status(actix_web::http::StatusCode::NOT_FOUND); + } + + view! { + <h1>"Not Found"</h1> + } +} diff --git a/examples/rust/webapp/src/lib.rs b/examples/rust/webapp/src/lib.rs new file mode 100644 index 0000000..1fd9810 --- /dev/null +++ b/examples/rust/webapp/src/lib.rs @@ -0,0 +1,9 @@ +pub mod app; + +#[cfg(feature = "hydrate")] +#[wasm_bindgen::prelude::wasm_bindgen] +pub fn hydrate() { + use app::*; + console_error_panic_hook::set_once(); + leptos::mount::hydrate_body(App); +} diff --git a/examples/rust/webapp/src/main.rs b/examples/rust/webapp/src/main.rs new file mode 100644 index 0000000..3fbc276 --- /dev/null +++ b/examples/rust/webapp/src/main.rs @@ -0,0 +1,88 @@ +#[cfg(feature = "ssr")] +#[actix_web::main] +async fn main() -> std::io::Result<()> { + use actix_files::Files; + use actix_web::*; + use leptos::prelude::*; + use leptos::config::get_configuration; + use leptos_meta::MetaTags; + use leptos_actix::{generate_route_list, LeptosRoutes}; + use webapp::app::*; + + let conf = get_configuration(None).unwrap(); + let addr = conf.leptos_options.site_addr; + + HttpServer::new(move || { + // Generate the list of routes in your Leptos App + let routes = generate_route_list(App); + let leptos_options = &conf.leptos_options; + let site_root = leptos_options.site_root.clone().to_string(); + + println!("listening on http://{}", &addr); + + App::new() + // serve JS/WASM/CSS from `pkg` + .service(Files::new("/pkg", format!("{site_root}/pkg"))) + // serve other assets from the `assets` directory + .service(Files::new("/assets", &site_root)) + // serve the favicon from /favicon.ico + .service(favicon) + .leptos_routes(routes, { + let leptos_options = leptos_options.clone(); + move || { + view! { + <!DOCTYPE html> + <html lang="en"> + <head> + <meta charset="utf-8"/> + <meta name="viewport" content="width=device-width, initial-scale=1"/> + <AutoReload options=leptos_options.clone() /> + <HydrationScripts options=leptos_options.clone()/> + <MetaTags/> + </head> + <body> + <App/> + </body> + </html> + } + } + }) + .app_data(web::Data::new(leptos_options.to_owned())) + //.wrap(middleware::Compress::default()) + }) + .bind(&addr)? + .run() + .await +} + +#[cfg(feature = "ssr")] +#[actix_web::get("favicon.ico")] +async fn favicon( + leptos_options: actix_web::web::Data<leptos::config::LeptosOptions>, +) -> actix_web::Result<actix_files::NamedFile> { + let leptos_options = leptos_options.into_inner(); + let site_root = &leptos_options.site_root; + Ok(actix_files::NamedFile::open(format!( + "{site_root}/favicon.ico" + ))?) +} + +#[cfg(not(any(feature = "ssr", feature = "csr")))] +pub fn main() { + // no client-side main function + // unless we want this to work with e.g., Trunk for pure client-side testing + // see lib.rs for hydration function instead + // see optional feature `csr` instead +} + +#[cfg(all(not(feature = "ssr"), feature = "csr"))] +pub fn main() { + // a client-side main function is required for using `trunk serve` + // prefer using `cargo leptos serve` instead + // to run: `trunk serve --open --features csr` + use webapp::app::*; + + console_error_panic_hook::set_once(); + + leptos::mount_to_body(App); +} diff --git a/examples/rust/webapp/style/main.scss b/examples/rust/webapp/style/main.scss new file mode 100644 index 0000000..e4538e1 --- /dev/null +++ b/examples/rust/webapp/style/main.scss @@ -0,0 +1,4 @@ +body { + font-family: sans-serif; + text-align: center; +} \ No newline at end of file diff --git a/harmony/src/modules/application/rust.rs b/harmony/src/modules/application/rust.rs index 20b8c46..5fc60c9 100644 --- a/harmony/src/modules/application/rust.rs +++ b/harmony/src/modules/application/rust.rs @@ -1,8 +1,16 @@ +use std::fs; +use std::path::PathBuf; +use std::process; use std::sync::Arc; use async_trait::async_trait; +use dockerfile_builder::Dockerfile; +use dockerfile_builder::instruction::{CMD, COPY, FROM, RUN, USER, WORKDIR}; +use dockerfile_builder::instruction_builder::CopyBuilder; +use log::{debug, info}; use serde::Serialize; +use crate::config::{REGISTRY_PROJECT, REGISTRY_URL}; use crate::{ score::Score, topology::{Topology, Url}, @@ -31,9 +39,17 @@ impl<T: Topology + std::fmt::Debug + Clone + Serialize + 'static> Score<T> for R } } +#[derive(Debug, Clone, Serialize)] +pub enum RustWebFramework { + Leptos, +} + #[derive(Debug, Clone, Serialize)] pub struct RustWebapp { pub name: String, + /// The path to the root of the Rust project to be containerized. + pub project_root: PathBuf, + pub framework: Option<RustWebFramework>, } impl Application for RustWebapp { @@ -44,7 +60,193 @@ impl Application for RustWebapp { #[async_trait] impl OCICompliant for RustWebapp { + /// Builds a Docker image for the Rust web application using a multi-stage build, + /// pushes it to the configured OCI registry, and returns the full image tag. async fn build_push_oci_image(&self) -> Result<String, String> { - todo!() + // This function orchestrates the build and push process. + // It's async to match the trait definition, though the underlying docker commands are blocking. + info!("Starting OCI image build and push for '{}'", self.name); + + // 1. Build the local image by calling the synchronous helper function. + let local_image_name = self + .build_docker_image() + .map_err(|e| format!("Failed to build Docker image: {}", e))?; + info!( + "Successfully built local Docker image: {}", + local_image_name + ); + + // 2. Push the image to the registry. + let remote_image_name = self + .push_docker_image(&local_image_name) + .map_err(|e| format!("Failed to push Docker image: {}", e))?; + info!("Successfully pushed Docker image to: {}", remote_image_name); + + Ok(remote_image_name) + } +} + +/// Implementation of helper methods for building and pushing the Docker image. +impl RustWebapp { + /// Generates a multi-stage Dockerfile for a Rust application. + fn build_dockerfile(&self) -> Result<PathBuf, Box<dyn std::error::Error>> { + let mut dockerfile = Dockerfile::new(); + + self.build_builder_image(&mut dockerfile); + + // --- Stage 2: Final Image --- + // Use a minimal, non-Alpine base image for the final container. + dockerfile.push(FROM::from("debian:bullseye-slim")); + + // Create a non-root user for security. + dockerfile.push(RUN::from( + "groupadd -r appgroup && useradd -r -s /bin/false -g appgroup appuser", + )); + + // Copy only the compiled binary from the builder stage. + let binary_path_in_builder = format!("/app/target/release/{}", self.name); + let binary_path_in_final = format!("/usr/local/bin/{}", self.name); + dockerfile.push( + CopyBuilder::builder() + .from("builder") + .src(binary_path_in_builder) + .dest(&binary_path_in_final) + .build() + .unwrap(), + ); + + // Run as the non-root user. + dockerfile.push(USER::from("appuser")); + + // Set the command to run the application. + dockerfile.push(CMD::from(binary_path_in_final)); + + // Save the Dockerfile to a uniquely named file in the project root to avoid conflicts. + let dockerfile_path = self.project_root.join("Dockerfile.harmony"); + fs::write(&dockerfile_path, dockerfile.to_string())?; + + Ok(dockerfile_path) + } + + /// Builds the Docker image using the generated Dockerfile. + pub fn build_docker_image(&self) -> Result<String, Box<dyn std::error::Error>> { + info!("Generating Dockerfile for '{}'", self.name); + let dockerfile_path = self.build_dockerfile()?; + + info!( + "Building Docker image with file {} from root {}", + dockerfile_path.to_string_lossy(), + self.project_root.to_string_lossy() + ); + let image_name = format!("{}-webapp", self.name); + + let output = process::Command::new("docker") + .args([ + "build", + "--file", + dockerfile_path.to_str().unwrap(), + "-t", + &image_name, + self.project_root.to_str().unwrap(), + ]) + .spawn()? + .wait_with_output()?; + + self.check_output(&output, "Failed to build Docker image")?; + + Ok(image_name) + } + + /// Tags and pushes a Docker image to the configured remote registry. + fn push_docker_image(&self, image_name: &str) -> Result<String, Box<dyn std::error::Error>> { + let full_tag = format!("{}/{}/{}", *REGISTRY_URL, *REGISTRY_PROJECT, &image_name); + info!("Pushing docker image {full_tag}"); + + // Tag the image for the remote registry. + let output = process::Command::new("docker") + .args(["tag", image_name, &full_tag]) + .output()?; + self.check_output(&output, "Tagging docker image failed")?; + debug!( + "docker tag output: stdout: {}, stderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + todo!("Are we good?"); + + // Push the image. + let output = process::Command::new("docker") + .args(["push", &full_tag]) + .output()?; + self.check_output(&output, "Pushing docker image failed")?; + debug!( + "docker push output: stdout: {}, stderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + + Ok(full_tag) + } + + /// Checks the output of a process command for success. + fn check_output( + &self, + output: &process::Output, + msg: &str, + ) -> Result<(), Box<dyn std::error::Error>> { + if !output.status.success() { + let error_message = format!("{}: {}", msg, String::from_utf8_lossy(&output.stderr)); + return Err(error_message.into()); + } + Ok(()) + } + + fn build_builder_image(&self, dockerfile: &mut Dockerfile) { + match self.framework { + Some(RustWebFramework::Leptos) => {todo!(r#" + # Get started with a build env with Rust nightly +FROM rustlang/rust:nightly-bookworm as builder + +# If you’re using stable, use this instead +# FROM rust:1.86-bullseye as builder + +# Install cargo-binstall, which makes it easier to install other +# cargo extensions like cargo-leptos +RUN wget https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-x86_64-unknown-linux-musl.tgz +RUN tar -xvf cargo-binstall-x86_64-unknown-linux-musl.tgz +RUN cp cargo-binstall /usr/local/cargo/bin + +# Install required tools +RUN apt-get update -y \ + && apt-get install -y --no-install-recommends clang + +# Install cargo-leptos +RUN cargo binstall cargo-leptos -y + +# Add the WASM target +RUN rustup target add wasm32-unknown-unknown + +# Make an /app dir, which everything will eventually live in +RUN mkdir -p /app +WORKDIR /app +COPY . . + +# Build the app +RUN cargo leptos build --release -vv + "#)} + None => { + // --- Stage 1: Builder --- + // Use the official Rust image as the build environment. + dockerfile.push(FROM::from("rust:latest as builder")); + + // Install the wasm32 target as required. + dockerfile.push(RUN::from("rustup target add wasm32-unknown-unknown")); + dockerfile.push(WORKDIR::from("/app")); + + // Copy the source code and build the application. + dockerfile.push(COPY::from(". .")); + dockerfile.push(RUN::from("cargo build --release --locked")); + } + } } }