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,585 @@
|
||||
package sqlstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
)
|
||||
|
||||
// Sync is the shared SQL implementation of storage.SyncStore: the streams a
|
||||
// sync response carries that are not room events.
|
||||
//
|
||||
// Like the other component stores it is written once with `?` placeholders
|
||||
// and rebound per driver. Every stream here follows the same shape — a
|
||||
// counter row handed out inside the writing transaction, and a stream_pos
|
||||
// column on the row it stamps — so that a reader can ask any of them "what
|
||||
// changed after position N" with one index lookup.
|
||||
type Sync struct {
|
||||
db *sql.DB
|
||||
rebind func(string) string
|
||||
isUnique func(error) bool
|
||||
}
|
||||
|
||||
// NewSync builds a sync store.
|
||||
func NewSync(db *sql.DB, rebind func(string) string, isUnique func(error) bool) *Sync {
|
||||
if rebind == nil {
|
||||
rebind = func(query string) string { return query }
|
||||
}
|
||||
if isUnique == nil {
|
||||
isUnique = func(error) bool { return false }
|
||||
}
|
||||
return &Sync{db: db, rebind: rebind, isUnique: isUnique}
|
||||
}
|
||||
|
||||
// maxToDeviceBatch bounds how many to-device messages one sync carries. A
|
||||
// device that has been offline for a week can have a long queue, and the
|
||||
// rest of it is still there on the next sync.
|
||||
const maxToDeviceBatch = 100
|
||||
|
||||
// q rebinds a statement for this driver.
|
||||
func (s *Sync) q(query string) string { return s.rebind(query) }
|
||||
|
||||
// tx runs fn in a transaction, rolling back on any error.
|
||||
func (s *Sync) tx(ctx context.Context, fn func(*sql.Tx) error) error {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
if err := fn(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const selectStreamPositionsSQL = `
|
||||
SELECT name, value FROM sync_sequences`
|
||||
|
||||
// StreamPositions implements storage.SyncStore.
|
||||
//
|
||||
// The PDU position comes from the events table and the rest from the
|
||||
// counter rows, and both are read here so that a caller gets one consistent
|
||||
// set. The counters are read rather than the rows they stamp because a
|
||||
// stream whose latest row was deleted — a drained to-device queue — must
|
||||
// not appear to have gone backwards.
|
||||
func (s *Sync) StreamPositions(ctx context.Context) (storage.StreamPositions, error) {
|
||||
var out storage.StreamPositions
|
||||
|
||||
err := s.db.QueryRowContext(ctx, s.q(selectMaxStreamOrderingSQL)).Scan(&out.PDU)
|
||||
if err != nil {
|
||||
return storage.StreamPositions{}, fmt.Errorf("read the top of the event stream: %w", err)
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, s.q(selectStreamPositionsSQL))
|
||||
if err != nil {
|
||||
return storage.StreamPositions{}, fmt.Errorf("read the stream positions: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
for rows.Next() {
|
||||
var (
|
||||
name string
|
||||
value int64
|
||||
)
|
||||
if err := rows.Scan(&name, &value); err != nil {
|
||||
return storage.StreamPositions{}, fmt.Errorf("read the stream positions: %w", err)
|
||||
}
|
||||
switch name {
|
||||
case seqReceipt:
|
||||
out.Receipt = value
|
||||
case seqToDevice:
|
||||
out.ToDevice = value
|
||||
case seqAccountData:
|
||||
out.AccountData = value
|
||||
case seqPresence:
|
||||
out.Presence = value
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return storage.StreamPositions{}, fmt.Errorf("read the stream positions: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
const (
|
||||
selectReceiptPositionSQL = `
|
||||
SELECT e.stream_ordering FROM roomserver_events e
|
||||
WHERE e.room_id = ? AND e.event_id = ?`
|
||||
|
||||
selectCurrentReceiptSQL = `
|
||||
SELECT r.event_id, e.stream_ordering, r.stream_pos
|
||||
FROM sync_receipts r
|
||||
LEFT JOIN roomserver_events e ON e.event_id = r.event_id
|
||||
WHERE r.room_id = ? AND r.user_id = ? AND r.receipt_type = ? AND r.thread_id = ?`
|
||||
|
||||
upsertReceiptSQL = `
|
||||
INSERT INTO sync_receipts
|
||||
(room_id, user_id, receipt_type, thread_id, event_id, ts_ms, stream_pos)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (room_id, user_id, receipt_type, thread_id) DO UPDATE SET
|
||||
event_id = excluded.event_id,
|
||||
ts_ms = excluded.ts_ms,
|
||||
stream_pos = excluded.stream_pos`
|
||||
)
|
||||
|
||||
// SetReceipt implements storage.SyncStore.
|
||||
//
|
||||
// A receipt that would move backwards is dropped. Two clients of one user
|
||||
// read a room at different speeds, and letting the slower one win would
|
||||
// make the unread marker jump backwards on the other — so the comparison is
|
||||
// on the position of the event being acknowledged, not on when the receipt
|
||||
// arrived.
|
||||
func (s *Sync) SetReceipt(ctx context.Context, r storage.Receipt) (int64, bool, error) {
|
||||
var (
|
||||
pos int64
|
||||
moved bool
|
||||
)
|
||||
err := s.tx(ctx, func(tx *sql.Tx) error {
|
||||
var target int64
|
||||
err := tx.QueryRowContext(ctx, s.q(selectReceiptPositionSQL), r.RoomID, r.EventID).Scan(&target)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return fmt.Errorf("event %q: %w", r.EventID, storage.ErrNoSuchEvent)
|
||||
case err != nil:
|
||||
return fmt.Errorf("locate the event a receipt names: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
haveEventID string
|
||||
havePos sql.NullInt64
|
||||
haveStream int64
|
||||
)
|
||||
err = tx.QueryRowContext(ctx, s.q(selectCurrentReceiptSQL),
|
||||
r.RoomID, r.UserID, r.ReceiptType, r.ThreadID).Scan(&haveEventID, &havePos, &haveStream)
|
||||
switch {
|
||||
case err == nil:
|
||||
// A receipt whose event has since been purged has no position
|
||||
// to compare against, and the new one supersedes it.
|
||||
if havePos.Valid && havePos.Int64 >= target {
|
||||
pos, moved = haveStream, false
|
||||
return nil
|
||||
}
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return fmt.Errorf("read the current receipt: %w", err)
|
||||
}
|
||||
|
||||
if pos, err = nextSequence(ctx, tx, s.q, syncSequences, seqReceipt); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, s.q(upsertReceiptSQL),
|
||||
r.RoomID, r.UserID, r.ReceiptType, r.ThreadID, r.EventID, r.TimestampMS, pos); err != nil {
|
||||
return fmt.Errorf("write the receipt: %w", err)
|
||||
}
|
||||
moved = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("set receipt in %q: %w", r.RoomID, err)
|
||||
}
|
||||
return pos, moved, nil
|
||||
}
|
||||
|
||||
const receiptColumns = `
|
||||
room_id, user_id, receipt_type, thread_id, event_id, ts_ms, stream_pos`
|
||||
|
||||
func scanReceipts(rows *sql.Rows) ([]storage.Receipt, error) {
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []storage.Receipt
|
||||
for rows.Next() {
|
||||
var r storage.Receipt
|
||||
if err := rows.Scan(&r.RoomID, &r.UserID, &r.ReceiptType, &r.ThreadID,
|
||||
&r.EventID, &r.TimestampMS, &r.StreamPos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Receipts implements storage.SyncStore.
|
||||
func (s *Sync) Receipts(ctx context.Context, roomIDs []string, from, to int64) ([]storage.Receipt, error) {
|
||||
if len(roomIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
query := `SELECT ` + receiptColumns + ` FROM sync_receipts
|
||||
WHERE room_id IN (` + placeholders(len(roomIDs)) + `) AND stream_pos > ?`
|
||||
args := make([]any, 0, len(roomIDs)+2)
|
||||
for _, id := range roomIDs {
|
||||
args = append(args, id)
|
||||
}
|
||||
args = append(args, from)
|
||||
if to > 0 {
|
||||
query += ` AND stream_pos <= ?`
|
||||
args = append(args, to)
|
||||
}
|
||||
query += ` ORDER BY stream_pos`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, s.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read receipts: %w", err)
|
||||
}
|
||||
receipts, err := scanReceipts(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read receipts: %w", err)
|
||||
}
|
||||
return receipts, nil
|
||||
}
|
||||
|
||||
// ReceiptsForUser implements storage.SyncStore.
|
||||
func (s *Sync) ReceiptsForUser(ctx context.Context, userID string, roomIDs []string) ([]storage.Receipt, error) {
|
||||
if len(roomIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
query := `SELECT ` + receiptColumns + ` FROM sync_receipts
|
||||
WHERE user_id = ? AND room_id IN (` + placeholders(len(roomIDs)) + `)
|
||||
ORDER BY stream_pos`
|
||||
args := make([]any, 0, len(roomIDs)+1)
|
||||
args = append(args, userID)
|
||||
for _, id := range roomIDs {
|
||||
args = append(args, id)
|
||||
}
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, s.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the receipts of %q: %w", userID, err)
|
||||
}
|
||||
receipts, err := scanReceipts(rows)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the receipts of %q: %w", userID, err)
|
||||
}
|
||||
return receipts, nil
|
||||
}
|
||||
|
||||
const insertToDeviceSQL = `
|
||||
INSERT INTO sync_to_device
|
||||
(stream_pos, localpart, device_id, sender, event_type, content, sent_at_ms)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
|
||||
// SendToDevice implements storage.SyncStore.
|
||||
//
|
||||
// The whole batch shares one transaction but takes a position each: a
|
||||
// message to two of a user's devices is two independent deliveries, and one
|
||||
// device acknowledging its copy must not drop the other's.
|
||||
func (s *Sync) SendToDevice(ctx context.Context, msgs []storage.NewToDeviceMessage) (int64, error) {
|
||||
var top int64
|
||||
err := s.tx(ctx, func(tx *sql.Tx) error {
|
||||
if len(msgs) == 0 {
|
||||
var err error
|
||||
top, err = currentSequence(ctx, tx, s.q, syncSequences, seqToDevice)
|
||||
return err
|
||||
}
|
||||
for _, m := range msgs {
|
||||
pos, err := nextSequence(ctx, tx, s.q, syncSequences, seqToDevice)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, s.q(insertToDeviceSQL),
|
||||
pos, m.Localpart, m.DeviceID, m.Sender, m.Type, string(m.Content), m.SentAtMS); err != nil {
|
||||
return fmt.Errorf("queue a to-device message for %s/%s: %w", m.Localpart, m.DeviceID, err)
|
||||
}
|
||||
top = pos
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("send to-device messages: %w", err)
|
||||
}
|
||||
return top, nil
|
||||
}
|
||||
|
||||
const selectToDeviceSQL = `
|
||||
SELECT stream_pos, localpart, device_id, sender, event_type, content, sent_at_ms
|
||||
FROM sync_to_device
|
||||
WHERE localpart = ? AND device_id = ? AND stream_pos > ?`
|
||||
|
||||
// ToDeviceMessages implements storage.SyncStore.
|
||||
func (s *Sync) ToDeviceMessages(ctx context.Context, localpart, deviceID string, from, to int64, limit int) ([]storage.ToDeviceMessage, error) {
|
||||
if limit <= 0 || limit > maxToDeviceBatch {
|
||||
limit = maxToDeviceBatch
|
||||
}
|
||||
|
||||
query := selectToDeviceSQL
|
||||
args := []any{localpart, deviceID, from}
|
||||
if to > 0 {
|
||||
query += ` AND stream_pos <= ?`
|
||||
args = append(args, to)
|
||||
}
|
||||
query += ` ORDER BY stream_pos LIMIT ?`
|
||||
args = append(args, limit)
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, s.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read to-device messages for %s/%s: %w", localpart, deviceID, err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []storage.ToDeviceMessage
|
||||
for rows.Next() {
|
||||
var (
|
||||
m storage.ToDeviceMessage
|
||||
content string
|
||||
)
|
||||
if err := rows.Scan(&m.StreamPos, &m.Localpart, &m.DeviceID,
|
||||
&m.Sender, &m.Type, &content, &m.SentAtMS); err != nil {
|
||||
return nil, fmt.Errorf("read to-device messages for %s/%s: %w", localpart, deviceID, err)
|
||||
}
|
||||
m.Content = []byte(content)
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const deleteToDeviceSQL = `
|
||||
DELETE FROM sync_to_device
|
||||
WHERE localpart = ? AND device_id = ? AND stream_pos <= ?`
|
||||
|
||||
// DeleteToDeviceMessages implements storage.SyncStore.
|
||||
func (s *Sync) DeleteToDeviceMessages(ctx context.Context, localpart, deviceID string, pos int64) error {
|
||||
if pos <= 0 {
|
||||
return nil
|
||||
}
|
||||
if _, err := s.db.ExecContext(ctx, s.q(deleteToDeviceSQL), localpart, deviceID, pos); err != nil {
|
||||
return fmt.Errorf("delete to-device messages for %s/%s: %w", localpart, deviceID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const (
|
||||
upsertPresenceSQL = `
|
||||
INSERT INTO sync_presence (user_id, presence, status_msg, last_active_ms, stream_pos)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (user_id) DO UPDATE SET
|
||||
presence = excluded.presence,
|
||||
status_msg = excluded.status_msg,
|
||||
last_active_ms = excluded.last_active_ms,
|
||||
stream_pos = excluded.stream_pos`
|
||||
|
||||
touchPresenceSQL = `
|
||||
UPDATE sync_presence SET last_active_ms = ? WHERE user_id = ?`
|
||||
)
|
||||
|
||||
// SetPresence implements storage.SyncStore.
|
||||
//
|
||||
// A write that changes nothing a peer would notice refreshes the
|
||||
// last-active timestamp in place and leaves the stream where it was. Every
|
||||
// /sync is such a write — a client says it is still online by syncing — and
|
||||
// moving the stream each time would wake every peer's long poll, which
|
||||
// would sync, which would move it again.
|
||||
func (s *Sync) SetPresence(ctx context.Context, p storage.PresenceState) (int64, bool, error) {
|
||||
var (
|
||||
pos int64
|
||||
moved bool
|
||||
)
|
||||
err := s.tx(ctx, func(tx *sql.Tx) error {
|
||||
var existing storage.PresenceState
|
||||
err := tx.QueryRowContext(ctx, s.q(selectPresenceSQL), p.UserID).Scan(
|
||||
&existing.UserID, &existing.Presence, &existing.StatusMsg,
|
||||
&existing.LastActiveMS, &existing.StreamPos)
|
||||
switch {
|
||||
case err == nil:
|
||||
if existing.Presence == p.Presence && existing.StatusMsg == p.StatusMsg {
|
||||
pos = existing.StreamPos
|
||||
if _, err := tx.ExecContext(ctx, s.q(touchPresenceSQL),
|
||||
p.LastActiveMS, p.UserID); err != nil {
|
||||
return fmt.Errorf("refresh the last-active timestamp: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return fmt.Errorf("read the current presence: %w", err)
|
||||
}
|
||||
|
||||
if pos, err = nextSequence(ctx, tx, s.q, syncSequences, seqPresence); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, s.q(upsertPresenceSQL),
|
||||
p.UserID, p.Presence, p.StatusMsg, p.LastActiveMS, pos); err != nil {
|
||||
return fmt.Errorf("write presence: %w", err)
|
||||
}
|
||||
moved = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("set the presence of %q: %w", p.UserID, err)
|
||||
}
|
||||
return pos, moved, nil
|
||||
}
|
||||
|
||||
const presenceColumns = `user_id, presence, status_msg, last_active_ms, stream_pos`
|
||||
|
||||
const selectPresenceSQL = `
|
||||
SELECT ` + presenceColumns + ` FROM sync_presence WHERE user_id = ?`
|
||||
|
||||
// Presence implements storage.SyncStore.
|
||||
func (s *Sync) Presence(ctx context.Context, userID string) (storage.PresenceState, error) {
|
||||
var p storage.PresenceState
|
||||
err := s.db.QueryRowContext(ctx, s.q(selectPresenceSQL), userID).
|
||||
Scan(&p.UserID, &p.Presence, &p.StatusMsg, &p.LastActiveMS, &p.StreamPos)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return storage.PresenceState{}, fmt.Errorf("presence of %q: %w", userID, storage.ErrNoSuchUser)
|
||||
case err != nil:
|
||||
return storage.PresenceState{}, fmt.Errorf("read the presence of %q: %w", userID, err)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// PresenceForUsers implements storage.SyncStore.
|
||||
func (s *Sync) PresenceForUsers(ctx context.Context, userIDs []string, from, to int64) ([]storage.PresenceState, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
query := `SELECT ` + presenceColumns + ` FROM sync_presence
|
||||
WHERE user_id IN (` + placeholders(len(userIDs)) + `) AND stream_pos > ?`
|
||||
args := make([]any, 0, len(userIDs)+2)
|
||||
for _, id := range userIDs {
|
||||
args = append(args, id)
|
||||
}
|
||||
args = append(args, from)
|
||||
if to > 0 {
|
||||
query += ` AND stream_pos <= ?`
|
||||
args = append(args, to)
|
||||
}
|
||||
query += ` ORDER BY stream_pos`
|
||||
|
||||
rows, err := s.db.QueryContext(ctx, s.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read presence: %w", err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []storage.PresenceState
|
||||
for rows.Next() {
|
||||
var p storage.PresenceState
|
||||
if err := rows.Scan(&p.UserID, &p.Presence, &p.StatusMsg, &p.LastActiveMS, &p.StreamPos); err != nil {
|
||||
return nil, fmt.Errorf("read presence: %w", err)
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const selectAccountDataChangesSQL = `
|
||||
SELECT room_id, data_type, stream_pos FROM user_account_data
|
||||
WHERE localpart = ? AND stream_pos > ?`
|
||||
|
||||
// AccountDataChanges implements storage.SyncStore.
|
||||
func (s *Sync) AccountDataChanges(ctx context.Context, localpart string, from, to int64) ([]storage.AccountDataEntry, error) {
|
||||
query := selectAccountDataChangesSQL
|
||||
args := []any{localpart, from}
|
||||
if to > 0 {
|
||||
query += ` AND stream_pos <= ?`
|
||||
args = append(args, to)
|
||||
}
|
||||
query += ` ORDER BY stream_pos`
|
||||
|
||||
return s.accountData(ctx, localpart, query, args)
|
||||
}
|
||||
|
||||
const selectAllAccountDataSQL = `
|
||||
SELECT room_id, data_type, stream_pos FROM user_account_data
|
||||
WHERE localpart = ?`
|
||||
|
||||
// AccountDataAt implements storage.SyncStore.
|
||||
func (s *Sync) AccountDataAt(ctx context.Context, localpart string, to int64) ([]storage.AccountDataEntry, error) {
|
||||
query := selectAllAccountDataSQL
|
||||
args := []any{localpart}
|
||||
if to > 0 {
|
||||
query += ` AND stream_pos <= ?`
|
||||
args = append(args, to)
|
||||
}
|
||||
query += ` ORDER BY room_id, data_type`
|
||||
|
||||
return s.accountData(ctx, localpart, query, args)
|
||||
}
|
||||
|
||||
func (s *Sync) accountData(ctx context.Context, localpart, query string, args []any) ([]storage.AccountDataEntry, error) {
|
||||
rows, err := s.db.QueryContext(ctx, s.q(query), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the account data of %q: %w", localpart, err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []storage.AccountDataEntry
|
||||
for rows.Next() {
|
||||
var e storage.AccountDataEntry
|
||||
if err := rows.Scan(&e.RoomID, &e.DataType, &e.StreamPos); err != nil {
|
||||
return nil, fmt.Errorf("read the account data of %q: %w", localpart, err)
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
const insertFilterSQL = `
|
||||
INSERT INTO sync_filters (localpart, filter_id, filter_json, created_at_ms)
|
||||
VALUES (?, ?, ?, ?)`
|
||||
|
||||
// SaveFilter implements storage.SyncStore.
|
||||
//
|
||||
// The ID is random rather than a counter. The spec says only that it is
|
||||
// opaque, and a counter would be a per-user one: two users would both have
|
||||
// a filter "1", so a filter ID leaking into a URL or a log would say which
|
||||
// user it belonged to only by accident of context.
|
||||
func (s *Sync) SaveFilter(ctx context.Context, localpart string, filter []byte, createdAtMS int64) (string, error) {
|
||||
for attempt := range 3 {
|
||||
filterID, err := newFilterID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, s.q(insertFilterSQL),
|
||||
localpart, filterID, string(filter), createdAtMS)
|
||||
switch {
|
||||
case err == nil:
|
||||
return filterID, nil
|
||||
case s.isUnique(err) && attempt < 2:
|
||||
// 96 bits of randomness collided, or the caller's own ID did.
|
||||
// Either way the answer is another ID.
|
||||
continue
|
||||
default:
|
||||
return "", fmt.Errorf("save a filter for %q: %w", localpart, err)
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("save a filter for %q: could not find an unused filter ID", localpart)
|
||||
}
|
||||
|
||||
// newFilterID mints a filter ID: 12 random bytes, URL-safe base64.
|
||||
func newFilterID() (string, error) {
|
||||
var raw [12]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return "", fmt.Errorf("generate a filter ID: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw[:]), nil
|
||||
}
|
||||
|
||||
const selectFilterSQL = `
|
||||
SELECT filter_json FROM sync_filters WHERE localpart = ? AND filter_id = ?`
|
||||
|
||||
// Filter implements storage.SyncStore.
|
||||
func (s *Sync) Filter(ctx context.Context, localpart, filterID string) ([]byte, error) {
|
||||
var body string
|
||||
err := s.db.QueryRowContext(ctx, s.q(selectFilterSQL), localpart, filterID).Scan(&body)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, fmt.Errorf("filter %q: %w", filterID, storage.ErrNoSuchFilter)
|
||||
case err != nil:
|
||||
return nil, fmt.Errorf("read filter %q: %w", filterID, err)
|
||||
}
|
||||
return []byte(body), nil
|
||||
}
|
||||
|
||||
// Compile-time proof that the shared implementation satisfies the interface.
|
||||
var _ storage.SyncStore = (*Sync)(nil)
|
||||
Reference in new issue
Block a user