Rooms shows each room's media and age, and sorts by them

Admins asked which rooms fill the disk. Synapse's admin API lists a
room's media but not their sizes, so the admin script asks the database,
read only, in one query: every room's creation time, and the files its
messages link to with their size on disk (remote ones as cached). An
encrypted room's files are hidden from the server, and the card says so.
o sorts by Synapse's size, members, newest or media, keeping the cursor
on its room; the list shows the total. If the query fails, the list
loads as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vvvomitandClaude Opus 5.5 committed 2026-10-30 22:22:29 +03:30
1 parent 3a46277acb
commit 75f3f5a08d
9 files changed
+183 -26

No files matched your search

+7 -2
View File
@@ -285,8 +285,13 @@ The short list is in the [README](../README.md).
`mas-cli` in its container instead, and signing in needs only the
admin's username: MAS issues the session.
- **Rooms** (Synapse): every room the server knows of, biggest first,
with its members (and how many are from this server), size, alias and
creator. `b` blocks a room so nobody here can join it (or unblocks
with its members (and how many are from this server), size, alias,
creator, when it was created, and its media: the files its messages
link to and their size on this server's disk (other servers' files as
far as they're cached), read from the database. An encrypted room's
files are hidden from the server, so there it says so, or "at least"
for files sent before it was encrypted. The total shows above the
list, and `o` sorts by size, members, newest or media. `b` blocks a room so nobody here can join it (or unblocks
it), `h` deletes its messages older than so many days from this
server's database, keeping those sent from here, and `x` deletes the
room: everyone here is made to leave, it's purged and blocked. That
+9 -1
View File
@@ -19,6 +19,9 @@ type Room struct {
Events int // state events: what Synapse sorts rooms by size with
Public, Encrypted bool
Federated, Blocked bool
Created time.Time // zero if the database couldn't say
MediaCount int // files its messages link to; -1 if unknown
MediaBytes int64 // their size on this server's disk
}
// Title is the room's name, else its alias, else its ID.
@@ -71,6 +74,8 @@ func parseRooms(out []byte) ([]Room, error) {
Encrypted *string `json:"encryption"`
Federated bool `json:"federatable"`
Blocked bool `json:"blocked"`
Created int64 `json:"created"`
Media []int64 `json:"media"`
} `json:"rooms"`
}
if err := json.Unmarshal(out, &v); err != nil {
@@ -86,7 +91,10 @@ func parseRooms(out []byte) ([]Room, error) {
for _, r := range v.Rooms {
rooms = append(rooms, Room{ID: r.ID, Name: Printable(str(r.Name)), Alias: Printable(str(r.Alias)), Creator: Printable(r.Creator),
Members: r.Members, Local: r.Local, Events: r.Events, Public: r.Public,
Encrypted: str(r.Encrypted) != "", Federated: r.Federated, Blocked: r.Blocked})
Encrypted: str(r.Encrypted) != "", Federated: r.Federated, Blocked: r.Blocked, MediaCount: -1})
if rm := &rooms[len(rooms)-1]; len(r.Media) == 2 {
rm.Created, rm.MediaCount, rm.MediaBytes = msTime(r.Created), int(r.Media[0]), r.Media[1]
}
}
return rooms, nil
}
+6 -2
View File
@@ -5,7 +5,8 @@ import "testing"
func TestParseRooms(t *testing.T) {
out := `{"rooms": [
{"room_id": "!a:x.org", "name": "Lounge", "canonical_alias": "#lounge:x.org", "joined_members": 12, "joined_local_members": 3,
"state_events": 80, "public": true, "encryption": null, "federatable": true, "blocked": true},
"state_events": 80, "public": true, "encryption": null, "federatable": true, "blocked": true,
"created": 1700000000000, "media": [172, 24100000]},
{"room_id": "!b:x.org", "name": null, "canonical_alias": null, "joined_members": 2, "encryption": "m.megolm.v1.aes-sha2"}
], "token": "t"}`
rooms, err := parseRooms([]byte(out))
@@ -15,7 +16,10 @@ func TestParseRooms(t *testing.T) {
if r := rooms[0]; r.Title() != "Lounge" || r.Members != 12 || r.Local != 3 || !r.Blocked || r.Encrypted || !r.Public {
t.Errorf("%+v", r)
}
if r := rooms[1]; r.Title() != "!b:x.org" || !r.Encrypted {
if r := rooms[0]; r.Created.UnixMilli() != 1700000000000 || r.MediaCount != 172 || r.MediaBytes != 24100000 {
t.Errorf("dates and media: %+v", r)
}
if r := rooms[1]; r.Title() != "!b:x.org" || !r.Encrypted || r.MediaCount != -1 || !r.Created.IsZero() {
t.Errorf("%+v", r)
}
}
+36
View File
@@ -108,6 +108,35 @@ def appservices():
except Exception:
pass
return out
def room_stats():
# Each room's creation time, and the files its messages link to, as
# count and bytes on this server's disk (remote ones as far as they're
# cached). The admin API lists a room's media but not their sizes, so
# this asks the database, read only. Encrypted messages hide their files.
import yaml, psycopg2
cfg = yaml.safe_load(open("/data/homeserver.yaml"))
args = {k: v for k, v in cfg["database"]["args"].items() if k not in ("cp_min", "cp_max")}
db = psycopg2.connect(**args)
db.set_session(readonly=True)
cur = db.cursor()
cur.execute("""
WITH urls AS (
SELECT DISTINCT e.room_id, substr(ej.json::jsonb #>> '{content,url}', 7) AS mxc
FROM events e JOIN event_json ej USING (event_id)
WHERE e.contains_url AND ej.json::jsonb #>> '{content,url}' LIKE 'mxc://%%'
), media AS (
SELECT u.room_id, coalesce(l.media_length, r.media_length) AS len
FROM urls u
LEFT JOIN local_media_repository l ON split_part(u.mxc, '/', 1) = %(me)s AND l.media_id = split_part(u.mxc, '/', 2)
LEFT JOIN remote_media_cache r ON r.media_origin = split_part(u.mxc, '/', 1) AND r.media_id = split_part(u.mxc, '/', 2)
)
SELECT c.room_id, c.created, coalesce(m.n, 0), coalesce(m.bytes, 0)
FROM (SELECT room_id, min(origin_server_ts) AS created FROM events WHERE type = 'm.room.create' AND state_key = '' GROUP BY room_id) c
LEFT JOIN (SELECT room_id, count(len) AS n, sum(len) AS bytes FROM media GROUP BY room_id) m USING (room_id)
""", {"me": cfg["server_name"]})
out = {room: (created, [int(n), int(size)]) for room, created, n, size in cur.fetchall()}
db.close()
return out
def run(tok):
if req["op"] == "list":
users, frm = [], "0"
@@ -176,6 +205,13 @@ def run(tok):
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(8) as pool:
list(pool.map(blocked, rooms[:300]))
try:
stats = room_stats()
for r in rooms:
if r["room_id"] in stats:
r["created"], r["media"] = stats[r["room_id"]]
except Exception:
pass # the list without dates and media
return {"rooms": rooms}
if req["op"] == "call":
return {"result": call(req["method"], req["path"], req.get("body"), token=tok)}
+27 -4
View File
@@ -210,11 +210,34 @@ func openRooms(a *App) {
a.jump(a.index("Rooms"))
rs := a.cur().(*roomsScreen)
rs.busy, rs.loaded = false, true
day := func(y, m, d int) time.Time { return time.Date(y, time.Month(m), d, 12, 0, 0, 0, time.UTC) }
rs.list = []deploy.Room{
{ID: "!kQx:example.org", Name: "Lounge", Alias: "#lounge:example.org", Creator: "@alice:example.org", Members: 214, Local: 31, Events: 1840, Public: true, Federated: true},
{ID: "!Hw2:matrix.org", Name: "Matrix HQ", Alias: "#matrix:matrix.org", Members: 9120, Local: 2, Events: 960, Public: true, Federated: true},
{ID: "!p0d:example.org", Name: "Book club", Members: 7, Local: 7, Events: 42, Encrypted: true},
{ID: "!sp4m:spam.example", Name: "free crypto", Members: 3, Local: 1, Events: 12, Federated: true, Blocked: true},
{ID: "!kQx:example.org", Name: "Lounge", Alias: "#lounge:example.org", Creator: "@alice:example.org", Members: 214, Local: 31, Events: 1840, Public: true, Federated: true,
Created: day(2024, 3, 9), MediaCount: 172, MediaBytes: 24 << 20},
{ID: "!Hw2:matrix.org", Name: "Matrix HQ", Alias: "#matrix:matrix.org", Members: 9120, Local: 2, Events: 960, Public: true, Federated: true,
Created: day(2019, 6, 1), MediaCount: 31, MediaBytes: 6 << 20},
{ID: "!p0d:example.org", Name: "Book club", Members: 7, Local: 7, Events: 42, Encrypted: true, Created: day(2025, 11, 2)},
{ID: "!sp4m:spam.example", Name: "free crypto", Members: 3, Local: 1, Events: 12, Federated: true, Blocked: true, MediaCount: -1},
}
}
// o sorts the rooms, keeping the cursor on the same room.
func TestRoomSort(t *testing.T) {
a := demoApp(t, 120, 36)
openRooms(a)
rs := a.cur().(*roomsScreen)
rs.cursor = 1 // Matrix HQ
order := func() (out []string) {
for _, r := range rs.list {
out = append(out, r.Name)
}
return out
}
for _, want := range []string{"Matrix HQ,Lounge,Book club,free crypto", "Book club,Lounge,Matrix HQ,free crypto", "Lounge,Matrix HQ,Book club,free crypto"} {
rs.update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("o")})
if got := strings.Join(order(), ","); got != want || rs.list[rs.cursor].Name != "Matrix HQ" {
t.Errorf("by %s: %s, cursor on %s", roomSorts[rs.sortBy], got, rs.list[rs.cursor].Name)
}
}
}
+85 -4
View File
@@ -3,6 +3,7 @@ package ui
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"time"
@@ -19,7 +20,11 @@ import (
//
// Every room Synapse knows of, biggest first, with who's in it. A room can
// be blocked, deleted from the server, or have its old history deleted.
// It signs in with the admin account the Users screen uses.
// It signs in with the admin account the Users screen uses. o sorts by
// Synapse's size, members, newest or media.
// roomSorts are what o steps through; Synapse lists rooms by size.
var roomSorts = []string{"size", "members", "newest", "media"}
type roomsMsg struct {
server string
@@ -47,6 +52,7 @@ type roomsScreen struct {
form *form // how much history to delete
confirm string // "delete" or "block", for the room under the cursor
narrow bool
sortBy int
busy bool
gen int
@@ -80,7 +86,7 @@ func (s *roomsScreen) keys() [][2]string {
keys = append(keys, [2]string{"b", map[bool]string{true: "unblock", false: "block"}[r.Blocked]},
[2]string{"h", "delete old history"}, [2]string{"x", "delete room"})
}
return append(keys, [2]string{"r", "reload"})
return append(keys, [2]string{"o", "sort"}, [2]string{"r", "reload"})
}
func (s *roomsScreen) enter(c *config.Config) tea.Cmd {
@@ -183,6 +189,7 @@ func (s *roomsScreen) update(msg tea.Msg) tea.Cmd {
if m.err == nil {
s.list, s.loaded = m.list, true
s.cursor = min(s.cursor, max(0, len(s.list)-1))
s.sortRooms("")
}
return nil
case roomOpMsg:
@@ -242,6 +249,12 @@ func (s *roomsScreen) update(msg tea.Msg) tea.Cmd {
return nil
}
_, ok = s.current()
if k.String() == "o" { // sorting needs no server
r, _ := s.current()
s.sortBy = (s.sortBy + 1) % len(roomSorts)
s.sortRooms(r.ID)
return nil
}
switch k.String() {
case "r":
return s.reload()
@@ -267,6 +280,28 @@ func (s *roomsScreen) update(msg tea.Msg) tea.Cmd {
return nil
}
// sortRooms orders the list by roomSorts[sortBy], keeping the cursor on
// the room with the given ID.
func (s *roomsScreen) sortRooms(keep string) {
sort.SliceStable(s.list, func(i, j int) bool {
a, b := s.list[i], s.list[j]
switch roomSorts[s.sortBy] {
case "members":
return a.Members > b.Members
case "newest":
return a.Created.After(b.Created)
case "media":
return a.MediaBytes > b.MediaBytes
}
return a.Events > b.Events
})
for i, r := range s.list {
if r.ID == keep {
s.cursor = i
}
}
}
func (s *roomsScreen) click(id string) (tea.Cmd, bool) {
if s.form != nil || s.confirm != "" || s.busy {
return nil, false
@@ -294,7 +329,15 @@ func (s *roomsScreen) view(w, h int) string {
if !s.loaded {
return foot
}
top := sMuted.Render(fmt.Sprintf("%d rooms, biggest first", len(s.list)))
top := sMuted.Render(plural(len(s.list), "room"))
var media int64
for _, r := range s.list {
media += r.MediaBytes
}
if media > 0 {
top += sMuted.Render(" · " + humanBytes(media) + " of media")
}
top += " " + mark("key:o", keyChip("o")+sMuted.Render(" by ")+sAccent.Render(roomSorts[s.sortBy]))
listH := max(3, h-lipgloss.Height(top)-lipgloss.Height(foot)-4)
var body string
switch {
@@ -375,12 +418,44 @@ func (s *roomsScreen) rowLine(r deploy.Room, w int, on bool) string {
if r.Blocked {
name = sFaint
}
right := sMuted.Render(fmt.Sprintf("%d members", r.Members))
// What the list is sorted by, so the order makes sense at a glance.
right := sMuted.Render(plural(r.Members, "member"))
switch roomSorts[s.sortBy] {
case "newest":
if !r.Created.IsZero() {
right = sMuted.Render(r.Created.Format("2006-01-02"))
}
case "media":
right = sMuted.Render(roomMedia(r, true))
}
room := w - 3 - lipgloss.Width(right) - 2
left := roomDot(r) + " " + name.Render(truncate(r.Title(), max(6, room)))
return left + strings.Repeat(" ", max(1, w-lipgloss.Width(left)-lipgloss.Width(right))) + right
}
// roomMedia is the size of the files a room's messages link to. An
// encrypted room's are hidden from the server, so there it's at least.
func roomMedia(r deploy.Room, short bool) string {
switch {
case r.MediaCount < 0:
return "media unknown"
case r.MediaCount == 0 && r.Encrypted:
if short {
return "encrypted"
}
return sMuted.Render("hidden: encrypted")
case r.MediaCount == 0:
return "no media"
case short:
return humanBytes(r.MediaBytes)
}
out := sTitle.Render(humanBytes(r.MediaBytes)) + sMuted.Render(" in "+plural(r.MediaCount, "file"))
if r.Encrypted {
out = sMuted.Render("at least ") + out // its encrypted messages' files are hidden
}
return out
}
func (s *roomsScreen) card(r deploy.Room, w int) string {
inner := w - 4
head := roomDot(r) + " " + gradient(truncate(r.Title(), inner-4))
@@ -395,6 +470,12 @@ func (s *roomsScreen) card(r deploy.Room, w int) string {
kv := func(k, v string) { lines = append(lines, sMuted.Render(fmt.Sprintf("%-11s", k))+v) }
kv("Members", sTitle.Render(fmt.Sprint(r.Members))+sMuted.Render(fmt.Sprintf(" %d from here", r.Local)))
kv("Size", sTitle.Render(fmt.Sprint(r.Events))+sMuted.Render(" state events"))
if !r.Created.IsZero() {
kv("Created", sTitle.Render(r.Created.Format("2006-01-02")))
}
if r.MediaCount >= 0 {
kv("Media", roomMedia(r, false))
}
var tags []string
for _, t := range []struct {
on bool
+9 -9
View File
@@ -3,7 +3,7 @@
│ ▸ Setup ││ │
│ ││ Rooms on example.org │
│ ▾ Manage example.org ││ │
│ ⌂ Overview ││ 4 rooms, biggest first │
│ ⌂ Overview ││ 4 rooms · 30.0 MB of media o by size │
│ @ Users ││ │
│ ▌ # Rooms ││ ▌ # Lounge 214 members ╭────────────────────────────────────────────╮ │
│ ▦ Dashboard ││ # Matrix HQ 9120 members │ # Lounge │ │
@@ -11,14 +11,14 @@
│ ◷ Backups ││ ⊘ free crypto 3 members │ │ │
│ ⚑ Alerts ││ │ Members 214 31 from here │ │
│ ↺ Restore ││ │ Size 1840 state events │ │
│ ↶ Roll back ││ │ public │ │
│ ✎ Fine-tune ││ │ Made by @alice:example.org │ │
│ ⚒ Maintenance ││ │ ID !kQx:example.org │ │
│ ⇢ Move server ││ │ │ │
│ ▤ Servers ││ │ b block h old history x delete │ │
│ ↶ Roll back ││ │ Created 0000-00-00 │ │
│ ✎ Fine-tune ││ │ Media 24.0 MB in 172 files │ │
│ ⚒ Maintenance ││ │ public │ │
│ ⇢ Move server ││ │ Made by @alice:example.org │ │
│ ▤ Servers ││ │ ID !kQx:example.org │ │
│ ││ │ │ │
│ ▸ Mirrors ││ │ b block h old history x delete │ │
│ ││ ╰────────────────────────────────────────────╯ │
│ ▸ Mirrors ││ │
│ ││ │
│ ▸ Test ││ │
│ ││ │
│ ▸ Host ││ │
@@ -33,4 +33,4 @@
│ ◐ interzone ctrl+y ││ │
│ ◂ fold ctrl+b menu ││ │
╰────────────────────────╯╰────────────────────────────────────────────────────────────────────────────────────────────╯
↑↓ select · b block · h delete old history · x delete room · r reload · esc back · ? all keys · ctrl+c quit
↑↓ select · b block · h delete old history · x delete room · o sort · r reload · esc back · ? all keys · ctrl+c quit
+3 -3
View File
@@ -1,7 +1,7 @@
◢◤ ◆ Manage › Rooms
Rooms on example.org
4 rooms, biggest first
4 rooms · 30.0 MB of media o by size
╭──────────────────────────────────────────╮
│ # Lounge │
@@ -9,6 +9,8 @@
│ │
│ Members 214 31 from here │
│ Size 1840 state events │
│ Created 0000-00-00 │
│ Media 24.0 MB in 172 files │
│ public │
│ Made by @alice:example.org │
│ ID !kQx:example.org │
@@ -35,6 +37,4 @@
‹ back ≡ menu ⋯
+1 -1
View File
@@ -1,6 +1,6 @@
◢◤ ◆ Manage › Rooms
Rooms on example.org
4 rooms, biggest first
4 rooms · 30.0 MB of media o by size
▌ # Lounge 214 members
# Matrix HQ 9120 members