cnats: NATS-native chat with Leptos SSR and Kanidm SSO
Initial import plus deployment packaging: multi-stage Dockerfile (cargo-leptos build -> debian-slim runtime), .dockerignore, and a dev-only docker-compose (app + local NATS). Production deployment lives in the infrastructure repo. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+349
@@ -0,0 +1,349 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
|
||||
use leptos_router::{
|
||||
components::{Route, Router, Routes, A},
|
||||
hooks::use_params_map,
|
||||
path,
|
||||
};
|
||||
|
||||
use crate::auth::{current_user, User};
|
||||
use crate::chat::{is_valid_room, room_subject, ChatMessage, SendMessage, DEFAULT_ROOM, ROOMS};
|
||||
|
||||
pub fn shell(options: LeptosOptions) -> impl IntoView {
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml"/>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"/>
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin=""/>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600;700;900&family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;1,400&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<AutoReload options=options.clone()/>
|
||||
<HydrationScripts options/>
|
||||
<MetaTags/>
|
||||
</head>
|
||||
<body>
|
||||
<App/>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
provide_meta_context();
|
||||
|
||||
view! {
|
||||
<Stylesheet id="leptos" href="/pkg/cnats.css"/>
|
||||
<Title text="cnats — chat over the bus"/>
|
||||
<Router>
|
||||
<Routes fallback=|| view! { <NotFound/> }>
|
||||
<Route path=path!("") view=ChatPage/>
|
||||
<Route path=path!("/r/:room") view=ChatPage/>
|
||||
</Routes>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ChatPage() -> impl IntoView {
|
||||
let params = use_params_map();
|
||||
let room = Memo::new(move |_| {
|
||||
params.with(|p| {
|
||||
p.get("room")
|
||||
.filter(|r| is_valid_room(r))
|
||||
.unwrap_or_else(|| DEFAULT_ROOM.to_string())
|
||||
})
|
||||
});
|
||||
let user = Resource::new(|| (), |_| current_user());
|
||||
|
||||
view! {
|
||||
<Suspense fallback=move || {
|
||||
view! {
|
||||
<main class="gate">
|
||||
<p class="gate-loading">"handshaking with the bus…"</p>
|
||||
</main>
|
||||
}
|
||||
}>
|
||||
{move || {
|
||||
user.get()
|
||||
.map(|res| match res {
|
||||
Ok(Some(u)) => view! { <ChatShell room user=u/> }.into_any(),
|
||||
_ => view! { <LoginGate/> }.into_any(),
|
||||
})
|
||||
}}
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// unauthenticated: the gate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[component]
|
||||
fn LoginGate() -> impl IntoView {
|
||||
view! {
|
||||
<main class="gate">
|
||||
<div class="gate-card">
|
||||
<div class="gate-badge">"MESSAGE BUS · AUTH REQUIRED"</div>
|
||||
<h1 class="gate-title">
|
||||
"CN" <span class="gate-title-accent">"ATS"</span>
|
||||
</h1>
|
||||
<p class="gate-sub">
|
||||
"Realtime chat carried on NATS subjects. Identity issued by your Kanidm realm — no separate passwords, no local accounts."
|
||||
</p>
|
||||
<a class="gate-btn" href="/auth/login" rel="external">
|
||||
<span class="gate-btn-glyph">"⏻"</span>
|
||||
"Sign in with Kanidm"
|
||||
</a>
|
||||
<dl class="gate-meta">
|
||||
<div><dt>"subjects"</dt><dd><code>"chat.room.*"</code></dd></div>
|
||||
<div><dt>"downlink"</dt><dd><code>"SSE"</code></dd></div>
|
||||
<div><dt>"identity"</dt><dd><code>"OIDC + PKCE"</code></dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// authenticated: the console
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum BusStatus {
|
||||
Connecting,
|
||||
Live,
|
||||
Offline,
|
||||
}
|
||||
|
||||
impl BusStatus {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
BusStatus::Connecting => "SYN…",
|
||||
BusStatus::Live => "LIVE",
|
||||
BusStatus::Offline => "RETRY",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ChatShell(room: Memo<String>, user: User) -> impl IntoView {
|
||||
let messages = RwSignal::new(Vec::<ChatMessage>::new());
|
||||
let status = RwSignal::new(BusStatus::Connecting);
|
||||
let list_ref = NodeRef::<leptos::html::Div>::new();
|
||||
|
||||
// Subscribe to the room's SSE feed (browser only). Reconnects whenever
|
||||
// the room changes; closes the previous stream first.
|
||||
#[cfg(feature = "hydrate")]
|
||||
{
|
||||
let es_handle = StoredValue::new_local(None::<web_sys::EventSource>);
|
||||
Effect::new(move |_| {
|
||||
let room = room.get();
|
||||
es_handle.update_value(|es| {
|
||||
if let Some(es) = es.take() {
|
||||
es.close();
|
||||
}
|
||||
});
|
||||
messages.set(Vec::new());
|
||||
status.set(BusStatus::Connecting);
|
||||
es_handle.set_value(open_event_source(&room, messages, status));
|
||||
});
|
||||
on_cleanup(move || {
|
||||
es_handle.update_value(|es| {
|
||||
if let Some(es) = es.take() {
|
||||
es.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Pin the stream to the bottom as messages arrive.
|
||||
Effect::new(move |_| {
|
||||
messages.track();
|
||||
if let Some(el) = list_ref.get() {
|
||||
el.set_scroll_top(el.scroll_height());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let draft = RwSignal::new(String::new());
|
||||
let send = ServerAction::<SendMessage>::new();
|
||||
let on_submit = move |ev: leptos::ev::SubmitEvent| {
|
||||
ev.prevent_default();
|
||||
let text = draft.get();
|
||||
if text.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
send.dispatch(SendMessage {
|
||||
room: room.get(),
|
||||
text,
|
||||
});
|
||||
draft.set(String::new());
|
||||
};
|
||||
|
||||
let me = user.username.clone();
|
||||
|
||||
view! {
|
||||
<div class="console">
|
||||
<nav class="rail">
|
||||
<div class="wordmark">
|
||||
"CN" <span class="wordmark-accent">"ATS"</span>
|
||||
<span class="wordmark-sub">"chat over the bus"</span>
|
||||
</div>
|
||||
|
||||
<div class="rail-label">"SUBJECTS"</div>
|
||||
<div class="rooms">
|
||||
{ROOMS
|
||||
.iter()
|
||||
.map(|(name, desc)| {
|
||||
let name = *name;
|
||||
let desc = *desc;
|
||||
view! {
|
||||
<A
|
||||
href=format!("/r/{name}")
|
||||
attr:class=move || {
|
||||
if room.get() == name { "room-link active" } else { "room-link" }
|
||||
}
|
||||
>
|
||||
<span class="room-hash">"❯"</span>
|
||||
<span class="room-text">
|
||||
<span class="room-name">{name}</span>
|
||||
<span class="room-desc">{desc}</span>
|
||||
</span>
|
||||
</A>
|
||||
}
|
||||
})
|
||||
.collect_view()}
|
||||
</div>
|
||||
|
||||
<div class="rail-foot">
|
||||
<div class="user-chip">
|
||||
<span class="user-avatar">
|
||||
{user.display_name.chars().next().unwrap_or('?').to_uppercase().to_string()}
|
||||
</span>
|
||||
<span class="user-names">
|
||||
<span class="user-display">{user.display_name.clone()}</span>
|
||||
<span class="user-handle">{format!("@{}", user.username)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<a class="logout" href="/auth/logout" rel="external" title="sign out">
|
||||
"EOT ⏏"
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main class="deck">
|
||||
<header class="topbar">
|
||||
<div class="topbar-room">
|
||||
<h1>{move || room.get()}</h1>
|
||||
<code class="subject-code">{move || room_subject(&room.get())}</code>
|
||||
</div>
|
||||
<div
|
||||
class="topbar-status"
|
||||
class:live=move || status.get() == BusStatus::Live
|
||||
class:offline=move || status.get() == BusStatus::Offline
|
||||
>
|
||||
<span class="led"></span>
|
||||
<span class="status-text">{move || status.get().label()}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="stream" node_ref=list_ref>
|
||||
<Show when=move || messages.with(|m| m.is_empty())>
|
||||
<div class="stream-empty">
|
||||
<span class="empty-glyph">"[ ∅ ]"</span>
|
||||
<p>"no traffic on this subject yet — say something"</p>
|
||||
</div>
|
||||
</Show>
|
||||
<For
|
||||
each=move || messages.get()
|
||||
key=|m| m.id.clone()
|
||||
children=move |m: ChatMessage| {
|
||||
let mine = m.username == me;
|
||||
view! {
|
||||
<article class="msg" class:mine=mine>
|
||||
<span class="msg-time">{m.time}</span>
|
||||
<span class="msg-user">{m.display_name}</span>
|
||||
<span class="msg-text">{m.text}</span>
|
||||
</article>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form class="composer" on:submit=on_submit>
|
||||
<span class="composer-prompt">"❯"</span>
|
||||
<input
|
||||
type="text"
|
||||
class="composer-input"
|
||||
placeholder=move || format!("PUB {} …", room_subject(&room.get()))
|
||||
prop:value=move || draft.get()
|
||||
on:input=move |ev| draft.set(event_target_value(&ev))
|
||||
autocomplete="off"
|
||||
maxlength="2000"
|
||||
/>
|
||||
<button type="submit" class="composer-send" disabled=move || send.pending().get()>
|
||||
"PUB ↵"
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
fn open_event_source(
|
||||
room: &str,
|
||||
messages: RwSignal<Vec<ChatMessage>>,
|
||||
status: RwSignal<BusStatus>,
|
||||
) -> Option<web_sys::EventSource> {
|
||||
use wasm_bindgen::{prelude::Closure, JsCast};
|
||||
use web_sys::{EventSource, MessageEvent};
|
||||
|
||||
let es = EventSource::new(&format!("/sse/{room}")).ok()?;
|
||||
|
||||
let on_open = Closure::<dyn FnMut()>::new(move || status.set(BusStatus::Live));
|
||||
es.set_onopen(Some(on_open.as_ref().unchecked_ref()));
|
||||
on_open.forget();
|
||||
|
||||
let on_error = Closure::<dyn FnMut()>::new(move || status.set(BusStatus::Offline));
|
||||
es.set_onerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
on_error.forget();
|
||||
|
||||
let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |ev: MessageEvent| {
|
||||
if let Some(data) = ev.data().as_string() {
|
||||
if let Ok(msg) = serde_json::from_str::<ChatMessage>(&data) {
|
||||
messages.update(|m| {
|
||||
m.push(msg);
|
||||
// keep the DOM bounded on long-lived tabs
|
||||
if m.len() > 500 {
|
||||
m.remove(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
es.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
on_message.forget();
|
||||
|
||||
Some(es)
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn NotFound() -> impl IntoView {
|
||||
view! {
|
||||
<main class="gate">
|
||||
<div class="gate-card">
|
||||
<div class="gate-badge">"ERR · NO RESPONDERS"</div>
|
||||
<h1 class="gate-title">"404"</h1>
|
||||
<p class="gate-sub">"No subscribers on this subject."</p>
|
||||
<a class="gate-btn" href="/">"⟵ back to the lobby"</a>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user