No description
  • Rust 75.2%
  • Vue 11.5%
  • TypeScript 11.1%
  • Just 1.1%
  • SurrealQL 0.7%
  • Other 0.4%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-10-28 17:59:27 +01:00
frontend Initial 2026-10-28 17:59:27 +01:00
handler-macros Initial 2026-10-28 17:59:27 +01:00
src Initial 2026-10-28 17:59:27 +01:00
.gitignore Initial 2026-10-28 17:59:27 +01:00
build.rs Initial 2026-10-28 17:59:27 +01:00
Cargo.lock Initial 2026-10-28 17:59:27 +01:00
Cargo.toml Initial 2026-10-28 17:59:27 +01:00
justfile Initial 2026-10-28 17:59:27 +01:00
README.md Initial 2026-10-28 17:59:27 +01:00

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 via SurrealValue.
  • 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, with ServerEvent and ClientEvent enums exported directly to TypeScript alongside HTTP bindings.
  • Single-Binary Output (rust-embed + build.rs): just build syncs 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])

  1. Separate storage-only fields from wire types when needed:
    • If a record has fields that should not go to the client (like password_hash on StoredUser), 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 Notice or UserInfo), 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,
      }
      
  2. Projecting Record IDs:
    • SurrealDB's native RecordId type does not implement ts_rs::TS. Project the key out in SurrealQL using record::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())?;
      
  3. Integer Types:
    • SurrealValue uses i64 for integers. TsApiCollector is configured with with_large_int("number"), so i64 in Rust maps to number in TypeScript (matching JSON.parse()).
  4. Monotonic Integer IDs (db::Sequence):
    • If you want increasing integer IDs (table:1, table:2, ...) instead of UUIDs, initialize db::Sequence::load(&db, "table_name").await? on AppState and lock it while inserting and broadcasting.

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

  1. URL & Method:

    • Every endpoint exposed to the frontend must start with /api/.
    • GET "/api/foo/bar" reads input (if present) from the query string (serde-querystring flat duplicate mode: scalars, Option<T>, and #[serde(default)] Vec<T>).
    • POST "/api/foo/bar" reads input (if present) from the JSON request body.
    • Route segments map to nested objects on the frontend client: POST "/api/quests/create" becomes backend.quests.create(input).
  2. Dependency Injection & Guards (HandlerProvide<T>):

    • The parameter named input is 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 with 401 session_expired if missing/expired).
      • user: Option<UserInfo> — resolves to Some(UserInfo) if logged in or None if anonymous.
      • gm: GmUser — requires a logged-in user with Role::Gm (rejects with 403 gm_required otherwise).
      • ip: ClientIp, trace: TraceId — request metadata.
    • To make your own type injectable, implement HandlerProvide<MyType> for HandlerInput.
  3. Two-Channel Error Handling (Outcome<T, E> vs RequestError):

    • 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.
    • RequestError is for cross-cutting / infrastructure failures (RequestError::internal(), RequestError::session_expired(), RequestError::forbidden(...)). It returns a non-2xx HTTP status with {"error_code": "..."} and throws a FrameworkError in frontend/src/lib/backend.ts.
    • HandlerResp<T>: Wrap your return type in HandlerResp<T> (including HandlerResp<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:

  1. Add a variant to ServerEvent or ClientEvent in src/ws.rs:
    #[derive(Debug, Clone, Serialize, TS)]
    #[serde(tag = "type", rename_all = "kebab-case")]
    pub enum ServerEvent {
        // ... existing variants ...
        QuestsChanged,
    }
    
  2. 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);
    
  3. Handle the event in frontend/src/lib/session.ts: handleServerEvent(event: ServerEvent) switches on event.type with 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, TsApiCollector scopes endpoint helper types inside each endpoint's closure in backendBindings.ts so identically named types across modules never collide. If you want to import a Rust type directly in Vue (like import type { Quest } from '../lib/backend'), register it in do_export_ts() in src/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:
    just typecheck
    
    This regenerates backendBindings.ts, checks the Rust workspace (cargo check --workspace), runs vue-tsc -b across all .ts and .vue files, and performs a test Vite bundle to catch any CSS/template issues.