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
@@ -0,0 +1,267 @@
|
||||
package syncapi
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/matrix/event"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
)
|
||||
|
||||
// The receipt types the Client-Server API defines.
|
||||
const (
|
||||
// ReceiptRead is public: everybody in the room sees it.
|
||||
ReceiptRead = "m.read"
|
||||
|
||||
// ReceiptReadPrivate is the user's own, and is reported only back to
|
||||
// them. It exists so that a user can mark a room read without telling
|
||||
// the room they read it.
|
||||
ReceiptReadPrivate = "m.read.private"
|
||||
|
||||
// ReceiptFullyRead is not a receipt at all: it is the read marker, and
|
||||
// is stored as the room account data type m.fully_read. It is named
|
||||
// here because POST /read_markers takes all three in one body.
|
||||
ReceiptFullyRead = "m.fully_read"
|
||||
)
|
||||
|
||||
// requireJoined refuses a caller who is not in the room.
|
||||
//
|
||||
// Every write in this file is a claim about a room — "I am typing in it",
|
||||
// "I have read this far" — rather than data belonging to the caller, so
|
||||
// being in the room is the condition for all of them.
|
||||
func (s *API) requireJoined(ctx context.Context, roomID, userID string) error {
|
||||
membership, err := s.rooms.Membership(ctx, roomID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if membership != event.MembershipJoin {
|
||||
return errForbiddenf("%s is not joined to %s", userID, roomID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReceiptRequest is POST /rooms/{roomID}/receipt/{receiptType}/{eventID}.
|
||||
type ReceiptRequest struct {
|
||||
RoomID string
|
||||
|
||||
// User is the full user ID sending the receipt.
|
||||
User string
|
||||
|
||||
ReceiptType string
|
||||
EventID string
|
||||
|
||||
// ThreadID is the thread the receipt is for, or empty for the room's
|
||||
// main timeline. Threads are PLAN.md phase 10; the value is stored so
|
||||
// that a client that sends one gets it back, rather than having its
|
||||
// threaded receipt silently collapse onto the main timeline's.
|
||||
ThreadID string
|
||||
}
|
||||
|
||||
// SetReceipt records a read receipt.
|
||||
func (s *API) SetReceipt(ctx context.Context, req ReceiptRequest) error {
|
||||
switch req.ReceiptType {
|
||||
case ReceiptRead, ReceiptReadPrivate, ReceiptFullyRead:
|
||||
default:
|
||||
return errInvalidParamf("%q is not a receipt type this server accepts", req.ReceiptType)
|
||||
}
|
||||
|
||||
if err := s.requireJoined(ctx, req.RoomID, req.User); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The spec routes m.fully_read through this endpoint too, and it is
|
||||
// account data rather than a receipt — but it is still a claim about a
|
||||
// room the caller has to be in, which is why the check above comes
|
||||
// first.
|
||||
if req.ReceiptType == ReceiptFullyRead {
|
||||
return s.setFullyRead(ctx, req.RoomID, req.User, req.EventID)
|
||||
}
|
||||
|
||||
_, moved, err := s.store.SetReceipt(ctx, storage.Receipt{
|
||||
RoomID: req.RoomID,
|
||||
UserID: req.User,
|
||||
ReceiptType: req.ReceiptType,
|
||||
ThreadID: req.ThreadID,
|
||||
EventID: req.EventID,
|
||||
TimestampMS: s.nowMS(),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Nothing moved means the user had already read further, and there is
|
||||
// nothing for anybody to be woken about.
|
||||
if !moved {
|
||||
return nil
|
||||
}
|
||||
// A private receipt concerns only its sender; a public one is part of
|
||||
// the room's ephemeral stream and everybody in it wants it.
|
||||
if req.ReceiptType == ReceiptReadPrivate {
|
||||
s.notifier.NotifyUser(req.User)
|
||||
return nil
|
||||
}
|
||||
s.notifier.NotifyRoom(req.RoomID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadMarkersRequest is POST /rooms/{roomID}/read_markers.
|
||||
type ReadMarkersRequest struct {
|
||||
RoomID string
|
||||
User string
|
||||
|
||||
// FullyRead is the event up to which the user has read, stored as the
|
||||
// room account data m.fully_read. It is where a client draws the
|
||||
// "unread from here" line, which is a different thing from a receipt:
|
||||
// the line stays where the user left it even as they scroll past.
|
||||
FullyRead string
|
||||
|
||||
// Read and ReadPrivate are ordinary receipts, sent in the same request
|
||||
// because a client moving the marker almost always moves both.
|
||||
Read string
|
||||
ReadPrivate string
|
||||
}
|
||||
|
||||
// SetReadMarkers implements the read markers endpoint: up to three
|
||||
// independent writes from one request.
|
||||
//
|
||||
// They are not atomic, and cannot usefully be: the marker is account data
|
||||
// and the receipts are the receipt stream, which are two streams with two
|
||||
// positions. A failure partway through leaves the earlier writes in place,
|
||||
// which is the same state a client would reach by sending them separately
|
||||
// and losing its connection — and which the next call corrects.
|
||||
func (s *API) SetReadMarkers(ctx context.Context, req ReadMarkersRequest) error {
|
||||
if err := s.requireJoined(ctx, req.RoomID, req.User); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.FullyRead != "" {
|
||||
if err := s.setFullyRead(ctx, req.RoomID, req.User, req.FullyRead); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, receipt := range []struct {
|
||||
receiptType string
|
||||
eventID string
|
||||
}{
|
||||
{ReceiptRead, req.Read},
|
||||
{ReceiptReadPrivate, req.ReadPrivate},
|
||||
} {
|
||||
if receipt.eventID == "" {
|
||||
continue
|
||||
}
|
||||
if err := s.SetReceipt(ctx, ReceiptRequest{
|
||||
RoomID: req.RoomID,
|
||||
User: req.User,
|
||||
ReceiptType: receipt.receiptType,
|
||||
EventID: receipt.eventID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setFullyRead writes the read marker as room account data.
|
||||
func (s *API) setFullyRead(ctx context.Context, roomID, userID, eventID string) error {
|
||||
localpart, ok := s.localpartOf(userID)
|
||||
if !ok {
|
||||
return errForbiddenf("%s is not a user of this server", userID)
|
||||
}
|
||||
content, err := json.Marshal(map[string]string{"event_id": eventID})
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshalling the read marker: %w", err)
|
||||
}
|
||||
if err := s.accounts.SetAccountData(ctx, localpart, roomID, ReceiptFullyRead, content); err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifier.NotifyUser(userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// receiptsEvent builds the m.receipt EDU of one room.
|
||||
//
|
||||
// The shape is the spec's, and it is an awkward one: a map of event ID to
|
||||
// receipt type to user ID to the receipt's data. It is nested that way
|
||||
// because a client's job is to answer "who has read up to this event",
|
||||
// which this shape makes a lookup and a flat list would make a scan.
|
||||
func receiptsEvent(receipts []storage.Receipt) *EphemeralEvent {
|
||||
if len(receipts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
type receiptData struct {
|
||||
TS int64 `json:"ts"`
|
||||
ThreadID string `json:"thread_id,omitempty"`
|
||||
}
|
||||
content := map[string]map[string]map[string]receiptData{}
|
||||
for _, r := range receipts {
|
||||
byType, ok := content[r.EventID]
|
||||
if !ok {
|
||||
byType = map[string]map[string]receiptData{}
|
||||
content[r.EventID] = byType
|
||||
}
|
||||
byUser, ok := byType[r.ReceiptType]
|
||||
if !ok {
|
||||
byUser = map[string]receiptData{}
|
||||
byType[r.ReceiptType] = byUser
|
||||
}
|
||||
byUser[r.UserID] = receiptData{TS: r.TimestampMS, ThreadID: r.ThreadID}
|
||||
}
|
||||
|
||||
body, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
// Every value here is a string or an integer, so this cannot
|
||||
// happen; dropping the EDU beats failing the sync if it does.
|
||||
return nil
|
||||
}
|
||||
return &EphemeralEvent{Type: "m.receipt", Content: body}
|
||||
}
|
||||
|
||||
// roomReceipts reads the receipts a user is entitled to see in a set of
|
||||
// rooms, between two positions.
|
||||
//
|
||||
// Private receipts are filtered here rather than in SQL: the query is the
|
||||
// same one the public receipts come from, and a WHERE clause that had to
|
||||
// name the asking user would turn one query per sync into two.
|
||||
func (s *API) roomReceipts(ctx context.Context, userID string, roomIDs []string, from, to int64) (map[string][]storage.Receipt, error) {
|
||||
if len(roomIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
receipts, err := s.store.Receipts(ctx, roomIDs, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// An initial sync also wants the user's own receipts however old they
|
||||
// are: a client that has just logged in has to know where it had read
|
||||
// up to, and that receipt was set long before this sync's window.
|
||||
if from == 0 {
|
||||
own, err := s.store.ReceiptsForUser(ctx, userID, roomIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
receipts = append(receipts, own...)
|
||||
}
|
||||
|
||||
out := map[string][]storage.Receipt{}
|
||||
seen := map[storage.Receipt]struct{}{}
|
||||
for _, r := range receipts {
|
||||
if r.ReceiptType == ReceiptReadPrivate && r.UserID != userID {
|
||||
continue
|
||||
}
|
||||
if _, dup := seen[r]; dup {
|
||||
// The user's own receipts can arrive from both reads above.
|
||||
continue
|
||||
}
|
||||
seen[r] = struct{}{}
|
||||
out[r.RoomID] = append(out[r.RoomID], r)
|
||||
}
|
||||
for roomID := range out {
|
||||
slices.SortFunc(out[roomID], func(a, b storage.Receipt) int {
|
||||
return cmp.Compare(a.StreamPos, b.StreamPos)
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Reference in new issue
Block a user