Phase 4: sync
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
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>
This commit is contained in:
1 parent
c96f88e994
commit
d187ad0d17
60 files changed
+10196
-264
No files matched your search
@@ -173,11 +173,7 @@ func (r *API) ResolveAlias(ctx context.Context, alias string) (ResolvedAlias, er
|
||||
|
||||
// RoomAliases lists the local aliases of a room, for a user who may see it.
|
||||
func (r *API) RoomAliases(ctx context.Context, roomID, userID string) ([]string, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, userID); err != nil {
|
||||
if _, err := r.requireReadable(ctx, roomID, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aliases, err := r.store.AliasesForRoom(ctx, roomID)
|
||||
|
||||
@@ -34,8 +34,16 @@ func (r *API) currentState(ctx context.Context, room storage.Room, rules roomver
|
||||
// is `unsigned`, which is per-server annotation: the age of the event, the
|
||||
// state it replaced, and the redaction that stripped it.
|
||||
type ClientEvent struct {
|
||||
EventID string `json:"event_id"`
|
||||
RoomID string `json:"room_id"`
|
||||
EventID string `json:"event_id"`
|
||||
|
||||
// RoomID is omitted when empty, because a /sync response carries its
|
||||
// events without one: they are already nested under the room they
|
||||
// belong to, and repeating it on every event of a client with a
|
||||
// thousand rooms is a measurable part of every response. Every other
|
||||
// endpoint sets it, and the spec has a separate name for the shape
|
||||
// without it — ClientEventWithoutRoomID — rather than two event types.
|
||||
RoomID string `json:"room_id,omitempty"`
|
||||
|
||||
Type string `json:"type"`
|
||||
StateKey *string `json:"state_key,omitempty"`
|
||||
Sender string `json:"sender"`
|
||||
@@ -98,11 +106,12 @@ func (r *API) unsigned(stored storage.StoredEvent, e *event.Event) json.RawMessa
|
||||
|
||||
// Event returns one event of a room, if the user may see it.
|
||||
func (r *API) Event(ctx context.Context, roomID, userID, eventID string) (ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
_, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, userID); err != nil {
|
||||
visible, err := r.requireReadable(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
|
||||
@@ -110,6 +119,12 @@ func (r *API) Event(ctx context.Context, roomID, userID, eventID string) (Client
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
// An event outside the user's window is reported as unknown rather
|
||||
// than as forbidden: whether a particular event ID exists in a room is
|
||||
// itself something they are not entitled to know.
|
||||
if !visible.Contains(stored.StreamOrdering) {
|
||||
return ClientEvent{}, fmt.Errorf("event %q: %w", eventID, ErrNoSuchEvent)
|
||||
}
|
||||
e, err := parseEvent(stored, rules)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
@@ -117,29 +132,18 @@ func (r *API) Event(ctx context.Context, roomID, userID, eventID string) (Client
|
||||
return r.clientEvent(stored, e, roomID), nil
|
||||
}
|
||||
|
||||
// RoomState returns a room's current state in the client shape.
|
||||
// RoomState returns a room's state in the client shape: the current state
|
||||
// for a member, and the state as it was when they left for a user who has.
|
||||
func (r *API) RoomState(ctx context.Context, roomID, userID string) ([]ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
_, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := r.store.CurrentStateEvents(ctx, roomID)
|
||||
visible, err := r.requireReadable(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ClientEvent, 0, len(stored))
|
||||
for _, s := range stored {
|
||||
e, err := parseEvent(s, rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r.clientEvent(s, e, roomID))
|
||||
}
|
||||
return out, nil
|
||||
return r.stateAt(ctx, roomID, rules, visible.To)
|
||||
}
|
||||
|
||||
// StateEventContent returns the content of one piece of a room's current
|
||||
@@ -148,23 +152,11 @@ func (r *API) RoomState(ctx context.Context, roomID, userID string) ([]ClientEve
|
||||
// The endpoint returns the content alone, not the event: a quirk of the
|
||||
// Client-Server API that predates the rest of it, and one clients depend on.
|
||||
func (r *API) StateEventContent(ctx context.Context, roomID, userID, eventType, stateKey string) (json.RawMessage, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
e, err := r.StateEvent(ctx, roomID, userID, eventType, stateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := r.store.CurrentStateEvent(ctx, roomID, eventType, stateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e, err := parseEvent(stored, rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return e.Content(), nil
|
||||
return e.Content, nil
|
||||
}
|
||||
|
||||
// StateEvent returns one piece of a room's current state as a whole event.
|
||||
@@ -172,14 +164,33 @@ func (r *API) StateEventContent(ctx context.Context, roomID, userID, eventType,
|
||||
// It is what ?format=event asks for on the state endpoint, and the only way
|
||||
// a client can see who set a piece of state and when.
|
||||
func (r *API) StateEvent(ctx context.Context, roomID, userID, eventType, stateKey string) (ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
_, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, userID); err != nil {
|
||||
visible, err := r.requireReadable(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
|
||||
// A member reads the one row they asked for. A user who has left has to
|
||||
// be served from the state as of their departure, which means reading
|
||||
// the snapshot and picking the tuple out of it — the room has moved on
|
||||
// since, and the current row is not theirs to see.
|
||||
if visible.To != 0 {
|
||||
state, err := r.stateAt(ctx, roomID, rules, visible.To)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
}
|
||||
for _, e := range state {
|
||||
if e.Type == eventType && e.StateKey != nil && *e.StateKey == stateKey {
|
||||
return e, nil
|
||||
}
|
||||
}
|
||||
return ClientEvent{}, fmt.Errorf("state %s/%s of %q: %w",
|
||||
eventType, stateKey, roomID, ErrNoSuchEvent)
|
||||
}
|
||||
|
||||
stored, err := r.store.CurrentStateEvent(ctx, roomID, eventType, stateKey)
|
||||
if err != nil {
|
||||
return ClientEvent{}, err
|
||||
@@ -201,44 +212,88 @@ type MembersRequest struct {
|
||||
// Membership and NotMembership filter the result; either may be empty.
|
||||
Membership string
|
||||
NotMembership string
|
||||
|
||||
// At is the stream position to report the membership as of, or 0 for
|
||||
// the current one.
|
||||
//
|
||||
// It is what ?at= asks for, and what a client that is rendering an
|
||||
// older part of a room's timeline needs: the names and avatars to show
|
||||
// against those messages are the ones their senders had then, not now.
|
||||
At int64
|
||||
}
|
||||
|
||||
// Members returns a room's m.room.member events.
|
||||
func (r *API) Members(ctx context.Context, req MembersRequest) ([]ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, req.RoomID)
|
||||
_, rules, err := r.roomAndRules(ctx, req.RoomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.requireVisibility(ctx, room, rules, req.User); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var filter []string
|
||||
if req.Membership != "" {
|
||||
filter = append(filter, req.Membership)
|
||||
}
|
||||
stored, err := r.store.Members(ctx, req.RoomID, filter)
|
||||
visible, err := r.requireReadable(ctx, req.RoomID, req.User)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := make([]ClientEvent, 0, len(stored))
|
||||
for _, s := range stored {
|
||||
e, err := parseEvent(s, rules)
|
||||
// The position to report as of: the one asked for, held inside what
|
||||
// the user may see. A user who has left is pinned to their departure
|
||||
// whatever they asked for — the room has moved on since, and the
|
||||
// current membership is not theirs to read.
|
||||
at := req.At
|
||||
if visible.To != 0 && (at == 0 || at > visible.To) {
|
||||
at = visible.To
|
||||
}
|
||||
if at != 0 && at <= visible.From {
|
||||
return nil, fmt.Errorf("%w: %s may not see %s as it was at %d",
|
||||
ErrForbidden, req.User, req.RoomID, req.At)
|
||||
}
|
||||
|
||||
var members []ClientEvent
|
||||
if at != 0 {
|
||||
state, err := r.stateAt(ctx, req.RoomID, rules, at)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.NotMembership != "" {
|
||||
membership, err := e.Membership()
|
||||
if err == nil && membership == req.NotMembership {
|
||||
continue
|
||||
}
|
||||
members = filterClientEvents(state, storage.TimelineFilter{Types: []string{event.TypeMember}})
|
||||
} else {
|
||||
var filter []string
|
||||
if req.Membership != "" {
|
||||
filter = append(filter, req.Membership)
|
||||
}
|
||||
out = append(out, r.clientEvent(s, e, req.RoomID))
|
||||
stored, err := r.store.Members(ctx, req.RoomID, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if members, err = r.clientEvents(stored, rules, req.RoomID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]ClientEvent, 0, len(members))
|
||||
for _, e := range members {
|
||||
membership := membershipOf(e)
|
||||
if req.Membership != "" && membership != req.Membership {
|
||||
continue
|
||||
}
|
||||
if req.NotMembership != "" && membership == req.NotMembership {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// membershipOf reads content.membership out of a projected member event.
|
||||
//
|
||||
// A member event that reached a room always has one — the authorisation
|
||||
// rules refuse one that does not — so an empty answer means the event is
|
||||
// not a member event at all.
|
||||
func membershipOf(e ClientEvent) string {
|
||||
var content struct {
|
||||
Membership string `json:"membership"`
|
||||
}
|
||||
_ = json.Unmarshal(e.Content, &content)
|
||||
return content.Membership
|
||||
}
|
||||
|
||||
// RoomMember is one joined member, as /joined_members reports them.
|
||||
type RoomMember struct {
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
@@ -333,47 +388,6 @@ func (r *API) requireJoined(ctx context.Context, roomID, userID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// requireVisibility refuses a caller who may not see a room's state.
|
||||
//
|
||||
// This is a room-level test, not the per-event history visibility the spec
|
||||
// defines. A member sees the room; so does anyone at all when the room's
|
||||
// history is world_readable; a user who has left sees the state as it was
|
||||
// when they left, which is their own membership event's snapshot and which
|
||||
// this returns the current state for instead.
|
||||
//
|
||||
// That last case is the gap, and it is deliberate. Serving a departed
|
||||
// member the state as of their leave event means answering every state read
|
||||
// from a historical snapshot and filtering each event by the visibility in
|
||||
// force when it was sent — which is the same machinery /messages and
|
||||
// /context need, and so belongs with them in Phase 4 rather than being
|
||||
// built twice. Until then a user who has left a room is refused, which errs
|
||||
// towards showing them too little.
|
||||
func (r *API) requireVisibility(ctx context.Context, room storage.Room, rules roomversion.Rules, userID string) error {
|
||||
entry, err := r.store.Membership(ctx, room.ID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.Membership == event.MembershipJoin {
|
||||
return nil
|
||||
}
|
||||
|
||||
summary, err := r.store.RoomSummary(ctx, room.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if summary.HistoryVisibility == HistoryVisibilityWorldReadable {
|
||||
return nil
|
||||
}
|
||||
|
||||
// An invited user can see enough of the room to decide, which the spec
|
||||
// delivers as stripped state on the invite rather than as a state read.
|
||||
if entry.Membership == event.MembershipInvite {
|
||||
return fmt.Errorf("%w: %s has been invited to %s but has not joined it",
|
||||
ErrForbidden, userID, room.ID)
|
||||
}
|
||||
return fmt.Errorf("%w: %s is not in %s", ErrForbidden, userID, room.ID)
|
||||
}
|
||||
|
||||
// CanSendStateEvent reports whether a user may send a state event of a type
|
||||
// into a room.
|
||||
//
|
||||
|
||||
@@ -98,10 +98,14 @@ type Notification struct {
|
||||
// they were persisted.
|
||||
//
|
||||
// It is the emit stage of the input pipeline and the seam the sync API
|
||||
// (PLAN.md phase 4) plugs into: a client long-polling /sync has to be woken
|
||||
// the moment an event lands, and the input pipeline is the only place that
|
||||
// knows one has. Phase 3 ships without a notifier, so this is nil and the
|
||||
// stage is skipped.
|
||||
// plugs into: a client long-polling /sync has to be woken the moment an
|
||||
// event lands, and the input pipeline is the only place that knows one
|
||||
// has. *syncapi.Notifier satisfies it; nil skips the stage, which is what
|
||||
// a build with no sync API does.
|
||||
//
|
||||
// An implementation must not block. It is called with the room's write
|
||||
// lock still held, so anything slow here serialises the room's writers
|
||||
// behind the slowest reader of it.
|
||||
type Notifier interface {
|
||||
EventPersisted(ctx context.Context, n Notification)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,10 @@ type fixture struct {
|
||||
api *roomserver.API
|
||||
store storage.RoomStore
|
||||
db storage.Database
|
||||
|
||||
// sends counts the messages the fill helper has sent, so that each
|
||||
// one gets its own transaction ID; see fill in stream_test.go.
|
||||
sends int
|
||||
}
|
||||
|
||||
// profiles is a stand-in for the userapi, so that these tests do not need
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
package roomserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/roomversion"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
)
|
||||
|
||||
// RoomSyncRequest asks what one user sees of one room between two
|
||||
// positions.
|
||||
//
|
||||
// It is the read model's largest operation and the one /sync is built on.
|
||||
// It is a single call rather than a timeline read plus two state reads
|
||||
// because the three answers have to agree with each other: which state the
|
||||
// response reports depends on where the timeline turned out to start, and
|
||||
// working that out in the caller would mean the caller deciding what the
|
||||
// timeline was — which is the question it asked.
|
||||
type RoomSyncRequest struct {
|
||||
RoomID string
|
||||
|
||||
// User is the full user ID syncing.
|
||||
User string
|
||||
|
||||
// Since is the position the user has already seen, exclusive. Zero is
|
||||
// an initial sync.
|
||||
Since int64
|
||||
|
||||
// To is the top of this sync, inclusive. It is fixed by the caller for
|
||||
// every room in one response, so that a token names one moment rather
|
||||
// than a different one per room.
|
||||
To int64
|
||||
|
||||
// TimelineLimit caps the events in the timeline.
|
||||
TimelineLimit int
|
||||
|
||||
// TimelineFilter and StateFilter narrow the two halves of the
|
||||
// response. The state filter is applied in this package rather than in
|
||||
// SQL: a state read is a set of tuples, not a window of a stream.
|
||||
TimelineFilter storage.TimelineFilter
|
||||
StateFilter storage.TimelineFilter
|
||||
|
||||
// FullState asks for the room's whole state even on an incremental
|
||||
// sync, which is what ?full_state=true means.
|
||||
FullState bool
|
||||
|
||||
// LazyLoadMembers leaves the member events out of the state except for
|
||||
// the senders who appear in the timeline.
|
||||
LazyLoadMembers bool
|
||||
}
|
||||
|
||||
// RoomSync is what one user sees of one room between two positions.
|
||||
type RoomSync struct {
|
||||
// Membership is the user's current membership in the room.
|
||||
Membership string
|
||||
|
||||
Timeline Timeline
|
||||
|
||||
// State is the room's state as of the start of the timeline on an
|
||||
// initial sync, and what changed between Since and the start of the
|
||||
// timeline on an incremental one. For an incremental sync with no gap
|
||||
// it is empty: every state change in the window is in the timeline
|
||||
// itself.
|
||||
State []ClientEvent
|
||||
|
||||
// Summary is the room's member counts and heroes.
|
||||
Summary RoomSyncSummary
|
||||
|
||||
// Visible is the span of the stream the user may read, which the
|
||||
// caller needs in order to bound the ephemeral streams the same way.
|
||||
Visible VisibleRange
|
||||
}
|
||||
|
||||
// RoomSync reads one room for one user.
|
||||
func (r *API) RoomSync(ctx context.Context, req RoomSyncRequest) (RoomSync, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, req.RoomID)
|
||||
if err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
summary, err := r.store.RoomSummary(ctx, room.ID)
|
||||
if err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
visible, err := r.visibleRange(ctx, room.ID, rules, req.User, summary.HistoryVisibility)
|
||||
if err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
if err := visible.refusal(room.ID, req.User); err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
|
||||
out := RoomSync{Membership: visible.Membership, Visible: visible}
|
||||
|
||||
// The timeline is read backwards even though it is reported forwards.
|
||||
// A client wants the *newest* events of the window it has missed — the
|
||||
// bottom of the room, which is what it is looking at — and a forward
|
||||
// read with a limit would hand it the oldest instead and then call the
|
||||
// rest a gap.
|
||||
out.Timeline, err = r.timeline(ctx, rules, visible, TimelineRequest{
|
||||
RoomID: req.RoomID,
|
||||
User: req.User,
|
||||
Low: req.Since,
|
||||
High: req.To,
|
||||
Direction: storage.DirectionBackward,
|
||||
Limit: req.TimelineLimit,
|
||||
Filter: req.TimelineFilter,
|
||||
})
|
||||
if err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
|
||||
if out.State, err = r.syncState(ctx, rules, visible, req, out.Timeline); err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
if out.Summary, err = r.RoomSummaryFor(ctx, req.RoomID, req.User); err != nil {
|
||||
return RoomSync{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// syncState decides which state a room's half of a sync response reports.
|
||||
//
|
||||
// The rule the spec sets is that a client which applies `state` and then
|
||||
// `timeline` ends up with the room's state at the end of the timeline. That
|
||||
// gives three cases:
|
||||
//
|
||||
// - An initial sync, or ?full_state=true: the whole state as of the start
|
||||
// of the timeline.
|
||||
// - An incremental sync whose timeline reaches back to `since`: nothing.
|
||||
// Every state change in between is a timeline event the client is
|
||||
// already being given.
|
||||
// - An incremental sync whose timeline was cut short — a gap: what
|
||||
// changed between `since` and where the timeline starts. Those changes
|
||||
// are not in the timeline and the client would otherwise never see
|
||||
// them.
|
||||
func (r *API) syncState(ctx context.Context, rules roomversion.Rules, visible VisibleRange, req RoomSyncRequest, timeline Timeline) ([]ClientEvent, error) {
|
||||
statePos, haveState := statePosition(timeline, req.To, visible)
|
||||
|
||||
switch {
|
||||
case !haveState:
|
||||
// The timeline reaches back to the room's create event, so there
|
||||
// is nothing before it to report.
|
||||
return nil, nil
|
||||
|
||||
case req.FullState || req.Since == 0:
|
||||
state, err := r.stateAt(ctx, req.RoomID, rules, statePos)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.shapeState(ctx, rules, req, timeline, state)
|
||||
|
||||
case !timeline.Limited:
|
||||
return nil, nil
|
||||
|
||||
default:
|
||||
before, err := r.stateAt(ctx, req.RoomID, rules, req.Since)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
after, err := r.stateAt(ctx, req.RoomID, rules, statePos)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.shapeState(ctx, rules, req, timeline, stateDelta(before, after))
|
||||
}
|
||||
}
|
||||
|
||||
// statePosition is the position a room's state is reported as of, and
|
||||
// whether there is any state to report at all.
|
||||
//
|
||||
// The state belongs at the start of the timeline, so that applying it and
|
||||
// then the timeline lands on the room's current state. A room with no
|
||||
// timeline events in this window is reported as of the top of the sync
|
||||
// instead: the state may still have been read for the first time.
|
||||
func statePosition(timeline Timeline, to int64, visible VisibleRange) (int64, bool) {
|
||||
if len(timeline.Events) > 0 {
|
||||
return timeline.Start, timeline.Start > 0
|
||||
}
|
||||
if visible.To != 0 && (to == 0 || to > visible.To) {
|
||||
to = visible.To
|
||||
}
|
||||
return to, to > 0
|
||||
}
|
||||
|
||||
// shapeState applies the state filter and lazy loading to a state set.
|
||||
func (r *API) shapeState(ctx context.Context, rules roomversion.Rules, req RoomSyncRequest, timeline Timeline, state []ClientEvent) ([]ClientEvent, error) {
|
||||
state = filterClientEvents(state, req.StateFilter)
|
||||
if !req.LazyLoadMembers {
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// Lazy loading: drop the member events and put back only the ones the
|
||||
// client needs to render the timeline it is being given.
|
||||
//
|
||||
// The spec also lets a server leave out members it has already sent
|
||||
// this device, which would need per-device bookkeeping of what each
|
||||
// one has seen. Warp sends them every time instead: it is the
|
||||
// behaviour `include_redundant_members: true` asks for, so no client
|
||||
// can be surprised by it, and it costs one state read rather than a
|
||||
// table.
|
||||
kept := make([]ClientEvent, 0, len(state))
|
||||
for _, e := range state {
|
||||
if e.Type != event.TypeMember {
|
||||
kept = append(kept, e)
|
||||
}
|
||||
}
|
||||
|
||||
senders := timelineSenders(timeline)
|
||||
members, err := r.memberEvents(ctx, req.RoomID, rules, senders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(kept, filterClientEvents(members, req.StateFilter)...), nil
|
||||
}
|
||||
|
||||
// timelineSenders lists the distinct senders of a timeline, in the order
|
||||
// they first appear.
|
||||
func timelineSenders(timeline Timeline) []string {
|
||||
seen := make(map[string]struct{}, len(timeline.Events))
|
||||
out := make([]string, 0, len(timeline.Events))
|
||||
for _, e := range timeline.Events {
|
||||
if _, dup := seen[e.Sender]; dup {
|
||||
continue
|
||||
}
|
||||
seen[e.Sender] = struct{}{}
|
||||
out = append(out, e.Sender)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// stateKey identifies one piece of state.
|
||||
type stateKeyTuple struct {
|
||||
eventType string
|
||||
stateKey string
|
||||
}
|
||||
|
||||
// tupleOf is the state tuple of a client event, and whether it has one.
|
||||
func tupleOf(e ClientEvent) (stateKeyTuple, bool) {
|
||||
if e.StateKey == nil {
|
||||
return stateKeyTuple{}, false
|
||||
}
|
||||
return stateKeyTuple{eventType: e.Type, stateKey: *e.StateKey}, true
|
||||
}
|
||||
|
||||
// stateDelta is what changed between two state sets: every tuple of `after`
|
||||
// whose event is not the one `before` had.
|
||||
//
|
||||
// A tuple that `before` had and `after` does not is left out. State is only
|
||||
// ever replaced, never removed — there is no way to unset a piece of room
|
||||
// state — so such a tuple can only come from state resolution dropping an
|
||||
// event, and there is nothing a client could be sent that would express it.
|
||||
func stateDelta(before, after []ClientEvent) []ClientEvent {
|
||||
had := make(map[stateKeyTuple]string, len(before))
|
||||
for _, e := range before {
|
||||
if tuple, ok := tupleOf(e); ok {
|
||||
had[tuple] = e.EventID
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]ClientEvent, 0, len(after))
|
||||
for _, e := range after {
|
||||
tuple, ok := tupleOf(e)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if had[tuple] == e.EventID {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// filterClientEvents applies the part of an event filter that is a
|
||||
// comparison on the event itself.
|
||||
//
|
||||
// It is the same filter the store applies to a timeline read, applied in Go
|
||||
// because a state read is a set of tuples rather than a window of a stream:
|
||||
// there is no index to push it down to.
|
||||
func filterClientEvents(events []ClientEvent, filter storage.TimelineFilter) []ClientEvent {
|
||||
if filter.IsEmpty() {
|
||||
return events
|
||||
}
|
||||
out := make([]ClientEvent, 0, len(events))
|
||||
for _, e := range events {
|
||||
if matchesFilter(e, filter) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// matchesFilter reports whether one event passes a filter. Exclusions win
|
||||
// over inclusions, which is what the spec requires.
|
||||
func matchesFilter(e ClientEvent, filter storage.TimelineFilter) bool {
|
||||
switch {
|
||||
case matchesAny(e.Type, filter.NotTypes):
|
||||
return false
|
||||
case matchesAny(e.Sender, filter.NotSenders):
|
||||
return false
|
||||
case len(filter.Types) > 0 && !matchesAny(e.Type, filter.Types):
|
||||
return false
|
||||
case len(filter.Senders) > 0 && !matchesAny(e.Sender, filter.Senders):
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// matchesAny reports whether value matches one of the filter patterns, each
|
||||
// of which may end in '*' as the spec's wildcard.
|
||||
func matchesAny(value string, patterns []string) bool {
|
||||
for _, pattern := range patterns {
|
||||
if prefix, isWildcard := strings.CutSuffix(pattern, "*"); isWildcard {
|
||||
if strings.HasPrefix(value, prefix) {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if value == pattern {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
package roomserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/roomversion"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
)
|
||||
|
||||
// The read model: the event stream as /sync, /messages and /context read
|
||||
// it.
|
||||
//
|
||||
// It is here rather than in the syncapi because reading an event means
|
||||
// parsing it under its room's version, and that is the roomserver's
|
||||
// business — the syncapi would otherwise need its own copy of the room
|
||||
// version registry, the event parser and the client projection, and a
|
||||
// second copy of those would be a second place for them to disagree. What
|
||||
// the syncapi gets instead is windows of ClientEvents with their positions,
|
||||
// and it assembles the response shape around them.
|
||||
|
||||
// MembershipAt is a user's current membership in a room, with the position
|
||||
// of the event that set it.
|
||||
type MembershipAt struct {
|
||||
RoomID string
|
||||
Membership string
|
||||
EventID string
|
||||
|
||||
// Position is the stream position of the membership event.
|
||||
Position int64
|
||||
}
|
||||
|
||||
// TimelineRequest is one window of a room's event stream.
|
||||
//
|
||||
// The bounds are the store's: Low exclusive, High inclusive, both
|
||||
// directions, and zero meaning unbounded at that end. Direction decides
|
||||
// only which end the limit trims and the order the store reads in — the
|
||||
// events always come back oldest first.
|
||||
type TimelineRequest struct {
|
||||
RoomID string
|
||||
|
||||
// User is the full user ID the window is read on behalf of. The result
|
||||
// is clamped to what their membership and the room's history
|
||||
// visibility allow.
|
||||
User string
|
||||
|
||||
Low int64
|
||||
High int64
|
||||
|
||||
Direction storage.TimelineDirection
|
||||
|
||||
// Limit caps how many events come back.
|
||||
Limit int
|
||||
|
||||
// Filter narrows which events are read. Applying it here rather than
|
||||
// after the limit is what keeps a filtered page from coming back short
|
||||
// and looking like the end of the room.
|
||||
Filter storage.TimelineFilter
|
||||
}
|
||||
|
||||
// Timeline is a window of a room's event stream.
|
||||
type Timeline struct {
|
||||
// Events are in stream order, oldest first, whichever direction was
|
||||
// asked for: a client renders a timeline forwards even when it paged
|
||||
// backwards to get it.
|
||||
Events []ClientEvent
|
||||
|
||||
// Start and End are the positions bounding the window: Start below the
|
||||
// first event and End at the last. They are the two tokens a client
|
||||
// needs to ask for the next page in either direction, and either can
|
||||
// be handed back as a bound without re-reading the event it names.
|
||||
Start int64
|
||||
End int64
|
||||
|
||||
// Limited reports that the limit cut the window short, so there is
|
||||
// more of it beyond the end the limit trimmed.
|
||||
Limited bool
|
||||
}
|
||||
|
||||
// StreamTop returns the top of this server's event stream.
|
||||
func (r *API) StreamTop(ctx context.Context) (int64, error) {
|
||||
return r.store.MaxStreamOrdering(ctx)
|
||||
}
|
||||
|
||||
// UserMemberships returns the rooms a user has one of the given memberships
|
||||
// in, with the position of each membership event.
|
||||
func (r *API) UserMemberships(ctx context.Context, userID string, memberships []string) ([]MembershipAt, error) {
|
||||
stored, err := r.store.MembershipsForUser(ctx, userID, memberships)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]MembershipAt, 0, len(stored))
|
||||
for _, m := range stored {
|
||||
out = append(out, MembershipAt{
|
||||
RoomID: m.RoomID,
|
||||
Membership: m.Membership,
|
||||
EventID: m.EventID,
|
||||
Position: m.StreamOrdering,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoomsWithEvents returns the subset of rooms that have an event after from
|
||||
// and at or before to.
|
||||
func (r *API) RoomsWithEvents(ctx context.Context, roomIDs []string, from, to int64) ([]string, error) {
|
||||
return r.store.RoomsWithEvents(ctx, roomIDs, from, to)
|
||||
}
|
||||
|
||||
// Timeline reads one window of a room's event stream, as far as the user is
|
||||
// allowed to see it.
|
||||
func (r *API) Timeline(ctx context.Context, req TimelineRequest) (Timeline, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, req.RoomID)
|
||||
if err != nil {
|
||||
return Timeline{}, err
|
||||
}
|
||||
visible, err := r.requireReadable(ctx, room.ID, req.User)
|
||||
if err != nil {
|
||||
return Timeline{}, err
|
||||
}
|
||||
return r.timeline(ctx, rules, visible, req)
|
||||
}
|
||||
|
||||
// timeline is Timeline with the room's rules and the user's visible range
|
||||
// already in hand, for the sync loop that reads many rooms at once.
|
||||
func (r *API) timeline(ctx context.Context, rules roomversion.Rules, visible VisibleRange, req TimelineRequest) (Timeline, error) {
|
||||
// An empty window is reported at the bound the caller came in on, so
|
||||
// that the tokens it hands back are still usable.
|
||||
empty := Timeline{Start: req.Low, End: req.Low}
|
||||
if req.Direction == storage.DirectionBackward && req.High > 0 {
|
||||
empty = Timeline{Start: req.High, End: req.High}
|
||||
}
|
||||
if req.Limit <= 0 {
|
||||
return empty, nil
|
||||
}
|
||||
|
||||
low, high, any := visible.Clamp(req.Low, req.High)
|
||||
if !any {
|
||||
return empty, nil
|
||||
}
|
||||
|
||||
// One more than asked for, so that "there is more" can be told from
|
||||
// "that was all" without a second query.
|
||||
stored, err := r.store.Timeline(ctx, storage.TimelineRequest{
|
||||
RoomID: req.RoomID,
|
||||
Low: low,
|
||||
High: high,
|
||||
Direction: req.Direction,
|
||||
Limit: req.Limit + 1,
|
||||
Filter: req.Filter,
|
||||
})
|
||||
if err != nil {
|
||||
return Timeline{}, err
|
||||
}
|
||||
|
||||
out := empty
|
||||
if len(stored) > req.Limit {
|
||||
out.Limited = true
|
||||
stored = stored[:req.Limit]
|
||||
}
|
||||
if len(stored) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// The store returned them in the direction asked for; a client always
|
||||
// renders a timeline oldest first.
|
||||
if req.Direction == storage.DirectionBackward {
|
||||
slices.Reverse(stored)
|
||||
}
|
||||
|
||||
out.Events = make([]ClientEvent, 0, len(stored))
|
||||
for _, s := range stored {
|
||||
e, err := parseEvent(s, rules)
|
||||
if err != nil {
|
||||
return Timeline{}, err
|
||||
}
|
||||
out.Events = append(out.Events, r.clientEvent(s, e, req.RoomID))
|
||||
}
|
||||
// Start sits below the oldest event, so that handing it back as a High
|
||||
// bound returns the page before this one; End is at the newest, so that
|
||||
// handing it back as a Low bound returns the page after.
|
||||
out.Start = stored[0].StreamOrdering - 1
|
||||
out.End = stored[len(stored)-1].StreamOrdering
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// EventPosition returns an event's position in the stream, for a user who
|
||||
// may see it.
|
||||
//
|
||||
// /context needs it: the timeline reads are bounded by position rather than
|
||||
// by event ID, so the event a context is centred on has to be located
|
||||
// before either side of it can be read.
|
||||
func (r *API) EventPosition(ctx context.Context, roomID, userID, eventID string) (int64, error) {
|
||||
visible, err := r.requireReadable(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
stored, err := r.store.Event(ctx, roomID, eventID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !visible.Contains(stored.StreamOrdering) {
|
||||
return 0, fmt.Errorf("event %q: %w", eventID, ErrNoSuchEvent)
|
||||
}
|
||||
return stored.StreamOrdering, nil
|
||||
}
|
||||
|
||||
// StateAt returns a room's state as of a stream position, in the client
|
||||
// shape.
|
||||
//
|
||||
// It is what a sync with a gap in it and a leaver's state read both need:
|
||||
// the state current state cannot give, because the room has moved on since.
|
||||
func (r *API) StateAt(ctx context.Context, roomID, userID string, pos int64) ([]ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
visible, err := r.requireReadable(ctx, room.ID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if visible.To != 0 && (pos == 0 || pos > visible.To) {
|
||||
pos = visible.To
|
||||
}
|
||||
return r.stateAt(ctx, roomID, rules, pos)
|
||||
}
|
||||
|
||||
// stateAt is StateAt with the checks already done.
|
||||
//
|
||||
// A position of zero is the room's current state, which is both cheaper to
|
||||
// read and what every caller that is up to date wants.
|
||||
func (r *API) stateAt(ctx context.Context, roomID string, rules roomversion.Rules, pos int64) ([]ClientEvent, error) {
|
||||
var (
|
||||
entries []storage.StateEntry
|
||||
err error
|
||||
)
|
||||
if pos == 0 {
|
||||
stored, err := r.store.CurrentStateEvents(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.clientEvents(stored, rules, roomID)
|
||||
}
|
||||
if entries, err = r.store.StateAtStream(ctx, roomID, pos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.clientEventsByID(ctx, roomID, rules, stateEntryIDs(entries))
|
||||
}
|
||||
|
||||
// StateBeforeEvent returns the state of a room as of an event's
|
||||
// prev_events: the state /context reports alongside it.
|
||||
func (r *API) StateBeforeEvent(ctx context.Context, roomID, userID, eventID string) ([]ClientEvent, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
visible, err := r.requireReadable(ctx, room.ID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := r.store.Event(ctx, roomID, eventID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !visible.Contains(stored.StreamOrdering) {
|
||||
return nil, fmt.Errorf("%w: %s may not see %s", ErrForbidden, userID, eventID)
|
||||
}
|
||||
|
||||
entries, err := r.store.StateBefore(ctx, roomID, eventID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state, err := r.clientEventsByID(ctx, roomID, rules, stateEntryIDs(entries))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The event itself, when it is a state event, is part of the state
|
||||
// after it but not before it. /context wants the state the event was
|
||||
// sent against, so it is left out — except that a client rendering the
|
||||
// event needs the sender's member event, which is in the snapshot
|
||||
// already.
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// MemberEvents returns the m.room.member events of specific users in a
|
||||
// room, in the client shape.
|
||||
//
|
||||
// Lazy-loading is what this is for: a client that asked for it is sent the
|
||||
// members who appear in the timeline it was given, rather than all of them.
|
||||
func (r *API) MemberEvents(ctx context.Context, roomID string, userIDs []string) ([]ClientEvent, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
_, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.memberEvents(ctx, roomID, rules, userIDs)
|
||||
}
|
||||
|
||||
// memberEvents is MemberEvents with the rules in hand.
|
||||
func (r *API) memberEvents(ctx context.Context, roomID string, rules roomversion.Rules, userIDs []string) ([]ClientEvent, error) {
|
||||
out := make([]ClientEvent, 0, len(userIDs))
|
||||
for _, userID := range userIDs {
|
||||
stored, err := r.store.CurrentStateEvent(ctx, roomID, event.TypeMember, userID)
|
||||
switch {
|
||||
case isNotFound(err):
|
||||
// A member who appears in the timeline but is not in the
|
||||
// room's current state: their membership was reset by state
|
||||
// resolution, or the event is old enough to predate it. Not an
|
||||
// error, and nothing to send.
|
||||
continue
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
e, err := parseEvent(stored, rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r.clientEvent(stored, e, roomID))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StrippedEvent is a piece of room state as it travels with an invite:
|
||||
// enough for a client to show the user what they are being asked to join,
|
||||
// and nothing that would let them read the room.
|
||||
//
|
||||
// It has no event ID and no timestamp on purpose — the spec's "stripped
|
||||
// state" is explicitly not an event, and a client must not put it in a
|
||||
// timeline.
|
||||
type StrippedEvent struct {
|
||||
Type string `json:"type"`
|
||||
StateKey string `json:"state_key"`
|
||||
Sender string `json:"sender"`
|
||||
Content json.RawMessage `json:"content"`
|
||||
}
|
||||
|
||||
// strippedStateTypes is what the spec says an invite carries: the state a
|
||||
// client needs to render the room in an invite list.
|
||||
var strippedStateTypes = []string{
|
||||
event.TypeCreate,
|
||||
event.TypeJoinRules,
|
||||
TypeCanonicalAlias,
|
||||
TypeName,
|
||||
TypeAvatar,
|
||||
TypeTopic,
|
||||
TypeEncryption,
|
||||
event.TypeHistoryVisibility,
|
||||
}
|
||||
|
||||
// StrippedState returns the stripped state of a room, plus the member
|
||||
// events of the users named.
|
||||
//
|
||||
// The member events are what makes an invite legible: a client showing
|
||||
// "Alice invited you" needs Alice's display name, and the invitee's own
|
||||
// member event carries the invite's reason.
|
||||
func (r *API) StrippedState(ctx context.Context, roomID string, members []string) ([]StrippedEvent, error) {
|
||||
_, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.strippedState(ctx, roomID, rules, members)
|
||||
}
|
||||
|
||||
// strippedState is StrippedState with the rules in hand.
|
||||
func (r *API) strippedState(ctx context.Context, roomID string, rules roomversion.Rules, members []string) ([]StrippedEvent, error) {
|
||||
var out []StrippedEvent
|
||||
|
||||
appendState := func(eventType, stateKey string) error {
|
||||
stored, err := r.store.CurrentStateEvent(ctx, roomID, eventType, stateKey)
|
||||
switch {
|
||||
case isNotFound(err):
|
||||
return nil
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
e, err := parseEvent(stored, rules)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, _ := e.StateKey()
|
||||
out = append(out, StrippedEvent{
|
||||
Type: e.Type(),
|
||||
StateKey: key,
|
||||
Sender: e.Sender(),
|
||||
Content: e.Content(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, eventType := range strippedStateTypes {
|
||||
if err := appendState(eventType, ""); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, member := range members {
|
||||
if err := appendState(event.TypeMember, member); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoomSyncSummary is the `summary` block of a room in a sync response.
|
||||
//
|
||||
// It exists for rooms with no name: a client showing a direct message has
|
||||
// to call it something, and the heroes are the members it names it after.
|
||||
type RoomSyncSummary struct {
|
||||
// Heroes are up to five members of the room other than the user
|
||||
// syncing, which is what a client falls back to for a room with no
|
||||
// name and no canonical alias.
|
||||
Heroes []string `json:"m.heroes,omitempty"`
|
||||
|
||||
JoinedMemberCount int `json:"m.joined_member_count"`
|
||||
InvitedMemberCount int `json:"m.invited_member_count"`
|
||||
}
|
||||
|
||||
// maxHeroes is how many members a summary names. The spec says five.
|
||||
const maxHeroes = 5
|
||||
|
||||
// RoomSummaryFor builds the summary block of a room for one user.
|
||||
func (r *API) RoomSummaryFor(ctx context.Context, roomID, userID string) (RoomSyncSummary, error) {
|
||||
entries, err := r.store.MembershipEntries(ctx, roomID,
|
||||
[]string{event.MembershipJoin, event.MembershipInvite})
|
||||
if err != nil {
|
||||
return RoomSyncSummary{}, err
|
||||
}
|
||||
|
||||
var summary RoomSyncSummary
|
||||
for _, entry := range entries {
|
||||
switch entry.Membership {
|
||||
case event.MembershipJoin:
|
||||
summary.JoinedMemberCount++
|
||||
case event.MembershipInvite:
|
||||
summary.InvitedMemberCount++
|
||||
}
|
||||
if entry.UserID != userID && len(summary.Heroes) < maxHeroes {
|
||||
summary.Heroes = append(summary.Heroes, entry.UserID)
|
||||
}
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
// clientEvents projects stored events into the client shape.
|
||||
func (r *API) clientEvents(stored []storage.StoredEvent, rules roomversion.Rules, roomID string) ([]ClientEvent, error) {
|
||||
out := make([]ClientEvent, 0, len(stored))
|
||||
for _, s := range stored {
|
||||
e, err := parseEvent(s, rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r.clientEvent(s, e, roomID))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// clientEventsByID reads events by ID and projects them.
|
||||
func (r *API) clientEventsByID(ctx context.Context, roomID string, rules roomversion.Rules, eventIDs []string) ([]ClientEvent, error) {
|
||||
if len(eventIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
stored, err := r.store.EventsByID(ctx, roomID, eventIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.clientEvents(stored, rules, roomID)
|
||||
}
|
||||
|
||||
// stateEntryIDs projects state entries onto the event IDs behind them.
|
||||
func stateEntryIDs(entries []storage.StateEntry) []string {
|
||||
out := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
out = append(out, entry.EventID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
package roomserver_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
|
||||
"github.com/dariuszjaniak/warp/server/internal/roomserver"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
)
|
||||
|
||||
// The read model: timeline windows, the state at a position, and the
|
||||
// visible range that bounds both. The visible range is the interesting part
|
||||
// — it is where history visibility is decided, and the one place in the
|
||||
// component where getting it wrong shows somebody a room they left.
|
||||
|
||||
// fill sends n messages into a room and returns their event IDs in order.
|
||||
// The bodies are "line 0", "line 1" and so on, counting from zero within
|
||||
// each call.
|
||||
//
|
||||
// Every send gets its own transaction ID, counted across the whole
|
||||
// fixture. Reusing one would make the second send an idempotent retry of
|
||||
// the first, and a test would then be asserting about a room with half the
|
||||
// events it thought it had.
|
||||
func (f *fixture) fill(roomID, sender string, n int) []string {
|
||||
f.t.Helper()
|
||||
out := make([]string, 0, n)
|
||||
for i := range n {
|
||||
f.sends++
|
||||
eventID, err := f.sendMessage(roomID, sender,
|
||||
"line "+strconv.Itoa(i), "fill-"+strconv.Itoa(f.sends))
|
||||
if err != nil {
|
||||
f.t.Fatalf("sendMessage: %v", err)
|
||||
}
|
||||
out = append(out, eventID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// publicRoom creates a room anybody may join.
|
||||
func (f *fixture) publicRoom() string {
|
||||
f.t.Helper()
|
||||
return f.createRoom(roomserver.CreateRoomRequest{Preset: "public_chat"}).RoomID
|
||||
}
|
||||
|
||||
func (f *fixture) join(roomID, userID string) {
|
||||
f.t.Helper()
|
||||
if _, err := f.api.JoinRoom(f.t.Context(), roomserver.JoinRequest{
|
||||
RoomID: roomID, User: userID,
|
||||
}); err != nil {
|
||||
f.t.Fatalf("JoinRoom(%s): %v", userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fixture) leave(roomID, userID string) {
|
||||
f.t.Helper()
|
||||
if err := f.api.LeaveRoom(f.t.Context(), roomID, userID, ""); err != nil {
|
||||
f.t.Fatalf("LeaveRoom(%s): %v", userID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// bodies projects client events onto their message bodies.
|
||||
func bodies(events []roomserver.ClientEvent) []string {
|
||||
out := make([]string, 0, len(events))
|
||||
for _, e := range events {
|
||||
var content struct {
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Content, &content); err == nil && content.Body != "" {
|
||||
out = append(out, content.Body)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestTimelineIsOldestFirstWhicheverWayItWasRead(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.fill(roomID, alice, 4)
|
||||
|
||||
backwards, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID,
|
||||
User: alice,
|
||||
Direction: storage.DirectionBackward,
|
||||
Limit: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
|
||||
// Reading backwards keeps the newest two, and hands them back oldest
|
||||
// first: a client renders a timeline forwards whichever way it paged.
|
||||
got := bodies(backwards.Events)
|
||||
if len(got) != 2 || got[0] != "line 2" || got[1] != "line 3" {
|
||||
t.Errorf("backwards timeline = %v, want [line 2 line 3]", got)
|
||||
}
|
||||
if !backwards.Limited {
|
||||
t.Error("a window the limit cut short must say so")
|
||||
}
|
||||
if backwards.Start >= backwards.End {
|
||||
t.Errorf("Start %d must sit below End %d", backwards.Start, backwards.End)
|
||||
}
|
||||
|
||||
// Start is below the oldest event, so handing it back as a High bound
|
||||
// returns the page before this one, with nothing repeated.
|
||||
earlier, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID,
|
||||
User: alice,
|
||||
High: backwards.Start,
|
||||
Direction: storage.DirectionBackward,
|
||||
Limit: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
if got := bodies(earlier.Events); len(got) != 2 || got[1] != "line 1" {
|
||||
t.Errorf("the page before = %v, want it to end at \"line 1\"", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimelineEndIsUsableAsTheNextLowBound(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.fill(roomID, alice, 3)
|
||||
|
||||
first, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: alice, Direction: storage.DirectionForward, Limit: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
next, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: alice, Low: first.End,
|
||||
Direction: storage.DirectionForward, Limit: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
|
||||
// Nothing may appear in both pages: End is a position already seen.
|
||||
seen := map[string]bool{}
|
||||
for _, e := range first.Events {
|
||||
seen[e.EventID] = true
|
||||
}
|
||||
for _, e := range next.Events {
|
||||
if seen[e.EventID] {
|
||||
t.Errorf("%s appeared in two consecutive pages", e.EventID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleRangeOfAMember(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
|
||||
visible, err := f.api.VisibleRange(t.Context(), roomID, alice)
|
||||
if err != nil {
|
||||
t.Fatalf("VisibleRange: %v", err)
|
||||
}
|
||||
if !visible.Allowed {
|
||||
t.Fatal("a joined member must be allowed to read the room")
|
||||
}
|
||||
// The default preset is shared history, so a member sees all of it and
|
||||
// is not bounded above.
|
||||
if visible.From != 0 || visible.To != 0 {
|
||||
t.Errorf("range = %+v, want it unbounded for shared history", visible)
|
||||
}
|
||||
if visible.Membership != event.MembershipJoin {
|
||||
t.Errorf("membership = %q, want join", visible.Membership)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleRangeOfAStranger(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
// private_chat is invite-only with shared history: a stranger sees
|
||||
// nothing of it.
|
||||
roomID := f.createRoom(roomserver.CreateRoomRequest{Preset: "private_chat"}).RoomID
|
||||
|
||||
visible, err := f.api.VisibleRange(t.Context(), roomID, bob)
|
||||
if err != nil {
|
||||
t.Fatalf("VisibleRange: %v", err)
|
||||
}
|
||||
if visible.Allowed {
|
||||
t.Error("a stranger must not be allowed to read a private room")
|
||||
}
|
||||
|
||||
if _, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: bob, Direction: storage.DirectionBackward, Limit: 10,
|
||||
}); !errors.Is(err, roomserver.ErrForbidden) {
|
||||
t.Errorf("Timeline for a stranger = %v, want ErrForbidden", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleRangeOfADepartedMemberEndsAtTheirLeave(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.join(roomID, bob)
|
||||
f.fill(roomID, alice, 2)
|
||||
f.leave(roomID, bob)
|
||||
f.fill(roomID, alice, 2)
|
||||
|
||||
visible, err := f.api.VisibleRange(t.Context(), roomID, bob)
|
||||
if err != nil {
|
||||
t.Fatalf("VisibleRange: %v", err)
|
||||
}
|
||||
if !visible.Allowed {
|
||||
t.Fatal("a departed member keeps what they saw while they were in the room")
|
||||
}
|
||||
if visible.To == 0 {
|
||||
t.Fatal("a departed member must be bounded above at their own leave")
|
||||
}
|
||||
|
||||
timeline, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: bob, Direction: storage.DirectionBackward, Limit: 50,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
// They see the two messages sent while they were in the room and
|
||||
// neither of the two sent afterwards. Each fill counts its bodies from
|
||||
// zero, so what is asserted is the count: four messages exist in the
|
||||
// room and Bob may read two of them.
|
||||
if got := bodies(timeline.Events); len(got) != 2 {
|
||||
t.Errorf("a departed member's timeline = %v, want the two messages from before they left", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleRangeWithJoinedHistoryStartsAtTheJoin(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.createRoom(roomserver.CreateRoomRequest{
|
||||
Preset: "public_chat",
|
||||
InitialState: []roomserver.StateEvent{{
|
||||
Type: event.TypeHistoryVisibility,
|
||||
Content: []byte(`{"history_visibility":"joined"}`),
|
||||
}},
|
||||
}).RoomID
|
||||
|
||||
f.fill(roomID, alice, 2)
|
||||
f.join(roomID, bob)
|
||||
f.fill(roomID, alice, 2)
|
||||
|
||||
timeline, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: bob, Direction: storage.DirectionBackward, Limit: 50,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
|
||||
// Only the messages sent after Bob joined. The two sent before carry
|
||||
// the same bodies — each fill counts from zero — so what is asserted
|
||||
// is the count: four messages exist and Bob may read two of them.
|
||||
got := bodies(timeline.Events)
|
||||
want := []string{"line 0", "line 1"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("timeline = %v, want %v", got, want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("timeline = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
// Bob's own member event is the first thing he sees, which is how a
|
||||
// client renders "you joined".
|
||||
var sawOwnJoin bool
|
||||
for _, e := range timeline.Events {
|
||||
if e.Type == event.TypeMember && e.StateKey != nil && *e.StateKey == bob {
|
||||
sawOwnJoin = true
|
||||
}
|
||||
}
|
||||
if !sawOwnJoin {
|
||||
t.Error("a user with joined history visibility must see their own join")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisibleRangeOfAWorldReadableRoom(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.createRoom(roomserver.CreateRoomRequest{
|
||||
Preset: "public_chat",
|
||||
InitialState: []roomserver.StateEvent{{
|
||||
Type: event.TypeHistoryVisibility,
|
||||
Content: []byte(`{"history_visibility":"world_readable"}`),
|
||||
}},
|
||||
}).RoomID
|
||||
f.fill(roomID, alice, 2)
|
||||
|
||||
visible, err := f.api.VisibleRange(t.Context(), roomID, bob)
|
||||
if err != nil {
|
||||
t.Fatalf("VisibleRange: %v", err)
|
||||
}
|
||||
if !visible.Allowed {
|
||||
t.Fatal("a world-readable room is readable by anybody")
|
||||
}
|
||||
|
||||
timeline, err := f.api.Timeline(t.Context(), roomserver.TimelineRequest{
|
||||
RoomID: roomID, User: bob, Direction: storage.DirectionBackward, Limit: 50,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Timeline: %v", err)
|
||||
}
|
||||
if got := bodies(timeline.Events); len(got) != 2 {
|
||||
t.Errorf("a stranger's timeline of a world-readable room = %v, want both messages", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoomStateOfADepartedMemberIsAsOfTheirLeave(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.join(roomID, bob)
|
||||
|
||||
if _, err := f.api.SendEvent(t.Context(), roomserver.SendEventRequest{
|
||||
RoomID: roomID, Sender: alice, Type: roomserver.TypeTopic, StateKey: stringPtr(""),
|
||||
Content: []byte(`{"topic":"while bob was here"}`),
|
||||
}); err != nil {
|
||||
t.Fatalf("setting the topic: %v", err)
|
||||
}
|
||||
f.leave(roomID, bob)
|
||||
if _, err := f.api.SendEvent(t.Context(), roomserver.SendEventRequest{
|
||||
RoomID: roomID, Sender: alice, Type: roomserver.TypeTopic, StateKey: stringPtr(""),
|
||||
Content: []byte(`{"topic":"after bob left"}`),
|
||||
}); err != nil {
|
||||
t.Fatalf("setting the topic again: %v", err)
|
||||
}
|
||||
|
||||
// Phase 3 refused a departed member outright and said so in a comment;
|
||||
// they are now served the room as it was when they left.
|
||||
topic, err := f.api.StateEventContent(t.Context(), roomID, bob, roomserver.TypeTopic, "")
|
||||
if err != nil {
|
||||
t.Fatalf("StateEventContent for a departed member: %v", err)
|
||||
}
|
||||
var content struct {
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
if err := json.Unmarshal(topic, &content); err != nil {
|
||||
t.Fatalf("unmarshal the topic: %v", err)
|
||||
}
|
||||
if content.Topic != "while bob was here" {
|
||||
t.Errorf("topic = %q, want the one in force when they left", content.Topic)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventOutsideTheVisibleRangeIsUnknown(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.join(roomID, bob)
|
||||
f.leave(roomID, bob)
|
||||
|
||||
later := f.fill(roomID, alice, 1)[0]
|
||||
|
||||
// Not "forbidden": whether a particular event ID exists in a room is
|
||||
// itself something a departed member is not entitled to know.
|
||||
if _, err := f.api.Event(t.Context(), roomID, bob, later); !errors.Is(err, roomserver.ErrNoSuchEvent) {
|
||||
t.Errorf("Event after a leave = %v, want ErrNoSuchEvent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoomSummaryCountsAndHeroes(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.publicRoom()
|
||||
f.join(roomID, bob)
|
||||
if err := f.api.InviteUser(t.Context(), roomserver.InviteRequest{
|
||||
RoomID: roomID, Sender: alice, Target: carol,
|
||||
}); err != nil {
|
||||
t.Fatalf("InviteUser: %v", err)
|
||||
}
|
||||
|
||||
summary, err := f.api.RoomSummaryFor(t.Context(), roomID, alice)
|
||||
if err != nil {
|
||||
t.Fatalf("RoomSummaryFor: %v", err)
|
||||
}
|
||||
if summary.JoinedMemberCount != 2 {
|
||||
t.Errorf("joined = %d, want 2", summary.JoinedMemberCount)
|
||||
}
|
||||
if summary.InvitedMemberCount != 1 {
|
||||
t.Errorf("invited = %d, want 1", summary.InvitedMemberCount)
|
||||
}
|
||||
// The heroes are everybody but the user asking: a client names a room
|
||||
// after the other people in it.
|
||||
for _, hero := range summary.Heroes {
|
||||
if hero == alice {
|
||||
t.Errorf("heroes = %v, want it to leave out the user asking", summary.Heroes)
|
||||
}
|
||||
}
|
||||
if len(summary.Heroes) != 2 {
|
||||
t.Errorf("heroes = %v, want both the other members", summary.Heroes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrippedStateIsEnoughToRenderAnInvite(t *testing.T) {
|
||||
f := newFixture(t, nil)
|
||||
roomID := f.createRoom(roomserver.CreateRoomRequest{
|
||||
Preset: "private_chat",
|
||||
Name: "The Study",
|
||||
}).RoomID
|
||||
if err := f.api.InviteUser(t.Context(), roomserver.InviteRequest{
|
||||
RoomID: roomID, Sender: alice, Target: bob,
|
||||
}); err != nil {
|
||||
t.Fatalf("InviteUser: %v", err)
|
||||
}
|
||||
|
||||
stripped, err := f.api.StrippedState(t.Context(), roomID, []string{bob, alice})
|
||||
if err != nil {
|
||||
t.Fatalf("StrippedState: %v", err)
|
||||
}
|
||||
|
||||
types := map[string]bool{}
|
||||
for _, e := range stripped {
|
||||
types[e.Type] = true
|
||||
// Stripped state is explicitly not an event, so it carries no ID
|
||||
// and no timestamp: a client must not put it in a timeline.
|
||||
if e.Sender == "" {
|
||||
t.Errorf("stripped %s has no sender", e.Type)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{event.TypeCreate, event.TypeJoinRules, roomserver.TypeName, event.TypeMember} {
|
||||
if !types[want] {
|
||||
t.Errorf("stripped state is missing %s (have %v)", want, types)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package roomserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/roomversion"
|
||||
)
|
||||
|
||||
// VisibleRange is the span of a room's event stream a user may read.
|
||||
//
|
||||
// It is a range rather than a yes or no because membership is not a yes or
|
||||
// no either. A user who has left a room keeps what they saw while they were
|
||||
// in it and sees nothing after their leave; a user who joined a room whose
|
||||
// history visibility is `joined` sees nothing from before their join. Both
|
||||
// are the same question — where does this user's window start and end — and
|
||||
// answering it once per room is what lets a timeline read be a single
|
||||
// bounded query rather than a filter applied to every event in it.
|
||||
type VisibleRange struct {
|
||||
// Allowed is false when the user may see nothing of the room at all.
|
||||
Allowed bool
|
||||
|
||||
// From is the first position the user may see, exclusive. Zero means
|
||||
// the start of the room.
|
||||
From int64
|
||||
|
||||
// To is the last position the user may see, inclusive. Zero means the
|
||||
// top of the stream, and goes on meaning that as the stream grows.
|
||||
To int64
|
||||
|
||||
// Membership is the user's current membership, empty for a user who was
|
||||
// never in the room.
|
||||
Membership string
|
||||
|
||||
// HistoryVisibility is the room's current history visibility, which the
|
||||
// bounds above were derived from.
|
||||
HistoryVisibility string
|
||||
}
|
||||
|
||||
// Contains reports whether a position is inside the range.
|
||||
func (v VisibleRange) Contains(pos int64) bool {
|
||||
switch {
|
||||
case !v.Allowed:
|
||||
return false
|
||||
case pos <= v.From:
|
||||
return false
|
||||
case v.To != 0 && pos > v.To:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Clamp narrows a caller's window to what the range allows, reporting
|
||||
// whether anything is left of it.
|
||||
//
|
||||
// The bounds are exclusive at the bottom and inclusive at the top, the same
|
||||
// as a storage.TimelineRequest, so the result can be handed straight to
|
||||
// one.
|
||||
func (v VisibleRange) Clamp(from, to int64) (int64, int64, bool) {
|
||||
if !v.Allowed {
|
||||
return 0, 0, false
|
||||
}
|
||||
from = max(from, v.From)
|
||||
if v.To != 0 && (to == 0 || to > v.To) {
|
||||
to = v.To
|
||||
}
|
||||
if to != 0 && from >= to {
|
||||
return 0, 0, false
|
||||
}
|
||||
return from, to, true
|
||||
}
|
||||
|
||||
// VisibleRange works out what a user may read of a room.
|
||||
//
|
||||
// The rules are the spec's history visibility:
|
||||
//
|
||||
// - world_readable: everything, to anybody, member or not.
|
||||
// - shared: everything, to anybody who is or has been a member.
|
||||
// - invited: from the user's invite onwards.
|
||||
// - joined: from the user's join onwards.
|
||||
//
|
||||
// A user who has left or was banned is bounded at their own membership
|
||||
// event in every case, which is what stops a kicked user's client from
|
||||
// going on streaming the room. An invitee is told enough to decide — the
|
||||
// stripped state that travels with the invite — and no timeline.
|
||||
//
|
||||
// The approximation here is the room's *current* history visibility. The
|
||||
// spec judges each event by the visibility in force when it was sent, so a
|
||||
// room that was once world_readable and is now `joined` hides history here
|
||||
// that the spec would show, and the reverse shows history it would hide.
|
||||
// Doing it exactly means resolving the history visibility at every event in
|
||||
// the window — a state read per event — and belongs with the state storage
|
||||
// work of PLAN.md open question 1. Until then this follows the setting the
|
||||
// room's members last agreed on, which is the one they would expect to
|
||||
// apply.
|
||||
func (r *API) VisibleRange(ctx context.Context, roomID, userID string) (VisibleRange, error) {
|
||||
room, rules, err := r.roomAndRules(ctx, roomID)
|
||||
if err != nil {
|
||||
return VisibleRange{}, err
|
||||
}
|
||||
summary, err := r.store.RoomSummary(ctx, room.ID)
|
||||
if err != nil {
|
||||
return VisibleRange{}, err
|
||||
}
|
||||
return r.visibleRange(ctx, roomID, rules, userID, summary.HistoryVisibility)
|
||||
}
|
||||
|
||||
// visibleRange is VisibleRange with the room's history visibility already
|
||||
// in hand, for the callers — a sync over many rooms — that have it.
|
||||
func (r *API) visibleRange(ctx context.Context, roomID string, rules roomversion.Rules, userID, historyVisibility string) (VisibleRange, error) {
|
||||
out := VisibleRange{HistoryVisibility: historyVisibility}
|
||||
|
||||
changes, err := r.membershipHistory(ctx, roomID, rules, userID)
|
||||
if err != nil {
|
||||
return VisibleRange{}, err
|
||||
}
|
||||
if len(changes) > 0 {
|
||||
out.Membership = changes[len(changes)-1].membership
|
||||
}
|
||||
|
||||
worldReadable := historyVisibility == HistoryVisibilityWorldReadable
|
||||
switch out.Membership {
|
||||
case event.MembershipJoin:
|
||||
out.Allowed = true
|
||||
case event.MembershipLeave, event.MembershipBan:
|
||||
out.Allowed = true
|
||||
// Bounded at their own membership event: what they saw stays
|
||||
// theirs, what happened afterwards does not.
|
||||
out.To = changes[len(changes)-1].position
|
||||
default:
|
||||
// Invited, knocking, or never a member. Only a world-readable room
|
||||
// has anything to show them.
|
||||
out.Allowed = worldReadable
|
||||
}
|
||||
|
||||
// World-readable removes the floor — they could read the room as a
|
||||
// stranger, so there is nothing to gain by hiding it from them as a
|
||||
// member — but not the ceiling: a leaver's *membership* view still ends
|
||||
// where they left, and the stranger's view is what /messages on a
|
||||
// world-readable room gives them anyway.
|
||||
if !worldReadable && out.Allowed {
|
||||
switch historyVisibility {
|
||||
case HistoryVisibilityInvited, HistoryVisibilityJoined:
|
||||
out.From = spanStart(changes, historyVisibility)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// membershipChange is one of a user's membership events in a room.
|
||||
type membershipChange struct {
|
||||
membership string
|
||||
position int64
|
||||
}
|
||||
|
||||
// membershipHistory reads a user's membership events in a room, oldest
|
||||
// first.
|
||||
func (r *API) membershipHistory(ctx context.Context, roomID string, rules roomversion.Rules, userID string) ([]membershipChange, error) {
|
||||
stored, err := r.store.UserMembershipEvents(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]membershipChange, 0, len(stored))
|
||||
for _, s := range stored {
|
||||
e, err := parseEvent(s, rules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
membership, err := e.Membership()
|
||||
if err != nil {
|
||||
// A member event with no membership could not have been
|
||||
// accepted into the room, so this is a corrupted row rather
|
||||
// than something a client sent. Skipping it would widen the
|
||||
// window silently.
|
||||
return nil, fmt.Errorf("member event %s of %s has no membership: %w", s.EventID, roomID, err)
|
||||
}
|
||||
out = append(out, membershipChange{membership: membership, position: s.StreamOrdering})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// spanStart is the floor of the user's current membership span, exclusive.
|
||||
//
|
||||
// For `joined` visibility that is the join that began the span they are in
|
||||
// — or, for a user who has left, the one that began the span they left
|
||||
// from. For `invited` it is the invite that preceded that join, because an
|
||||
// invitee is entitled to the room from the moment they were asked.
|
||||
//
|
||||
// A user who joined, left and rejoined therefore sees their latest span and
|
||||
// not the earlier ones, which is what the spec's per-event rule works out
|
||||
// to for everything after their last join.
|
||||
func spanStart(changes []membershipChange, historyVisibility string) int64 {
|
||||
// Walk back to the membership event that opened the current span.
|
||||
start := len(changes) - 1
|
||||
for start > 0 && changes[start].membership != event.MembershipJoin {
|
||||
start--
|
||||
}
|
||||
for start > 0 && changes[start-1].membership == event.MembershipJoin {
|
||||
// Consecutive joins are profile changes, not rejoins; the span
|
||||
// began at the first of them.
|
||||
start--
|
||||
}
|
||||
if historyVisibility == HistoryVisibilityInvited &&
|
||||
start > 0 && changes[start-1].membership == event.MembershipInvite {
|
||||
start--
|
||||
}
|
||||
// Exclusive, so one below the event itself: the membership event is the
|
||||
// first thing the user sees, which is how a client renders "you joined".
|
||||
return changes[start].position - 1
|
||||
}
|
||||
|
||||
// requireReadable refuses a caller who may see nothing of a room, and
|
||||
// returns the range for one who may.
|
||||
func (r *API) requireReadable(ctx context.Context, roomID, userID string) (VisibleRange, error) {
|
||||
visible, err := r.VisibleRange(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return VisibleRange{}, err
|
||||
}
|
||||
return visible, visible.refusal(roomID, userID)
|
||||
}
|
||||
|
||||
// refusal turns a range that allows nothing into the error a client is
|
||||
// given for it.
|
||||
func (v VisibleRange) refusal(roomID, userID string) error {
|
||||
if v.Allowed {
|
||||
return nil
|
||||
}
|
||||
if v.Membership == event.MembershipInvite {
|
||||
return fmt.Errorf("%w: %s has been invited to %s but has not joined it",
|
||||
ErrForbidden, userID, roomID)
|
||||
}
|
||||
return fmt.Errorf("%w: %s is not in %s", ErrForbidden, userID, roomID)
|
||||
}
|
||||
Reference in new issue
Block a user