feat: reorganize workbook into 3 tracks (core, engineering-2026, ecosystems)
This commit is contained in:
1 parent
82677455b2
commit
2e002b6176
64 files changed
+2295
-196
No files matched your search
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "eco01-cli-clap"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
@@ -0,0 +1,18 @@
|
||||
# 01 — Parsowanie argumentów CLI z `clap`
|
||||
|
||||
`clap` (Command Line Argument Parser) to absolutny standard w ekosystemie Rusta do budowy narzędzi CLI.
|
||||
|
||||
## Zakres
|
||||
* Deklaratywne makra `#[derive(Parser)]` i `#[derive(Subcommand)]`
|
||||
* Flagi (`--verbose` / `-v`), opcje z wartościami domyślnymi, argumenty pozycyjne i podkomendy (`add`, `list`, `done`)
|
||||
* Testowanie parsera bez uruchamiania procesu: `Cli::try_parse_from(...)`
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. Uzupełnij atrybuty `clap` w strukturze `Cli` i enumie `Command` (np. `#[arg(short, long)]`, `#[command(subcommand)]`).
|
||||
2. Zaimplementuj `parse_cli(args: &[&str]) -> Result<Cli, clap::Error>` używając `Cli::try_parse_from(args)`.
|
||||
3. Zaimplementuj `describe_command(cli: &Cli) -> String`, aby zamienić sparsowaną komendę na czytelny opis (w prawdziwym CLI byłoby tu wywołanie logiki biznesowej).
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eco01-cli-clap
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Debug, Parser, PartialEq, Eq)]
|
||||
#[command(name = "todoctl", about = "Mini CLI do nauki clap")]
|
||||
pub struct Cli {
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
pub verbose: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
/// Dodaj nowe zadanie
|
||||
Add {
|
||||
/// Tytuł zadania
|
||||
title: String,
|
||||
|
||||
/// Priorytet (1-5)
|
||||
#[arg(short, long, default_value_t = 3)]
|
||||
priority: u8,
|
||||
},
|
||||
/// Wyświetl listę zadań
|
||||
List {
|
||||
/// Pokaż również ukończone
|
||||
#[arg(long, default_value_t = false)]
|
||||
all: bool,
|
||||
},
|
||||
/// Oznacz zadanie jako ukończone
|
||||
Done { id: u64 },
|
||||
}
|
||||
|
||||
pub fn parse_cli(args: &[&str]) -> Result<Cli, clap::Error> {
|
||||
todo!("Użyj Cli::try_parse_from(args)")
|
||||
}
|
||||
|
||||
pub fn describe_command(cli: &Cli) -> String {
|
||||
todo!(
|
||||
"Zwróć: Add -> \"add:<title>:p<priority>\", List -> \"list:all=<bool>\", Done -> \"done:<id>\""
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_add_with_defaults_and_flags() {
|
||||
let cli = parse_cli(&["todoctl", "-v", "add", "Learn clap"]).unwrap();
|
||||
assert!(cli.verbose);
|
||||
assert_eq!(
|
||||
cli.command,
|
||||
Command::Add {
|
||||
title: String::from("Learn clap"),
|
||||
priority: 3
|
||||
}
|
||||
);
|
||||
assert_eq!(describe_command(&cli), "add:Learn clap:p3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_list_and_done_subcommands() {
|
||||
let list_cli = parse_cli(&["todoctl", "list", "--all"]).unwrap();
|
||||
assert_eq!(describe_command(&list_cli), "list:all=true");
|
||||
|
||||
let done_cli = parse_cli(&["todoctl", "done", "42"]).unwrap();
|
||||
assert_eq!(describe_command(&done_cli), "done:42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_arguments() {
|
||||
assert!(parse_cli(&["todoctl", "done", "not-a-number"]).is_err());
|
||||
assert!(parse_cli(&["todoctl", "unknown"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "eco02-web-backend-axum"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
[dev-dependencies]
|
||||
http-body-util = "0.1"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
@@ -0,0 +1,18 @@
|
||||
# 02 — Web Backend z `axum` + `tokio` + `serde`
|
||||
|
||||
`axum` (oparty na `tokio` i `tower`) to najpopularniejszy nowoczesny framework backendowy w Ruście.
|
||||
|
||||
## Zakres
|
||||
* Routing HTTP (`Router::new().route(...)`)
|
||||
* Serializacja/deserializacja JSON (`axum::Json`, `serde::Serialize`, `serde::Deserialize`)
|
||||
* Kody statusu HTTP (`StatusCode`) i testowanie routera w pamięci bez otwierania portów (`tower::ServiceExt::oneshot`)
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
Zbuduj router w `build_router()`:
|
||||
1. `GET /health` -> zwraca `200 OK` i JSON `{"status": "ok"}`.
|
||||
2. `POST /echo` -> przyjmuje JSON `EchoRequest { message: String }`; jeśli `message.trim().is_empty()`, zwraca `400 BAD_REQUEST`, inaczej `200 OK` z `EchoResponse { echoed: message, len }`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eco02-web-backend-axum
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct HealthResponse {
|
||||
pub status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct EchoRequest {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct EchoResponse {
|
||||
pub echoed: String,
|
||||
pub len: usize,
|
||||
}
|
||||
|
||||
async fn health_handler() -> Json<HealthResponse> {
|
||||
todo!("Zwróć Json(HealthResponse {{ status: \"ok\".into() }})")
|
||||
}
|
||||
|
||||
async fn echo_handler(Json(payload): Json<EchoRequest>) -> Result<Json<EchoResponse>, StatusCode> {
|
||||
todo!("Odrzuć pusty message jako Err(StatusCode::BAD_REQUEST), inaczej zwróć EchoResponse")
|
||||
}
|
||||
|
||||
pub fn build_router() -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(health_handler))
|
||||
.route("/echo", post(echo_handler))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::{body::Body, http::Request};
|
||||
use http_body_util::BodyExt;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_endpoint_returns_ok_json() {
|
||||
let app = build_router();
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/health")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = response.into_body().collect().await.unwrap().to_bytes();
|
||||
let body: HealthResponse = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
body,
|
||||
HealthResponse {
|
||||
status: String::from("ok")
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn echo_endpoint_validates_and_echoes() {
|
||||
let app = build_router();
|
||||
let ok_resp = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/echo")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"message":"rust"}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ok_resp.status(), StatusCode::OK);
|
||||
let bytes = ok_resp.into_body().collect().await.unwrap().to_bytes();
|
||||
let body: EchoResponse = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
body,
|
||||
EchoResponse {
|
||||
echoed: String::from("rust"),
|
||||
len: 4
|
||||
}
|
||||
);
|
||||
|
||||
let bad_resp = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/echo")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"message":" "}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bad_resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "eco03-shared-core-ffi"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
thiserror = "2"
|
||||
@@ -0,0 +1,17 @@
|
||||
# 03 — Wspólny Rdzeń pod Mobile (iOS/Android UniFFI) i Desktop (Tauri)
|
||||
|
||||
W projektach mobilnych (Swift/Kotlin) oraz desktopowych (Tauri v2) w Ruście pisze się **wspólny, niezależny od platformy rdzeń logiki**, a następnie wystawia go przez cienką granicę FFI/IPC (`UniFFI`, `tauri::command`).
|
||||
|
||||
## Kluczowe zasady projektowania granicy FFI/IPC
|
||||
* Płaskie, serializowalne DTO (`String`, `u64`, `Vec<T>`, `Option<T>`) — bez referencji z lifetime'ami `'a` w publicznym API.
|
||||
* Jawne, serializowalne błędy (`thiserror::Error` + `Serialize`) — **zero `panic!` przez granicę FFI** (panika przez FFI to Undefined Behavior w C/Swift/Kotlin).
|
||||
* Zero typów zależnych od systemu operacyjnego (`std::os::unix`) na granicy API.
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. Zaimplementuj `validate_and_create_note(input: CreateNoteDto) -> Result<NoteDto, CoreError>` (walidacja pustego tytułu, generowanie prostego sluga lowercase z `-` zamiast spacji).
|
||||
2. Wykorzystaj `thiserror::Error` w `CoreError` dla czytelnych komunikatów błędów.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eco03-shared-core-ffi
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CreateNoteDto {
|
||||
pub title: String,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct NoteDto {
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
pub word_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum CoreError {
|
||||
#[error("note title cannot be empty")]
|
||||
EmptyTitle,
|
||||
#[error("note body exceeds maximum length of {max} characters")]
|
||||
BodyTooLong { max: usize },
|
||||
}
|
||||
|
||||
pub fn validate_and_create_note(input: CreateNoteDto) -> Result<NoteDto, CoreError> {
|
||||
todo!(
|
||||
"Odrzuć pusty title (EmptyTitle), body > 500 znaków (BodyTooLong {{ max: 500 }}), zbuduj slug (lowercase, spacje -> '-') i policz word_count"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builds_ffi_friendly_note_dto() {
|
||||
let dto = CreateNoteDto {
|
||||
title: String::from(" Hello Rust Mobile "),
|
||||
body: String::from("Shared core works on iOS and Android"),
|
||||
};
|
||||
let note = validate_and_create_note(dto).unwrap();
|
||||
assert_eq!(note.slug, "hello-rust-mobile");
|
||||
assert_eq!(note.title, "Hello Rust Mobile");
|
||||
assert_eq!(note.word_count, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_typed_errors_instead_of_panicking() {
|
||||
let empty = CreateNoteDto {
|
||||
title: String::from(" "),
|
||||
body: String::from("ok"),
|
||||
};
|
||||
assert_eq!(validate_and_create_note(empty), Err(CoreError::EmptyTitle));
|
||||
|
||||
let huge = CreateNoteDto {
|
||||
title: String::from("Valid"),
|
||||
body: "a".repeat(501),
|
||||
};
|
||||
assert_eq!(
|
||||
validate_and_create_note(huge),
|
||||
Err(CoreError::BodyTooLong { max: 500 })
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "eco04-wasm-logic"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,13 @@
|
||||
# 04 — Logika pod WebAssembly (Frontend / Przeglądarka)
|
||||
|
||||
Na froncie Rust najczęściej pełni rolę **szybkiego, deterministycznego modułu obliczeniowego (WASM)** wywoływanego z TypeScriptu (np. parsery, walidatory, wyszukiwarki, edytory), wymieniającego dane przez JSON lub binarne bufory.
|
||||
|
||||
Moduł testujesz normalnie natywnie (`make test PKG=eco04-wasm-logic`), a w docelowej aplikacji webowej wystarczy dodać atrybut `#[wasm_bindgen]` i skompilować pod target `wasm32-unknown-unknown`.
|
||||
|
||||
## Zadania (`src/lib.rs`)
|
||||
1. `analyze_text_json(input_json: &str) -> Result<String, String>` — zdeserializuj `TextInput { text: String }`, policz liczbę znaków (`chars().count()`), słów i linii, a wynik zwróć jako zserializowany JSON `TextStats`.
|
||||
|
||||
## Uruchomienie testów
|
||||
```bash
|
||||
make test PKG=eco04-wasm-logic
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
#![allow(unused_variables, dead_code)]
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct TextInput {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct TextStats {
|
||||
pub chars: usize,
|
||||
pub words: usize,
|
||||
pub lines: usize,
|
||||
}
|
||||
|
||||
pub fn analyze_text_json(input_json: &str) -> Result<String, String> {
|
||||
todo!("Deserializuj TextInput z JSON, policz chars/words/lines i zserializuj TextStats do JSON")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn processes_json_boundary_for_js_interop() {
|
||||
let raw = r#"{"text":"Rust\nin browser"}"#;
|
||||
let out_json = analyze_text_json(raw).unwrap();
|
||||
let stats: TextStats = serde_json::from_str(&out_json).unwrap();
|
||||
assert_eq!(
|
||||
stats,
|
||||
TextStats {
|
||||
chars: 15,
|
||||
words: 3,
|
||||
lines: 2
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_error_on_invalid_json() {
|
||||
assert!(analyze_text_json("{invalid").is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user