Files
Warp/server/internal/storage/rooms.go
T
tajniak81andClaude Opus 5 c96f88e994
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
Phase 3: rooms, local only
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>
2026-10-16 10:34:57 +02:00

358 lines
13 KiB
Go

package storage
import (
"context"
"errors"
)
// Errors the room store returns for cases a caller has to tell apart.
var (
// ErrNoSuchRoom is returned for a room this server does not know.
ErrNoSuchRoom = errors.New("no such room")
// ErrRoomExists is returned by CreateRoom for a room ID already taken.
// It can only happen through a room ID collision, which for a room
// version 12 room would mean two identical create events.
ErrRoomExists = errors.New("room already exists")
// ErrNoSuchEvent is returned for an event ID the room store does not
// hold.
ErrNoSuchEvent = errors.New("no such event")
// ErrNoSuchAlias is returned for an unknown room alias.
ErrNoSuchAlias = errors.New("no such room alias")
// ErrAliasExists is returned by CreateAlias for an alias already
// pointing somewhere.
ErrAliasExists = errors.New("room alias already exists")
)
// Room is one room this server takes part in.
//
// The version is fixed when the room is created and is what every later read
// needs first: an event cannot even be parsed without knowing the rules it
// was written under.
type Room struct {
ID string
// Version is the room version identifier, e.g. "11".
Version string
// Creator is the full user ID that sent the m.room.create event.
Creator string
// Published reports whether the room is in this server's public room
// directory.
Published bool
CreatedAtMS int64
}
// NewRoom describes a room to create. The create event itself is written by
// the same Write call that appends any other event.
type NewRoom struct {
ID string
Version string
Creator string
Published bool
CreatedAtMS int64
}
// RoomProfile is the denormalised view of a room's state that a room
// listing is searched and ordered by.
//
// It is all derivable from the room's current state, and is stored anyway:
// the public room directory sorts every published room by member count and
// pages the result, which cannot be done by reading each room's state in
// turn. The roomserver recomputes it whenever one of the state events behind
// it changes and hands it to Write; the store only keeps it, because
// knowing that m.room.name means a name is the roomserver's business.
//
// JoinedMembers is the exception: the store maintains it itself, by counting
// the current-state rows whose membership is "join".
type RoomProfile struct {
Name string
Topic string
AvatarURL string
CanonicalAlias string
JoinRule string
HistoryVisibility string
GuestAccess string
// RoomType is m.room.create's content.type: empty for a normal room,
// "m.space" for a space.
RoomType string
}
// StateEntry is one piece of room state and the event that holds it.
type StateEntry struct {
Type string
StateKey string
EventID string
// Membership is the membership value of an m.room.member entry, and
// empty on every other kind of state. It travels with the entry so that
// the store can keep "who is joined to this room" answerable with an
// index instead of by parsing event JSON.
Membership string
}
// StoredEvent is an event as the room store holds it: the canonical JSON
// plus the columns worth indexing separately.
//
// JSON is the authority. The other fields are projections of it, written out
// so that the store can answer "the members of this room" or "events in
// stream order" without parsing every row.
type StoredEvent struct {
RoomID string
EventID string
Type string
// StateKey is nil for a non-state event. The empty string is a
// perfectly good state key, which is why this is a pointer.
StateKey *string
Sender string
Depth int64
OriginServerTS int64
// JSON is the event as canonical JSON, exactly as it was signed.
JSON []byte
// StreamOrdering is this server's own monotonic position for the event:
// the order it was persisted in, which is the order /sync and /messages
// hand events to clients.
StreamOrdering int64
// RedactedBy is the event ID of the redaction that applies to this
// event, or empty. The JSON is rewritten in place when a redaction is
// applied, so a redacted event is already stripped on the way out; this
// field is what lets unsigned.redacted_because be filled in.
RedactedBy string
}
// IsState reports whether the event is a state event.
func (e StoredEvent) IsState() bool { return e.StateKey != nil }
// TransactionRef records a client transaction ID against the event it
// produced, so that a retried PUT returns the first event rather than
// sending a second one.
type TransactionRef struct {
Localpart string
DeviceID string
TxnID string
}
// RoomWrite is one event and everything its arrival changes, written in a
// single transaction.
//
// Persisting an event is never just an insert: it moves the room's forward
// extremities, it may replace a piece of current state, and it may strip an
// earlier event. Splitting that across calls would leave a window in which
// the room's current state disagrees with its events, so the whole lot goes
// down together.
type RoomWrite struct {
// Event is the event being appended. Its StreamOrdering is assigned by
// the store and returned.
Event StoredEvent
// StateBefore is the room state the event was authorised against: the
// full state of the room as of its prev_events. It is stored as a
// deduplicated snapshot, so appending a message to a quiet room adds no
// state rows at all.
StateBefore []StateEntry
// StateDelta are the pieces of current state this event changes — for
// an ordinary state event, the single tuple it writes. It is empty for
// an event that changes no state.
StateDelta []StateEntry
// StateDeltaIsWholeState says that StateDelta is the room's entire new
// current state, and that any tuple not in it must be removed. State
// resolution across a forked room produces such a result; a single
// state event does not, and rewriting the whole of a large room's state
// on every join would make filling a room quadratic.
StateDeltaIsWholeState bool
// Profile updates the denormalised room listing columns. It is nil when
// this event changes none of them.
Profile *RoomProfile
// Extremities replaces the room's forward extremities. For a locally
// created event that is the event itself, since it descends from every
// extremity there was.
Extremities []string
// Transaction, when set, records the client transaction ID this event
// came from.
Transaction *TransactionRef
// Redacts is the event ID this event redacts, when the redaction is to
// be applied. RedactedJSON is the target's redacted form, which
// replaces the stored JSON.
Redacts string
RedactedJSON []byte
}
// RoomAlias is a local alias and the room it points at.
type RoomAlias struct {
Alias string
RoomID string
// Creator is the full user ID that created the alias.
Creator string
CreatedAtMS int64
}
// MembershipEntry is one member of a room.
type MembershipEntry struct {
UserID string
Membership string
EventID string
}
// RoomFilter narrows and pages a room listing.
type RoomFilter struct {
// Search matches a substring of the room ID, name, topic or canonical
// alias, case-insensitively. Empty matches everything.
Search string
// Limit caps the returned rows; 0 means the store's own default.
Limit int
// Offset skips rows, for paging.
Offset int
}
// RoomSummary is a room as a listing shows it: the room row, its
// denormalised state and its member count.
type RoomSummary struct {
Room
RoomProfile
// JoinedMembers is how many members of the room are joined.
JoinedMembers int
}
// RoomStats are the room counts the admin dashboard shows.
type RoomStats struct {
Rooms int
Published int
Events int
}
// RoomStore persists rooms, their events and their state: the storage half
// of the roomserver component.
//
// Every method takes identifiers the caller has already validated. The store
// interprets nothing: it does not know the authorisation rules, it does not
// know which room versions exist, and it never parses an event. What it
// guarantees is that a room's events, its state and its extremities are only
// ever seen in a consistent set.
type RoomStore interface {
// CreateRoom inserts the room row, returning ErrRoomExists when the ID
// is taken.
CreateRoom(ctx context.Context, room NewRoom) error
// Room reads one room, returning ErrNoSuchRoom if it is absent.
Room(ctx context.Context, roomID string) (Room, error)
// Write appends one event and applies everything it changes. It returns
// the stream ordering the event was given.
Write(ctx context.Context, w RoomWrite) (int64, error)
// Event reads one event of a room, returning ErrNoSuchEvent if it is
// absent.
Event(ctx context.Context, roomID, eventID string) (StoredEvent, error)
// EventsByID reads events by ID within one room. Unknown IDs are left
// out rather than reported: state resolution needs exactly that
// behaviour for events this server does not have.
EventsByID(ctx context.Context, roomID string, eventIDs []string) ([]StoredEvent, error)
// CurrentState returns the room's resolved current state.
CurrentState(ctx context.Context, roomID string) ([]StateEntry, error)
// CurrentStateEvents returns the events behind the room's current
// state, which is what the authorisation rules are run against.
CurrentStateEvents(ctx context.Context, roomID string) ([]StoredEvent, error)
// CurrentStateEvent returns one piece of current state, or
// ErrNoSuchEvent when the room has no such state.
CurrentStateEvent(ctx context.Context, roomID, eventType, stateKey string) (StoredEvent, error)
// StateBefore returns the state snapshot recorded against an event: the
// state of the room as of that event's prev_events.
StateBefore(ctx context.Context, roomID, eventID string) ([]StateEntry, error)
// Extremities returns the room's forward extremities, which are the
// prev_events of the next event to be sent.
Extremities(ctx context.Context, roomID string) ([]StoredEvent, error)
// Members returns the m.room.member events of a room. memberships
// filters by membership value; empty returns every member event,
// including the users who have left.
Members(ctx context.Context, roomID string, memberships []string) ([]StoredEvent, error)
// MembershipEntries returns the memberships of a room without the event
// bodies, which is what /joined_members needs.
MembershipEntries(ctx context.Context, roomID string, memberships []string) ([]MembershipEntry, error)
// Membership returns a user's membership in a room and the event that
// set it. A user who was never in the room gets an empty membership and
// no error: "never joined" and "left" are the same answer to every rule
// that asks.
Membership(ctx context.Context, roomID, userID string) (MembershipEntry, error)
// RoomsForUser lists the rooms a user has one of the given memberships
// in, ordered by room ID.
RoomsForUser(ctx context.Context, userID string, memberships []string) ([]string, error)
// TransactionEvent returns the event a client transaction ID already
// produced, or ErrNoSuchEvent when this is the first time it is seen.
TransactionEvent(ctx context.Context, ref TransactionRef) (string, error)
// CreateAlias points an alias at a room, returning ErrAliasExists when
// the alias is taken.
CreateAlias(ctx context.Context, alias RoomAlias) error
// DeleteAlias removes an alias, returning ErrNoSuchAlias if it is
// absent.
DeleteAlias(ctx context.Context, alias string) error
// Alias resolves an alias, returning ErrNoSuchAlias if it is absent.
// The creator comes back with it because the permission check on
// deleting an alias is partly about who made it.
Alias(ctx context.Context, alias string) (RoomAlias, error)
// AliasesForRoom lists the local aliases pointing at a room, sorted.
AliasesForRoom(ctx context.Context, roomID string) ([]string, error)
// SetPublished adds or removes a room from the public room directory,
// returning ErrNoSuchRoom for a room that does not exist.
SetPublished(ctx context.Context, roomID string, published bool) error
// PublishedRooms returns a page of the public room directory ordered by
// descending joined-member count, plus the total number of published
// rooms matching the filter.
PublishedRooms(ctx context.Context, filter RoomFilter) ([]RoomSummary, int, error)
// ListRooms returns a page of every room for the admin API, plus the
// total matching the filter.
ListRooms(ctx context.Context, filter RoomFilter) ([]RoomSummary, int, error)
// RoomSummary returns one room with its denormalised state, returning
// ErrNoSuchRoom if it is absent.
RoomSummary(ctx context.Context, roomID string) (RoomSummary, error)
// PurgeRoom deletes a room and everything belonging to it, returning
// ErrNoSuchRoom for a room that does not exist. It is the admin API's
// last resort and has no undo.
PurgeRoom(ctx context.Context, roomID string) error
// RoomStats returns the aggregate counts for the admin dashboard.
RoomStats(ctx context.Context) (RoomStats, error)
}