lumina-framework 0.1.5

A beautiful, fast, and elegant web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
# 📚 Lumina Framework — Dokumentasi Lengkap


> Dokumentasi detail penggunaan Lumina Framework.
> Untuk quick start, lihat [README.md]./README.md.

---

## 📑 Daftar Isi


1. [Arsitektur]#arsitektur
2. [Instalasi & Setup]#instalasi--setup
3. [Konfigurasi]#konfigurasi
4. [Routing]#routing
5. [Controller & View]#controller--view
6. [Model & Database (ORM)]#model--database-orm
7. [Validasi Request]#validasi-request
8. [Autentikasi & Facade Auth]#autentikasi--facade-auth
9. [Session & Persistence]#session--persistence
10. [Debugging (dd!)]#debugging-dd
11. [CLI Tools]#cli-tools
12. [Eager Loading (N+1 Solution)]#eager-loading-n1-solution
13. [HTMX Integration (Zero-Mouse UI)]#htmx-integration-zero-mouse-ui
14. [File Upload & Image Manipulation (Advanced)]#file-upload--image-manipulation-advanced
15. [Persistent Queue System]#persistent-queue-system
16. [Blade Template Syntax]#blade-template-syntax
17. [Logging & Debugging]#logging--debugging
18. [Rate Limiting]#rate-limiting
19. [**CHEAT SHEET (Quick Reference)**]./CHEAT_SHEET.md

---

## Arsitektur

... (keep existing content) ...

## Controller & View


### View Builder (Laravel Style)

Lumina menggunakan fluent API untuk merender template. Ini menghindari penggunaan `tera::Context` secara manual.

```rust
use crate::core::view::View;

pub async fn index(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    View::make("home.index")
        .with("title", "Lumina Framework")
        .with("version", "v0.1.0")
        .render(&state, &session)
        .await
}
```

---

## Model & Database (ORM)


### Relasi (Relationships)

Lumina mendukung relasi dasar secara out-of-the-box.

#### Has Many

```rust
// Di dalam impl User
pub async fn posts(&self, db: &DatabasePool) -> Result<Vec<Post>, sqlx::Error> {
    Self::has_many::<Post>(db, "user_id", self.id).await
}
```

#### Belongs To

```rust
// Di dalam impl Post
pub    async fn user(&self, db: &DatabasePool) -> Result<User, sqlx::Error> {
        Self::belongs_to::<User>(db, self.user_id).await
    }
}
```

> 📖 **Panduan Lengkap:** Untuk tutorial mendalam tentang relasi (HasOne, HasMany, ManyToMany) dan Eager Loading, silakan baca [**Tutorial Database Relationships**]./docs/RELATIONSHIPS.md.

---

---

## Eager Loading (N+1 Solution)


Eager Loading digunakan untuk mengambil data relasi secara efisien dalam satu query tambahan (menggunakan `WHERE IN`), menghindari masalah N+1 query yang lambat.

### Cara Penggunaan

Cukup tambahkan `.with("nama_relasi")` pada saat membangun query.

```rust
// Mengambil user beserta semua posts mereka (Hanya 2 query total)
let users = User::query(&db).with("posts").get().await?;

for u in users {
    // Data posts tersedia di Option<Vec<Post>>
    if let Some(posts) = u.posts {
        println!("User {} punya {} posts", u.name, posts.len());
    }
}
```

### Konfigurasi Model

Untuk mendukung Eager Loading, model harus mengimplementasikan metode `eager_load` pada trait `Model`.

```rust
#[async_trait]

impl Model for User {
    // ...
    async fn eager_load(models: &mut [Self], db: &DatabasePool, relation: &str) {
        if relation == "posts" {
            let ids: Vec<i64> = models.iter().map(|m| m.id).collect();
            let all_posts = Post::query(db).where_in("user_id", &ids).get().await.unwrap_or_default();

            for model in models {
                let user_posts = all_posts.iter()
                    .filter(|p| p.user_id == model.id)
                    .cloned()
                    .collect();
                model.posts = Some(user_posts);
            }
        }
    }
}
```

---

## HTMX Integration (Zero-Mouse UI)


Lumina terintegrasi dengan **HTMX** untuk memberikan pengalaman Single Page Application (SPA) tanpa perlu menulis JavaScript. Ini sangat mendukung workflow **Keyboardholic**.

### Fitur Utama

1.  **Partial Rendering**: Lumina otomatis mendeteksi request HTMX dan dapat merender hanya bagian konten tanpa layout penuh.
2.  **HX-Boost**: Semua link standar otomatis dikonversi menjadi request HTMX yang cepat.
3.  **is_htmx Detection**: Di dalam controller, Anda bisa mengecek `req.is_htmx()` untuk memberikan respon yang berbeda.

### Penggunaan di Controller

Gunakan `req.is_htmx()` untuk logika percabangan jika diperlukan. Secara default, `View::render(&req)` sudah menyuntikkan variabel `is_htmx` ke template.

```rust
pub async fn index(req: Request) -> impl IntoResponse {
    View::make("dashboard.index")
        .render(&req) // Otomatis mengirim variabel is_htmx ke template
        .await
}
```

### Penggunaan di Template

Lumina menggunakan pola kondisinal di `layout.blade.rs` untuk menangani partial render:

```html
{% if is_htmx %}
    {% block content %}{% endblock %}
{% else %}
    <!-- Full Layout with Scripts & Styles -->
    <body hx-boost="true">
        {% block content %}{% endblock %}
    </body>
{% endif %}
```

---

## Autentikasi & Facade Auth


Untuk mempermudah penggunaan, gunakan struct `Auth` yang menyediakan API statis untuk operasi autentikasi.

```rust
use crate::core::auth::Auth;

// Cek password
if Auth::check("plain_password", &hashed_password) { ... }

// Login User (Menyimpan JWT dan data user ke session)
Auth::login(&session, auth_user).await?;

// Logout
Auth::logout(&session).await;
```

---

## Session & Persistence


Secara default, Lumina menyimpan session di **Database (MySQL/PostgreSQL/SQLite)** sesuai konfigurasi `DATABASE_URL` Anda.

- **Persistence**: Session tetap ada meskipun server di-restart.
- **Auto Logout**: User akan otomatis logout jika tidak ada aktivitas selama **5 menit** (Inactivity Timeout).
- **Fallback**: Jika database tidak tersedia, Lumina akan otomatis menggunakan memori RAM sebagai penyimpanan sementara.

---

## Debugging (dd!)


Gunakan makro `dd!` (Dump & Die) untuk melihat isi variabel langsung di browser dengan tampilan yang cantik.

```rust
crate::dd!(user_data);
```

---

## CLI Tools


| Command | Deskripsi |
|---|---|
| `./lumina watch` | Menjalankan server dengan **Hot Reload**. |
| `./lumina serve` | Menjalankan server biasa. |
| `./lumina migrate` | Menjalankan migrasi database. |
| `./lumina make:controller` | Membuat file controller baru. |

---

> Lihat [CHEAT_SHEET.md]./CHEAT_SHEET.md untuk referensi cepat penulisan kode "Beauty Code".

---

## Arsitektur


Lumina mengikuti pola **MVC** terinspirasi dari Laravel, dibangun di atas:

| Komponen | Library |
|---|---|
| Async Runtime | Tokio |
| HTTP Layer | Axum 0.7 |
| Database | SQLx (SQLite / MySQL / PostgreSQL) |
| Template Engine | Tera |
| Autentikasi | jsonwebtoken |
| Validasi | validator |
| Password Hashing | bcrypt |
| Debugging | Custom dd!() & Dump Tool |

```
lumina/
├── src/
│   ├── core/          ← Router, Validation, Auth, View Engine
│   ├── http/          ← Server, Middleware, Auth middleware
│   ├── app/
│   │   ├── controllers/   ← Request handlers
│   │   ├── models/        ← Database models
│   │   └── services/      ← Business logic
│   └── database/      ← Connection pool, Migrations, Model trait
├── routes/
│   ├── web.rs         ← HTML routes
│   └── api.rs         ← JSON/API routes
└── resources/views/   ← Tera .blade.rs templates
```

---

## Instalasi & Setup


### Prasyarat

- Rust stable terbaru: `rustup update`
- Git

### Clone & Jalankan


```bash
git clone https://github.com/your-org/lumina.git
cd lumina

# Salin konfigurasi

cp .env.example .env

# Jalankan server (migrasi DB otomatis berjalan)

cargo run
```

Server berjalan di **http://127.0.0.1:8000**

---

## Konfigurasi


Edit file `.env` di root project:

```env
APP_NAME=Lumina
APP_ENV=development
APP_DEBUG=true
APP_URL=http://localhost:8000

# Pilih salah satu:

DATABASE_URL=sqlite:./lumina.db
# DATABASE_URL=mysql://root:password@127.0.0.1/lumina

# DATABASE_URL=postgres://postgres:password@127.0.0.1/lumina


JWT_SECRET=your-super-secret-key-min-32-chars
```

> **Catatan:** `DATABASE_URL` dengan prefix `sqlite:` akan otomatis memilih driver SQLite. MySQL dan PostgreSQL juga didukung.

---

## Routing


### Web Routes (`routes/web.rs`)


Daftarkan route HTML di `routes/web.rs` menggunakan fluent builder API:

```rust
use crate::core::router::Router;
use crate::app::controllers::home_controller::HomeController;
use crate::core::application::AppState;
use std::sync::Arc;

pub fn register() -> Router<Arc<AppState>> {
    Router::new()
        .get("/",           HomeController::index)
        .get("/about",      HomeController::about)
        .get("/users",      UserController::index)
        .get("/users/:id",  UserController::show)
        .post("/users",     UserController::store)
        .put("/users/:id",  UserController::update)
        .delete("/users/:id", UserController::destroy)
}
```

### API Routes (`routes/api.rs`)


API routes di-prefix `/api` secara otomatis oleh `Application::build_router`.

```rust
use axum::{Router as AxumRouter, routing, middleware::from_fn};
use crate::http::middleware::auth_required;

pub fn register() -> Router<Arc<AppState>> {
    // Public — tidak butuh token
    let public = AxumRouter::new()
        .route("/auth/login",    routing::post(AuthController::api_login))
        .route("/auth/register", routing::post(AuthController::api_register));

    // Protected — wajib Bearer token
    let protected = AxumRouter::new()
        .route("/auth/me",   routing::get(AuthController::me))
        .route("/users",     routing::get(ApiController::index))
        .route("/users/:id", routing::get(ApiController::show))
        .route_layer(from_fn(auth_required));

    Router::from_axum(
        AxumRouter::new().merge(public).merge(protected)
    )
}
```

### HTTP Methods yang Didukung


| Method | Builder |
|--------|---------|
| GET | `.get(path, handler)` |
| POST | `.post(path, handler)` |
| PUT | `.put(path, handler)` |
| PATCH | `.patch(path, handler)` |
| DELETE | `.delete(path, handler)` |

### Route Parameters


Gunakan `:param` pada path, lalu ekstrak dengan `Path<T>`:

```rust
use axum::extract::Path;

pub async fn show(
    State(state): State<Arc<AppState>>,
    Path(id): Path<u32>
) -> Html<String> {
    // id tersedia sebagai u32
}
```

---

## Controller


### Membuat Controller Baru


Buat file di `src/app/controllers/nama_controller.rs`:

```rust
use axum::{extract::State, response::Html};
use std::sync::Arc;
use crate::core::application::AppState;
use tera::Context;

pub struct ProductController;

impl ProductController {
    /// GET /products — Daftar semua produk
    pub async fn index(State(state): State<Arc<AppState>>) -> Html<String> {
        let mut ctx = Context::new();
        ctx.insert("title", "Daftar Produk");
        ctx.insert("products", &vec!["Produk A", "Produk B"]);

        let html = state.view.render("products/index.blade.rs", &ctx);
        Html(html)
    }
}
```

Lalu daftarkan di `src/app/controllers/mod.rs`:

```rust
pub mod product_controller;
```

Dan tambahkan ke route:

```rust
// routes/web.rs
use crate::app::controllers::product_controller::ProductController;

Router::new()
    .get("/products", ProductController::index)
```

### JSON Response (API Controller)


```rust
use axum::Json;
use serde_json::{json, Value};

pub struct ApiController;

impl ApiController {
    pub async fn index() -> Json<Value> {
        Json(json!({
            "status": "success",
            "data": [
                {"id": 1, "name": "Alice"},
                {"id": 2, "name": "Bob"}
            ]
        }))
    }
}
```

### Fluent Redirect API


Lumina menyediakan *builder* untuk redirect bergaya Laravel:

```rust
use crate::core::response::Redirect;

pub async fn store(session: Session) -> impl IntoResponse {
    Redirect::to("/dashboard")
        .with_success("Data berhasil disimpan!")
        .send(&session)
        .await
}
```

Tersedia metode:
- `.with_success(msg)`: Pesan sukses hijau.
- `.with_error(msg)`: Pesan error merah.
- `.with_errors(hashmap)`: Error validasi per field.
- `.with_input(struct/json)`: Menyimpan data form agar tidak hilang (*Old Input*).

### Extractor & Dependency Injection


Lumina menggunakan sistem *Extractor* milik Axum untuk menyuntikkan data secara otomatis ke dalam parameter fungsi Controller (Dependency Injection).

| Parameter | Nama Extractor | Fungsi |
|-----------|----------------|--------|
| `State(state)` | `State<AppState>` | Memberikan akses ke database, view engine, dan service global. |
| `session` | `Session` | Akses ke session user (Flash messages, data login, dll). |
| `token` | `CsrfToken` | Digunakan untuk validasi CSRF dan sinkronisasi token di form. |
| `user` | `AuthUser` | Mengambil data user yang sedang login secara otomatis. |
| `Path(id)` | `Path<T>` | Mengambil parameter ID dari URL (misal: `/users/:id`). |
| `ValidatedForm(f)`| `ValidatedForm<T>` | Mengambil data form dan memvalidasinya secara otomatis. |

#### Contoh Penggunaan Lengkap:


```rust
pub async fn profile(
    State(state): State<AppState>, // Inject State
    user: AuthUser,                // Inject User Login
    session: Session               // Inject Session
) -> impl IntoResponse {
    View::make("user.profile")
        .with("user", user)
        .render(&state, &session)
        .await
}
```

### ⚡ Lumina Request & Fluent API (Laravel-Style)


Untuk mempermudah kurva belajar dan mengurangi import boilerplate, Lumina menyediakan bundle extractor `Request` yang dibekali dengan *shortcut methods* ekspresif bergaya Laravel.

| Shortcut Method | Return Type | Kegunaan |
|-----------------|-------------|----------|
| `req.db()` | `&DatabasePool` | Akses langsung ke database pool |
| `req.view(tpl)` | `ViewBuilder` | Membuat view builder baru |
| `req.redirect(p)`| `Redirect` | Membuat instance Laravel-style redirect |
| `req.back()` | `Redirect` | Membuat redirect kembali ke halaman asal |
| `req.session_get(k)`| `Option<T>` | Mengambil data session |
| `req.session_set(k, v)`| `()` | Menyimpan data ke session |
| `req.json(v)` | `Response` | Mengembalikan JSON response instan |

#### Contoh Penggunaan Praktis:


```rust
use crate::core::request::Request;

pub struct HomeController;

impl HomeController {
    pub async fn index(req: Request) -> impl IntoResponse {
        // req.view() otomatis menggunakan ViewEngine di state
        req.view("home.index")
            .with("title", "Lumina Framework")
            .render(&req)
            .await
    }

    pub async fn store(req: Request) -> impl IntoResponse {
        // req.redirect() mempermudah redirect response
        req.redirect("/dashboard")
            .with_success("Data berhasil disimpan!")
            .go(&req)
            .await
    }
}
```

---

## Model & Lumina Eloquent ORM


Lumina hadir dengan **ORM Mandiri (Eloquent / Active Record)** yang anggun dan ekspresif. Anda tidak perlu lagi menulis raw SQL query string atau melakukan konversi parameter manual (`?` vs `$1`). Lumina menangani cross-database query (PostgreSQL, SQLite, MySQL) secara transparan!

### Mendeklarasikan Model (`#[derive(LuminaModel)]`)


Cukup tambahkan derive `LuminaModel` pada struct model Anda:

```rust
use lumina::prelude::*;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default, LuminaModel)]

#[lumina(table = "products")]

pub struct Product {
    pub id: i64,
    pub name: String,
    pub price: i64,
    pub created_at: Option<String>,
    pub updated_at: Option<String>,
    pub deleted_at: Option<String>,
}

impl Product {
    pub fn new() -> Self {
        Self::default()
    }
}
```

Dengan satu derive di atas, Anda langsung mendapatkan fitur Eloquent lengkap:
- `Product::all(db).await?` — Ambil semua record aktif (ORDER BY id DESC).
- `Product::find(db, id).await?` — Mengembalikan `Ok(Some(item))` atau `Ok(None)`.
- `Product::find_or_fail(db, id).await?` — Mengembalikan record atau error jika tidak ada.
- `Product::where_eq(db, "name", "Sepatu").first().await?` — Fluent query builder.
- `Product::latest(db).paginate(page, per_page).await?` — Paginasi bawaan.
- `Product::count(db).await?` — Hitung total record aktif.
- `$model.save(db).await?` — Otomatis `INSERT` jika ID == 0, atau `UPDATE` jika ID > 0.
- `Product::destroy(db, id).await?` / `$model.delete(db).await?` — Soft delete instan.

---

### Controller yang Cantik & Ergonomis (Laravel Style)


Dengan `Request` extractor dan `LuminaResult`, controller Anda menjadi sangat ringkas, bersih, dan ekspresif. Tidak ada lagi signature yang panjang atau konversi status code manual:

```rust
use lumina::prelude::*;
use crate::app::models::product::Product;

pub struct ProductController;

impl ProductController {
    /// GET /api/products — Ambil seluruh data
    pub async fn index(req: Request) -> LuminaResult {
        let products = Product::all(req.db()).await?;
        req.ok(products)
    }

    /// GET /api/products/paged — Paginasi instan (otomatis membaca ?page=X&per_page=Y)
    pub async fn paginate(req: Request) -> LuminaResult {
        let (page, per_page) = req.pagination();
        let paginator = Product::paginate(req.db(), page, per_page).await?;
        req.paginate(paginator)
    }

    /// GET /api/products/:id — Detail satu produk (otomatis membaca :id dari route)
    pub async fn show(req: Request) -> LuminaResult {
        let id = req.id_or_fail()?;
        match Product::find(req.db(), id).await? {
            Some(product) => req.ok(product),
            None => req.not_found("Produk tidak ditemukan"),
        }
    }

    /// POST /api/products — Simpan data baru (Active Record)
    pub async fn store(req: Request, ValidatedJson(input): ValidatedJson<CreateProductInput>) -> LuminaResult {
        let mut product = Product {
            name: input.name,
            price: input.price,
            ..Default::default()
        };
        let id = product.save(req.db()).await?;
        product.id = id;
        req.created_with(product, "Produk berhasil ditambahkan")
    }

    /// PUT /api/products/:id — Update data
    pub async fn update(
        req: Request,
        ValidatedJson(input): ValidatedJson<UpdateProductInput>,
    ) -> LuminaResult {
        let id = req.id_or_fail()?;
        let mut product = match Product::find(req.db(), id).await? {
            Some(p) => p,
            None => return req.not_found("Produk tidak ditemukan"),
        };
        product.name = input.name;
        product.price = input.price;
        product.save(req.db()).await?;
        req.success(product, "Produk berhasil diperbarui")
    }

    /// DELETE /api/products/:id — Hapus data
    pub async fn destroy(req: Request) -> LuminaResult {
        let id = req.id_or_fail()?;
        if Product::destroy(req.db(), id).await? {
            req.success(serde_json::json!({ "id": id }), "Produk berhasil dihapus")
        } else {
            req.not_found("Produk tidak ditemukan")
        }
    }
}
```

### Soft Delete


Lumina menggunakan **soft delete** secara default. Record tidak benar-benar dihapus,
melainkan kolom `deleted_at` diisi timestamp:

```sql
-- Di migrasi, tambahkan kolom ini:
deleted_at TIMESTAMP NULL DEFAULT NULL
```

---

## Validasi Request


### ValidatedJson (untuk API)


```rust
use serde::Deserialize;
use validator::Validate;
use crate::core::validation::ValidatedJson;

#[derive(Debug, Deserialize, Validate)]

pub struct CreateProductRequest {
    #[validate(length(min = 3, message = "Nama minimal 3 karakter"))]
    pub name: String,

    #[validate(range(min = 0.0, message = "Harga tidak boleh negatif"))]
    pub price: f64,
}

pub async fn store(
    ValidatedJson(payload): ValidatedJson<CreateProductRequest>
) -> Json<Value> {
    // Jika sampai sini, data sudah valid
    Json(json!({"status": "success", "name": payload.name}))
}
```

Jika validasi gagal, Lumina otomatis mengembalikan **HTTP 422**:

```json
{
  "message": "The given data was invalid.",
  "errors": {
    "name": ["Nama minimal 3 karakter"],
    "price": ["Harga tidak boleh negatif"]
  }
}
```

### ValidatedForm (Otomatis & Cerdas)


`ValidatedForm<T>` adalah cara paling elegan untuk menangani form HTML. Berbeda dengan `ValidatedJson`, extractor ini **otomatis** melakukan interupsi jika data tidak valid.

```rust
use crate::core::validation::ValidatedForm;

pub async fn store(
    // Jika validasi gagal, Lumina otomatis:
    // 1. Redirect balik ke halaman asal (Referer).
    // 2. Flash pesan error ke session.
    // 3. Simpan data input ke session (Old Input).
    ValidatedForm(payload): ValidatedForm<CreateProductRequest>
) -> impl IntoResponse {
    // Jika kode ini jalan, berarti data SUDAH PASTI VALID.
    Redirect::to("/products").with_success("Produk dibuat!").send(&session).await
}
```

### Aturan Validasi yang Tersedia


| Aturan | Contoh |
|--------|--------|
| Panjang string | `#[validate(length(min = 3, max = 100))]` |
| Format email | `#[validate(email)]` |
| Rentang angka | `#[validate(range(min = 1, max = 999))]` |
| Wajib diisi | Field non-Option otomatis wajib diisi |
| Regex | `#[validate(regex(path = *MY_REGEX))]` |

---

## Template Engine


Lumina menggunakan **Tera** — template engine mirip Jinja2/Blade.

Template disimpan di `resources/views/**/*.blade.rs`.

### Rendering View


```rust
use tera::Context;

pub async fn index(State(state): State<Arc<AppState>>) -> Html<String> {
    let mut ctx = Context::new();
    ctx.insert("title", "Halaman Produk");
    ctx.insert("user_name", "Budi");

    Html(state.view.render("products/index.blade.rs", &ctx))
}
```

### Contoh Template (`resources/views/products/index.blade.rs`)


```html
{% extends "layout.blade.rs" %}

{% block content %}
<h1>{{ title }}</h1>
<p>Selamat datang, {{ user_name }}!</p>

{% if products %}
<ul>
  {% for product in products %}
  <li>{{ product.name }} — Rp{{ product.price }}</li>
  {% endfor %}
</ul>
{% else %}
<p>Belum ada produk.</p>
{% endif %}
{% endblock %}
```

### Layout (`resources/views/layout.blade.rs`)


```html
<!DOCTYPE html>

<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}Lumina{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
```

---

## Autentikasi JWT


### Register via API


**Endpoint:** `POST /api/auth/register`

```json
{
  "name": "Slamet Sugandi",
  "email": "slamet@lumina.rs",
  "password": "rahasia123"
}
```

**Response sukses:**
```json
{"success": true, "message": "User registered", "id": 1}
```

### Login via API


**Endpoint:** `POST /api/auth/login`

```json
{
  "email": "slamet@lumina.rs",
  "password": "rahasia123"
}
```

**Response sukses:**
```json
{"success": true, "token": "eyJ0eXAiOiJKV1QiLCJhbGci..."}
```

### Mengakses Route Terproteksi


Sertakan token di header:

```
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGci...
```

**Endpoint:** `GET /api/auth/me`

```json
{"success": true, "data": {"id": 1, "name": "Authenticated User"}}
```

### JWT Claims


Token JWT berisi:

```json
{
  "sub": "1",
  "email": "slamet@lumina.rs",
  "role": "user",
  "iat": 1714218000,
  "exp": 1714304400
}
```

Token expire dalam **24 jam** secara default.

---

## Service Layer


Service layer memisahkan business logic dari controller.

### Membuat Service


```rust
// src/app/services/product_service.rs
use std::sync::Arc;
use crate::database::connection::DatabasePool;
use crate::app::models::product::Product;
use crate::database::model::Model;

pub struct ProductService {
    db: Arc<DatabasePool>,
}

impl ProductService {
    pub fn new(db: Arc<DatabasePool>) -> Self {
        Self { db }
    }

    pub async fn create(&self, name: String, price: f64) -> Result<i64, String> {
        let product = Product { id: 0, name, price };
        product.save(&self.db)
            .await
            .map_err(|e| format!("DB error: {}", e))
    }

    pub async fn get_all(&self) -> Result<Vec<Product>, String> {
        Product::all(&self.db)
            .await
            .map_err(|e| format!("DB error: {}", e))
    }
}
```

### Mendaftarkan Service ke AppState


Tambahkan di `src/core/application.rs`:

```rust
pub struct AppState {
    pub db:              Arc<DatabasePool>,
    pub view:            ViewEngine,
    pub auth_service:    Arc<AuthService>,
    pub product_service: Arc<ProductService>,   // ← tambahkan
}
```

---

## Middleware


### Middleware yang Tersedia


| Middleware | Lokasi | Fungsi |
|------------|--------|--------|
| `logger` | `src/http/middleware.rs` | Log setiap request |
| `auth_required` | `src/http/middleware.rs` | Validasi JWT Bearer token |

### Menerapkan Middleware ke Route Group


```rust
use axum::middleware::from_fn;
use crate::http::middleware::auth_required;

let protected = AxumRouter::new()
    .route("/dashboard", routing::get(DashboardController::index))
    .route_layer(from_fn(auth_required));
```

### Membuat Middleware Kustom


```rust
// src/http/middleware.rs
use axum::{
    middleware::Next,
    response::Response,
    http::Request,
    body::Body,
};

pub async fn my_middleware(
    req: Request<Body>,
    next: Next,
) -> Response {
    println!("→ Before handler");
    let response = next.run(req).await;
    println!("← After handler");
    response
}
```

Terapkan ke router:

```rust
use axum::middleware::from_fn;

Router::new()
    .get("/path", handler)
    .layer(from_fn(my_middleware))
```

---

## CLI Tools


Lumina memiliki CLI bawaan untuk mempercepat development.

### Menjalankan CLI


```bash
# Windows

lumina.bat <command>

# Linux/macOS

./lumina <command>
```

### Perintah yang Tersedia


```bash
# Menjalankan server

lumina serve
lumina serve --port 3000

# Membuat file baru

lumina make:controller ProductController
lumina make:model Product
lumina make:service ProductService
lumina make:middleware RateLimiter

# Database

lumina migrate
lumina migrate:fresh
```

### Contoh Output


```
✨ Lumina Framework v0.1.0
🔄 Running migrations...
✅ Migrations done.
🌐 Listening on http://127.0.0.1:8000
```

---

## 🎓 Tutorial: Membangun CRUD Produk


Tutorial langkah demi langkah membangun fitur CRUD produk.

### Langkah 1 — Setup


```bash
cp .env.example .env
# Edit DATABASE_URL di .env

cargo run
```

### Langkah 2 — Tambah Migrasi


Buat file di `database/migrations/` (migrasi berjalan otomatis saat startup):

```sql
CREATE TABLE IF NOT EXISTS products (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    name       TEXT    NOT NULL,
    price      REAL    NOT NULL DEFAULT 0,
    deleted_at TIMESTAMP NULL DEFAULT NULL
);
```

### Langkah 3 — Buat Model


`src/app/models/product.rs` — implementasikan trait `Model` (lihat bagian [Model & Database](#model--database)).

Daftarkan di `src/app/models/mod.rs`:
```rust
pub mod product;
```

### Langkah 4 — Buat Controller


`src/app/controllers/product_controller.rs`:

```rust
use axum::{extract::{State, Path}, Json};
use std::sync::Arc;
use serde_json::{json, Value};
use crate::core::application::AppState;
use crate::database::model::Model;
use crate::app::models::product::Product;

pub struct ProductController;

impl ProductController {
    pub async fn index(State(state): State<Arc<AppState>>) -> Json<Value> {
        match Product::all(&state.db).await {
            Ok(p)  => Json(json!({"status": "success", "data": p})),
            Err(e) => Json(json!({"status": "error", "message": e.to_string()})),
        }
    }

    pub async fn show(
        State(state): State<Arc<AppState>>,
        Path(id): Path<i64>
    ) -> Json<Value> {
        match Product::find(&state.db, id).await {
            Ok(p)  => Json(json!({"status": "success", "data": p})),
            Err(_) => Json(json!({"status": "error", "message": "Not found"})),
        }
    }
}
```

### Langkah 5 — Daftarkan Route


`routes/api.rs`:

```rust
.route("/products",     routing::get(ProductController::index))
.route("/products/:id", routing::get(ProductController::show))
```

### Langkah 6 — Test


```bash
# Daftar semua produk

curl http://localhost:8000/api/products

# Produk by ID

curl http://localhost:8000/api/products/1
```

---

## File Upload & Image Manipulation (Advanced)


Lumina menyediakan sistem penanganan file yang intuitif dan *fluent*, terinspirasi dari kemudahan Laravel namun dengan performa pemrosesan gambar native Rust yang sangat cepat.

### Ringkasan Penggunaan


Gunakan `LuminaMultipart` di controller untuk mengekstrak file dan data form secara otomatis.

```rust
pub async fn store(req: Request, multipart: LuminaMultipart) -> impl IntoResponse {
    if let Some(file) = multipart.file("image") {
        // Manipulasi & Simpan
        let path = file.clone()
            .thumbnail(300, 300)
            .grayscale()
            .store(&req, "avatars").await?;

        return req.redirect("/profile").with_success("Avatar diupdate!").go(&req).await;
    }
}
```

> 📖 **Panduan Lengkap:** Untuk tutorial mendalam tentang manipulasi gambar, silakan baca [**Tutorial File Upload & Image Manipulation**]./docs/FILE_UPLOAD.md.

---

## 🐛 Troubleshooting


| Masalah | Solusi |
|---------|--------|
| `❌ Gagal connect ke database` | Periksa `DATABASE_URL` di `.env` |
| `❌ Parsing error(s)` saat startup | Periksa sintaks template .blade.rs di `resources/views/` |
| JWT token invalid | Pastikan `JWT_SECRET` sama di semua environment |
| `cargo run` gagal build | Jalankan `cargo check` untuk melihat error detail |

---

## 🛠️ Debugging Tools (Premium)


Lumina dilengkapi dengan alat bantu debugging premium:

### Dump & Die (`dd!`)


Gunakan makro `dd!()` di mana saja dalam kode Rust Anda untuk menghentikan eksekusi dan menampilkan data secara visual di browser dengan tampilan *Dark Mode* yang elegan.

```rust
let user = User::find(&db, 1).await?;
dd!(user); // Eksekusi berhenti di sini dan merender UI debugger
```

### Template Dump (`dump`)


Dalam template Tera, Anda bisa melihat isi variabel menggunakan filter `dump`:

```html
{{ dump(var=products) }}
```

---

## Persistent Queue System


Lumina memiliki sistem antrean (Queue) berbasis database yang persisten. Pekerjaan (Job) disimpan di tabel `jobs` dan diproses di background oleh worker.

### Membuat Job Baru

Gunakan CLI untuk membuat class Job baru:
```bash
./lumina make:job SendEmailJob
```

### Menjalankan Job

```rust
use crate::app::jobs::SendEmailJob;

// Dispatch job ke antrean
state.queue.push(SendEmailJob::new(email, content)).await?;
```

### Queue Resilience

Worker Lumina memiliki mekanisme *retry* otomatis. Jika tabel `jobs` belum tersedia (misal saat startup awal), worker akan menunggu dan mencoba kembali setiap 30 detik tanpa mematikan seluruh aplikasi.

---

## Blade Template Syntax


Lumina menyediakan *preprocessor* yang memungkinkan Anda menulis template dengan sintaks bergaya Laravel Blade. Sintaks ini akan diterjemahkan secara otomatis ke engine `Tera`.

### Direktif yang Tersedia

- `@extends('layout')`: Mewarisi layout (otomatis mencari file `.blade.rs`).
- `@section('name')` / `@endsection`: Mendefinisikan blok konten.
- `@yield('name')`: Menampilkan isi dari sebuah section.
- `@if(condition)` / `@elseif(condition)` / `@else` / `@endif`.
- `@foreach(items as item)` / `@endforeach`.
- `@auth` / `@endauth`: Menampilkan konten hanya jika user sudah login.
- `@guest` / `@endguest`: Menampilkan konten hanya jika user belum login.
- `@csrf`: Men-generate input hidden untuk token CSRF.
- `@include('partial')`: Menyertakan file template lain.

---

## Logging & Debugging


Lumina menggunakan sistem logging terstruktur yang mencetak ke console (development) dan ke file (production).

### Konfigurasi Logging

Atur level log di file `.env`:
```env
LOG_LEVEL=info  # debug, info, warn, error
```

### File Logging

Semua log disimpan secara otomatis di folder `storage/logs/`. File log di-roll setiap hari (misal: `lumina.2026-05-10.log`).

### Debugging Tools

- `dd!($var)`: Dump and Die (merender UI debugger cantik di browser).
- `dump!($var)`: Mencetak variabel ke terminal secara terstruktur tanpa menghentikan eksekusi.

---

## Rate Limiting


Lumina menyertakan middleware Rate Limiter bawaan untuk melindungi aplikasi dari brute-force atau DDoS level aplikasi.

### Konfigurasi

Atur batas request di file `.env`:
```env
RATE_LIMIT_MAX=60     # Maksimal request per window
RATE_LIMIT_WINDOW=60  # Durasi window dalam detik
```

### Penggunaan Per-Route

Anda bisa menerapkan limit yang lebih ketat untuk route tertentu (misal login):
```rust
use crate::core::rate_limit::{RateLimitConfig, rate_limit_with_config};

// Di route builder
.route("/login", post(handler))
.layer(from_fn_with_state(state, |state, req, next| async move {
    rate_limit_with_config(state, RateLimitConfig::strict(), req, next).await
}))
```

---

## 🌍 Lumina Localization (I18n)

Lumina menyediakan sistem multi-bahasa yang terintegrasi dengan middleware dan view engine.
- **Deteksi:** Mendukung deteksi bahasa via query param `?lang=id` atau header `Accept-Language`.
- **Global Function:** Gunakan `{{ __("key") }}` di dalam template Tera/Blade.

## 📡 Lumina Echo (WebSockets)

Sistem real-time broadcasting untuk komunikasi dua arah.
- **Event Broadcasting:** Cukup implementasikan trait `ShouldBroadcast` pada struct event Anda.
- **Client Side:** Gunakan `resources/js/echo.js` untuk mendengarkan event di browser.

## 🔐 Lumina Socialite (OAuth)

Autentikasi modular untuk provider pihak ketiga.
- **Modular Driver:** Mendukung penambahan provider baru dengan mudah.
- **Auto Registration:** Secara otomatis mendaftarkan user baru yang login via sosial media.

## 💾 Lumina Backup System

Sistem perlindungan data otomatis.
- **Full Backup:** Mencakup ekspor database (SQL/SQLite) dan pengarsipan folder storage.
- **Automatic Schedule:** Berjalan otomatis setiap hari jam 02:00 pagi.

---

> **Lumina Framework** — Built with ❤️ and 🦀 Rust
>
> Lisensi: MIT | Penulis: Slamet Sugandi <packercyber@gmail.com>