# FlowRust > Lenguaje y framework web expresivo con sintaxis de bloques `{ }` sin `;` obligatorio que transpila a Rust nativo sobre Axum, SeaORM, Tokio, Mediator, FluentValidation, JWT y Argon2. ## Documentación para Modelos (Archivos Planos) - [index.html](./index.html): Landing page interactiva con comparador `.fr` → Rust y mapeo de tipos. - [docs.html](./docs.html): Visor web de todas las especificaciones oficiales. - [llms-full.txt](./llms-full.txt): Documentación completa concatenada (todas las especificaciones `specs/*.md` en un solo archivo de texto). ## Arquitectura Interna del Framework (Cómo Funciona Cada Crate) ### 1. `crates/flowrust-compiler` (Compilador `.fr` → Rust) - `lexer.rs`: Tokeniza palabras clave (`entity`, `struct`, `enum`, `interface`, `impl`, `mod`, `validator`, `fn`, `async`, `match`, `test`), `f"..."`, atributos `@...` y supresión de saltos de línea dentro de `()` / `[]`. - `ast.rs`: Define `Program`, `Item` (`Entity`, `Struct`, `Enum`, `Interface`, `Impl`, `Mod`, `Validator`, `Function`, `Test`), expresiones y sentencias. - `parser.rs`: Parser descendente recursivo + Pratt parser para expresiones, encadenamiento multilínea y bloques `validator ... for ...` (`rule_for`, `when`, `unless`). - `loader.rs`: Resuelve recursivamente `import "ruta.fr"` relativos con detección de ciclos, `LoadedProject` y `load_project_with_overrides` (buffers en memoria). - `typecheck.rs`: Validación semántica previa a `rustc` (tipos duplicados, relaciones `@has_many`/`@belongs_to`, colisiones de rutas HTTP, `@require_role` sin `AuthUser`, `validator`, y chequeo profundo de `let`, `return`, campos, aridad, `if`/`not` y `match` exhaustivo). - `formatter.rs`: `format_source` y `organize_and_format_source` (ordena y deduplica `import`s y formatea bloques a 4 espacios). - `codegen.rs`: Transpila AST a Rust idiomático (`SeaORM`, `FluentValidator`, `axum::Router`, `Mediator`, `AppConfig`, `RateLimiter`, `health_router`, `openapi_router`, `#[cfg(test)]`), con `CodegenConfig` (inyección de `jobs`/`realtime`), coerción automática de literales `str`, auto-`.as_ref()` en `self.db`/`state.db` y `*ActiveModel` ergonómico. - `openapi.rs`: Genera especificación `OpenAPI 3.1` desde el AST (`paths`, `components.schemas`, `bearerAuth`). - `source_map.rs`: Mapea líneas Rust generadas a líneas originales `.fr` para traducir errores de `rustc --message-format=json`. ### 2. `crates/flowrust-runtime` (Runtime y Primitivas) - `error.rs`: `ApiError` unificado (`{ codigo, mensaje, detalles }`), `ValidationFailure`, mapeo automático de `sea_orm::DbErr` (incluyendo `409 Conflict` en restricciones únicas) y registro de errores internos. - `validation.rs`: Trait `Validatable` y extractor `ValidatedJson` (`400` JSON inválido, `422` validación fallida). - `fluent_validation.rs`: `FluentValidator`, `ValidationResult`, `FluentField` y `RuleBuilder` con reglas encadenables (`.not_empty()`, `.min_len()`, `.max_len()`, `.email()`, `.inclusive_between()`, `.must()`, `.when()`, `.unless()`, `.with_message()`). - `mediator.rs`: `Command`, `Query`, `CommandHandler`, `QueryHandler` y `Mediator` (`send` / `query`). - `security.rs`: `JwtConfig`, `Claims`, `issue_token`, `verify_token`, extractor `AuthUser`, `require_role`, `require_any_role`, `hash_password` y `verify_password` (Argon2id). - `config.rs`: `AppConfig::from_env()` / `from_env_or_dev()` con carga automática de `.env`, incluyendo `REDIS_URL` y `REALTIME_CHANNEL`. - `middleware.rs`: `RateLimiter`, `rate_limit_middleware` (`429`), `build_cors_layer`. - `db.rs` & `pagination.rs`: `run_in_tx` (transacciones con rollback automático), `Migrator` (`_flowrust_migrations`), `PageQuery`, `Page`, `paginate_select`. - `observability.rs` & `openapi.rs`: `request_logging_middleware`, `health_router` (`/health/live`, `/health/ready`) y `openapi_router` (`/openapi.json`, `/docs` con Scalar UI, `/swagger` con Swagger UI). - `jobs.rs`, `realtime.rs`, `uploads.rs`, `ws.rs`: `JobQueue`, `DatabaseJobStore` (`_flowrust_jobs` con reintentos), `SseChannel`, `UploadConfig`/`parse_multipart_parts`, `RealtimeHub`, `RealtimeBackend` y `RedisRealtimeBackend` (`--features redis-pubsub` + `start_listener()`). ### 3. `crates/flowrust-cli` (CLI `flowrust`) - `new [--template basic|vertical-slice]`: Crea proyecto base o Vertical Slice (`shared/`, `requests/`, `responses/`, FluentValidation, `.env`, JWT, Scalar). - `check [PATH]`: Carga `import`s, valida sintaxis y ejecuta `typecheck`. - `build [PATH]`: Transpila a `.flowrust/generated/` y compila con `cargo build` + Source Maps. - `run [PATH] [--watch]` y `dev [PATH]`: Ejecuta desde la raíz del proyecto (para `.env` y SQLite); con `dev` / `--watch` recarga automáticamente al guardar cambios en `.fr`. - `fmt [PATH] [--check]`: Formatea y reorganiza `import`s. - `test [PATH]`: Compila y ejecuta bloques `test "..." { ... }`. - `migrate status|sql|up|down`: Gestiona migraciones SeaORM. - `dockerize`: Genera `Dockerfile` multi-stage y `.dockerignore`. - `docs`: Sincroniza `specs/*.md` hacia `docs/specs-data.js`, `docs/llms.txt` y `docs/llms-full.txt`. ### 4. `crates/flowrust-lsp` y `editors/vscode/` - Servidor LSP sobre `stdio` (JSON-RPC 2.0) con soporte multi-archivo (`flowrust.toml` + `import`s), diagnósticos en vivo, autocompletado, hover, formateo (`textDocument/formatting`), *Go-to-Definition* (`F12`) y *Rename* (`F2`). - Extensión VS Code sin dependencias `npm` en runtime (`.vscodeignore` para `.vsix`), icono `.fr`, gramática TextMate y proveedores LSP completos. ## Especificaciones Oficiales (`specs/*.md`) - **FlowRust — Roadmap de Implementación por Fases** (`specs/00-roadmap.md`) - **01 — Sintaxis, Bloques y Sistema de Tipos** (`specs/01-syntax-and-types.md`) - **02 — Capa ORM estilo SeaORM** (`specs/02-seaorm-layer.md`) - **03 — Routing HTTP, DTOs, Validación y `ApiError`** (`specs/03-http-routing-and-errors.md`) - **04 — Interfaces, Inyección de Dependencias y Mediator** (`specs/04-di-and-mediator.md`) - **05 — Seguridad, JWT, Argon2 y Middlewares** (`specs/05-jwt-and-security.md`) - **06 — OpenAPI 3.1 y Swagger / Scalar UI Automáticos** (`specs/06-openapi-and-docs.md`) - **07 — Módulos Multi-archivo (`import`), `enum`/`match`, Listas y `flowrust fmt`** (`specs/07-modules-enums-and-fmt.md`) - **08 — Observabilidad (`tracing`), Healthchecks y `flowrust test`** (`specs/08-observability-and-testing.md`) - **09 — Persistencia Avanzada (`Page[T]`, Transacciones y Migraciones Incrementales)** (`specs/09-advanced-persistence.md`) - **10 — Ecosistema Cloud (`JobQueue`, SSE, Drivers DB y `flowrust dockerize`)** (`specs/10-cloud-jobs-and-docker.md`) - **11 — Source Maps y Typechecker Semántico Previo** (`specs/11-sourcemaps-and-typecheck.md`) - **12 — Language Server (`flowrust-lsp`) y Extensión VS Code** (`specs/12-lsp-and-vscode.md`) - **13 — Subida de Archivos (`uploads`), Salas en Tiempo Real (`ws`) y Contenedores Live** (`specs/13-uploads-websockets-and-containers.md`) - **Especificación 14: FluentValidation Nativo (`validator` + `ValidationResult`)** (`specs/14-fluent-validation.md`) - **15 — LSP Multi-archivo, Go-to-Definition y Rename** (`specs/15-lsp-multifile-and-navigation.md`) - **16 — Typechecker Semántico Profundo** (`specs/16-deep-typechecker.md`) - **17 — Ergonomía del Lenguaje `.fr`** (`specs/17-language-ergonomics.md`) - **18 — Primitivas Cloud Persistentes y Distribuidas (`v0.5`)** (`specs/18-distributed-cloud-primitives.md`) - **19 — Loop Suscriptor en `RedisRealtimeBackend` (`v0.6`)** (`specs/19-redis-pubsub-subscriber.md`) - **20 — Cableado Declarativo de `DatabaseJobStore` y `RedisRealtimeBackend` (`v0.6`)** (`specs/20-declarative-cloud-wiring.md`) - **21 — Suite E2E Automatizada en CI (`v0.6`)** (`specs/21-ci-e2e-suite.md`) - **22 — Empaquetado `.vsix` y Releases Binarios (`v1.0`)** (`specs/22-packaging-and-distribution.md`) - **23 — Interoperabilidad con Crates Externos (`[dependencies]` + `use`)** (`specs/23-external-crates-interop.md`) - **24 — Sintaxis Moderna, Tipos Estándar y Ergonomía de Endpoints (`v1.0`)** (`specs/24-modern-syntax-sugar.md`) ## Ejemplos Completos de Cada Tipo de Código en FlowRust ### 1. Sintaxis Base, Tipos, `f"..."`, `ref`/`mut` y Acceso Estático con `.` ```flowrust # Tipos estándar: long/int (i64), double/float (f64), string/str (String), bool, byte (u8), void (()), List[T] (Vec), Dictionary[K, V] (HashMap), DateTime, Guid # Bloques { } sin ';' obligatorio; retornos con ':' o '->'; operadores: and, or, not; acceso estático con '.' fn saludar(nombre: string, mut intentos: long): Result[string, ApiError] { let etiquetas = ["api", "rust"] let primera = etiquetas[0] if intentos < 1 or nombre.trim() == "" { return Err(ApiError.bad_request(f"Parámetro inválido: {primera}")) } intentos = intentos + 1 return Ok(f"Hola {nombre}, intento #{intentos}") } ``` ### 2. Entidades SeaORM (`entity`), Relaciones y CRUD ```flowrust @table("users") entity User { @primary_key id: long @unique email: string password_hash: string @has_many(entity = "Note") notes: List[Note] } @table("notes") entity Note { @primary_key id: long title: string @default(false) archived: bool owner_id: long @belongs_to(entity = "User", from = "owner_id", to = "id") owner: Option[User] } async fn crear_y_buscar(db: Arc[DatabaseConnection], uid: long, titulo: string): Result[NoteModel, ApiError] { let nuevo = NoteActiveModel { title: titulo, archived: false, owner_id: uid, } let guardado = nuevo.insert(db).await? let _actual = Note.get_or_404(db, guardado.id).await? return Ok(guardado) } ``` ### 3. DTOs Declarativos y Validación Manual (`fn validate`) ```flowrust struct ProfileDto { @email email: string @min_len(3) @max_len(40) username: string @range(18, 120) age: long } impl ProfileDto { fn validate(ref self): Result[(), ApiError] { if self.username.trim() == "admin" { return Err(ApiError.validation("username", "Nombre reservado")) } return Ok(()) } } ``` ### 4. FluentValidation Nativo (`validator ... for ...`) ```flowrust struct UpdateNoteDto { @min_len(3) @max_len(120) title: string @not_empty content: string archived: bool } validator UpdateNoteValidator for UpdateNoteDto { rule_for(title) .not_empty() .min_len(3) .max_len(120) .with_message("El título debe tener entre 3 y 120 caracteres") rule_for(content) .not_empty() .must(|c| not c.contains("spam"), "No se permite contenido spam") when(self.archived) { rule_for(content) .min_len(10) .with_message("Las notas archivadas requieren al menos 10 caracteres") } } ``` ### 5. Interfaces (`interface`) e Implementaciones (`impl`) ```flowrust interface ClockService { async fn now_iso(ref self): string } struct SystemClock {} impl ClockService for SystemClock { async fn now_iso(ref self): string { return "2026-12-03T00:00:00Z" } } ``` ### 6. CQRS con Mediator (`Command`, `Query`, `CommandHandler`, `QueryHandler`) ```flowrust struct CreateNoteCmd { title: string owner_id: long } impl Command for CreateNoteCmd { type Response = NoteResponseDto } struct CreateNoteHandler { db: Arc[DatabaseConnection] } impl CommandHandler[CreateNoteCmd] for CreateNoteHandler { async fn handle(ref self, cmd: CreateNoteCmd): Result[NoteResponseDto, ApiError] { let model = NoteActiveModel { title: cmd.title, archived: false, owner_id: cmd.owner_id } let saved = model.insert(self.db).await? return Ok(NoteResponseDto { id: saved.id, title: saved.title, archived: saved.archived, owner_id: saved.owner_id }) } } struct ListNotesQuery { owner_id: long page: PageQuery } impl Query for ListNotesQuery { type Response = Page[NoteResponseDto] } ``` ### 7. Rutas HTTP (`@group`, `@get`, `@post`, `@patch`, `@delete`) y Extractores ```flowrust @group("/api/v1/notes") mod notes_routes { @post("/") @require_role("member") async fn create_note( auth: AuthUser, state: AppState, dto: Validated[CreateNoteDto] ): ApiCreated[NoteResponseDto] { let res = state.mediator.send(CreateNoteCmd { title: dto.title, owner_id: auth.user_id()? }).await? return created(res) } @get("/") @require_role("member") async fn list_notes( auth: AuthUser, state: AppState, page: Query[PageQuery] ): ApiResult[Page[NoteResponseDto]] { let res = state.mediator.query(ListNotesQuery { owner_id: auth.user_id()?, page: page }).await? return ok(res) } @delete("/{id}") @require_role("admin", "member") async fn delete_note(auth: AuthUser, state: AppState, id: Path[long]): Result[StatusCode, ApiError] { let _note = Note.get_or_404(state.db, id).await? Note.delete_by_id(id).exec(state.db).await? return no_content() } } ``` ### 8. Seguridad JWT + Argon2 (`/register` y `/login`) ```flowrust @group("/api/v1/auth") mod auth_routes { @post("/register") async fn register(state: AppState, dto: Validated[RegisterDto]): ApiCreated[AuthResponseDto] { let hashed = hash_password(ref dto.password)? let saved = UserActiveModel { email: dto.email, password_hash: hashed }.insert(state.db).await? let token = issue_token(ref state.jwt, saved.id.to_string(), ["member".to_string()])? return created(AuthResponseDto { access_token: token, token_type: "Bearer" }) } @post("/login") async fn login(state: AppState, dto: Validated[LoginDto]): ApiResult[AuthResponseDto] { let user = User.find().filter(UserColumn.Email.eq(dto.email)).one(state.db).await?.ok_or_else(|| ApiError.unauthorized("Invalid credentials"))? let is_valid = verify_password(ref dto.password, ref user.password_hash)? if not is_valid { return Err(ApiError.unauthorized("Invalid credentials")) } let token = issue_token(ref state.jwt, user.id.to_string(), ["member".to_string()])? return ok(AuthResponseDto { access_token: token, token_type: "Bearer" }) } } ``` ### 9. `enum`, `match`, Listas e `import` Multi-archivo ```flowrust import "entities/models.fr" import "features/notes/responses/note_response.fr" enum TaskPriority { Low, Medium, High, } fn priority_label(p: TaskPriority): string { let labels = ["baja", "media", "alta"] match p { TaskPriority.Low => return labels[0] TaskPriority.Medium => return labels[1] TaskPriority.High => return labels[2] } } ``` ### 10. Paginación (`Page[T]`) y Transacciones (`run_in_tx`) ```flowrust async fn listar_paginado(db: Arc[DatabaseConnection], uid: long, q: PageQuery): Result[Page[NoteResponseDto], ApiError] { let select = Note.find().filter(NoteColumn.OwnerId.eq(uid)) let page = paginate_select(select, db, ref q).await? return Ok(page.map(|n| to_note_response(n))) } async fn crear_en_transaccion(db: ref DatabaseConnection, uid: long, titulo: string): Result[NoteModel, ApiError] { return run_in_tx(db, |tx| Box.pin(async move { let n = NoteActiveModel { title: titulo, archived: false, owner_id: uid }.insert(tx).await? return Ok(n) })).await } ``` ### 11. Testing Nativo (`test "..." { ... }`) ```flowrust test "el validador rechaza datos inválidos" { let dto = RegisterDto { email: "mal", password: "123" } assert(dto.validate().is_err()) assert_eq(dto.email, "mal") } ``` ### 12. Background Jobs, SSE, Multipart Uploads y Salas Tiempo Real (Runtime) - `JobQueue::new(buffer)`: ejecuta tareas en segundo plano (`enqueue`, `enqueue_fn`). - `SseChannel::channel(buffer)`: streaming Server-Sent Events sobre Axum (`Sse`). - `UploadConfig` + `parse_multipart_parts`: validación de tamaño máximo y tipos MIME. - `RealtimeHub`: pub/sub de salas en tiempo real sobre `tokio::sync::broadcast`. ### 13. Estructura Recomendada: Vertical Slice (`flowrust new api --template vertical-slice`) ```text src/ ├── main.fr ├── entities/models.fr ├── shared/note_mapper.fr └── features/ ├── auth/ │ ├── requests/{register_request.fr, login_request.fr} │ ├── responses/auth_response.fr │ ├── register.fr │ └── login.fr └── notes/ ├── requests/{create_note_request.fr, update_note_request.fr} ├── responses/note_response.fr └── {create_note.fr, list_notes.fr, update_note.fr, delete_note.fr} ``` ### 14. Endpoints Integrados Automáticamente en Toda App Generada - `GET /docs`: Referencia interactiva **Scalar UI**. - `GET /swagger`: **Swagger UI**. - `GET /openapi.json`: Esquema **OpenAPI 3.1** generado desde el AST. - `GET /health/live` y `GET /health/ready` (con `db.ping()`). ### 15. Ergonomía `.fr` (Coerción `str`, Auto-`.as_ref()` y `*ActiveModel` Simplificado) ```flowrust struct CreateNoteDto { title: str content: str } fn saludo_por_defecto() -> str { let etiqueta: str = "general" return "Nota creada" } async fn guardar_nota_ergonomica(ref self, dto: CreateNoteDto, uid: int) -> Result[NoteModel, ApiError] { # Sin Set(...), sin ..Default.default(), sin .as_ref() y sin .to_string() let model = NoteActiveModel { title: dto.title, content: dto.content, archived: false, owner_id: uid, } let saved = model.insert(self.db).await? return Ok(saved) } ``` ### 16. Jobs Persistentes (`DatabaseJobStore`) y Tiempo Real Distribuido con Redis (`flowrust.toml` + `AppState`) ```toml # flowrust.toml [project] name = "mi_api_cloud" version = "0.1.0" entry = "src/main.fr" database_driver = "postgres" jobs_backend = "database" realtime_backend = "redis" ``` ```dotenv # .env DATABASE_URL=postgres://flowrust:flowrust_dev_password@localhost:5432/flowrust_test REDIS_URL=redis://127.0.0.1:6379 REALTIME_CHANNEL=flowrust:realtime ``` ```flowrust @group("/api/v1/events") mod events_routes { @post("/notify") async fn notify_and_enqueue(State(ref state): State[AppState]) -> Result[StatusCode, ApiError] { let _job_id = state.jobs.enqueue("send_welcome_email", "{\"user\":1}", 3).await? let msg = RealtimeMessage { room: "notes:1", sender: "api", payload: "updated" } let _ = state.realtime.publish_async(msg).await? return Ok(StatusCode.ACCEPTED) } } ``` ### 17. CI/CD, Contenedores y Distribución (`.github/workflows/`) ```yaml # .github/workflows/ci.yml: cargo check --workspace, --features redis-pubsub, cargo test --workspace, # flowrust check/test sobre ejemplos y migraciones live en PostgreSQL 16 y MySQL 8. # .github/workflows/release.yml (tags v*): compila binarios Linux/Windows/macOS y empaqueta editors/vscode (.vsix). ``` ### 18. Uso de Cualquier Crate de Rust (`flowrust.toml` `[dependencies]` + `use`) ```toml # flowrust.toml [project] name = "mi_api" version = "0.1.0" entry = "src/main.fr" database_driver = "sqlite" [dependencies] reqwest = { version = "0.12", features = ["json"] } chrono = { version = "0.4", features = ["serde"] } ``` ```flowrust use reqwest.Client use chrono.Utc async fn consultar_externo() -> Result[str, ApiError] { let now = Utc.now().to_rfc3339() let _client = Client.new() return Ok(f"Listo en {now}") } ``` ### 19. Sintaxis Moderna, Tipos Estándar y Extractores Cortos ```flowrust # Retornos con ':' (alternativa a '->') y tipos estándar: string, long, double, decimal, byte, void, List[T], Dictionary[K, V], DateTime, Guid struct ProductDto { id: Guid name: string price: double tags: List[string] attrs: Dictionary[string, string] created_at: DateTime } @group("/api/v1/notes") mod modern_notes { @get("/{id}") async fn get_note(state: AppState, id: Path[long]): ApiResult[NoteResponseDto] { let note = Note.get_or_404(state.db, id).await? return ok(to_note_response(note)) } @post("/") async fn create_note(state: AppState, dto: Validated[CreateNoteDto]): ApiCreated[NoteResponseDto] { let model = NoteActiveModel { title: dto.title, content: dto.content, archived: false, owner_id: 1 } let saved = model.insert(state.db).await? return created(to_note_response(saved)) } } ```