Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.280.1 KB2026-09-140.1.167.6 KB2026-09-140.1.064.9 KB2026-09-14
Version
0.1.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
64.9 KB
Downloads
3
Checksum
3f5a7260ef28c5f7ca3540b87faa9176bdf8039ad720f809e49a0f7117b8528b
Dependencies
None

todo.rs

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
//! mon の上に `/api/todos` と一覧のページを載せる例。
//!
//!     cargo run --example todo
//!
//! mon が持つのは土台だけなので、表もルートもこちら側で用意する。

use anyhow::Context;
use axum::Router;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Html;
use axum::routing::get;
use chrono::{DateTime, Utc};
use mon::extract::{Json, Path, Query};
use mon::state::AppState;
use mon::{AppError, conf, database, html, log, page, relay, route, session};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use uuid::Uuid;


/// 選び出す列。3 箇所で同じものを使う
const COLUMN: &str = "id, title, done, created_at, updated_at";


#[derive(Debug, Clone, Serialize, FromRow)]
struct Todo {
    id: Uuid,
    title: String,
    done: bool,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

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

#[derive(Debug, Deserialize)]
struct UpdateTodo {
    title: Option<String>,
    done: Option<bool>,
}

#[derive(Debug, Deserialize)]
struct ListQuery {
    done: Option<bool>,
    limit: Option<i64>,
}


#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let _log = log::start("info,tower_http=debug");

    let conf = conf::load()?;
    let port = conf.port;
    let database = database::connect(&conf.database_url).await?;
    prepare(&database).await?;

    let client = relay::client(&conf).context("中継に使うクライアントを作れません")?;
    let store = session::store(&conf, &database);
    session::prepare(&store).await?;
    session::start_sweep(store.clone(), conf.session_max_age);

    let routes = routes(&conf);
    let state = AppState {
        database,
        client,
        session: store,
        conf: Arc::new(conf),
    };

    let address = SocketAddr::from(([0, 0, 0, 0], port));
    let listener = TcpListener::bind(address)
        .await
        .with_context(|| format!("{address} で待ち受けられません"))?;
    tracing::info!("listening on http://{address}");

    // ConnectInfo を入れると、CLIENT_IP_HEADER がないときに TCP の相手を使える
    let app = route::wrap(routes, state).into_make_service_with_connect_info::<SocketAddr>();

    axum::serve(listener, app).await?;
    Ok(())
}


/// パスは全部こちらで決める。mon は 1 つも取らない
fn routes(conf: &mon::Conf) -> Router<AppState> {
    Router::new()
        .route("/", get(index))
        .route("/api/todos", get(list))
        .route("/api/todos", axum::routing::post(create))
        .route("/api/todos/{id}", get(get_one))
        .route("/api/todos/{id}", axum::routing::patch(update))
        .route("/api/todos/{id}", axum::routing::delete(remove))
        .route("/health", get(route::health))
        .nest("/api/session", session::router())
        .nest("/relay", relay::router())
        .nest_service("/static", route::assets(conf))
        .fallback(page::not_found)
}


async fn prepare(database: &SqlitePool) -> anyhow::Result<()> {
    sqlx::query(
        "create table if not exists todo (\
         id blob primary key not null, title text not null, done integer not null default 0, \
         created_at text not null, updated_at text not null)",
    )
    .execute(database)
    .await
    .context("todo の表を作れません")?;

    Ok(())
}


/// GET / — 保存されているものを並べたページ
async fn index(State(state): State<AppState>) -> Result<Html<String>, AppError> {
    let items = select(&state.database, None, None).await?;
    Ok(Html(html::document("todo", &page(&items))))
}


fn page(items: &[Todo]) -> String {
    let mut out = String::new();
    out.push_str("<h1>todo</h1>");
    out.push_str("<p>SQLite に入っているものを、サーバー側で HTML にして返しています。</p>");

    if items.is_empty() {
        out.push_str(r#"<p class="note">まだ 1 件もありません。</p>"#);
        return out;
    }

    out.push_str("<ul>");
    for item in items {
        let class = if item.done { r#" class="done""# } else { "" };
        out.push_str(&format!("<li{}>{}</li>", class, html::escape(&item.title)));
    }
    out.push_str("</ul>");
    out
}


async fn select(
    database: &SqlitePool,
    done: Option<bool>,
    limit: Option<i64>,
) -> Result<Vec<Todo>, sqlx::Error> {
    let mut sql = format!("select {} from todo", COLUMN);
    if done.is_some() {
        sql.push_str(" where done = ?");
    }
    sql.push_str(" order by created_at limit ?");

    let mut statement = sqlx::query_as::<_, Todo>(&sql);
    if let Some(done) = done {
        statement = statement.bind(done);
    }

    // SQLite では負の limit が「上限なし」を意味する
    statement.bind(limit.unwrap_or(-1)).fetch_all(database).await
}


/// GET /api/todos?done=true&limit=10
async fn list(
    State(state): State<AppState>,
    Query(query): Query<ListQuery>,
) -> Result<Json<Vec<Todo>>, AppError> {
    Ok(Json(select(&state.database, query.done, query.limit).await?))
}


/// POST /api/todos  `{"title": "..."}`
async fn create(
    State(state): State<AppState>,
    Json(body): Json<CreateTodo>,
) -> Result<(StatusCode, Json<Todo>), AppError> {
    let title = validate_title(&body.title)?;
    let now = Utc::now();
    let todo = Todo {
        id: Uuid::now_v7(), // 生成時刻の順に並ぶ UUID
        title,
        done: false,
        created_at: now,
        updated_at: now,
    };

    sqlx::query("insert into todo (id, title, done, created_at, updated_at) values (?, ?, ?, ?, ?)")
        .bind(todo.id)
        .bind(&todo.title)
        .bind(todo.done)
        .bind(todo.created_at)
        .bind(todo.updated_at)
        .execute(&state.database)
        .await?;

    Ok((StatusCode::CREATED, Json(todo)))
}


/// GET /api/todos/{id}
async fn get_one(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> Result<Json<Todo>, AppError> {
    let found = sqlx::query_as::<_, Todo>(&format!("select {} from todo where id = ?", COLUMN))
        .bind(id)
        .fetch_optional(&state.database)
        .await?;

    found.map(Json).ok_or_else(|| not_found(id))
}


/// PATCH /api/todos/{id}  `{"title": "...", "done": true}`(どちらも省略できる)
async fn update(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
    Json(body): Json<UpdateTodo>,
) -> Result<Json<Todo>, AppError> {
    let title = body.title.as_deref().map(validate_title).transpose()?;
    let sql = format!(
        "update todo set title = coalesce(?, title), done = coalesce(?, done), updated_at = ? \
         where id = ? returning {}",
        COLUMN
    );

    let updated = sqlx::query_as::<_, Todo>(&sql)
        .bind(title)
        .bind(body.done)
        .bind(Utc::now())
        .bind(id)
        .fetch_optional(&state.database)
        .await?;

    updated.map(Json).ok_or_else(|| not_found(id))
}


/// DELETE /api/todos/{id}
async fn remove(
    State(state): State<AppState>,
    Path(id): Path<Uuid>,
) -> Result<StatusCode, AppError> {
    let result = sqlx::query("delete from todo where id = ?")
        .bind(id)
        .execute(&state.database)
        .await?;

    if result.rows_affected() == 0 {
        return Err(not_found(id));
    }

    Ok(StatusCode::NO_CONTENT)
}


fn not_found(id: Uuid) -> AppError {
    AppError::NotFound(format!("todo {id} は存在しません"))
}


fn validate_title(title: &str) -> Result<String, AppError> {
    let title = title.trim();
    if title.is_empty() {
        return Err(AppError::Validation("title は必須です".to_owned()));
    }

    if title.chars().count() > 200 {
        return Err(AppError::Validation("title は 200 文字以内にしてください".to_owned()));
    }

    Ok(title.to_owned())
}