diff options
| -rw-r--r-- | gleam/gossip/Makefile | 8 | ||||
| -rw-r--r-- | gleam/gossip/README.md | 330 | ||||
| -rw-r--r-- | gleam/gossip/src/client.gleam | 4 | ||||
| -rw-r--r-- | gleam/gossip/src/gossip.gleam | 111 | ||||
| -rw-r--r-- | gleam/gossip/src/p2p_peer.gleam | 37 | ||||
| -rw-r--r-- | gleam/gossip/src/registry.gleam | 298 | ||||
| -rw-r--r-- | gleam/gossip/src/validation.gleam | 95 | ||||
| -rw-r--r-- | gleam/gossip/test/gossip_test.gleam | 142 |
8 files changed, 443 insertions, 582 deletions
diff --git a/gleam/gossip/Makefile b/gleam/gossip/Makefile index 5938bee..0233bae 100644 --- a/gleam/gossip/Makefile +++ b/gleam/gossip/Makefile @@ -1,4 +1,4 @@ -.PHONY: build install uninstall clean help check-deps +.PHONY: build test install uninstall clean help check-deps # Colors for output BLUE := \033[0;34m @@ -15,6 +15,7 @@ help: @echo "" @echo "Available targets:" @echo " $(GREEN)build$(NC) - Compile the project (checks dependencies)" + @echo " $(GREEN)test$(NC) - Run the test suite" @echo " $(GREEN)install$(NC) - Install gossip wrapper to $(INSTALL_PATH)/$(BINARY_NAME)" @echo " $(GREEN)uninstall$(NC) - Remove installed binary" @echo " $(GREEN)clean$(NC) - Remove build artifacts" @@ -56,6 +57,11 @@ build: check-deps gleam build @echo "$(GREEN)✓ Build complete$(NC)" +test: check-deps + @echo "$(BLUE)Running tests...$(NC)" + gleam test + @echo "$(GREEN)✓ Tests passed$(NC)" + install: build @echo "$(BLUE)Installing $(BINARY_NAME) to $(INSTALL_PATH)/...$(NC)" @if [ ! -w $(INSTALL_PATH) ]; then \ diff --git a/gleam/gossip/README.md b/gleam/gossip/README.md index 88ad662..3038455 100644 --- a/gleam/gossip/README.md +++ b/gleam/gossip/README.md @@ -1,327 +1,107 @@ # Gossip: P2P Chat -A decentralized peer-to-peer chat system. Multiple peers connect via Erlang's distributed protocol with no central server. Built with Gleam and the BEAM VM. +A decentralized peer-to-peer chat system built with Gleam on the BEAM VM. Peers connect directly using Erlang's distributed protocol — no central server. -## Features +## Prerequisites -- **No central server** - every peer is independent and equal -- **Works anywhere** - same machine, local network, or across the internet -- **Loop-free messaging** - origin tracking prevents infinite message echoes -- **Eventually consistent** - all peers converge to the same state via gossip -- **Type-safe** - Gleam's compiler prevents entire categories of bugs -- **Built on proven tech** - Erlang has 30+ years of production-grade distributed systems +- **Erlang/OTP 25+**: `brew install erlang` / `sudo apt-get install erlang` +- **Gleam** (to build): `brew install gleam` / [gleam.run/getting-started](https://gleam.run/getting-started/) ## Quick Start -### Prerequisites - -**Erlang/OTP 25+** is the only runtime dependency. - -Install: -- **macOS**: `brew install erlang` -- **Ubuntu/Debian**: `sudo apt-get install erlang` -- **Other**: [erlang.org/downloads](https://www.erlang.org/downloads) - -### Setup & Run - ```bash -git clone <gossip-repo> +git clone <repo> cd gossip make build -# Option 1: Run from project directory -./bin/gossip alice -./bin/gossip bob alice@127.0.0.1 - -# Option 2: Install system-wide -make install -gossip alice -gossip bob alice@127.0.0.1 -``` - -### Example: Same Machine (Localhost) - -```bash # Terminal 1 ./bin/gossip alice -# Terminal 2 +# Terminal 2 ./bin/gossip bob alice@127.0.0.1 ``` -Type messages in either terminal. They appear as `[sender] message`. Each message displays exactly once (no duplicates). - -Commands: -- `/list` - Show connected peers -- `/quit` or `/leave` - Gracefully exit -- `Ctrl+D` - Force exit - -## How It Works - -### Architecture - -Each peer runs two actors (lightweight processes): - -``` -Peer -├── Client Actor -│ └── Receives and displays ChatMessages -└── Registry Actor - ├── Maintains list of known clients - ├── Maintains list of connected peers - └── Routes and propagates messages -``` - -### Message Flow - -1. **User types** → input_loop reads message -2. **Local registry** receives message with `is_local=True` - - Does NOT display (terminal already echoed the input) - - Marks message as seen (prevents re-display if bounced back) - - Forwards to all connected peers with `is_local=False` -3. **Remote registries** receive with `is_local=False` - - Display to their user - - Forward to their peers (except sender, tracked via `last_sender_id`) -4. **Loop prevention**: Two-part tracking prevents infinite echoes - - `origin_id`: Who created the message (immutable) - - `last_sender_id`: Who just forwarded it to us (updated each hop) - - When forwarding: skip the sender to prevent bouncing back - -### Example: Message Flow with 3 Peers - -``` -Alice types "hello" - ↓ -Alice's registry sends to [Bob, Carol] - ↓ -Bob's registry: displays "hello", forwards to [Carol] -Carol's registry: displays "hello", forwards to [Bob] (but Bob skips it back) - ↓ -Everyone sees [Alice] hello -``` - -### Network Topology - -Peers form a **mesh network** - each peer knows about all other peers and can communicate with any of them directly. This is efficient for small networks (3-20 peers). For larger networks, a hierarchical topology would be needed. - -### Distributed Mode - -Peers communicate via **Erlang's distributed protocol**, which uses: -- `-sname` flags to identify peers on the network -- Port 4369 (EPMD) for service discovery -- Random ports 9000-9100 for peer communication -- Shared "cookies" for authentication - -This is why `./bin/gossip alice@192.168.1.10` works - Erlang handles all the networking transparently. - ## Usage -**Same machine (3 peers):** +**Same machine:** ```bash -./bin/gossip alice # Terminal 1 -./bin/gossip bob alice@127.0.0.1 # Terminal 2 -./bin/gossip carol alice@127.0.0.1 # Terminal 3 +./bin/gossip alice # first peer +./bin/gossip bob alice@127.0.0.1 # each subsequent peer +./bin/gossip carol alice@127.0.0.1 ``` **Different machines:** ```bash -./bin/gossip alice --network # Machine 1 -./bin/gossip bob alice@machine1.local # Machine 2 (or alice@192.168.1.10) -``` - -**After `make install`, use `gossip` directly:** -```bash -gossip alice -gossip bob alice@127.0.0.1 +./bin/gossip alice --network # first peer — binds to FQDN, not localhost +./bin/gossip bob alice@machine.local # or alice@192.168.1.10 ``` -## Building & Distribution +**After `make install`**, use `gossip` directly from any directory. -### Build from Source +## Commands -```bash -make build -``` +| Command | Action | +|---|---| +| `/list` | Show connected peers | +| `/help` | Show this list | +| `/quit` | Leave the network | +| `Ctrl+D` | Force exit | -Outputs compiled bytecode to `build/dev/erlang/`. +## Message Format -### Install System-Wide - -```bash -make install -``` +Messages display as `[HH:MM:SS] [sender] text`. Each message appears exactly once per peer — the gossip protocol deduplicates across network cycles. -Copies wrapper script to `/usr/local/bin/gossip`. You can then run from anywhere: -```bash -gossip alice -``` - -To uninstall: -```bash -make uninstall -``` - -### Share with Others - -**Option 1: Give them the git repo** -```bash -git clone <your-gossip-repo> -cd gossip -make install -``` - -**Option 2: Create a custom binary** -The `bin/gossip` is a portable shell script. You can: -1. Package the entire project directory -2. Users run `make install` to set it up -3. Or copy `bin/gossip` to their PATH - -**Requirements for sharing:** -- Recipient must have Erlang/OTP 25+ installed -- Works on macOS, Linux, and most Unix systems -- Windows users can use WSL2 or Docker - -## Architecture & Design - -### Invariants (Always True) - -1. Each registry's client list eventually converges to the same set -2. Messages are delivered at most once per peer (origin tracking) -3. Messages flow through all connected peers -4. No single point of failure (truly decentralized) - -### Loop Prevention Proof - -Each message includes: -- `origin_id`: Registry ID of original sender (immutable) -- `last_sender_id`: Registry ID of peer that forwarded it (changes each hop) - -When forwarding a message: -1. Check if `last_sender_id` matches our registry ID -2. If yes: skip forwarding (we're the last sender, would echo back) -3. If no: forward with `last_sender_id` = our registry ID +## How It Works -This prevents immediate echo-back AND handles cycles in the mesh: -``` -A → B → C → B (receiving from C, B's ID != C's ID, so B would forward) -But B checks: is last_sender_id (from C) == B's ID? No. -So B would forward back to C... except C isn't in the list to forward to. -Actually: B filters peers using last_sender_id to skip the sender. -Result: Message doesn't loop infinitely. -``` +Each peer runs two actors: +- **Client** — displays messages to the terminal +- **Registry** — maintains peer list, routes messages, enforces deduplication -### Eventually Consistent Gossip +**Message flow:** +1. User types → message is echoed locally as `[time] [you] text` (terminal echo is suppressed to avoid garbled output when peers write simultaneously) +2. Registry broadcasts to all peers with `origin_id` (creator) and `last_sender_id` (last hop) +3. Each receiving peer displays the message, then forwards to all *except* the sender +4. Peers skip messages they've already seen — dedup key is `(origin_id, sender, text, timestamp)` -When peers connect: -1. New peer sends `PeerJoin` to existing peer -2. Existing peer responds with `PeerAck` + sends `Gossip` message -3. Gossip contains list of all known clients and peers -4. New peer merges this information with their local state -5. Gossip messages are **idempotent** - applying twice = applying once +**Network topology:** Full mesh — every peer connects directly to every other peer. Suitable for small networks (~20 peers). -This ensures all peers eventually have the same view of who's online. +**Peer discovery:** When a new peer joins, existing peers share their full peer list via gossip. The new peer then connects to everyone in the list, forming a complete mesh automatically. ## Code Organization | File | Purpose | -|------|---------| -| `src/gossip.gleam` | Entry point, CLI, validation | -| `src/p2p_peer.gleam` | Peer startup, input handling | +|---|---| +| `src/gossip.gleam` | Entry point, CLI | +| `src/validation.gleam` | Name/address validation, registry ID hashing | +| `src/p2p_peer.gleam` | Peer startup, user input loop | | `src/client.gleam` | Message display actor | -| `src/registry.gleam` | Message routing, deduplication, gossip | +| `src/registry.gleam` | Message routing, deduplication, gossip protocol | | `src/messages.gleam` | Message type definitions | | `src/gossip_utils.erl` | Erlang FFI utilities | -| `bin/gossip_wrapper` | Unix wrapper script | - -**Total**: ~1350 lines of code - -## Extending - -Possible enhancements: -- **Persistence**: Add message history storage in `registry.gleam` -- **Authentication**: Add credentials to `PeerJoin` message -- **Encryption**: Use Gleam crypto library in `propagate_broadcasts` -- **Private messages**: Add `PrivateMessage` type in `messages.gleam` -- **Partial mesh**: For many peers (100+), don't connect to all peers - -## Troubleshooting - -### "Erlang/OTP is not installed" +| `bin/gossip` | Shell wrapper (sets Erlang flags, locates build dir) | -Install Erlang first (see Prerequisites section above). +## Building -### "Could not connect to node: alice@hostname" - -Check: -1. Is the peer running? Start it with: `gossip alice` -2. Network connectivity: `ping alice-machine.local` or `ping 192.168.1.10` -3. Firewall blocking EPMD (port 4369) or node ports (9000-9100)? - -### "modules not found" - -Rebuild: ```bash -make clean -make build +make build # compile +make test # run tests +make install # copy bin/gossip to /usr/local/bin +make uninstall # remove it +make clean # remove build artifacts ``` -### Peers don't see each other's messages - -1. Verify connection: Bootstrap peer should show `To connect from another machine...`, connecting peer should show `Joined peer: ...` -2. Check network: Both on same network? Firewall allows communication? -3. Try different bootstrap peer or address format - -### My hostname isn't resolving +## Troubleshooting -Use IP address instead: -```bash -gossip Bob alice@192.168.1.10 -``` +**"Could not connect to node: alice@hostname"** +- Is the peer running? → `./bin/gossip alice` +- Network reachable? → `ping hostname` +- Firewall blocking EPMD (port 4369) or Erlang ports (9000–9100)? -Or add hostname to `/etc/hosts`: +**"modules not found"** ```bash -192.168.1.10 alice-machine.local +make clean && make build ``` -## Design Decisions - -### Why Erlang/BEAM? - -- **Proven concurrency**: Erlang has 30+ years of experience with distributed systems -- **Fault tolerance**: "Let it crash" philosophy with supervisor trees -- **Transparent distribution**: Erlang handles networking automatically -- **Scalability**: Can handle thousands of lightweight processes - -### Why Gleam? - -- **Type safety**: Compile-time guarantees prevent entire categories of bugs -- **Functional**: Immutability makes concurrent code safer -- **Modern**: Better syntax than Erlang while maintaining compatibility - -### Why Shell Wrapper Instead of Escript? - -- **Simplicity**: Auditable shell code -- **Portability**: Works on any Unix system -- **Flexibility**: Easy to modify for custom configurations -- **Build transparency**: Users see what actually runs - -### Loop Prevention via Origin Tracking - -Alternative approaches considered: -- TTL (Time-To-Live): Less elegant, requires coordinating TTL values -- DLQ (Dead Letter Queue): Complex, requires persistence -- Spanning tree: Overkill for small mesh networks -- Origin + Last Sender: Simple, elegant, works perfectly - -## License - -Open source - use for educational and personal projects. - -## Architecture References - -- **Gossip Protocols**: [Wikipedia](https://en.wikipedia.org/wiki/Gossip_protocol) -- **Erlang/OTP**: [erlang.org](https://www.erlang.org/) -- **Gleam**: [gleam.run](https://gleam.run/) -- **BEAM VM**: [Erlang Documentation](https://www.erlang.org/doc/) -- **Distributed Systems**: [Designing Data-Intensive Applications](https://dataintensive.net/) - +**Peers don't see each other's messages** +- Connecting peer should print `Joined peer: alice@...` on success +- For cross-machine connections, the first peer must use `--network` so it binds to the network interface rather than localhost diff --git a/gleam/gossip/src/client.gleam b/gleam/gossip/src/client.gleam index ab1e368..33c86f7 100644 --- a/gleam/gossip/src/client.gleam +++ b/gleam/gossip/src/client.gleam @@ -31,8 +31,8 @@ fn loop(subject: process.Subject(messages.Message)) -> Nil { let msg = process.receive_forever(subject) case msg { - messages.ChatMessage(from, text, _timestamp) -> { - io.println("[" <> from <> "] " <> text) + messages.ChatMessage(from, text, timestamp) -> { + io.println("[" <> timestamp <> "] [" <> from <> "] " <> text) loop(subject) } messages.UserJoinMessage(name) -> { diff --git a/gleam/gossip/src/gossip.gleam b/gleam/gossip/src/gossip.gleam index e40e48c..ce275de 100644 --- a/gleam/gossip/src/gossip.gleam +++ b/gleam/gossip/src/gossip.gleam @@ -1,9 +1,9 @@ import gleam/erlang/charlist import gleam/io -import gleam/list import gleam/option.{None, Some} import gleam/string import p2p_peer +import validation /// Main entry point for interactive mode. /// @@ -93,7 +93,7 @@ pub fn main_with_args(peer_name: String, bootstrap_peer: String) -> Nil { /// 5. If bootstrap peer provided, connect to them /// 6. Start input loop to read user messages fn run_peer(name: String, remote_name: option.Option(String)) -> Nil { - let validated_name = validate_peer_name(name) + let validated_name = validation.validate_peer_name(name) case validated_name { Error(msg) -> { @@ -102,7 +102,7 @@ fn run_peer(name: String, remote_name: option.Option(String)) -> Nil { Ok(clean_name) -> { // Validate remote name if provided let remote_validation = case remote_name { - Some(remote) -> validate_remote_peer(remote) + Some(remote) -> validation.validate_remote_peer(remote) None -> Ok(Nil) } @@ -113,7 +113,7 @@ fn run_peer(name: String, remote_name: option.Option(String)) -> Nil { Ok(Nil) -> { // Generate registry_id from peer name hash to ensure uniqueness // Uses string length + char codes to reduce collisions (much better than just length) - let registry_id = hash_peer_name(clean_name) + let registry_id = validation.hash_peer_name(clean_name) // Start the peer (creates client and registry actors) let #(_client_subject, registry_subject) = @@ -141,109 +141,6 @@ fn run_peer(name: String, remote_name: option.Option(String)) -> Nil { } } -/// Validate a peer name. -/// -/// Requirements: -/// - Non-empty after trimming whitespace -/// - At least 1 character, at most 32 characters -/// - Must be a valid identifier (alphanumeric + underscore) -fn validate_peer_name(name: String) -> Result(String, String) { - let trimmed = string.trim(name) - - case string.length(trimmed) { - 0 -> Error("Peer name cannot be empty") - len if len > 32 -> Error("Peer name too long (max 32 characters)") - _ -> { - // Check for valid characters: alphanumeric and underscore - case is_valid_identifier(trimmed) { - True -> Ok(trimmed) - False -> - Error("Peer name must contain only letters, numbers, and underscores") - } - } - } -} - -/// Validate a remote peer address. -/// -/// Accepts: -/// - Peer name: "alice" (alphanumeric) -/// - Node address: "alice@localhost" or "alice@192.168.1.1" -fn validate_remote_peer(remote: String) -> Result(Nil, String) { - let trimmed = string.trim(remote) - - case string.length(trimmed) { - 0 -> Error("Remote peer address cannot be empty") - len if len > 256 -> Error("Remote peer address too long") - _ -> { - // Check if it's a node address (contains @) or just a peer name - case string.contains(trimmed, "@") { - True -> { - // Node address format: peer_name@hostname - // Basic validation: should have exactly one @ - let parts = string.split(trimmed, "@") - case list.length(parts) { - 2 -> { - let peer_part = case parts { - [p, _] -> p - _ -> "" - } - case is_valid_identifier(peer_part) { - True -> Ok(Nil) - False -> Error("Invalid peer name in address: " <> peer_part) - } - } - _ -> Error("Invalid node address format (expected: peer@hostname)") - } - } - False -> { - // Just a peer name - case is_valid_identifier(trimmed) { - True -> Ok(Nil) - False -> - Error("Invalid peer name (must be alphanumeric + underscore)") - } - } - } - } - } -} - -/// Check if a string is a valid identifier. -/// Valid: alphanumeric (a-z, A-Z, 0-9) and underscore -fn is_valid_identifier(s: String) -> Bool { - let chars = string.split(s, "") - list.all(chars, fn(c) { - let is_alpha = - string.contains("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", c) - let is_digit = string.contains("0123456789", c) - let is_underscore = c == "_" - is_alpha || is_digit || is_underscore - }) -} - -/// Generate a unique registry ID from a peer name. -/// -/// Uses string length combined with sum of character codes (via Erlang binary_to_list). -/// This provides much better collision resistance than length alone. -/// Examples: -/// - "alice" (5) + (97+108+105+99+101) = 5 + 510 = 515 -/// - "bob" (3) + (98+111+98) = 3 + 307 = 310 -/// - "carol" (5) + (99+97+114+111+108) = 5 + 529 = 534 -/// -/// Collisions are still theoretically possible but extremely unlikely -/// for names used in small networks (< 1000 peers). -fn hash_peer_name(name: String) -> Int { - let len = string.length(name) - let char_sum = sum_char_codes(name) - len * 100 + char_sum -} - -/// Sum the character codes of all characters in a string. -/// Uses Erlang's binary_to_list to convert string to character codes, then sums them. -@external(erlang, "gossip_utils", "sum_char_codes") -fn sum_char_codes(str: String) -> Int - /// Read a line from stdin with a prompt. /// /// Uses Erlang's io:get_line which returns a charlist. diff --git a/gleam/gossip/src/p2p_peer.gleam b/gleam/gossip/src/p2p_peer.gleam index 08234fb..b10a884 100644 --- a/gleam/gossip/src/p2p_peer.gleam +++ b/gleam/gossip/src/p2p_peer.gleam @@ -26,22 +26,9 @@ pub fn start( } io.println("") - io.println("Ready to receive messages as: " <> name) - io.println("") - io.println("To connect from another peer, tell them to run:") - io.println("") - io.println("Same machine:") - io.println(" gossip <their-name> " <> full_node_address) - io.println("") - io.println("Different machine (replace with actual hostname/IP):") - io.println( - " gossip <their-name> " <> name <> "@<your-machine-hostname-or-ip>", - ) - io.println("") - io.println( - "Note: For cross-machine connections, the bootstrap peer must use --network flag:", - ) - io.println(" gossip " <> name <> " --network") + io.println("Ready as: " <> name <> " (" <> full_node_address <> ")") + io.println("Others connect with: gossip <name> " <> full_node_address) + io.println("Type /help for commands.") io.println("") #(client_subject, registry_subject) @@ -210,10 +197,16 @@ pub fn input_loop( input_loop(registry_subject, name, registry_id) } "/list" -> { - // List connected peers process.send(registry_subject, messages.ListPeers(0)) input_loop(registry_subject, name, registry_id) } + "/help" | "/?" -> { + io.println("Commands:") + io.println(" /list — show connected peers") + io.println(" /help — show this message") + io.println(" /quit — leave the network") + input_loop(registry_subject, name, registry_id) + } "/quit" | "/leave" -> { // User explicitly quit - notify peers and exit process.send( @@ -225,19 +218,13 @@ pub fn input_loop( exit_vm() } _ -> { - // Get current timestamp let timestamp = get_timestamp() - - // Send message to registry with: - // - origin_id = our registry_id (so other peers know it's from us) - // - last_sender_id = -1 (local input, not forwarded from peers) - // - timestamp = current time - // - is_local = True (indicates this came from local input) + // Echo own message locally (terminal echo is suppressed during input) + io.println("[" <> timestamp <> "] [" <> name <> "] " <> trimmed) process.send( registry_subject, messages.Broadcast(name, trimmed, registry_id, -1, timestamp, True), ) - input_loop(registry_subject, name, registry_id) } } diff --git a/gleam/gossip/src/registry.gleam b/gleam/gossip/src/registry.gleam index c89fd1f..713dd47 100644 --- a/gleam/gossip/src/registry.gleam +++ b/gleam/gossip/src/registry.gleam @@ -2,18 +2,18 @@ import gleam/erlang/process import gleam/list import gleam/int import gleam/io -import gleam/string import messages /// Peer information including health status for liveness detection. -/// -/// Structure: #(peer_name, registry_id, registry_subject, last_heartbeat_time, consecutive_failures) -/// - peer_name: the peer's name -/// - registry_id: unique identifier for loop prevention -/// - registry_subject: Subject to send messages to this peer -/// - last_heartbeat_time: Unix timestamp of last successful heartbeat response -/// - consecutive_failures: number of consecutive failed heartbeat pings (resets on success) -type Peer = #(String, Int, process.Subject(messages.Message), Int, Int) +type Peer { + Peer( + name: String, + registry_id: Int, + registry_subject: process.Subject(messages.Message), + last_heartbeat_time: Int, + consecutive_failures: Int, + ) +} // === Heartbeat Configuration === // Timeout for receiving messages in the main loop (milliseconds) @@ -31,42 +31,14 @@ const peer_unresponsive_threshold_s = 120 // This allows time for network issues, peer reconnection, etc. const peer_failure_threshold = 3 -// === Peer Accessor Functions === -// Extract peer fields for better readability and DRY code - -/// Get the peer's name -fn peer_name(peer: Peer) -> String { - peer.0 -} - -/// Get the peer's registry ID -fn peer_registry_id(peer: Peer) -> Int { - peer.1 -} - -/// Get the peer's registry subject -fn peer_registry(peer: Peer) -> process.Subject(messages.Message) { - peer.2 -} - -/// Get the last heartbeat timestamp -fn peer_last_heartbeat(peer: Peer) -> Int { - peer.3 -} - -/// Get the consecutive failures count -fn peer_failures(peer: Peer) -> Int { - peer.4 -} - /// Create a new peer with updated health status fn peer_with_health(peer: Peer, last_heartbeat_time: Int, failures: Int) -> Peer { - #(peer_name(peer), peer_registry_id(peer), peer_registry(peer), last_heartbeat_time, failures) + Peer(..peer, last_heartbeat_time: last_heartbeat_time, consecutive_failures: failures) } /// Check if a peer is considered healthy (not yet failed too many times) fn peer_is_healthy(peer: Peer) -> Bool { - peer_failures(peer) < peer_failure_threshold + peer.consecutive_failures < peer_failure_threshold } /// Registry state: all information a peer's registry maintains. @@ -75,9 +47,7 @@ fn peer_is_healthy(peer: Peer) -> Bool { /// - clients: always contains at least our local client /// - peers: list of other peer registries we're connected to /// - registry_id: uniquely identifies this registry for loop prevention -/// -/// Note: Message deduplication is tracked in the process dictionary (not in state) -/// because state updates don't persist across loop iterations reliably. +/// - seen_messages: bounded dedup store, capped at 1000 entries type RegistryState { RegistryState( clients: List(#(String, process.Subject(messages.Message))), @@ -85,6 +55,7 @@ type RegistryState { local_client: process.Subject(messages.Message), local_name: String, registry_id: Int, + seen_messages: List(#(Int, String, String, String)), ) } @@ -104,6 +75,7 @@ pub fn start(client_subject: process.Subject(messages.Message), name: String, re local_client: client_subject, local_name: name, registry_id: registry_id, + seen_messages: [], ) // Create a channel to communicate the subject back @@ -117,9 +89,6 @@ pub fn start(client_subject: process.Subject(messages.Message), name: String, re // Send the subject back so the caller can use it process.send(channel, registry_subject) - // Initialize the process dictionary to track seen messages - let _ = init_seen_messages_store() - // Start the loop loop(registry_subject, initial_state) }) @@ -140,35 +109,22 @@ pub fn start(client_subject: process.Subject(messages.Message), name: String, re registry_subject } -/// Initialize the seen messages store in process dictionary -fn init_seen_messages_store() -> Nil { - erl_put("seen_broadcast_ids", []) -} - /// Check if we've seen this message before -fn has_seen_message(message_id: #(Int, String, String, String)) -> Bool { - let seen = erl_get("seen_broadcast_ids") - list.contains(seen, message_id) +fn has_seen_message(message_id: #(Int, String, String, String), state: RegistryState) -> Bool { + list.contains(state.seen_messages, message_id) } -/// Mark a message as seen -fn mark_message_seen(message_id: #(Int, String, String, String)) -> Nil { - let seen = erl_get("seen_broadcast_ids") - let new_seen = [message_id, ..seen] +/// Mark a message as seen; returns updated state +fn mark_message_seen(message_id: #(Int, String, String, String), state: RegistryState) -> RegistryState { + let new_seen = [message_id, ..state.seen_messages] // Keep bounded to prevent memory leak let trimmed = case list.length(new_seen) > 1000 { True -> list.take(new_seen, 900) False -> new_seen } - erl_put("seen_broadcast_ids", trimmed) + RegistryState(..state, seen_messages: trimmed) } -@external(erlang, "erlang", "put") -fn erl_put(key: String, value: a) -> Nil - -@external(erlang, "erlang", "get") -fn erl_get(key: String) -> a - /// Check peer health and send heartbeat ping if needed. /// /// Logic: @@ -177,16 +133,16 @@ fn erl_get(key: String) -> a /// /// Returns updated peer tuple with new failure count fn check_and_ping_peer(peer: Peer, current_time: Int, local_name: String, local_registry_id: Int) -> Peer { - let time_since_last_heartbeat = current_time - peer_last_heartbeat(peer) - + let time_since_last_heartbeat = current_time - peer.last_heartbeat_time + case time_since_last_heartbeat > peer_unresponsive_threshold_s { True -> { // Peer unresponsive: increment failure counter - peer_with_health(peer, peer_last_heartbeat(peer), peer_failures(peer) + 1) + peer_with_health(peer, peer.last_heartbeat_time, peer.consecutive_failures + 1) } False -> { // Peer appears healthy: send a heartbeat ping - let _ = erlang_send(peer_registry(peer), messages.Heartbeat(local_name, local_registry_id)) + let _ = erlang_send(peer.registry_subject, messages.Heartbeat(local_name, local_registry_id)) peer } } @@ -247,80 +203,91 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil let msg = erlang_receive_with_timeout(heartbeat_check_interval_ms) case msg { - messages.PeerJoin(peer_name, peer_registry_id) -> { + messages.PeerJoin(joining_name, joining_registry_id) -> { // Peer handshake: add them to our peer list - let peer_registry = whereis_global_subject(peer_name) - case is_valid_subject(peer_registry) { + let peer_subj = whereis_global_subject(joining_name) + case is_valid_subject(peer_subj) { True -> { let current_time = get_unix_timestamp() - let new_peer: Peer = #(peer_name, peer_registry_id, peer_registry, current_time, 0) + let new_peer = Peer( + name: joining_name, + registry_id: joining_registry_id, + registry_subject: peer_subj, + last_heartbeat_time: current_time, + consecutive_failures: 0, + ) let new_peers = list.append(state.peers, [new_peer]) let new_state = RegistryState(..state, peers: new_peers) - - // Send back acknowledgement (they'll look us up in global registry) - let _ = erlang_send(peer_registry, messages.PeerAck(state.local_name, state.registry_id)) - - // Display peer join to local client - let _ = process.send(state.local_client, messages.UserJoinMessage(peer_name)) - - // Send updated peer list to the new peer - let peer_names = list.map(new_state.peers, fn(p) { p.0 }) - let _ = erlang_send(peer_registry, messages.RegistrySnapshot(peer_names)) - - // Propagate join message to other peers - let _ = list.each(state.peers, fn(p) { - erlang_send(p.2, messages.UserJoinMessage(peer_name)) - }) - - loop(subject, new_state) + + // Send back acknowledgement (they'll look us up in global registry) + let _ = erlang_send(peer_subj, messages.PeerAck(state.local_name, state.registry_id)) + + // Display peer join to local client + let _ = process.send(state.local_client, messages.UserJoinMessage(joining_name)) + + // Send updated peer list to the new peer + let peer_names = list.map(new_state.peers, fn(p) { p.name }) + let _ = erlang_send(peer_subj, messages.RegistrySnapshot(peer_names)) + + // Propagate join message to other peers + let _ = list.each(state.peers, fn(p) { + erlang_send(p.registry_subject, messages.UserJoinMessage(joining_name)) + }) + + loop(subject, new_state) } False -> loop(subject, state) } } - messages.PeerAck(peer_name, peer_registry_id) -> { + messages.PeerAck(acking_name, acking_registry_id) -> { // Peer handshake response: look them up in global registry and add to our peer list - let already_connected = list.any(state.peers, fn(p) { p.0 == peer_name }) + let already_connected = list.any(state.peers, fn(p) { p.name == acking_name }) case already_connected { True -> loop(subject, state) False -> { // Look up the responding peer's registry in the global registry - let peer_registry = whereis_global_subject(peer_name) - case is_valid_subject(peer_registry) { + let peer_subj = whereis_global_subject(acking_name) + case is_valid_subject(peer_subj) { True -> { let current_time = get_unix_timestamp() - let new_peer: Peer = #(peer_name, peer_registry_id, peer_registry, current_time, 0) + let new_peer = Peer( + name: acking_name, + registry_id: acking_registry_id, + registry_subject: peer_subj, + last_heartbeat_time: current_time, + consecutive_failures: 0, + ) let new_peers = list.append(state.peers, [new_peer]) let new_state = RegistryState(..state, peers: new_peers) - - // Send current network state to the new peer via gossip - let client_names = list.map(state.clients, fn(c) { c.0 }) - let peer_info = list.map(new_state.peers, fn(p) { #(p.0, p.1) }) - let _ = erlang_send(peer_registry, messages.Gossip(client_names, peer_info)) - - // Display peer join to local client - let _ = process.send(state.local_client, messages.UserJoinMessage(peer_name)) - - // Send updated peer list to the new peer - let peer_names = list.map(new_state.peers, fn(p) { p.0 }) - let _ = erlang_send(peer_registry, messages.RegistrySnapshot(peer_names)) - - // Propagate join message to other peers - let _ = list.each(state.peers, fn(p) { - erlang_send(p.2, messages.UserJoinMessage(peer_name)) - }) - - loop(subject, new_state) + + // Send current network state to the new peer via gossip + let client_names = list.map(state.clients, fn(c) { c.0 }) + let peer_info = list.map(new_state.peers, fn(p) { #(p.name, p.registry_id) }) + let _ = erlang_send(peer_subj, messages.Gossip(client_names, peer_info)) + + // Display peer join to local client + let _ = process.send(state.local_client, messages.UserJoinMessage(acking_name)) + + // Send updated peer list to the new peer + let peer_names = list.map(new_state.peers, fn(p) { p.name }) + let _ = erlang_send(peer_subj, messages.RegistrySnapshot(peer_names)) + + // Propagate join message to other peers + let _ = list.each(state.peers, fn(p) { + erlang_send(p.registry_subject, messages.UserJoinMessage(acking_name)) + }) + + loop(subject, new_state) } False -> { // Peer not found in global registry yet, skip for now - // They will eventually gossip to us with their info loop(subject, state) } } } } - } + } messages.ClientJoin(name, client_subject, origin_id) -> { // Client joined: add if new, propagate to other peers @@ -334,12 +301,12 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil case state.registry_id == origin_id { True -> { // Send registry snapshot to the joining client - let peer_names = list.map(state.peers, fn(p) { p.0 }) + let peer_names = list.map(state.peers, fn(p) { p.name }) let _ = process.send(state.local_client, messages.RegistrySnapshot(peer_names)) - + // Broadcast join message to all peers let _ = list.each(state.peers, fn(peer) { - erlang_send(peer.2, messages.UserJoinMessage(name)) + erlang_send(peer.registry_subject, messages.UserJoinMessage(name)) }) Nil } @@ -364,7 +331,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil // Broadcast to all peers - send ClientLeave so they can propagate it let _ = list.each(state.peers, fn(peer) { - erlang_send(peer.2, messages.ClientLeave(client_name, origin_id, state.registry_id)) + erlang_send(peer.registry_subject, messages.ClientLeave(client_name, origin_id, state.registry_id)) }) Nil } @@ -374,9 +341,9 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil // Forward leave message to other peers (not back to the peer that sent it) let _ = list.each(state.peers, fn(peer) { - case peer.1 == last_sender_id { + case peer.registry_id == last_sender_id { True -> Nil // Don't send back to the peer that relayed this to us - False -> erlang_send(peer.2, messages.ClientLeave(client_name, origin_id, state.registry_id)) + False -> erlang_send(peer.registry_subject, messages.ClientLeave(client_name, origin_id, state.registry_id)) } }) Nil @@ -387,7 +354,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil messages.Broadcast(from, text, origin_id, last_sender_id, timestamp, is_local) -> { // Broadcast message: display and forward - // + // // Message Display Strategy: // - is_local=True: DON'T display (user already sees terminal echo) // - is_local=False: Display (message from another peer, not yet visible) @@ -395,10 +362,10 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil // Message deduplication: Track ALL messages (local and network) to prevent // duplicates when messages bounce back through mesh networks. // Use (origin_id, from, text, timestamp) as unique identifier. - + let message_id = #(origin_id, from, text, timestamp) - let already_seen = has_seen_message(message_id) - + let already_seen = has_seen_message(message_id, state) + // Only display messages from OTHER peers (not local input) case !already_seen && !is_local { True -> { @@ -407,26 +374,26 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil } False -> Nil } - + // Mark as seen regardless of origin // Local messages are tracked so bouncebacks don't display again - let _ = mark_message_seen(message_id) - - case state.peers { - [] -> Nil - _peers -> { - // Filter out the peer that sent this to us (identified by last_sender_id) - let peers_to_forward = list.filter(state.peers, fn(peer) { - peer.1 != last_sender_id - }) - - // Forward with our registry_id as last_sender_id so peers know not to echo back - // Set is_local=False since we're forwarding from a peer - propagate_broadcasts(peers_to_forward, messages.Broadcast(from, text, origin_id, state.registry_id, timestamp, False)) - } - } - loop(subject, state) - } + let new_state = mark_message_seen(message_id, state) + + case new_state.peers { + [] -> Nil + _peers -> { + // Filter out the peer that sent this to us (identified by last_sender_id) + let peers_to_forward = list.filter(new_state.peers, fn(peer) { + peer.registry_id != last_sender_id + }) + + // Forward with our registry_id as last_sender_id so peers know not to echo back + // Set is_local=False since we're forwarding from a peer + propagate_broadcasts(peers_to_forward, messages.Broadcast(from, text, origin_id, new_state.registry_id, timestamp, False)) + } + } + loop(subject, new_state) + } messages.Gossip(_peer_client_names, peer_info) -> { // Gossip: learn about clients and peers from remote registries @@ -437,7 +404,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil let new_state = RegistryState(..state, peers: new_peers) // Display updated peer list to local client - let peer_names = list.map(new_state.peers, fn(p) { p.0 }) + let peer_names = list.map(new_state.peers, fn(p) { p.name }) let _ = process.send(state.local_client, messages.RegistrySnapshot(peer_names)) loop(subject, new_state) @@ -446,9 +413,9 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil messages.Heartbeat(sender_name, sender_registry_id) -> { // Heartbeat ping from another peer: respond immediately // Get the registry of the sender from our peer list - case list.find(state.peers, fn(p) { peer_name(p) == sender_name && peer_registry_id(p) == sender_registry_id }) { + case list.find(state.peers, fn(p) { p.name == sender_name && p.registry_id == sender_registry_id }) { Ok(peer) -> { - let peer_reg = peer_registry(peer) + let peer_reg = peer.registry_subject // Send HeartbeatAck back to the sender let _ = erlang_send(peer_reg, messages.HeartbeatAck(state.local_name, state.registry_id)) loop(subject, state) @@ -464,7 +431,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil // Heartbeat acknowledgement: reset peer's health status let current_time = get_unix_timestamp() let updated_peers = list.map(state.peers, fn(peer) { - case peer_name(peer) == sender_name { + case peer.name == sender_name { True -> peer_with_health(peer, current_time, 0) // Successful response: reset failures False -> peer } @@ -475,7 +442,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil messages.ListPeers(_) -> { // User requested to see list of connected peers - let peer_names = list.map(state.peers, fn(p) { p.0 }) + let peer_names = list.map(state.peers, fn(p) { p.name }) let _ = process.send(state.local_client, messages.RegistrySnapshot(peer_names)) loop(subject, state) } @@ -519,11 +486,7 @@ fn loop(subject: process.Subject(messages.Message), state: RegistryState) -> Nil /// to reach peer registries across the network. fn propagate(peers: List(Peer), msg: messages.Message) -> Nil { list.each(peers, fn(peer) { - let _name = peer.0 - let _peer_id = peer.1 - let registry_subject = peer.2 - // Use erlang_send since these are raw Pids, not proper Gleam Subjects - let _ = erlang_send(registry_subject, msg) + let _ = erlang_send(peer.registry_subject, msg) Nil }) } @@ -534,11 +497,7 @@ fn propagate(peers: List(Peer), msg: messages.Message) -> Nil { /// Uses raw Erlang ! operator to reach peer registries across the network. fn propagate_broadcasts(peers: List(Peer), msg: messages.Message) -> Nil { list.each(peers, fn(peer) { - let _name = peer.0 - let _peer_id = peer.1 - let registry_subject = peer.2 - // Use erlang_send since these are raw Pids, not proper Gleam Subjects - let _ = erlang_send(registry_subject, msg) + let _ = erlang_send(peer.registry_subject, msg) Nil }) } @@ -613,22 +572,27 @@ fn auto_discover_peers( True -> peers False -> { // Check if we already know this peer - let already_known = list.any(peers, fn(p) { p.0 == peer_name }) + let already_known = list.any(peers, fn(p) { p.name == peer_name }) case already_known { True -> peers False -> { // Try to look up and connect to this peer - let peer_registry = whereis_global_subject(peer_name) - case is_valid_subject(peer_registry) { - True -> { - // Found the peer, add them to our peer list - let current_time = get_unix_timestamp() - let new_peer: Peer = #(peer_name, peer_registry_id, peer_registry, current_time, 0) - list.append(peers, [new_peer]) + let peer_subj = whereis_global_subject(peer_name) + case is_valid_subject(peer_subj) { + True -> { + // Found the peer, add them to our peer list + let current_time = get_unix_timestamp() + let new_peer = Peer( + name: peer_name, + registry_id: peer_registry_id, + registry_subject: peer_subj, + last_heartbeat_time: current_time, + consecutive_failures: 0, + ) + list.append(peers, [new_peer]) } False -> { // Peer not found locally or on connected nodes, skip for now - // They may become available later peers } } diff --git a/gleam/gossip/src/validation.gleam b/gleam/gossip/src/validation.gleam new file mode 100644 index 0000000..361f1d8 --- /dev/null +++ b/gleam/gossip/src/validation.gleam @@ -0,0 +1,95 @@ +import gleam/list +import gleam/string + +/// Validate a peer name. +/// +/// Requirements: +/// - Non-empty after trimming whitespace +/// - At least 1 character, at most 32 characters +/// - Must be a valid identifier (alphanumeric + underscore) +pub fn validate_peer_name(name: String) -> Result(String, String) { + let trimmed = string.trim(name) + + case string.length(trimmed) { + 0 -> Error("Peer name cannot be empty") + len if len > 32 -> Error("Peer name too long (max 32 characters)") + _ -> { + case is_valid_identifier(trimmed) { + True -> Ok(trimmed) + False -> + Error("Peer name must contain only letters, numbers, and underscores") + } + } + } +} + +/// Validate a remote peer address. +/// +/// Accepts: +/// - Peer name: "alice" (alphanumeric) +/// - Node address: "alice@localhost" or "alice@192.168.1.1" +pub fn validate_remote_peer(remote: String) -> Result(Nil, String) { + let trimmed = string.trim(remote) + + case string.length(trimmed) { + 0 -> Error("Remote peer address cannot be empty") + len if len > 256 -> Error("Remote peer address too long") + _ -> { + case string.contains(trimmed, "@") { + True -> { + let parts = string.split(trimmed, "@") + case list.length(parts) { + 2 -> { + let peer_part = case parts { + [p, _] -> p + _ -> "" + } + case is_valid_identifier(peer_part) { + True -> Ok(Nil) + False -> Error("Invalid peer name in address: " <> peer_part) + } + } + _ -> Error("Invalid node address format (expected: peer@hostname)") + } + } + False -> { + case is_valid_identifier(trimmed) { + True -> Ok(Nil) + False -> + Error("Invalid peer name (must be alphanumeric + underscore)") + } + } + } + } + } +} + +/// Check if a string is a valid identifier. +/// Valid: alphanumeric (a-z, A-Z, 0-9) and underscore. +/// Note: empty string returns True (vacuous truth from list.all). +/// Callers that care about empty should check length separately. +pub fn is_valid_identifier(s: String) -> Bool { + let chars = string.split(s, "") + list.all(chars, fn(c) { + let is_alpha = + string.contains( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + c, + ) + let is_digit = string.contains("0123456789", c) + let is_underscore = c == "_" + is_alpha || is_digit || is_underscore + }) +} + +/// Generate a unique registry ID from a peer name. +/// +/// Uses erlang:phash2 for collision-resistant hashing. +/// Deterministic: same name always produces the same ID. +pub fn hash_peer_name(name: String) -> Int { + // phash2 returns 0..range-1; use 2^30 for full positive-int range + erlang_phash2(name, 1_073_741_824) +} + +@external(erlang, "erlang", "phash2") +fn erlang_phash2(term: String, range: Int) -> Int diff --git a/gleam/gossip/test/gossip_test.gleam b/gleam/gossip/test/gossip_test.gleam index fba3c88..113d622 100644 --- a/gleam/gossip/test/gossip_test.gleam +++ b/gleam/gossip/test/gossip_test.gleam @@ -1,13 +1,145 @@ import gleeunit +import gleeunit/should +import validation pub fn main() -> Nil { gleeunit.main() } -// gleeunit test functions end in `_test` -pub fn hello_world_test() { - let name = "Joe" - let greeting = "Hello, " <> name <> "!" +// === validate_peer_name === - assert greeting == "Hello, Joe!" +pub fn validate_peer_name_simple_test() { + validation.validate_peer_name("alice") + |> should.equal(Ok("alice")) } + +pub fn validate_peer_name_trims_whitespace_test() { + validation.validate_peer_name(" alice ") + |> should.equal(Ok("alice")) +} + +pub fn validate_peer_name_empty_test() { + validation.validate_peer_name("") + |> should.be_error() +} + +pub fn validate_peer_name_whitespace_only_test() { + validation.validate_peer_name(" ") + |> should.be_error() +} + +pub fn validate_peer_name_too_long_test() { + // 33 characters — one over the limit + validation.validate_peer_name("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") + |> should.be_error() +} + +pub fn validate_peer_name_invalid_char_test() { + validation.validate_peer_name("alice!") + |> should.be_error() +} + +pub fn validate_peer_name_underscore_ok_test() { + validation.validate_peer_name("alice_1") + |> should.equal(Ok("alice_1")) +} + +pub fn validate_peer_name_uppercase_ok_test() { + validation.validate_peer_name("Alice") + |> should.equal(Ok("Alice")) +} + +// === validate_remote_peer === + +pub fn validate_remote_peer_name_only_test() { + validation.validate_remote_peer("alice") + |> should.equal(Ok(Nil)) +} + +pub fn validate_remote_peer_at_localhost_test() { + validation.validate_remote_peer("alice@localhost") + |> should.equal(Ok(Nil)) +} + +pub fn validate_remote_peer_at_ip_test() { + validation.validate_remote_peer("alice@192.168.1.1") + |> should.equal(Ok(Nil)) +} + +pub fn validate_remote_peer_empty_test() { + validation.validate_remote_peer("") + |> should.be_error() +} + +pub fn validate_remote_peer_invalid_name_test() { + validation.validate_remote_peer("al!ce") + |> should.be_error() +} + +pub fn validate_remote_peer_double_at_test() { + validation.validate_remote_peer("alice@host@extra") + |> should.be_error() +} + +// === is_valid_identifier === + +pub fn is_valid_identifier_letters_test() { + validation.is_valid_identifier("hello") + |> should.be_true() +} + +pub fn is_valid_identifier_underscores_test() { + validation.is_valid_identifier("_ok_") + |> should.be_true() +} + +pub fn is_valid_identifier_digits_test() { + validation.is_valid_identifier("123") + |> should.be_true() +} + +pub fn is_valid_identifier_empty_is_true_test() { + // Vacuous truth: list.all([], ...) returns True. + // Callers must check length separately to reject empty strings. + validation.is_valid_identifier("") + |> should.be_true() +} + +pub fn is_valid_identifier_bang_test() { + validation.is_valid_identifier("hi!") + |> should.be_false() +} + +pub fn is_valid_identifier_space_test() { + validation.is_valid_identifier("hi there") + |> should.be_false() +} + +// === hash_peer_name === + +pub fn hash_peer_name_deterministic_test() { + // Same input always produces same output + validation.hash_peer_name("alice") + |> should.equal(validation.hash_peer_name("alice")) +} + +pub fn hash_peer_name_different_names_differ_test() { + let alice = validation.hash_peer_name("alice") + let bob = validation.hash_peer_name("bob") + alice + |> should.not_equal(bob) +} + +pub fn hash_peer_name_anagram_collision_test() { + // "listen" and "silent" are anagrams — same chars, same length. + // With the old len*100+sum formula they collide. This test is RED + // until Phase 2 replaces the formula with erlang:phash2. + let listen = validation.hash_peer_name("listen") + let silent = validation.hash_peer_name("silent") + listen + |> should.not_equal(silent) +} + +// === deduplicate_peers (tested via validation module indirectly through registry) === +// deduplicate_peers is internal to registry.gleam; we test it indirectly. +// If direct testing is desired, make it pub in registry.gleam. |