Files
Warp/server/internal/syncapi/typing.go
T
tajniak81andClaude Opus 5.5 6aaf554336
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s
Phase 5: federation
Implements PLAN.md Phase 5: the Server-Server API. Warp joins rooms on
other servers and lets their users join its rooms, invites across servers
with the invitee's server countersigning, rejects remote invites (locally
if the inviter is unreachable), and exchanges events, typing, receipts and
to-device messages with other homeservers — all behind the runtime switch,
which now starts and stops real outbound traffic.

The protocol lives in internal/federation with no knowledge of rooms:
X-Matrix signing (fuzzed parser), the spec's discovery algorithm keeping
the dial address and the TLS name apart, a signed client that refuses
every request while the switch is off or the policy denies the
destination, and a key ring that caches other servers' keys for at most a
week, with optional notaries.

The roomserver takes events from elsewhere through the spec's intake:
signatures and hashes (a hash mismatch keeps the redacted form), the rules
against the event's own auth events, against the state before it — with
/get_missing_events for small gaps and /state_ids for wide ones — and
against the current state, where a failure is a soft failure. Events held
without their state are outliers: a column on roomserver_events, because
the current state of a room joined over federation is almost all
outliers, and excluded from every timeline query. Forks are resolved at
the room's head. Membership across servers is make_join/send_join,
make_leave/send_leave and countersigned invites, in both directions;
m.room.server_acl is enforced on everything another server sends.
History before a remote join is backfilled when /messages pages past it,
stored at negative stream positions.

internal/federationapi is the running component: the inbound endpoints,
and an outbound queue that persists what it owes each destination, sends
it in transactions of 50 PDUs and 100 EDUs, backs off from ten seconds to
six hours, survives restarts, and drops events persisted while federation
is off rather than delivering a backlog in one burst. Its Module is what
the switch starts and stops.

Also: a TLS listener for port 8448, trusted key servers, key validity and
an outbound CA bundle in the config; per-destination health and backoff
reset in the admin API; remote profiles, aliases and directories in the
Client-Server API; a Complement federation profile. See
docs/federation.md, including its known gaps (no partial-state joins, no
key rotation).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 17:14:20 +02:00

224 lines
6.0 KiB
Go

package syncapi
import (
"context"
"encoding/json"
"slices"
"sync"
"time"
)
// Typing notifications are held in memory and nowhere else.
//
// They expire in seconds, they are worthless after a restart — nobody is
// still typing the message they were typing when the server went down —
// and they arrive one per keystroke-burst per room. Writing them to disk
// would be the busiest table in the database, holding the least valuable
// data in it. Dendrite reaches the same conclusion.
//
// The cost of the choice is that a restart clears them, which a client
// cannot tell from everybody having stopped typing, and that a second
// process would not see them. The second only matters when Warp stops
// being one process, which PLAN.md says is not the plan.
// typingTracker holds who is typing in which room, and expires them.
type typingTracker struct {
timeout time.Duration
notifier *Notifier
now func() time.Time
mu sync.Mutex
// rooms is room ID -> user ID -> when the notification expires.
rooms map[string]map[string]time.Time
// timers hold the expiry wake-ups, so that a notification running out
// reaches a blocked sync rather than waiting for one to ask.
timers map[typingKey]*time.Timer
closed bool
}
type typingKey struct {
roomID string
userID string
}
func newTypingTracker(timeout time.Duration, notifier *Notifier, now func() time.Time) *typingTracker {
return &typingTracker{
timeout: timeout,
notifier: notifier,
now: now,
rooms: map[string]map[string]time.Time{},
timers: map[typingKey]*time.Timer{},
}
}
// set records that a user is typing in a room for a while, or stops them.
//
// The timeout a client asks for is honoured up to the configured cap: a
// client that asks for an hour would leave the room claiming somebody was
// typing long after they closed it.
func (t *typingTracker) set(roomID, userID string, typing bool, timeout time.Duration) {
t.mu.Lock()
if t.closed {
t.mu.Unlock()
return
}
key := typingKey{roomID: roomID, userID: userID}
if timer, ok := t.timers[key]; ok {
timer.Stop()
delete(t.timers, key)
}
switch {
case !typing:
if users, ok := t.rooms[roomID]; ok {
delete(users, userID)
if len(users) == 0 {
delete(t.rooms, roomID)
}
}
default:
if timeout <= 0 || timeout > t.timeout {
timeout = t.timeout
}
users, ok := t.rooms[roomID]
if !ok {
users = map[string]time.Time{}
t.rooms[roomID] = users
}
users[userID] = t.now().Add(timeout)
t.timers[key] = time.AfterFunc(timeout, func() { t.expire(key) })
}
t.mu.Unlock()
// Outside the lock: the notifier takes its own, and a sync woken by it
// will want to read this tracker.
t.notifier.NotifyRoom(roomID)
}
// expire drops a notification whose timer has fired and wakes the room.
func (t *typingTracker) expire(key typingKey) {
t.mu.Lock()
delete(t.timers, key)
users, ok := t.rooms[key.roomID]
if ok {
delete(users, key.userID)
if len(users) == 0 {
delete(t.rooms, key.roomID)
}
}
t.mu.Unlock()
if ok {
t.notifier.NotifyRoom(key.roomID)
}
}
// users lists who is typing in a room, sorted, skipping anyone whose
// notification has run out.
//
// The expiry check is here as well as in the timer because the two answer
// different failure modes: the timer wakes a blocked client, and this makes
// sure a notification is never *reported* after its deadline even if the
// timer has not run yet.
func (t *typingTracker) users(roomID string) []string {
t.mu.Lock()
defer t.mu.Unlock()
now := t.now()
out := make([]string, 0, len(t.rooms[roomID]))
for userID, expires := range t.rooms[roomID] {
if expires.After(now) {
out = append(out, userID)
}
}
slices.Sort(out)
return out
}
// rooms with anybody typing, which is how a sync knows a room has an
// ephemeral change without asking per room.
func (t *typingTracker) activeRooms() []string {
t.mu.Lock()
defer t.mu.Unlock()
now := t.now()
out := make([]string, 0, len(t.rooms))
for roomID, users := range t.rooms {
for _, expires := range users {
if expires.After(now) {
out = append(out, roomID)
break
}
}
}
slices.Sort(out)
return out
}
// close stops every timer. A server shutting down should not be held up by
// a typing notification.
func (t *typingTracker) close() {
t.mu.Lock()
defer t.mu.Unlock()
t.closed = true
for key, timer := range t.timers {
timer.Stop()
delete(t.timers, key)
}
t.rooms = map[string]map[string]time.Time{}
}
// TypingRequest is PUT /rooms/{roomID}/typing/{userID}.
type TypingRequest struct {
RoomID string
// User is the full user ID said to be typing, which the handler has
// already checked is the caller.
User string
Typing bool
// Timeout is how long the notification should last. Zero takes the
// server's own.
Timeout time.Duration
}
// SetTyping records a typing notification.
//
// Being in the room is required: a typing notification is published to
// everybody in it, so it is a write to the room even though it is not an
// event in it.
func (s *API) SetTyping(ctx context.Context, req TypingRequest) error {
if err := s.requireJoined(ctx, req.RoomID, req.User); err != nil {
return err
}
s.typing.set(req.RoomID, req.User, req.Typing, req.Timeout)
if s.outbound != nil && s.isLocal(req.User) {
s.outbound.Typing(ctx, req.RoomID, req.User, req.Typing, req.Timeout)
}
return nil
}
// typingEvent is the m.typing EDU of a room, or nil when nobody is typing.
//
// The event is the whole list rather than a delta, which is what the spec
// defines: a client replaces what it had, so a missed update corrects
// itself on the next one.
func (s *API) typingEvent(roomID string) *EphemeralEvent {
users := s.typing.users(roomID)
if len(users) == 0 {
return nil
}
content, err := json.Marshal(map[string][]string{"user_ids": users})
if err != nil {
// Marshalling a list of strings cannot fail; if it somehow did,
// dropping the notification is better than failing the sync.
s.log.Error("marshalling a typing notification failed", "room_id", roomID, "error", err)
return nil
}
return &EphemeralEvent{Type: "m.typing", Content: content}
}