first commit

This commit is contained in:
phattaranun.a committed 2026-05-24 22:55:17 +07:00
commit 2a1854ab08
120 files changed
+11300

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# docker-compose only — wires services together.
# All runtime vars are centralized here at the repository root.
# shared app defaults
NEXT_PUBLIC_API_BASE=/api
NEXT_PUBLIC_FILES_BASE=/files
INTERNAL_API_BASE=http://at-transit-backend:18080/api
BACKEND_INTERNAL_URL=http://at-transit-backend:18080
STORAGE_INTERNAL_URL=http://seaweed-filer:8888
STORAGE_BUCKET_PATH=/buckets/transit
# backend runtime defaults
SQL_DB_URL=postgres://transit:transit@localhost:5432/at-transit
STORAGE_URL=http://localhost:8888
STORAGE_PUBLIC_BASE=/files
BIND_ADDR=0.0.0.0:8080
CORS_ORIGINS=http://localhost:3000
RUST_LOG=info,backend=debug
SEED_ASSETS_DIR=../storage/seed-assets
SQL_DB_USER=transit
SQL_DB_PASSWORD=transit
SQL_DB_NAME=at-transit
BACKEND_PORT=8080
FRONTEND_PORT=3000
SEAWEED_MASTER_PORT=9333
SEAWEED_VOLUME_PORT=8081
STORAGE_PORT=8888
+17
View File
@@ -0,0 +1,17 @@
.env
.github/
node_modules/
dist/
*.log
.vscode/
.DS_Store
.idea/
.venv/
script/images
*.png
*.jpg
*.jpeg
*.sql
!backend/migrations/*.sql
*.vps
+41
View File
@@ -0,0 +1,41 @@
.PHONY: lint lint-be lint-fe fmt fmt-be fmt-fe check typecheck build
# ── Backend ──────────────────────────────────────────────────────────────────
lint-be:
cd backend && cargo clippy -- -D warnings
fmt-be:
cd backend && cargo fmt
fmt-be-check:
cd backend && cargo fmt -- --check
check-be:
cd backend && cargo check
# ── Frontend ─────────────────────────────────────────────────────────────────
lint-fe:
cd frontend && npm run lint
typecheck-fe:
cd frontend && npx tsc --noEmit
# ── Combined ─────────────────────────────────────────────────────────────────
lint: lint-be lint-fe
fmt: fmt-be
check: fmt-be-check lint-be check-be typecheck-fe lint-fe
# ── Build ────────────────────────────────────────────────────────────────────
build:
docker compose build
up:
docker compose up -d
down:
docker compose down
logs:
docker compose logs -f
+166
View File
@@ -0,0 +1,166 @@
# AT Transit — Full Stack
ระบบค้นเส้นทางรถโดยสาร / ตู้รถ / จุดจอด ภาคใต้
Postgres (PostGIS + JSONB) · SeaweedFS · Rust + Axum · Next.js · nginx
## เริ่มต้นใช้งานเร็วสุด
```bash
cd web-at-transit
cp .env.example .env # ตรวจ SQL_DB_PASSWORD ฯลฯ
docker compose up --build
```
ตัวอย่าง endpoint:
- หน้าเว็บ: <http://localhost:8000>
- API: <http://localhost:8000/api/route-groups>
- ไฟล์ที่อัปโหลด: <http://localhost:8000/files/...>
## Deploy บน Dokploy
ถ้า deploy ผ่าน Dokploy และแยก `backend` กับ `frontend` เป็นคนละ service:
- อย่าใช้โหมด `Docker Stack` / `Swarm`
- ให้ใช้ service แบบ `Dockerfile` หรือ `Image`
- backend ใช้ build context `backend/` และ Dockerfile `backend/Dockerfile`
- frontend ใช้ build context `frontend/` และ Dockerfile `frontend/Dockerfile`
สาเหตุของ error นี้:
```text
This node is not a swarm manager
```
คือ Dokploy กำลังพยายาม deploy แบบ Swarm (`docker stack` / `docker service`) แต่เครื่อง target ไม่ได้เปิด Swarm manager และ repo นี้ไม่ได้ต้องการ Swarm
### Backend service
ตั้งค่า internal port เป็น `8080`
env ที่ต้องมี:
```bash
SQL_DB_URL=postgres://itmeadmin:Admin%40Pass001%23%21@infra-postgres:5432/at-transit
STORAGE_URL=http://seaweed-filer:8888
STORAGE_BUCKET=transit
STORAGE_PUBLIC_BASE=/files
BIND_ADDR=0.0.0.0:8080
RUST_LOG=info,sqlx=warn,tower_http=info
CORS_ALLOW_ORIGINS=https://<your-frontend-domain>
SEED_ASSETS_DIR=/seed-assets
```
ถ้าจะ mount รูป seed ให้ mount path `storage/seed-assets` ไปที่ `/seed-assets` แบบ read-only
### Frontend service
ตั้งค่า internal port เป็น `3000`
build args / env ที่ต้องมี:
```bash
NEXT_PUBLIC_API_BASE=/api
NEXT_PUBLIC_FILE_BASE=/files
INTERNAL_API_BASE=http://<backend-service-name>:8080/api
BACKEND_INTERNAL_URL=http://<backend-service-name>:8080
STORAGE_INTERNAL_URL=http://seaweed-filer:8888
STORAGE_BUCKET_PATH=/buckets/transit
PORT=3000
```
ถ้ามี reverse proxy หน้า Dokploy ให้ route:
- `/api` ไป backend
- `/files` ไป backend
- `/` ไป frontend
## โครงสร้างโฟลเดอร์
```
app/
├─ docker-compose.yml 5 services: db, seaweedfs, backend, frontend, proxy
├─ nginx.conf reverse-proxy + /files cache 1 ปี
├─ backend/ Rust + Axum + SQLx (1 endpoint = 1 folder)
│ └─ src/api/<endpoint>/{mod,dto,repo,service,handler}.rs
├─ frontend/ Next.js App Router + react-leaflet
└─ storage/seed-assets/ วางรูปเพื่อ ingest ครั้งแรกอัตโนมัติ
```
## Backend ↔ Frontend แยกขาด
ทั้งสองฝั่งถูกแยก codebase, Dockerfile, และ env
และ "คุย" กันด้วย REST JSON ผ่าน nginx เท่านั้น
ไม่มีการแชร์โค้ดหรือ type ระหว่างกัน (frontend ประกาศ type ใน `src/lib/api.ts` ตาม contract)
## Endpoint Map (15 เส้น)
| Method | Path | Folder |
|--------|------|--------|
| GET | `/api/provinces` | `list_provinces` |
| GET | `/api/route-groups` | `list_route_groups` |
| GET | `/api/routes?group=&province=` | `list_routes` |
| GET | `/api/routes/:route_id` | `get_route` |
| GET | `/api/routes/:route_id/stops` | `list_route_stops` |
| GET | `/api/stops?bbox=&q=` | `list_stops` |
| GET | `/api/stops/:stop_code` | `get_stop` |
| GET | `/api/schedules?route_id=&stop_id=&stop_code=` | `list_schedules` |
| POST | `/api/images` (multipart) | `upload_image` |
| GET | `/api/images?entity_type=&entity_id=` | `list_images` |
| DELETE | `/api/images/:id` | `delete_image` |
| GET | `/files/*path` | `proxy_file` |
| POST | `/api/visits` | `record_visit` |
| GET | `/api/visits/summary` | `get_visits_summary` |
| GET | `/api/visits/by-page?path=&since=` | `get_visits_by_page` |
## JSONB Field Guide
| ตาราง | คอลัมน์ | ตัวอย่างคีย์ |
|------|--------|-------------|
| `routes` | `contact` | `phones[{label,number}]`, `email`, `line_id`, `office_hours` |
| `routes` | `metadata` | `headway_minutes`, `first_departure`, `last_departure`, `fare_baht`, `notes`, `tags[]` |
| `stations` | `attributes` | `has_ticketing`, `has_restroom`, `cover_type`, `landmark_note` |
| `stations` | `metadata` | `alias_names[]`, `nearest_landmark`, `accessibility` |
| `schedules` | `variants` | `weekday_only`, `weekend_only`, `holiday_only`, `notes` |
| `images` | `meta` | `mime`, `size_bytes`, `width`, `height`, `alt_th`, `sha256`, `pending_gc` |
| `sponsors` | `meta` | `description_th`, `tier`, `display_url` |
ทุกคอลัมน์ JSONB มี GIN `jsonb_path_ops` index สำหรับ `@>` / `@?` queries.
## วิธีอัปโหลดรูป
หนึ่ง multipart POST:
```bash
curl -X POST http://localhost:8000/api/images \
-F entity_type=route \
-F entity_id=SU01 \
-F kind=photo \
-F alt_th="รถตู้สาย SU01" \
-F display_order=0 \
-F file=@/path/to/photo.jpg
```
ระบบจะ:
1. ส่งไฟล์ไป SeaweedFS filer (`/buckets/transit/<entity_type>/<entity_id>/<filename>`)
2. ตรวจขนาดภาพด้วย crate `image` (width/height) และคำนวณ sha256
3. บันทึกแถวใน `transit.images` พร้อม metadata JSONB
หรือวางไฟล์ลง `storage/seed-assets/<entity_type>/<entity_id>/...`
แล้ว backend จะ ingest อัตโนมัติเมื่อ images ยังว่าง
## Flow Nodes (อ้างอิงตามจริงในโค้ด)
| โหนด | หน้า | การ action สำคัญ |
|------|------|--------------------|
| **N1** | `/` (Home) | คลิกการ์ดหมวด → `/routes?group=` · คลิกการ์ดจังหวัด → `/routes?province=` |
| **N2** | `/routes` (รายการเส้นทาง) | คลิกการ์ดเส้นทาง → `/routes/[routeId]` |
| **N3** | `/routes/[routeId]` | คลิก "ดูแบบขยาย" → `/routes/[routeId]/expanded` · คลิกชื่อจุดจอด → `/stops/[stopId]` |
| **N3b** | `/routes/[routeId]/expanded` | แกลเลอรีภาพ · เบอร์โทร · เมตาดาตา |
| **N4** | `/stops` (รายการจุดจอด + แผนที่) | popup marker → `/stops/[stopId]` · คลิกการ์ด → `/stops/[stopId]` |
| **N4b** | `/stops/[stopId]` | คลิกเส้นทาง → `/routes/[routeId]` |
ทุกหน้ายิง `POST /api/visits` ด้วย `visitor_id` UUID v4 ใน `localStorage`
## Image Flow Overview
ดูภาพรวมการไหลของหน้าและ action ทั้งหมดใน `flow-overview.md` (mermaid diagram)
+4
View File
@@ -0,0 +1,4 @@
target
.git
.gitignore
README.md
+14
View File
@@ -0,0 +1,14 @@
.env
.github/
node_modules/
dist/
*.log
.vscode/
.DS_Store
.idea/
.venv/
migrations/
*.png
*.jpg
*.jpeg
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "backend"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.7", features = ["multipart", "macros"] }
tokio = { version = "1", features = ["full"] }
tower = "0.5"
tower-http = { version = "0.6", features = ["cors", "trace"] }
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "json", "macros"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "serde"] }
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream", "multipart", "json"] }
anyhow = "1"
thiserror = "2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
dotenvy = "0.15"
sha2 = "0.10"
hex = "0.4"
mime = "0.3"
mime_guess = "2"
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
futures = "0.3"
bytes = "1"
walkdir = "2"
urlencoding = "2"
[profile.release]
strip = true
lto = false
codegen-units = 16
opt-level = 2
+15
View File
@@ -0,0 +1,15 @@
# syntax=docker/dockerfile:1.7
FROM rust:1.88-bookworm AS builder
WORKDIR /build
ENV CARGO_BUILD_JOBS=2
COPY Cargo.toml Cargo.lock* ./
RUN mkdir src && echo "fn main() {}" > src/main.rs && cargo build --release && rm -rf src
COPY . .
RUN touch src/main.rs && cargo build --release
FROM gcr.io/distroless/cc-debian12@sha256:aa0b7af67fa8211751ea6e00baa8373ba56cc1417ffc986ec9619bd0e1556b56
WORKDIR /app
COPY --from=builder /build/target/release/backend /app/backend
ENV BIND_ADDR=0.0.0.0:8080
EXPOSE 8080
CMD ["/app/backend"]
+1
View File
@@ -0,0 +1 @@
// no DTOs beyond path id
+18
View File
@@ -0,0 +1,18 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{
extract::{Path, State},
http::StatusCode,
routing::delete,
Router,
};
use uuid::Uuid;
pub fn route() -> Router<AppState> {
Router::new().route("/api/images/:id", delete(handler))
}
async fn handler(State(state): State<AppState>, Path(id): Path<Uuid>) -> AppResult<StatusCode> {
service::handle(&state, id).await?;
Ok(StatusCode::NO_CONTENT)
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+34
View File
@@ -0,0 +1,34 @@
use sqlx::PgPool;
use uuid::Uuid;
pub struct ImageRowMin {
pub fid: String,
pub url_path: String,
}
pub async fn fetch_min(pool: &PgPool, id: Uuid) -> Result<Option<ImageRowMin>, sqlx::Error> {
let row: Option<(String, String)> =
sqlx::query_as("SELECT fid, url_path FROM images WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await?;
Ok(row.map(|(fid, url_path)| ImageRowMin { fid, url_path }))
}
pub async fn delete(pool: &PgPool, id: Uuid) -> Result<u64, sqlx::Error> {
let r = sqlx::query("DELETE FROM images WHERE id = $1")
.bind(id)
.execute(pool)
.await?;
Ok(r.rows_affected())
}
pub async fn mark_pending_gc(pool: &PgPool, id: Uuid) -> Result<(), sqlx::Error> {
sqlx::query(
"UPDATE images SET meta = meta || '{\"pending_gc\":true}'::jsonb WHERE id = $1",
)
.bind(id)
.execute(pool)
.await?;
Ok(())
}
+25
View File
@@ -0,0 +1,25 @@
use super::repo;
use crate::{error::{AppError, AppResult}, state::AppState};
use uuid::Uuid;
pub async fn handle(state: &AppState, id: Uuid) -> AppResult<()> {
let Some(row) = repo::fetch_min(&state.db, id).await? else {
return Err(AppError::NotFound);
};
// strip public_base prefix to compute filer relative path
let rel = row
.url_path
.strip_prefix(state.public_base.as_str())
.unwrap_or(&row.url_path);
match state.seaweed.delete(rel).await {
Ok(()) => {
repo::delete(&state.db, id).await?;
Ok(())
}
Err(e) => {
tracing::warn!("filer delete failed for {id}: {e:?}; marking pending_gc");
repo::mark_pending_gc(&state.db, id).await?;
Err(AppError::Internal("storage delete failed".into()))
}
}
}
+16
View File
@@ -0,0 +1,16 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteDetail {
pub route_id: String,
pub name_th: String,
pub vehicle_type: String,
pub route_group_id: i16,
pub route_group_code: String,
pub route_group_label_th: String,
pub contact: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub province_ids: Vec<i16>,
pub images: SqlxJson<serde_json::Value>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes/:route_id", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(route_id): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let row = service::handle(&state, &route_id).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+31
View File
@@ -0,0 +1,31 @@
use super::dto::RouteDetail;
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool, route_id: &str) -> Result<Option<RouteDetail>, sqlx::Error> {
let sql = r#"
SELECT r.route_id,
r.name_th,
r.vehicle_type::text AS vehicle_type,
r.route_group_id,
g.code AS route_group_code,
g.label_th AS route_group_label_th,
r.contact,
r.metadata,
COALESCE(ARRAY(SELECT province_id FROM route_provinces rp WHERE rp.route_id = r.route_id ORDER BY province_id), '{}') AS province_ids,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'route' AND i.entity_id = r.route_id
), '[]'::jsonb) AS images
FROM routes r
JOIN route_groups g ON g.id = r.route_group_id
WHERE r.route_id = $1
"#;
sqlx::query_as::<_, RouteDetail>(sql)
.bind(route_id)
.fetch_optional(pool)
.await
}
+8
View File
@@ -0,0 +1,8 @@
use super::{dto::RouteDetail, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn handle(state: &AppState, route_id: &str) -> AppResult<RouteDetail> {
repo::fetch(&state.db, route_id)
.await?
.ok_or(AppError::NotFound)
}
+18
View File
@@ -0,0 +1,18 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct StopDetail {
pub id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub images: SqlxJson<serde_json::Value>,
pub routes: SqlxJson<serde_json::Value>,
pub lng: Option<f64>,
pub lat: Option<f64>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/stops/:stop_code", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(code): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let row = service::handle(&state, &code).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+38
View File
@@ -0,0 +1,38 @@
use super::dto::StopDetail;
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool, code: &str) -> Result<Option<StopDetail>, sqlx::Error> {
let sql = r#"
SELECT s.id, s.code, s.name_th, s.city_th, s.province_th,
s.station_type::text AS station_type,
s.attributes, s.metadata,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'station' AND i.entity_id = s.code
), '[]'::jsonb) AS images,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'route_id', r.route_id,
'name_th', r.name_th,
'vehicle_type', r.vehicle_type::text,
'route_group_code', g.code,
'route_group_label_th', g.label_th
) ORDER BY rs.stop_sequence, r.route_id)
FROM route_stops rs
JOIN routes r ON r.route_id = rs.route_id
JOIN route_groups g ON g.id = r.route_group_id
WHERE rs.station_id = s.id
), '[]'::jsonb) AS routes,
s.lng, s.lat
FROM stations s
WHERE s.code = $1
"#;
sqlx::query_as::<_, StopDetail>(sql)
.bind(code)
.fetch_optional(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::StopDetail, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn handle(state: &AppState, code: &str) -> AppResult<StopDetail> {
repo::fetch(&state.db, code).await?.ok_or(AppError::NotFound)
}
+15
View File
@@ -0,0 +1,15 @@
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
pub struct ByPageQuery {
pub path: String,
pub since: Option<NaiveDate>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct DailyPoint {
pub visit_date: NaiveDate,
pub total_visits: i64,
pub unique_visitors: i64,
}
@@ -0,0 +1,15 @@
use super::{dto::ByPageQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits/by-page", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ByPageQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "path": q.path, "series": rows })))
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
@@ -0,0 +1,18 @@
use super::dto::{ByPageQuery, DailyPoint};
use sqlx::PgPool;
pub async fn series(pool: &PgPool, q: &ByPageQuery) -> Result<Vec<DailyPoint>, sqlx::Error> {
sqlx::query_as::<_, DailyPoint>(
r#"
SELECT visit_date, total_visits, unique_visitors
FROM visit_daily_stats
WHERE page_path = $1
AND ($2::date IS NULL OR visit_date >= $2)
ORDER BY visit_date
"#,
)
.bind(&q.path)
.bind(q.since)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ByPageQuery) -> AppResult<Vec<DailyPoint>> {
Ok(repo::series(&state.db, q).await?)
}
+16
View File
@@ -0,0 +1,16 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct TopPage {
pub page_path: String,
pub total_visits: i64,
pub unique_visitors: i64,
}
#[derive(Debug, Serialize)]
pub struct VisitsSummary {
pub total_all_time: i64,
pub total_today: i64,
pub unique_today: i64,
pub top_pages: Vec<TopPage>,
}
@@ -0,0 +1,11 @@
use super::{dto::VisitsSummary, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits/summary", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<VisitsSummary>> {
Ok(Json(service::handle(&state).await?))
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
@@ -0,0 +1,24 @@
use super::dto::{TopPage, VisitsSummary};
use sqlx::PgPool;
pub async fn fetch(pool: &PgPool) -> Result<VisitsSummary, sqlx::Error> {
let (total_all_time,): (i64,) =
sqlx::query_as("SELECT total_all_time FROM visit_totals WHERE id = 1")
.fetch_one(pool)
.await?;
let today: Option<(i64, i64)> = sqlx::query_as(
"SELECT COALESCE(SUM(total_visits),0)::bigint, COALESCE(SUM(unique_visitors),0)::bigint \
FROM visit_daily_stats WHERE visit_date = CURRENT_DATE",
)
.fetch_optional(pool)
.await?;
let (total_today, unique_today) = today.unwrap_or((0, 0));
let top_pages = sqlx::query_as::<_, TopPage>(
"SELECT page_path, total_visits, unique_visitors \
FROM visit_daily_stats WHERE visit_date = CURRENT_DATE \
ORDER BY total_visits DESC LIMIT 10",
)
.fetch_all(pool)
.await?;
Ok(VisitsSummary { total_all_time, total_today, unique_today, top_pages })
}
@@ -0,0 +1,6 @@
use super::{dto::VisitsSummary, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState) -> AppResult<VisitsSummary> {
Ok(repo::fetch(&state.db).await?)
}
+7
View File
@@ -0,0 +1,7 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct ListImagesQuery {
pub entity_type: Option<String>,
pub entity_id: Option<String>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListImagesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/images", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListImagesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+19
View File
@@ -0,0 +1,19 @@
use super::dto::ListImagesQuery;
use crate::shared::ImageRef;
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListImagesQuery) -> Result<Vec<ImageRef>, sqlx::Error> {
sqlx::query_as::<_, ImageRef>(
r#"
SELECT id, entity_type, entity_id, kind, url_path, display_order, meta
FROM images
WHERE ($1::text IS NULL OR entity_type = $1)
AND ($2::text IS NULL OR entity_id = $2)
ORDER BY entity_type, entity_id, display_order, created_at
"#,
)
.bind(q.entity_type.as_deref())
.bind(q.entity_id.as_deref())
.fetch_all(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, shared::ImageRef, state::AppState};
pub async fn handle(state: &AppState, q: &ListImagesQuery) -> AppResult<Vec<ImageRef>> {
Ok(repo::list(&state.db, q).await?)
}
+7
View File
@@ -0,0 +1,7 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ProvinceRow {
pub id: i16,
pub name_th: String,
}
+13
View File
@@ -0,0 +1,13 @@
use super::service;
use crate::error::AppResult;
use crate::state::AppState;
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/provinces", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+10
View File
@@ -0,0 +1,10 @@
use super::dto::ProvinceRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool) -> Result<Vec<ProvinceRow>, sqlx::Error> {
sqlx::query_as::<_, ProvinceRow>(
"SELECT id, name_th FROM provinces ORDER BY id",
)
.fetch_all(pool)
.await
}
@@ -0,0 +1,7 @@
use super::{dto::ProvinceRow, repo};
use crate::error::AppResult;
use crate::state::AppState;
pub async fn handle(state: &AppState) -> AppResult<Vec<ProvinceRow>> {
Ok(repo::list(&state.db).await?)
}
+10
View File
@@ -0,0 +1,10 @@
use serde::Serialize;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteGroupRow {
pub id: i16,
pub code: String,
pub label_th: String,
pub display_order: i16,
pub is_active: bool,
}
@@ -0,0 +1,12 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/route-groups", get(handler))
}
async fn handler(State(state): State<AppState>) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+11
View File
@@ -0,0 +1,11 @@
use super::dto::RouteGroupRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool) -> Result<Vec<RouteGroupRow>, sqlx::Error> {
sqlx::query_as::<_, RouteGroupRow>(
"SELECT id, code, label_th, display_order, is_active \
FROM route_groups WHERE is_active ORDER BY display_order, id",
)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::RouteGroupRow, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState) -> AppResult<Vec<RouteGroupRow>> {
Ok(repo::list(&state.db).await?)
}
+14
View File
@@ -0,0 +1,14 @@
use serde::Serialize;
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteStopRow {
pub stop_sequence: i16,
pub station_id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
}
@@ -0,0 +1,15 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Path, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes/:route_id/stops", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(route_id): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &route_id).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+23
View File
@@ -0,0 +1,23 @@
use super::dto::RouteStopRow;
use sqlx::PgPool;
pub async fn list(pool: &PgPool, route_id: &str) -> Result<Vec<RouteStopRow>, sqlx::Error> {
let sql = r#"
SELECT rs.stop_sequence,
s.id AS station_id,
s.code,
s.name_th,
s.city_th,
s.province_th,
s.station_type::text AS station_type,
s.attributes
FROM route_stops rs
JOIN stations s ON s.id = rs.station_id
WHERE rs.route_id = $1
ORDER BY rs.stop_sequence
"#;
sqlx::query_as::<_, RouteStopRow>(sql)
.bind(route_id)
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::RouteStopRow, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, route_id: &str) -> AppResult<Vec<RouteStopRow>> {
Ok(repo::list(&state.db, route_id).await?)
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListRoutesQuery {
pub group: Option<String>,
pub province: Option<i16>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct RouteListRow {
pub route_id: String,
pub name_th: String,
pub vehicle_type: String,
pub route_group_id: i16,
pub route_group_code: String,
pub route_group_label_th: String,
pub contact: SqlxJson<serde_json::Value>,
pub metadata: SqlxJson<serde_json::Value>,
pub province_ids: Vec<i16>,
pub images: SqlxJson<serde_json::Value>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListRoutesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/routes", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListRoutesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+36
View File
@@ -0,0 +1,36 @@
use super::dto::{ListRoutesQuery, RouteListRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListRoutesQuery) -> Result<Vec<RouteListRow>, sqlx::Error> {
let sql = r#"
SELECT r.route_id,
r.name_th,
r.vehicle_type::text AS vehicle_type,
r.route_group_id,
g.code AS route_group_code,
g.label_th AS route_group_label_th,
r.contact,
r.metadata,
COALESCE(ARRAY(SELECT province_id FROM route_provinces rp WHERE rp.route_id = r.route_id ORDER BY province_id), '{}') AS province_ids,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'route' AND i.entity_id = r.route_id
), '[]'::jsonb) AS images
FROM routes r
JOIN route_groups g ON g.id = r.route_group_id
WHERE ($1::text IS NULL OR g.code = $1)
AND ($2::smallint IS NULL OR EXISTS (
SELECT 1 FROM route_provinces rp
WHERE rp.route_id = r.route_id AND rp.province_id = $2))
ORDER BY g.display_order, r.route_id
"#;
sqlx::query_as::<_, RouteListRow>(sql)
.bind(q.group.as_deref())
.bind(q.province)
.fetch_all(pool)
.await
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListRoutesQuery) -> AppResult<Vec<RouteListRow>> {
Ok(repo::list(&state.db, q).await?)
}
+22
View File
@@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListSchedulesQuery {
pub route_id: Option<String>,
pub stop_id: Option<i32>,
pub stop_code: Option<String>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ScheduleRow {
pub id: i32,
pub route_id: String,
pub station_id: i32,
pub station_code: String,
pub station_name_th: String,
pub direction_note: Option<String>,
pub departure_times: Vec<String>,
pub variants: SqlxJson<serde_json::Value>,
pub schedule_note: Option<String>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListSchedulesQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/schedules", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListSchedulesQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+28
View File
@@ -0,0 +1,28 @@
use super::dto::{ListSchedulesQuery, ScheduleRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListSchedulesQuery) -> Result<Vec<ScheduleRow>, sqlx::Error> {
let sql = r#"
SELECT sc.id,
sc.route_id,
sc.station_id,
s.code AS station_code,
s.name_th AS station_name_th,
sc.direction_note,
ARRAY(SELECT to_char(t, 'HH24:MI') FROM unnest(sc.departure_times) AS t) AS departure_times,
sc.variants,
sc.schedule_note
FROM schedules sc
JOIN stations s ON s.id = sc.station_id
WHERE ($1::text IS NULL OR sc.route_id = $1)
AND ($2::int IS NULL OR sc.station_id = $2)
AND ($3::text IS NULL OR s.code = $3)
ORDER BY sc.route_id, sc.station_id, sc.id
"#;
sqlx::query_as::<_, ScheduleRow>(sql)
.bind(q.route_id.as_deref())
.bind(q.stop_id)
.bind(q.stop_code.as_deref())
.fetch_all(pool)
.await
}
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListSchedulesQuery) -> AppResult<Vec<ScheduleRow>> {
Ok(repo::list(&state.db, q).await?)
}
+23
View File
@@ -0,0 +1,23 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
#[derive(Debug, Deserialize)]
pub struct ListStopsQuery {
/// "minLng,minLat,maxLng,maxLat"
pub bbox: Option<String>,
pub q: Option<String>,
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct StopRow {
pub id: i32,
pub code: String,
pub name_th: String,
pub city_th: Option<String>,
pub province_th: Option<String>,
pub station_type: String,
pub attributes: SqlxJson<serde_json::Value>,
pub images: SqlxJson<serde_json::Value>,
pub lng: Option<f64>,
pub lat: Option<f64>,
}
+15
View File
@@ -0,0 +1,15 @@
use super::{dto::ListStopsQuery, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::{Query, State}, routing::get, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/stops", get(handler))
}
async fn handler(
State(state): State<AppState>,
Query(q): Query<ListStopsQuery>,
) -> AppResult<Json<serde_json::Value>> {
let rows = service::handle(&state, &q).await?;
Ok(Json(serde_json::json!({ "items": rows })))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+39
View File
@@ -0,0 +1,39 @@
use super::dto::{ListStopsQuery, StopRow};
use sqlx::PgPool;
pub async fn list(pool: &PgPool, q: &ListStopsQuery) -> Result<Vec<StopRow>, sqlx::Error> {
let (min_lng, min_lat, max_lng, max_lat) = parse_bbox(q.bbox.as_deref());
let sql = r#"
SELECT s.id, s.code, s.name_th, s.city_th, s.province_th,
s.station_type::text AS station_type, s.attributes,
COALESCE((
SELECT jsonb_agg(jsonb_build_object(
'id', i.id, 'kind', i.kind, 'url_path', i.url_path,
'display_order', i.display_order, 'meta', i.meta
) ORDER BY i.display_order)
FROM images i
WHERE i.entity_type = 'station' AND i.entity_id = s.code
), '[]'::jsonb) AS images,
s.lng, s.lat
FROM stations s
WHERE ($1::float8 IS NULL OR s.lng IS NULL OR (s.lng BETWEEN $1 AND $3 AND s.lat BETWEEN $2 AND $4))
AND ($5::text IS NULL OR s.name_th ILIKE '%' || $5 || '%')
ORDER BY s.id
"#;
sqlx::query_as::<_, StopRow>(sql)
.bind(min_lng)
.bind(min_lat)
.bind(max_lng)
.bind(max_lat)
.bind(q.q.as_deref())
.fetch_all(pool)
.await
}
fn parse_bbox(s: Option<&str>) -> (Option<f64>, Option<f64>, Option<f64>, Option<f64>) {
let Some(s) = s else { return (None, None, None, None); };
let parts: Vec<_> = s.split(',').collect();
if parts.len() != 4 { return (None, None, None, None); }
let p: Vec<Option<f64>> = parts.iter().map(|x| x.trim().parse().ok()).collect();
(p[0], p[1], p[2], p[3])
}
+6
View File
@@ -0,0 +1,6 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, q: &ListStopsQuery) -> AppResult<Vec<StopRow>> {
Ok(repo::list(&state.db, q).await?)
}
+37
View File
@@ -0,0 +1,37 @@
use crate::state::AppState;
use axum::Router;
pub mod list_provinces;
pub mod list_route_groups;
pub mod list_routes;
pub mod get_route;
pub mod list_route_stops;
pub mod list_stops;
pub mod get_stop;
pub mod list_schedules;
pub mod upload_image;
pub mod list_images;
pub mod delete_image;
pub mod proxy_file;
pub mod record_visit;
pub mod get_visits_summary;
pub mod get_visits_by_page;
pub fn router() -> Router<AppState> {
Router::new()
.merge(list_provinces::route())
.merge(list_route_groups::route())
.merge(list_routes::route())
.merge(get_route::route())
.merge(list_route_stops::route())
.merge(list_stops::route())
.merge(get_stop::route())
.merge(list_schedules::route())
.merge(upload_image::route())
.merge(list_images::route())
.merge(delete_image::route())
.merge(proxy_file::route())
.merge(record_visit::route())
.merge(get_visits_summary::route())
.merge(get_visits_by_page::route())
}
+29
View File
@@ -0,0 +1,29 @@
use super::service;
use crate::{error::AppResult, state::AppState};
use axum::{
extract::{Path, State},
http::{header, HeaderMap, HeaderValue},
response::IntoResponse,
routing::get,
Router,
};
pub fn route() -> Router<AppState> {
Router::new().route("/files/*path", get(handler))
}
async fn handler(
State(state): State<AppState>,
Path(path): Path<String>,
) -> AppResult<impl IntoResponse> {
let (bytes, mime) = service::fetch(&state, &path).await?;
let mut h = HeaderMap::new();
if let Ok(v) = HeaderValue::from_str(&mime) {
h.insert(header::CONTENT_TYPE, v);
}
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
Ok((h, bytes))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod handler;
pub mod service;
pub use handler::route;
pub mod dto { /* empty */ }
pub mod repo { /* empty */ }
+9
View File
@@ -0,0 +1,9 @@
use crate::{error::{AppError, AppResult}, state::AppState};
pub async fn fetch(state: &AppState, path: &str) -> AppResult<(bytes::Bytes, String)> {
state
.seaweed
.fetch(&format!("/{}", path.trim_start_matches('/')))
.await
.map_err(|e| AppError::Internal(e.to_string()))
}
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub struct RecordVisitBody {
pub page_path: String,
pub visitor_id: Uuid,
}
#[derive(Debug, Serialize)]
pub struct RecordVisitResp {
pub counted: bool,
pub unique_today: bool,
}
+14
View File
@@ -0,0 +1,14 @@
use super::{dto::*, service};
use crate::{error::AppResult, state::AppState};
use axum::{extract::State, routing::post, Json, Router};
pub fn route() -> Router<AppState> {
Router::new().route("/api/visits", post(handler))
}
async fn handler(
State(state): State<AppState>,
Json(body): Json<RecordVisitBody>,
) -> AppResult<Json<RecordVisitResp>> {
Ok(Json(service::handle(&state, body).await?))
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+41
View File
@@ -0,0 +1,41 @@
use sqlx::PgPool;
use uuid::Uuid;
pub async fn record(pool: &PgPool, visitor_id: Uuid, page_path: &str) -> Result<bool, sqlx::Error> {
let mut tx = pool.begin().await?;
// returns true when newly inserted (unique today)
let row: Option<(bool,)> = sqlx::query_as(
r#"
INSERT INTO visitor_seen (visitor_id, page_path, visit_date)
VALUES ($1, $2, CURRENT_DATE)
ON CONFLICT DO NOTHING
RETURNING (xmax = 0) AS is_new
"#,
)
.bind(visitor_id)
.bind(page_path)
.fetch_optional(&mut *tx)
.await?;
let is_new = row.map(|(b,)| b).unwrap_or(false);
sqlx::query(
r#"
INSERT INTO visit_daily_stats (visit_date, page_path, total_visits, unique_visitors)
VALUES (CURRENT_DATE, $1, 1, $2::bigint)
ON CONFLICT (visit_date, page_path) DO UPDATE
SET total_visits = visit_daily_stats.total_visits + 1,
unique_visitors = visit_daily_stats.unique_visitors + EXCLUDED.unique_visitors
"#,
)
.bind(page_path)
.bind(if is_new { 1i64 } else { 0i64 })
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE visit_totals SET total_all_time = total_all_time + 1 WHERE id = 1")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(is_new)
}
+7
View File
@@ -0,0 +1,7 @@
use super::{dto::*, repo};
use crate::{error::AppResult, state::AppState};
pub async fn handle(state: &AppState, body: RecordVisitBody) -> AppResult<RecordVisitResp> {
let is_new = repo::record(&state.db, body.visitor_id, &body.page_path).await?;
Ok(RecordVisitResp { counted: true, unique_today: is_new })
}
+27
View File
@@ -0,0 +1,27 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
use uuid::Uuid;
#[derive(Debug, Deserialize)]
pub struct UploadForm {
pub entity_type: String,
pub entity_id: String,
#[serde(default = "default_kind")]
pub kind: String,
pub alt_th: Option<String>,
#[serde(default)]
pub display_order: i16,
}
fn default_kind() -> String { "photo".into() }
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct CreatedImage {
pub id: Uuid,
pub entity_type: String,
pub entity_id: String,
pub kind: String,
pub url_path: String,
pub display_order: i16,
pub meta: SqlxJson<serde_json::Value>,
}
+64
View File
@@ -0,0 +1,64 @@
use super::{dto::*, service};
use crate::{error::{AppError, AppResult}, state::AppState};
use axum::{extract::{Multipart, State}, routing::post, Json, Router};
use bytes::Bytes;
pub fn route() -> Router<AppState> {
Router::new().route("/api/images", post(handler))
}
async fn handler(
State(state): State<AppState>,
mut mp: Multipart,
) -> AppResult<Json<serde_json::Value>> {
let mut entity_type: Option<String> = None;
let mut entity_id: Option<String> = None;
let mut kind: Option<String> = None;
let mut alt_th: Option<String> = None;
let mut display_order: i16 = 0;
let mut filename: Option<String> = None;
let mut mime: Option<String> = None;
let mut bytes: Option<Bytes> = None;
while let Some(field) = mp
.next_field()
.await
.map_err(|e| AppError::BadRequest(e.to_string()))?
{
match field.name().unwrap_or("") {
"entity_type" => entity_type = Some(field.text().await.map_err(io)?),
"entity_id" => entity_id = Some(field.text().await.map_err(io)?),
"kind" => kind = Some(field.text().await.map_err(io)?),
"alt_th" => alt_th = Some(field.text().await.map_err(io)?),
"display_order" => {
display_order = field.text().await.map_err(io)?.parse().unwrap_or(0)
}
"file" => {
filename = field.file_name().map(|s| s.to_string());
mime = field.content_type().map(|s| s.to_string());
bytes = Some(field.bytes().await.map_err(io)?);
}
_ => {}
}
}
let form = UploadForm {
entity_type: entity_type.ok_or_else(|| AppError::BadRequest("entity_type".into()))?,
entity_id: entity_id.ok_or_else(|| AppError::BadRequest("entity_id".into()))?,
kind: kind.unwrap_or_else(|| "photo".into()),
alt_th,
display_order,
};
let input = service::UploadInput {
form,
filename: filename.unwrap_or_else(|| "upload.bin".into()),
mime: mime.unwrap_or_else(|| "application/octet-stream".into()),
bytes: bytes.ok_or_else(|| AppError::BadRequest("file missing".into()))?,
};
let row = service::upload(&state, input).await?;
Ok(Json(serde_json::to_value(row).unwrap()))
}
fn io(e: axum::extract::multipart::MultipartError) -> AppError {
AppError::BadRequest(e.to_string())
}
+5
View File
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handler;
pub mod repo;
pub mod service;
pub use handler::route;
+54
View File
@@ -0,0 +1,54 @@
use super::dto::CreatedImage;
use sqlx::PgPool;
use uuid::Uuid;
pub async fn insert(
pool: &PgPool,
entity_type: &str,
entity_id: &str,
kind: &str,
fid: &str,
url_path: &str,
display_order: i16,
meta: &serde_json::Value,
) -> Result<CreatedImage, sqlx::Error> {
sqlx::query_as::<_, CreatedImage>(
r#"
INSERT INTO images (entity_type, entity_id, kind, fid, url_path, display_order, meta)
VALUES ($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT (fid) DO UPDATE
SET entity_type = EXCLUDED.entity_type,
entity_id = EXCLUDED.entity_id,
kind = EXCLUDED.kind,
url_path = EXCLUDED.url_path,
display_order = EXCLUDED.display_order,
meta = EXCLUDED.meta
RETURNING id, entity_type, entity_id, kind, url_path, display_order, meta
"#,
)
.bind(entity_type)
.bind(entity_id)
.bind(kind)
.bind(fid)
.bind(url_path)
.bind(display_order)
.bind(meta)
.fetch_one(pool)
.await
}
pub async fn count(pool: &PgPool) -> Result<i64, sqlx::Error> {
let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM images")
.fetch_one(pool)
.await?;
Ok(n)
}
pub async fn exists_fid(pool: &PgPool, fid: &str) -> Result<bool, sqlx::Error> {
let row: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM images WHERE fid = $1")
.bind(fid)
.fetch_optional(pool)
.await?;
Ok(row.is_some())
}
+136
View File
@@ -0,0 +1,136 @@
use super::{dto::*, repo};
use crate::{error::{AppError, AppResult}, state::AppState};
use bytes::Bytes;
use sha2::{Digest, Sha256};
use std::path::Path;
pub struct UploadInput {
pub form: UploadForm,
pub filename: String,
pub mime: String,
pub bytes: Bytes,
}
pub async fn upload(state: &AppState, input: UploadInput) -> AppResult<CreatedImage> {
validate_entity_type(&input.form.entity_type)?;
validate_kind(&input.form.kind)?;
if input.bytes.is_empty() {
return Err(AppError::BadRequest("empty file".into()));
}
let (w, h) = probe_dimensions(&input.bytes);
let sha = hex::encode(Sha256::digest(&input.bytes));
let size = input.bytes.len() as i64;
let stored = state
.seaweed
.upload(
&input.form.entity_type,
&input.form.entity_id,
&input.filename,
&input.mime,
input.bytes,
)
.await
.map_err(|e| AppError::Internal(e.to_string()))?;
let meta = serde_json::json!({
"mime": input.mime,
"size_bytes": size,
"width": w,
"height": h,
"alt_th": input.form.alt_th,
"sha256": sha,
});
let row = repo::insert(
&state.db,
&input.form.entity_type,
&input.form.entity_id,
&input.form.kind,
&stored.fid,
&format!("{}{}", state.public_base, stored.url_path),
input.form.display_order,
&meta,
)
.await?;
Ok(row)
}
fn validate_entity_type(t: &str) -> AppResult<()> {
match t {
"route" | "station" | "sponsor" | "province" | "bus" | "misc" => Ok(()),
_ => Err(AppError::BadRequest("invalid entity_type".into())),
}
}
fn validate_kind(k: &str) -> AppResult<()> {
match k {
"photo" | "logo" | "icon" | "map" | "hero" => Ok(()),
_ => Err(AppError::BadRequest("invalid kind".into())),
}
}
fn probe_dimensions(bytes: &[u8]) -> (Option<u32>, Option<u32>) {
match image::load_from_memory(bytes) {
Ok(img) => (Some(img.width()), Some(img.height())),
Err(_) => (None, None),
}
}
/// Walk `dir/<entity_type>/<entity_id>/*.{jpg,png,webp}` and ingest each file
/// once. Skips files whose sha256 already lives in `images` (matched
/// by fid path).
pub async fn ingest_seed_dir(state: &AppState, dir: &str) -> AppResult<()> {
if repo::count(&state.db).await? > 0 {
tracing::info!("seed-assets: images table already populated, skipping");
return Ok(());
}
let base = Path::new(dir);
if !base.exists() {
tracing::warn!("seed-assets dir not found: {dir}");
return Ok(());
}
let mut count = 0;
for entry in walkdir::WalkDir::new(base).min_depth(3).max_depth(3) {
let entry = match entry { Ok(e) => e, Err(_) => continue };
if !entry.file_type().is_file() { continue; }
let path = entry.path();
let rel = match path.strip_prefix(base) { Ok(p) => p, Err(_) => continue };
let mut comps = rel.components();
let Some(et) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(eid) = comps.next().and_then(|c| c.as_os_str().to_str()) else { continue };
let Some(fname) = path.file_name().and_then(|s| s.to_str()) else { continue };
let mime = mime_guess::from_path(path).first_or_octet_stream().to_string();
let bytes = match tokio::fs::read(path).await {
Ok(b) => Bytes::from(b),
Err(e) => { tracing::warn!("read {path:?}: {e}"); continue }
};
let candidate_fid = format!("/{}/{}/{}", et, eid, fname);
if repo::exists_fid(&state.db, &candidate_fid).await.unwrap_or(false) {
continue;
}
let res = upload(
state,
UploadInput {
form: UploadForm {
entity_type: et.into(),
entity_id: eid.into(),
kind: "photo".into(),
alt_th: None,
display_order: 0,
},
filename: fname.into(),
mime,
bytes,
},
)
.await;
match res {
Ok(_) => count += 1,
Err(e) => tracing::warn!("ingest {path:?} failed: {e:?}"),
}
}
tracing::info!("seed-assets ingested {count} files from {dir}");
Ok(())
}
+34
View File
@@ -0,0 +1,34 @@
use std::env;
#[derive(Clone, Debug)]
pub struct Config {
pub database_url: String,
pub storage_url: String,
pub storage_public_base: String,
pub bind_addr: String,
pub cors_origins: Vec<String>,
pub seed_assets_dir: Option<String>,
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
let _ = dotenvy::dotenv();
Ok(Self {
database_url: env::var("SQL_DB_URL").or_else(|_| env::var("DATABASE_URL"))?,
storage_url: env::var("STORAGE_URL")
.or_else(|_| env::var("SEAWEED_FILER_URL"))
.unwrap_or_else(|_| "http://localhost:8888".into()),
storage_public_base: env::var("STORAGE_PUBLIC_BASE")
.or_else(|_| env::var("SEAWEED_PUBLIC_BASE"))
.unwrap_or_else(|_| "/files".into()),
bind_addr: env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:8080".into()),
cors_origins: env::var("CORS_ORIGINS")
.unwrap_or_else(|_| "http://localhost:3000".into())
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
seed_assets_dir: env::var("SEED_ASSETS_DIR").ok(),
})
}
}
+43
View File
@@ -0,0 +1,43 @@
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
fn normalize_database_url(raw: &str) -> String {
let Some(scheme_pos) = raw.find("://") else {
return raw.to_string();
};
let (scheme, rest) = raw.split_at(scheme_pos + 3);
let Some(at_pos) = rest.rfind('@') else {
return raw.to_string();
};
let (userinfo, hostpart) = rest.split_at(at_pos);
let hostpart = &hostpart[1..];
if !userinfo.contains('@') && !userinfo.contains('#') {
return raw.to_string();
}
let Some(colon_pos) = userinfo.find(':') else {
return raw.to_string();
};
let username = &userinfo[..colon_pos];
let password = &userinfo[colon_pos + 1..];
format!(
"{scheme}{}:{}@{hostpart}",
urlencoding::encode(username),
urlencoding::encode(password)
)
}
pub async fn connect(url: &str) -> anyhow::Result<PgPool> {
let url = normalize_database_url(url);
let pool = PgPoolOptions::new()
.max_connections(16)
.acquire_timeout(std::time::Duration::from_secs(10))
.connect(&url)
.await?;
Ok(pool)
}
+44
View File
@@ -0,0 +1,44 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("not found")]
NotFound,
#[error("bad request: {0}")]
BadRequest(String),
#[error(transparent)]
Sqlx(#[from] sqlx::Error),
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Anyhow(#[from] anyhow::Error),
#[error("internal: {0}")]
Internal(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (code, msg) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "not_found".to_string()),
AppError::BadRequest(m) => (StatusCode::BAD_REQUEST, m.clone()),
AppError::Sqlx(sqlx::Error::RowNotFound) => {
(StatusCode::NOT_FOUND, "not_found".to_string())
}
_ => {
tracing::error!("internal: {self:?}");
(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error".to_string(),
)
}
};
(code, Json(json!({ "error": msg }))).into_response()
}
}
pub type AppResult<T> = Result<T, AppError>;
+69
View File
@@ -0,0 +1,69 @@
mod api;
mod config;
mod db;
mod error;
mod shared;
mod state;
mod storage;
use axum::http::{HeaderValue, Method};
use std::sync::Arc;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.json()
.with_ansi(false)
.flatten_event(true)
.with_current_span(true)
.with_span_list(true)
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let cfg = config::Config::from_env()?;
tracing::info!("config loaded: bind={}", cfg.bind_addr);
let pool = db::connect(&cfg.database_url).await?;
let storage = Arc::new(storage::seaweed::SeaweedClient::new(cfg.storage_url.clone()));
let state = state::AppState {
db: pool.clone(),
seaweed: storage.clone(),
public_base: cfg.storage_public_base.clone(),
};
// Optional: ingest seed assets if images table empty
if let Some(dir) = cfg.seed_assets_dir.clone() {
let s = state.clone();
tokio::spawn(async move {
if let Err(e) = api::upload_image::service::ingest_seed_dir(&s, &dir).await {
tracing::warn!("seed-assets ingest skipped: {e:?}");
}
});
}
let cors_origins: Vec<HeaderValue> = cfg
.cors_origins
.iter()
.filter_map(|o| o.parse::<HeaderValue>().ok())
.collect();
let cors = CorsLayer::new()
.allow_origin(cors_origins)
.allow_methods([Method::GET, Method::POST, Method::DELETE, Method::OPTIONS])
.allow_headers([axum::http::header::CONTENT_TYPE, axum::http::header::AUTHORIZATION])
.allow_credentials(false);
let app = axum::Router::new()
.merge(api::router())
.layer(TraceLayer::new_for_http())
.layer(cors)
.with_state(state);
let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?;
tracing::info!("listening on {}", cfg.bind_addr);
axum::serve(listener, app).await?;
Ok(())
}
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
use sqlx::types::Json as SqlxJson;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct ImageRef {
pub id: Uuid,
pub entity_type: String,
pub entity_id: String,
pub kind: String,
pub url_path: String,
pub display_order: i16,
pub meta: SqlxJson<serde_json::Value>,
}
+10
View File
@@ -0,0 +1,10 @@
use crate::storage::seaweed::SeaweedClient;
use sqlx::PgPool;
use std::sync::Arc;
#[derive(Clone)]
pub struct AppState {
pub db: PgPool,
pub seaweed: Arc<SeaweedClient>,
pub public_base: String,
}
+1
View File
@@ -0,0 +1 @@
pub mod seaweed;
+126
View File
@@ -0,0 +1,126 @@
use bytes::Bytes;
use reqwest::Client;
use serde::Deserialize;
#[derive(Debug, Clone)]
pub struct SeaweedClient {
pub filer_url: String,
pub http: Client,
}
#[derive(Debug, Deserialize)]
pub struct UploadResult {
#[serde(default)]
pub fid: String,
#[serde(default)]
pub size: u64,
#[serde(default)]
pub mime: Option<String>,
pub name: Option<String>,
}
#[derive(Debug)]
pub struct StoredObject {
pub fid: String,
pub url_path: String,
pub size: u64,
pub mime: String,
}
impl SeaweedClient {
pub fn new(filer_url: impl Into<String>) -> Self {
Self {
filer_url: filer_url.into(),
http: Client::builder()
.timeout(std::time::Duration::from_secs(60))
.build()
.expect("reqwest client"),
}
}
/// PUT bytes to `/buckets/transit/<entity_type>/<entity_id>/<filename>`.
/// Returns the relative public path under SEAWEED_PUBLIC_BASE (without prefix).
pub async fn upload(
&self,
entity_type: &str,
entity_id: &str,
filename: &str,
mime: &str,
bytes: Bytes,
) -> anyhow::Result<StoredObject> {
let safe_name = sanitize_filename(filename);
let key = format!(
"/buckets/transit/{}/{}/{}",
sanitize_segment(entity_type),
sanitize_segment(entity_id),
safe_name
);
let url = format!("{}{}", self.filer_url, key);
let size = bytes.len() as u64;
let resp = self
.http
.put(&url)
.header(reqwest::header::CONTENT_TYPE, mime)
.body(bytes)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("filer upload failed: {} {}", resp.status(), resp.text().await.unwrap_or_default());
}
let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
let fid = body
.get("fid")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
.unwrap_or_else(|| key.clone());
Ok(StoredObject {
fid,
url_path: key.trim_start_matches("/buckets/transit").to_string(),
size,
mime: mime.to_string(),
})
}
pub async fn delete(&self, url_path: &str) -> anyhow::Result<()> {
let url = format!("{}/buckets/transit{}", self.filer_url, url_path);
let resp = self.http.delete(&url).send().await?;
if !resp.status().is_success() && resp.status() != reqwest::StatusCode::NOT_FOUND {
anyhow::bail!("filer delete failed: {}", resp.status());
}
Ok(())
}
pub async fn fetch(&self, url_path: &str) -> anyhow::Result<(Bytes, String)> {
let url = format!("{}/buckets/transit{}", self.filer_url, url_path);
let resp = self.http.get(&url).send().await?;
if !resp.status().is_success() {
anyhow::bail!("filer fetch failed: {}", resp.status());
}
let mime = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
let bytes = resp.bytes().await?;
Ok((bytes, mime))
}
}
fn sanitize_segment(s: &str) -> String {
s.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
.collect()
}
fn sanitize_filename(s: &str) -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'_'
}
})
.collect()
}
+59
View File
@@ -0,0 +1,59 @@
name: at-transit
networks:
internal-network:
external: true
services:
backend:
build:
context: ./backend
image: at-transit-backend:latest
container_name: at-transit-backend
restart: unless-stopped
networks:
- internal-network
extra_hosts:
- "host-gateway:host-gateway"
env_file:
- .env.at-transit
environment:
STORAGE_BUCKET: transit
STORAGE_PUBLIC_BASE: /files
BIND_ADDR: 0.0.0.0:${BACKEND_PORT}
RUST_LOG: info,sqlx=warn,tower_http=info
CORS_ALLOW_ORIGINS: "*"
SEED_ASSETS_DIR: /seed-assets
volumes:
- ./storage/seed-assets:/seed-assets:ro
ports:
- "${BACKEND_PORT}:${BACKEND_PORT}"
frontend:
build:
context: ./frontend
args:
NEXT_PUBLIC_API_BASE: /api
NEXT_PUBLIC_FILES_BASE: /files
BACKEND_INTERNAL_URL: http://at-transit-backend:${BACKEND_PORT}
INTERNAL_API_BASE: http://at-transit-backend:${BACKEND_PORT}/api
STORAGE_INTERNAL_URL: ${STORAGE_URL}
STORAGE_BUCKET_PATH: /buckets/transit
image: at-transit-frontend:latest
container_name: at-transit-frontend
restart: unless-stopped
networks:
- internal-network
extra_hosts:
- "host-gateway:host-gateway"
environment:
NEXT_PUBLIC_API_BASE: /api
NEXT_PUBLIC_FILES_BASE: /files
HOSTNAME: 0.0.0.0
INTERNAL_API_BASE: http://at-transit-backend:${BACKEND_PORT}/api
BACKEND_INTERNAL_URL: http://at-transit-backend:${BACKEND_PORT}
STORAGE_INTERNAL_URL: ${STORAGE_URL}
STORAGE_BUCKET_PATH: /buckets/transit
PORT: 3000
ports:
- "${FRONTEND_PORT}:3000"
+6
View File
@@ -0,0 +1,6 @@
node_modules
.next
npm-debug.log*
.git
.gitignore
README.md
+4
View File
@@ -0,0 +1,4 @@
node_modules
.next
.env.local
*.log
+37
View File
@@ -0,0 +1,37 @@
# syntax=docker/dockerfile:1.7
FROM node:20-alpine AS deps
WORKDIR /app
ARG NEXT_PUBLIC_API_BASE=/api
ARG NEXT_PUBLIC_FILES_BASE=/files
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
FROM node:20-alpine AS build
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
ARG NEXT_PUBLIC_API_BASE=/api
ARG NEXT_PUBLIC_FILES_BASE=/files
ARG BACKEND_INTERNAL_URL=http://localhost:20001
ARG INTERNAL_API_BASE=http://localhost:20001/api
ARG STORAGE_INTERNAL_URL=http://localhost:3103
ARG STORAGE_BUCKET_PATH=/buckets/transit
ENV NEXT_PUBLIC_API_BASE=$NEXT_PUBLIC_API_BASE
ENV NEXT_PUBLIC_FILES_BASE=$NEXT_PUBLIC_FILES_BASE
ENV BACKEND_INTERNAL_URL=$BACKEND_INTERNAL_URL
ENV INTERNAL_API_BASE=$INTERNAL_API_BASE
ENV STORAGE_INTERNAL_URL=$STORAGE_INTERNAL_URL
ENV STORAGE_BUCKET_PATH=$STORAGE_BUCKET_PATH
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV HOSTNAME=0.0.0.0
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
+8
View File
@@ -0,0 +1,8 @@
# Frontend — Next.js App Router
```bash
npm install
npm run dev
```
Talks to backend purely via REST through nginx (`/api/*`, `/files/*`).
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+28
View File
@@ -0,0 +1,28 @@
/** @type {import('next').NextConfig} */
const BACKEND_INTERNAL_URL =
process.env.BACKEND_INTERNAL_URL || "http://localhost:20001";
const STORAGE_INTERNAL_URL =
process.env.STORAGE_INTERNAL_URL || process.env.FILER_INTERNAL_URL || "http://localhost:3103";
const STORAGE_BUCKET_PATH =
process.env.STORAGE_BUCKET_PATH || process.env.FILER_BUCKET_PATH || "/buckets/transit";
const nextConfig = {
reactStrictMode: true,
output: "standalone",
images: {
remotePatterns: [{ protocol: "http", hostname: "**" }, { protocol: "https", hostname: "**" }]
},
async rewrites() {
return [
{
source: "/files/:path*",
destination: `${STORAGE_INTERNAL_URL}${STORAGE_BUCKET_PATH}/:path*`
},
{
source: "/api/:path*",
destination: `${BACKEND_INTERNAL_URL}/api/:path*`
}
];
}
};
export default nextConfig;
+5853
View File
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint"
},
"dependencies": {
"leaflet": "^1.9.4",
"next": "^16.2.6",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-leaflet": "^4.2.1",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/leaflet": "^1.9.12",
"@types/node": "^20.14.10",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/uuid": "^9.0.8",
"eslint": "^8.57.0",
"eslint-config-next": "^14.2.5",
"typescript": "^5.5.4"
}
}
+1
View File
@@ -0,0 +1 @@
// Minimal placeholder so `public/` exists for the Dockerfile copy step.
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more