garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /docs/adr/028-proximity-chat.md

raw

ADR-028: Proximity Chat with Place-Derived Channels


Metadata:


Tier (ADR-031). Chat is a Simulation-tier feature: it requires a logged-in session, alongside avatars and prims. The anonymous Viewer tier has no chat.

Implemented (protocol v11): Local (proximity say/shout), Global, and Rooms — ChatSend/ChatMessage/ChatSubscribe (kinds 17–19), ChatHub routing, per-scope rate limits, SQLite scrollback for durable channels (migration V6), and the egui chat panel. Deferred to cartopolis_geo: the geo tiers (country/province/municipality) and avatar geo-authority on the sim — they slot in as extra channels behind the same resolve() with no protocol change.

Context

Problem: The sim has no chat. The obvious model — named rooms users join — is a poor fit for a world that is already situated: every avatar has a real-world lat/lng, and the interesting question is "who is near me / in my city" rather than "who joined #general". We want chat scopes derived from geography, without turning every message into a geocoding request.

Requirements:

Non-goals (deliberately deferred, see Consequences): multi-simulator chat routing, cross-sim presence, a boundary-rendering data layer, polygon-accurate boundaries, and voice/video media — this ADR is text only; real-time audio/video is a separate transport deferred behind auth (see Consequences).

Decision

Chat channels are a pure function of position, resolved server-side against a sparse place hierarchy, with a proximity tier below the administrative ones.

Five scopes, coarse to fine:

ScopeChannel keyMembership
Globalgeo:everyone
Countrygeo:iso1:NLposition
Provincegeo:iso1:NL/iso2:NL-GRposition
Municipalitygeo:iso1:NL/iso2:NL-GR/cbs:GM0014position
Local (tier 0)(none — computed per send)radius around the sender
Roomroom:<slug>explicit opt-in, non-geographic

Tier 0 exists because the smallest administrative tier is still an entire city; proximity chat is where co-presence actually reads as social.

Approach:

Place model (cartopolis_geo, new crate)

A resolved location is a sparse hierarchy, so degradation is "the list is shorter" rather than a special case:

pub struct PlacePath { levels: Vec<PlaceRef> }      // coarse → fine, may skip
pub struct PlaceRef {
    level: PlaceLevel,   // Country | Province | Municipality (extensible)
    code:  String,       // namespaced: iso1:NL, iso2:NL-GR, cbs:GM0014, osm:r47826
    name:  String,       // "Groningen"
    label: String,       // "Provincie" / "Bundesland" / "State"
}

Global is the implicit root and never appears in the vec. Mid-ocean yields an empty vec; Portugal yields one entry; Groningen yields three.

Codes are namespaced by source so two providers cannot mint the same key. These strings are channel identity and scrollback keys — a collision across a border would silently merge two cities' conversations.

level is semantic, never the raw OSM admin_level: level 4 is a provincie in NL, a Bundesland in DE, a région in FR, and absent in some countries. label carries the per-country display term as data.

Sources plug in behind a provider trait

pub trait PlaceProvider {
    fn precision(&self) -> u8;                        // centroid stub < polygons
    fn levels(&self) -> &[PlaceLevel];
    fn covers(&self, lat: f64, lng: f64) -> bool;
    fn resolve(&self, lat: f64, lng: f64) -> Vec<PlaceRef>;
}

PlaceRegistry queries every covering provider and merges per level, highest precision winning. Adding a country, swapping a data source, or running mixed precision (polygons for NL, countries-only elsewhere) is provider registration — no change to the model, protocol, or UI.

v0 ships two providers:

The upgrade to polygon-accurate municipalities is a higher-precision provider behind the same resolve() signature — a data change with zero protocol impact.

Coverage: "no data" is not "nowhere"

enum LevelResult { Resolved(PlaceRef), Outside, NoData }

NoData (no provider offers this level here — municipality in Portugal) hides the tab. Outside (covered, but inside no unit — the North Sea) shows it disabled. Without the distinction both look like a bug to the user.

Membership, hysteresis, linger

Membership is recomputed only when an avatar has moved >50 m since its last resolve — at walking speed, roughly once per avatar per 6 s, each costing microseconds. The client never asserts membership; it is told.

Positions are geo-anchored (ADR-029): prims carry an absolute f64 lat/lng, and avatar positions resolve to lat/lng the same way. The sim passes that coordinate straight to resolve() — no tangent-frame conversion, since the sim holds geo authority and has no anchor of its own.

Protocol (adds kinds 17–19, bumps PROTOCOL_VERSION; ADR-009 envelope unchanged)

enum ChatScope { Local { shout: bool }, Place(PlaceLevel), Global, Room(String) }

ChatSend     { request_id: u32, scope: ChatScope, body: String }         // kind 17
ChatMessage  { channel: String, sender_id: u64, sender_name: String,
               sent_at_ms: u64, body: String, distance_m: Option<f32> }  // kind 18
ChatChannels { channels: Vec<ChannelInfo> }                              // kind 19

ChatSend carries a scope, not a channel string — the client says "province", the server decides which province. ChatChannels is pushed whenever the resolved set changes and drives the tab strip.

Coarsening rule: a scope resolves to the nearest available level, coarsening. Asking for Province where none exists sends to Country. A message always has somewhere to land, and the client needs no per-country knowledge.

Routing, persistence, limits

Threat model (P-07)

Rationale

Primary Reasoning:

  1. Derived membership removes the entire room-management surface. No join, leave, room list, or invite paths — and no way to be in a channel you are not standing in, which satisfies P-01 by construction rather than by validation.
  2. A local lookup is the only way to make membership reliable. Reverse geocoding puts channel membership behind a service that already needs an 800 ms throttle and a 15 s → 4 m backoff ladder; a wobble would flap every user's channels. A local table cannot fail, and lets client and server compute identical answers from identical data — so tab labels can never disagree with authority near a border.
  3. The sparse hierarchy plus provider registry is cheap flexibility at the interface, not expensive flexibility in infrastructure: roughly a trait and two enums. It absorbs new countries, new sources, and the centroid → polygon upgrade without touching the wire format.
  4. Worldwide baseline, NL enhancement — the same shape ADR-027 used for 3DBAG. Global and country work anywhere; province works anywhere via Natural Earth admin_1 when added; only municipality is NL-only today. This keeps ADR-023's objection (a NL-only source baking NL assumptions into the registry's shape) from applying: the tier structure is worldwide, only the finest tier degrades.

Alternatives Considered:

AlternativeProsConsRejected Because
Named rooms users joinTrivial; familiarIgnores that every avatar already has a real positionThe world is situated; geography is the interesting axis
Nominatim reverse geocode per resolveNo bundled data10–100 ms, async, fails; client/server can disagree at bordersMembership must not inherit a throttled service's failure modes
Overpass is_in per resolveGenuine PIP service, already hostedSame latency and throttle problemsSame; useful as a build-time verification oracle instead
Polygon boundaries in v0Accurate at bordersOverpass extraction, ring assembly, simplification tolerance, pack formatDeferrable behind resolve(); ship the stub, upgrade invisibly
Raw OSM admin_level as the tier keyDirect from sourceLevel 4 means different things per country; not portableSemantic level + display label is the same cost and correct
Distance-only tiers (radius rings)No geo data at all"Everyone within 10 km" is not a community; ignores real boundariesPlaces are what users actually identify with
Multi-sim peer mesh in this ADRFuture-proofTrusted transport + directory service before auth existsInverts the roadmap's auth-first sequencing; ChatBus is the seam

Consequences

Positive:

Negative / risks:

Related