Phase 3: rooms, local only
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s

Implements PLAN.md Phase 3: the roomserver, the room half of storage, the
Client-Server room endpoints and the admin room endpoints. A client can now
create a room, invite, join, leave, kick, ban, send messages and state,
redact, name a room with an alias and find one in the public directory.
Nothing talks to another server; every operation that would need to is
refused with a message that says so rather than a bare M_FORBIDDEN.

roomserver: one input pipeline every event goes through, whatever sent it —
validate, authorise, resolve, persist, emit. The rules are not
reimplemented here; internal/matrix is pure library code and this is what
connects it to a database and to a room's history. The Client-Server
handlers do no authorisation of their own, deliberately: whether Alice may
kick Bob is a question about the room's power levels, and the one place
that is answered correctly is the authorisation rules inside the pipeline.

A mutex per room serialises writers. Two events racing into one room would
each read the same forward extremities, both become one, and fork the room
for no reason — which would then need state resolution to put back
together. State resolution is wired in anyway for the multi-extremity
case. It is unreachable from outside in this phase, and the alternative is
a pipeline that authorises against one arbitrary branch of a fork without
saying so.

Room versions 3 to 12 all work and are each tested end to end. Version 12
earns that coverage: its room ID is the create event's own ID, its create
event carries no room_id, and the create event is excluded from every other
event's auth_events — so the state auth.Check is given is the event's
auth_events plus the create event, which that version identifies by room ID
rather than citing.

createRoom sends the spec's events in the spec's order, each authorised
against what the ones before it produced. A failure part-way leaves an
incomplete room, which is the lesser evil: the alternative is holding every
event of a new room in memory and writing them in one transaction, making
the pipeline that authorises them a special case. The one failure a second
client can cause at any time, an alias clash, takes the room row back out.

Redactions stay two decisions, as the spec keeps them. The rules let almost
any redaction into the room; whether it applies to its target is a separate
test, run inside the same transaction as the redaction itself so that a
client holding an event ID can always read the stripped event.

storage: events keyed by event ID rather than by a surrogate, since an
event ID appears in prev_events, auth_events, state snapshots and client
requests alike. Stream ordering comes from a counter row bumped inside the
write transaction, because a PostgreSQL sequence is explicitly not
transactional and a rolled-back write would leave a hole in the stream that
/sync would have to be taught to skip. State snapshots are stored per event
and deduplicated by content hash, so the table grows with state changes
rather than with traffic — and that is what makes "the state after a
forward extremity" answerable at all. The room's listing columns are
denormalised onto its row because the public directory orders every
published room by member count and pages the result, which cannot be done
by reading each room's state in turn.

Federation-disabled behaviour from PLAN.md section 3 is enforced here.
Restricted joins are the exception that works: the rule needs a signature
from the authorising user's server verified, and while federation is off
that server is always this one.

adminapi: room list and detail, purge, force-leave, and room and event
counters on the dashboard. clientapi gains its own rate-limit buckets for
createRoom and for joining, both of which write events rather than read
them.

Tested against the real event core and a real database rather than fakes:
what is under test is whether an event this server signs is one the
authorisation rules accept, and a fake of either would only prove that the
pipeline calls what the fake expects. The storage tests run against both
SQL drivers. docs/rooms.md describes the pipeline, the storage decisions
and the known gaps — chief among them that history visibility is
room-level rather than per-event, and that /sync still reports no rooms,
both of which belong with the event stream in Phase 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5 committed 2026-10-16 10:34:57 +02:00
1 parent 2fbd5f53ce
commit c96f88e994
45 files changed
+9637 -42

No files matched your search

+27
View File
@@ -22,6 +22,7 @@ import (
"github.com/dariuszjaniak/warp/server/internal/buildinfo"
"github.com/dariuszjaniak/warp/server/internal/federation"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/roomserver"
"github.com/dariuszjaniak/warp/server/internal/settings"
"github.com/dariuszjaniak/warp/server/internal/storage"
"github.com/dariuszjaniak/warp/server/internal/userapi"
@@ -34,6 +35,7 @@ const Prefix = "/_warp/admin/v1"
type AdminAPI struct {
serverName string
users *userapi.API
rooms *roomserver.API
settings *settings.Service
federation *federation.Gate
database storage.Database
@@ -44,6 +46,12 @@ type AdminAPI struct {
type Options struct {
ServerName string
Users *userapi.API
// Rooms is the roomserver component. A server that started without a
// signing key has none, and the room endpoints then report that rather
// than failing on the first call.
Rooms *roomserver.API
Settings *settings.Service
Federation *federation.Gate
@@ -73,6 +81,7 @@ func New(opts Options) (*AdminAPI, error) {
return &AdminAPI{
serverName: opts.ServerName,
users: opts.Users,
rooms: opts.Rooms,
settings: opts.Settings,
federation: opts.Federation,
database: opts.Database,
@@ -89,6 +98,11 @@ func (a *AdminAPI) RegisterRoutes(r *httputil.Router) {
a.handle(r, "GET "+Prefix+"/users", a.handleGetUsers)
a.handle(r, "POST "+Prefix+"/users", a.handlePostUsers)
a.handle(r, "GET "+Prefix+"/stats", a.handleGetStats)
a.handle(r, "GET "+Prefix+"/rooms", a.handleGetRooms)
a.handle(r, "GET "+Prefix+"/rooms/{roomID}", a.handleGetRoom)
a.handle(r, "DELETE "+Prefix+"/rooms/{roomID}", a.handleDeleteRoom)
a.handle(r, "POST "+Prefix+"/rooms/{roomID}/force_leave", a.handleForceLeave)
}
// adminHandler is a handler that has already been shown to be an admin.
@@ -288,6 +302,10 @@ type statsResponse struct {
Deactivated int `json:"deactivated"`
Devices int `json:"devices"`
Rooms int `json:"rooms"`
PublishedRooms int `json:"published_rooms"`
Events int `json:"events"`
FederationEnabled bool `json:"federation_enabled"`
RegistrationEnabled bool `json:"registration_enabled"`
}
@@ -311,6 +329,15 @@ func (a *AdminAPI) handleGetStats(w http.ResponseWriter, r *http.Request, _ user
if a.database != nil {
resp.Database = a.database.Driver()
}
if a.rooms != nil {
roomStats, err := a.rooms.Stats(r.Context())
if err != nil {
return err
}
resp.Rooms = roomStats.Rooms
resp.PublishedRooms = roomStats.Published
resp.Events = roomStats.Events
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
+22 -1
View File
@@ -13,6 +13,8 @@ import (
"github.com/dariuszjaniak/warp/server/internal/adminapi"
"github.com/dariuszjaniak/warp/server/internal/federation"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/matrix/signing"
"github.com/dariuszjaniak/warp/server/internal/roomserver"
"github.com/dariuszjaniak/warp/server/internal/settings"
"github.com/dariuszjaniak/warp/server/internal/storage"
_ "github.com/dariuszjaniak/warp/server/internal/storage/drivers"
@@ -26,6 +28,7 @@ type testServer struct {
t *testing.T
handler http.Handler
users *userapi.API
rooms *roomserver.API
settings *settings.Service
}
@@ -61,9 +64,25 @@ func newTestServer(t *testing.T, defaults settings.Defaults) *testServer {
t.Fatalf("settings.New: %v", err)
}
key, err := signing.Generate("test")
if err != nil {
t.Fatalf("signing.Generate: %v", err)
}
rooms, err := roomserver.New(roomserver.Options{
ServerName: testServerName,
Store: db.Rooms(),
Profiles: users,
SigningKey: key,
Logger: slog.New(slog.DiscardHandler),
})
if err != nil {
t.Fatalf("roomserver.New: %v", err)
}
api, err := adminapi.New(adminapi.Options{
ServerName: testServerName,
Users: users,
Rooms: rooms,
Settings: settingsService,
Federation: federation.NewGate(settingsService.FederationEnabled,
federation.NewPolicy([]string{"friend.example"}, []string{"spam.example"})),
@@ -76,7 +95,9 @@ func newTestServer(t *testing.T, defaults settings.Defaults) *testServer {
router := httputil.NewRouter(nil)
api.RegisterRoutes(router)
return &testServer{t: t, handler: router, users: users, settings: settingsService}
return &testServer{
t: t, handler: router, users: users, rooms: rooms, settings: settingsService,
}
}
func (ts *testServer) do(method, path, token string, body any) *httptest.ResponseRecorder {
+249
View File
@@ -0,0 +1,249 @@
package adminapi
import (
"errors"
"net/http"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/matrix/id"
"github.com/dariuszjaniak/warp/server/internal/roomserver"
"github.com/dariuszjaniak/warp/server/internal/storage"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
// adminRoom is one row of the room list. Like the user list it is a flat
// shape, because the panel shows it as a table.
type adminRoom struct {
RoomID string `json:"room_id"`
RoomVersion string `json:"room_version"`
Creator string `json:"creator"`
Name string `json:"name,omitempty"`
Topic string `json:"topic,omitempty"`
CanonicalAlias string `json:"canonical_alias,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
RoomType string `json:"room_type,omitempty"`
JoinRule string `json:"join_rule,omitempty"`
HistoryVisibility string `json:"history_visibility,omitempty"`
GuestAccess string `json:"guest_access,omitempty"`
Published bool `json:"published"`
JoinedMembers int `json:"joined_members"`
CreatedAtMS int64 `json:"created_at_ms"`
}
type roomsResponse struct {
Rooms []adminRoom `json:"rooms"`
// Total is the number of rooms matching the query, not the number
// returned, so the panel can page.
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// defaultRoomPageLimit is what a request without ?limit= gets.
const defaultRoomPageLimit = 50
// handleGetRooms implements GET /_warp/admin/v1/rooms.
func (a *AdminAPI) handleGetRooms(w http.ResponseWriter, r *http.Request, _ userapi.Authenticated) error {
if err := a.requireRooms(); err != nil {
return err
}
query := r.URL.Query()
limit, err := intParam(query.Get("limit"), defaultRoomPageLimit)
if err != nil {
return httputil.InvalidParam("limit must be a number")
}
offset, err := intParam(query.Get("offset"), 0)
if err != nil {
return httputil.InvalidParam("offset must be a number")
}
if limit < 0 || offset < 0 {
return httputil.InvalidParam("limit and offset must not be negative")
}
summaries, total, err := a.rooms.ListRooms(r.Context(), storage.RoomFilter{
Search: query.Get("search"),
Limit: limit,
Offset: offset,
})
if err != nil {
return err
}
resp := roomsResponse{
Rooms: make([]adminRoom, 0, len(summaries)),
Total: total,
Limit: limit,
Offset: offset,
}
for _, summary := range summaries {
resp.Rooms = append(resp.Rooms, adminRoomOf(summary))
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// roomDetailResponse is GET /_warp/admin/v1/rooms/{roomID}: the list row
// plus what only a count can answer.
type roomDetailResponse struct {
adminRoom
Members int `json:"members"`
InvitedMembers int `json:"invited_members"`
Aliases []string `json:"aliases"`
// ForwardExtremities is where the room's DAG currently ends. There is
// normally exactly one; more than one means the room has forked, which
// is worth an operator seeing.
ForwardExtremities []string `json:"forward_extremities"`
}
// handleGetRoom implements GET /_warp/admin/v1/rooms/{roomID}.
func (a *AdminAPI) handleGetRoom(w http.ResponseWriter, r *http.Request, _ userapi.Authenticated) error {
roomID, err := a.pathRoomID(r)
if err != nil {
return err
}
details, err := a.rooms.RoomDetails(r.Context(), roomID)
if err != nil {
return roomError(err)
}
httputil.WriteJSON(w, http.StatusOK, roomDetailResponse{
adminRoom: adminRoomOf(details.RoomSummary),
Members: details.Members,
InvitedMembers: details.InvitedMembers,
Aliases: details.Aliases,
ForwardExtremities: details.ForwardExtremities,
})
return nil
}
// handleDeleteRoom implements DELETE /_warp/admin/v1/rooms/{roomID}: the
// purge.
//
// It is a DELETE on the room rather than a POST to an action, because that
// is what it is, and because the method makes a panel's confirm dialog
// mandatory in a way a POST does not. There is no undo: the room's events
// are deleted, and the members are not told, because the only way to tell
// them would have been to add an event to the room that no longer exists.
func (a *AdminAPI) handleDeleteRoom(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := a.pathRoomID(r)
if err != nil {
return err
}
if err := a.rooms.PurgeRoom(r.Context(), roomID); err != nil {
return roomError(err)
}
a.log.Warn("room purged through the admin API",
"room_id", roomID, "by", auth.UserID)
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// forceLeaveRequest is the POST /rooms/{roomID}/force_leave body.
type forceLeaveRequest struct {
UserID string `json:"user_id"`
}
// handleForceLeave implements POST /_warp/admin/v1/rooms/{roomID}/force_leave.
//
// It makes a user leave a room without asking the room's rules whether they
// may. A user stuck in a room — one whose power levels are broken, or whose
// last moderator has gone — is what this exists for, and in such a room the
// rules are exactly what is in the way. It is still an ordinary membership
// event, signed and added to the room, so the other members see what
// happened.
func (a *AdminAPI) handleForceLeave(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := a.pathRoomID(r)
if err != nil {
return err
}
var req forceLeaveRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.UserID == "" {
return httputil.MissingParam("A user ID is required")
}
if err := a.rooms.ForceLeave(r.Context(), roomID, req.UserID); err != nil {
return roomError(err)
}
a.log.Warn("user removed from a room through the admin API",
"room_id", roomID, "user_id", req.UserID, "by", auth.UserID)
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// adminRoomOf projects a stored room onto the list row.
func adminRoomOf(summary storage.RoomSummary) adminRoom {
return adminRoom{
RoomID: summary.ID,
RoomVersion: summary.Version,
Creator: summary.Creator,
Name: summary.Name,
Topic: summary.Topic,
CanonicalAlias: summary.CanonicalAlias,
AvatarURL: summary.AvatarURL,
RoomType: summary.RoomType,
JoinRule: summary.JoinRule,
HistoryVisibility: summary.HistoryVisibility,
GuestAccess: summary.GuestAccess,
Published: summary.Published,
JoinedMembers: summary.JoinedMembers,
CreatedAtMS: summary.CreatedAtMS,
}
}
// pathRoomID reads the {roomID} path value and insists there is a
// roomserver to ask about it.
func (a *AdminAPI) pathRoomID(r *http.Request) (string, error) {
if err := a.requireRooms(); err != nil {
return "", err
}
roomID := r.PathValue("roomID")
if err := id.ValidateRoomID(roomID); err != nil {
return "", httputil.InvalidParam("%s is not a valid room ID", roomID)
}
return roomID, nil
}
// requireRooms refuses a room endpoint on a server that started without a
// signing key, and so without a roomserver.
func (a *AdminAPI) requireRooms() error {
if a.rooms == nil {
return httputil.Unknown(http.StatusServiceUnavailable,
"This server has no signing key, so it has no rooms")
}
return nil
}
// roomError maps a roomserver error onto a Matrix error. The admin API has
// a shorter list than the Client-Server one, because an admin endpoint
// never hits the authorisation rules.
func roomError(err error) error {
var matrixErr *httputil.MatrixError
switch {
case err == nil:
return nil
case errors.As(err, &matrixErr):
return err
case errors.Is(err, roomserver.ErrNoSuchRoom):
return httputil.NotFound("Unknown room")
case errors.Is(err, roomserver.ErrNoSuchEvent):
return httputil.NotFound("Unknown event")
case errors.Is(err, roomserver.ErrForbidden), errors.Is(err, roomserver.ErrRejected):
return httputil.Forbidden("%s", err.Error())
case errors.Is(err, roomserver.ErrInvalidContent):
return httputil.BadJSON("%s", err.Error())
default:
return err
}
}
+208
View File
@@ -0,0 +1,208 @@
package adminapi_test
import (
"net/http"
"net/url"
"testing"
"github.com/dariuszjaniak/warp/server/internal/adminapi"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/roomserver"
"github.com/dariuszjaniak/warp/server/internal/settings"
)
// createRoom makes a room through the roomserver directly: the admin API
// has no createRoom, and would be the wrong place for one.
func (ts *testServer) createRoom(creator string, req roomserver.CreateRoomRequest) string {
ts.t.Helper()
req.Creator = "@" + creator + ":" + testServerName
resp, err := ts.rooms.CreateRoom(ts.t.Context(), req)
if err != nil {
ts.t.Fatalf("CreateRoom: %v", err)
}
return resp.RoomID
}
func TestAdminRoomList(t *testing.T) {
ts := newTestServer(t, settings.Defaults{})
token := ts.admin("admin")
ts.user("alice")
roomID := ts.createRoom("alice", roomserver.CreateRoomRequest{
Name: "Operations",
Preset: roomserver.PresetPublicChat,
Visibility: roomserver.VisibilityPublic,
})
ts.createRoom("alice", roomserver.CreateRoomRequest{Name: "Quiet"})
rec := ts.do(http.MethodGet, adminapi.Prefix+"/rooms", token, nil)
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if total, _ := body["total"].(float64); total != 2 {
t.Errorf("total = %v, want 2", body["total"])
}
rooms, _ := body["rooms"].([]any)
if len(rooms) != 2 {
t.Fatalf("the list has %d rooms, want 2: %s", len(rooms), rec.Body.String())
}
// The search covers the name, which is the column the panel sorts by.
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms?search=operations", token, nil)
expectStatus(t, rec, http.StatusOK)
body = jsonBody(t, rec)
rooms, _ = body["rooms"].([]any)
if len(rooms) != 1 {
t.Fatalf("the search returned %d rooms, want 1", len(rooms))
}
found, _ := rooms[0].(map[string]any)
if found["room_id"] != roomID {
t.Errorf("the search found %v, want %q", found["room_id"], roomID)
}
if found["published"] != true {
t.Errorf("the published flag is %v, want true", found["published"])
}
if found["joined_members"] != float64(1) {
t.Errorf("joined_members = %v, want 1", found["joined_members"])
}
// An ordinary user is refused, and told why rather than given a 404.
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms", ts.user("bob"), nil)
expectError(t, rec, http.StatusForbidden, httputil.ErrCodeForbidden)
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms?limit=lots", token, nil)
expectError(t, rec, http.StatusBadRequest, httputil.ErrCodeInvalidParam)
}
func TestAdminRoomDetail(t *testing.T) {
ts := newTestServer(t, settings.Defaults{})
token := ts.admin("admin")
ts.user("alice")
roomID := ts.createRoom("alice", roomserver.CreateRoomRequest{
Name: "Detailed",
Preset: roomserver.PresetPublicChat,
RoomAliasName: "detailed",
})
rec := ts.do(http.MethodGet, adminapi.Prefix+"/rooms/"+url.PathEscape(roomID), token, nil)
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if body["room_id"] != roomID || body["name"] != "Detailed" {
t.Errorf("the detail is %s", rec.Body.String())
}
if body["creator"] != "@alice:"+testServerName {
t.Errorf("creator = %v", body["creator"])
}
if body["members"] != float64(1) || body["joined_members"] != float64(1) {
t.Errorf("members = %v, joined = %v", body["members"], body["joined_members"])
}
aliases, _ := body["aliases"].([]any)
if len(aliases) != 1 {
t.Errorf("aliases = %v, want one", body["aliases"])
}
// A room filled by one server ends at a single event.
extremities, _ := body["forward_extremities"].([]any)
if len(extremities) != 1 {
t.Errorf("forward_extremities = %v, want one", body["forward_extremities"])
}
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms/"+
url.PathEscape("!nope:"+testServerName), token, nil)
expectError(t, rec, http.StatusNotFound, httputil.ErrCodeNotFound)
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms/not-a-room", token, nil)
expectError(t, rec, http.StatusBadRequest, httputil.ErrCodeInvalidParam)
}
func TestAdminPurgeRoom(t *testing.T) {
ts := newTestServer(t, settings.Defaults{})
token := ts.admin("admin")
ts.user("alice")
roomID := ts.createRoom("alice", roomserver.CreateRoomRequest{Name: "Doomed"})
escaped := url.PathEscape(roomID)
// An ordinary user cannot destroy a room.
rec := ts.do(http.MethodDelete, adminapi.Prefix+"/rooms/"+escaped, ts.user("bob"), nil)
expectError(t, rec, http.StatusForbidden, httputil.ErrCodeForbidden)
rec = ts.do(http.MethodDelete, adminapi.Prefix+"/rooms/"+escaped, token, nil)
expectStatus(t, rec, http.StatusOK)
rec = ts.do(http.MethodGet, adminapi.Prefix+"/rooms/"+escaped, token, nil)
expectError(t, rec, http.StatusNotFound, httputil.ErrCodeNotFound)
// Purging twice is a 404, not a silent success: an operator who sees
// an OK has to be able to believe the room was there.
rec = ts.do(http.MethodDelete, adminapi.Prefix+"/rooms/"+escaped, token, nil)
expectError(t, rec, http.StatusNotFound, httputil.ErrCodeNotFound)
}
func TestAdminForceLeave(t *testing.T) {
ts := newTestServer(t, settings.Defaults{})
token := ts.admin("admin")
ts.user("alice")
ts.user("bob")
roomID := ts.createRoom("alice", roomserver.CreateRoomRequest{Preset: roomserver.PresetPublicChat})
escaped := url.PathEscape(roomID)
bobID := "@bob:" + testServerName
if _, err := ts.rooms.JoinRoom(t.Context(), roomserver.JoinRequest{
RoomID: roomID, User: bobID,
}); err != nil {
t.Fatalf("bob joining: %v", err)
}
rec := ts.do(http.MethodPost, adminapi.Prefix+"/rooms/"+escaped+"/force_leave",
token, map[string]any{"user_id": bobID})
expectStatus(t, rec, http.StatusOK)
membership, err := ts.rooms.Membership(t.Context(), roomID, bobID)
if err != nil {
t.Fatalf("Membership: %v", err)
}
if membership != "leave" {
t.Errorf("bob's membership is %q, want leave", membership)
}
// A user who is not in the room has nothing to leave.
rec = ts.do(http.MethodPost, adminapi.Prefix+"/rooms/"+escaped+"/force_leave",
token, map[string]any{"user_id": "@carol:" + testServerName})
expectError(t, rec, http.StatusForbidden, httputil.ErrCodeForbidden)
rec = ts.do(http.MethodPost, adminapi.Prefix+"/rooms/"+escaped+"/force_leave",
token, map[string]any{})
expectError(t, rec, http.StatusBadRequest, httputil.ErrCodeMissingParam)
}
// TestAdminStatsCountsRooms checks the dashboard counters follow the rooms.
func TestAdminStatsCountsRooms(t *testing.T) {
ts := newTestServer(t, settings.Defaults{})
token := ts.admin("admin")
ts.user("alice")
rec := ts.do(http.MethodGet, adminapi.Prefix+"/stats", token, nil)
expectStatus(t, rec, http.StatusOK)
if rooms, _ := jsonBody(t, rec)["rooms"].(float64); rooms != 0 {
t.Errorf("a fresh server reports %v rooms, want 0", rooms)
}
ts.createRoom("alice", roomserver.CreateRoomRequest{
Preset: roomserver.PresetPublicChat,
Visibility: roomserver.VisibilityPublic,
})
rec = ts.do(http.MethodGet, adminapi.Prefix+"/stats", token, nil)
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if rooms, _ := body["rooms"].(float64); rooms != 1 {
t.Errorf("rooms = %v, want 1", body["rooms"])
}
if published, _ := body["published_rooms"].(float64); published != 1 {
t.Errorf("published_rooms = %v, want 1", body["published_rooms"])
}
if events, _ := body["events"].(float64); events == 0 {
t.Error("a server with a room reports no events")
}
}