Host draws the swarm on a map of Iran, with data pulsing along each link

The node reads its peers and each one's bitswap ledger; links between
peers are a guess and the legend says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vvvomitandClaude Opus 5.5 committed 2026-10-30 19:22:59 +03:30
1 parent 0ccda18a8d
commit 39dde3c737
7 files changed
+661 -6

No files matched your search

+3 -1
View File
@@ -111,4 +111,6 @@ bundles and where files live: [docs/usage.md](docs/usage.md).
MIT, see [LICENSE](LICENSE). The playbook interzone drives,
[matrix-docker-ansible-deploy](https://github.com/spantaleev/matrix-docker-ansible-deploy),
is AGPL-3.0 and keeps its own license.
is AGPL-3.0 and keeps its own license. The Host map's IP locations are
[DB-IP Lite](https://db-ip.com/db/lite.php) (CC BY 4.0) and its borders
[Natural Earth](https://www.naturalearthdata.com/) (public domain).
+10
View File
@@ -91,6 +91,16 @@ The short list is in the [README](../README.md).
shows the swarm that it holds Matrix software, like a sharing server.
To stop: `systemctl disable --now interzone-ipfs-follow.timer interzone-ipfs`.
Below the numbers, when the window is tall enough, a map of Iran shows
the node and each peer it's connected to, placed by IP address without
going online (Iranian addresses at their town, others on the map's edge
toward their country), with pulses running along each link as data moves
in or out. The node only knows its own links: the dotted lines between
peers are a guess. A machine that runs
[interzone-mirror](https://itsjustadream.g0th.ir/vvvomit/interzone-mirror)'s
IPFS node shows that node here, and interzone won't set up a second one
on it: Host refuses, and an IPFS deploy to it uses the mirror's node.
The swarm is private: its key ships with interzone, which keeps the
public IPFS network out but isn't a secret. Its entry node is at
infamous.g0th.ir (TCP 4001, or WebSocket on yeule.g0th.ir:443). The
+81 -3
View File
@@ -6,6 +6,9 @@ import (
"context"
"encoding/json"
"fmt"
"net"
"net/netip"
"os/exec"
"slices"
"strconv"
"strings"
@@ -26,6 +29,7 @@ type HostStats struct {
Parts []string // what it hosts, from PartNames
Last string // ipfs-follow's last log line
Mirror string // the container, when the node is interzone-mirror's entry node
selfNames []string // host names the node announces, looked up into Self
Peers int
RepoSize int64
@@ -39,7 +43,17 @@ type HostStats struct {
DataReceived int64
Published string // when the newest publish the node knows was made
PublishedParts []HostPart
Wanted, Received int64 // of the parts it hosts: their size, and how much is here
Wanted, Received int64 // of the parts it hosts: their size, and how much is here
Self []netip.Addr // the node's public addresses, as it announces them
PeerList []Peer // the peers it's connected to, up to 24: each is asked for its ledger
}
// Peer is a node the hosting node is connected to, with what bitswap has
// exchanged with it.
type Peer struct {
ID string
Addr netip.Addr
Sent, Recv int64
}
// HostPart is one part of the newest publish on the node.
@@ -63,12 +77,42 @@ func ReadHostStats(ctx context.Context, t config.Target) (*HostStats, error) {
if err != nil {
return nil, fmt.Errorf("%s", lastLine(stderr.String(), err))
}
return parseHostStats(string(out)), nil
s := parseHostStats(string(out))
// A name the node announces (the mirror's PUBLIC_HOST), or failing all
// else the server's own, says where it is.
names := s.selfNames
if t.Mode == "ssh" {
names = append(names, t.Host)
}
for _, n := range names {
if len(s.Self) > 0 {
break
}
if a, err := netip.ParseAddr(n); err == nil {
s.Self = append(s.Self, a)
continue
}
ips, _ := net.DefaultResolver.LookupNetIP(ctx, "ip", n)
s.Self = append(s.Self, ips...)
}
return s, nil
}
// findMirrorNode sets c to interzone-mirror's IPFS container, if the
// machine has one, running or not.
const findMirrorNode = `c=$(docker ps -a --filter label=com.docker.compose.service=ipfs --format '{{.Names}} {{.Image}}' 2>/dev/null | awk '$2 ~ /kubo/ {print $1; exit}')`
// LocalMirrorNode is the name of interzone-mirror's IPFS container on this
// machine, if one runs; asked without sudo, as docker's group allows.
func LocalMirrorNode(ctx context.Context) string {
out, _ := exec.CommandContext(ctx, "sh", "-c", findMirrorNode+`
[ -n "$c" ] && docker inspect -f '{{.State.Running}}' "$c" | grep -q true && echo "$c"`).Output()
return strings.TrimSpace(string(out))
}
// mirrorStatsScript finds interzone-mirror's compose service ipfs (see its
// IPFS.md), which publishes every part, and reads it like a hosting node.
const mirrorStatsScript = `c=$(docker ps -a --filter label=com.docker.compose.service=ipfs --format '{{.Names}} {{.Image}}' 2>/dev/null | awk '$2 ~ /kubo/ {print $1; exit}')
const mirrorStatsScript = findMirrorNode + `
if [ -n "$c" ]; then
echo installed yes
echo mirror $c
@@ -98,6 +142,11 @@ ipfs() { runuser -u ` + ipfsUser + ` -- env IPFS_PATH=` + ipfsRepo + ` ` + ipfsB
const ipfsStatsScript = `echo peers $(ipfs swarm peers | wc -l)
echo repo $(ipfs repo stat --size-only --enc=json)
echo bw $(ipfs stats bw)
echo self $(ipfs id -f '<addrs>')
ipfs swarm peers | head -24 | while read -r a; do
l=$(ipfs bitswap ledger --enc=json "${a##*/}" </dev/null)
echo peer $a $(echo "$l" | grep -oE '"Sent":[0-9]+' | cut -d: -f2) $(echo "$l" | grep -oE '"Recv":[0-9]+' | cut -d: -f2)
done
echo bitswap "{$(ipfs stats bitswap --enc=json | grep -oE '"(BlocksSent|DataSent|BlocksReceived|DataReceived)":[0-9]+' | paste -sd,)}"
# The newest publish: ipfs-follow pins its root directly, the mirror's
# publish recursively.
@@ -175,6 +224,35 @@ func parseHostStats(out string) *HostStats {
var x struct{ Created string }
_ = json.Unmarshal([]byte(v), &x)
s.Published = x.Created
case "self":
for _, a := range strings.Fields(v) {
f := strings.Split(a, "/") // /ip4/<ip>/tcp/4001/p2p/<id>, /dns4/<name>/…
if len(f) < 3 {
continue
}
switch f[1] {
case "ip4", "ip6":
if ip, err := netip.ParseAddr(f[2]); err == nil && ip.IsGlobalUnicast() && !ip.IsPrivate() && !slices.Contains(s.Self, ip) {
s.Self = append(s.Self, ip)
}
case "dns", "dns4", "dns6":
if !slices.Contains(s.selfNames, f[2]) {
s.selfNames = append(s.selfNames, f[2])
}
}
}
case "peer": // /ip4/<ip>/tcp/4001/p2p/<id> sent recv
f := strings.Fields(v)
parts := strings.Split(f[0], "/")
if len(parts) < 3 {
continue
}
ip, _ := netip.ParseAddr(parts[2])
p := Peer{ID: parts[len(parts)-1], Addr: ip}
if len(f) == 3 {
p.Sent, p.Recv = num(f[1]), num(f[2])
}
s.PeerList = append(s.PeerList, p)
case "mirror":
s.Mirror = v
case "root":
+16
View File
@@ -42,3 +42,19 @@ links {"Links":[{"Hash":{"/":"bafypkg"},"Name":"packages","Tsize":3000},{"Hash":
t.Fatalf("%+v", s)
}
}
func TestParseHostStatsPeers(t *testing.T) {
s := parseHostStats(`installed yes
active active
self /ip4/10.0.0.5/tcp/4001/p2p/me /ip4/2.176.0.9/tcp/4001/p2p/me /dns4/mirror.example/tcp/4001/p2p/me
peer /ip4/5.160.0.1/tcp/4001/p2p/12D3a 300 9000
peer /ip6/2a01::1/tcp/4001/p2p/12D3b
`)
if len(s.Self) != 1 || s.Self[0].String() != "2.176.0.9" || len(s.selfNames) != 1 || s.selfNames[0] != "mirror.example" {
t.Fatalf("self %v names %v", s.Self, s.selfNames)
}
if len(s.PeerList) != 2 || s.PeerList[0].ID != "12D3a" || s.PeerList[0].Sent != 300 || s.PeerList[0].Recv != 9000 ||
s.PeerList[1].Addr.String() != "2a01::1" || s.PeerList[1].Sent != 0 {
t.Fatalf("%+v", s.PeerList)
}
}
+75 -2
View File
@@ -40,6 +40,13 @@ type hostStatsMsg struct {
}
type hostTickMsg struct{ n int }
// hostFrameMsg moves the swarm map's pulses on.
type hostFrameMsg struct{}
func (hostFrameMsg) owner() string { return "Host" }
const hostFrame = 100 * time.Millisecond
func (hostStatsMsg) owner() string { return "Host" }
func (hostTickMsg) owner() string { return "Host" }
@@ -63,6 +70,50 @@ type hostScreen struct {
statsFor string // the target the stats are of
ticks int // the newest tick asked for; older ones are dropped
in, out []float64 // recent rates, bytes a second
ledger map[string][2]int64 // each peer's bitswap sent and received, at ledgerAt
ledgerAt time.Time
rates map[string]peerRate
phase float64 // seconds into the map's animation
animating bool // a hostFrameMsg is on its way
}
// mirrorHere says the form's target runs interzone-mirror's node, which
// already hosts everything.
func (s *hostScreen) mirrorHere() bool {
return s.stats != nil && s.stats.Mirror != "" && s.statsFor == targetKey(s.target())
}
// moving says whether data is moving with any peer, so the map animates.
func (s *hostScreen) moving() bool {
for _, r := range s.rates {
if r.in+r.out > 0 {
return true
}
}
return false
}
func (s *hostScreen) frame() tea.Cmd {
if s.animating || !s.visible || !s.moving() {
return nil
}
s.animating = true
return tea.Tick(hostFrame, func(time.Time) tea.Msg { return hostFrameMsg{} })
}
// readLedgers turns the peers' bitswap totals into rates since the last reading.
func (s *hostScreen) readLedgers(st *deploy.HostStats, now time.Time) {
secs := now.Sub(s.ledgerAt).Seconds()
next := map[string][2]int64{}
s.rates = map[string]peerRate{}
for _, p := range st.PeerList {
next[p.ID] = [2]int64{p.Sent, p.Recv}
if was, ok := s.ledger[p.ID]; ok && secs > 0 {
s.rates[p.ID] = peerRate{in: max(0, float64(p.Recv-was[1])/secs), out: max(0, float64(p.Sent-was[0])/secs)}
}
}
s.ledger, s.ledgerAt = next, now
}
func newHostScreen() *hostScreen {
@@ -98,6 +149,9 @@ func (s *hostScreen) keys() [][2]string {
if s.running {
return [][2]string{{"ctrl+x", "stop"}, {"↑↓", "scroll"}}
}
if s.mirrorHere() {
return [][2]string{{"↑↓", "move"}}
}
return [][2]string{{"enter", "start hosting"}, {"↑↓", "move"}}
}
@@ -208,7 +262,7 @@ func (s *hostScreen) update(msg tea.Msg) tea.Cmd {
case hostStatsMsg:
s.polling = false
if m.target != s.statsFor {
s.in, s.out = nil, nil
s.in, s.out, s.ledger, s.rates = nil, nil, nil, nil
}
if m.target != targetKey(s.target()) {
return s.tick(0) // the form moved on meanwhile
@@ -220,10 +274,15 @@ func (s *hostScreen) update(msg tea.Msg) tea.Cmd {
}
s.in = append(s.in, m.stats.RateIn)[max(0, len(s.in)+1-hostHistory):]
s.out = append(s.out, m.stats.RateOut)[max(0, len(s.out)+1-hostHistory):]
s.readLedgers(m.stats, time.Now())
if !s.visible {
return nil
}
return s.tick(5 * time.Second)
return tea.Batch(s.tick(5*time.Second), s.frame())
case hostFrameMsg:
s.animating = false
s.phase += hostFrame.Seconds()
return s.frame()
case hostTickMsg:
if s.visible && m.n == s.ticks {
return s.poll()
@@ -244,6 +303,10 @@ func (s *hostScreen) update(msg tea.Msg) tea.Cmd {
return nil
}
if m.String() == "enter" {
if s.mirrorHere() {
s.err = fmt.Errorf("%s already hosts everything here: interzone-mirror's node, below", map[bool]string{true: "this machine", false: s.target().Host}[s.target().Mode != "ssh"])
return nil
}
return s.start()
}
s.err = nil
@@ -282,6 +345,11 @@ func (s *hostScreen) view(w, h int) string {
status = append(status, strings.Split(sMuted.Width(min(w, maxFormWidth)).Render(" "+l), "\n")...)
}
status = append(status, s.statsView(w)...)
// The swarm map, below the numbers, if it still leaves the form 8 rows.
if room := h - lipgloss.Height(intro) - len(status) - 3 - 8 - 1; s.statsActive() && room >= 12 {
status = append(status, "")
status = append(status, swarmMap(s.stats, s.rates, s.phase, min(w, maxFormWidth), min(room, 24))...)
}
bottom := strings.Join(status, "\n")
formH := max(6, h-lipgloss.Height(intro)-lipgloss.Height(bottom)-3)
if s.running || s.done {
@@ -290,6 +358,11 @@ func (s *hostScreen) view(w, h int) string {
return intro + "\n\n" + s.form.View(w, formH) + "\n\n" + bottom
}
// statsActive says the form's target runs a node, so there's a swarm to draw.
func (s *hostScreen) statsActive() bool {
return s.stats != nil && s.stats.Installed && s.stats.Active && s.statsFor == targetKey(s.target())
}
// statsView is the hosting node's numbers, when the form's target hosts.
func (s *hostScreen) statsView(w int) []string {
st := s.stats
+428
View File
@@ -0,0 +1,428 @@
package ui
import (
"fmt"
"math"
"sort"
"strings"
"github.com/charmbracelet/lipgloss"
"interzone/internal/deploy"
"interzone/internal/geo"
)
// ── The Host screen's swarm map ────────────────────────────────────
//
// Iran drawn in braille dots (2×4 to a cell), the hosting node and every
// peer it's connected to placed by their IPs (geo), a line to each, and
// pulses running along them as bitswap moves data: in toward the node,
// out toward the peer. Peers abroad sit on the map's edge, toward their
// country. The node only knows its own connections; the faint dotted lines
// between peers are a guess (a small private swarm tends to connect every
// node to every other), and the legend says so.
// The part of the world drawn, in degrees, and where it's centred.
const (
mapLonMin, mapLonMax = 43.0, 64.5
mapLatMin, mapLatMax = 24.6, 40.1
iranLon, iranLat = 53.7, 32.4
)
var mapKx = math.Cos(32.4 * math.Pi / 180) // a degree of longitude is shorter here
// Layers: a cell takes the colour of the highest one drawn into it.
const (
layerFill = iota + 1
layerNeighbour
layerBorder
layerGuess
layerLink
layerLive
layerPulseIn
layerPulseOut
layerText
)
// peerRate is how fast bitswap moves data with a peer, bytes a second.
type peerRate struct{ in, out float64 }
type mapCell struct {
bits uint8
layer int
style int // index into the canvas's palette
text string // a marker or a label's letter, drawn instead of the dots
}
type mapCanvas struct {
w, h int // cells
cells []mapCell
palette []lipgloss.Style
scale float64 // dots a degree (of latitude)
ox, oy float64 // dot offset of mapLonMin, mapLatMax
}
func newMapCanvas(w, h int) *mapCanvas {
c := &mapCanvas{w: w, h: h, cells: make([]mapCell, w*h)}
gw, gh := (mapLonMax-mapLonMin)*mapKx, mapLatMax-mapLatMin
c.scale = min(float64(2*w)/gw, float64(4*h)/gh)
c.ox = (float64(2*w) - gw*c.scale) / 2
c.oy = (float64(4*h) - gh*c.scale) / 2
return c
}
func (c *mapCanvas) style(st lipgloss.Style) int {
c.palette = append(c.palette, st)
return len(c.palette) - 1
}
// project turns lon/lat into dot coordinates.
func (c *mapCanvas) project(lon, lat float64) (float64, float64) {
return c.ox + (lon-mapLonMin)*mapKx*c.scale, c.oy + (mapLatMax-lat)*c.scale
}
var brailleBit = [4][2]uint8{{0x01, 0x08}, {0x02, 0x10}, {0x04, 0x20}, {0x40, 0x80}}
func (c *mapCanvas) dot(x, y, layer, style int) {
if x < 0 || y < 0 || x >= 2*c.w || y >= 4*c.h {
return
}
cell := &c.cells[(y/4)*c.w+x/2]
cell.bits |= brailleBit[y%4][x%2]
if layer >= cell.layer {
cell.layer, cell.style = layer, style
}
}
// line draws from one dot to another, every step'th dot of it.
func (c *mapCanvas) line(x0, y0, x1, y1 float64, step, layer, style int) {
n := int(math.Max(math.Abs(x1-x0), math.Abs(y1-y0)))
for i := 0; i <= n; i += step {
t := 0.0
if n > 0 {
t = float64(i) / float64(n)
}
c.dot(int(math.Round(x0+(x1-x0)*t)), int(math.Round(y0+(y1-y0)*t)), layer, style)
}
}
// put writes text from a cell rightwards, over anything below layer.
func (c *mapCanvas) put(cx, cy int, s string, layer, style int) bool {
r := []rune(s)
cx = clampInt(cx, 0, c.w-len(r))
if cy < 0 || cy >= c.h || cx < 0 {
return false
}
for i := range r {
if cell := c.cells[cy*c.w+cx+i]; cell.text != "" || cell.layer > layer {
return false
}
}
for i, ch := range r {
c.cells[cy*c.w+cx+i] = mapCell{layer: layerText, style: style, text: string(ch)}
}
return true
}
func (c *mapCanvas) render() []string {
rows := make([]string, c.h)
for y := range c.h {
var b strings.Builder
run, runStyle := "", -1
flush := func() {
if run == "" {
return
}
if runStyle < 0 {
b.WriteString(run)
} else {
b.WriteString(c.palette[runStyle].Render(run))
}
run = ""
}
for x := range c.w {
cell := c.cells[y*c.w+x]
ch, st := " ", -1
switch {
case cell.text != "":
ch, st = cell.text, cell.style
case cell.bits != 0:
ch, st = string(rune(0x2800+int(cell.bits))), cell.style
}
if st != runStyle {
flush()
runStyle = st
}
run += ch
}
flush()
rows[y] = b.String()
}
return rows
}
// inside says whether a point is inside a ring (even-odd).
func inside(x, y float64, ring [][2]float64) bool {
in := false
for i, j := 0, len(ring)-1; i < len(ring); j, i = i, i+1 {
xi, yi, xj, yj := ring[i][0], ring[i][1], ring[j][0], ring[j][1]
if (yi > y) != (yj > y) && x < (xj-xi)*(y-yi)/(yj-yi)+xi {
in = !in
}
}
return in
}
// mapNode is a spot on the map: the hosting node, or the peers in one town
// or one country abroad.
type mapNode struct {
x, y float64 // dots
label string
abroad bool
edge string // the arrow an abroad marker points with
peers int
rate peerRate
}
// edgePoint is where the line from Iran's middle toward x, y leaves the
// map, a little inside it, and which way it points.
func (c *mapCanvas) edgePoint(x, y float64) (float64, float64, string) {
cx, cy := c.project(iranLon, iranLat)
dx, dy := x-cx, y-cy
if dx == 0 && dy == 0 {
dx = 1
}
maxX, maxY := float64(2*c.w-3), float64(4*c.h-5)
t := math.Inf(1)
for _, s := range []float64{(2 - cx) / dx, (maxX - cx) / dx, (4 - cy) / dy, (maxY - cy) / dy} {
if s > 0 && s < t {
t = s
}
}
ex, ey := cx+dx*t, cy+dy*t
arrow := "▸"
switch {
case math.Abs(ex-2) < 1:
arrow = "◂"
case math.Abs(ey-4) < 1:
arrow = "▴"
case math.Abs(ey-maxY) < 1:
arrow = "▾"
}
return ex, ey, arrow
}
// swarmMap draws the node and its peers in w×h cells (h rows of map, then
// two of legend), phase seconds into the animation.
func swarmMap(st *deploy.HostStats, rates map[string]peerRate, phase float64, w, h int) []string {
h -= 2
// As wide as the map needs at this height, if the width allows.
gw, gh := (mapLonMax-mapLonMin)*mapKx, mapLatMax-mapLatMin
w = min(w, int(math.Ceil(float64(4*h)*gw/gh/2)))
c := newMapCanvas(w, h)
fill := c.style(sFaint)
neighbour := c.style(sFaint)
border := c.style(sMuted)
guess := c.style(lipgloss.NewStyle().Foreground(cAmber))
link := c.style(lipgloss.NewStyle().Foreground(cPurple))
live := c.style(lipgloss.NewStyle().Foreground(cPurple).Bold(true))
pulseIn := c.style(lipgloss.NewStyle().Foreground(cMint).Bold(true))
pulseOut := c.style(lipgloss.NewStyle().Foreground(cPink).Bold(true))
label := c.style(sMuted)
me := c.style(sAccent)
peerIdle := c.style(sMuted)
peerLive := c.style(lipgloss.NewStyle().Foreground(cMint).Bold(true))
// Iran, filled with a light texture, and its neighbours' borders.
for y := 2; y < 4*h; y += 4 {
for x := (y / 4 % 2) * 2; x < 2*w; x += 4 { // every other cell, staggered
lon := mapLonMin + (float64(x)-c.ox)/c.scale/mapKx
lat := mapLatMax - (float64(y)-c.oy)/c.scale
for _, s := range geo.Shapes {
if s.Country == "IR" && inside(lon, lat, s.Ring) {
c.dot(x, y, layerFill, fill)
break
}
}
}
}
for _, s := range geo.Shapes {
layer, style := layerNeighbour, neighbour
if s.Country == "IR" {
layer, style = layerBorder, border
}
for i := range s.Ring {
a, b := s.Ring[i], s.Ring[(i+1)%len(s.Ring)]
x0, y0 := c.project(a[0], a[1])
x1, y1 := c.project(b[0], b[1])
c.line(x0, y0, x1, y1, 1, layer, style)
}
}
// Where the node is, and its peers, grouped by town or country.
var self *mapNode
for _, a := range st.Self {
if p, ok := geo.Locate(a); ok {
self = c.place(p, "you")
break
}
}
if self == nil {
x, y := c.project(iranLon, iranLat)
self = &mapNode{x: x, y: y, label: "you (place unknown)"}
}
groups := map[string]*mapNode{}
var nodes []*mapNode
for _, p := range st.PeerList {
where, ok := geo.Locate(p.Addr)
key := where.Country + "/" + where.Town
if !ok {
key = "?"
}
n := groups[key]
if n == nil {
if ok {
n = c.place(where, "")
} else {
x, y, arrow := c.edgePoint(c.project(iranLon, mapLatMin-10))
n = &mapNode{x: x, y: y, abroad: true, edge: arrow, label: "?"}
}
groups[key] = n
nodes = append(nodes, n)
}
n.peers++
r := rates[p.ID]
n.rate.in += r.in
n.rate.out += r.out
}
sort.SliceStable(nodes, func(i, j int) bool { return nodes[i].peers > nodes[j].peers })
// One marker a cell: a spot that lands on a taken cell moves to the
// nearest free one, the busiest first.
used := map[[2]int]bool{{int(self.x) / 2, int(self.y) / 4}: true}
for _, n := range nodes {
cx, cy := int(n.x)/2, int(n.y)/4
search:
for d := 0; d < 6; d++ {
for dy := -d; dy <= d; dy++ {
for dx := -d * 2; dx <= d*2; dx += 2 { // two apart sideways leaves room between
at := [2]int{cx + dx, cy + dy}
if (d == 0 || max(abs(dx)/2, abs(dy)) == d) && at[0] >= 0 && at[0] < w && at[1] >= 0 && at[1] < h && !used[at] {
used[at] = true
n.x, n.y = float64(at[0]*2)+0.5, float64(at[1]*4)+1.5
break search
}
}
}
}
}
// Guessed links between peers: all of them in a small swarm, else each
// to its two nearest.
for i, a := range nodes {
var near []*mapNode
for j, b := range nodes {
if j != i && (len(nodes) <= 12 && j > i || len(nodes) > 12) {
near = append(near, b)
}
}
if len(nodes) > 12 {
sort.Slice(near, func(x, y int) bool {
return math.Hypot(near[x].x-a.x, near[x].y-a.y) < math.Hypot(near[y].x-a.x, near[y].y-a.y)
})
near = near[:min(2, len(near))]
}
for _, b := range near {
c.line(a.x, a.y, b.x, b.y, 3, layerGuess, guess)
}
}
// The node's own links, and data moving along them.
for _, n := range nodes {
layer, style := layerLink, link
if n.rate.in+n.rate.out > 0 {
layer, style = layerLive, live
}
c.line(self.x, self.y, n.x, n.y, 1, layer, style)
pulses := func(rate float64, fromX, fromY, toX, toY float64, layer, style int) {
if rate <= 0 {
return
}
k := int(math.Min(4, math.Max(1, 1+math.Log10(rate/1e3)))) // 1 to 4 a line
length := math.Hypot(toX-fromX, toY-fromY)
period := math.Max(1, length/24) // seconds to cross: about 24 dots a second
for i := range k {
t := math.Mod(phase/period+float64(i)/float64(k), 1)
for tail := range 3 { // a head and a short tail behind it
tt := t - float64(tail)*1.5/math.Max(length, 1)
if tt < 0 {
continue
}
c.dot(int(math.Round(fromX+(toX-fromX)*tt)), int(math.Round(fromY+(toY-fromY)*tt)), layer, style)
}
}
}
pulses(n.rate.in, n.x, n.y, self.x, self.y, layerPulseIn, pulseIn)
pulses(n.rate.out, self.x, self.y, n.x, n.y, layerPulseOut, pulseOut)
}
// Markers, then labels where they fit.
mark := func(n *mapNode, glyph string, style int) (int, int) {
cx, cy := clampInt(int(n.x)/2, 0, w-1), clampInt(int(n.y)/4, 0, h-1)
c.cells[cy*w+cx] = mapCell{layer: layerText, style: style, text: glyph}
return cx, cy
}
for _, n := range nodes {
glyph, style := "●", peerIdle
if n.rate.in+n.rate.out > 0 {
style = peerLive
}
if n.abroad {
glyph = n.edge
}
cx, cy := mark(n, glyph, style)
text := n.label
if n.peers > 1 {
text += fmt.Sprintf(" ×%d", n.peers)
}
if !c.put(cx+1, cy, text, layerPulseOut, label) && !c.put(cx-len([]rune(text)), cy, text, layerPulseOut, label) {
c.put(cx-len([]rune(text))/2, cy+1, text, layerPulseOut, label)
}
}
cx, cy := mark(self, "◆", me)
if !c.put(cx+1, cy, self.label, layerPulseOut, me) {
c.put(cx-len([]rune(self.label)), cy, self.label, layerPulseOut, me)
}
rows := c.render()
key := func(st lipgloss.Style, glyph, what string) string { return st.Render(glyph) + sFaint.Render(" "+what) }
rows = append(rows,
key(sAccent, "◆", "this node")+" "+key(sMuted, "●", "peer")+" "+
key(lipgloss.NewStyle().Foreground(cMint).Bold(true), "⠒", "coming in")+" "+
key(lipgloss.NewStyle().Foreground(cPink).Bold(true), "⠒", "going out")+" "+key(lipgloss.NewStyle().Foreground(cAmber), "⠂⠂", "likely links, guessed"),
sFaint.Render(geo.Credit+" · borders by Natural Earth"))
return rows
}
// place puts a located address on the map: in Iran at its town, abroad on
// the edge toward its country.
func (c *mapCanvas) place(p geo.Place, label string) *mapNode {
x, y := c.project(p.Lon, p.Lat)
if p.Country == "IR" {
x, y = math.Round(x/2)*2+0.5, math.Round(y/4)*4+1.5 // the middle of its cell
if label == "" {
label = p.Town
}
return &mapNode{x: x, y: y, label: label}
}
ex, ey, arrow := c.edgePoint(x, y)
if label == "" {
label = p.Country
} else {
label += " (" + p.Country + ")"
}
return &mapNode{x: ex, y: ey, label: label, abroad: true, edge: arrow}
}
func clampInt(v, lo, hi int) int { return max(lo, min(hi, v)) }
func abs(v int) int { return max(v, -v) }
+48
View File
@@ -0,0 +1,48 @@
package ui
import (
"net/netip"
"strings"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
"interzone/internal/deploy"
)
func TestSwarmMap(t *testing.T) {
st := &deploy.HostStats{Self: []netip.Addr{netip.MustParseAddr("2.176.0.1")}, PeerList: []deploy.Peer{
{ID: "a", Addr: netip.MustParseAddr("5.160.0.1")},
{ID: "b", Addr: netip.MustParseAddr("81.169.145.1")}, // Germany: on the edge
{ID: "c", Addr: netip.MustParseAddr("10.0.0.1")}, // nowhere: "?"
}}
rows := swarmMap(st, map[string]peerRate{"b": {out: 1e6}}, 0.5, 80, 24)
if len(rows) != 24 {
t.Fatalf("%d rows, want 24", len(rows))
}
text := ansi.Strip(strings.Join(rows, "\n"))
for _, want := range []string{"◆you", "DE", "?", "DB-IP"} {
if !strings.Contains(text, want) {
t.Errorf("no %q in\n%s", want, text)
}
}
for _, r := range rows {
if w := ansi.StringWidth(r); w > 80 {
t.Errorf("a row is %d wide", w)
}
}
}
func TestReadLedgers(t *testing.T) {
s := &hostScreen{}
t0 := time.Now()
s.readLedgers(&deploy.HostStats{PeerList: []deploy.Peer{{ID: "a", Sent: 100, Recv: 1000}}}, t0)
s.readLedgers(&deploy.HostStats{PeerList: []deploy.Peer{{ID: "a", Sent: 600, Recv: 1000}, {ID: "b", Recv: 50}}}, t0.Add(5*time.Second))
if r := s.rates["a"]; r.out != 100 || r.in != 0 {
t.Fatalf("a: %+v", r)
}
if _, ok := s.rates["b"]; ok || !s.moving() {
t.Fatalf("a new peer has no rate yet: %+v", s.rates)
}
}