Files
buzz/crates/buzz-relay/src/audio/handler.rs
Kalvin C 8a2c9af2db feat(deletion): add durable whole-community deletion (#4425)
## Summary

Adds a durable, operator-controlled V1 for deleting an entire Buzz
community without deleting another tenant's data.

The workflow is exposed through `buzz-admin deletions`:

- `sweep` records independent fleet storage-taxonomy observations
- `submit`, `list`, `inspect`, and `approve` manage a deletion request
- `unblock` resumes a fail-closed request after an operator records
remediation identity and reason
- `run` and `drain` execute bounded work

Requests advance through a PostgreSQL-backed state machine and stop at
`retention_pending` after logical deletion has been independently
verified across PostgreSQL, object storage, and Redis.

This PR ships the engine and CLI, not a continuously running worker or
Kubernetes packaging. For V1, a cluster/VM administrator invokes
`/usr/local/bin/buzz-admin` from the existing relay image, for example
with `kubectl exec` or an equivalent container/VM exec path.

## What whole-community V1 removes

For the target community, V1 removes:

- rows from the allowlisted community-scoped PostgreSQL catalog,
including members, profiles, authored events and bodies, DMs, reactions,
mentions, memberships, tokens, workflows, moderation, audit, feedback,
and rate-limit state
- media sidecars and upload-attribution records under
`_meta/<community>/` and `_uploads/<community>/`
- Git repository pointers under `repos/<community>/`
- Redis keys under `buzz:<community>:*`

The community row survives as a permanent tombstone, and deletion
control-plane records remain as evidence of the request, approval,
execution, and result.

## Safety model

Deletion is not a broad `DELETE CASCADE` followed by optimistic cleanup.
The destructive boundaries are durable and fail closed.

### 1. Inventory and approval

- `submit` resolves the target and freezes the schema plus summary-only
storage inventory.
- Approval is bound to the exact request, community, and frozen
inventory digest.
- Unsupported manifest versions, malformed keys inside the target's
owned prefixes, live scoped-table/write-fence coverage drift,
frozen-inventory mismatch, and approval mismatch block execution rather
than guessing. Migration and catalog revision numbers are not
authorization gates; the executor validates the live safety shape
instead.
- Storage inventory is server-side prefix scoped to exactly:
  - `_meta/<community>/`
  - `_uploads/<community>/`
  - `repos/<community>/`
- The deletion path never lists the whole shared bucket and has no
arbitrary per-community object cap. Its listing work is proportional to
the target community's bindings, not total fleet storage.
- Fleet-wide taxonomy sweeps remain independent observability. They
report unknown writer shapes but do not gate deletion submission,
fencing, or destructive progress. Maintainers must add deletion taxonomy
coverage whenever a new community-owned object-key class is introduced;
writer-coverage tests bind the current media and Git writers to that
contract.

### 2. Quiesce, fence, and destructive freeze

- Writes continue through submission, inventory, and approval. They stop
when execution moves the target into `quiescing` and then establishes
the durable fence.
- Already-admitted external effects finish under heartbeated
serving-write leases; the exact admitted lease may renew while the
community is quiescing, but new lease acquisition is rejected. The
executor drains admitted leases before destructive work.
- Invite minting after quiescing begins fails as typed `AccessDenied`
(HTTP 503 at the relay boundary) before an invite can be persisted.
- Database triggers enforce the community write fence across the
complete catalog of community-scoped tables. Startup/readiness and
destructive execution validate that catalog so a newly added but
unfenced table cannot silently escape.
- **Named isolation assumption — fresh write snapshot.** Every writer
transaction that can reach a community-fenced relation must use
PostgreSQL `READ COMMITTED`; each guarded write therefore observes a
statement snapshot no older than acquisition of the community deletion
lock. `REPEATABLE READ` and `SERIALIZABLE` can retain a pre-fence
snapshot and are unsupported for writers. The writer pool refuses
non-`READ COMMITTED` sessions at connection setup, and both SQL fence
functions reject an explicit per-transaction isolation override with
SQLSTATE `25000`. Configuration-delivered bad isolation can surface
through SQLx as a pool-acquire timeout because every `after_connect`
attempt is rejected; the precise `community writes require READ
COMMITTED isolation` reason remains observable when the SQL guard is
reached. Read-only replica transactions are outside this assumption.
- Holding the shared advisory lock until the guarded write executes is a
separate liveness condition: under `READ COMMITTED`, releasing it early
does not permit resurrection because the trigger rechecks the fence, but
it can turn a fleet sweep into a statement-wide SQLSTATE `55000` abort.
- After the fence closes writers, storage is re-enumerated into chunked
side-table rows. Per-prefix counts and digests bind those concrete keys
to the destructive manifest.
- Manifest chunk insertion, update, and deletion are protected after
freeze. This closes the race where an unbound key could otherwise appear
after the manifest was committed.

### 3. Checkpointed destruction

- Target-owned object bindings are deleted from the frozen destructive
manifest in bounded batches with durable progress.
- The concrete key list lives in chunked side-table rows rather than one
request-row JSON value. It supports large communities, resumable
execution, and terminal cleanup.
- Missing objects are accepted as idempotent crash-window outcomes;
malformed ownership, changed evidence, and unexplained target-prefix
drift fail closed.
- PostgreSQL purging remains scoped by `community_id`, including the
guarded NIP-RS hard-delete path discovered with real Desktop kind
`30078` read-state data.
- Redis cleanup explicitly scans and `UNLINK`s only
`buzz:<community_id>:*`. Natural expiry is insufficient because some
keys, including tunnel generation counters used as fencing state, are
deliberately persistent.

### 4. Independent verification

- PostgreSQL logical absence is checked after purge.
- The three target-owned storage prefixes are freshly inventoried again
and must be empty.
- Redis requires two complete empty namespace scans.
- Only after all three stores pass does the request advance through
`logically_verified` to `retention_pending`.

## What V1 deliberately does not erase

### Shared content-addressed storage

Per-community deletion removes bindings, metadata, attribution records,
and Git pointers. It does **not** physically delete fleet-shared CAS
bytes that another community may still reference:

- media blobs and thumbnails
- Git manifests, packs, and indexes (`manifests/`, `packs/`, and `idx/`)

Safe reclamation requires a separate fleet-wide reachability and
retention GC. Unknown keys elsewhere in the shared bucket do not block
one community's deletion; malformed or unrecognized keys inside that
community's three owned prefixes still fail closed.

### External retained copies

The online logical-deletion proof does not erase object
versions/replicas, database backups/WAL, CDN copies, provider retention
copies, or observability exports. Those require their own retention and
purge controls.

### Member-only erasure

This PR erases a whole community. It does not implement the different
operation "erase one npub while preserving the community."

Removing membership or accepting NIP-09 is not member erasure. A
member-only workflow would need to find and selectively remove or redact
authored event content and pubkeys, profile data, DMs, reactions,
mentions, memberships/roles, tokens, workflows/subscriptions, upload
attribution, moderation/audit history, repository attribution, and
identity embedded in tags or JSON. It would also need explicit rules for
ownership transfer, surviving replies and thread metadata, audit-chain
integrity, immutable Git history, and shared-CAS reachability. That
requires a pubkey-level fence and selective graph rewrite; it is a
separate deletion product, not a safe extension of this whole-tenant
worker.

## In scope

- migration `0029_community_deletion.sql`: requests, approvals, leases,
manifest chunks, checkpoints, tombstones, and the universal write-fence
catalog
- durable executor leases, generations, heartbeats, retry/block state,
and resumable stage transitions
- operator-driven `sweep`, `submit`, `list`, `inspect`, `approve`,
`unblock`, `run`, and `drain` commands
- serving-path fences for database writes and external effects across
event ingest, media, Git, workflow, push, invites, mesh/tunnel, and
related paths
- target-prefix-only storage inventory, summary manifests, post-fence
destructive chunks, and bounded batch deletion
- exact community Redis namespace purge and two-pass absence
verification
- cross-community isolation, crash/resume, manifest-integrity,
writer-taxonomy, and schema/migration regressions
- desired-state `schema/schema.sql` support without requiring a SQLx
migration ledger

## Deferred / not covered

- dedicated Helm/chart worker Deployment, service account, secrets,
probes, resources, and network policy
- autonomous `buzz-admin deletions worker` poll loop and worker-only
health server
- least-privilege separation among migration, relay-serving, and
destructive execution roles
- fleet-wide shared-CAS physical GC
- backup/provider/CDN/observability retention completion
- member-only erasure
- provider-native conditional-delete improvements
- a general force-continue escape hatch; permanent safety failures
remain fail closed unless an operator remediates the cause and records
an audited `unblock`

The removed continuous-worker implementation remains deferred; no remote
follow-up branch is claimed by this PR.

## Validation

### Current PR head and repository state

Current pushed head: `359d8402ee15f049768f54156f67b953c7a7e2ed`, rebased
onto `cc9a2f783375e51a6e8d1f2f9d01d5f7e22813d1` (`origin/main` at push
time). The complete PR diff is now 47 files, 9,834 additions, and 517
deletions.

The bespoke source-scanner stack was removed to keep this PR scoped to
community deletion. Tyler/team requested the underlying fenced-write
safety behavior, not `ast-grep`,
`crates/buzz-db/tests/community_fenced_writes.rs`, its 27 fixtures, or
the new `scripts/lints/community_*.yml` rules. Those scanner-specific
files, dependencies, Hermit links, and runner wiring are absent from the
current tree. The production database write fence, startup/destructive
live-catalog validation, and deletion behavior remain.

Source validation on this exact SHA passed:

- `cargo fmt --all -- --check`
- `bash -n scripts/run-tests.sh`
- `cargo nextest run -p buzz-db --all-targets`: 102 passed, 173 skipped,
0 failed
- `cargo nextest run -p buzz-deletion --all-targets`: 10 passed, 9
skipped, 0 failed
- `cargo nextest run -p buzz-admin --all-targets`: 1 passed, 0 failed
- affected-package/all-target Clippy with warnings denied
- lockfile consistency
- Helm 3.16.4 lint and all 44 chart unit tests
- Helm region controls using that fixture: default
`BUZZ_S3_REGION=us-east-1`, explicit `eu-west-2` override, and
blank-region schema rejection

The prior Kubernetes battery below was run against
`928992237358a3294621ac0280830b77155abc04`. It remains useful evidence
for the patch-equivalent production deletion implementation, but it is
**not** claimed as exact-SHA evidence for current head
`359d8402ee15f049768f54156f67b953c7a7e2ed`; the current cleanup removes
only scanner/test/tooling infrastructure. CI restarted for the new head
after the rebase and is pending. Human review remains
`CHANGES_REQUESTED`.

### Prior-head live Kubernetes deletion and safety gates

The full program used one immutable image, real PostgreSQL, Redis,
MinIO, and a three-relay Kubernetes release:

- source: `928992237358a3294621ac0280830b77155abc04` (**prior head**)
- image: `buzz-e2e:sha-928992237358`
- immutable image digest:
`sha256:a1a204f4618ac22d9e210be5e5290645a15d79831ae30b0e44379357c8e4a895`
- evidence root:
`/tmp/buzz-e2e/20260807T033025Z-928992237358-full-gates/`
- evidence-manifest digest:
`82875c5bc9bea7370b796a7aef3457b3a1c8306c84c59e0f7388bbb5ad30e865`

Passed gates at that prior head:

- **Chart/operator region:** default `us-east-1`, explicit nondefault
propagation, blank-region schema rejection, live in-pod environment, and
an in-pod taxonomy sweep over 18 objects with zero unknown.
- **Fenced writers and lifecycle:** open-write/fence ordering;
100-attempt anti-starvation; invite, push matcher, and exhausted-reaper
bystander isolation; non-`READ-COMMITTED` rejection; manifest/tombstone
contracts; eight-failure stage block and audited `unblock`.
- **Destructive lifecycle:** submit → approve → run →
`retention_pending`; PostgreSQL tombstone and Redis/S3 verification
true; zero retries/errors; terminal reruns rejected with exit 5.
- **Fresh 10,001-object crash boundary:** exactly two chunks (10,000 +
1). The executor deleted chunk 0 from MinIO while its PostgreSQL stamp
was row-lock-blocked, was killed with `SIGKILL`, left one object and
both stamps absent, then resumed the same request under generation 2 to
zero objects and terminal state.
- **Independent dead-owner recovery:** a dedicated executor claimed
generation 1, blocked before effects, and was killed through containerd
with `SIGKILL` (no TERM cleanup). The request remained owned and
unreclaimable before lease expiry; a successor claimed generation 2
after 60 seconds and completed with two attempts and zero retries.
- **Three-pod socket isolation:** ordinary NIP-42 and joined
huddle-audio target witnesses on every replica received exact `1008 /
community deleted`; healthy-tenant witnesses on those pods remained
live; deleted-host reconnect returned HTTP 404.
- **Health/provenance:** all replicas independently returned ready and
retained the exact image digest before/after destructive runs and an
audio-enabled rolling restart; PostgreSQL, Redis, and MinIO were healthy
at close.

Instrument corrections were retained as evidence rather than counted as
product failures: a foreground PostgreSQL forward caused an initial
`PoolTimedOut`; Kubernetes pod deletion exercised graceful TERM rather
than dead-owner recovery; shell-background socket witnesses died with
their parent; and the first image build hit the corporate TLS proxy.
Detached forwarding/witnesses, containerd `SIGKILL`, and the configured
internal CA/Artifactory mirror produced the discriminating runs without
weakening product security.

### Prior-head cleanup

For the prior-head Kubernetes run, the Helm release was removed,
namespace absence was verified, run-owned Screen sessions were absent,
and that source worktree remained clean. The evidence manifest was
independently recomputed and every indexed artifact passed `shasum -a
256 -c`. The current `359d8402` source worktree is also clean after the
scanner-only cleanup and push.

---------

Signed-off-by: npub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xc <5288f082d91aff2de5bc8be23fbfa01ca2e3859cac57a91b7a3fa9f12349505c@buzz.block.builderlab.xyz>
Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Signed-off-by: am <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
Signed-off-by: cid <d9f92a72922bf45c17379a47d64dae84b6020397c2d5a52b5317d512068cd9d3@buzz.block.builderlab.xyz>
Co-authored-by: npub122y0pqkertljmedu303rl0aqrj3w8pvu43t6jxm6875lzg6f2pwqegc3xc <5288f082d91aff2de5bc8be23fbfa01ca2e3859cac57a91b7a3fa9f12349505c@buzz.block.builderlab.xyz>
Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
Co-authored-by: cid <d9f92a72922bf45c17379a47d64dae84b6020397c2d5a52b5317d512068cd9d3@buzz.block.builderlab.xyz>
2026-08-12 09:25:58 -07:00

1516 lines
57 KiB
Rust

//! WebSocket audio handler: NIP-42 auth → room join → frame relay → cleanup.
//!
//! ```text
//! ws_audio_handler
//! └─ handle_audio_connection
//! ├─ send challenge, await auth (5s timeout)
//! ├─ ensure_membership (auto-add for ephemeral channels)
//! ├─ room.add_peer → broadcast joined
//! ├─ spawn send_loop + heartbeat_loop
//! ├─ run recv_loop (blocks until disconnect)
//! └─ cleanup: remove peer, broadcast left, emit lifecycle events
//! ```
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
use std::time::Duration;
use axum::extract::ws::{Message as WsMessage, WebSocket};
use axum::http::{HeaderMap, StatusCode};
use axum::{
extract::{Path, State, WebSocketUpgrade},
response::IntoResponse,
};
use bytes::Bytes;
use futures_util::{SinkExt, StreamExt};
use nostr::{EventBuilder, Kind, Tag};
use serde::Deserialize;
use tokio::sync::{mpsc, watch, OwnedSemaphorePermit, Semaphore};
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use uuid::Uuid;
use buzz_auth::generate_challenge;
use buzz_core::tenant::TenantContext;
use buzz_db::channel::MemberRole;
use buzz_core::StoredEvent;
use buzz_pubsub::EventTopic;
use crate::audio::room::PeerCtrl;
use crate::state::{run_registered_community_connection, AppState, CommunityConnectionControl};
/// Maximum binary frame size: 4 KB is generous for a single Opus packet.
const MAX_AUDIO_FRAME_BYTES: usize = 4096;
/// Maximum text frame size: 8 KB bounds auth/control JSON parsing.
const MAX_TEXT_FRAME_BYTES: usize = 8192;
/// Parser-level cap for this route. Text auth/control frames are the largest
/// message type audio accepts; binary Opus frames are bounded more tightly
/// after parsing.
const MAX_WEBSOCKET_MESSAGE_BYTES: usize = MAX_TEXT_FRAME_BYTES;
/// Heartbeat interval.
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
/// Missed pong limit before disconnect.
const MAX_MISSED_PONGS: u8 = 3;
/// Auth timeout.
const AUTH_TIMEOUT: Duration = Duration::from_secs(5);
/// WebSocket upgrade handler for `/huddle/:channel_id/audio`.
pub async fn ws_audio_handler(
State(state): State<Arc<AppState>>,
Path(channel_id): Path<Uuid>,
headers: HeaderMap,
ws: WebSocketUpgrade,
) -> impl IntoResponse {
// Row zero: bind this huddle-audio connection to its community from the
// request host BEFORE the WebSocket upgrade, identical to the main relay
// door. An unmapped host or lookup failure fails closed with a generic 404
// — never a default tenant — so an unauthenticated caller cannot probe
// which communities exist on this deployment.
let raw_host = headers
.get(axum::http::header::HOST)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let tenant = match crate::tenant::bind_community(&state.db, raw_host).await {
Ok(ctx) => ctx,
Err(_) => {
return (
StatusCode::NOT_FOUND,
"relay: no community is configured for this host",
)
.into_response();
}
};
let permit = match acquire_audio_connection_permit(&state.conn_semaphore) {
Some(permit) => permit,
None => {
warn!(channel_id = %channel_id, "Connection limit reached, rejecting audio WebSocket");
return (
StatusCode::SERVICE_UNAVAILABLE,
"relay: connection limit reached",
)
.into_response();
}
};
// Keep the parser boundary at the largest message this route accepts. The
// checks in the receive loop still distinguish text from binary policy, but
// they run after tungstenite has assembled a message.
limit_audio_websocket(ws).on_upgrade(move |socket| {
handle_audio_connection(socket, state, tenant, channel_id, permit)
})
}
fn acquire_audio_connection_permit(
conn_semaphore: &Arc<Semaphore>,
) -> Option<OwnedSemaphorePermit> {
Arc::clone(conn_semaphore).try_acquire_owned().ok()
}
fn limit_audio_websocket<F>(ws: WebSocketUpgrade<F>) -> WebSocketUpgrade<F> {
ws.max_message_size(MAX_WEBSOCKET_MESSAGE_BYTES)
.max_frame_size(MAX_WEBSOCKET_MESSAGE_BYTES)
}
/// Highest huddle audio protocol version this relay understands. Clients are
/// allowed to negotiate any version in `1..=CURRENT_PROTOCOL_VERSION`; older
/// versions stay supported indefinitely for staged rollouts.
const CURRENT_PROTOCOL_VERSION: u8 = 2;
#[derive(Deserialize)]
struct AuthMsg {
#[serde(rename = "type")]
msg_type: String,
event: nostr::Event,
parent_channel_id: Option<Uuid>,
/// Huddle audio protocol version requested by the client. Defaults to 1
/// when missing so existing clients keep working without recompile. A
/// room is pinned to whichever version its first peer requested; later
/// peers must match or get `upgrade_required`.
#[serde(default = "default_protocol_version")]
protocol_version: u8,
}
fn default_protocol_version() -> u8 {
1
}
async fn handle_audio_connection(
socket: WebSocket,
state: Arc<AppState>,
tenant: TenantContext,
channel_id: Uuid,
_permit: OwnedSemaphorePermit,
) {
let cancel = CancellationToken::new();
let control = CommunityConnectionControl::new(cancel);
let community_id = tenant.community();
let registry = Arc::clone(&state.community_connections);
let check_state = Arc::clone(&state);
let run_state = Arc::clone(&state);
run_registered_community_connection(
&registry,
Uuid::new_v4(),
community_id,
control,
move || async move { check_state.db.is_community_active(community_id).await },
move |control| {
handle_active_audio_connection(socket, run_state, tenant, channel_id, control)
},
)
.await;
}
async fn handle_active_audio_connection(
socket: WebSocket,
state: Arc<AppState>,
tenant: TenantContext,
channel_id: Uuid,
control: CommunityConnectionControl,
) {
let cancel = control.cancellation_token();
let disconnect_reason = control.disconnect_reason();
let (mut ws_send, mut ws_recv) = socket.split();
let challenge = generate_challenge();
let challenge_msg =
serde_json::json!({"type": "challenge", "challenge": challenge}).to_string();
if ws_send
.send(WsMessage::Text(challenge_msg.into()))
.await
.is_err()
{
return;
}
let auth_result = tokio::select! {
biased;
_ = cancel.cancelled() => return,
result = tokio::time::timeout(AUTH_TIMEOUT, async {
while let Some(Ok(msg)) = ws_recv.next().await {
if let WsMessage::Text(text) = msg {
if text.len() > MAX_TEXT_FRAME_BYTES {
warn!(channel_id = %channel_id, "auth text frame too large — dropping");
continue;
}
if let Ok(auth) = serde_json::from_str::<AuthMsg>(&text) {
if auth.msg_type == "auth" {
return Some(auth);
}
}
}
}
None
}) => result,
};
let auth_msg = match auth_result {
Ok(Some(a)) => a,
_ => {
debug!(channel_id = %channel_id, "audio auth timeout or disconnect");
return;
}
};
// Extract NIP-OA auth tag before verify_auth_event consumes the event.
let auth_tag_json = crate::handlers::auth::extract_auth_tag_json(&auth_msg.event);
let relay_url = crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &tenant);
let auth_ctx = match state
.auth
.verify_auth_event(auth_msg.event, &challenge, &relay_url)
.await
{
Ok(ctx) => ctx,
Err(e) => {
warn!(channel_id = %channel_id, "audio auth failed: {e}");
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({"type":"error","message":"auth failed"})
.to_string()
.into(),
))
.await;
return;
}
};
let pubkey = auth_ctx.pubkey;
let pubkey_hex = pubkey.to_hex();
let pubkey_bytes = pubkey.to_bytes().to_vec();
let parent_channel_id = auth_msg.parent_channel_id;
if crate::api::relay_members::enforce_relay_membership(
&state,
tenant.community(),
pubkey.as_bytes(),
auth_tag_json.as_deref(),
)
.await
.is_err()
{
warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "audio: relay membership denied");
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({"type": "error", "message": "restricted: not a relay member"})
.to_string()
.into(),
))
.await;
return;
}
// ── Step 3: membership check / auto-add ───────────────────────────────────
let parent_id_for_event = match ensure_membership(
&state,
&tenant,
channel_id,
&pubkey_bytes,
parent_channel_id,
)
.await
{
Ok(parent_id) => parent_id,
Err(e) => {
warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "audio membership denied: {e}");
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({"type":"error","message":"not a member"})
.to_string()
.into(),
))
.await;
return;
}
};
// Huddle cross-pod routing (mesh) OR single-pod guardrail.
//
// When the mesh is live (`state.mesh()` is `Some`), a huddle can span pods:
// Redis arbitrates ownership and this pod either owns the room locally or
// forwards the client to the owner over a `HuddleControl` stream. When the
// mesh is off, we keep today's behavior exactly — including the
// `huddle_audio_available=false` rejection under a non-mesh horizontal
// deployment (two peers on different pods would never hear each other).
//
// `remote_owner` is `Some` only on the non-owner path; it carries the
// registration to the owner and, once the client is admitted locally, is
// opened so its media forwards to the owner instead of fanning out locally.
let mut pending_remote: Option<crate::audio::join::JoinOutcome> = None;
// The freshly-acquired owner lease, if this connection won the CAS. Held
// until `add_peer` succeeds, then installed in the owner registry so the
// renewer's lifetime matches the room's, not this connection's failure
// paths (archived channel, version reject, room full) which return early.
let mut acquired_lease: Option<crate::audio::join::HuddleLease> = None;
match state.mesh() {
Some(mesh) => {
if mesh.owners.is_draining() {
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({
"type": "error",
"code": "huddle_relay_draining",
"message": "relay is draining; reconnect"
})
.to_string()
.into(),
))
.await;
return;
}
match crate::audio::join::resolve_join_owner_ready(
&mesh.directory,
tenant.community(),
channel_id,
mesh.local_runtime_id,
&mesh.owners,
)
.await
{
Ok(resolved) => {
acquired_lease = resolved.acquired;
pending_remote = Some(resolved.outcome);
}
Err(e) => {
warn!(
channel_id = %channel_id,
pubkey = %pubkey_hex,
"huddle join rejected by fence: {e}"
);
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({
"type": "error",
"code": "join_rejected",
"message": "huddle join rejected"
})
.to_string()
.into(),
))
.await;
return;
}
}
}
None => {
if !state.config.huddle_audio_available {
debug!(
channel_id = %channel_id,
pubkey = %pubkey_hex,
"huddle audio unavailable under horizontal scaling — rejecting join"
);
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({
"type": "error",
"code": "huddle_audio_unavailable",
"message": "huddle audio unavailable in this deployment"
})
.to_string()
.into(),
))
.await;
return;
}
}
}
let room = state
.audio_rooms
.get_or_create(tenant.community(), channel_id);
// Re-check archived status after obtaining the room. This closes the
// cross-boundary race: a joiner that passed ensure_membership before
// the last peer archived the channel could get a fresh room via
// get_or_create (the old room was already cleaned up). This DB check
// catches that case. The room-level ended flag (checked inside add_peer)
// handles the same-room case.
match state.db.get_channel(tenant.community(), channel_id).await {
Ok(ch) if ch.archived_at.is_some() => {
debug!(channel_id = %channel_id, "channel archived before room join");
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({"type":"error","message":"huddle has ended"})
.to_string()
.into(),
))
.await;
state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
return;
}
Err(e) => {
warn!(channel_id = %channel_id, "pre-join channel check failed (fail-closed): {e}");
state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
return;
}
Ok(_) => {} // Channel exists and is not archived — proceed.
}
// Reject unsupported future versions up-front so we don't accidentally
// pin a room to a version we can't speak. Versions 1..=CURRENT are OK.
let requested_version = auth_msg.protocol_version;
if requested_version == 0 || requested_version > CURRENT_PROTOCOL_VERSION {
warn!(
channel_id = %channel_id,
pubkey = %pubkey_hex,
requested_version,
current = CURRENT_PROTOCOL_VERSION,
"audio: client requested unsupported protocol version"
);
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({
"type": "error",
"code": "unsupported_version",
"message": format!(
"huddle audio protocol v{requested_version} not supported; relay max is v{CURRENT_PROTOCOL_VERSION}"
),
"current_version": CURRENT_PROTOCOL_VERSION,
})
.to_string()
.into(),
))
.await;
return;
}
// Remote registration happens before ingress admission. The owner-assigned
// index is therefore the only index this client ever has; no frame or
// `joined` message can escape with an ingress-local placeholder.
let mut remote_session: Option<crate::audio::join::RemoteHuddleSession> = None;
let mut remote_stream: Option<buzz_relay_mesh::MeshStream> = None;
let mut remote_fence: Option<Arc<crate::audio::mesh::GenerationFloor>> = None;
if let (Some(mesh), Some(crate::audio::join::JoinOutcome::RemoteOwner { .. })) =
(state.mesh(), pending_remote)
{
let outcome = pending_remote.expect("RemoteOwner matched above");
let fenced = outcome.fenced_header(channel_id, mesh.local_runtime_id);
let crate::audio::join::JoinOutcome::RemoteOwner {
owner_runtime_id, ..
} = outcome
else {
unreachable!("matched RemoteOwner above");
};
match crate::audio::join::dial_remote_owner(
Arc::clone(&mesh.transport),
mesh.local_runtime_id,
owner_runtime_id,
fenced,
tenant.community(),
pubkey_hex.clone(),
requested_version,
)
.await
{
Ok((session, stream)) => {
remote_session = Some(session);
remote_stream = Some(stream);
remote_fence = Some(Arc::clone(&mesh.audio_fence));
}
Err(crate::audio::join::DialError::Rejected(reason)) => {
warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "huddle owner rejected registration: {reason:?}");
let _ = ws_send
.send(WsMessage::Text(
remote_rejection_ws_error(&reason).to_string().into(),
))
.await;
state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
return;
}
Err(crate::audio::join::DialError::Mesh(e)) => {
warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "huddle owner registration failed: {e}");
let _ = ws_send
.send(WsMessage::Text(
serde_json::json!({
"type": "error", "code": "huddle_owner_unreachable",
"message": "could not reach the huddle owner"
})
.to_string()
.into(),
))
.await;
state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
return;
}
}
}
let admission = if let Some(session) = remote_session.as_ref() {
room.add_peer_at_index(pubkey_hex.clone(), requested_version, session.peer_index())
.map(|(id, audio, ctrl)| (id, session.peer_index(), audio, ctrl))
} else {
room.add_peer(pubkey_hex.clone(), requested_version)
};
let (peer_id, peer_index, audio_rx, peer_ctrl_rx) = match admission {
Ok(v) => v,
Err(crate::audio::room::AdmissionError::Full) => {
warn!(channel_id = %channel_id, "audio room full (255 peers exhausted)");
let _ = ws_send.send(WsMessage::Text(serde_json::json!({"type":"error","code":"room_full","message":"peer index space exhausted"}).to_string().into())).await;
if let (Some(session), Some(stream)) = (remote_session.as_ref(), remote_stream.as_mut())
{
crate::audio::join::send_clean_close(stream, session.fenced(), session.pubkey())
.await;
}
return;
}
Err(crate::audio::room::AdmissionError::Ended) => {
debug!(channel_id = %channel_id, "room ended before admission");
let _ = ws_send.send(WsMessage::Text(serde_json::json!({"type":"error","code":"room_ended","message":"huddle has ended"}).to_string().into())).await;
if let (Some(session), Some(stream)) = (remote_session.as_ref(), remote_stream.as_mut())
{
crate::audio::join::send_clean_close(stream, session.fenced(), session.pubkey())
.await;
}
return;
}
Err(crate::audio::room::AdmissionError::VersionMismatch { pinned, requested }) => {
info!(channel_id = %channel_id, pubkey = %pubkey_hex, pinned, requested, "audio: protocol version mismatch — upgrade required");
let _ = ws_send.send(WsMessage::Text(serde_json::json!({
"type": "error", "code": "upgrade_required",
"message": format!("this huddle is using audio protocol v{pinned}; your client requested v{requested}"),
"pinned_version": pinned, "requested_version": requested,
}).to_string().into())).await;
if let (Some(session), Some(stream)) = (remote_session.as_ref(), remote_stream.as_mut())
{
crate::audio::join::send_clean_close(stream, session.fenced(), session.pubkey())
.await;
}
return;
}
};
info!(
channel_id = %channel_id,
pubkey = %pubkey_hex,
peer_index,
"audio peer joined"
);
// Owner path: install (or reuse) this room's single lease renewer now that
// a peer is admitted, and capture its owner-loss signal. The connection
// that won the CAS holds `acquired_lease`; it installs the renewer. A
// steady-state owner (an earlier joiner installed it) reuses the room's
// existing signal. `owner_lost` drives this connection's own teardown
// below; `owner_generation` fences the release on room-empty so a stale
// teardown cannot release a newer epoch a re-acquire installed.
//
// The reuse arm's live entry is guaranteed by `resolve_join_owner_ready`:
// it re-resolves until the CAS winner has installed (reuse) or a fresh CAS
// wins (acquire), never returning a `LocalOwner` snapshot with a missing
// registry entry. So a local owner peer here always gets a real `lost`
// watcher — the ownerless split-brain (an owner peer fanning stale media
// with no way to observe lease loss, since local WS peers have no per-frame
// fence) cannot occur. A `None` on the reuse arm is therefore an invariant
// violation, not a benign race; log it loudly rather than proceed silently.
let mut owner_lost: Option<CancellationToken> = None;
let mut owner_draining: Option<CancellationToken> = None;
let mut owner_generation: Option<u64> = None;
if let Some(mesh) = state.mesh() {
match (pending_remote, acquired_lease.take()) {
(Some(crate::audio::join::JoinOutcome::LocalOwner { generation }), Some(lease)) => {
let signals =
mesh.owners
.attach_signals(channel_id, Arc::new(mesh.directory.clone()), lease);
owner_lost = Some(signals.lost);
owner_draining = Some(signals.draining);
owner_generation = Some(generation);
}
(Some(crate::audio::join::JoinOutcome::LocalOwner { generation }), None) => {
owner_lost = mesh.owners.lost_for(channel_id);
owner_draining = mesh.owners.drain_for(channel_id);
owner_generation = Some(generation);
if owner_lost.is_none() {
error!(
channel_id = %channel_id,
"huddle owner-ready invariant violated: LocalOwner reuse with no live \
registry entry after resolve_join_owner_ready — owner peer has no \
lease-loss watcher"
);
}
}
_ => {}
}
}
// Remote registration and owner-assigned ingress admission completed above.
let peers_snapshot: Vec<serde_json::Value> = if let Some(session) = remote_session.as_ref() {
session
.roster()
.peers
.iter()
.map(|peer| serde_json::json!({"pubkey": peer.pubkey, "peer_index": peer.peer_index}))
.collect()
} else {
room.peer_pubkeys()
.into_iter()
.map(|(pk, idx)| serde_json::json!({"pubkey": pk, "peer_index": idx}))
.collect()
};
let joined_msg = serde_json::json!({
"type": "joined",
"pubkey": pubkey_hex,
"peer_index": peer_index,
"peers": peers_snapshot,
})
.to_string();
if remote_session.is_some() {
if ws_send
.send(WsMessage::Text(joined_msg.into()))
.await
.is_err()
{
room.remove_peer(peer_id);
state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
return;
}
} else {
room.broadcast_control(joined_msg);
}
// ── Step 6: emit kind:48101 (PARTICIPANT_JOINED) ──────────────────────────
emit_participant_event(
&state,
&tenant,
Kind::Custom(48101),
channel_id,
parent_id_for_event,
&pubkey_hex,
)
.await;
let missed_pongs = Arc::new(AtomicU8::new(0));
// Dual-channel pattern (matches connection.rs): data channel for audio,
// control channel for Ping/Pong/Close/control JSON with priority drain.
let (data_tx, data_rx) = mpsc::channel::<WsMessage>(16);
let (ctrl_tx, ctrl_rx) = mpsc::channel::<WsMessage>(8);
let send_cancel = cancel.child_token();
let send_task = tokio::spawn(send_loop(
ws_send,
data_rx,
ctrl_rx,
send_cancel,
disconnect_reason,
));
let hb_cancel = cancel.clone();
let hb_missed = Arc::clone(&missed_pongs);
let heartbeat_task = tokio::spawn(heartbeat_loop(ctrl_tx.clone(), hb_missed, hb_cancel));
let fwd_cancel = cancel.child_token();
let forward_task = tokio::spawn(audio_forward_loop(
audio_rx,
peer_ctrl_rx,
data_tx,
ctrl_tx.clone(),
fwd_cancel,
));
// Non-owner path: own the owner's `HuddleControl` stream in a reader task.
// It races the owner's teardown signal against our own cancellation:
// * owner speaks first (`Goodbye` / stream close) → tear the client down
// and close its WS so it rejoins (against a fresh owner/generation),
// and forget the local generation floor so the rejoin isn't fenced by
// the dead session. Redis remains the ownership arbiter; forgetting the
// floor only clears local stale-frame suppression.
// * we cancel first (client left / heartbeat death) → send the clean
// `UnregisterPeer` + `Goodbye(SessionEnded)` so the owner drops us.
let reader_task = remote_stream.map(|mut stream| {
let reader_cancel = cancel.clone();
let fence = remote_fence.expect("remote_fence set whenever remote_stream is");
let fenced = remote_session
.as_ref()
.expect("remote_session set whenever remote_stream is")
.fenced();
let pubkey = remote_session
.as_ref()
.expect("remote_session set whenever remote_stream is")
.pubkey()
.to_string();
let roster_revision = remote_session
.as_ref()
.expect("remote_session set whenever remote_stream is")
.roster()
.revision;
let roster_ctrl_tx = ctrl_tx.clone();
tokio::spawn(async move {
tokio::select! {
cause = crate::audio::join::read_owner_control(
&mut stream,
fenced,
roster_revision,
&roster_ctrl_tx,
) => {
teardown_remote_huddle(cause, channel_id, &reader_cancel, &fence);
}
_ = reader_cancel.cancelled() => {
crate::audio::join::send_clean_close(&mut stream, fenced, &pubkey).await;
}
}
})
});
// Owner path: watch the room's owner-loss / owner-drain signals. Fenced loss
// and intentional drain both close local owner clients for rejoin and forget
// the local generation floor so the fresh generation is accepted. The cause
// distinction is carried on the remote control streams; locally the action
// is the same WS teardown. Silent on ordinary client leave.
let owner_teardown_task = if owner_lost.is_some() || owner_draining.is_some() {
let fence = Arc::clone(
&state
.mesh()
.expect("owner teardown watcher only exists when mesh owner state exists")
.audio_fence,
);
let owner_cancel = cancel.clone();
Some(tokio::spawn(async move {
let lost_fired = async {
match &owner_lost {
Some(token) => token.cancelled().await,
None => std::future::pending().await,
}
};
let drain_fired = async {
match &owner_draining {
Some(token) => token.cancelled().await,
None => std::future::pending().await,
}
};
tokio::select! {
_ = drain_fired => {
info!(
channel_id = %channel_id,
"huddle owner is draining — closing local client for rejoin"
);
owner_cancel.cancel();
fence.forget(channel_id);
}
_ = lost_fired => {
info!(
channel_id = %channel_id,
"huddle owner lost its lease — closing local client for rejoin"
);
owner_cancel.cancel();
fence.forget(channel_id);
}
_ = owner_cancel.cancelled() => {}
}
}))
} else {
None
};
recv_loop(
ws_recv,
Arc::clone(&room),
peer_id,
requested_version,
ctrl_tx,
Arc::clone(&missed_pongs),
cancel.clone(),
remote_session.as_mut(),
)
.await;
cancel.cancel();
let _ = send_task.await;
let _ = heartbeat_task.await;
let _ = forward_task.await;
// The reader task owns the owner control stream; joining it here guarantees
// its clean-close (or teardown) completes before connection cleanup returns.
if let Some(reader_task) = reader_task {
let _ = reader_task.await;
}
// The owner teardown watcher is cancelled by `cancel.cancel()` above (or has
// already fired); join it so it settles before cleanup.
if let Some(owner_teardown_task) = owner_teardown_task {
let _ = owner_teardown_task.await;
}
// Atomic owner remove + end check: remove_peer_and_check_ended holds the
// AdmissionGuard lock across index recycling AND the is_empty + ended=true
// check. Ingress mirrors never archive authoritative huddle state; they
// remove locally and let the owner decide room lifetime.
let should_auto_end = if remote_session.is_some() {
room.remove_peer(peer_id);
false
} else {
room.remove_peer_and_check_ended(peer_id)
.map(|(_, ended)| ended)
.unwrap_or(false)
};
let left_msg = serde_json::json!({
"type": "left",
"pubkey": pubkey_hex,
"peer_index": peer_index,
})
.to_string();
if remote_session.is_none() {
room.broadcast_control(left_msg);
}
emit_participant_event(
&state,
&tenant,
Kind::Custom(48102),
channel_id,
parent_id_for_event,
&pubkey_hex,
)
.await;
let room_emptied;
if should_auto_end {
info!(channel_id = %channel_id, "audio room empty — auto-ending huddle");
match state
.db
.archive_channel(tenant.community(), channel_id)
.await
{
Err(e) => {
warn!(channel_id = %channel_id, "auto-archive failed, huddle stays alive: {e}");
room.clear_ended();
room_emptied = false;
}
Ok(()) => {
room_emptied = state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
emit_participant_event(
&state,
&tenant,
Kind::Custom(48103),
channel_id,
parent_id_for_event,
&pubkey_hex,
)
.await;
}
}
} else {
room_emptied = state
.audio_rooms
.cleanup_if_empty(tenant.community(), channel_id);
}
// Owner path: release this room's lease when the room empties, so a new
// owner can acquire and the renewer stops cleanly (silent, not owner-loss).
// Fenced on the generation this connection saw as owner: if the room
// emptied and a re-acquire installed a newer epoch in the gap, `release`
// is a no-op for the stale generation and leaves the live renewer running.
// Only the last leaver empties the room, so exactly one release fires.
if room_emptied {
if let (Some(mesh), Some(generation)) = (state.mesh(), owner_generation) {
mesh.owners.release(channel_id, generation);
}
}
info!(
channel_id = %channel_id,
pubkey = %pubkey_hex,
"audio peer left"
);
}
/// React to a non-owner huddle teardown signal read off the owner's control
/// stream: cancel the connection (which drives the client's WS to close so it
/// rejoins) and forget the local generation floor for this session.
///
/// The `cause` is logged for observability but does not change behaviour —
/// every cause is recoverable by a rejoin, whether against a fresh owner
/// (`OwnerLost`/`StreamClosed`), a draining owner (`OwnerDraining`), or a room
/// that simply ended (`SessionEnded`). `forget` clears local stale-frame
/// suppression so the rejoin's fresh generation is accepted; it never
/// authorizes ownership — Redis fenced CAS remains the arbiter.
fn teardown_remote_huddle(
cause: crate::audio::join::HuddleTeardownCause,
channel_id: Uuid,
cancel: &CancellationToken,
fence: &crate::audio::mesh::GenerationFloor,
) {
info!(
channel_id = %channel_id,
?cause,
"owner tore down cross-pod huddle session — closing client for rejoin"
);
cancel.cancel();
fence.forget(channel_id);
}
/// Map an owner's registration rejection to the client-facing WS error, using
/// the same `code`s a same-pod join produces so a cross-pod client handles them
/// identically. Fence rejections carry their taxonomy code for observability.
fn remote_rejection_ws_error(reason: &crate::audio::join::RegisterRejection) -> serde_json::Value {
use crate::audio::join::RegisterRejection;
match reason {
RegisterRejection::RoomFull => serde_json::json!({
"type": "error", "code": "room_full",
"message": "peer index space exhausted"
}),
RegisterRejection::RoomEnded => serde_json::json!({
"type": "error", "code": "room_ended", "message": "huddle has ended"
}),
RegisterRejection::VersionMismatch { pinned, requested } => serde_json::json!({
"type": "error", "code": "upgrade_required",
"message": format!(
"this huddle is using audio protocol v{pinned}; your client requested v{requested}"
),
"pinned_version": pinned,
"requested_version": requested,
}),
RegisterRejection::Fenced(f) => serde_json::json!({
"type": "error", "code": "join_rejected",
"message": "huddle join rejected",
"fence_reason": f.code(),
}),
}
}
/// Receive loop: reads client frames and routes them. Local/owner joins fan
/// out through the local room; a non-owner join forwards to the huddle owner
/// via `remote_session`. Argument count reflects the pre-existing connection
/// wiring plus the one mesh session; a param struct would obscure more than it
/// clarifies at this single call site.
#[allow(clippy::too_many_arguments)]
async fn recv_loop(
mut ws_recv: futures_util::stream::SplitStream<WebSocket>,
room: Arc<crate::audio::room::Room>,
peer_id: Uuid,
protocol_version: u8,
ctrl_tx: mpsc::Sender<WsMessage>,
missed_pongs: Arc<AtomicU8>,
cancel: CancellationToken,
mut remote_session: Option<&mut crate::audio::join::RemoteHuddleSession>,
) {
use crate::audio::wire::{FrameHeader, V2_HEADER_LEN};
loop {
tokio::select! {
biased;
_ = cancel.cancelled() => break,
msg = ws_recv.next() => {
match msg {
Some(Ok(WsMessage::Binary(data))) => {
if data.len() > MAX_AUDIO_FRAME_BYTES {
warn!(peer_id = %peer_id, bytes = data.len(), "audio frame too large — dropping");
continue;
}
// Protocol v2 sanity-parse: validate the header is
// present and well-shaped, then forward opaquely.
// We never strip, rewrite, or re-encode bytes — the
// header is sender-authored telemetry only — but we
// do refuse to broadcast frames that are clearly
// malformed for the room's pinned protocol so we
// don't help v2 peers feed garbage to other v2 peers.
if protocol_version >= 2 {
// Frame must carry at least the 8-byte header
// plus a non-empty Opus payload.
if data.len() <= V2_HEADER_LEN {
warn!(
peer_id = %peer_id,
bytes = data.len(),
"v2 frame missing header or payload — dropping"
);
continue;
}
match FrameHeader::parse(&data) {
Some((header, payload)) if !payload.is_empty() => {
// Header is well-formed. `level_dbov` is
// already clamped by `parse` — bad values
// do not drop the frame, they just lose
// the metric (which the relay does not
// trust for anything anyway).
tracing::trace!(
peer_id = %peer_id,
seq = header.seq,
ts_48k = header.ts_48k,
level_dbov = header.level_dbov,
is_dtx = header.is_dtx(),
"v2 audio frame"
);
}
_ => {
warn!(
peer_id = %peer_id,
bytes = data.len(),
"v2 frame failed header parse — dropping"
);
continue;
}
}
}
// Non-owner path forwards the client's Opus to the
// huddle owner as a datagram (the owner is the sole
// fan-out authority); the owner-side room fans it back
// to every participant, including our co-located peers.
// Owner/local path fans out through the local room.
match remote_session.as_deref_mut() {
Some(session) => session.forward_media(&data),
None => room.broadcast_frame(peer_id, data),
}
}
Some(Ok(WsMessage::Text(text))) => {
if text.len() > MAX_TEXT_FRAME_BYTES {
warn!(peer_id = %peer_id, bytes = text.len(), "control text frame too large — dropping");
continue;
}
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) {
if v.get("type").and_then(|t| t.as_str()) == Some("leave") {
break;
}
}
}
Some(Ok(WsMessage::Pong(_))) => {
missed_pongs.store(0, Ordering::Relaxed);
}
Some(Ok(WsMessage::Ping(data))) => {
// Pong goes through the control channel — priority delivery.
let _ = ctrl_tx.try_send(WsMessage::Pong(data));
}
Some(Ok(WsMessage::Close(_))) | None => break,
Some(Err(e)) => {
debug!(peer_id = %peer_id, "ws error: {e}");
break;
}
}
}
}
}
}
/// Outbound send loop with control-frame priority (matches connection.rs pattern).
///
/// Control frames (Ping, Pong, Close, control JSON) are drained first on every
/// iteration, so heartbeat pings are never starved by audio backpressure.
async fn send_loop<S>(
mut ws_send: S,
mut data_rx: mpsc::Receiver<WsMessage>,
mut ctrl_rx: mpsc::Receiver<WsMessage>,
cancel: CancellationToken,
disconnect_reason: watch::Receiver<Option<crate::state::CommunityDisconnectReason>>,
) where
S: futures_util::Sink<WsMessage> + Unpin,
{
loop {
// Priority: drain all pending control frames before data.
while let Ok(ctrl_msg) = ctrl_rx.try_recv() {
if ws_send.send(ctrl_msg).await.is_err() {
return;
}
}
tokio::select! {
biased;
_ = cancel.cancelled() => {
let close = disconnect_reason
.borrow()
.map_or(WsMessage::Close(None), |reason| reason.close_message());
let _ = ws_send.send(close).await;
break;
}
Some(ctrl_msg) = ctrl_rx.recv() => {
if ws_send.send(ctrl_msg).await.is_err() { break; }
}
Some(msg) = data_rx.recv() => {
if ws_send.send(msg).await.is_err() { break; }
}
}
}
}
// Bridges the room's mpsc channel to the WS send channel.
/// Bridges room per-peer channels → WS send channels.
/// Audio frames (from room audio_rx) go to data_tx.
/// Control messages (from room ctrl_rx) go to ws ctrl_tx (priority path).
/// Two separate room channels ensure control is never starved by audio backpressure.
async fn audio_forward_loop(
mut audio_rx: mpsc::Receiver<Bytes>,
mut peer_ctrl_rx: mpsc::Receiver<PeerCtrl>,
data_tx: mpsc::Sender<WsMessage>,
ctrl_tx: mpsc::Sender<WsMessage>,
cancel: CancellationToken,
) {
loop {
tokio::select! {
biased;
_ = cancel.cancelled() => break,
// Control messages get priority over audio in the select.
msg = peer_ctrl_rx.recv() => {
match msg {
Some(PeerCtrl::Json(json)) => {
let _ = ctrl_tx.try_send(WsMessage::Text(json.into()));
}
Some(PeerCtrl::Close) | None => break,
}
}
frame = audio_rx.recv() => {
match frame {
Some(bytes) => {
let _ = data_tx.try_send(WsMessage::Binary(bytes));
}
None => break,
}
}
}
}
}
async fn heartbeat_loop(
ws_tx: mpsc::Sender<WsMessage>,
missed_pongs: Arc<AtomicU8>,
cancel: CancellationToken,
) {
let mut interval = tokio::time::interval(HEARTBEAT_INTERVAL);
loop {
tokio::select! {
_ = interval.tick() => {
// fetch_add returns the previous value; +1 gives the current count.
let missed = missed_pongs.fetch_add(1, Ordering::Relaxed) + 1;
if missed >= MAX_MISSED_PONGS {
warn!("audio: {missed} missed pongs — closing connection");
cancel.cancel();
break;
}
if ws_tx.try_send(WsMessage::Ping(axum::body::Bytes::new())).is_err() {
cancel.cancel();
break;
}
}
_ = cancel.cancelled() => break,
}
}
}
async fn ensure_membership(
state: &AppState,
tenant: &TenantContext,
channel_id: Uuid,
pubkey_bytes: &[u8],
parent_channel_id: Option<Uuid>,
) -> Result<Uuid, String> {
// Load channel first — reject archived channels before any membership check.
// This ensures auto-ended huddles can't be rejoined by existing members.
let channel = state
.db
.get_channel(tenant.community(), channel_id)
.await
.map_err(|e| format!("db error: {e}"))?;
if channel.archived_at.is_some() {
return Err("channel is archived".into());
}
// Lifecycle events for an ephemeral huddle belong in its parent channel.
// Resolve that parent from a creator-signed kind:48100 event instead of
// trusting the UUID supplied by the client during audio auth.
let lifecycle_parent_id = if channel.ttl_seconds.is_some() {
let parent_id = parent_channel_id.ok_or("ephemeral channel requires parent linkage")?;
let linked = state
.db
.huddle_started_link_exists(
tenant.community(),
parent_id,
channel_id,
&channel.created_by,
)
.await
.map_err(|e| format!("db error: {e}"))?;
if !linked {
return Err("ephemeral channel is not linked to claimed parent".into());
}
parent_id
} else {
channel_id
};
// Fast path: already a member.
let is_member = state
.is_member_cached(tenant.community(), channel_id, pubkey_bytes)
.await
.map_err(|e| format!("db error: {e}"))?;
if is_member {
return Ok(lifecycle_parent_id);
}
if channel.visibility == "open" {
return Ok(lifecycle_parent_id);
}
// Auto-add path: private ephemeral channel + caller is member of parent.
if channel.ttl_seconds.is_some() {
let parent_member = state
.is_member_cached(tenant.community(), lifecycle_parent_id, pubkey_bytes)
.await
.map_err(|e| format!("db error: {e}"))?;
if parent_member {
state
.db
.add_member(
tenant.community(),
channel_id,
pubkey_bytes,
MemberRole::Member,
Some(&channel.created_by),
)
.await
.map_err(|e| format!("auto-add failed: {e}"))?;
state.invalidate_membership(tenant, channel_id, pubkey_bytes);
return Ok(lifecycle_parent_id);
}
}
Err("not a member".into())
}
async fn emit_participant_event(
state: &AppState,
tenant: &TenantContext,
kind: Kind,
channel_id: Uuid,
parent_channel_id: Uuid,
participant_pubkey: &str,
) {
let content = serde_json::json!({"ephemeral_channel_id": channel_id.to_string()}).to_string();
let h_tag = match Tag::parse(["h", &parent_channel_id.to_string()]) {
Ok(t) => t,
Err(e) => {
warn!("audio: failed to parse h tag: {e}");
return;
}
};
let p_tag = match Tag::parse(["p", participant_pubkey]) {
Ok(t) => t,
Err(e) => {
warn!("audio: failed to parse p tag: {e}");
return;
}
};
let tags = vec![h_tag, p_tag];
let event = match EventBuilder::new(kind, content)
.tags(tags)
.sign_with_keys(&state.relay_keypair)
{
Ok(e) => e,
Err(e) => {
warn!("audio: failed to sign lifecycle event: {e}");
return;
}
};
let event_id_hex = event.id.to_hex();
// 1. Persist to DB so late-joining clients can reconstruct huddle state
// from historical queries. Without this, lifecycle events only exist
// for the duration of the Redis pub/sub delivery and are lost forever.
let stored = match state
.db
.insert_event(tenant.community(), &event, Some(parent_channel_id))
.await
{
Ok((stored, true)) => stored,
Ok((_, false)) => {
// Duplicate — already persisted (e.g. concurrent emit). Skip fan-out
// to avoid double-delivery, matching the side_effects.rs pattern.
debug!(
event_id = %event_id_hex,
channel_id = %parent_channel_id,
"audio lifecycle event already persisted — skipping fan-out"
);
return;
}
Err(e) => {
// DB failure during disconnect cleanup. Still broadcast so live
// subscribers see the leave/end event immediately — suppressing it
// would leave connected clients stale. Late joiners will have an
// inconsistent view until the next huddle lifecycle event lands.
warn!(
event_id = %event_id_hex,
channel_id = %parent_channel_id,
kind = %event.kind.as_u16(),
"audio: failed to persist lifecycle event: {e}"
);
StoredEvent::new(event.clone(), Some(parent_channel_id))
}
};
// 2. Mark as locally-published before Redis broadcast to prevent
// double-delivery when the event echoes back through the subscriber loop.
state.mark_local_event(tenant.community(), &event.id);
// 3. Local fan-out to WS subscribers on this node, through the guarded send
// path so a stale subscription on a removed/non-member connection cannot
// receive this channel's audio lifecycle event (same gate as
// dispatch_persistent_event in the ingest handler).
crate::handlers::event::fan_out_event_to_local_subscribers(state, tenant.community(), &stored)
.await;
// 4. Cross-node broadcast via Redis pub/sub.
if let Err(e) = state
.pubsub
.publish_event(tenant, EventTopic::Channel(parent_channel_id), &event)
.await
{
state
.local_event_ids
.invalidate(&(tenant.community(), event.id.to_bytes()));
warn!(
event_id = %event_id_hex,
channel_id = %parent_channel_id,
"audio: failed to publish lifecycle event: {e}"
);
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use axum::{routing::get, Router};
use futures_util::SinkExt;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tokio_tungstenite::{connect_async, tungstenite::Message};
use super::*;
#[test]
fn audio_connection_permits_share_the_global_websocket_budget() {
let semaphore = Arc::new(Semaphore::new(1));
let first = acquire_audio_connection_permit(&semaphore).expect("first permit");
assert!(
acquire_audio_connection_permit(&semaphore).is_none(),
"audio connections must stop when the global WebSocket budget is exhausted"
);
drop(first);
assert!(
acquire_audio_connection_permit(&semaphore).is_some(),
"dropping an audio connection must return its global permit"
);
}
async fn handler_receives_message_of_size(size: usize) -> bool {
let (received_tx, received_rx) = oneshot::channel();
let received_tx = Arc::new(Mutex::new(Some(received_tx)));
let app = Router::new().route(
"/",
get({
let received_tx = Arc::clone(&received_tx);
move |ws: WebSocketUpgrade| {
let received_tx = Arc::clone(&received_tx);
async move {
limit_audio_websocket(ws).on_upgrade(move |mut socket| async move {
let received = matches!(socket.recv().await, Some(Ok(_)));
if let Some(tx) =
received_tx.lock().expect("result lock poisoned").take()
{
let _ = tx.send(received);
}
})
}
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind test WebSocket listener");
let addr = listener.local_addr().expect("test listener address");
let server = tokio::spawn(async move {
axum::serve(listener, app)
.await
.expect("test WebSocket server");
});
let (mut client, _) = connect_async(format!("ws://{addr}/"))
.await
.expect("connect test WebSocket client");
client
.send(Message::Text("x".repeat(size).into()))
.await
.expect("send test WebSocket message");
let received = tokio::time::timeout(Duration::from_secs(2), received_rx)
.await
.expect("server should process the test message")
.expect("server should report whether it received the message");
server.abort();
let _ = server.await;
received
}
#[tokio::test]
async fn audio_send_loop_sends_policy_close_when_community_is_deleted() {
use futures_util::Sink;
struct MockSink {
messages: Arc<Mutex<Vec<WsMessage>>>,
}
impl Sink<WsMessage> for MockSink {
type Error = std::io::Error;
fn poll_ready(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn start_send(
self: std::pin::Pin<&mut Self>,
item: WsMessage,
) -> Result<(), Self::Error> {
self.messages.lock().expect("mock sink poisoned").push(item);
Ok(())
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.poll_flush(cx)
}
}
let (_data_tx, data_rx) = mpsc::channel(1);
let (_ctrl_tx, ctrl_rx) = mpsc::channel(1);
let cancel = CancellationToken::new();
let control = CommunityConnectionControl::new(cancel.clone());
let disconnect_reason = control.disconnect_reason();
let registry = crate::state::CommunityConnectionRegistry::new();
let community = buzz_core::CommunityId::from_uuid(Uuid::new_v4());
let _guard = registry.register(Uuid::new_v4(), community, control);
assert_eq!(registry.disconnect_community(community), 1);
let messages = Arc::new(Mutex::new(Vec::new()));
let sink = MockSink {
messages: Arc::clone(&messages),
};
send_loop(sink, data_rx, ctrl_rx, cancel, disconnect_reason).await;
let messages = messages.lock().expect("mock sink poisoned");
assert_eq!(messages.len(), 1);
match &messages[0] {
WsMessage::Close(Some(close)) => {
assert_eq!(close.code, axum::extract::ws::close_code::POLICY);
assert_eq!(close.reason.as_str(), "community deleted");
}
other => panic!("expected one 1008 deletion close, got {other:?}"),
}
}
#[tokio::test]
async fn audio_websocket_parser_rejects_oversized_messages_before_handler_reads_them() {
assert!(
handler_receives_message_of_size(MAX_WEBSOCKET_MESSAGE_BYTES).await,
"messages at the audio route limit should still reach the handler"
);
assert!(
!handler_receives_message_of_size(MAX_WEBSOCKET_MESSAGE_BYTES + 1).await,
"oversized messages must be rejected by the WebSocket parser before the handler sees them"
);
}
}