2018-05-24 07:54:42 -05: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 03:20:40 -05:00
|
|
|
"bytes"
|
2018-05-24 07:54:42 -05:00
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2022-09-01 03:20:40 -05:00
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2022-09-19 11:39:06 -05:00
|
|
|
"strconv"
|
2022-09-01 03:20:40 -05:00
|
|
|
"time"
|
2018-05-24 07:54:42 -05:00
|
|
|
|
2022-08-29 07:18:33 -05:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
|
2018-05-24 07:54:42 -05:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2020-12-02 11:41:00 -06:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2022-01-05 11:44:49 -06:00
|
|
|
"github.com/matrix-org/dendrite/setup/jetstream"
|
2021-01-26 06:56:20 -06:00
|
|
|
"github.com/matrix-org/dendrite/setup/process"
|
2018-05-24 07:54:42 -05:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
// OutputRoomEventConsumer consumes events that originated in the room server.
|
|
|
|
type OutputRoomEventConsumer struct {
|
2022-09-01 03:20:40 -05:00
|
|
|
ctx context.Context
|
|
|
|
cfg *config.AppServiceAPI
|
|
|
|
client *http.Client
|
|
|
|
jetstream nats.JetStreamContext
|
|
|
|
topic string
|
|
|
|
rsAPI api.AppserviceRoomserverAPI
|
|
|
|
}
|
|
|
|
|
|
|
|
type appserviceState struct {
|
|
|
|
*config.ApplicationService
|
|
|
|
backoff int
|
2018-05-24 07:54:42 -05:00
|
|
|
}
|
|
|
|
|
2018-07-05 11:34:59 -05:00
|
|
|
// NewOutputRoomEventConsumer creates a new OutputRoomEventConsumer. Call
|
|
|
|
// Start() to begin consuming from room servers.
|
2018-05-24 07:54:42 -05:00
|
|
|
func NewOutputRoomEventConsumer(
|
2021-01-26 06:56:20 -06:00
|
|
|
process *process.ProcessContext,
|
2022-09-01 03:20:40 -05:00
|
|
|
cfg *config.AppServiceAPI,
|
|
|
|
client *http.Client,
|
2022-01-05 11:44:49 -06:00
|
|
|
js nats.JetStreamContext,
|
2022-05-05 07:17:38 -05:00
|
|
|
rsAPI api.AppserviceRoomserverAPI,
|
2018-05-24 07:54:42 -05:00
|
|
|
) *OutputRoomEventConsumer {
|
2022-01-05 11:44:49 -06:00
|
|
|
return &OutputRoomEventConsumer{
|
2022-09-01 03:20:40 -05:00
|
|
|
ctx: process.Context(),
|
|
|
|
cfg: cfg,
|
|
|
|
client: client,
|
|
|
|
jetstream: js,
|
|
|
|
topic: cfg.Matrix.JetStream.Prefixed(jetstream.OutputRoomEvent),
|
|
|
|
rsAPI: rsAPI,
|
2018-05-24 07:54:42 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start consuming from room servers
|
|
|
|
func (s *OutputRoomEventConsumer) Start() error {
|
2022-09-01 03:20:40 -05: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 07:54:42 -05:00
|
|
|
}
|
|
|
|
|
2018-07-05 11:34:59 -05:00
|
|
|
// onMessage is called when the appservice component receives a new event from
|
|
|
|
// the room server output log.
|
2022-09-01 03:20:40 -05: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))
|
|
|
|
events := make([]*gomatrixserverlib.HeaderedEvent, 0, len(msgs))
|
|
|
|
for _, msg := range msgs {
|
2022-10-05 05:12:42 -05: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 03:20:40 -05: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 10:10:31 -05:00
|
|
|
}
|
2022-09-01 03:20:40 -05:00
|
|
|
events = append(events, output.NewRoomEvent.Event)
|
|
|
|
if len(output.NewRoomEvent.AddsStateEventIDs) > 0 {
|
|
|
|
newEventID := output.NewRoomEvent.Event.EventID()
|
|
|
|
eventsReq := &api.QueryEventsByIDRequest{
|
2023-03-01 10:06:47 -06:00
|
|
|
RoomID: output.NewRoomEvent.Event.RoomID(),
|
2022-09-01 03:20:40 -05:00
|
|
|
EventIDs: make([]string, 0, len(output.NewRoomEvent.AddsStateEventIDs)),
|
2022-05-24 03:07:33 -05:00
|
|
|
}
|
2022-09-01 03:20:40 -05: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 03:07:33 -05:00
|
|
|
}
|
2022-04-06 10:10:31 -05:00
|
|
|
}
|
2022-09-01 03:20:40 -05:00
|
|
|
|
|
|
|
case api.OutputTypeNewInviteEvent:
|
2022-09-02 09:03:33 -05:00
|
|
|
if output.NewInviteEvent == nil || !s.appserviceIsInterestedInEvent(ctx, output.NewInviteEvent.Event, state.ApplicationService) {
|
2022-09-01 03:20:40 -05:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
events = append(events, output.NewInviteEvent.Event)
|
|
|
|
|
|
|
|
default:
|
|
|
|
continue
|
2022-03-07 11:17:16 -06:00
|
|
|
}
|
|
|
|
}
|
2018-05-24 07:54:42 -05:00
|
|
|
|
2022-09-01 03:20:40 -05: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 11:44:49 -06:00
|
|
|
return true
|
2022-02-02 07:32:48 -06:00
|
|
|
}
|
|
|
|
|
2022-09-19 11:39:06 -05: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 03:20:40 -05: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 11:39:06 -05:00
|
|
|
return s.sendEvents(ctx, state, events, txnID) == nil
|
2018-05-24 07:54:42 -05:00
|
|
|
}
|
|
|
|
|
2022-09-01 03:20:40 -05: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,
|
2020-11-16 09:44:53 -06:00
|
|
|
events []*gomatrixserverlib.HeaderedEvent,
|
2022-09-19 11:39:06 -05:00
|
|
|
txnID string,
|
2018-07-05 11:34:59 -05:00
|
|
|
) error {
|
2022-09-01 03:20:40 -05:00
|
|
|
// Create the transaction body.
|
|
|
|
transaction, err := json.Marshal(
|
|
|
|
gomatrixserverlib.ApplicationServiceTransaction{
|
|
|
|
Events: gomatrixserverlib.HeaderedToClientEvents(events, gomatrixserverlib.FormatAll),
|
|
|
|
},
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-05-30 07:43:13 -05:00
|
|
|
}
|
|
|
|
|
2022-09-19 11:39:06 -05:00
|
|
|
// If txnID is not defined, generate one from the events.
|
|
|
|
if txnID == "" {
|
|
|
|
txnID = fmt.Sprintf("%d_%d", events[0].Event.OriginServerTS(), len(transaction))
|
|
|
|
}
|
2018-05-30 07:43:13 -05:00
|
|
|
|
2022-09-01 03:20:40 -05:00
|
|
|
// Send the transaction to the appservice.
|
|
|
|
// https://matrix.org/docs/spec/application_service/r0.1.2#put-matrix-app-v1-transactions-txnid
|
2022-09-19 11:39:06 -05:00
|
|
|
address := fmt.Sprintf("%s/transactions/%s?access_token=%s", state.URL, txnID, url.QueryEscape(state.HSToken))
|
2022-09-01 03:20:40 -05:00
|
|
|
req, err := http.NewRequestWithContext(ctx, "PUT", address, bytes.NewBuffer(transaction))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := s.client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return state.backoffAndPause(err)
|
2021-03-03 10:27:44 -06:00
|
|
|
}
|
|
|
|
|
2022-09-01 03:20:40 -05: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:
|
|
|
|
return state.backoffAndPause(fmt.Errorf("received HTTP status code %d from appservice", resp.StatusCode))
|
2021-03-03 10:27:44 -06:00
|
|
|
}
|
2022-09-01 03:20:40 -05: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 10:27:44 -06:00
|
|
|
}
|
|
|
|
|
2018-05-30 07:43:13 -05:00
|
|
|
// appserviceIsInterestedInEvent returns a boolean depending on whether a given
|
|
|
|
// event falls within one of a given application service's namespaces.
|
2021-03-03 10:27:44 -06:00
|
|
|
//
|
|
|
|
// TODO: This should be cached, see https://github.com/matrix-org/dendrite/issues/1682
|
2022-09-01 03:20:40 -05:00
|
|
|
func (s *OutputRoomEventConsumer) appserviceIsInterestedInEvent(ctx context.Context, event *gomatrixserverlib.HeaderedEvent, appservice *config.ApplicationService) bool {
|
|
|
|
switch {
|
|
|
|
case appservice.URL == "":
|
2018-06-18 04:43:15 -05:00
|
|
|
return false
|
2022-09-01 03:20:40 -05:00
|
|
|
case appservice.IsInterestedInUserID(event.Sender()):
|
|
|
|
return true
|
|
|
|
case appservice.IsInterestedInRoomID(event.RoomID()):
|
2018-07-16 07:30:04 -05:00
|
|
|
return true
|
2018-05-30 07:43:13 -05:00
|
|
|
}
|
|
|
|
|
2020-03-20 16:40:24 -05:00
|
|
|
if event.Type() == gomatrixserverlib.MRoomMember && event.StateKey() != nil {
|
|
|
|
if appservice.IsInterestedInUserID(*event.StateKey()) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-30 07:43:13 -05:00
|
|
|
// Check all known room aliases of the room the event came from
|
|
|
|
queryReq := api.GetAliasesForRoomIDRequest{RoomID: event.RoomID()}
|
|
|
|
var queryRes api.GetAliasesForRoomIDResponse
|
2020-05-01 04:48:17 -05:00
|
|
|
if err := s.rsAPI.GetAliasesForRoomID(ctx, &queryReq, &queryRes); err == nil {
|
2018-05-30 07:43:13 -05:00
|
|
|
for _, alias := range queryRes.Aliases {
|
2018-07-16 07:30:04 -05:00
|
|
|
if appservice.IsInterestedInRoomAlias(alias) {
|
|
|
|
return true
|
2018-05-30 07:43:13 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.WithFields(log.Fields{
|
2022-09-01 03:20:40 -05:00
|
|
|
"appservice": appservice.ID,
|
|
|
|
"room_id": event.RoomID(),
|
2018-05-30 07:43:13 -05:00
|
|
|
}).WithError(err).Errorf("Unable to get aliases for room")
|
|
|
|
}
|
|
|
|
|
2021-03-03 10:27:44 -06:00
|
|
|
// Check if any of the members in the room match the appservice
|
|
|
|
return s.appserviceJoinedAtEvent(ctx, event, appservice)
|
2018-05-30 07:43:13 -05:00
|
|
|
}
|
2022-09-01 03:20:40 -05:00
|
|
|
|
|
|
|
// appserviceJoinedAtEvent returns a boolean depending on whether a given
|
|
|
|
// appservice has membership at the time a given event was created.
|
|
|
|
func (s *OutputRoomEventConsumer) appserviceJoinedAtEvent(ctx context.Context, event *gomatrixserverlib.HeaderedEvent, appservice *config.ApplicationService) bool {
|
|
|
|
// 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{
|
|
|
|
RoomID: event.RoomID(),
|
|
|
|
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
|
|
|
|
case ev.Type != gomatrixserverlib.MRoomMember:
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
var membership gomatrixserverlib.MemberContent
|
|
|
|
err = json.Unmarshal(ev.Content, &membership)
|
|
|
|
switch {
|
|
|
|
case err != nil:
|
|
|
|
continue
|
|
|
|
case membership.Membership == gomatrixserverlib.Join:
|
2022-09-02 09:03:33 -05:00
|
|
|
if appservice.IsInterestedInUserID(*ev.StateKey) {
|
|
|
|
return true
|
|
|
|
}
|
2022-09-01 03:20:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
log.WithFields(log.Fields{
|
|
|
|
"appservice": appservice.ID,
|
|
|
|
"room_id": event.RoomID(),
|
|
|
|
}).WithError(err).Errorf("Unable to get membership for room")
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|