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 4: the read model. /sync, /messages and /context, the filters that narrow them, and the streams a response carries that are not room events — typing, receipts, presence and to-device messages. With this a client can be used against Warp, which is milestone M1. The one architectural choice is that the syncapi has no copy of the rooms: it reads them through the roomserver. Dendrite gives its syncapi its own tables and feeds them from the output stream, which is right for a design where the two can be separate processes, and Dendrite's could be. Warp is one process by decision, and there the copy buys nothing and costs the hardest class of bug a homeserver has — a read model that disagrees with the room, where a client is shown a message that was rejected and the only way to find out is to compare two tables. So the roomserver grew a read model (stream.go, roomsync.go, visibility.go) rather than exporting its store: reading an event means parsing it under its room's version, and a second copy of the version registry, the parser and the client projection would be a second place for them to disagree. syncapi: stream tokens naming a position in each of five independent streams, so a client that has seen receipt 7 but only event 4 can say so in one opaque string. A token with fewer positions than this build writes is accepted and the rest read as zero, which is what lets a token stored before a stream existed go on working. The PDU position comes from MAX(stream_ordering) and not from the counter row the other four use: the counter is advanced inside the writing transaction, so a token taken from it would name a position whose event no reader can see yet, and the event would be skipped for good once that transaction committed. Long polling goes through a notifier that wakes by room and by user rather than globally — an event wakes the listeners of its room, a membership event also wakes the user it names, so an invite reaches a client that is not in the room yet. A wake-up is only ever a hint: the listener re-reads the streams and decides for itself what changed, which is what makes it safe for the notifier to hold no state about what each client has seen. The listener registers before the read, so an event landing in between leaves the channel signalled and the sync reads again rather than blocking on a change it just missed. EventPersisted must not block, because it is called with the room's write lock still held. "Something happened" is not "a token moved". A stream can move without this user being concerned by it, and returning on every such move would turn a long poll back into a busy loop. The same trap caught presence twice over: a client says it is still online by syncing, so ?set_presence= makes every sync a presence write, and a stream that moved each time would wake every peer, which would sync, which would move it again. SetPresence therefore reports whether anything a peer would notice actually changed, and a write that only refreshes the last-active timestamp leaves the stream alone. Timeline windows are named by their two ends and a direction, Low exclusive and High inclusive in both directions, rather than by "from" and "to" as the wire format spells them. Each of those would otherwise be the low bound in one direction and the high bound in the other, which is exactly the off-by-one every pagination bug is made of; the handlers translate once and nothing below them thinks about it again. A sync's timeline is read backwards and reported forwards, because a client wants the newest events of the window it missed — a forward read with a limit hands it the oldest and then calls the rest a gap. visibility: history visibility is now a span rather than a yes or no, which is what Phase 3 deferred here. A user who has left a room is served the room as it was when they left — their state reads, their members and their timeline — instead of being refused, and is bounded above at their own membership event so a kicked client cannot go on streaming. Their span is found from their own member events, so a user who joined, left and rejoined sees their latest span. ?at= on /members is honoured for the same reason. What is left is that the span is computed from the room's current history_visibility where the spec judges each event by the one in force when it was sent; that is a state read per event and belongs with open question 1. Typing is held in memory and nowhere else: notifications expire in seconds, are worthless across a restart, and arrive one per keystroke-burst per room, so persisting them would be the busiest table in the database holding the least valuable data in it. Receipts only ever advance, compared on the position of the event acknowledged rather than on arrival, because two of a user's clients read at different speeds and the slower one must not drag the marker backwards. To-device queues are per device and drained by the next sync rather than by the one that delivered them, so a client that crashes in between gets the batch again — the right way round, since a lost key share leaves a message permanently undecryptable and a duplicate is ignored. A wildcard addressee is expanded when sent, not stored, because "every device" means the ones that existed then. Presence is off by default, which answers PLAN.md open question 3. It is the noisiest thing in Matrix and the one genuinely fan-out notification here; a private homeserver gains little from it. With it off the endpoints refuse rather than disappearing, because a client that gets a 404 from /presence concludes the server is too old to have it and stops asking. storage: one migration per driver adding the receipt, to-device, presence and filter tables with a counter row each, and a stream position on the existing account data table rather than a parallel one — there is exactly one current value per (user, room, type), and a second table would be a second thing to keep in step. Account data is reported in an event list but is not an event, so it gets its own response type: a room event with an empty sender and no timestamp would make a client decide what that meant. Deliberately missing, each named in docs/sync.md: notification counts (they need push rules, Phase 8), device lists (the keyserver, Phase 7), anything remote (Phase 5), threads (Phase 10). device_lists is sent as two empty lists because a client reads a missing one as malformed; the notification counts are left out entirely, because a zero there is a claim and an absent field is not. Tested through HTTP rather than against the builder, because what is worth pinning down is the response a client sees — which section a room lands in, whether a token handed back can be handed in again, whether paging terminates and loses nothing. The storage tests run against both SQL drivers; the notifier has its own tests for the concurrent case. A live server was driven end to end, which is what caught the two bugs the unit tests had missed: a backwards /messages page must be in reverse chronological order, and `start` must name where the page began rather than position zero when ?from= was omitted. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
397 lines
15 KiB
Go
397 lines
15 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)
|
|
|
|
// MembershipsForUser is RoomsForUser with the membership and the
|
|
// position of the event that set it: one query for everything a sync
|
|
// needs to know about where a user stands.
|
|
MembershipsForUser(ctx context.Context, userID string, memberships []string) ([]SyncMembership, error)
|
|
|
|
// UserMembershipEvents returns every m.room.member event of one user in
|
|
// one room, oldest first.
|
|
//
|
|
// It is how far back a user's own view of a room reaches: a user who
|
|
// joined, left and rejoined has several spans, and only their own
|
|
// membership events say where each one began. There is one row per
|
|
// membership change of one user in one room, so this stays small
|
|
// however busy the room is.
|
|
UserMembershipEvents(ctx context.Context, roomID, userID string) ([]StoredEvent, error)
|
|
|
|
// MaxStreamOrdering returns the top of this server's event stream, or 0
|
|
// for a server that has persisted no events.
|
|
MaxStreamOrdering(ctx context.Context) (int64, error)
|
|
|
|
// Timeline reads one window of a room's event stream. See
|
|
// TimelineRequest: the bounds are exclusive and the limit is required.
|
|
Timeline(ctx context.Context, req TimelineRequest) ([]StoredEvent, error)
|
|
|
|
// RoomsWithEvents returns the subset of roomIDs that have an event
|
|
// after from and at or before to.
|
|
//
|
|
// It is what keeps an incremental sync down to one query for the common
|
|
// case of nothing having happened: a user in two hundred rooms would
|
|
// otherwise need two hundred timeline reads to find that out.
|
|
RoomsWithEvents(ctx context.Context, roomIDs []string, from, to int64) ([]string, error)
|
|
|
|
// StateAtStream returns the room's state as of a stream position: the
|
|
// state after the last event at or before pos.
|
|
//
|
|
// It answers the two questions current state cannot. A user who has
|
|
// left sees the room as it was when they left, and a sync with a gap in
|
|
// it has to say which state changed inside that gap.
|
|
StateAtStream(ctx context.Context, roomID string, pos int64) ([]StateEntry, 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)
|
|
}
|