2018-05-24 13:54:42 +01:00
|
|
|
// Copyright 2018 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 (
|
2022-09-01 09:20:40 +01:00
|
|
|
"bytes"
|
2018-05-24 13:54:42 +01:00
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2022-09-01 09:20:40 +01:00
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2022-09-19 17:39:06 +01:00
|
|
|
"strconv"
|
2022-09-01 09:20:40 +01:00
|
|
|
"time"
|
2018-05-24 13:54:42 +01:00
|
|
|
|
2022-08-29 13:18:33 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-19 15:50:33 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2022-08-29 13:18:33 +01:00
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
|
2018-05-24 13:54:42 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2023-04-27 12:54:20 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/types"
|
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"
|
2023-04-04 18:16:53 +01:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/synctypes"
|
2018-05-24 13:54:42 +01:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2023-04-04 18:16:53 +01:00
|
|
|
// ApplicationServiceTransaction is the transaction that is sent off to an
|
|
|
|
// application service.
|
|
|
|
type ApplicationServiceTransaction struct {
|
|
|
|
Events []synctypes.ClientEvent `json:"events"`
|
|
|
|
}
|
|
|
|
|
2018-05-24 13:54:42 +01:00
|
|
|
// OutputRoomEventConsumer consumes events that originated in the room server.
|
|
|
|
type OutputRoomEventConsumer struct {
|
2022-09-01 09:20:40 +01:00
|
|
|
ctx context.Context
|
|
|
|
cfg *config.AppServiceAPI
|
|
|
|
jetstream nats.JetStreamContext
|
|
|
|
topic string
|
|
|
|
rsAPI api.AppserviceRoomserverAPI
|
|
|
|
}
|
|
|
|
|
|
|
|
type appserviceState struct {
|
|
|
|
*config.ApplicationService
|
|
|
|
backoff int
|
2018-05-24 13:54:42 +01:00
|
|
|
}
|
|
|
|
|
2018-07-05 17:34:59 +01:00
|
|
|
// NewOutputRoomEventConsumer creates a new OutputRoomEventConsumer. Call
|
|
|
|
// Start() to begin consuming from room servers.
|
2018-05-24 13:54:42 +01:00
|
|
|
func NewOutputRoomEventConsumer(
|
2021-01-26 12:56:20 +00:00
|
|
|
process *process.ProcessContext,
|
2022-09-01 09:20:40 +01:00
|
|
|
cfg *config.AppServiceAPI,
|
2022-01-05 17:44:49 +00:00
|
|
|
js nats.JetStreamContext,
|
2022-05-05 13:17:38 +01:00
|
|
|
rsAPI api.AppserviceRoomserverAPI,
|
2018-05-24 13:54:42 +01:00
|
|
|
) *OutputRoomEventConsumer {
|
2022-01-05 17:44:49 +00:00
|
|
|
return &OutputRoomEventConsumer{
|
2022-09-01 09:20:40 +01:00
|
|
|
ctx: process.Context(),
|
|
|
|
cfg: cfg,
|
|
|
|
jetstream: js,
|
|
|
|
topic: cfg.Matrix.JetStream.Prefixed(jetstream.OutputRoomEvent),
|
|
|
|
rsAPI: rsAPI,
|
2018-05-24 13:54:42 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start consuming from room servers
|
|
|
|
func (s *OutputRoomEventConsumer) Start() error {
|
2022-09-01 09:20:40 +01:00
|
|
|
for _, as := range s.cfg.Derived.ApplicationServices {
|
|
|
|
appsvc := as
|
|
|
|
state := &appserviceState{
|
|
|
|
ApplicationService: &appsvc,
|
|
|
|
}
|
|
|
|
token := jetstream.Tokenise(as.ID)
|
|
|
|
if err := jetstream.JetStreamConsumer(
|
|
|
|
s.ctx, s.jetstream, s.topic,
|
|
|
|
s.cfg.Matrix.JetStream.Durable("Appservice_"+token),
|
|
|
|
50, // maximum number of events to send in a single transaction
|
|
|
|
func(ctx context.Context, msgs []*nats.Msg) bool {
|
|
|
|
return s.onMessage(ctx, state, msgs)
|
|
|
|
},
|
|
|
|
nats.DeliverNew(), nats.ManualAck(),
|
|
|
|
); err != nil {
|
|
|
|
return fmt.Errorf("failed to create %q consumer: %w", token, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
2018-05-24 13:54:42 +01:00
|
|
|
}
|
|
|
|
|
2018-07-05 17:34:59 +01:00
|
|
|
// onMessage is called when the appservice component receives a new event from
|
|
|
|
// the room server output log.
|
2022-09-01 09:20:40 +01:00
|
|
|
func (s *OutputRoomEventConsumer) onMessage(
|
|
|
|
ctx context.Context, state *appserviceState, msgs []*nats.Msg,
|
|
|
|
) bool {
|
|
|
|
log.WithField("appservice", state.ID).Tracef("Appservice worker received %d message(s) from roomserver", len(msgs))
|
2023-04-27 12:54:20 +01:00
|
|
|
events := make([]*types.HeaderedEvent, 0, len(msgs))
|
2022-09-01 09:20:40 +01:00
|
|
|
for _, msg := range msgs {
|
2022-10-05 11:12:42 +01:00
|
|
|
// Only handle events we care about
|
|
|
|
receivedType := api.OutputType(msg.Header.Get(jetstream.RoomEventType))
|
|
|
|
if receivedType != api.OutputTypeNewRoomEvent && receivedType != api.OutputTypeNewInviteEvent {
|
|
|
|
continue
|
|
|
|
}
|
2022-09-01 09:20:40 +01: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.WithField("appservice", state.ID).WithError(err).Errorf("Appservice failed to parse message, ignoring")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
switch output.Type {
|
|
|
|
case api.OutputTypeNewRoomEvent:
|
|
|
|
if output.NewRoomEvent == nil || !s.appserviceIsInterestedInEvent(ctx, output.NewRoomEvent.Event, state.ApplicationService) {
|
|
|
|
continue
|
2022-04-06 16:10:31 +01:00
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
events = append(events, output.NewRoomEvent.Event)
|
|
|
|
if len(output.NewRoomEvent.AddsStateEventIDs) > 0 {
|
|
|
|
newEventID := output.NewRoomEvent.Event.EventID()
|
|
|
|
eventsReq := &api.QueryEventsByIDRequest{
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: output.NewRoomEvent.Event.RoomID().String(),
|
2022-09-01 09:20:40 +01:00
|
|
|
EventIDs: make([]string, 0, len(output.NewRoomEvent.AddsStateEventIDs)),
|
2022-05-24 09:07:33 +01:00
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
eventsRes := &api.QueryEventsByIDResponse{}
|
|
|
|
for _, eventID := range output.NewRoomEvent.AddsStateEventIDs {
|
|
|
|
if eventID != newEventID {
|
|
|
|
eventsReq.EventIDs = append(eventsReq.EventIDs, eventID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(eventsReq.EventIDs) > 0 {
|
|
|
|
if err := s.rsAPI.QueryEventsByID(s.ctx, eventsReq, eventsRes); err != nil {
|
|
|
|
log.WithError(err).Errorf("s.rsAPI.QueryEventsByID failed")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
events = append(events, eventsRes.Events...)
|
2022-05-24 09:07:33 +01:00
|
|
|
}
|
2022-04-06 16:10:31 +01:00
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
|
|
|
|
default:
|
|
|
|
continue
|
2022-03-07 17:17:16 +00:00
|
|
|
}
|
|
|
|
}
|
2018-05-24 13:54:42 +01:00
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
// If there are no events selected for sending then we should
|
|
|
|
// ack the messages so that we don't get sent them again in the
|
|
|
|
// future.
|
|
|
|
if len(events) == 0 {
|
2022-01-05 17:44:49 +00:00
|
|
|
return true
|
2022-02-02 13:32:48 +00:00
|
|
|
}
|
|
|
|
|
2022-09-19 17:39:06 +01:00
|
|
|
txnID := ""
|
|
|
|
// Try to get the message metadata, if we're able to, use the timestamp as the txnID
|
|
|
|
metadata, err := msgs[0].Metadata()
|
|
|
|
if err == nil {
|
|
|
|
txnID = strconv.Itoa(int(metadata.Timestamp.UnixNano()))
|
|
|
|
}
|
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
// Send event to any relevant application services. If we hit
|
|
|
|
// an error here, return false, so that we negatively ack.
|
|
|
|
log.WithField("appservice", state.ID).Debugf("Appservice worker sending %d events(s) from roomserver", len(events))
|
2022-09-19 17:39:06 +01:00
|
|
|
return s.sendEvents(ctx, state, events, txnID) == nil
|
2018-05-24 13:54:42 +01:00
|
|
|
}
|
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
// sendEvents passes events to the appservice by using the transactions
|
|
|
|
// endpoint. It will block for the backoff period if necessary.
|
|
|
|
func (s *OutputRoomEventConsumer) sendEvents(
|
|
|
|
ctx context.Context, state *appserviceState,
|
2023-04-27 12:54:20 +01:00
|
|
|
events []*types.HeaderedEvent,
|
2022-09-19 17:39:06 +01:00
|
|
|
txnID string,
|
2018-07-05 17:34:59 +01:00
|
|
|
) error {
|
2022-09-01 09:20:40 +01:00
|
|
|
// Create the transaction body.
|
|
|
|
transaction, err := json.Marshal(
|
2023-04-04 18:16:53 +01:00
|
|
|
ApplicationServiceTransaction{
|
2023-06-14 15:23:46 +01:00
|
|
|
Events: synctypes.ToClientEvents(gomatrixserverlib.ToPDUs(events), synctypes.FormatAll, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
2023-06-06 21:55:18 +01:00
|
|
|
return s.rsAPI.QueryUserIDForSender(ctx, roomID, senderID)
|
|
|
|
}),
|
2022-09-01 09:20:40 +01:00
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-05-30 13:43:13 +01:00
|
|
|
}
|
|
|
|
|
2022-09-19 17:39:06 +01:00
|
|
|
// If txnID is not defined, generate one from the events.
|
|
|
|
if txnID == "" {
|
2023-05-02 15:03:16 +01:00
|
|
|
txnID = fmt.Sprintf("%d_%d", events[0].PDU.OriginServerTS(), len(transaction))
|
2022-09-19 17:39:06 +01:00
|
|
|
}
|
2018-05-30 13:43:13 +01:00
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
// Send the transaction to the appservice.
|
|
|
|
// https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid
|
2023-04-04 08:42:46 +01:00
|
|
|
address := fmt.Sprintf("%s/transactions/%s?access_token=%s", state.RequestUrl(), txnID, url.QueryEscape(state.HSToken))
|
2022-09-01 09:20:40 +01:00
|
|
|
req, err := http.NewRequestWithContext(ctx, "PUT", address, bytes.NewBuffer(transaction))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
2023-04-04 08:42:46 +01:00
|
|
|
resp, err := state.HTTPClient.Do(req)
|
2022-09-01 09:20:40 +01:00
|
|
|
if err != nil {
|
|
|
|
return state.backoffAndPause(err)
|
2021-03-03 16:27:44 +00:00
|
|
|
}
|
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
// If the response was fine then we can clear any backoffs in place and
|
|
|
|
// report that everything was OK. Otherwise, back off for a while.
|
|
|
|
switch resp.StatusCode {
|
|
|
|
case http.StatusOK:
|
|
|
|
state.backoff = 0
|
|
|
|
default:
|
2023-04-04 08:42:46 +01:00
|
|
|
return state.backoffAndPause(fmt.Errorf("received HTTP status code %d from appservice url %s", resp.StatusCode, address))
|
2021-03-03 16:27:44 +00:00
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// backoff pauses the calling goroutine for a 2^some backoff exponent seconds
|
|
|
|
func (s *appserviceState) backoffAndPause(err error) error {
|
|
|
|
if s.backoff < 6 {
|
|
|
|
s.backoff++
|
|
|
|
}
|
|
|
|
duration := time.Second * time.Duration(math.Pow(2, float64(s.backoff)))
|
|
|
|
log.WithField("appservice", s.ID).WithError(err).Errorf("Unable to send transaction to appservice, backing off for %s", duration.String())
|
|
|
|
time.Sleep(duration)
|
|
|
|
return err
|
2021-03-03 16:27:44 +00:00
|
|
|
}
|
|
|
|
|
2018-05-30 13:43:13 +01:00
|
|
|
// appserviceIsInterestedInEvent returns a boolean depending on whether a given
|
|
|
|
// event falls within one of a given application service's namespaces.
|
2021-03-03 16:27:44 +00:00
|
|
|
//
|
|
|
|
// TODO: This should be cached, see https://github.com/matrix-org/dendrite/issues/1682
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) appserviceIsInterestedInEvent(ctx context.Context, event *types.HeaderedEvent, appservice *config.ApplicationService) bool {
|
2023-06-06 21:55:18 +01:00
|
|
|
user := ""
|
2023-09-15 15:39:06 +01:00
|
|
|
userID, err := s.rsAPI.QueryUserIDForSender(ctx, event.RoomID(), event.SenderID())
|
2023-06-06 21:55:18 +01:00
|
|
|
if err == nil {
|
|
|
|
user = userID.String()
|
|
|
|
}
|
|
|
|
|
2022-09-01 09:20:40 +01:00
|
|
|
switch {
|
|
|
|
case appservice.URL == "":
|
2018-06-18 10:43:15 +01:00
|
|
|
return false
|
2023-06-06 21:55:18 +01:00
|
|
|
case appservice.IsInterestedInUserID(user):
|
2022-09-01 09:20:40 +01:00
|
|
|
return true
|
2023-09-15 15:39:06 +01:00
|
|
|
case appservice.IsInterestedInRoomID(event.RoomID().String()):
|
2018-07-16 13:30:04 +01:00
|
|
|
return true
|
2018-05-30 13:43:13 +01:00
|
|
|
}
|
|
|
|
|
2023-04-19 15:50:33 +01:00
|
|
|
if event.Type() == spec.MRoomMember && event.StateKey() != nil {
|
2020-03-20 21:40:24 +00:00
|
|
|
if appservice.IsInterestedInUserID(*event.StateKey()) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-30 13:43:13 +01:00
|
|
|
// Check all known room aliases of the room the event came from
|
2023-09-15 15:39:06 +01:00
|
|
|
queryReq := api.GetAliasesForRoomIDRequest{RoomID: event.RoomID().String()}
|
2018-05-30 13:43:13 +01:00
|
|
|
var queryRes api.GetAliasesForRoomIDResponse
|
2020-05-01 10:48:17 +01:00
|
|
|
if err := s.rsAPI.GetAliasesForRoomID(ctx, &queryReq, &queryRes); err == nil {
|
2018-05-30 13:43:13 +01:00
|
|
|
for _, alias := range queryRes.Aliases {
|
2018-07-16 13:30:04 +01:00
|
|
|
if appservice.IsInterestedInRoomAlias(alias) {
|
|
|
|
return true
|
2018-05-30 13:43:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.WithFields(log.Fields{
|
2022-09-01 09:20:40 +01:00
|
|
|
"appservice": appservice.ID,
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2018-05-30 13:43:13 +01:00
|
|
|
}).WithError(err).Errorf("Unable to get aliases for room")
|
|
|
|
}
|
|
|
|
|
2021-03-03 16:27:44 +00:00
|
|
|
// Check if any of the members in the room match the appservice
|
|
|
|
return s.appserviceJoinedAtEvent(ctx, event, appservice)
|
2018-05-30 13:43:13 +01:00
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
|
|
|
|
// appserviceJoinedAtEvent returns a boolean depending on whether a given
|
|
|
|
// appservice has membership at the time a given event was created.
|
2023-04-27 12:54:20 +01:00
|
|
|
func (s *OutputRoomEventConsumer) appserviceJoinedAtEvent(ctx context.Context, event *types.HeaderedEvent, appservice *config.ApplicationService) bool {
|
2022-09-01 09:20:40 +01:00
|
|
|
// TODO: This is only checking the current room state, not the state at
|
|
|
|
// the event in question. Pretty sure this is what Synapse does too, but
|
|
|
|
// until we have a lighter way of checking the state before the event that
|
|
|
|
// doesn't involve state res, then this is probably OK.
|
|
|
|
membershipReq := &api.QueryMembershipsForRoomRequest{
|
2023-09-15 15:39:06 +01:00
|
|
|
RoomID: event.RoomID().String(),
|
2022-09-01 09:20:40 +01:00
|
|
|
JoinedOnly: true,
|
|
|
|
}
|
|
|
|
membershipRes := &api.QueryMembershipsForRoomResponse{}
|
|
|
|
|
|
|
|
// XXX: This could potentially race if the state for the event is not known yet
|
|
|
|
// e.g. the event came over federation but we do not have the full state persisted.
|
|
|
|
if err := s.rsAPI.QueryMembershipsForRoom(ctx, membershipReq, membershipRes); err == nil {
|
|
|
|
for _, ev := range membershipRes.JoinEvents {
|
|
|
|
switch {
|
|
|
|
case ev.StateKey == nil:
|
|
|
|
continue
|
2023-04-19 15:50:33 +01:00
|
|
|
case ev.Type != spec.MRoomMember:
|
2022-09-01 09:20:40 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
var membership gomatrixserverlib.MemberContent
|
|
|
|
err = json.Unmarshal(ev.Content, &membership)
|
|
|
|
switch {
|
|
|
|
case err != nil:
|
|
|
|
continue
|
2023-04-19 15:50:33 +01:00
|
|
|
case membership.Membership == spec.Join:
|
2022-09-02 15:03:33 +01:00
|
|
|
if appservice.IsInterestedInUserID(*ev.StateKey) {
|
|
|
|
return true
|
|
|
|
}
|
2022-09-01 09:20:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"appservice": appservice.ID,
|
2023-09-15 15:39:06 +01:00
|
|
|
"room_id": event.RoomID().String(),
|
2022-09-01 09:20:40 +01:00
|
|
|
}).WithError(err).Errorf("Unable to get membership for room")
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|