acton-service 0.20.0

Production-ready Rust backend framework with type-enforced API versioning
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
//! HTMX Task Manager Example
//!
//! A comprehensive example demonstrating HTMX patterns with acton-service:
//!
//! - **Askama Templates**: Server-side rendering with TemplateContext
//! - **SSE Real-Time Updates**: Live task updates across clients
//! - **Session Authentication**: Login/logout with AuthSession
//! - **ServiceBuilder Integration**: Batteries-included backend with health checks
//!
//! ## Running
//!
//! ```bash
//! cargo run --manifest-path=acton-service/Cargo.toml \
//!   --example task-manager --features htmx-full
//! ```
//!
//! Then open http://localhost:3000 in your browser (or the port configured via ACTON_SERVER_PORT).
//!
//! ## Endpoints
//!
//! - `/` - Task manager UI (frontend)
//! - `/login` - Login page (frontend)
//! - `/health` - Health check (auto-provided by ServiceBuilder)
//! - `/ready` - Readiness probe (auto-provided by ServiceBuilder)

use std::convert::Infallible;
use std::sync::Arc;

use acton_service::prelude::*;
use acton_service::session::{
    create_memory_session_layer, AuthSession, FlashMessage, SessionConfig, TypedSession,
};
use acton_service::versioning::VersionedApiBuilder;
use tokio::sync::RwLock;

// ============================================================================
// Data Models
// ============================================================================

/// A task in our task manager.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: u64,
    pub title: String,
    pub completed: bool,
}

/// In-memory task storage.
#[derive(Debug, Default)]
pub struct TaskStore {
    tasks: Vec<Task>,
    next_id: u64,
}

impl TaskStore {
    fn add(&mut self, title: String) -> Task {
        self.next_id += 1;
        let task = Task {
            id: self.next_id,
            title,
            completed: false,
        };
        self.tasks.push(task.clone());
        task
    }

    fn get(&self, id: u64) -> Option<&Task> {
        self.tasks.iter().find(|t| t.id == id)
    }

    fn update(&mut self, id: u64, title: String) -> Option<Task> {
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == id) {
            task.title = title;
            Some(task.clone())
        } else {
            None
        }
    }

    fn toggle(&mut self, id: u64) -> Option<Task> {
        if let Some(task) = self.tasks.iter_mut().find(|t| t.id == id) {
            task.completed = !task.completed;
            Some(task.clone())
        } else {
            None
        }
    }

    fn delete(&mut self, id: u64) -> bool {
        let len_before = self.tasks.len();
        self.tasks.retain(|t| t.id != id);
        self.tasks.len() < len_before
    }

    fn all(&self) -> Vec<Task> {
        self.tasks.clone()
    }

    fn stats(&self) -> (usize, usize, usize) {
        let total = self.tasks.len();
        let completed = self.tasks.iter().filter(|t| t.completed).count();
        let pending = total - completed;
        (total, completed, pending)
    }
}

type SharedStore = Arc<RwLock<TaskStore>>;

// ============================================================================
// Templates
// ============================================================================

#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
    ctx: TemplateContext,
    tasks: Vec<Task>,
    total_tasks: usize,
    completed_tasks: usize,
    pending_tasks: usize,
}

#[derive(Template)]
#[template(path = "tasks/item.html")]
struct TaskItemTemplate {
    task: Task,
}

#[derive(Template)]
#[template(path = "tasks/edit.html")]
struct TaskEditTemplate {
    task: Task,
}

#[derive(Template)]
#[template(path = "auth/login.html")]
struct LoginTemplate {
    ctx: TemplateContext,
}

// ============================================================================
// Form Data
// ============================================================================

#[derive(Debug, Deserialize)]
struct CreateTaskForm {
    title: String,
}

#[derive(Debug, Deserialize)]
struct UpdateTaskForm {
    title: String,
}

#[derive(Debug, Deserialize)]
struct LoginForm {
    username: String,
}

// ============================================================================
// Response Helpers
// ============================================================================

/// Render OOB stat updates as HTML.
fn render_stats_oob(total: usize, completed: usize, pending: usize) -> String {
    format!(
        r#"<span class="stat-value" id="total-count" hx-swap-oob="outerHTML">{}</span>
<span class="stat-value" id="pending-count" hx-swap-oob="outerHTML">{}</span>
<span class="stat-value" id="completed-count" hx-swap-oob="outerHTML">{}</span>"#,
        total, pending, completed
    )
}

// ============================================================================
// Handlers
// ============================================================================

/// Home page - shows task list.
async fn index(
    flash: FlashMessages,
    auth: TypedSession<AuthSession>,
    Extension(store): Extension<SharedStore>,
) -> impl IntoResponse {
    let tasks = store.read().await.all();
    let (total, completed, pending) = store.read().await.stats();

    let ctx = TemplateContext::new()
        .with_path("/")
        .with_auth(auth.data().user_id.clone())
        .with_flash(flash.into_messages());

    HtmlTemplate::page(IndexTemplate {
        ctx,
        tasks,
        total_tasks: total,
        completed_tasks: completed,
        pending_tasks: pending,
    })
}

/// Create a new task.
async fn create_task(
    Extension(store): Extension<SharedStore>,
    Form(form): Form<CreateTaskForm>,
) -> impl IntoResponse {
    let title = form.title.trim();
    if title.is_empty() {
        return Html("<div class=\"flash flash-error\">Task title cannot be empty</div>")
            .into_response();
    }

    let task = store.write().await.add(title.to_string());

    // Return the new task item with OOB stats update
    let (total, completed, pending) = store.read().await.stats();
    let task_html = TaskItemTemplate { task }.render().unwrap_or_default();
    let stats_html = render_stats_oob(total, completed, pending);

    // Delete empty message if present
    let delete_empty = r#"<li id="empty-message" hx-swap-oob="delete"></li>"#;

    Html(format!("{}{}{}", task_html, stats_html, delete_empty)).into_response()
}

/// Get a single task (for cancel edit).
async fn get_task(
    Path(id): Path<u64>,
    Extension(store): Extension<SharedStore>,
) -> impl IntoResponse {
    match store.read().await.get(id).cloned() {
        Some(task) => HtmlTemplate::fragment(TaskItemTemplate { task }).into_response(),
        None => (StatusCode::NOT_FOUND, "Task not found").into_response(),
    }
}

/// Get task edit form.
async fn edit_task_form(
    Path(id): Path<u64>,
    Extension(store): Extension<SharedStore>,
) -> impl IntoResponse {
    match store.read().await.get(id).cloned() {
        Some(task) => HtmlTemplate::fragment(TaskEditTemplate { task }).into_response(),
        None => (StatusCode::NOT_FOUND, "Task not found").into_response(),
    }
}

/// Update a task.
async fn update_task(
    Path(id): Path<u64>,
    Extension(store): Extension<SharedStore>,
    Form(form): Form<UpdateTaskForm>,
) -> impl IntoResponse {
    let title = form.title.trim();
    if title.is_empty() {
        // Return the task unchanged
        if let Some(task) = store.read().await.get(id).cloned() {
            return HtmlTemplate::fragment(TaskItemTemplate { task }).into_response();
        }
        return (StatusCode::NOT_FOUND, "Task not found").into_response();
    }

    match store.write().await.update(id, title.to_string()) {
        Some(task) => HtmlTemplate::fragment(TaskItemTemplate { task }).into_response(),
        None => (StatusCode::NOT_FOUND, "Task not found").into_response(),
    }
}

/// Toggle task completion.
async fn toggle_task(
    Path(id): Path<u64>,
    Extension(store): Extension<SharedStore>,
) -> impl IntoResponse {
    // Use a block to ensure write lock is released before reading stats
    let toggle_result = { store.write().await.toggle(id) };

    match toggle_result {
        Some(task) => {
            // Update stats via OOB
            let (total, completed, pending) = store.read().await.stats();
            let task_html = TaskItemTemplate { task }.render().unwrap_or_default();
            let stats_html = render_stats_oob(total, completed, pending);

            Html(format!("{}{}", task_html, stats_html)).into_response()
        }
        None => (StatusCode::NOT_FOUND, "Task not found").into_response(),
    }
}

/// Delete a task.
async fn delete_task(
    Path(id): Path<u64>,
    Extension(store): Extension<SharedStore>,
) -> impl IntoResponse {
    // Use a block to ensure write lock is released before reading stats
    let deleted = { store.write().await.delete(id) };

    if deleted {
        // Update stats via OOB - return empty content to remove the task
        let (total, completed, pending) = store.read().await.stats();
        let stats_html = render_stats_oob(total, completed, pending);

        Html(stats_html).into_response()
    } else {
        (StatusCode::NOT_FOUND, "Task not found").into_response()
    }
}

/// SSE endpoint for real-time updates.
async fn events(
    Extension(broadcaster): Extension<Arc<SseBroadcaster>>,
) -> Sse<impl Stream<Item = std::result::Result<SseEvent, Infallible>>> {
    let rx = broadcaster.subscribe();

    // Create a stream from the broadcast receiver
    let stream = stream::unfold(rx, |mut rx| async move {
        match rx.recv().await {
            Ok(msg) => {
                let mut event = SseEvent::default().data(msg.data);
                if let Some(event_type) = msg.event_type {
                    event = event.event(event_type);
                }
                Some((Ok(event), rx))
            }
            Err(_) => None, // Channel closed
        }
    });

    Sse::new(stream).keep_alive(KeepAlive::default())
}

/// Login page.
async fn login_page(flash: FlashMessages, auth: TypedSession<AuthSession>) -> impl IntoResponse {
    let ctx = TemplateContext::new()
        .with_path("/login")
        .with_auth(auth.data().user_id.clone())
        .with_flash(flash.into_messages());

    HtmlTemplate::page(LoginTemplate { ctx })
}

/// Handle login.
async fn login(
    mut auth: TypedSession<AuthSession>,
    Form(form): Form<LoginForm>,
) -> impl IntoResponse {
    let username = form.username.trim();
    if username.is_empty() {
        let _ =
            FlashMessages::push(auth.session(), FlashMessage::error("Username is required")).await;
        return Redirect::to("/login").into_response();
    }

    // In a real app, you'd validate credentials here
    auth.data_mut()
        .login(username.to_string(), vec!["user".to_string()]);
    if let Err(e) = auth.save().await {
        tracing::error!("Failed to save session: {}", e);
    }

    let _ = FlashMessages::push(
        auth.session(),
        FlashMessage::success(format!("Welcome back, {}!", username)),
    )
    .await;

    Redirect::to("/").into_response()
}

/// Handle logout.
async fn logout(mut auth: TypedSession<AuthSession>) -> impl IntoResponse {
    let _ = FlashMessages::push(
        auth.session(),
        FlashMessage::info("You have been logged out"),
    )
    .await;

    auth.data_mut().logout();
    if let Err(e) = auth.save().await {
        tracing::error!("Failed to save session: {}", e);
    }

    Redirect::to("/").into_response()
}

// ============================================================================
// Application
// ============================================================================

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize shared state
    let store: SharedStore = Arc::new(RwLock::new(TaskStore::default()));
    let broadcaster = Arc::new(SseBroadcaster::new());

    // Add some sample tasks
    {
        let mut s = store.write().await;
        s.add("Learn HTMX with acton-service".to_string());
        s.add("Build something awesome".to_string());
        s.add("Deploy to production".to_string());
    }

    // Create session layer
    let session_config = SessionConfig::default();
    let session_layer = create_memory_session_layer(&session_config);

    // Build routes using VersionedApiBuilder with frontend routes
    // This gives us:
    // - Automatic /health and /ready endpoints
    // - Automatic tracing/observability initialization
    // - Graceful shutdown handling
    // - Unversioned frontend routes for HTMX UI
    let routes = VersionedApiBuilder::new()
        .with_frontend_routes(|router| {
            router
                // Pages
                .route("/", get(index))
                .route("/login", get(login_page))
                // Task CRUD
                .route("/tasks", post(create_task))
                .route(
                    "/tasks/{id}",
                    get(get_task).put(update_task).delete(delete_task),
                )
                .route("/tasks/{id}/edit", get(edit_task_form))
                .route("/tasks/{id}/toggle", post(toggle_task))
                // SSE
                .route("/events", get(events))
                // Auth
                .route("/login", post(login))
                .route("/logout", post(logout))
                // Extensions
                .layer(Extension(store))
                .layer(Extension(broadcaster))
                // Session layer
                .layer(session_layer)
        })
        .build_routes();

    // Build and run the service
    // ServiceBuilder handles:
    // - Configuration loading (from env/files)
    // - Tracing initialization
    // - Health/readiness endpoints
    // - Graceful shutdown on SIGTERM/SIGINT
    ServiceBuilder::new()
        .with_routes(routes)
        .build()
        .serve()
        .await?;

    Ok(())
}