- Rust 75.2%
- Vue 11.5%
- TypeScript 11.1%
- Just 1.1%
- SurrealQL 0.7%
- Other 0.4%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| frontend | ||
| handler-macros | ||
| src | ||
| .gitignore | ||
| build.rs | ||
| Cargo.lock | ||
| Cargo.toml | ||
| justfile | ||
| README.md | ||
tavern-arch
A full-stack Rust + Vue 3 service template designed for maximum end-to-end type safety and single-binary deployment:
- Embedded Database (
surrealdb+kv-rocksdb): Runs in-process and stores data on disk (--db-path), with idempotent schema setup (src/schema.surql) and compile-time checked deserialization viaSurrealValue. - Auto-Registered Typed RPC (
handler-macros+src/server/): Endpoints annotated with#[handler(GET/POST "/api/...")]self-register at startup, dependency-inject database/bus/auth guards from their function signature (HandlerProvide<T>), and export a nested TypeScript client (frontend/src/lib/backendBindings.ts). - Typed Real-Time WebSockets (
src/bus.rs+src/ws.rs): In-memory pub/sub bus and presence tracker exposed over/ws, withServerEventandClientEventenums exported directly to TypeScript alongside HTTP bindings. - Single-Binary Output (
rust-embed+build.rs):just buildsyncs TypeScript bindings, typechecks and bundles the Vue 3 + Tailwind v4 SPA (frontend/dist), and embeds it into the release binary.
Project Layout
.
├── Cargo.toml # Workspace root (binary + handler-macros)
├── build.rs # Runs `pnpm --dir frontend build` on release builds
├── justfile # Common dev, typecheck, and build recipes
├── handler-macros/ # Proc macros: #[handler], #[input], #[output]
├── src/
│ ├── main.rs # CLI (`server`, `export-ts`, `create-user`)
│ ├── schema.surql # Idempotent SurrealQL table & index definitions
│ ├── db.rs # Surreal<Db> connection, Sequence helper, DB provider
│ ├── auth.rs # User accounts, SurrealDB session store, auth guards
│ ├── bus.rs # In-memory pub/sub Bus and online Presence tracker
│ ├── ws.rs # Typed WebSocket upgrade & ServerEvent / ClientEvent
│ ├── server/ # Router, HandlerInput/Output, TsApiCollector, SPA fallback
│ └── handlers/ # HTTP RPC endpoint modules (auth, health, notices)
└── frontend/
├── vite.config.ts # Proxies `/api` and `/ws` to 127.0.0.1:8080 in dev
└── src/
├── lib/
│ ├── backendBindings.ts # GENERATED by `just push-bindings` (do not edit)
│ ├── backend.ts # `backend` RPC client + `FrameworkError`
│ └── session.ts # Reactive auth state + WebSocket connection
├── components/ # Vue 3 `<script setup lang="ts">` components
└── App.vue
Quickstart & Commands
# 1. Install frontend dependencies (once)
pnpm --dir frontend install
# 2. Create an initial user account (roles: `gm` or `player`)
just create-user karczmarz secret123 gm
# 3. Sync TS bindings, build the frontend, and start the server on 127.0.0.1:8080
just serve
# 4. Run full-stack typechecks (Rust + vue-tsc + Vite build check)
just typecheck
# 5. Produce a self-contained single binary at ./target/release/tavern-arch
just build
For hot-reloading frontend work during development, run cargo run -- server in one terminal and pnpm --dir frontend dev in another (Vite proxies /api and /ws to http://127.0.0.1:8080).
How to Implement a New Feature
Step 1: Define the Database Schema (src/schema.surql)
src/schema.surql is executed every time the database opens (db::connect), so all statements must be idempotent (IF NOT EXISTS):
DEFINE TABLE IF NOT EXISTS quest SCHEMALESS;
DEFINE INDEX IF NOT EXISTS quest_status ON quest FIELDS status;
Modeling Records in Rust (SurrealValue + #[output])
- Separate storage-only fields from wire types when needed:
- If a record has fields that should not go to the client (like
password_hashonStoredUser), define a private struct with#[derive(Debug, Clone, SurrealValue)]for.create()/.select(). - If a struct is both read from SurrealDB and returned to the frontend (like
NoticeorUserInfo), stack#[output]and#[derive(Debug, Clone, SurrealValue)]on the same struct:use handler_macros::output; use surrealdb::types::SurrealValue; #[output] #[derive(Debug, Clone, SurrealValue)] pub struct Quest { pub id: String, pub title: String, pub reward_gold: i64, pub created_at: i64, }
- If a record has fields that should not go to the client (like
- Projecting Record IDs:
- SurrealDB's native
RecordIdtype does not implementts_rs::TS. Project the key out in SurrealQL usingrecord::id(id):let quests: Vec<Quest> = db .query("SELECT record::id(id) AS id, title, reward_gold, created_at FROM quest ORDER BY created_at DESC") .await .and_then(|mut res| res.take(0)) .map_err(|_| RequestError::internal())?;
- SurrealDB's native
- Integer Types:
SurrealValueusesi64for integers.TsApiCollectoris configured withwith_large_int("number"), soi64in Rust maps tonumberin TypeScript (matchingJSON.parse()).
- Monotonic Integer IDs (
db::Sequence):- If you want increasing integer IDs (
table:1,table:2, ...) instead of UUIDs, initializedb::Sequence::load(&db, "table_name").await?onAppStateand lock it while inserting and broadcasting.
- If you want increasing integer IDs (
Step 2: Create Backend Handlers (src/handlers/)
Create a new module src/handlers/quests.rs and register it in src/handlers/mod.rs (pub mod quests;). Because #[handler] uses linker .init_array sections, you do not need to register routes in a central router table—compiling the module is enough.
use handler_macros::{handler, input, output};
use uuid::Uuid;
use crate::auth::UserInfo;
use crate::bus::Bus;
use crate::db::{Database, now_millis};
use crate::server::{Outcome, RequestError};
#[input]
pub struct CreateQuestInput {
pub title: String,
pub reward_gold: i64,
}
#[output]
#[serde(tag = "code", rename_all = "snake_case")]
pub enum CreateQuestError {
TitleEmpty,
NegativeReward,
}
/// Creates a new quest.
/// Doc comments on handlers and fields are carried over as JSDoc in TypeScript!
#[handler(POST "/api/quests/create")]
pub async fn create_quest(
db: &'static Database,
_bus: &'static Bus,
_user: UserInfo,
input: CreateQuestInput,
) -> Result<Outcome<Quest, CreateQuestError>, RequestError> {
let title = input.title.trim();
if title.is_empty() {
return Ok(Outcome::no(CreateQuestError::TitleEmpty));
}
if input.reward_gold < 0 {
return Ok(Outcome::no(CreateQuestError::NegativeReward));
}
let id = Uuid::new_v4().to_string();
// ... insert into SurrealDB ...
Ok(Outcome::ok(Quest {
id,
title: title.to_owned(),
reward_gold: input.reward_gold,
created_at: now_millis(),
}))
}
Handler Rules & Conventions
-
URL & Method:
- Every endpoint exposed to the frontend must start with
/api/. GET "/api/foo/bar"readsinput(if present) from the query string (serde-querystringflat duplicate mode: scalars,Option<T>, and#[serde(default)] Vec<T>).POST "/api/foo/bar"readsinput(if present) from the JSON request body.- Route segments map to nested objects on the frontend client:
POST "/api/quests/create"becomesbackend.quests.create(input).
- Every endpoint exposed to the frontend must start with
-
Dependency Injection & Guards (
HandlerProvide<T>):- The parameter named
inputis reserved for the request payload (#[input]). - Every other parameter is resolved before the handler runs via
<HandlerInput as HandlerProvide<T>>::provide(&handler_input).await:db: &'static Database— the embedded SurrealDB instance.bus: &'static Bus— the in-memory WebSocket pub/sub bus.presence: &'static Presence— online user tracker.user: UserInfo— requires a valid session cookie (rejects with401 session_expiredif missing/expired).user: Option<UserInfo>— resolves toSome(UserInfo)if logged in orNoneif anonymous.gm: GmUser— requires a logged-in user withRole::Gm(rejects with403 gm_requiredotherwise).ip: ClientIp,trace: TraceId— request metadata.
- To make your own type injectable, implement
HandlerProvide<MyType> for HandlerInput.
- The parameter named
-
Two-Channel Error Handling (
Outcome<T, E>vsRequestError):Outcome<T, E>is for domain outcomes the calling UI should explicitly handle (e.g., validation errors,InvalidCredentials,Forbidden). It serializes as HTTP 200{"status": "ok", "data": T} | {"status": "error", "error": E}and becomes a discriminated union in TypeScript.RequestErroris for cross-cutting / infrastructure failures (RequestError::internal(),RequestError::session_expired(),RequestError::forbidden(...)). It returns a non-2xx HTTP status with{"error_code": "..."}and throws aFrameworkErrorinfrontend/src/lib/backend.ts.HandlerResp<T>: Wrap your return type inHandlerResp<T>(includingHandlerResp<Outcome<T, E>>) when you need to attach cookies (SetCookie), custom headers, or a specific HTTP status code (e.g.,201 Created).
Step 3: Add Real-Time WebSocket Events (src/ws.rs)
If your feature needs live push notifications or client-to-server socket commands:
- Add a variant to
ServerEventorClientEventinsrc/ws.rs:#[derive(Debug, Clone, Serialize, TS)] #[serde(tag = "type", rename_all = "kebab-case")] pub enum ServerEvent { // ... existing variants ... QuestsChanged, } - Broadcast from your handler:
use crate::ws::{ServerEvent, broadcast, send_to_user}; // To everyone currently connected: broadcast(bus, &ServerEvent::QuestsChanged); // Or to a specific user's open tabs: send_to_user(bus, "karczmarz", &ServerEvent::QuestsChanged); - Handle the event in
frontend/src/lib/session.ts:handleServerEvent(event: ServerEvent)switches onevent.typewith full TypeScript narrowing.
Step 4: Sync Bindings & Consume in Vue
Run just push-bindings whenever you add or change backend handlers, inputs, outputs, or WebSocket events:
just push-bindings
- Shared Named Types: By default,
TsApiCollectorscopes endpoint helper types inside each endpoint's closure inbackendBindings.tsso identically named types across modules never collide. If you want to import a Rust type directly in Vue (likeimport type { Quest } from '../lib/backend'), register it indo_export_ts()insrc/main.rs:exporter.register_shared_type::<handlers::quests::Quest>(); - Calling Endpoints in Vue:
import { backend, describeApiError } from '../lib/backend' const res = await backend.quests.create({ title: 'Zabić smoka', reward_gold: 500, }) if (res.status === 'error') { // TypeScript narrows `res.error` to `CreateQuestError` switch (res.error.code) { case 'title_empty': // ... break case 'negative_reward': // ... break } return } // TypeScript narrows `res.data` to `Quest` console.log('Created quest:', res.data.id) - Verify Everything:
This regeneratesjust typecheckbackendBindings.ts, checks the Rust workspace (cargo check --workspace), runsvue-tsc -bacross all.tsand.vuefiles, and performs a test Vite bundle to catch any CSS/template issues.