2017-06-28 16:10:17 +01:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package consumers
|
|
|
|
|
|
|
|
import (
|
2017-09-13 13:37:50 +01:00
|
|
|
"context"
|
2023-07-14 07:04:25 +01:00
|
|
|
"encoding/base64"
|
2017-06-28 16:10:17 +01:00
|
|
|
"encoding/json"
|
2023-07-14 07:04:25 +01:00
|
|
|
"errors"
|
2017-06-28 16:10:17 +01:00
|
|
|
"fmt"
|
2022-11-11 09:35:17 +00:00
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
syncAPITypes "github.com/matrix-org/dendrite/syncapi/types"
|
2023-04-19 15:50:33 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2022-02-09 12:11:43 +00:00
|
|
|
|
2022-02-11 17:15:44 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
"github.com/nats-io/nats.go"
|
2023-01-19 20:02:32 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2022-02-11 17:15:44 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2021-11-24 10:45:23 +00:00
|
|
|
"github.com/matrix-org/dendrite/federationapi/queue"
|
|
|
|
"github.com/matrix-org/dendrite/federationapi/storage"
|
|
|
|
"github.com/matrix-org/dendrite/federationapi/types"
|
2017-06-28 16:10:17 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2020-12-02 17:41:00 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2022-01-05 17:44:49 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/jetstream"
|
2021-01-26 12:56:20 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/process"
|
2017-06-28 16:10:17 +01:00
|
|
|
)
|
|
|
|
|
2017-10-11 18:13:43 +01:00
|
|
|
// OutputRoomEventConsumer consumes events that originated in the room server.
|
|
|
|
type OutputRoomEventConsumer struct {
|
2022-11-11 09:35:17 +00:00
|
|
|
ctx context.Context
|
|
|
|
cfg *config.FederationAPI
|
|
|
|
rsAPI api.FederationRoomserverAPI
|
|
|
|
jetstream nats.JetStreamContext
|
|
|
|
natsClient *nats.Conn
|
|
|
|
durable string
|
|
|
|
db storage.Database
|
|
|
|
queues *queue.OutgoingQueues
|
|
|
|
topic string
|
|
|
|
topicPresence string
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
|
2017-10-11 18:13:43 +01:00
|
|
|
// NewOutputRoomEventConsumer creates a new OutputRoomEventConsumer. Call Start() to begin consuming from room servers.
|
|
|
|
func NewOutputRoomEventConsumer(
|
2021-01-26 12:56:20 +00:00
|
|
|
process *process.ProcessContext,
|
2021-11-24 10:45:23 +00:00
|
|
|
cfg *config.FederationAPI,
|
2022-01-05 17:44:49 +00:00
|
|
|
js nats.JetStreamContext,
|
2022-11-11 09:35:17 +00:00
|
|
|
natsClient *nats.Conn,
|
2017-08-16 13:36:41 +01:00
|
|
|
queues *queue.OutgoingQueues,
|
2020-01-03 14:07:05 +00:00
|
|
|
store storage.Database,
|
2022-05-17 13:23:35 +01:00
|
|
|
rsAPI api.FederationRoomserverAPI,
|
2017-10-11 18:13:43 +01:00
|
|
|
) *OutputRoomEventConsumer {
|
2022-01-05 17:44:49 +00:00
|
|
|
return &OutputRoomEventConsumer{
|
2022-11-11 09:35:17 +00:00
|
|
|
ctx: process.Context(),
|
|
|
|
cfg: cfg,
|
|
|
|
jetstream: js,
|
|
|
|
natsClient: natsClient,
|
|
|
|
db: store,
|
|
|
|
queues: queues,
|
|
|
|
rsAPI: rsAPI,
|
|
|
|
durable: cfg.Matrix.JetStream.Durable("FederationAPIRoomServerConsumer"),
|
|
|
|
topic: cfg.Matrix.JetStream.Prefixed(jetstream.OutputRoomEvent),
|
|
|
|
topicPresence: cfg.Matrix.JetStream.Prefixed(jetstream.RequestPresence),
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start consuming from room servers
|
2017-10-11 18:13:43 +01:00
|
|
|
func (s *OutputRoomEventConsumer) Start() error {
|
2022-02-02 13:32:48 +00:00
|
|
|
return jetstream.JetStreamConsumer(
|
2022-08-31 12:21:56 +01:00
|
|
|
s.ctx, s.jetstream, s.topic, s.durable, 1,
|
|
|
|
s.onMessage, nats.DeliverAll(), nats.ManualAck(),
|
2022-01-27 14:29:14 +00:00
|
|
|
)
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// onMessage is called when the federation server receives a new event from the room server output log.
|
|
|
|
// It is unsafe to call this with messages for the same room in multiple gorountines
|
|
|
|
// because updates it will likely fail with a types.EventIDMismatchError when it
|
|
|
|
// realises that it cannot update the room state using the deltas.
|
2022-08-31 12:21:56 +01:00
|
|
|
func (s *OutputRoomEventConsumer) onMessage(ctx context.Context, msgs []*nats.Msg) bool {
|
|
|
|
msg := msgs[0] // Guaranteed to exist if onMessage is called
|
2022-10-05 11:12:42 +01:00
|
|
|
receivedType := api.OutputType(msg.Header.Get(jetstream.RoomEventType))
|
|
|
|
|
2023-01-19 20:02:32 +00:00
|
|
|
// Only handle events we care about, avoids unneeded unmarshalling
|
|
|
|
switch receivedType {
|
|
|
|
case api.OutputTypeNewRoomEvent, api.OutputTypeNewInboundPeek, api.OutputTypePurgeRoom:
|
|
|
|
default:
|
2022-10-05 11:12:42 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-02-02 13:32:48 +00:00
|
|
|
// Parse out the event JSON
|
|
|
|
var output api.OutputEvent
|
|
|
|
if err := json.Unmarshal(msg.Data, &output); err != nil {
|
|
|
|
// If the message was invalid, log it and move on to the next message in the stream
|
|
|
|
log.WithError(err).Errorf("roomserver output log: message parse failure")
|
|
|
|
return true
|
|
|
|
}
|
2020-04-03 14:29:06 +01:00
|
|
|
|
2022-02-02 13:32:48 +00:00
|
|
|
switch output.Type {
|
|
|
|
case api.OutputTypeNewRoomEvent:
|
|
|
|
ev := output.NewRoomEvent.Event
|
2022-05-17 13:23:35 +01:00
|
|
|
if err := s.processMessage(*output.NewRoomEvent, output.NewRoomEvent.RewritesState); err != nil {
|
2022-02-11 17:15:44 +00:00
|
|
|
// panic rather than continue with an inconsistent database
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event_id": ev.EventID(),
|
|
|
|
"event": string(ev.JSON()),
|
|
|
|
"add": output.NewRoomEvent.AddsStateEventIDs,
|
|
|
|
"del": output.NewRoomEvent.RemovesStateEventIDs,
|
|
|
|
log.ErrorKey: err,
|
|
|
|
}).Panicf("roomserver output log: write room event failure")
|
2022-02-02 13:32:48 +00:00
|
|
|
}
|
2022-01-05 17:44:49 +00:00
|
|
|
|
2022-02-02 13:32:48 +00:00
|
|
|
case api.OutputTypeNewInboundPeek:
|
|
|
|
if err := s.processInboundPeek(*output.NewInboundPeek); err != nil {
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"event": output.NewInboundPeek,
|
|
|
|
log.ErrorKey: err,
|
|
|
|
}).Panicf("roomserver output log: remote peek event failure")
|
|
|
|
return false
|
2021-01-22 14:55:08 +00:00
|
|
|
}
|
2017-06-28 16:10:17 +01:00
|
|
|
|
2023-01-19 20:02:32 +00:00
|
|
|
case api.OutputTypePurgeRoom:
|
|
|
|
log.WithField("room_id", output.PurgeRoom.RoomID).Warn("Purging room from federation API")
|
|
|
|
if err := s.db.PurgeRoom(ctx, output.PurgeRoom.RoomID); err != nil {
|
|
|
|
logrus.WithField("room_id", output.PurgeRoom.RoomID).WithError(err).Error("Failed to purge room from federation API")
|
|
|
|
} else {
|
|
|
|
logrus.WithField("room_id", output.PurgeRoom.RoomID).Warn("Room purged from federation API")
|
|
|
|
}
|
|
|
|
|
2022-02-02 13:32:48 +00:00
|
|
|
default:
|
|
|
|
log.WithField("type", output.Type).Debug(
|
|
|
|
"roomserver output log: ignoring unknown output type",
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
|
2021-01-22 14:55:08 +00:00
|
|
|
// processInboundPeek starts tracking a new federated inbound peek (replacing the existing one if any)
|
2021-11-24 10:45:23 +00:00
|
|
|
// causing the federationapi to start sending messages to the peeking server
|
2021-01-22 14:55:08 +00:00
|
|
|
func (s *OutputRoomEventConsumer) processInboundPeek(orp api.OutputNewInboundPeek) error {
|
|
|
|
|
|
|
|
// FIXME: there's a race here - we should start /sending new peeked events
|
|
|
|
// atomically after the orp.LatestEventID to ensure there are no gaps between
|
|
|
|
// the peek beginning and the send stream beginning.
|
|
|
|
//
|
|
|
|
// We probably need to track orp.LatestEventID on the inbound peek, but it's
|
|
|
|
// unclear how we then use that to prevent the race when we start the send
|
|
|
|
// stream.
|
|
|
|
//
|
|
|
|
// This is making the tests flakey.
|
|
|
|
|
2022-01-05 17:44:49 +00:00
|
|
|
return s.db.AddInboundPeek(s.ctx, orp.ServerName, orp.RoomID, orp.PeekID, orp.RenewalInterval)
|
2021-01-22 14:55:08 +00:00
|
|
|
}
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
// processMessage updates the list of currently joined hosts in the room
|
|
|
|
// and then sends the event to the hosts that were joined before the event.
|
2022-05-17 13:23:35 +01:00
|
|
|
func (s *OutputRoomEventConsumer) processMessage(ore api.OutputNewRoomEvent, rewritesState bool) error {
|
2022-11-11 09:35:17 +00:00
|
|
|
|
2022-05-09 16:19:35 +01:00
|
|
|
addsStateEvents, missingEventIDs := ore.NeededStateEventIDs()
|
|
|
|
|
|
|
|
// Ask the roomserver and add in the rest of the results into the set.
|
|
|
|
// Finally, work out if there are any more events missing.
|
|
|
|
if len(missingEventIDs) > 0 {
|
2022-03-07 17:17:16 +00:00
|
|
|
eventsReq := &api.QueryEventsByIDRequest{
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: ore.Event.RoomID().String(),
|
2022-05-09 16:19:35 +01:00
|
|
|
EventIDs: missingEventIDs,
|
2022-03-07 17:17:16 +00:00
|
|
|
}
|
2022-05-09 16:19:35 +01:00
|
|
|
eventsRes := &api.QueryEventsByIDResponse{}
|
2022-03-07 17:17:16 +00:00
|
|
|
if err := s.rsAPI.QueryEventsByID(s.ctx, eventsReq, eventsRes); err != nil {
|
|
|
|
return fmt.Errorf("s.rsAPI.QueryEventsByID: %w", err)
|
|
|
|
}
|
2022-05-09 16:19:35 +01:00
|
|
|
if len(eventsRes.Events) != len(missingEventIDs) {
|
|
|
|
return fmt.Errorf("missing state events")
|
2022-03-07 17:17:16 +00:00
|
|
|
}
|
2022-05-09 16:19:35 +01:00
|
|
|
addsStateEvents = append(addsStateEvents, eventsRes.Events...)
|
2022-03-07 17:17:16 +00:00
|
|
|
}
|
|
|
|
|
2023-05-02 15:03:16 +01:00
|
|
|
evs := make([]gomatrixserverlib.PDU, len(addsStateEvents))
|
2023-04-27 12:54:20 +01:00
|
|
|
for i := range evs {
|
2023-05-02 15:03:16 +01:00
|
|
|
evs[i] = addsStateEvents[i].PDU
|
2023-04-27 12:54:20 +01:00
|
|
|
}
|
|
|
|
|
2023-06-28 19:29:49 +01:00
|
|
|
addsJoinedHosts, err := JoinedHostsFromEvents(s.ctx, evs, s.rsAPI)
|
2017-06-28 16:10:17 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Update our copy of the current state.
|
|
|
|
// We keep a copy of the current state because the state at each event is
|
|
|
|
// expressed as a delta against the current state.
|
2017-10-06 14:13:53 +01:00
|
|
|
// TODO(#290): handle EventIDMismatchError and recover the current state by
|
|
|
|
// talking to the roomserver
|
2017-06-28 16:10:17 +01:00
|
|
|
oldJoinedHosts, err := s.db.UpdateRoom(
|
2022-01-05 17:44:49 +00:00
|
|
|
s.ctx,
|
2023-09-15 15:39:06 +01:00
|
|
|
ore.Event.RoomID().String(),
|
2017-09-18 14:15:17 +01:00
|
|
|
addsJoinedHosts,
|
|
|
|
ore.RemovesStateEventIDs,
|
2022-05-17 13:23:35 +01:00
|
|
|
rewritesState, // if we're re-writing state, nuke all joined hosts before adding
|
2017-06-28 16:10:17 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-11-11 09:35:17 +00:00
|
|
|
// If we added new hosts, inform them about our known presence events for this room
|
2023-04-19 15:50:33 +01:00
|
|
|
if s.cfg.Matrix.Presence.EnableOutbound && len(addsJoinedHosts) > 0 && ore.Event.Type() == spec.MRoomMember && ore.Event.StateKey() != nil {
|
2022-11-11 09:35:17 +00:00
|
|
|
membership, _ := ore.Event.Membership()
|
2023-04-19 15:50:33 +01:00
|
|
|
if membership == spec.Join {
|
2023-09-15 15:39:06 +01:00
|
|
|
s.sendPresence(ore.Event.RoomID().String(), addsJoinedHosts)
|
2022-11-11 09:35:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-16 13:20:24 +01:00
|
|
|
if oldJoinedHosts == nil {
|
|
|
|
// This means that there is nothing to update as this is a duplicate
|
|
|
|
// message.
|
|
|
|
// This can happen if dendrite crashed between reading the message and
|
|
|
|
// persisting the stream position.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
if ore.SendAsServer == api.DoNotSendToOtherServers {
|
|
|
|
// Ignore event that we don't need to send anywhere.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Work out which hosts were joined at the event itself.
|
2017-07-12 10:46:29 +01:00
|
|
|
joinedHostsAtEvent, err := s.joinedHostsAtEvent(ore, oldJoinedHosts)
|
2017-06-28 16:10:17 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-01-22 14:55:08 +00:00
|
|
|
// TODO: do housekeeping to evict unrenewed peeking hosts
|
|
|
|
|
|
|
|
// TODO: implement query to let the fedapi check whether a given peek is live or not
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
// Send the event.
|
2017-10-16 13:20:24 +01:00
|
|
|
return s.queues.SendEvent(
|
2023-04-19 15:50:33 +01:00
|
|
|
ore.Event, spec.ServerName(ore.SendAsServer), joinedHostsAtEvent,
|
2017-10-16 13:20:24 +01:00
|
|
|
)
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
|
2022-11-11 09:35:17 +00:00
|
|
|
func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []types.JoinedHost) {
|
2023-04-19 15:50:33 +01:00
|
|
|
joined := make([]spec.ServerName, 0, len(addedJoined))
|
2022-11-11 09:35:17 +00:00
|
|
|
for _, added := range addedJoined {
|
|
|
|
joined = append(joined, added.ServerName)
|
|
|
|
}
|
|
|
|
|
|
|
|
// get our locally joined users
|
|
|
|
var queryRes api.QueryMembershipsForRoomResponse
|
|
|
|
err := s.rsAPI.QueryMembershipsForRoom(s.ctx, &api.QueryMembershipsForRoomRequest{
|
|
|
|
JoinedOnly: true,
|
|
|
|
LocalOnly: true,
|
|
|
|
RoomID: roomID,
|
|
|
|
}, &queryRes)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("failed to calculate joined rooms for user")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// send every presence we know about to the remote server
|
|
|
|
content := types.Presence{}
|
|
|
|
for _, ev := range queryRes.JoinEvents {
|
|
|
|
msg := nats.NewMsg(s.topicPresence)
|
|
|
|
msg.Header.Set(jetstream.UserID, ev.Sender)
|
|
|
|
|
|
|
|
var presence *nats.Msg
|
|
|
|
presence, err = s.natsClient.RequestMsg(msg, time.Second*10)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Errorf("unable to get presence")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
statusMsg := presence.Header.Get("status_msg")
|
|
|
|
e := presence.Header.Get("error")
|
|
|
|
if e != "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var lastActive int
|
|
|
|
lastActive, err = strconv.Atoi(presence.Header.Get("last_active_ts"))
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
p := syncAPITypes.PresenceInternal{LastActiveTS: spec.Timestamp(lastActive)}
|
2022-11-11 09:35:17 +00:00
|
|
|
|
|
|
|
content.Push = append(content.Push, types.PresenceContent{
|
|
|
|
CurrentlyActive: p.CurrentlyActive(),
|
|
|
|
LastActiveAgo: p.LastActiveAgo(),
|
|
|
|
Presence: presence.Header.Get("presence"),
|
|
|
|
StatusMsg: &statusMsg,
|
|
|
|
UserID: ev.Sender,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(content.Push) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
edu := &gomatrixserverlib.EDU{
|
2023-04-19 15:50:33 +01:00
|
|
|
Type: spec.MPresence,
|
2022-11-11 09:35:17 +00:00
|
|
|
Origin: string(s.cfg.Matrix.ServerName),
|
|
|
|
}
|
|
|
|
if edu.Content, err = json.Marshal(content); err != nil {
|
|
|
|
log.WithError(err).Error("failed to marshal EDU JSON")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err := s.queues.SendEDU(edu, s.cfg.Matrix.ServerName, joined); err != nil {
|
|
|
|
log.WithError(err).Error("failed to send EDU")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
// joinedHostsAtEvent works out a list of matrix servers that were joined to
|
2021-01-22 14:55:08 +00:00
|
|
|
// the room at the event (including peeking ones)
|
2017-06-28 16:10:17 +01:00
|
|
|
// It is important to use the state at the event for sending messages because:
|
2022-08-05 10:12:41 +01:00
|
|
|
//
|
|
|
|
// 1. We shouldn't send messages to servers that weren't in the room.
|
|
|
|
// 2. If a server is kicked from the rooms it should still be told about the
|
|
|
|
// kick event.
|
|
|
|
//
|
2017-06-28 16:10:17 +01:00
|
|
|
// Usually the list can be calculated locally, but sometimes it will need fetch
|
|
|
|
// events from the room server.
|
|
|
|
// Returns an error if there was a problem talking to the room server.
|
2017-10-11 18:13:43 +01:00
|
|
|
func (s *OutputRoomEventConsumer) joinedHostsAtEvent(
|
2017-07-12 10:46:29 +01:00
|
|
|
ore api.OutputNewRoomEvent, oldJoinedHosts []types.JoinedHost,
|
2023-04-19 15:50:33 +01:00
|
|
|
) ([]spec.ServerName, error) {
|
2017-06-28 16:10:17 +01:00
|
|
|
// Combine the delta into a single delta so that the adds and removes can
|
|
|
|
// cancel each other out. This should reduce the number of times we need
|
|
|
|
// to fetch a state event from the room server.
|
|
|
|
combinedAdds, combinedRemoves := combineDeltas(
|
|
|
|
ore.AddsStateEventIDs, ore.RemovesStateEventIDs,
|
|
|
|
ore.StateBeforeAddsEventIDs, ore.StateBeforeRemovesEventIDs,
|
|
|
|
)
|
2023-05-02 15:03:16 +01:00
|
|
|
combinedAddsEvents, err := s.lookupStateEvents(combinedAdds, ore.Event.PDU)
|
2017-06-28 16:10:17 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2023-06-28 19:29:49 +01:00
|
|
|
combinedAddsJoinedHosts, err := JoinedHostsFromEvents(s.ctx, combinedAddsEvents, s.rsAPI)
|
2017-06-28 16:10:17 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
removed := map[string]bool{}
|
|
|
|
for _, eventID := range combinedRemoves {
|
|
|
|
removed[eventID] = true
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
joined := map[spec.ServerName]bool{}
|
2017-06-28 16:10:17 +01:00
|
|
|
for _, joinedHost := range oldJoinedHosts {
|
|
|
|
if removed[joinedHost.MemberEventID] {
|
|
|
|
// This m.room.member event is part of the current state of the
|
|
|
|
// room, but not part of the state at the event we are processing
|
|
|
|
// Therefore we can't use it to tell whether the server was in
|
|
|
|
// the room at the event.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
joined[joinedHost.ServerName] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, joinedHost := range combinedAddsJoinedHosts {
|
|
|
|
// This m.room.member event was part of the state of the room at the
|
|
|
|
// event, but isn't part of the current state of the room now.
|
|
|
|
joined[joinedHost.ServerName] = true
|
|
|
|
}
|
|
|
|
|
2021-01-22 14:55:08 +00:00
|
|
|
// handle peeking hosts
|
2023-09-15 15:39:06 +01:00
|
|
|
inboundPeeks, err := s.db.GetInboundPeeks(s.ctx, ore.Event.PDU.RoomID().String())
|
2021-01-22 14:55:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, inboundPeek := range inboundPeeks {
|
|
|
|
joined[inboundPeek.ServerName] = true
|
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
var result []spec.ServerName
|
2017-06-28 16:10:17 +01:00
|
|
|
for serverName, include := range joined {
|
|
|
|
if include {
|
|
|
|
result = append(result, serverName)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2022-05-17 13:23:35 +01:00
|
|
|
// JoinedHostsFromEvents turns a list of state events into a list of joined hosts.
|
2017-06-28 16:10:17 +01:00
|
|
|
// This errors if one of the events was invalid.
|
|
|
|
// It should be impossible for an invalid event to get this far in the pipeline.
|
2023-06-28 19:29:49 +01:00
|
|
|
func JoinedHostsFromEvents(ctx context.Context, evs []gomatrixserverlib.PDU, rsAPI api.FederationRoomserverAPI) ([]types.JoinedHost, error) {
|
2017-06-28 16:10:17 +01:00
|
|
|
var joinedHosts []types.JoinedHost
|
|
|
|
for _, ev := range evs {
|
|
|
|
if ev.Type() != "m.room.member" || ev.StateKey() == nil {
|
|
|
|
continue
|
|
|
|
}
|
2017-07-07 14:11:32 +01:00
|
|
|
membership, err := ev.Membership()
|
|
|
|
if err != nil {
|
2017-06-28 16:10:17 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
2023-04-19 15:50:33 +01:00
|
|
|
if membership != spec.Join {
|
2017-06-28 16:10:17 +01:00
|
|
|
continue
|
|
|
|
}
|
2023-07-14 07:04:25 +01:00
|
|
|
var domain spec.ServerName
|
2023-09-15 15:39:06 +01:00
|
|
|
userID, err := rsAPI.QueryUserIDForSender(ctx, ev.RoomID(), spec.SenderID(*ev.StateKey()))
|
2023-06-28 19:29:49 +01:00
|
|
|
if err != nil {
|
2023-07-14 07:04:25 +01:00
|
|
|
if errors.As(err, new(base64.CorruptInputError)) {
|
|
|
|
// Fallback to using the "old" way of getting the user domain, avoids
|
|
|
|
// "illegal base64 data at input byte 0" errors
|
|
|
|
// FIXME: we should do this in QueryUserIDForSender instead
|
|
|
|
_, domain, err = gomatrixserverlib.SplitID('@', *ev.StateKey())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
domain = userID.Domain()
|
2023-06-28 19:29:49 +01:00
|
|
|
}
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
joinedHosts = append(joinedHosts, types.JoinedHost{
|
2023-07-14 07:04:25 +01:00
|
|
|
MemberEventID: ev.EventID(), ServerName: domain,
|
2017-06-28 16:10:17 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
return joinedHosts, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// combineDeltas combines two deltas into a single delta.
|
|
|
|
// Assumes that the order of operations is add(1), remove(1), add(2), remove(2).
|
|
|
|
// Removes duplicate entries and redundant operations from each delta.
|
|
|
|
func combineDeltas(adds1, removes1, adds2, removes2 []string) (adds, removes []string) {
|
|
|
|
addSet := map[string]bool{}
|
|
|
|
removeSet := map[string]bool{}
|
|
|
|
|
|
|
|
// combine processes each unique value in a list.
|
|
|
|
// If the value is in the removeFrom set then it is removed from that set.
|
|
|
|
// Otherwise it is added to the addTo set.
|
|
|
|
combine := func(values []string, removeFrom, addTo map[string]bool) {
|
|
|
|
processed := map[string]bool{}
|
|
|
|
for _, value := range values {
|
|
|
|
if processed[value] {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
processed[value] = true
|
|
|
|
if removeFrom[value] {
|
|
|
|
delete(removeFrom, value)
|
|
|
|
} else {
|
|
|
|
addTo[value] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
combine(adds1, nil, addSet)
|
|
|
|
combine(removes1, addSet, removeSet)
|
|
|
|
combine(adds2, removeSet, addSet)
|
|
|
|
combine(removes2, addSet, removeSet)
|
|
|
|
|
|
|
|
for value := range addSet {
|
|
|
|
adds = append(adds, value)
|
|
|
|
}
|
|
|
|
for value := range removeSet {
|
|
|
|
removes = append(removes, value)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// lookupStateEvents looks up the state events that are added by a new event.
|
2017-10-11 18:13:43 +01:00
|
|
|
func (s *OutputRoomEventConsumer) lookupStateEvents(
|
2023-05-02 15:03:16 +01:00
|
|
|
addsStateEventIDs []string, event gomatrixserverlib.PDU,
|
|
|
|
) ([]gomatrixserverlib.PDU, error) {
|
2017-06-28 16:10:17 +01:00
|
|
|
// Fast path if there aren't any new state events.
|
|
|
|
if len(addsStateEventIDs) == 0 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fast path if the only state event added is the event itself.
|
|
|
|
if len(addsStateEventIDs) == 1 && addsStateEventIDs[0] == event.EventID() {
|
2023-05-02 15:03:16 +01:00
|
|
|
return []gomatrixserverlib.PDU{event}, nil
|
2017-06-28 16:10:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
missing := addsStateEventIDs
|
2023-05-02 15:03:16 +01:00
|
|
|
var result []gomatrixserverlib.PDU
|
2017-06-28 16:10:17 +01:00
|
|
|
|
|
|
|
// Check if event itself is being added.
|
|
|
|
for _, eventID := range missing {
|
|
|
|
if eventID == event.EventID() {
|
|
|
|
result = append(result, event)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
missing = missingEventsFrom(result, addsStateEventIDs)
|
|
|
|
|
|
|
|
if len(missing) == 0 {
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// At this point the missing events are neither the event itself nor are
|
|
|
|
// they present in our local database. Our only option is to fetch them
|
|
|
|
// from the roomserver using the query API.
|
2023-09-15 15:39:06 +01:00
|
|
|
eventReq := api.QueryEventsByIDRequest{EventIDs: missing, RoomID: event.RoomID().String()}
|
2017-06-28 16:10:17 +01:00
|
|
|
var eventResp api.QueryEventsByIDResponse
|
2022-01-05 17:44:49 +00:00
|
|
|
if err := s.rsAPI.QueryEventsByID(s.ctx, &eventReq, &eventResp); err != nil {
|
2017-06-28 16:10:17 +01:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-03-16 17:29:52 +00:00
|
|
|
for _, headeredEvent := range eventResp.Events {
|
2023-05-02 15:03:16 +01:00
|
|
|
result = append(result, headeredEvent.PDU)
|
2020-03-16 17:29:52 +00:00
|
|
|
}
|
|
|
|
|
2017-06-28 16:10:17 +01:00
|
|
|
missing = missingEventsFrom(result, addsStateEventIDs)
|
|
|
|
|
|
|
|
if len(missing) != 0 {
|
|
|
|
return nil, fmt.Errorf(
|
|
|
|
"missing %d state events IDs at event %q", len(missing), event.EventID(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2023-05-02 15:03:16 +01:00
|
|
|
func missingEventsFrom(events []gomatrixserverlib.PDU, required []string) []string {
|
2017-06-28 16:10:17 +01:00
|
|
|
have := map[string]bool{}
|
|
|
|
for _, event := range events {
|
|
|
|
have[event.EventID()] = true
|
|
|
|
}
|
|
|
|
var missing []string
|
|
|
|
for _, eventID := range required {
|
|
|
|
if !have[eventID] {
|
|
|
|
missing = append(missing, eventID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return missing
|
|
|
|
}
|