refactor: update GMSL (#3058)

Sister PR to https://github.com/matrix-org/gomatrixserverlib/pull/364

Read this commit by commit to avoid going insane.
This commit is contained in:
kegsay 2023-04-19 15:50:33 +01:00 committed by GitHub
parent 9fa39263c0
commit 72285b2659
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
306 changed files with 2117 additions and 1934 deletions

View File

@ -20,10 +20,9 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/matrix-org/gomatrixserverlib"
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/appservice/consumers" "github.com/matrix-org/dendrite/appservice/consumers"
"github.com/matrix-org/dendrite/appservice/query" "github.com/matrix-org/dendrite/appservice/query"
@ -86,7 +85,7 @@ func NewInternalAPI(
func generateAppServiceAccount( func generateAppServiceAccount(
userAPI userapi.AppserviceUserAPI, userAPI userapi.AppserviceUserAPI,
as config.ApplicationService, as config.ApplicationService,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
var accRes userapi.PerformAccountCreationResponse var accRes userapi.PerformAccountCreationResponse
err := userAPI.PerformAccountCreation(context.Background(), &userapi.PerformAccountCreationRequest{ err := userAPI.PerformAccountCreation(context.Background(), &userapi.PerformAccountCreationRequest{

View File

@ -27,7 +27,7 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/dendrite/userapi" "github.com/matrix-org/dendrite/userapi"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
) )
@ -326,7 +326,7 @@ func TestRoomserverConsumerOneInvite(t *testing.T) {
room := test.NewRoom(t, alice) room := test.NewRoom(t, alice)
// Invite Bob // Invite Bob
room.CreateAndInsert(t, alice, gomatrixserverlib.MRoomMember, map[string]interface{}{ room.CreateAndInsert(t, alice, spec.MRoomMember, map[string]interface{}{
"membership": "invite", "membership": "invite",
}, test.WithStateKey(bob.ID)) }, test.WithStateKey(bob.ID))
@ -345,7 +345,7 @@ func TestRoomserverConsumerOneInvite(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, ev := range txn.Events { for _, ev := range txn.Events {
if ev.Type != gomatrixserverlib.MRoomMember { if ev.Type != spec.MRoomMember {
continue continue
} }
// Usually we would check the event content for the membership, but since // Usually we would check the event content for the membership, but since

View File

@ -26,6 +26,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
@ -240,7 +241,7 @@ func (s *OutputRoomEventConsumer) appserviceIsInterestedInEvent(ctx context.Cont
return true return true
} }
if event.Type() == gomatrixserverlib.MRoomMember && event.StateKey() != nil { if event.Type() == spec.MRoomMember && event.StateKey() != nil {
if appservice.IsInterestedInUserID(*event.StateKey()) { if appservice.IsInterestedInUserID(*event.StateKey()) {
return true return true
} }
@ -286,7 +287,7 @@ func (s *OutputRoomEventConsumer) appserviceJoinedAtEvent(ctx context.Context, e
switch { switch {
case ev.StateKey == nil: case ev.StateKey == nil:
continue continue
case ev.Type != gomatrixserverlib.MRoomMember: case ev.Type != spec.MRoomMember:
continue continue
} }
var membership gomatrixserverlib.MemberContent var membership gomatrixserverlib.MemberContent
@ -294,7 +295,7 @@ func (s *OutputRoomEventConsumer) appserviceJoinedAtEvent(ctx context.Context, e
switch { switch {
case err != nil: case err != nil:
continue continue
case membership.Membership == gomatrixserverlib.Join: case membership.Membership == spec.Join:
if appservice.IsInterestedInUserID(*ev.StateKey) { if appservice.IsInterestedInUserID(*ev.StateKey) {
return true return true
} }

View File

@ -171,7 +171,7 @@ func startup() {
cfg.Global.TrustedIDServers = []string{} cfg.Global.TrustedIDServers = []string{}
cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID) cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID)
cfg.Global.PrivateKey = sk cfg.Global.PrivateKey = sk
cfg.Global.ServerName = gomatrixserverlib.ServerName(hex.EncodeToString(pk)) cfg.Global.ServerName = spec.ServerName(hex.EncodeToString(pk))
cfg.ClientAPI.RegistrationDisabled = false cfg.ClientAPI.RegistrationDisabled = false
cfg.ClientAPI.OpenRegistrationWithoutVerificationEnabled = true cfg.ClientAPI.OpenRegistrationWithoutVerificationEnabled = true

View File

@ -35,6 +35,7 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
userapiAPI "github.com/matrix-org/dendrite/userapi/api" userapiAPI "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/pinecone/types" "github.com/matrix-org/pinecone/types"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -140,9 +141,9 @@ func (m *DendriteMonolith) SetStaticPeer(uri string) {
} }
} }
func getServerKeyFromString(nodeID string) (gomatrixserverlib.ServerName, error) { func getServerKeyFromString(nodeID string) (spec.ServerName, error) {
var nodeKey gomatrixserverlib.ServerName var nodeKey spec.ServerName
if userID, err := gomatrixserverlib.NewUserID(nodeID, false); err == nil { if userID, err := spec.NewUserID(nodeID, false); err == nil {
hexKey, decodeErr := hex.DecodeString(string(userID.Domain())) hexKey, decodeErr := hex.DecodeString(string(userID.Domain()))
if decodeErr != nil || len(hexKey) != ed25519.PublicKeySize { if decodeErr != nil || len(hexKey) != ed25519.PublicKeySize {
return "", fmt.Errorf("UserID domain is not a valid ed25519 public key: %v", userID.Domain()) return "", fmt.Errorf("UserID domain is not a valid ed25519 public key: %v", userID.Domain())
@ -154,7 +155,7 @@ func getServerKeyFromString(nodeID string) (gomatrixserverlib.ServerName, error)
if decodeErr != nil || len(hexKey) != ed25519.PublicKeySize { if decodeErr != nil || len(hexKey) != ed25519.PublicKeySize {
return "", fmt.Errorf("Relay server uri is not a valid ed25519 public key: %v", nodeID) return "", fmt.Errorf("Relay server uri is not a valid ed25519 public key: %v", nodeID)
} else { } else {
nodeKey = gomatrixserverlib.ServerName(nodeID) nodeKey = spec.ServerName(nodeID)
} }
} }
@ -162,7 +163,7 @@ func getServerKeyFromString(nodeID string) (gomatrixserverlib.ServerName, error)
} }
func (m *DendriteMonolith) SetRelayServers(nodeID string, uris string) { func (m *DendriteMonolith) SetRelayServers(nodeID string, uris string) {
relays := []gomatrixserverlib.ServerName{} relays := []spec.ServerName{}
for _, uri := range strings.Split(uris, ",") { for _, uri := range strings.Split(uris, ",") {
uri = strings.TrimSpace(uri) uri = strings.TrimSpace(uri)
if len(uri) == 0 { if len(uri) == 0 {
@ -188,7 +189,7 @@ func (m *DendriteMonolith) SetRelayServers(nodeID string, uris string) {
m.p2pMonolith.RelayRetriever.SetRelayServers(relays) m.p2pMonolith.RelayRetriever.SetRelayServers(relays)
} else { } else {
relay.UpdateNodeRelayServers( relay.UpdateNodeRelayServers(
gomatrixserverlib.ServerName(nodeKey), spec.ServerName(nodeKey),
relays, relays,
m.p2pMonolith.ProcessCtx.Context(), m.p2pMonolith.ProcessCtx.Context(),
m.p2pMonolith.GetFederationAPI(), m.p2pMonolith.GetFederationAPI(),
@ -215,7 +216,7 @@ func (m *DendriteMonolith) GetRelayServers(nodeID string) string {
relaysString += string(relay) relaysString += string(relay)
} }
} else { } else {
request := api.P2PQueryRelayServersRequest{Server: gomatrixserverlib.ServerName(nodeKey)} request := api.P2PQueryRelayServersRequest{Server: spec.ServerName(nodeKey)}
response := api.P2PQueryRelayServersResponse{} response := api.P2PQueryRelayServersResponse{}
err := m.p2pMonolith.GetFederationAPI().P2PQueryRelayServers(m.p2pMonolith.ProcessCtx.Context(), &request, &response) err := m.p2pMonolith.GetFederationAPI().P2PQueryRelayServers(m.p2pMonolith.ProcessCtx.Context(), &request, &response)
if err != nil { if err != nil {
@ -291,7 +292,7 @@ func (m *DendriteMonolith) RegisterUser(localpart, password string) (string, err
pubkey := m.p2pMonolith.Router.PublicKey() pubkey := m.p2pMonolith.Router.PublicKey()
userID := userutil.MakeUserID( userID := userutil.MakeUserID(
localpart, localpart,
gomatrixserverlib.ServerName(hex.EncodeToString(pubkey[:])), spec.ServerName(hex.EncodeToString(pubkey[:])),
) )
userReq := &userapiAPI.PerformAccountCreationRequest{ userReq := &userapiAPI.PerformAccountCreationRequest{
AccountType: userapiAPI.AccountTypeUser, AccountType: userapiAPI.AccountTypeUser,
@ -342,7 +343,7 @@ func (m *DendriteMonolith) Start() {
prefix := hex.EncodeToString(pk) prefix := hex.EncodeToString(pk)
cfg := monolith.GenerateDefaultConfig(sk, m.StorageDirectory, m.CacheDirectory, prefix) cfg := monolith.GenerateDefaultConfig(sk, m.StorageDirectory, m.CacheDirectory, prefix)
cfg.Global.ServerName = gomatrixserverlib.ServerName(hex.EncodeToString(pk)) cfg.Global.ServerName = spec.ServerName(hex.EncodeToString(pk))
cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID) cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID)
cfg.Global.JetStream.InMemory = false cfg.Global.JetStream.InMemory = false
// NOTE : disabled for now since there is a 64 bit alignment panic on 32 bit systems // NOTE : disabled for now since there is a 64 bit alignment panic on 32 bit systems

View File

@ -18,7 +18,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
func TestMonolithStarts(t *testing.T) { func TestMonolithStarts(t *testing.T) {
@ -110,7 +110,7 @@ func TestParseServerKey(t *testing.T) {
name string name string
serverKey string serverKey string
expectedErr bool expectedErr bool
expectedKey gomatrixserverlib.ServerName expectedKey spec.ServerName
}{ }{
{ {
name: "valid userid as key", name: "valid userid as key",

View File

@ -33,6 +33,7 @@ import (
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/dendrite/userapi" "github.com/matrix-org/dendrite/userapi"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
_ "golang.org/x/mobile/bind" _ "golang.org/x/mobile/bind"
@ -134,7 +135,7 @@ func (m *DendriteMonolith) Start() {
Generate: true, Generate: true,
SingleDatabase: true, SingleDatabase: true,
}) })
cfg.Global.ServerName = gomatrixserverlib.ServerName(hex.EncodeToString(pk)) cfg.Global.ServerName = spec.ServerName(hex.EncodeToString(pk))
cfg.Global.PrivateKey = sk cfg.Global.PrivateKey = sk
cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID) cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID)
cfg.Global.JetStream.StoragePath = config.Path(fmt.Sprintf("%s/", m.StorageDirectory)) cfg.Global.JetStream.StoragePath = config.Path(fmt.Sprintf("%s/", m.StorageDirectory))

View File

@ -18,8 +18,8 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/syncapi" "github.com/matrix-org/dendrite/syncapi"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
@ -123,7 +123,7 @@ func TestPurgeRoom(t *testing.T) {
room := test.NewRoom(t, aliceAdmin, test.RoomPreset(test.PresetTrustedPrivateChat)) room := test.NewRoom(t, aliceAdmin, test.RoomPreset(test.PresetTrustedPrivateChat))
// Invite Bob // Invite Bob
room.CreateAndInsert(t, aliceAdmin, gomatrixserverlib.MRoomMember, map[string]interface{}{ room.CreateAndInsert(t, aliceAdmin, spec.MRoomMember, map[string]interface{}{
"membership": "invite", "membership": "invite",
}, test.WithStateKey(bob.ID)) }, test.WithStateKey(bob.ID))
@ -194,7 +194,7 @@ func TestAdminEvacuateRoom(t *testing.T) {
room := test.NewRoom(t, aliceAdmin) room := test.NewRoom(t, aliceAdmin)
// Join Bob // Join Bob
room.CreateAndInsert(t, bob, gomatrixserverlib.MRoomMember, map[string]interface{}{ room.CreateAndInsert(t, bob, spec.MRoomMember, map[string]interface{}{
"membership": "join", "membership": "join",
}, test.WithStateKey(bob.ID)) }, test.WithStateKey(bob.ID))
@ -291,10 +291,10 @@ func TestAdminEvacuateUser(t *testing.T) {
room2 := test.NewRoom(t, aliceAdmin) room2 := test.NewRoom(t, aliceAdmin)
// Join Bob // Join Bob
room.CreateAndInsert(t, bob, gomatrixserverlib.MRoomMember, map[string]interface{}{ room.CreateAndInsert(t, bob, spec.MRoomMember, map[string]interface{}{
"membership": "join", "membership": "join",
}, test.WithStateKey(bob.ID)) }, test.WithStateKey(bob.ID))
room2.CreateAndInsert(t, bob, gomatrixserverlib.MRoomMember, map[string]interface{}{ room2.CreateAndInsert(t, bob, spec.MRoomMember, map[string]interface{}{
"membership": "join", "membership": "join",
}, test.WithStateKey(bob.ID)) }, test.WithStateKey(bob.ID))

View File

@ -8,14 +8,14 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
var ( var (
ctx = context.Background() ctx = context.Background()
serverName = gomatrixserverlib.ServerName("example.com") serverName = spec.ServerName("example.com")
// space separated localpart+password -> account // space separated localpart+password -> account
lookup = make(map[string]*api.Account) lookup = make(map[string]*api.Account)
device = &api.Device{ device = &api.Device{

View File

@ -22,6 +22,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -37,13 +38,13 @@ type SyncAPIProducer struct {
TopicTypingEvent string TopicTypingEvent string
TopicPresenceEvent string TopicPresenceEvent string
JetStream nats.JetStreamContext JetStream nats.JetStreamContext
ServerName gomatrixserverlib.ServerName ServerName spec.ServerName
UserAPI userapi.ClientUserAPI UserAPI userapi.ClientUserAPI
} }
func (p *SyncAPIProducer) SendReceipt( func (p *SyncAPIProducer) SendReceipt(
ctx context.Context, ctx context.Context,
userID, roomID, eventID, receiptType string, timestamp gomatrixserverlib.Timestamp, userID, roomID, eventID, receiptType string, timestamp spec.Timestamp,
) error { ) error {
m := &nats.Msg{ m := &nats.Msg{
Subject: p.TopicReceiptEvent, Subject: p.TopicReceiptEvent,
@ -154,7 +155,7 @@ func (p *SyncAPIProducer) SendPresence(
m.Header.Set("status_msg", *statusMsg) m.Header.Set("status_msg", *statusMsg)
} }
m.Header.Set("last_active_ts", strconv.Itoa(int(gomatrixserverlib.AsTimestamp(time.Now())))) m.Header.Set("last_active_ts", strconv.Itoa(int(spec.AsTimestamp(time.Now()))))
_, err := p.JetStream.PublishMsg(m, nats.Context(ctx)) _, err := p.JetStream.PublishMsg(m, nats.Context(ctx))
return err return err

View File

@ -10,6 +10,7 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -262,7 +263,7 @@ func AdminDownloadState(req *http.Request, cfg *config.ClientAPI, device *api.De
&roomserverAPI.PerformAdminDownloadStateRequest{ &roomserverAPI.PerformAdminDownloadStateRequest{
UserID: device.UserID, UserID: device.UserID,
RoomID: roomID, RoomID: roomID,
ServerName: gomatrixserverlib.ServerName(serverName), ServerName: spec.ServerName(serverName),
}, },
res, res,
); err != nil { ); err != nil {

View File

@ -22,6 +22,7 @@ import (
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -31,7 +32,7 @@ func GetAliases(
req *http.Request, rsAPI api.ClientRoomserverAPI, device *userapi.Device, roomID string, req *http.Request, rsAPI api.ClientRoomserverAPI, device *userapi.Device, roomID string,
) util.JSONResponse { ) util.JSONResponse {
stateTuple := gomatrixserverlib.StateKeyTuple{ stateTuple := gomatrixserverlib.StateKeyTuple{
EventType: gomatrixserverlib.MRoomHistoryVisibility, EventType: spec.MRoomHistoryVisibility,
StateKey: "", StateKey: "",
} }
stateReq := &api.QueryCurrentStateRequest{ stateReq := &api.QueryCurrentStateRequest{
@ -53,7 +54,7 @@ func GetAliases(
return util.ErrorResponse(fmt.Errorf("historyVisEvent.HistoryVisibility: %w", err)) return util.ErrorResponse(fmt.Errorf("historyVisEvent.HistoryVisibility: %w", err))
} }
} }
if visibility != gomatrixserverlib.WorldReadable { if visibility != spec.WorldReadable {
queryReq := api.QueryMembershipForUserRequest{ queryReq := api.QueryMembershipForUserRequest{
RoomID: roomID, RoomID: roomID,
UserID: device.UserID, UserID: device.UserID,

View File

@ -26,6 +26,8 @@ import (
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
roomserverVersion "github.com/matrix-org/dendrite/roomserver/version" roomserverVersion "github.com/matrix-org/dendrite/roomserver/version"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
@ -233,7 +235,7 @@ func createRoom(
createContent["room_version"] = roomVersion createContent["room_version"] = roomVersion
powerLevelContent := eventutil.InitialPowerLevelsContent(userID) powerLevelContent := eventutil.InitialPowerLevelsContent(userID)
joinRuleContent := gomatrixserverlib.JoinRuleContent{ joinRuleContent := gomatrixserverlib.JoinRuleContent{
JoinRule: gomatrixserverlib.Invite, JoinRule: spec.Invite,
} }
historyVisibilityContent := gomatrixserverlib.HistoryVisibilityContent{ historyVisibilityContent := gomatrixserverlib.HistoryVisibilityContent{
HistoryVisibility: historyVisibilityShared, HistoryVisibility: historyVisibilityShared,
@ -253,40 +255,40 @@ func createRoom(
switch r.Preset { switch r.Preset {
case presetPrivateChat: case presetPrivateChat:
joinRuleContent.JoinRule = gomatrixserverlib.Invite joinRuleContent.JoinRule = spec.Invite
historyVisibilityContent.HistoryVisibility = historyVisibilityShared historyVisibilityContent.HistoryVisibility = historyVisibilityShared
case presetTrustedPrivateChat: case presetTrustedPrivateChat:
joinRuleContent.JoinRule = gomatrixserverlib.Invite joinRuleContent.JoinRule = spec.Invite
historyVisibilityContent.HistoryVisibility = historyVisibilityShared historyVisibilityContent.HistoryVisibility = historyVisibilityShared
for _, invitee := range r.Invite { for _, invitee := range r.Invite {
powerLevelContent.Users[invitee] = 100 powerLevelContent.Users[invitee] = 100
} }
case presetPublicChat: case presetPublicChat:
joinRuleContent.JoinRule = gomatrixserverlib.Public joinRuleContent.JoinRule = spec.Public
historyVisibilityContent.HistoryVisibility = historyVisibilityShared historyVisibilityContent.HistoryVisibility = historyVisibilityShared
} }
createEvent := fledglingEvent{ createEvent := fledglingEvent{
Type: gomatrixserverlib.MRoomCreate, Type: spec.MRoomCreate,
Content: createContent, Content: createContent,
} }
powerLevelEvent := fledglingEvent{ powerLevelEvent := fledglingEvent{
Type: gomatrixserverlib.MRoomPowerLevels, Type: spec.MRoomPowerLevels,
Content: powerLevelContent, Content: powerLevelContent,
} }
joinRuleEvent := fledglingEvent{ joinRuleEvent := fledglingEvent{
Type: gomatrixserverlib.MRoomJoinRules, Type: spec.MRoomJoinRules,
Content: joinRuleContent, Content: joinRuleContent,
} }
historyVisibilityEvent := fledglingEvent{ historyVisibilityEvent := fledglingEvent{
Type: gomatrixserverlib.MRoomHistoryVisibility, Type: spec.MRoomHistoryVisibility,
Content: historyVisibilityContent, Content: historyVisibilityContent,
} }
membershipEvent := fledglingEvent{ membershipEvent := fledglingEvent{
Type: gomatrixserverlib.MRoomMember, Type: spec.MRoomMember,
StateKey: userID, StateKey: userID,
Content: gomatrixserverlib.MemberContent{ Content: gomatrixserverlib.MemberContent{
Membership: gomatrixserverlib.Join, Membership: spec.Join,
DisplayName: profile.DisplayName, DisplayName: profile.DisplayName,
AvatarURL: profile.AvatarURL, AvatarURL: profile.AvatarURL,
}, },
@ -299,7 +301,7 @@ func createRoom(
if r.Name != "" { if r.Name != "" {
nameEvent = &fledglingEvent{ nameEvent = &fledglingEvent{
Type: gomatrixserverlib.MRoomName, Type: spec.MRoomName,
Content: eventutil.NameContent{ Content: eventutil.NameContent{
Name: r.Name, Name: r.Name,
}, },
@ -308,7 +310,7 @@ func createRoom(
if r.Topic != "" { if r.Topic != "" {
topicEvent = &fledglingEvent{ topicEvent = &fledglingEvent{
Type: gomatrixserverlib.MRoomTopic, Type: spec.MRoomTopic,
Content: eventutil.TopicContent{ Content: eventutil.TopicContent{
Topic: r.Topic, Topic: r.Topic,
}, },
@ -317,7 +319,7 @@ func createRoom(
if r.GuestCanJoin { if r.GuestCanJoin {
guestAccessEvent = &fledglingEvent{ guestAccessEvent = &fledglingEvent{
Type: gomatrixserverlib.MRoomGuestAccess, Type: spec.MRoomGuestAccess,
Content: eventutil.GuestAccessContent{ Content: eventutil.GuestAccessContent{
GuestAccess: "can_join", GuestAccess: "can_join",
}, },
@ -347,7 +349,7 @@ func createRoom(
} }
aliasEvent = &fledglingEvent{ aliasEvent = &fledglingEvent{
Type: gomatrixserverlib.MRoomCanonicalAlias, Type: spec.MRoomCanonicalAlias,
Content: eventutil.CanonicalAlias{ Content: eventutil.CanonicalAlias{
Alias: roomAlias, Alias: roomAlias,
}, },
@ -362,25 +364,25 @@ func createRoom(
} }
switch r.InitialState[i].Type { switch r.InitialState[i].Type {
case gomatrixserverlib.MRoomCreate: case spec.MRoomCreate:
continue continue
case gomatrixserverlib.MRoomPowerLevels: case spec.MRoomPowerLevels:
powerLevelEvent = r.InitialState[i] powerLevelEvent = r.InitialState[i]
case gomatrixserverlib.MRoomJoinRules: case spec.MRoomJoinRules:
joinRuleEvent = r.InitialState[i] joinRuleEvent = r.InitialState[i]
case gomatrixserverlib.MRoomHistoryVisibility: case spec.MRoomHistoryVisibility:
historyVisibilityEvent = r.InitialState[i] historyVisibilityEvent = r.InitialState[i]
case gomatrixserverlib.MRoomGuestAccess: case spec.MRoomGuestAccess:
guestAccessEvent = &r.InitialState[i] guestAccessEvent = &r.InitialState[i]
case gomatrixserverlib.MRoomName: case spec.MRoomName:
nameEvent = &r.InitialState[i] nameEvent = &r.InitialState[i]
case gomatrixserverlib.MRoomTopic: case spec.MRoomTopic:
topicEvent = &r.InitialState[i] topicEvent = &r.InitialState[i]
default: default:
@ -510,30 +512,30 @@ func createRoom(
// If this is a direct message then we should invite the participants. // If this is a direct message then we should invite the participants.
if len(r.Invite) > 0 { if len(r.Invite) > 0 {
// Build some stripped state for the invite. // Build some stripped state for the invite.
var globalStrippedState []gomatrixserverlib.InviteV2StrippedState var globalStrippedState []fclient.InviteV2StrippedState
for _, event := range builtEvents { for _, event := range builtEvents {
// Chosen events from the spec: // Chosen events from the spec:
// https://spec.matrix.org/v1.3/client-server-api/#stripped-state // https://spec.matrix.org/v1.3/client-server-api/#stripped-state
switch event.Type() { switch event.Type() {
case gomatrixserverlib.MRoomCreate: case spec.MRoomCreate:
fallthrough fallthrough
case gomatrixserverlib.MRoomName: case spec.MRoomName:
fallthrough fallthrough
case gomatrixserverlib.MRoomAvatar: case spec.MRoomAvatar:
fallthrough fallthrough
case gomatrixserverlib.MRoomTopic: case spec.MRoomTopic:
fallthrough fallthrough
case gomatrixserverlib.MRoomCanonicalAlias: case spec.MRoomCanonicalAlias:
fallthrough fallthrough
case gomatrixserverlib.MRoomEncryption: case spec.MRoomEncryption:
fallthrough fallthrough
case gomatrixserverlib.MRoomMember: case spec.MRoomMember:
fallthrough fallthrough
case gomatrixserverlib.MRoomJoinRules: case spec.MRoomJoinRules:
ev := event.Event ev := event.Event
globalStrippedState = append( globalStrippedState = append(
globalStrippedState, globalStrippedState,
gomatrixserverlib.NewInviteV2StrippedState(ev), fclient.NewInviteV2StrippedState(ev),
) )
} }
} }
@ -542,7 +544,7 @@ func createRoom(
for _, invitee := range r.Invite { for _, invitee := range r.Invite {
// Build the invite event. // Build the invite event.
inviteEvent, err := buildMembershipEvent( inviteEvent, err := buildMembershipEvent(
ctx, invitee, "", profileAPI, device, gomatrixserverlib.Invite, ctx, invitee, "", profileAPI, device, spec.Invite,
roomID, r.IsDirect, cfg, evTime, rsAPI, asAPI, roomID, r.IsDirect, cfg, evTime, rsAPI, asAPI,
) )
if err != nil { if err != nil {
@ -551,7 +553,7 @@ func createRoom(
} }
inviteStrippedState := append( inviteStrippedState := append(
globalStrippedState, globalStrippedState,
gomatrixserverlib.NewInviteV2StrippedState(inviteEvent.Event), fclient.NewInviteV2StrippedState(inviteEvent.Event),
) )
// Send the invite event to the roomserver. // Send the invite event to the roomserver.
var inviteRes roomserverAPI.PerformInviteResponse var inviteRes roomserverAPI.PerformInviteResponse

View File

@ -20,6 +20,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
@ -35,7 +36,7 @@ type roomDirectoryResponse struct {
Servers []string `json:"servers"` Servers []string `json:"servers"`
} }
func (r *roomDirectoryResponse) fillServers(servers []gomatrixserverlib.ServerName) { func (r *roomDirectoryResponse) fillServers(servers []spec.ServerName) {
r.Servers = make([]string, len(servers)) r.Servers = make([]string, len(servers))
for i, s := range servers { for i, s := range servers {
r.Servers[i] = string(s) r.Servers[i] = string(s)
@ -253,7 +254,7 @@ func GetVisibility(
var v roomVisibility var v roomVisibility
if len(res.RoomIDs) == 1 { if len(res.RoomIDs) == 1 {
v.Visibility = gomatrixserverlib.Public v.Visibility = spec.Public
} else { } else {
v.Visibility = "private" v.Visibility = "private"
} }
@ -278,7 +279,7 @@ func SetVisibility(
queryEventsReq := roomserverAPI.QueryLatestEventsAndStateRequest{ queryEventsReq := roomserverAPI.QueryLatestEventsAndStateRequest{
RoomID: roomID, RoomID: roomID,
StateToFetch: []gomatrixserverlib.StateKeyTuple{{ StateToFetch: []gomatrixserverlib.StateKeyTuple{{
EventType: gomatrixserverlib.MRoomPowerLevels, EventType: spec.MRoomPowerLevels,
StateKey: "", StateKey: "",
}}, }},
} }
@ -291,7 +292,7 @@ func SetVisibility(
// NOTSPEC: Check if the user's power is greater than power required to change m.room.canonical_alias event // NOTSPEC: Check if the user's power is greater than power required to change m.room.canonical_alias event
power, _ := gomatrixserverlib.NewPowerLevelContentFromEvent(queryEventsRes.StateEvents[0].Event) power, _ := gomatrixserverlib.NewPowerLevelContentFromEvent(queryEventsRes.StateEvents[0].Event)
if power.UserLevel(dev.UserID) < power.EventLevel(gomatrixserverlib.MRoomCanonicalAlias, true) { if power.UserLevel(dev.UserID) < power.EventLevel(spec.MRoomCanonicalAlias, true) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden("userID doesn't have power level to change visibility"), JSON: jsonerror.Forbidden("userID doesn't have power level to change visibility"),

View File

@ -23,8 +23,8 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/api" "github.com/matrix-org/dendrite/clientapi/api"
@ -72,7 +72,7 @@ func GetPostPublicRooms(
} }
} }
serverName := gomatrixserverlib.ServerName(request.Server) serverName := spec.ServerName(request.Server)
if serverName != "" && !cfg.Matrix.IsLocalServerName(serverName) { if serverName != "" && !cfg.Matrix.IsLocalServerName(serverName) {
res, err := federation.GetPublicRoomsFiltered( res, err := federation.GetPublicRoomsFiltered(
req.Context(), cfg.Matrix.ServerName, serverName, req.Context(), cfg.Matrix.ServerName, serverName,

View File

@ -23,7 +23,7 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -49,7 +49,7 @@ func JoinRoomByIDOrAlias(
for _, serverName := range serverNames { for _, serverName := range serverNames {
joinReq.ServerNames = append( joinReq.ServerNames = append(
joinReq.ServerNames, joinReq.ServerNames,
gomatrixserverlib.ServerName(serverName), spec.ServerName(serverName),
) )
} }
} }

View File

@ -21,6 +21,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
@ -70,7 +71,7 @@ func SendBan(
} }
} }
return sendMembership(req.Context(), profileAPI, device, roomID, gomatrixserverlib.Ban, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI) return sendMembership(req.Context(), profileAPI, device, roomID, spec.Ban, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI)
} }
func sendMembership(ctx context.Context, profileAPI userapi.ClientUserAPI, device *userapi.Device, func sendMembership(ctx context.Context, profileAPI userapi.ClientUserAPI, device *userapi.Device,
@ -149,14 +150,14 @@ func SendKick(
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
// kick is only valid if the user is not currently banned or left (that is, they are joined or invited) // kick is only valid if the user is not currently banned or left (that is, they are joined or invited)
if queryRes.Membership != gomatrixserverlib.Join && queryRes.Membership != gomatrixserverlib.Invite { if queryRes.Membership != spec.Join && queryRes.Membership != spec.Invite {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Unknown("cannot /kick banned or left users"), JSON: jsonerror.Unknown("cannot /kick banned or left users"),
} }
} }
// TODO: should we be using SendLeave instead? // TODO: should we be using SendLeave instead?
return sendMembership(req.Context(), profileAPI, device, roomID, gomatrixserverlib.Leave, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI) return sendMembership(req.Context(), profileAPI, device, roomID, spec.Leave, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI)
} }
func SendUnban( func SendUnban(
@ -190,14 +191,14 @@ func SendUnban(
} }
// unban is only valid if the user is currently banned // unban is only valid if the user is currently banned
if queryRes.Membership != gomatrixserverlib.Ban { if queryRes.Membership != spec.Ban {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.Unknown("can only /unban users that are banned"), JSON: jsonerror.Unknown("can only /unban users that are banned"),
} }
} }
// TODO: should we be using SendLeave instead? // TODO: should we be using SendLeave instead?
return sendMembership(req.Context(), profileAPI, device, roomID, gomatrixserverlib.Leave, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI) return sendMembership(req.Context(), profileAPI, device, roomID, spec.Leave, body.Reason, cfg, body.UserID, evTime, rsAPI, asAPI)
} }
func SendInvite( func SendInvite(
@ -255,7 +256,7 @@ func sendInvite(
asAPI appserviceAPI.AppServiceInternalAPI, evTime time.Time, asAPI appserviceAPI.AppServiceInternalAPI, evTime time.Time,
) (util.JSONResponse, error) { ) (util.JSONResponse, error) {
event, err := buildMembershipEvent( event, err := buildMembershipEvent(
ctx, userID, reason, profileAPI, device, gomatrixserverlib.Invite, ctx, userID, reason, profileAPI, device, spec.Invite,
roomID, false, cfg, evTime, rsAPI, asAPI, roomID, false, cfg, evTime, rsAPI, asAPI,
) )
if err != nil { if err != nil {
@ -480,7 +481,7 @@ func SendForget(
func getPowerlevels(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAPI, roomID string) (*gomatrixserverlib.PowerLevelContent, *util.JSONResponse) { func getPowerlevels(req *http.Request, rsAPI roomserverAPI.ClientRoomserverAPI, roomID string) (*gomatrixserverlib.PowerLevelContent, *util.JSONResponse) {
plEvent := roomserverAPI.GetStateEvent(req.Context(), rsAPI, roomID, gomatrixserverlib.StateKeyTuple{ plEvent := roomserverAPI.GetStateEvent(req.Context(), rsAPI, roomID, gomatrixserverlib.StateKeyTuple{
EventType: gomatrixserverlib.MRoomPowerLevels, EventType: spec.MRoomPowerLevels,
StateKey: "", StateKey: "",
}) })
if plEvent == nil { if plEvent == nil {

View File

@ -20,7 +20,7 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -49,7 +49,7 @@ func PeekRoomByIDOrAlias(
for _, serverName := range serverNames { for _, serverName := range serverNames {
peekReq.ServerNames = append( peekReq.ServerNames = append(
peekReq.ServerNames, peekReq.ServerNames,
gomatrixserverlib.ServerName(serverName), spec.ServerName(serverName),
) )
} }
} }

View File

@ -27,7 +27,7 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -123,7 +123,7 @@ func GetPresence(
} }
} }
p := types.PresenceInternal{LastActiveTS: gomatrixserverlib.Timestamp(lastActive)} p := types.PresenceInternal{LastActiveTS: spec.Timestamp(lastActive)}
currentlyActive := p.CurrentlyActive() currentlyActive := p.CurrentlyActive()
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,

View File

@ -21,6 +21,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
appserviceAPI "github.com/matrix-org/dendrite/appservice/api" appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes" "github.com/matrix-org/dendrite/clientapi/auth/authtypes"
@ -351,7 +352,7 @@ func buildMembershipEvents(
} }
content := gomatrixserverlib.MemberContent{ content := gomatrixserverlib.MemberContent{
Membership: gomatrixserverlib.Join, Membership: spec.Join,
} }
content.DisplayName = newProfile.DisplayName content.DisplayName = newProfile.DisplayName

View File

@ -22,7 +22,7 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/clientapi/producers"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
@ -31,7 +31,7 @@ import (
) )
func SetReceipt(req *http.Request, userAPI api.ClientUserAPI, syncProducer *producers.SyncAPIProducer, device *userapi.Device, roomID, receiptType, eventID string) util.JSONResponse { func SetReceipt(req *http.Request, userAPI api.ClientUserAPI, syncProducer *producers.SyncAPIProducer, device *userapi.Device, roomID, receiptType, eventID string) util.JSONResponse {
timestamp := gomatrixserverlib.AsTimestamp(time.Now()) timestamp := spec.AsTimestamp(time.Now())
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{
"roomID": roomID, "roomID": roomID,
"receiptType": receiptType, "receiptType": receiptType,

View File

@ -20,6 +20,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
@ -77,7 +78,7 @@ func SendRedaction(
allowedToRedact := ev.Sender() == device.UserID allowedToRedact := ev.Sender() == device.UserID
if !allowedToRedact { if !allowedToRedact {
plEvent := roomserverAPI.GetStateEvent(req.Context(), rsAPI, roomID, gomatrixserverlib.StateKeyTuple{ plEvent := roomserverAPI.GetStateEvent(req.Context(), rsAPI, roomID, gomatrixserverlib.StateKeyTuple{
EventType: gomatrixserverlib.MRoomPowerLevels, EventType: spec.MRoomPowerLevels,
StateKey: "", StateKey: "",
}) })
if plEvent == nil { if plEvent == nil {
@ -114,7 +115,7 @@ func SendRedaction(
builder := gomatrixserverlib.EventBuilder{ builder := gomatrixserverlib.EventBuilder{
Sender: device.UserID, Sender: device.UserID,
RoomID: roomID, RoomID: roomID,
Type: gomatrixserverlib.MRoomRedaction, Type: spec.MRoomRedaction,
Redacts: eventID, Redacts: eventID,
} }
err := builder.SetContent(r) err := builder.SetContent(r)

View File

@ -37,6 +37,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/gomatrixserverlib/tokens" "github.com/matrix-org/gomatrixserverlib/tokens"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -206,10 +207,10 @@ var (
// previous parameters with the ones supplied. This mean you cannot "build up" request params. // previous parameters with the ones supplied. This mean you cannot "build up" request params.
type registerRequest struct { type registerRequest struct {
// registration parameters // registration parameters
Password string `json:"password"` Password string `json:"password"`
Username string `json:"username"` Username string `json:"username"`
ServerName gomatrixserverlib.ServerName `json:"-"` ServerName spec.ServerName `json:"-"`
Admin bool `json:"admin"` Admin bool `json:"admin"`
// user-interactive auth params // user-interactive auth params
Auth authDict `json:"auth"` Auth authDict `json:"auth"`
@ -478,7 +479,7 @@ func Register(
} }
var r registerRequest var r registerRequest
host := gomatrixserverlib.ServerName(req.Host) host := spec.ServerName(req.Host)
if v := cfg.Matrix.VirtualHostForHTTPHost(host); v != nil { if v := cfg.Matrix.VirtualHostForHTTPHost(host); v != nil {
r.ServerName = v.ServerName r.ServerName = v.ServerName
} else { } else {
@ -824,7 +825,7 @@ func checkAndCompleteFlow(
func completeRegistration( func completeRegistration(
ctx context.Context, ctx context.Context,
userAPI userapi.ClientUserAPI, userAPI userapi.ClientUserAPI,
username string, serverName gomatrixserverlib.ServerName, displayName string, username string, serverName spec.ServerName, displayName string,
password, appserviceID, ipAddr, userAgent, sessionID string, password, appserviceID, ipAddr, userAgent, sessionID string,
inhibitLogin eventutil.WeakBoolean, inhibitLogin eventutil.WeakBoolean,
deviceDisplayName, deviceID *string, deviceDisplayName, deviceID *string,
@ -994,7 +995,7 @@ func RegisterAvailable(
// Squash username to all lowercase letters // Squash username to all lowercase letters
username = strings.ToLower(username) username = strings.ToLower(username)
domain := cfg.Matrix.ServerName domain := cfg.Matrix.ServerName
host := gomatrixserverlib.ServerName(req.Host) host := spec.ServerName(req.Host)
if v := cfg.Matrix.VirtualHostForHTTPHost(host); v != nil { if v := cfg.Matrix.VirtualHostForHTTPHost(host); v != nil {
domain = v.ServerName domain = v.ServerName
} }

View File

@ -22,8 +22,8 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/setup/base" "github.com/matrix-org/dendrite/setup/base"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
@ -257,7 +257,7 @@ func Setup(
}), }),
).Methods(http.MethodPost, http.MethodOptions) ).Methods(http.MethodPost, http.MethodOptions)
v3mux.Handle("/join/{roomIDOrAlias}", v3mux.Handle("/join/{roomIDOrAlias}",
httputil.MakeAuthAPI(gomatrixserverlib.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI(spec.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
if r := rateLimits.Limit(req, device); r != nil { if r := rateLimits.Limit(req, device); r != nil {
return *r return *r
} }
@ -273,7 +273,7 @@ func Setup(
if mscCfg.Enabled("msc2753") { if mscCfg.Enabled("msc2753") {
v3mux.Handle("/peek/{roomIDOrAlias}", v3mux.Handle("/peek/{roomIDOrAlias}",
httputil.MakeAuthAPI(gomatrixserverlib.Peek, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI(spec.Peek, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
if r := rateLimits.Limit(req, device); r != nil { if r := rateLimits.Limit(req, device); r != nil {
return *r return *r
} }
@ -293,7 +293,7 @@ func Setup(
}, httputil.WithAllowGuests()), }, httputil.WithAllowGuests()),
).Methods(http.MethodGet, http.MethodOptions) ).Methods(http.MethodGet, http.MethodOptions)
v3mux.Handle("/rooms/{roomID}/join", v3mux.Handle("/rooms/{roomID}/join",
httputil.MakeAuthAPI(gomatrixserverlib.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI(spec.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
if r := rateLimits.Limit(req, device); r != nil { if r := rateLimits.Limit(req, device); r != nil {
return *r return *r
} }
@ -1398,7 +1398,7 @@ func Setup(
}, httputil.WithAllowGuests()), }, httputil.WithAllowGuests()),
).Methods(http.MethodPost, http.MethodOptions) ).Methods(http.MethodPost, http.MethodOptions)
v3mux.Handle("/rooms/{roomId}/receipt/{receiptType}/{eventId}", v3mux.Handle("/rooms/{roomId}/receipt/{receiptType}/{eventId}",
httputil.MakeAuthAPI(gomatrixserverlib.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse { httputil.MakeAuthAPI(spec.Join, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
if r := rateLimits.Limit(req, device); r != nil { if r := rateLimits.Limit(req, device); r != nil {
return *r return *r
} }

View File

@ -24,6 +24,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -117,7 +118,7 @@ func SendEvent(
// If we're sending a membership update, make sure to strip the authorised // If we're sending a membership update, make sure to strip the authorised
// via key if it is present, otherwise other servers won't be able to auth // via key if it is present, otherwise other servers won't be able to auth
// the event if the room is set to the "restricted" join rule. // the event if the room is set to the "restricted" join rule.
if eventType == gomatrixserverlib.MRoomMember { if eventType == spec.MRoomMember {
delete(r, "join_authorised_via_users_server") delete(r, "join_authorised_via_users_server")
} }
@ -136,7 +137,7 @@ func SendEvent(
timeToGenerateEvent := time.Since(startedGeneratingEvent) timeToGenerateEvent := time.Since(startedGeneratingEvent)
// validate that the aliases exists // validate that the aliases exists
if eventType == gomatrixserverlib.MRoomCanonicalAlias && stateKey != nil && *stateKey == "" { if eventType == spec.MRoomCanonicalAlias && stateKey != nil && *stateKey == "" {
aliasReq := api.AliasEvent{} aliasReq := api.AliasEvent{}
if err = json.Unmarshal(e.Content(), &aliasReq); err != nil { if err = json.Unmarshal(e.Content(), &aliasReq); err != nil {
return util.ErrorResponse(fmt.Errorf("unable to parse alias event: %w", err)) return util.ErrorResponse(fmt.Errorf("unable to parse alias event: %w", err))

View File

@ -25,6 +25,7 @@ import (
"github.com/matrix-org/dendrite/syncapi/synctypes" "github.com/matrix-org/dendrite/syncapi/synctypes"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -68,7 +69,7 @@ func OnIncomingStateRequest(ctx context.Context, device *userapi.Device, rsAPI a
// that marks the room as world-readable. If we don't then we assume that // that marks the room as world-readable. If we don't then we assume that
// the room is not world-readable. // the room is not world-readable.
for _, ev := range stateRes.StateEvents { for _, ev := range stateRes.StateEvents {
if ev.Type() == gomatrixserverlib.MRoomHistoryVisibility { if ev.Type() == spec.MRoomHistoryVisibility {
content := map[string]string{} content := map[string]string{}
if err := json.Unmarshal(ev.Content(), &content); err != nil { if err := json.Unmarshal(ev.Content(), &content); err != nil {
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed")
@ -185,9 +186,9 @@ func OnIncomingStateTypeRequest(
StateKey: stateKey, StateKey: stateKey,
}, },
} }
if evType != gomatrixserverlib.MRoomHistoryVisibility && stateKey != "" { if evType != spec.MRoomHistoryVisibility && stateKey != "" {
stateToFetch = append(stateToFetch, gomatrixserverlib.StateKeyTuple{ stateToFetch = append(stateToFetch, gomatrixserverlib.StateKeyTuple{
EventType: gomatrixserverlib.MRoomHistoryVisibility, EventType: spec.MRoomHistoryVisibility,
StateKey: "", StateKey: "",
}) })
} }
@ -208,7 +209,7 @@ func OnIncomingStateTypeRequest(
// that marks the room as world-readable. If we don't then we assume that // that marks the room as world-readable. If we don't then we assume that
// the room is not world-readable. // the room is not world-readable.
for _, ev := range stateRes.StateEvents { for _, ev := range stateRes.StateEvents {
if ev.Type() == gomatrixserverlib.MRoomHistoryVisibility { if ev.Type() == spec.MRoomHistoryVisibility {
content := map[string]string{} content := map[string]string{}
if err := json.Unmarshal(ev.Content(), &content); err != nil { if err := json.Unmarshal(ev.Content(), &content); err != nil {
util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed") util.GetLogger(ctx).WithError(err).Error("json.Unmarshal for history visibility failed")
@ -242,7 +243,7 @@ func OnIncomingStateTypeRequest(
} }
// If the user has never been in the room then stop at this point. // If the user has never been in the room then stop at this point.
// We won't tell the user about a room they have never joined. // We won't tell the user about a room they have never joined.
if !membershipRes.HasBeenInRoom || membershipRes.Membership == gomatrixserverlib.Ban { if !membershipRes.HasBeenInRoom || membershipRes.Membership == spec.Ban {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
JSON: jsonerror.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)), JSON: jsonerror.Forbidden(fmt.Sprintf("Unknown room %q or user %q has never joined this room", roomID, device.UserID)),

View File

@ -27,6 +27,7 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -43,7 +44,7 @@ func SearchUserDirectory(
searchString string, searchString string,
limit int, limit int,
federation *fclient.FederationClient, federation *fclient.FederationClient,
localServerName gomatrixserverlib.ServerName, localServerName spec.ServerName,
) util.JSONResponse { ) util.JSONResponse {
if limit < 10 { if limit < 10 {
limit = 10 limit = 10

View File

@ -30,6 +30,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// MembershipRequest represents the body of an incoming POST request // MembershipRequest represents the body of an incoming POST request
@ -278,7 +279,7 @@ func queryIDServerPubKey(ctx context.Context, idServerName string, keyID string)
} }
var pubKeyRes struct { var pubKeyRes struct {
PublicKey gomatrixserverlib.Base64Bytes `json:"public_key"` PublicKey spec.Base64Bytes `json:"public_key"`
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {

View File

@ -19,13 +19,14 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// ParseUsernameParam extracts localpart from usernameParam. // ParseUsernameParam extracts localpart from usernameParam.
// usernameParam can either be a user ID or just the localpart/username. // usernameParam can either be a user ID or just the localpart/username.
// If serverName is passed, it is verified against the domain obtained from usernameParam (if present) // If serverName is passed, it is verified against the domain obtained from usernameParam (if present)
// Returns error in case of invalid usernameParam. // Returns error in case of invalid usernameParam.
func ParseUsernameParam(usernameParam string, cfg *config.Global) (string, gomatrixserverlib.ServerName, error) { func ParseUsernameParam(usernameParam string, cfg *config.Global) (string, spec.ServerName, error) {
localpart := usernameParam localpart := usernameParam
if strings.HasPrefix(usernameParam, "@") { if strings.HasPrefix(usernameParam, "@") {
@ -45,6 +46,6 @@ func ParseUsernameParam(usernameParam string, cfg *config.Global) (string, gomat
} }
// MakeUserID generates user ID from localpart & server name // MakeUserID generates user ID from localpart & server name
func MakeUserID(localpart string, server gomatrixserverlib.ServerName) string { func MakeUserID(localpart string, server spec.ServerName) string {
return fmt.Sprintf("@%s:%s", localpart, string(server)) return fmt.Sprintf("@%s:%s", localpart, string(server))
} }

View File

@ -16,16 +16,16 @@ import (
"testing" "testing"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
var ( var (
localpart = "somelocalpart" localpart = "somelocalpart"
serverName gomatrixserverlib.ServerName = "someservername" serverName spec.ServerName = "someservername"
invalidServerName gomatrixserverlib.ServerName = "invalidservername" invalidServerName spec.ServerName = "invalidservername"
goodUserID = "@" + localpart + ":" + string(serverName) goodUserID = "@" + localpart + ":" + string(serverName)
badUserID = "@bad:user:name@noservername:" badUserID = "@bad:user:name@noservername:"
) )
// TestGoodUserID checks that correct localpart is returned for a valid user ID. // TestGoodUserID checks that correct localpart is returned for a valid user ID.

View File

@ -14,8 +14,8 @@
package defaults package defaults
import "github.com/matrix-org/gomatrixserverlib" import "github.com/matrix-org/gomatrixserverlib/spec"
var DefaultServerNames = map[gomatrixserverlib.ServerName]struct{}{ var DefaultServerNames = map[spec.ServerName]struct{}{
"3bf0258d23c60952639cc4c69c71d1508a7d43a0475d9000ff900a1848411ec7": {}, "3bf0258d23c60952639cc4c69c71d1508a7d43a0475d9000ff900a1848411ec7": {},
} }

View File

@ -33,6 +33,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
pineconeRouter "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router"
@ -77,7 +78,7 @@ func main() {
cfg = monolith.GenerateDefaultConfig(sk, *instanceDir, *instanceDir, *instanceName) cfg = monolith.GenerateDefaultConfig(sk, *instanceDir, *instanceDir, *instanceName)
} }
cfg.Global.ServerName = gomatrixserverlib.ServerName(hex.EncodeToString(pk)) cfg.Global.ServerName = spec.ServerName(hex.EncodeToString(pk))
cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID) cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID)
p2pMonolith := monolith.P2PMonolith{} p2pMonolith := monolith.P2PMonolith{}

View File

@ -51,7 +51,7 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/dendrite/userapi" "github.com/matrix-org/dendrite/userapi"
userAPI "github.com/matrix-org/dendrite/userapi/api" userAPI "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
pineconeConnections "github.com/matrix-org/pinecone/connections" pineconeConnections "github.com/matrix-org/pinecone/connections"
@ -347,7 +347,7 @@ func (p *P2PMonolith) startEventHandler() {
eLog := logrus.WithField("pinecone", "events") eLog := logrus.WithField("pinecone", "events")
p.RelayRetriever = relay.NewRelayServerRetriever( p.RelayRetriever = relay.NewRelayServerRetriever(
context.Background(), context.Background(),
gomatrixserverlib.ServerName(p.Router.PublicKey().String()), spec.ServerName(p.Router.PublicKey().String()),
p.dendrite.FederationAPI, p.dendrite.FederationAPI,
p.dendrite.RelayAPI, p.dendrite.RelayAPI,
stopRelayServerSync, stopRelayServerSync,
@ -373,7 +373,7 @@ func (p *P2PMonolith) startEventHandler() {
// eLog.Info("Broadcast received from: ", e.PeerID) // eLog.Info("Broadcast received from: ", e.PeerID)
req := &federationAPI.PerformWakeupServersRequest{ req := &federationAPI.PerformWakeupServersRequest{
ServerNames: []gomatrixserverlib.ServerName{gomatrixserverlib.ServerName(e.PeerID)}, ServerNames: []spec.ServerName{spec.ServerName(e.PeerID)},
} }
res := &federationAPI.PerformWakeupServersResponse{} res := &federationAPI.PerformWakeupServersResponse{}
if err := p.dendrite.FederationAPI.PerformWakeupServers(p.ProcessCtx.Context(), req, res); err != nil { if err := p.dendrite.FederationAPI.PerformWakeupServers(p.ProcessCtx.Context(), req, res); err != nil {

View File

@ -21,7 +21,7 @@ import (
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
relayServerAPI "github.com/matrix-org/dendrite/relayapi/api" relayServerAPI "github.com/matrix-org/dendrite/relayapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.uber.org/atomic" "go.uber.org/atomic"
) )
@ -32,10 +32,10 @@ const (
type RelayServerRetriever struct { type RelayServerRetriever struct {
ctx context.Context ctx context.Context
serverName gomatrixserverlib.ServerName serverName spec.ServerName
federationAPI federationAPI.FederationInternalAPI federationAPI federationAPI.FederationInternalAPI
relayAPI relayServerAPI.RelayInternalAPI relayAPI relayServerAPI.RelayInternalAPI
relayServersQueried map[gomatrixserverlib.ServerName]bool relayServersQueried map[spec.ServerName]bool
queriedServersMutex sync.Mutex queriedServersMutex sync.Mutex
running atomic.Bool running atomic.Bool
quit chan bool quit chan bool
@ -43,7 +43,7 @@ type RelayServerRetriever struct {
func NewRelayServerRetriever( func NewRelayServerRetriever(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
federationAPI federationAPI.FederationInternalAPI, federationAPI federationAPI.FederationInternalAPI,
relayAPI relayServerAPI.RelayInternalAPI, relayAPI relayServerAPI.RelayInternalAPI,
quit chan bool, quit chan bool,
@ -53,14 +53,14 @@ func NewRelayServerRetriever(
serverName: serverName, serverName: serverName,
federationAPI: federationAPI, federationAPI: federationAPI,
relayAPI: relayAPI, relayAPI: relayAPI,
relayServersQueried: make(map[gomatrixserverlib.ServerName]bool), relayServersQueried: make(map[spec.ServerName]bool),
running: *atomic.NewBool(false), running: *atomic.NewBool(false),
quit: quit, quit: quit,
} }
} }
func (r *RelayServerRetriever) InitializeRelayServers(eLog *logrus.Entry) { func (r *RelayServerRetriever) InitializeRelayServers(eLog *logrus.Entry) {
request := federationAPI.P2PQueryRelayServersRequest{Server: gomatrixserverlib.ServerName(r.serverName)} request := federationAPI.P2PQueryRelayServersRequest{Server: spec.ServerName(r.serverName)}
response := federationAPI.P2PQueryRelayServersResponse{} response := federationAPI.P2PQueryRelayServersResponse{}
err := r.federationAPI.P2PQueryRelayServers(r.ctx, &request, &response) err := r.federationAPI.P2PQueryRelayServers(r.ctx, &request, &response)
if err != nil { if err != nil {
@ -76,13 +76,13 @@ func (r *RelayServerRetriever) InitializeRelayServers(eLog *logrus.Entry) {
eLog.Infof("Registered relay servers: %v", response.RelayServers) eLog.Infof("Registered relay servers: %v", response.RelayServers)
} }
func (r *RelayServerRetriever) SetRelayServers(servers []gomatrixserverlib.ServerName) { func (r *RelayServerRetriever) SetRelayServers(servers []spec.ServerName) {
UpdateNodeRelayServers(r.serverName, servers, r.ctx, r.federationAPI) UpdateNodeRelayServers(r.serverName, servers, r.ctx, r.federationAPI)
// Replace list of servers to sync with and mark them all as unsynced. // Replace list of servers to sync with and mark them all as unsynced.
r.queriedServersMutex.Lock() r.queriedServersMutex.Lock()
defer r.queriedServersMutex.Unlock() defer r.queriedServersMutex.Unlock()
r.relayServersQueried = make(map[gomatrixserverlib.ServerName]bool) r.relayServersQueried = make(map[spec.ServerName]bool)
for _, server := range servers { for _, server := range servers {
r.relayServersQueried[server] = false r.relayServersQueried[server] = false
} }
@ -90,10 +90,10 @@ func (r *RelayServerRetriever) SetRelayServers(servers []gomatrixserverlib.Serve
r.StartSync() r.StartSync()
} }
func (r *RelayServerRetriever) GetRelayServers() []gomatrixserverlib.ServerName { func (r *RelayServerRetriever) GetRelayServers() []spec.ServerName {
r.queriedServersMutex.Lock() r.queriedServersMutex.Lock()
defer r.queriedServersMutex.Unlock() defer r.queriedServersMutex.Unlock()
relayServers := []gomatrixserverlib.ServerName{} relayServers := []spec.ServerName{}
for server := range r.relayServersQueried { for server := range r.relayServersQueried {
relayServers = append(relayServers, server) relayServers = append(relayServers, server)
} }
@ -101,11 +101,11 @@ func (r *RelayServerRetriever) GetRelayServers() []gomatrixserverlib.ServerName
return relayServers return relayServers
} }
func (r *RelayServerRetriever) GetQueriedServerStatus() map[gomatrixserverlib.ServerName]bool { func (r *RelayServerRetriever) GetQueriedServerStatus() map[spec.ServerName]bool {
r.queriedServersMutex.Lock() r.queriedServersMutex.Lock()
defer r.queriedServersMutex.Unlock() defer r.queriedServersMutex.Unlock()
result := map[gomatrixserverlib.ServerName]bool{} result := map[spec.ServerName]bool{}
for server, queried := range r.relayServersQueried { for server, queried := range r.relayServersQueried {
result[server] = queried result[server] = queried
} }
@ -128,7 +128,7 @@ func (r *RelayServerRetriever) SyncRelayServers(stop <-chan bool) {
t := time.NewTimer(relayServerRetryInterval) t := time.NewTimer(relayServerRetryInterval)
for { for {
relayServersToQuery := []gomatrixserverlib.ServerName{} relayServersToQuery := []spec.ServerName{}
func() { func() {
r.queriedServersMutex.Lock() r.queriedServersMutex.Lock()
defer r.queriedServersMutex.Unlock() defer r.queriedServersMutex.Unlock()
@ -158,10 +158,10 @@ func (r *RelayServerRetriever) SyncRelayServers(stop <-chan bool) {
} }
} }
func (r *RelayServerRetriever) queryRelayServers(relayServers []gomatrixserverlib.ServerName) { func (r *RelayServerRetriever) queryRelayServers(relayServers []spec.ServerName) {
logrus.Info("Querying relay servers for any available transactions") logrus.Info("Querying relay servers for any available transactions")
for _, server := range relayServers { for _, server := range relayServers {
userID, err := gomatrixserverlib.NewUserID("@user:"+string(r.serverName), false) userID, err := spec.NewUserID("@user:"+string(r.serverName), false)
if err != nil { if err != nil {
return return
} }
@ -187,8 +187,8 @@ func (r *RelayServerRetriever) queryRelayServers(relayServers []gomatrixserverli
} }
func UpdateNodeRelayServers( func UpdateNodeRelayServers(
node gomatrixserverlib.ServerName, node spec.ServerName,
relays []gomatrixserverlib.ServerName, relays []spec.ServerName,
ctx context.Context, ctx context.Context,
fedAPI federationAPI.FederationInternalAPI, fedAPI federationAPI.FederationInternalAPI,
) { ) {
@ -201,7 +201,7 @@ func UpdateNodeRelayServers(
} }
// Remove old, non-matching relays // Remove old, non-matching relays
var serversToRemove []gomatrixserverlib.ServerName var serversToRemove []spec.ServerName
for _, existingServer := range response.RelayServers { for _, existingServer := range response.RelayServers {
shouldRemove := true shouldRemove := true
for _, newServer := range relays { for _, newServer := range relays {

View File

@ -21,13 +21,13 @@ import (
federationAPI "github.com/matrix-org/dendrite/federationapi/api" federationAPI "github.com/matrix-org/dendrite/federationapi/api"
relayServerAPI "github.com/matrix-org/dendrite/relayapi/api" relayServerAPI "github.com/matrix-org/dendrite/relayapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gotest.tools/v3/poll" "gotest.tools/v3/poll"
) )
var testRelayServers = []gomatrixserverlib.ServerName{"relay1", "relay2"} var testRelayServers = []spec.ServerName{"relay1", "relay2"}
type FakeFedAPI struct { type FakeFedAPI struct {
federationAPI.FederationInternalAPI federationAPI.FederationInternalAPI
@ -48,8 +48,8 @@ type FakeRelayAPI struct {
func (r *FakeRelayAPI) PerformRelayServerSync( func (r *FakeRelayAPI) PerformRelayServerSync(
ctx context.Context, ctx context.Context,
userID gomatrixserverlib.UserID, userID spec.UserID,
relayServer gomatrixserverlib.ServerName, relayServer spec.ServerName,
) error { ) error {
return nil return nil
} }

View File

@ -21,8 +21,8 @@ import (
"github.com/matrix-org/dendrite/cmd/dendrite-demo-pinecone/defaults" "github.com/matrix-org/dendrite/cmd/dendrite-demo-pinecone/defaults"
"github.com/matrix-org/dendrite/federationapi/api" "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
pineconeRouter "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router"
@ -52,16 +52,16 @@ func NewPineconeRoomProvider(
} }
func (p *PineconeRoomProvider) Rooms() []fclient.PublicRoom { func (p *PineconeRoomProvider) Rooms() []fclient.PublicRoom {
list := map[gomatrixserverlib.ServerName]struct{}{} list := map[spec.ServerName]struct{}{}
for k := range defaults.DefaultServerNames { for k := range defaults.DefaultServerNames {
list[k] = struct{}{} list[k] = struct{}{}
} }
for _, k := range p.r.Peers() { for _, k := range p.r.Peers() {
list[gomatrixserverlib.ServerName(k.PublicKey)] = struct{}{} list[spec.ServerName(k.PublicKey)] = struct{}{}
} }
return bulkFetchPublicRoomsFromServers( return bulkFetchPublicRoomsFromServers(
context.Background(), p.fedClient, context.Background(), p.fedClient,
gomatrixserverlib.ServerName(p.r.PublicKey().String()), list, spec.ServerName(p.r.PublicKey().String()), list,
) )
} }
@ -69,8 +69,8 @@ func (p *PineconeRoomProvider) Rooms() []fclient.PublicRoom {
// Returns a list of public rooms. // Returns a list of public rooms.
func bulkFetchPublicRoomsFromServers( func bulkFetchPublicRoomsFromServers(
ctx context.Context, fedClient *fclient.FederationClient, ctx context.Context, fedClient *fclient.FederationClient,
origin gomatrixserverlib.ServerName, origin spec.ServerName,
homeservers map[gomatrixserverlib.ServerName]struct{}, homeservers map[spec.ServerName]struct{},
) (publicRooms []fclient.PublicRoom) { ) (publicRooms []fclient.PublicRoom) {
limit := 200 limit := 200
// follow pipeline semantics, see https://blog.golang.org/pipelines for more info. // follow pipeline semantics, see https://blog.golang.org/pipelines for more info.
@ -84,7 +84,7 @@ func bulkFetchPublicRoomsFromServers(
// concurrently query for public rooms // concurrently query for public rooms
reqctx, reqcancel := context.WithTimeout(ctx, time.Second*5) reqctx, reqcancel := context.WithTimeout(ctx, time.Second*5)
for hs := range homeservers { for hs := range homeservers {
go func(homeserverDomain gomatrixserverlib.ServerName) { go func(homeserverDomain spec.ServerName) {
defer wg.Done() defer wg.Done()
util.GetLogger(reqctx).WithField("hs", homeserverDomain).Info("Querying HS for public rooms") util.GetLogger(reqctx).WithField("hs", homeserverDomain).Info("Querying HS for public rooms")
fres, err := fedClient.GetPublicRooms(reqctx, origin, homeserverDomain, int(limit), "", false, "") fres, err := fedClient.GetPublicRooms(reqctx, origin, homeserverDomain, int(limit), "", false, "")

View File

@ -27,8 +27,8 @@ import (
clienthttputil "github.com/matrix-org/dendrite/clientapi/httputil" clienthttputil "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/cmd/dendrite-demo-pinecone/defaults" "github.com/matrix-org/dendrite/cmd/dendrite-demo-pinecone/defaults"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
pineconeRouter "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router"
@ -80,12 +80,12 @@ func (p *PineconeUserProvider) FederatedUserProfiles(w http.ResponseWriter, r *h
} }
func (p *PineconeUserProvider) QuerySearchProfiles(ctx context.Context, req *userapi.QuerySearchProfilesRequest, res *userapi.QuerySearchProfilesResponse) error { func (p *PineconeUserProvider) QuerySearchProfiles(ctx context.Context, req *userapi.QuerySearchProfilesRequest, res *userapi.QuerySearchProfilesResponse) error {
list := map[gomatrixserverlib.ServerName]struct{}{} list := map[spec.ServerName]struct{}{}
for k := range defaults.DefaultServerNames { for k := range defaults.DefaultServerNames {
list[k] = struct{}{} list[k] = struct{}{}
} }
for _, k := range p.r.Peers() { for _, k := range p.r.Peers() {
list[gomatrixserverlib.ServerName(k.PublicKey)] = struct{}{} list[spec.ServerName(k.PublicKey)] = struct{}{}
} }
res.Profiles = bulkFetchUserDirectoriesFromServers(context.Background(), req, p.fedClient, list) res.Profiles = bulkFetchUserDirectoriesFromServers(context.Background(), req, p.fedClient, list)
return nil return nil
@ -96,7 +96,7 @@ func (p *PineconeUserProvider) QuerySearchProfiles(ctx context.Context, req *use
func bulkFetchUserDirectoriesFromServers( func bulkFetchUserDirectoriesFromServers(
ctx context.Context, req *userapi.QuerySearchProfilesRequest, ctx context.Context, req *userapi.QuerySearchProfilesRequest,
fedClient *fclient.FederationClient, fedClient *fclient.FederationClient,
homeservers map[gomatrixserverlib.ServerName]struct{}, homeservers map[spec.ServerName]struct{},
) (profiles []authtypes.Profile) { ) (profiles []authtypes.Profile) {
jsonBody, err := json.Marshal(req) jsonBody, err := json.Marshal(req)
if err != nil { if err != nil {
@ -115,7 +115,7 @@ func bulkFetchUserDirectoriesFromServers(
// concurrently query for public rooms // concurrently query for public rooms
reqctx, reqcancel := context.WithTimeout(ctx, time.Second*5) reqctx, reqcancel := context.WithTimeout(ctx, time.Second*5)
for hs := range homeservers { for hs := range homeservers {
go func(homeserverDomain gomatrixserverlib.ServerName) { go func(homeserverDomain spec.ServerName) {
defer wg.Done() defer wg.Done()
util.GetLogger(reqctx).WithField("hs", homeserverDomain).Info("Querying HS for users") util.GetLogger(reqctx).WithField("hs", homeserverDomain).Info("Querying HS for users")

View File

@ -33,6 +33,7 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/matrix-org/dendrite/appservice" "github.com/matrix-org/dendrite/appservice"
@ -145,7 +146,7 @@ func main() {
} }
} }
cfg.Global.ServerName = gomatrixserverlib.ServerName(hex.EncodeToString(pk)) cfg.Global.ServerName = spec.ServerName(hex.EncodeToString(pk))
cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID) cfg.Global.KeyID = gomatrixserverlib.KeyID(signing.KeyID)
configErrors := &config.ConfigErrors{} configErrors := &config.ConfigErrors{}

View File

@ -21,6 +21,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const KeyID = "ed25519:dendrite-demo-yggdrasil" const KeyID = "ed25519:dendrite-demo-yggdrasil"
@ -36,7 +37,7 @@ func (f *YggdrasilKeys) KeyRing() *gomatrixserverlib.KeyRing {
func (f *YggdrasilKeys) FetchKeys( func (f *YggdrasilKeys) FetchKeys(
ctx context.Context, ctx context.Context,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) { ) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
res := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult) res := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult)
for req := range requests { for req := range requests {
@ -54,7 +55,7 @@ func (f *YggdrasilKeys) FetchKeys(
Key: hexkey, Key: hexkey,
}, },
ExpiredTS: gomatrixserverlib.PublicKeyNotExpired, ExpiredTS: gomatrixserverlib.PublicKeyNotExpired,
ValidUntilTS: gomatrixserverlib.AsTimestamp(time.Now().Add(24 * time.Hour * 365)), ValidUntilTS: spec.AsTimestamp(time.Now().Add(24 * time.Hour * 365)),
} }
} }
return res, nil return res, nil

View File

@ -23,7 +23,7 @@ import (
"regexp" "regexp"
"strings" "strings"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/neilalexander/utp" "github.com/neilalexander/utp"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -134,14 +134,14 @@ func (n *Node) PeerCount() int {
return len(n.core.GetPeers()) return len(n.core.GetPeers())
} }
func (n *Node) KnownNodes() []gomatrixserverlib.ServerName { func (n *Node) KnownNodes() []spec.ServerName {
nodemap := map[string]struct{}{} nodemap := map[string]struct{}{}
for _, peer := range n.core.GetPeers() { for _, peer := range n.core.GetPeers() {
nodemap[hex.EncodeToString(peer.Key)] = struct{}{} nodemap[hex.EncodeToString(peer.Key)] = struct{}{}
} }
var nodes []gomatrixserverlib.ServerName var nodes []spec.ServerName
for node := range nodemap { for node := range nodemap {
nodes = append(nodes, gomatrixserverlib.ServerName(node)) nodes = append(nodes, spec.ServerName(node))
} }
return nodes return nodes
} }

View File

@ -21,8 +21,8 @@ import (
"github.com/matrix-org/dendrite/cmd/dendrite-demo-yggdrasil/yggconn" "github.com/matrix-org/dendrite/cmd/dendrite-demo-yggdrasil/yggconn"
"github.com/matrix-org/dendrite/federationapi/api" "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -46,7 +46,7 @@ func NewYggdrasilRoomProvider(
func (p *YggdrasilRoomProvider) Rooms() []fclient.PublicRoom { func (p *YggdrasilRoomProvider) Rooms() []fclient.PublicRoom {
return bulkFetchPublicRoomsFromServers( return bulkFetchPublicRoomsFromServers(
context.Background(), p.fedClient, context.Background(), p.fedClient,
gomatrixserverlib.ServerName(p.node.DerivedServerName()), spec.ServerName(p.node.DerivedServerName()),
p.node.KnownNodes(), p.node.KnownNodes(),
) )
} }
@ -55,8 +55,8 @@ func (p *YggdrasilRoomProvider) Rooms() []fclient.PublicRoom {
// Returns a list of public rooms. // Returns a list of public rooms.
func bulkFetchPublicRoomsFromServers( func bulkFetchPublicRoomsFromServers(
ctx context.Context, fedClient *fclient.FederationClient, ctx context.Context, fedClient *fclient.FederationClient,
origin gomatrixserverlib.ServerName, origin spec.ServerName,
homeservers []gomatrixserverlib.ServerName, homeservers []spec.ServerName,
) (publicRooms []fclient.PublicRoom) { ) (publicRooms []fclient.PublicRoom) {
limit := 200 limit := 200
// follow pipeline semantics, see https://blog.golang.org/pipelines for more info. // follow pipeline semantics, see https://blog.golang.org/pipelines for more info.
@ -69,7 +69,7 @@ func bulkFetchPublicRoomsFromServers(
wg.Add(len(homeservers)) wg.Add(len(homeservers))
// concurrently query for public rooms // concurrently query for public rooms
for _, hs := range homeservers { for _, hs := range homeservers {
go func(homeserverDomain gomatrixserverlib.ServerName) { go func(homeserverDomain spec.ServerName) {
defer wg.Done() defer wg.Done()
util.GetLogger(ctx).WithField("hs", homeserverDomain).Info("Querying HS for public rooms") util.GetLogger(ctx).WithField("hs", homeserverDomain).Info("Querying HS for public rooms")
fres, err := fedClient.GetPublicRooms(ctx, origin, homeserverDomain, int(limit), "", false, "") fres, err := fedClient.GetPublicRooms(ctx, origin, homeserverDomain, int(limit), "", false, "")

View File

@ -14,6 +14,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
var requestFrom = flag.String("from", "", "the server name that the request should originate from") var requestFrom = flag.String("from", "", "the server name that the request should originate from")
@ -49,7 +50,7 @@ func main() {
panic("unexpected key block") panic("unexpected key block")
} }
serverName := gomatrixserverlib.ServerName(*requestFrom) serverName := spec.ServerName(*requestFrom)
client := fclient.NewFederationClient( client := fclient.NewFederationClient(
[]*fclient.SigningIdentity{ []*fclient.SigningIdentity{
{ {
@ -83,10 +84,10 @@ func main() {
} }
} }
req := gomatrixserverlib.NewFederationRequest( req := fclient.NewFederationRequest(
method, method,
serverName, serverName,
gomatrixserverlib.ServerName(u.Host), spec.ServerName(u.Host),
u.RequestURI(), u.RequestURI(),
) )
@ -97,7 +98,7 @@ func main() {
} }
if err = req.Sign( if err = req.Sign(
gomatrixserverlib.ServerName(*requestFrom), spec.ServerName(*requestFrom),
gomatrixserverlib.KeyID(keyBlock.Headers["Key-ID"]), gomatrixserverlib.KeyID(keyBlock.Headers["Key-ID"]),
privateKey, privateKey,
); err != nil { ); err != nil {

View File

@ -5,11 +5,11 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"github.com/matrix-org/gomatrixserverlib"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
func main() { func main() {
@ -30,7 +30,7 @@ func main() {
SingleDatabase: true, SingleDatabase: true,
}) })
if *serverName != "" { if *serverName != "" {
cfg.Global.ServerName = gomatrixserverlib.ServerName(*serverName) cfg.Global.ServerName = spec.ServerName(*serverName)
} }
uri := config.DataSource(*dbURI) uri := config.DataSource(*dbURI)
if uri.IsSQLite() || uri == "" { if uri.IsSQLite() || uri == "" {

View File

@ -8,6 +8,7 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
) )
@ -22,9 +23,9 @@ type FederationInternalAPI interface {
P2PFederationAPI P2PFederationAPI
QueryServerKeys(ctx context.Context, request *QueryServerKeysRequest, response *QueryServerKeysResponse) error QueryServerKeys(ctx context.Context, request *QueryServerKeysRequest, response *QueryServerKeysResponse) error
LookupServerKeys(ctx context.Context, s gomatrixserverlib.ServerName, keyRequests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp) ([]gomatrixserverlib.ServerKeys, error) LookupServerKeys(ctx context.Context, s spec.ServerName, keyRequests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp) ([]gomatrixserverlib.ServerKeys, error)
MSC2836EventRelationships(ctx context.Context, origin, dst gomatrixserverlib.ServerName, r fclient.MSC2836EventRelationshipsRequest, roomVersion gomatrixserverlib.RoomVersion) (res fclient.MSC2836EventRelationshipsResponse, err error) MSC2836EventRelationships(ctx context.Context, origin, dst spec.ServerName, r fclient.MSC2836EventRelationshipsRequest, roomVersion gomatrixserverlib.RoomVersion) (res fclient.MSC2836EventRelationshipsResponse, err error)
MSC2946Spaces(ctx context.Context, origin, dst gomatrixserverlib.ServerName, roomID string, suggestedOnly bool) (res fclient.MSC2946SpacesResponse, err error) MSC2946Spaces(ctx context.Context, origin, dst spec.ServerName, roomID string, suggestedOnly bool) (res fclient.MSC2946SpacesResponse, err error)
// Broadcasts an EDU to all servers in rooms we are joined to. Used in the yggdrasil demos. // Broadcasts an EDU to all servers in rooms we are joined to. Used in the yggdrasil demos.
PerformBroadcastEDU( PerformBroadcastEDU(
@ -67,9 +68,9 @@ type RoomserverFederationAPI interface {
// containing only the server names (without information for membership events). // containing only the server names (without information for membership events).
// The response will include this server if they are joined to the room. // The response will include this server if they are joined to the room.
QueryJoinedHostServerNamesInRoom(ctx context.Context, request *QueryJoinedHostServerNamesInRoomRequest, response *QueryJoinedHostServerNamesInRoomResponse) error QueryJoinedHostServerNamesInRoom(ctx context.Context, request *QueryJoinedHostServerNamesInRoomRequest, response *QueryJoinedHostServerNamesInRoomResponse) error
GetEventAuth(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (res fclient.RespEventAuth, err error) GetEventAuth(ctx context.Context, origin, s spec.ServerName, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (res fclient.RespEventAuth, err error)
GetEvent(ctx context.Context, origin, s gomatrixserverlib.ServerName, eventID string) (res gomatrixserverlib.Transaction, err error) GetEvent(ctx context.Context, origin, s spec.ServerName, eventID string) (res gomatrixserverlib.Transaction, err error)
LookupMissingEvents(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespMissingEvents, err error) LookupMissingEvents(ctx context.Context, origin, s spec.ServerName, roomID string, missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespMissingEvents, err error)
} }
type P2PFederationAPI interface { type P2PFederationAPI interface {
@ -99,9 +100,9 @@ type P2PFederationAPI interface {
// implements as proxy calls, with built-in backoff/retries/etc. Errors returned from functions in // implements as proxy calls, with built-in backoff/retries/etc. Errors returned from functions in
// this interface are of type FederationClientError // this interface are of type FederationClientError
type KeyserverFederationAPI interface { type KeyserverFederationAPI interface {
GetUserDevices(ctx context.Context, origin, s gomatrixserverlib.ServerName, userID string) (res fclient.RespUserDevices, err error) GetUserDevices(ctx context.Context, origin, s spec.ServerName, userID string) (res fclient.RespUserDevices, err error)
ClaimKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, oneTimeKeys map[string]map[string]string) (res fclient.RespClaimKeys, err error) ClaimKeys(ctx context.Context, origin, s spec.ServerName, oneTimeKeys map[string]map[string]string) (res fclient.RespClaimKeys, err error)
QueryKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, keys map[string][]string) (res fclient.RespQueryKeys, err error) QueryKeys(ctx context.Context, origin, s spec.ServerName, keys map[string][]string) (res fclient.RespQueryKeys, err error)
} }
// an interface for gmsl.FederationClient - contains functions called by federationapi only. // an interface for gmsl.FederationClient - contains functions called by federationapi only.
@ -111,33 +112,33 @@ type FederationClient interface {
SendTransaction(ctx context.Context, t gomatrixserverlib.Transaction) (res fclient.RespSend, err error) SendTransaction(ctx context.Context, t gomatrixserverlib.Transaction) (res fclient.RespSend, err error)
// Perform operations // Perform operations
LookupRoomAlias(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomAlias string) (res fclient.RespDirectory, err error) LookupRoomAlias(ctx context.Context, origin, s spec.ServerName, roomAlias string) (res fclient.RespDirectory, err error)
Peek(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, peekID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespPeek, err error) Peek(ctx context.Context, origin, s spec.ServerName, roomID, peekID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespPeek, err error)
MakeJoin(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, userID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespMakeJoin, err error) MakeJoin(ctx context.Context, origin, s spec.ServerName, roomID, userID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespMakeJoin, err error)
SendJoin(ctx context.Context, origin, s gomatrixserverlib.ServerName, event *gomatrixserverlib.Event) (res fclient.RespSendJoin, err error) SendJoin(ctx context.Context, origin, s spec.ServerName, event *gomatrixserverlib.Event) (res fclient.RespSendJoin, err error)
MakeLeave(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, userID string) (res fclient.RespMakeLeave, err error) MakeLeave(ctx context.Context, origin, s spec.ServerName, roomID, userID string) (res fclient.RespMakeLeave, err error)
SendLeave(ctx context.Context, origin, s gomatrixserverlib.ServerName, event *gomatrixserverlib.Event) (err error) SendLeave(ctx context.Context, origin, s spec.ServerName, event *gomatrixserverlib.Event) (err error)
SendInviteV2(ctx context.Context, origin, s gomatrixserverlib.ServerName, request gomatrixserverlib.InviteV2Request) (res fclient.RespInviteV2, err error) SendInviteV2(ctx context.Context, origin, s spec.ServerName, request fclient.InviteV2Request) (res fclient.RespInviteV2, err error)
GetEvent(ctx context.Context, origin, s gomatrixserverlib.ServerName, eventID string) (res gomatrixserverlib.Transaction, err error) GetEvent(ctx context.Context, origin, s spec.ServerName, eventID string) (res gomatrixserverlib.Transaction, err error)
GetEventAuth(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (res fclient.RespEventAuth, err error) GetEventAuth(ctx context.Context, origin, s spec.ServerName, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string) (res fclient.RespEventAuth, err error)
GetUserDevices(ctx context.Context, origin, s gomatrixserverlib.ServerName, userID string) (fclient.RespUserDevices, error) GetUserDevices(ctx context.Context, origin, s spec.ServerName, userID string) (fclient.RespUserDevices, error)
ClaimKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, oneTimeKeys map[string]map[string]string) (fclient.RespClaimKeys, error) ClaimKeys(ctx context.Context, origin, s spec.ServerName, oneTimeKeys map[string]map[string]string) (fclient.RespClaimKeys, error)
QueryKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, keys map[string][]string) (fclient.RespQueryKeys, error) QueryKeys(ctx context.Context, origin, s spec.ServerName, keys map[string][]string) (fclient.RespQueryKeys, error)
Backfill(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, limit int, eventIDs []string) (res gomatrixserverlib.Transaction, err error) Backfill(ctx context.Context, origin, s spec.ServerName, roomID string, limit int, eventIDs []string) (res gomatrixserverlib.Transaction, err error)
MSC2836EventRelationships(ctx context.Context, origin, dst gomatrixserverlib.ServerName, r fclient.MSC2836EventRelationshipsRequest, roomVersion gomatrixserverlib.RoomVersion) (res fclient.MSC2836EventRelationshipsResponse, err error) MSC2836EventRelationships(ctx context.Context, origin, dst spec.ServerName, r fclient.MSC2836EventRelationshipsRequest, roomVersion gomatrixserverlib.RoomVersion) (res fclient.MSC2836EventRelationshipsResponse, err error)
MSC2946Spaces(ctx context.Context, origin, dst gomatrixserverlib.ServerName, roomID string, suggestedOnly bool) (res fclient.MSC2946SpacesResponse, err error) MSC2946Spaces(ctx context.Context, origin, dst spec.ServerName, roomID string, suggestedOnly bool) (res fclient.MSC2946SpacesResponse, err error)
ExchangeThirdPartyInvite(ctx context.Context, origin, s gomatrixserverlib.ServerName, builder gomatrixserverlib.EventBuilder) (err error) ExchangeThirdPartyInvite(ctx context.Context, origin, s spec.ServerName, builder gomatrixserverlib.EventBuilder) (err error)
LookupState(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, eventID string, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespState, err error) LookupState(ctx context.Context, origin, s spec.ServerName, roomID string, eventID string, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespState, err error)
LookupStateIDs(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, eventID string) (res fclient.RespStateIDs, err error) LookupStateIDs(ctx context.Context, origin, s spec.ServerName, roomID string, eventID string) (res fclient.RespStateIDs, err error)
LookupMissingEvents(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespMissingEvents, err error) LookupMissingEvents(ctx context.Context, origin, s spec.ServerName, roomID string, missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion) (res fclient.RespMissingEvents, err error)
} }
type P2PFederationClient interface { type P2PFederationClient interface {
P2PSendTransactionToRelay(ctx context.Context, u gomatrixserverlib.UserID, t gomatrixserverlib.Transaction, forwardingServer gomatrixserverlib.ServerName) (res fclient.EmptyResp, err error) P2PSendTransactionToRelay(ctx context.Context, u spec.UserID, t gomatrixserverlib.Transaction, forwardingServer spec.ServerName) (res fclient.EmptyResp, err error)
P2PGetTransactionFromRelay(ctx context.Context, u gomatrixserverlib.UserID, prev fclient.RelayEntry, relayServer gomatrixserverlib.ServerName) (res fclient.RespGetRelayTransaction, err error) P2PGetTransactionFromRelay(ctx context.Context, u spec.UserID, prev fclient.RelayEntry, relayServer spec.ServerName) (res fclient.RespGetRelayTransaction, err error)
} }
// FederationClientError is returned from FederationClient methods in the event of a problem. // FederationClientError is returned from FederationClient methods in the event of a problem.
@ -153,7 +154,7 @@ func (e FederationClientError) Error() string {
} }
type QueryServerKeysRequest struct { type QueryServerKeysRequest struct {
ServerName gomatrixserverlib.ServerName ServerName spec.ServerName
KeyIDToCriteria map[gomatrixserverlib.KeyID]gomatrixserverlib.PublicKeyNotaryQueryCriteria KeyIDToCriteria map[gomatrixserverlib.KeyID]gomatrixserverlib.PublicKeyNotaryQueryCriteria
} }
@ -172,7 +173,7 @@ type QueryServerKeysResponse struct {
} }
type QueryPublicKeysRequest struct { type QueryPublicKeysRequest struct {
Requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp `json:"requests"` Requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp `json:"requests"`
} }
type QueryPublicKeysResponse struct { type QueryPublicKeysResponse struct {
@ -180,13 +181,13 @@ type QueryPublicKeysResponse struct {
} }
type PerformDirectoryLookupRequest struct { type PerformDirectoryLookupRequest struct {
RoomAlias string `json:"room_alias"` RoomAlias string `json:"room_alias"`
ServerName gomatrixserverlib.ServerName `json:"server_name"` ServerName spec.ServerName `json:"server_name"`
} }
type PerformDirectoryLookupResponse struct { type PerformDirectoryLookupResponse struct {
RoomID string `json:"room_id"` RoomID string `json:"room_id"`
ServerNames []gomatrixserverlib.ServerName `json:"server_names"` ServerNames []spec.ServerName `json:"server_names"`
} }
type PerformJoinRequest struct { type PerformJoinRequest struct {
@ -199,7 +200,7 @@ type PerformJoinRequest struct {
} }
type PerformJoinResponse struct { type PerformJoinResponse struct {
JoinedVia gomatrixserverlib.ServerName JoinedVia spec.ServerName
LastError *gomatrix.HTTPError LastError *gomatrix.HTTPError
} }
@ -223,9 +224,9 @@ type PerformLeaveResponse struct {
} }
type PerformInviteRequest struct { type PerformInviteRequest struct {
RoomVersion gomatrixserverlib.RoomVersion `json:"room_version"` RoomVersion gomatrixserverlib.RoomVersion `json:"room_version"`
Event *gomatrixserverlib.HeaderedEvent `json:"event"` Event *gomatrixserverlib.HeaderedEvent `json:"event"`
InviteRoomState []gomatrixserverlib.InviteV2StrippedState `json:"invite_room_state"` InviteRoomState []fclient.InviteV2StrippedState `json:"invite_room_state"`
} }
type PerformInviteResponse struct { type PerformInviteResponse struct {
@ -241,7 +242,7 @@ type QueryJoinedHostServerNamesInRoomRequest struct {
// QueryJoinedHostServerNamesInRoomResponse is a response to QueryJoinedHostServerNames // QueryJoinedHostServerNamesInRoomResponse is a response to QueryJoinedHostServerNames
type QueryJoinedHostServerNamesInRoomResponse struct { type QueryJoinedHostServerNamesInRoomResponse struct {
ServerNames []gomatrixserverlib.ServerName `json:"server_names"` ServerNames []spec.ServerName `json:"server_names"`
} }
type PerformBroadcastEDURequest struct { type PerformBroadcastEDURequest struct {
@ -251,7 +252,7 @@ type PerformBroadcastEDUResponse struct {
} }
type PerformWakeupServersRequest struct { type PerformWakeupServersRequest struct {
ServerNames []gomatrixserverlib.ServerName `json:"server_names"` ServerNames []spec.ServerName `json:"server_names"`
} }
type PerformWakeupServersResponse struct { type PerformWakeupServersResponse struct {
@ -265,24 +266,24 @@ type InputPublicKeysResponse struct {
} }
type P2PQueryRelayServersRequest struct { type P2PQueryRelayServersRequest struct {
Server gomatrixserverlib.ServerName Server spec.ServerName
} }
type P2PQueryRelayServersResponse struct { type P2PQueryRelayServersResponse struct {
RelayServers []gomatrixserverlib.ServerName RelayServers []spec.ServerName
} }
type P2PAddRelayServersRequest struct { type P2PAddRelayServersRequest struct {
Server gomatrixserverlib.ServerName Server spec.ServerName
RelayServers []gomatrixserverlib.ServerName RelayServers []spec.ServerName
} }
type P2PAddRelayServersResponse struct { type P2PAddRelayServersResponse struct {
} }
type P2PRemoveRelayServersRequest struct { type P2PRemoveRelayServersRequest struct {
Server gomatrixserverlib.ServerName Server spec.ServerName
RelayServers []gomatrixserverlib.ServerName RelayServers []spec.ServerName
} }
type P2PRemoveRelayServersResponse struct { type P2PRemoveRelayServersResponse struct {

View File

@ -4,8 +4,9 @@ import (
"context" "context"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type ServersInRoomProvider interface { type ServersInRoomProvider interface {
GetServersForRoom(ctx context.Context, roomID string, event *gomatrixserverlib.Event) []gomatrixserverlib.ServerName GetServersForRoom(ctx context.Context, roomID string, event *gomatrixserverlib.Event) []spec.ServerName
} }

View File

@ -20,6 +20,7 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -40,7 +41,7 @@ type KeyChangeConsumer struct {
durable string durable string
db storage.Database db storage.Database
queues *queue.OutgoingQueues queues *queue.OutgoingQueues
isLocalServerName func(gomatrixserverlib.ServerName) bool isLocalServerName func(spec.ServerName) bool
rsAPI roomserverAPI.FederationRoomserverAPI rsAPI roomserverAPI.FederationRoomserverAPI
topic string topic string
} }
@ -140,7 +141,7 @@ func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) bool {
} }
// Pack the EDU and marshal it // Pack the EDU and marshal it
edu := &gomatrixserverlib.EDU{ edu := &gomatrixserverlib.EDU{
Type: gomatrixserverlib.MDeviceListUpdate, Type: spec.MDeviceListUpdate,
Origin: string(originServerName), Origin: string(originServerName),
} }
event := gomatrixserverlib.DeviceListUpdateEvent{ event := gomatrixserverlib.DeviceListUpdateEvent{

View File

@ -28,6 +28,7 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -39,7 +40,7 @@ type OutputPresenceConsumer struct {
durable string durable string
db storage.Database db storage.Database
queues *queue.OutgoingQueues queues *queue.OutgoingQueues
isLocalServerName func(gomatrixserverlib.ServerName) bool isLocalServerName func(spec.ServerName) bool
rsAPI roomserverAPI.FederationRoomserverAPI rsAPI roomserverAPI.FederationRoomserverAPI
topic string topic string
outboundPresenceEnabled bool outboundPresenceEnabled bool
@ -127,7 +128,7 @@ func (t *OutputPresenceConsumer) onMessage(ctx context.Context, msgs []*nats.Msg
statusMsg = &status statusMsg = &status
} }
p := types.PresenceInternal{LastActiveTS: gomatrixserverlib.Timestamp(ts)} p := types.PresenceInternal{LastActiveTS: spec.Timestamp(ts)}
content := fedTypes.Presence{ content := fedTypes.Presence{
Push: []fedTypes.PresenceContent{ Push: []fedTypes.PresenceContent{
@ -142,7 +143,7 @@ func (t *OutputPresenceConsumer) onMessage(ctx context.Context, msgs []*nats.Msg
} }
edu := &gomatrixserverlib.EDU{ edu := &gomatrixserverlib.EDU{
Type: gomatrixserverlib.MPresence, Type: spec.MPresence,
Origin: string(serverName), Origin: string(serverName),
} }
if edu.Content, err = json.Marshal(content); err != nil { if edu.Content, err = json.Marshal(content); err != nil {

View File

@ -28,6 +28,7 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
syncTypes "github.com/matrix-org/dendrite/syncapi/types" syncTypes "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -39,7 +40,7 @@ type OutputReceiptConsumer struct {
durable string durable string
db storage.Database db storage.Database
queues *queue.OutgoingQueues queues *queue.OutgoingQueues
isLocalServerName func(gomatrixserverlib.ServerName) bool isLocalServerName func(spec.ServerName) bool
topic string topic string
} }
@ -107,7 +108,7 @@ func (t *OutputReceiptConsumer) onMessage(ctx context.Context, msgs []*nats.Msg)
return true return true
} }
receipt.Timestamp = gomatrixserverlib.Timestamp(timestamp) receipt.Timestamp = spec.Timestamp(timestamp)
joined, err := t.db.GetJoinedHosts(ctx, receipt.RoomID) joined, err := t.db.GetJoinedHosts(ctx, receipt.RoomID)
if err != nil { if err != nil {
@ -115,7 +116,7 @@ func (t *OutputReceiptConsumer) onMessage(ctx context.Context, msgs []*nats.Msg)
return false return false
} }
names := make([]gomatrixserverlib.ServerName, len(joined)) names := make([]spec.ServerName, len(joined))
for i := range joined { for i := range joined {
names[i] = joined[i].ServerName names[i] = joined[i].ServerName
} }
@ -133,7 +134,7 @@ func (t *OutputReceiptConsumer) onMessage(ctx context.Context, msgs []*nats.Msg)
} }
edu := &gomatrixserverlib.EDU{ edu := &gomatrixserverlib.EDU{
Type: gomatrixserverlib.MReceipt, Type: spec.MReceipt,
Origin: string(receiptServerName), Origin: string(receiptServerName),
} }
if edu.Content, err = json.Marshal(content); err != nil { if edu.Content, err = json.Marshal(content); err != nil {

View File

@ -22,6 +22,7 @@ import (
"time" "time"
syncAPITypes "github.com/matrix-org/dendrite/syncapi/types" syncAPITypes "github.com/matrix-org/dendrite/syncapi/types"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
@ -207,9 +208,9 @@ func (s *OutputRoomEventConsumer) processMessage(ore api.OutputNewRoomEvent, rew
} }
// If we added new hosts, inform them about our known presence events for this room // If we added new hosts, inform them about our known presence events for this room
if s.cfg.Matrix.Presence.EnableOutbound && len(addsJoinedHosts) > 0 && ore.Event.Type() == gomatrixserverlib.MRoomMember && ore.Event.StateKey() != nil { if s.cfg.Matrix.Presence.EnableOutbound && len(addsJoinedHosts) > 0 && ore.Event.Type() == spec.MRoomMember && ore.Event.StateKey() != nil {
membership, _ := ore.Event.Membership() membership, _ := ore.Event.Membership()
if membership == gomatrixserverlib.Join { if membership == spec.Join {
s.sendPresence(ore.Event.RoomID(), addsJoinedHosts) s.sendPresence(ore.Event.RoomID(), addsJoinedHosts)
} }
} }
@ -239,12 +240,12 @@ func (s *OutputRoomEventConsumer) processMessage(ore api.OutputNewRoomEvent, rew
// Send the event. // Send the event.
return s.queues.SendEvent( return s.queues.SendEvent(
ore.Event, gomatrixserverlib.ServerName(ore.SendAsServer), joinedHostsAtEvent, ore.Event, spec.ServerName(ore.SendAsServer), joinedHostsAtEvent,
) )
} }
func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []types.JoinedHost) { func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []types.JoinedHost) {
joined := make([]gomatrixserverlib.ServerName, 0, len(addedJoined)) joined := make([]spec.ServerName, 0, len(addedJoined))
for _, added := range addedJoined { for _, added := range addedJoined {
joined = append(joined, added.ServerName) joined = append(joined, added.ServerName)
} }
@ -285,7 +286,7 @@ func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []type
continue continue
} }
p := syncAPITypes.PresenceInternal{LastActiveTS: gomatrixserverlib.Timestamp(lastActive)} p := syncAPITypes.PresenceInternal{LastActiveTS: spec.Timestamp(lastActive)}
content.Push = append(content.Push, types.PresenceContent{ content.Push = append(content.Push, types.PresenceContent{
CurrentlyActive: p.CurrentlyActive(), CurrentlyActive: p.CurrentlyActive(),
@ -301,7 +302,7 @@ func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []type
} }
edu := &gomatrixserverlib.EDU{ edu := &gomatrixserverlib.EDU{
Type: gomatrixserverlib.MPresence, Type: spec.MPresence,
Origin: string(s.cfg.Matrix.ServerName), Origin: string(s.cfg.Matrix.ServerName),
} }
if edu.Content, err = json.Marshal(content); err != nil { if edu.Content, err = json.Marshal(content); err != nil {
@ -326,7 +327,7 @@ func (s *OutputRoomEventConsumer) sendPresence(roomID string, addedJoined []type
// Returns an error if there was a problem talking to the room server. // Returns an error if there was a problem talking to the room server.
func (s *OutputRoomEventConsumer) joinedHostsAtEvent( func (s *OutputRoomEventConsumer) joinedHostsAtEvent(
ore api.OutputNewRoomEvent, oldJoinedHosts []types.JoinedHost, ore api.OutputNewRoomEvent, oldJoinedHosts []types.JoinedHost,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
// Combine the delta into a single delta so that the adds and removes can // 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 // cancel each other out. This should reduce the number of times we need
// to fetch a state event from the room server. // to fetch a state event from the room server.
@ -349,7 +350,7 @@ func (s *OutputRoomEventConsumer) joinedHostsAtEvent(
removed[eventID] = true removed[eventID] = true
} }
joined := map[gomatrixserverlib.ServerName]bool{} joined := map[spec.ServerName]bool{}
for _, joinedHost := range oldJoinedHosts { for _, joinedHost := range oldJoinedHosts {
if removed[joinedHost.MemberEventID] { if removed[joinedHost.MemberEventID] {
// This m.room.member event is part of the current state of the // This m.room.member event is part of the current state of the
@ -376,7 +377,7 @@ func (s *OutputRoomEventConsumer) joinedHostsAtEvent(
joined[inboundPeek.ServerName] = true joined[inboundPeek.ServerName] = true
} }
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for serverName, include := range joined { for serverName, include := range joined {
if include { if include {
result = append(result, serverName) result = append(result, serverName)
@ -398,7 +399,7 @@ func JoinedHostsFromEvents(evs []*gomatrixserverlib.Event) ([]types.JoinedHost,
if err != nil { if err != nil {
return nil, err return nil, err
} }
if membership != gomatrixserverlib.Join { if membership != spec.Join {
continue continue
} }
_, serverName, err := gomatrixserverlib.SplitID('@', *ev.StateKey()) _, serverName, err := gomatrixserverlib.SplitID('@', *ev.StateKey())

View File

@ -20,6 +20,7 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -39,7 +40,7 @@ type OutputSendToDeviceConsumer struct {
durable string durable string
db storage.Database db storage.Database
queues *queue.OutgoingQueues queues *queue.OutgoingQueues
isLocalServerName func(gomatrixserverlib.ServerName) bool isLocalServerName func(spec.ServerName) bool
topic string topic string
} }
@ -107,7 +108,7 @@ func (t *OutputSendToDeviceConsumer) onMessage(ctx context.Context, msgs []*nats
// Pack the EDU and marshal it // Pack the EDU and marshal it
edu := &gomatrixserverlib.EDU{ edu := &gomatrixserverlib.EDU{
Type: gomatrixserverlib.MDirectToDevice, Type: spec.MDirectToDevice,
Origin: string(originServerName), Origin: string(originServerName),
} }
tdm := gomatrixserverlib.ToDeviceMessage{ tdm := gomatrixserverlib.ToDeviceMessage{
@ -127,7 +128,7 @@ func (t *OutputSendToDeviceConsumer) onMessage(ctx context.Context, msgs []*nats
} }
log.Debugf("Sending send-to-device message into %q destination queue", destServerName) log.Debugf("Sending send-to-device message into %q destination queue", destServerName)
if err := t.queues.SendEDU(edu, originServerName, []gomatrixserverlib.ServerName{destServerName}); err != nil { if err := t.queues.SendEDU(edu, originServerName, []spec.ServerName{destServerName}); err != nil {
log.WithError(err).Error("failed to send EDU") log.WithError(err).Error("failed to send EDU")
return false return false
} }

View File

@ -25,6 +25,7 @@ import (
"github.com/matrix-org/dendrite/setup/jetstream" "github.com/matrix-org/dendrite/setup/jetstream"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -36,7 +37,7 @@ type OutputTypingConsumer struct {
durable string durable string
db storage.Database db storage.Database
queues *queue.OutgoingQueues queues *queue.OutgoingQueues
isLocalServerName func(gomatrixserverlib.ServerName) bool isLocalServerName func(spec.ServerName) bool
topic string topic string
} }
@ -97,7 +98,7 @@ func (t *OutputTypingConsumer) onMessage(ctx context.Context, msgs []*nats.Msg)
return false return false
} }
names := make([]gomatrixserverlib.ServerName, len(joined)) names := make([]spec.ServerName, len(joined))
for i := range joined { for i := range joined {
names[i] = joined[i].ServerName names[i] = joined[i].ServerName
} }

View File

@ -17,6 +17,7 @@ import (
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/federationapi/api" "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/dendrite/federationapi/routing" "github.com/matrix-org/dendrite/federationapi/routing"
@ -25,12 +26,12 @@ import (
) )
type server struct { type server struct {
name gomatrixserverlib.ServerName // server name name spec.ServerName // server name
validity time.Duration // key validity duration from now validity time.Duration // key validity duration from now
config *config.FederationAPI // skeleton config, from TestMain config *config.FederationAPI // skeleton config, from TestMain
fedclient *fclient.FederationClient // uses MockRoundTripper fedclient *fclient.FederationClient // uses MockRoundTripper
cache *caching.Caches // server-specific cache cache *caching.Caches // server-specific cache
api api.FederationInternalAPI // server-specific server key API api api.FederationInternalAPI // server-specific server key API
} }
func (s *server) renew() { func (s *server) renew() {
@ -83,7 +84,7 @@ func TestMain(m *testing.M) {
Generate: true, Generate: true,
SingleDatabase: false, SingleDatabase: false,
}) })
cfg.Global.ServerName = gomatrixserverlib.ServerName(s.name) cfg.Global.ServerName = spec.ServerName(s.name)
cfg.Global.PrivateKey = testPriv cfg.Global.PrivateKey = testPriv
cfg.Global.JetStream.InMemory = true cfg.Global.JetStream.InMemory = true
cfg.Global.JetStream.TopicPrefix = string(s.name[:1]) cfg.Global.JetStream.TopicPrefix = string(s.name[:1])
@ -141,7 +142,7 @@ func (m *MockRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err
} }
// Get the keys and JSON-ify them. // Get the keys and JSON-ify them.
keys := routing.LocalKeys(s.config, gomatrixserverlib.ServerName(req.Host)) keys := routing.LocalKeys(s.config, spec.ServerName(req.Host))
body, err := json.MarshalIndent(keys.JSON, "", " ") body, err := json.MarshalIndent(keys.JSON, "", " ")
if err != nil { if err != nil {
return nil, err return nil, err
@ -166,8 +167,8 @@ func TestServersRequestOwnKeys(t *testing.T) {
} }
res, err := s.api.FetchKeys( res, err := s.api.FetchKeys(
context.Background(), context.Background(),
map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{ map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp{
req: gomatrixserverlib.AsTimestamp(time.Now()), req: spec.AsTimestamp(time.Now()),
}, },
) )
if err != nil { if err != nil {
@ -192,8 +193,8 @@ func TestRenewalBehaviour(t *testing.T) {
res, err := serverA.api.FetchKeys( res, err := serverA.api.FetchKeys(
context.Background(), context.Background(),
map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{ map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp{
req: gomatrixserverlib.AsTimestamp(time.Now()), req: spec.AsTimestamp(time.Now()),
}, },
) )
if err != nil { if err != nil {
@ -216,8 +217,8 @@ func TestRenewalBehaviour(t *testing.T) {
res, err = serverA.api.FetchKeys( res, err = serverA.api.FetchKeys(
context.Background(), context.Background(),
map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{ map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp{
req: gomatrixserverlib.AsTimestamp(time.Now()), req: spec.AsTimestamp(time.Now()),
}, },
) )
if err != nil { if err != nil {

View File

@ -16,6 +16,7 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
"github.com/matrix-org/dendrite/federationapi" "github.com/matrix-org/dendrite/federationapi"
@ -56,7 +57,7 @@ type fedClient struct {
fedClientMutex sync.Mutex fedClientMutex sync.Mutex
api.FederationClient api.FederationClient
allowJoins []*test.Room allowJoins []*test.Room
keys map[gomatrixserverlib.ServerName]struct { keys map[spec.ServerName]struct {
key ed25519.PrivateKey key ed25519.PrivateKey
keyID gomatrixserverlib.KeyID keyID gomatrixserverlib.KeyID
} }
@ -64,7 +65,7 @@ type fedClient struct {
sentTxn bool sentTxn bool
} }
func (f *fedClient) GetServerKeys(ctx context.Context, matrixServer gomatrixserverlib.ServerName) (gomatrixserverlib.ServerKeys, error) { func (f *fedClient) GetServerKeys(ctx context.Context, matrixServer spec.ServerName) (gomatrixserverlib.ServerKeys, error) {
f.fedClientMutex.Lock() f.fedClientMutex.Lock()
defer f.fedClientMutex.Unlock() defer f.fedClientMutex.Unlock()
fmt.Println("GetServerKeys:", matrixServer) fmt.Println("GetServerKeys:", matrixServer)
@ -83,11 +84,11 @@ func (f *fedClient) GetServerKeys(ctx context.Context, matrixServer gomatrixserv
} }
keys.ServerName = matrixServer keys.ServerName = matrixServer
keys.ValidUntilTS = gomatrixserverlib.AsTimestamp(time.Now().Add(10 * time.Hour)) keys.ValidUntilTS = spec.AsTimestamp(time.Now().Add(10 * time.Hour))
publicKey := pkey.Public().(ed25519.PublicKey) publicKey := pkey.Public().(ed25519.PublicKey)
keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{ keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{
keyID: { keyID: {
Key: gomatrixserverlib.Base64Bytes(publicKey), Key: spec.Base64Bytes(publicKey),
}, },
} }
toSign, err := json.Marshal(keys.ServerKeyFields) toSign, err := json.Marshal(keys.ServerKeyFields)
@ -105,7 +106,7 @@ func (f *fedClient) GetServerKeys(ctx context.Context, matrixServer gomatrixserv
return keys, nil return keys, nil
} }
func (f *fedClient) MakeJoin(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, userID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespMakeJoin, err error) { func (f *fedClient) MakeJoin(ctx context.Context, origin, s spec.ServerName, roomID, userID string, roomVersions []gomatrixserverlib.RoomVersion) (res fclient.RespMakeJoin, err error) {
for _, r := range f.allowJoins { for _, r := range f.allowJoins {
if r.ID == roomID { if r.ID == roomID {
res.RoomVersion = r.Version res.RoomVersion = r.Version
@ -114,7 +115,7 @@ func (f *fedClient) MakeJoin(ctx context.Context, origin, s gomatrixserverlib.Se
RoomID: roomID, RoomID: roomID,
Type: "m.room.member", Type: "m.room.member",
StateKey: &userID, StateKey: &userID,
Content: gomatrixserverlib.RawJSON([]byte(`{"membership":"join"}`)), Content: spec.RawJSON([]byte(`{"membership":"join"}`)),
PrevEvents: r.ForwardExtremities(), PrevEvents: r.ForwardExtremities(),
} }
var needed gomatrixserverlib.StateNeeded var needed gomatrixserverlib.StateNeeded
@ -129,7 +130,7 @@ func (f *fedClient) MakeJoin(ctx context.Context, origin, s gomatrixserverlib.Se
} }
return return
} }
func (f *fedClient) SendJoin(ctx context.Context, origin, s gomatrixserverlib.ServerName, event *gomatrixserverlib.Event) (res fclient.RespSendJoin, err error) { func (f *fedClient) SendJoin(ctx context.Context, origin, s spec.ServerName, event *gomatrixserverlib.Event) (res fclient.RespSendJoin, err error) {
f.fedClientMutex.Lock() f.fedClientMutex.Lock()
defer f.fedClientMutex.Unlock() defer f.fedClientMutex.Unlock()
for _, r := range f.allowJoins { for _, r := range f.allowJoins {
@ -147,7 +148,7 @@ func (f *fedClient) SendTransaction(ctx context.Context, t gomatrixserverlib.Tra
f.fedClientMutex.Lock() f.fedClientMutex.Lock()
defer f.fedClientMutex.Unlock() defer f.fedClientMutex.Unlock()
for _, edu := range t.EDUs { for _, edu := range t.EDUs {
if edu.Type == gomatrixserverlib.MDeviceListUpdate { if edu.Type == spec.MDeviceListUpdate {
f.sentTxn = true f.sentTxn = true
} }
} }
@ -174,7 +175,7 @@ func testFederationAPIJoinThenKeyUpdate(t *testing.T, dbType test.DBType) {
jsctx, _ := natsInstance.Prepare(processCtx, &cfg.Global.JetStream) jsctx, _ := natsInstance.Prepare(processCtx, &cfg.Global.JetStream)
defer jetstream.DeleteAllStreams(jsctx, &cfg.Global.JetStream) defer jetstream.DeleteAllStreams(jsctx, &cfg.Global.JetStream)
serverA := gomatrixserverlib.ServerName("server.a") serverA := spec.ServerName("server.a")
serverAKeyID := gomatrixserverlib.KeyID("ed25519:servera") serverAKeyID := gomatrixserverlib.KeyID("ed25519:servera")
serverAPrivKey := test.PrivateKeyA serverAPrivKey := test.PrivateKeyA
creator := test.NewUser(t, test.WithSigningServer(serverA, serverAKeyID, serverAPrivKey)) creator := test.NewUser(t, test.WithSigningServer(serverA, serverAKeyID, serverAPrivKey))
@ -203,7 +204,7 @@ func testFederationAPIJoinThenKeyUpdate(t *testing.T, dbType test.DBType) {
fc := &fedClient{ fc := &fedClient{
allowJoins: []*test.Room{room}, allowJoins: []*test.Room{room},
t: t, t: t,
keys: map[gomatrixserverlib.ServerName]struct { keys: map[spec.ServerName]struct {
key ed25519.PrivateKey key ed25519.PrivateKey
keyID gomatrixserverlib.KeyID keyID gomatrixserverlib.KeyID
}{ }{
@ -223,7 +224,7 @@ func testFederationAPIJoinThenKeyUpdate(t *testing.T, dbType test.DBType) {
fsapi.PerformJoin(context.Background(), &api.PerformJoinRequest{ fsapi.PerformJoin(context.Background(), &api.PerformJoinRequest{
RoomID: room.ID, RoomID: room.ID,
UserID: joiningUser.ID, UserID: joiningUser.ID,
ServerNames: []gomatrixserverlib.ServerName{serverA}, ServerNames: []spec.ServerName{serverA},
}, &resp) }, &resp)
if resp.JoinedVia != serverA { if resp.JoinedVia != serverA {
t.Errorf("PerformJoin: joined via %v want %v", resp.JoinedVia, serverA) t.Errorf("PerformJoin: joined via %v want %v", resp.JoinedVia, serverA)
@ -302,7 +303,7 @@ func TestRoomsV3URLEscapeDoNot404(t *testing.T) {
_, privKey, _ := ed25519.GenerateKey(nil) _, privKey, _ := ed25519.GenerateKey(nil)
cfg.Global.KeyID = gomatrixserverlib.KeyID("ed25519:auto") cfg.Global.KeyID = gomatrixserverlib.KeyID("ed25519:auto")
cfg.Global.ServerName = gomatrixserverlib.ServerName("localhost") cfg.Global.ServerName = spec.ServerName("localhost")
cfg.Global.PrivateKey = privKey cfg.Global.PrivateKey = privKey
cfg.Global.JetStream.InMemory = true cfg.Global.JetStream.InMemory = true
keyRing := &test.NopJSONVerifier{} keyRing := &test.NopJSONVerifier{}
@ -312,7 +313,7 @@ func TestRoomsV3URLEscapeDoNot404(t *testing.T) {
federationapi.AddPublicRoutes(processCtx, routers, cfg, &natsInstance, nil, nil, keyRing, nil, &internal.FederationInternalAPI{}, nil, caching.DisableMetrics) federationapi.AddPublicRoutes(processCtx, routers, cfg, &natsInstance, nil, nil, keyRing, nil, &internal.FederationInternalAPI{}, nil, caching.DisableMetrics)
baseURL, cancel := test.ListenAndServe(t, routers.Federation, true) baseURL, cancel := test.ListenAndServe(t, routers.Federation, true)
defer cancel() defer cancel()
serverName := gomatrixserverlib.ServerName(strings.TrimPrefix(baseURL, "https://")) serverName := spec.ServerName(strings.TrimPrefix(baseURL, "https://"))
fedCli := fclient.NewFederationClient( fedCli := fclient.NewFederationClient(
cfg.Global.SigningIdentities(), cfg.Global.SigningIdentities(),
@ -325,7 +326,7 @@ func TestRoomsV3URLEscapeDoNot404(t *testing.T) {
t.Errorf("failed to parse event: %s", err) t.Errorf("failed to parse event: %s", err)
} }
he := ev.Headered(tc.roomVer) he := ev.Headered(tc.roomVer)
invReq, err := gomatrixserverlib.NewInviteV2Request(he, nil) invReq, err := fclient.NewInviteV2Request(he, nil)
if err != nil { if err != nil {
t.Errorf("failed to create invite v2 request: %s", err) t.Errorf("failed to create invite v2 request: %s", err)
continue continue

View File

@ -17,6 +17,7 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -107,7 +108,7 @@ func NewFederationInternalAPI(
} }
} }
func (a *FederationInternalAPI) isBlacklistedOrBackingOff(s gomatrixserverlib.ServerName) (*statistics.ServerStatistics, error) { func (a *FederationInternalAPI) isBlacklistedOrBackingOff(s spec.ServerName) (*statistics.ServerStatistics, error) {
stats := a.statistics.ForServer(s) stats := a.statistics.ForServer(s)
if stats.Blacklisted() { if stats.Blacklisted() {
return stats, &api.FederationClientError{ return stats, &api.FederationClientError{
@ -144,7 +145,7 @@ func failBlacklistableError(err error, stats *statistics.ServerStatistics) (unti
} }
func (a *FederationInternalAPI) doRequestIfNotBackingOffOrBlacklisted( func (a *FederationInternalAPI) doRequestIfNotBackingOffOrBlacklisted(
s gomatrixserverlib.ServerName, request func() (interface{}, error), s spec.ServerName, request func() (interface{}, error),
) (interface{}, error) { ) (interface{}, error) {
stats, err := a.isBlacklistedOrBackingOff(s) stats, err := a.isBlacklistedOrBackingOff(s)
if err != nil { if err != nil {
@ -169,7 +170,7 @@ func (a *FederationInternalAPI) doRequestIfNotBackingOffOrBlacklisted(
} }
func (a *FederationInternalAPI) doRequestIfNotBlacklisted( func (a *FederationInternalAPI) doRequestIfNotBlacklisted(
s gomatrixserverlib.ServerName, request func() (interface{}, error), s spec.ServerName, request func() (interface{}, error),
) (interface{}, error) { ) (interface{}, error) {
stats := a.statistics.ForServer(s) stats := a.statistics.ForServer(s)
if blacklisted := stats.Blacklisted(); blacklisted { if blacklisted := stats.Blacklisted(); blacklisted {

View File

@ -6,13 +6,14 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// Functions here are "proxying" calls to the gomatrixserverlib federation // Functions here are "proxying" calls to the gomatrixserverlib federation
// client. // client.
func (a *FederationInternalAPI) GetEventAuth( func (a *FederationInternalAPI) GetEventAuth(
ctx context.Context, origin, s gomatrixserverlib.ServerName, ctx context.Context, origin, s spec.ServerName,
roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion, roomID, eventID string,
) (res fclient.RespEventAuth, err error) { ) (res fclient.RespEventAuth, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
@ -27,7 +28,7 @@ func (a *FederationInternalAPI) GetEventAuth(
} }
func (a *FederationInternalAPI) GetUserDevices( func (a *FederationInternalAPI) GetUserDevices(
ctx context.Context, origin, s gomatrixserverlib.ServerName, userID string, ctx context.Context, origin, s spec.ServerName, userID string,
) (fclient.RespUserDevices, error) { ) (fclient.RespUserDevices, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -41,7 +42,7 @@ func (a *FederationInternalAPI) GetUserDevices(
} }
func (a *FederationInternalAPI) ClaimKeys( func (a *FederationInternalAPI) ClaimKeys(
ctx context.Context, origin, s gomatrixserverlib.ServerName, oneTimeKeys map[string]map[string]string, ctx context.Context, origin, s spec.ServerName, oneTimeKeys map[string]map[string]string,
) (fclient.RespClaimKeys, error) { ) (fclient.RespClaimKeys, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -55,7 +56,7 @@ func (a *FederationInternalAPI) ClaimKeys(
} }
func (a *FederationInternalAPI) QueryKeys( func (a *FederationInternalAPI) QueryKeys(
ctx context.Context, origin, s gomatrixserverlib.ServerName, keys map[string][]string, ctx context.Context, origin, s spec.ServerName, keys map[string][]string,
) (fclient.RespQueryKeys, error) { ) (fclient.RespQueryKeys, error) {
ires, err := a.doRequestIfNotBackingOffOrBlacklisted(s, func() (interface{}, error) { ires, err := a.doRequestIfNotBackingOffOrBlacklisted(s, func() (interface{}, error) {
return a.federation.QueryKeys(ctx, origin, s, keys) return a.federation.QueryKeys(ctx, origin, s, keys)
@ -67,7 +68,7 @@ func (a *FederationInternalAPI) QueryKeys(
} }
func (a *FederationInternalAPI) Backfill( func (a *FederationInternalAPI) Backfill(
ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, limit int, eventIDs []string, ctx context.Context, origin, s spec.ServerName, roomID string, limit int, eventIDs []string,
) (res gomatrixserverlib.Transaction, err error) { ) (res gomatrixserverlib.Transaction, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -81,7 +82,7 @@ func (a *FederationInternalAPI) Backfill(
} }
func (a *FederationInternalAPI) LookupState( func (a *FederationInternalAPI) LookupState(
ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion, ctx context.Context, origin, s spec.ServerName, roomID, eventID string, roomVersion gomatrixserverlib.RoomVersion,
) (res gomatrixserverlib.StateResponse, err error) { ) (res gomatrixserverlib.StateResponse, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -96,7 +97,7 @@ func (a *FederationInternalAPI) LookupState(
} }
func (a *FederationInternalAPI) LookupStateIDs( func (a *FederationInternalAPI) LookupStateIDs(
ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID, eventID string, ctx context.Context, origin, s spec.ServerName, roomID, eventID string,
) (res gomatrixserverlib.StateIDResponse, err error) { ) (res gomatrixserverlib.StateIDResponse, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -110,7 +111,7 @@ func (a *FederationInternalAPI) LookupStateIDs(
} }
func (a *FederationInternalAPI) LookupMissingEvents( func (a *FederationInternalAPI) LookupMissingEvents(
ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, ctx context.Context, origin, s spec.ServerName, roomID string,
missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion, missing fclient.MissingEvents, roomVersion gomatrixserverlib.RoomVersion,
) (res fclient.RespMissingEvents, err error) { ) (res fclient.RespMissingEvents, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
@ -125,7 +126,7 @@ func (a *FederationInternalAPI) LookupMissingEvents(
} }
func (a *FederationInternalAPI) GetEvent( func (a *FederationInternalAPI) GetEvent(
ctx context.Context, origin, s gomatrixserverlib.ServerName, eventID string, ctx context.Context, origin, s spec.ServerName, eventID string,
) (res gomatrixserverlib.Transaction, err error) { ) (res gomatrixserverlib.Transaction, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
@ -139,7 +140,7 @@ func (a *FederationInternalAPI) GetEvent(
} }
func (a *FederationInternalAPI) LookupServerKeys( func (a *FederationInternalAPI) LookupServerKeys(
ctx context.Context, s gomatrixserverlib.ServerName, keyRequests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, ctx context.Context, s spec.ServerName, keyRequests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
) ([]gomatrixserverlib.ServerKeys, error) { ) ([]gomatrixserverlib.ServerKeys, error) {
ctx, cancel := context.WithTimeout(ctx, time.Minute) ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel() defer cancel()
@ -153,7 +154,7 @@ func (a *FederationInternalAPI) LookupServerKeys(
} }
func (a *FederationInternalAPI) MSC2836EventRelationships( func (a *FederationInternalAPI) MSC2836EventRelationships(
ctx context.Context, origin, s gomatrixserverlib.ServerName, r fclient.MSC2836EventRelationshipsRequest, ctx context.Context, origin, s spec.ServerName, r fclient.MSC2836EventRelationshipsRequest,
roomVersion gomatrixserverlib.RoomVersion, roomVersion gomatrixserverlib.RoomVersion,
) (res fclient.MSC2836EventRelationshipsResponse, err error) { ) (res fclient.MSC2836EventRelationshipsResponse, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Minute) ctx, cancel := context.WithTimeout(ctx, time.Minute)
@ -168,7 +169,7 @@ func (a *FederationInternalAPI) MSC2836EventRelationships(
} }
func (a *FederationInternalAPI) MSC2946Spaces( func (a *FederationInternalAPI) MSC2946Spaces(
ctx context.Context, origin, s gomatrixserverlib.ServerName, roomID string, suggestedOnly bool, ctx context.Context, origin, s spec.ServerName, roomID string, suggestedOnly bool,
) (res fclient.MSC2946SpacesResponse, err error) { ) (res fclient.MSC2946SpacesResponse, err error) {
ctx, cancel := context.WithTimeout(ctx, time.Minute) ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel() defer cancel()

View File

@ -24,8 +24,8 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -34,7 +34,7 @@ const (
FailuresUntilBlacklist = 8 FailuresUntilBlacklist = 8
) )
func (t *testFedClient) QueryKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, keys map[string][]string) (fclient.RespQueryKeys, error) { func (t *testFedClient) QueryKeys(ctx context.Context, origin, s spec.ServerName, keys map[string][]string) (fclient.RespQueryKeys, error) {
t.queryKeysCalled = true t.queryKeysCalled = true
if t.shouldFail { if t.shouldFail {
return fclient.RespQueryKeys{}, fmt.Errorf("Failure") return fclient.RespQueryKeys{}, fmt.Errorf("Failure")
@ -42,7 +42,7 @@ func (t *testFedClient) QueryKeys(ctx context.Context, origin, s gomatrixserverl
return fclient.RespQueryKeys{}, nil return fclient.RespQueryKeys{}, nil
} }
func (t *testFedClient) ClaimKeys(ctx context.Context, origin, s gomatrixserverlib.ServerName, oneTimeKeys map[string]map[string]string) (fclient.RespClaimKeys, error) { func (t *testFedClient) ClaimKeys(ctx context.Context, origin, s spec.ServerName, oneTimeKeys map[string]map[string]string) (fclient.RespClaimKeys, error) {
t.claimKeysCalled = true t.claimKeysCalled = true
if t.shouldFail { if t.shouldFail {
return fclient.RespClaimKeys{}, fmt.Errorf("Failure") return fclient.RespClaimKeys{}, fmt.Errorf("Failure")

View File

@ -7,6 +7,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -31,14 +32,14 @@ func (s *FederationInternalAPI) StoreKeys(
func (s *FederationInternalAPI) FetchKeys( func (s *FederationInternalAPI) FetchKeys(
_ context.Context, _ context.Context,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) { ) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
// Run in a background context - we don't want to stop this work just // Run in a background context - we don't want to stop this work just
// because the caller gives up waiting. // because the caller gives up waiting.
ctx := context.Background() ctx := context.Background()
now := gomatrixserverlib.AsTimestamp(time.Now()) now := spec.AsTimestamp(time.Now())
results := map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult{} results := map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult{}
origRequests := map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{} origRequests := map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp{}
for k, v := range requests { for k, v := range requests {
origRequests[k] = v origRequests[k] = v
} }
@ -95,7 +96,7 @@ func (s *FederationInternalAPI) FetcherName() string {
// a request for our own server keys, either current or old. // a request for our own server keys, either current or old.
func (s *FederationInternalAPI) handleLocalKeys( func (s *FederationInternalAPI) handleLocalKeys(
_ context.Context, _ context.Context,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult,
) { ) {
for req := range requests { for req := range requests {
@ -111,10 +112,10 @@ func (s *FederationInternalAPI) handleLocalKeys(
// Insert our own key into the response. // Insert our own key into the response.
results[req] = gomatrixserverlib.PublicKeyLookupResult{ results[req] = gomatrixserverlib.PublicKeyLookupResult{
VerifyKey: gomatrixserverlib.VerifyKey{ VerifyKey: gomatrixserverlib.VerifyKey{
Key: gomatrixserverlib.Base64Bytes(s.cfg.Matrix.PrivateKey.Public().(ed25519.PublicKey)), Key: spec.Base64Bytes(s.cfg.Matrix.PrivateKey.Public().(ed25519.PublicKey)),
}, },
ExpiredTS: gomatrixserverlib.PublicKeyNotExpired, ExpiredTS: gomatrixserverlib.PublicKeyNotExpired,
ValidUntilTS: gomatrixserverlib.AsTimestamp(time.Now().Add(s.cfg.Matrix.KeyValidityPeriod)), ValidUntilTS: spec.AsTimestamp(time.Now().Add(s.cfg.Matrix.KeyValidityPeriod)),
} }
} else { } else {
// The key request doesn't match our current key. Let's see // The key request doesn't match our current key. Let's see
@ -128,7 +129,7 @@ func (s *FederationInternalAPI) handleLocalKeys(
// Insert our own key into the response. // Insert our own key into the response.
results[req] = gomatrixserverlib.PublicKeyLookupResult{ results[req] = gomatrixserverlib.PublicKeyLookupResult{
VerifyKey: gomatrixserverlib.VerifyKey{ VerifyKey: gomatrixserverlib.VerifyKey{
Key: gomatrixserverlib.Base64Bytes(oldVerifyKey.PrivateKey.Public().(ed25519.PublicKey)), Key: spec.Base64Bytes(oldVerifyKey.PrivateKey.Public().(ed25519.PublicKey)),
}, },
ExpiredTS: oldVerifyKey.ExpiredAt, ExpiredTS: oldVerifyKey.ExpiredAt,
ValidUntilTS: gomatrixserverlib.PublicKeyNotValid, ValidUntilTS: gomatrixserverlib.PublicKeyNotValid,
@ -146,8 +147,8 @@ func (s *FederationInternalAPI) handleLocalKeys(
// satisfied from our local database/cache. // satisfied from our local database/cache.
func (s *FederationInternalAPI) handleDatabaseKeys( func (s *FederationInternalAPI) handleDatabaseKeys(
ctx context.Context, ctx context.Context,
now gomatrixserverlib.Timestamp, now spec.Timestamp,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult,
) error { ) error {
// Ask the database/cache for the keys. // Ask the database/cache for the keys.
@ -180,9 +181,9 @@ func (s *FederationInternalAPI) handleDatabaseKeys(
// the remaining requests. // the remaining requests.
func (s *FederationInternalAPI) handleFetcherKeys( func (s *FederationInternalAPI) handleFetcherKeys(
ctx context.Context, ctx context.Context,
_ gomatrixserverlib.Timestamp, _ spec.Timestamp,
fetcher gomatrixserverlib.KeyFetcher, fetcher gomatrixserverlib.KeyFetcher,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, results map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult,
) error { ) error {
logrus.WithFields(logrus.Fields{ logrus.WithFields(logrus.Fields{

View File

@ -10,6 +10,7 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -81,8 +82,8 @@ func (r *FederationInternalAPI) PerformJoin(
// Deduplicate the server names we were provided but keep the ordering // Deduplicate the server names we were provided but keep the ordering
// as this encodes useful information about which servers are most likely // as this encodes useful information about which servers are most likely
// to respond. // to respond.
seenSet := make(map[gomatrixserverlib.ServerName]bool) seenSet := make(map[spec.ServerName]bool)
var uniqueList []gomatrixserverlib.ServerName var uniqueList []spec.ServerName
for _, srv := range request.ServerNames { for _, srv := range request.ServerNames {
if seenSet[srv] || r.cfg.Matrix.IsLocalServerName(srv) { if seenSet[srv] || r.cfg.Matrix.IsLocalServerName(srv) {
continue continue
@ -144,7 +145,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
ctx context.Context, ctx context.Context,
roomID, userID string, roomID, userID string,
content map[string]interface{}, content map[string]interface{},
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
supportedVersions []gomatrixserverlib.RoomVersion, supportedVersions []gomatrixserverlib.RoomVersion,
unsigned map[string]interface{}, unsigned map[string]interface{},
) error { ) error {
@ -176,7 +177,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
// Set all the fields to be what they should be, this should be a no-op // Set all the fields to be what they should be, this should be a no-op
// but it's possible that the remote server returned us something "odd" // but it's possible that the remote server returned us something "odd"
respMakeJoin.JoinEvent.Type = gomatrixserverlib.MRoomMember respMakeJoin.JoinEvent.Type = spec.MRoomMember
respMakeJoin.JoinEvent.Sender = userID respMakeJoin.JoinEvent.Sender = userID
respMakeJoin.JoinEvent.StateKey = &userID respMakeJoin.JoinEvent.StateKey = &userID
respMakeJoin.JoinEvent.RoomID = roomID respMakeJoin.JoinEvent.RoomID = roomID
@ -185,7 +186,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
content = map[string]interface{}{} content = map[string]interface{}{}
} }
_ = json.Unmarshal(respMakeJoin.JoinEvent.Content, &content) _ = json.Unmarshal(respMakeJoin.JoinEvent.Content, &content)
content["membership"] = gomatrixserverlib.Join content["membership"] = spec.Join
if err = respMakeJoin.JoinEvent.SetContent(content); err != nil { if err = respMakeJoin.JoinEvent.SetContent(content); err != nil {
return fmt.Errorf("respMakeJoin.JoinEvent.SetContent: %w", err) return fmt.Errorf("respMakeJoin.JoinEvent.SetContent: %w", err)
} }
@ -234,7 +235,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
// contain signatures that we don't know about. // contain signatures that we don't know about.
if len(respSendJoin.Event) > 0 { if len(respSendJoin.Event) > 0 {
var remoteEvent *gomatrixserverlib.Event var remoteEvent *gomatrixserverlib.Event
remoteEvent, err = respSendJoin.Event.UntrustedEvent(respMakeJoin.RoomVersion) remoteEvent, err = gomatrixserverlib.UntrustedEvent(respSendJoin.Event, respMakeJoin.RoomVersion)
if err == nil && isWellFormedMembershipEvent( if err == nil && isWellFormedMembershipEvent(
remoteEvent, roomID, userID, remoteEvent, roomID, userID,
) { ) {
@ -316,7 +317,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
func isWellFormedMembershipEvent(event *gomatrixserverlib.Event, roomID, userID string) bool { func isWellFormedMembershipEvent(event *gomatrixserverlib.Event, roomID, userID string) bool {
if membership, err := event.Membership(); err != nil { if membership, err := event.Membership(); err != nil {
return false return false
} else if membership != gomatrixserverlib.Join { } else if membership != spec.Join {
return false return false
} }
if event.RoomID() != roomID { if event.RoomID() != roomID {
@ -343,8 +344,8 @@ func (r *FederationInternalAPI) PerformOutboundPeek(
// Deduplicate the server names we were provided but keep the ordering // Deduplicate the server names we were provided but keep the ordering
// as this encodes useful information about which servers are most likely // as this encodes useful information about which servers are most likely
// to respond. // to respond.
seenSet := make(map[gomatrixserverlib.ServerName]bool) seenSet := make(map[spec.ServerName]bool)
var uniqueList []gomatrixserverlib.ServerName var uniqueList []spec.ServerName
for _, srv := range request.ServerNames { for _, srv := range request.ServerNames {
if seenSet[srv] { if seenSet[srv] {
continue continue
@ -410,7 +411,7 @@ func (r *FederationInternalAPI) PerformOutboundPeek(
func (r *FederationInternalAPI) performOutboundPeekUsingServer( func (r *FederationInternalAPI) performOutboundPeekUsingServer(
ctx context.Context, ctx context.Context,
roomID string, roomID string,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
supportedVersions []gomatrixserverlib.RoomVersion, supportedVersions []gomatrixserverlib.RoomVersion,
) error { ) error {
if !r.shouldAttemptDirectFederation(serverName) { if !r.shouldAttemptDirectFederation(serverName) {
@ -553,7 +554,7 @@ func (r *FederationInternalAPI) PerformLeave(
// Set all the fields to be what they should be, this should be a no-op // Set all the fields to be what they should be, this should be a no-op
// but it's possible that the remote server returned us something "odd" // but it's possible that the remote server returned us something "odd"
respMakeLeave.LeaveEvent.Type = gomatrixserverlib.MRoomMember respMakeLeave.LeaveEvent.Type = spec.MRoomMember
respMakeLeave.LeaveEvent.Sender = request.UserID respMakeLeave.LeaveEvent.Sender = request.UserID
respMakeLeave.LeaveEvent.StateKey = &request.UserID respMakeLeave.LeaveEvent.StateKey = &request.UserID
respMakeLeave.LeaveEvent.RoomID = request.RoomID respMakeLeave.LeaveEvent.RoomID = request.RoomID
@ -649,7 +650,7 @@ func (r *FederationInternalAPI) PerformInvite(
"destination": destination, "destination": destination,
}).Info("Sending invite") }).Info("Sending invite")
inviteReq, err := gomatrixserverlib.NewInviteV2Request(request.Event, request.InviteRoomState) inviteReq, err := fclient.NewInviteV2Request(request.Event, request.InviteRoomState)
if err != nil { if err != nil {
return fmt.Errorf("gomatrixserverlib.NewInviteV2Request: %w", err) return fmt.Errorf("gomatrixserverlib.NewInviteV2Request: %w", err)
} }
@ -659,7 +660,7 @@ func (r *FederationInternalAPI) PerformInvite(
return fmt.Errorf("r.federation.SendInviteV2: failed to send invite: %w", err) return fmt.Errorf("r.federation.SendInviteV2: failed to send invite: %w", err)
} }
inviteEvent, err := inviteRes.Event.UntrustedEvent(request.RoomVersion) inviteEvent, err := gomatrixserverlib.UntrustedEvent(inviteRes.Event, request.RoomVersion)
if err != nil { if err != nil {
return fmt.Errorf("r.federation.SendInviteV2 failed to decode event response: %w", err) return fmt.Errorf("r.federation.SendInviteV2 failed to decode event response: %w", err)
} }
@ -705,7 +706,7 @@ func (r *FederationInternalAPI) PerformWakeupServers(
return nil return nil
} }
func (r *FederationInternalAPI) MarkServersAlive(destinations []gomatrixserverlib.ServerName) { func (r *FederationInternalAPI) MarkServersAlive(destinations []spec.ServerName) {
for _, srv := range destinations { for _, srv := range destinations {
wasBlacklisted := r.statistics.ForServer(srv).MarkServerAlive() wasBlacklisted := r.statistics.ForServer(srv).MarkServerAlive()
r.queues.RetryServer(srv, wasBlacklisted) r.queues.RetryServer(srv, wasBlacklisted)
@ -715,7 +716,7 @@ func (r *FederationInternalAPI) MarkServersAlive(destinations []gomatrixserverli
func sanityCheckAuthChain(authChain []*gomatrixserverlib.Event) error { func sanityCheckAuthChain(authChain []*gomatrixserverlib.Event) error {
// sanity check we have a create event and it has a known room version // sanity check we have a create event and it has a known room version
for _, ev := range authChain { for _, ev := range authChain {
if ev.Type() == gomatrixserverlib.MRoomCreate && ev.StateKeyEquals("") { if ev.Type() == spec.MRoomCreate && ev.StateKeyEquals("") {
// make sure the room version is known // make sure the room version is known
content := ev.Content() content := ev.Content()
verBody := struct { verBody := struct {
@ -767,7 +768,7 @@ func setDefaultRoomVersionFromJoinEvent(
// FederatedAuthProvider is an auth chain provider which fetches events from the server provided // FederatedAuthProvider is an auth chain provider which fetches events from the server provided
func federatedAuthProvider( func federatedAuthProvider(
ctx context.Context, federation api.FederationClient, ctx context.Context, federation api.FederationClient,
keyRing gomatrixserverlib.JSONVerifier, origin, server gomatrixserverlib.ServerName, keyRing gomatrixserverlib.JSONVerifier, origin, server spec.ServerName,
) gomatrixserverlib.AuthChainProvider { ) gomatrixserverlib.AuthChainProvider {
// A list of events that we have retried, if they were not included in // A list of events that we have retried, if they were not included in
// the auth events supplied in the send_join. // the auth events supplied in the send_join.
@ -873,7 +874,7 @@ func (r *FederationInternalAPI) P2PRemoveRelayServers(
} }
func (r *FederationInternalAPI) shouldAttemptDirectFederation( func (r *FederationInternalAPI) shouldAttemptDirectFederation(
destination gomatrixserverlib.ServerName, destination spec.ServerName,
) bool { ) bool {
var shouldRelay bool var shouldRelay bool
stats := r.statistics.ForServer(destination) stats := r.statistics.ForServer(destination)

View File

@ -24,8 +24,8 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/dendrite/setup/process"
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -36,14 +36,14 @@ type testFedClient struct {
shouldFail bool shouldFail bool
} }
func (t *testFedClient) LookupRoomAlias(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomAlias string) (res fclient.RespDirectory, err error) { func (t *testFedClient) LookupRoomAlias(ctx context.Context, origin, s spec.ServerName, roomAlias string) (res fclient.RespDirectory, err error) {
return fclient.RespDirectory{}, nil return fclient.RespDirectory{}, nil
} }
func TestPerformWakeupServers(t *testing.T) { func TestPerformWakeupServers(t *testing.T) {
testDB := test.NewInMemoryFederationDatabase() testDB := test.NewInMemoryFederationDatabase()
server := gomatrixserverlib.ServerName("wakeup") server := spec.ServerName("wakeup")
testDB.AddServerToBlacklist(server) testDB.AddServerToBlacklist(server)
testDB.SetServerAssumedOffline(context.Background(), server) testDB.SetServerAssumedOffline(context.Background(), server)
blacklisted, err := testDB.IsServerBlacklisted(server) blacklisted, err := testDB.IsServerBlacklisted(server)
@ -73,7 +73,7 @@ func TestPerformWakeupServers(t *testing.T) {
) )
req := api.PerformWakeupServersRequest{ req := api.PerformWakeupServersRequest{
ServerNames: []gomatrixserverlib.ServerName{server}, ServerNames: []spec.ServerName{server},
} }
res := api.PerformWakeupServersResponse{} res := api.PerformWakeupServersResponse{}
err = fedAPI.PerformWakeupServers(context.Background(), &req, &res) err = fedAPI.PerformWakeupServers(context.Background(), &req, &res)
@ -90,8 +90,8 @@ func TestPerformWakeupServers(t *testing.T) {
func TestQueryRelayServers(t *testing.T) { func TestQueryRelayServers(t *testing.T) {
testDB := test.NewInMemoryFederationDatabase() testDB := test.NewInMemoryFederationDatabase()
server := gomatrixserverlib.ServerName("wakeup") server := spec.ServerName("wakeup")
relayServers := []gomatrixserverlib.ServerName{"relay1", "relay2"} relayServers := []spec.ServerName{"relay1", "relay2"}
err := testDB.P2PAddRelayServersForServer(context.Background(), server, relayServers) err := testDB.P2PAddRelayServersForServer(context.Background(), server, relayServers)
assert.NoError(t, err) assert.NoError(t, err)
@ -127,8 +127,8 @@ func TestQueryRelayServers(t *testing.T) {
func TestRemoveRelayServers(t *testing.T) { func TestRemoveRelayServers(t *testing.T) {
testDB := test.NewInMemoryFederationDatabase() testDB := test.NewInMemoryFederationDatabase()
server := gomatrixserverlib.ServerName("wakeup") server := spec.ServerName("wakeup")
relayServers := []gomatrixserverlib.ServerName{"relay1", "relay2"} relayServers := []spec.ServerName{"relay1", "relay2"}
err := testDB.P2PAddRelayServersForServer(context.Background(), server, relayServers) err := testDB.P2PAddRelayServersForServer(context.Background(), server, relayServers)
assert.NoError(t, err) assert.NoError(t, err)
@ -153,7 +153,7 @@ func TestRemoveRelayServers(t *testing.T) {
req := api.P2PRemoveRelayServersRequest{ req := api.P2PRemoveRelayServersRequest{
Server: server, Server: server,
RelayServers: []gomatrixserverlib.ServerName{"relay1"}, RelayServers: []spec.ServerName{"relay1"},
} }
res := api.P2PRemoveRelayServersResponse{} res := api.P2PRemoveRelayServersResponse{}
err = fedAPI.P2PRemoveRelayServers(context.Background(), &req, &res) err = fedAPI.P2PRemoveRelayServers(context.Background(), &req, &res)
@ -162,7 +162,7 @@ func TestRemoveRelayServers(t *testing.T) {
finalRelays, err := testDB.P2PGetRelayServersForServer(context.Background(), server) finalRelays, err := testDB.P2PGetRelayServersForServer(context.Background(), server)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, 1, len(finalRelays)) assert.Equal(t, 1, len(finalRelays))
assert.Equal(t, gomatrixserverlib.ServerName("relay2"), finalRelays[0]) assert.Equal(t, spec.ServerName("relay2"), finalRelays[0])
} }
func TestPerformDirectoryLookup(t *testing.T) { func TestPerformDirectoryLookup(t *testing.T) {
@ -199,9 +199,9 @@ func TestPerformDirectoryLookup(t *testing.T) {
func TestPerformDirectoryLookupRelaying(t *testing.T) { func TestPerformDirectoryLookupRelaying(t *testing.T) {
testDB := test.NewInMemoryFederationDatabase() testDB := test.NewInMemoryFederationDatabase()
server := gomatrixserverlib.ServerName("wakeup") server := spec.ServerName("wakeup")
testDB.SetServerAssumedOffline(context.Background(), server) testDB.SetServerAssumedOffline(context.Background(), server)
testDB.P2PAddRelayServersForServer(context.Background(), server, []gomatrixserverlib.ServerName{"relay"}) testDB.P2PAddRelayServersForServer(context.Background(), server, []spec.ServerName{"relay"})
cfg := config.FederationAPI{ cfg := config.FederationAPI{
Matrix: &config.Global{ Matrix: &config.Global{

View File

@ -7,6 +7,7 @@ import (
"github.com/matrix-org/dendrite/federationapi/api" "github.com/matrix-org/dendrite/federationapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -25,7 +26,7 @@ func (f *FederationInternalAPI) QueryJoinedHostServerNamesInRoom(
return return
} }
func (a *FederationInternalAPI) fetchServerKeysDirectly(ctx context.Context, serverName gomatrixserverlib.ServerName) (*gomatrixserverlib.ServerKeys, error) { func (a *FederationInternalAPI) fetchServerKeysDirectly(ctx context.Context, serverName spec.ServerName) (*gomatrixserverlib.ServerKeys, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second*30) ctx, cancel := context.WithTimeout(ctx, time.Second*30)
defer cancel() defer cancel()
ires, err := a.doRequestIfNotBackingOffOrBlacklisted(serverName, func() (interface{}, error) { ires, err := a.doRequestIfNotBackingOffOrBlacklisted(serverName, func() (interface{}, error) {

View File

@ -22,6 +22,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/nats-io/nats.go" "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -46,7 +47,7 @@ type SyncAPIProducer struct {
func (p *SyncAPIProducer) SendReceipt( func (p *SyncAPIProducer) SendReceipt(
ctx context.Context, ctx context.Context,
userID, roomID, eventID, receiptType string, timestamp gomatrixserverlib.Timestamp, userID, roomID, eventID, receiptType string, timestamp spec.Timestamp,
) error { ) error {
m := &nats.Msg{ m := &nats.Msg{
Subject: p.TopicReceiptEvent, Subject: p.TopicReceiptEvent,
@ -155,7 +156,7 @@ func (p *SyncAPIProducer) SendPresence(
if statusMsg != nil { if statusMsg != nil {
m.Header.Set("status_msg", *statusMsg) m.Header.Set("status_msg", *statusMsg)
} }
lastActiveTS := gomatrixserverlib.AsTimestamp(time.Now().Add(-(time.Duration(lastActiveAgo) * time.Millisecond))) lastActiveTS := spec.AsTimestamp(time.Now().Add(-(time.Duration(lastActiveAgo) * time.Millisecond)))
m.Header.Set("last_active_ts", strconv.Itoa(int(lastActiveTS))) m.Header.Set("last_active_ts", strconv.Itoa(int(lastActiveTS)))
log.Tracef("Sending presence to syncAPI: %+v", m.Header) log.Tracef("Sending presence to syncAPI: %+v", m.Header)
@ -164,7 +165,7 @@ func (p *SyncAPIProducer) SendPresence(
} }
func (p *SyncAPIProducer) SendDeviceListUpdate( func (p *SyncAPIProducer) SendDeviceListUpdate(
ctx context.Context, deviceListUpdate gomatrixserverlib.RawJSON, origin gomatrixserverlib.ServerName, ctx context.Context, deviceListUpdate spec.RawJSON, origin spec.ServerName,
) (err error) { ) (err error) {
m := nats.NewMsg(p.TopicDeviceListUpdate) m := nats.NewMsg(p.TopicDeviceListUpdate)
m.Header.Set("origin", string(origin)) m.Header.Set("origin", string(origin))
@ -175,7 +176,7 @@ func (p *SyncAPIProducer) SendDeviceListUpdate(
} }
func (p *SyncAPIProducer) SendSigningKeyUpdate( func (p *SyncAPIProducer) SendSigningKeyUpdate(
ctx context.Context, data gomatrixserverlib.RawJSON, origin gomatrixserverlib.ServerName, ctx context.Context, data spec.RawJSON, origin spec.ServerName,
) (err error) { ) (err error) {
m := nats.NewMsg(p.TopicSigningKeyUpdate) m := nats.NewMsg(p.TopicSigningKeyUpdate)
m.Header.Set("origin", string(origin)) m.Header.Set("origin", string(origin))

View File

@ -24,6 +24,7 @@ import (
"github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrix"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.uber.org/atomic" "go.uber.org/atomic"
@ -51,11 +52,11 @@ type destinationQueue struct {
queues *OutgoingQueues queues *OutgoingQueues
db storage.Database db storage.Database
process *process.ProcessContext process *process.ProcessContext
signing map[gomatrixserverlib.ServerName]*fclient.SigningIdentity signing map[spec.ServerName]*fclient.SigningIdentity
rsAPI api.FederationRoomserverAPI rsAPI api.FederationRoomserverAPI
client fedapi.FederationClient // federation client client fedapi.FederationClient // federation client
origin gomatrixserverlib.ServerName // origin of requests origin spec.ServerName // origin of requests
destination gomatrixserverlib.ServerName // destination of requests destination spec.ServerName // destination of requests
running atomic.Bool // is the queue worker running? running atomic.Bool // is the queue worker running?
backingOff atomic.Bool // true if we're backing off backingOff atomic.Bool // true if we're backing off
overflowed atomic.Bool // the queues exceed maxPDUsInMemory/maxEDUsInMemory, so we should consult the database for more overflowed atomic.Bool // the queues exceed maxPDUsInMemory/maxEDUsInMemory, so we should consult the database for more
@ -426,7 +427,7 @@ func (oq *destinationQueue) nextTransaction(
relaySuccess := false relaySuccess := false
logrus.Infof("Sending %q to relay servers: %v", t.TransactionID, relayServers) logrus.Infof("Sending %q to relay servers: %v", t.TransactionID, relayServers)
// TODO : how to pass through actual userID here?!?!?!?! // TODO : how to pass through actual userID here?!?!?!?!
userID, userErr := gomatrixserverlib.NewUserID("@user:"+string(oq.destination), false) userID, userErr := spec.NewUserID("@user:"+string(oq.destination), false)
if userErr != nil { if userErr != nil {
return userErr, sendMethod return userErr, sendMethod
} }
@ -507,7 +508,7 @@ func (oq *destinationQueue) createTransaction(
// it so that we retry with the same transaction ID. // it so that we retry with the same transaction ID.
oq.transactionIDMutex.Lock() oq.transactionIDMutex.Lock()
if oq.transactionID == "" { if oq.transactionID == "" {
now := gomatrixserverlib.AsTimestamp(time.Now()) now := spec.AsTimestamp(time.Now())
oq.transactionID = gomatrixserverlib.TransactionID(fmt.Sprintf("%d-%d", now, oq.statistics.SuccessCount())) oq.transactionID = gomatrixserverlib.TransactionID(fmt.Sprintf("%d-%d", now, oq.statistics.SuccessCount()))
} }
oq.transactionIDMutex.Unlock() oq.transactionIDMutex.Unlock()
@ -518,7 +519,7 @@ func (oq *destinationQueue) createTransaction(
} }
t.Origin = oq.origin t.Origin = oq.origin
t.Destination = oq.destination t.Destination = oq.destination
t.OriginServerTS = gomatrixserverlib.AsTimestamp(time.Now()) t.OriginServerTS = spec.AsTimestamp(time.Now())
t.TransactionID = oq.transactionID t.TransactionID = oq.transactionID
var pduReceipts []*receipt.Receipt var pduReceipts []*receipt.Receipt

View File

@ -23,6 +23,7 @@ import (
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -43,12 +44,12 @@ type OutgoingQueues struct {
process *process.ProcessContext process *process.ProcessContext
disabled bool disabled bool
rsAPI api.FederationRoomserverAPI rsAPI api.FederationRoomserverAPI
origin gomatrixserverlib.ServerName origin spec.ServerName
client fedapi.FederationClient client fedapi.FederationClient
statistics *statistics.Statistics statistics *statistics.Statistics
signing map[gomatrixserverlib.ServerName]*fclient.SigningIdentity signing map[spec.ServerName]*fclient.SigningIdentity
queuesMutex sync.Mutex // protects the below queuesMutex sync.Mutex // protects the below
queues map[gomatrixserverlib.ServerName]*destinationQueue queues map[spec.ServerName]*destinationQueue
} }
func init() { func init() {
@ -87,7 +88,7 @@ func NewOutgoingQueues(
db storage.Database, db storage.Database,
process *process.ProcessContext, process *process.ProcessContext,
disabled bool, disabled bool,
origin gomatrixserverlib.ServerName, origin spec.ServerName,
client fedapi.FederationClient, client fedapi.FederationClient,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
statistics *statistics.Statistics, statistics *statistics.Statistics,
@ -101,15 +102,15 @@ func NewOutgoingQueues(
origin: origin, origin: origin,
client: client, client: client,
statistics: statistics, statistics: statistics,
signing: map[gomatrixserverlib.ServerName]*fclient.SigningIdentity{}, signing: map[spec.ServerName]*fclient.SigningIdentity{},
queues: map[gomatrixserverlib.ServerName]*destinationQueue{}, queues: map[spec.ServerName]*destinationQueue{},
} }
for _, identity := range signing { for _, identity := range signing {
queues.signing[identity.ServerName] = identity queues.signing[identity.ServerName] = identity
} }
// Look up which servers we have pending items for and then rehydrate those queues. // Look up which servers we have pending items for and then rehydrate those queues.
if !disabled { if !disabled {
serverNames := map[gomatrixserverlib.ServerName]struct{}{} serverNames := map[spec.ServerName]struct{}{}
if names, err := db.GetPendingPDUServerNames(process.Context()); err == nil { if names, err := db.GetPendingPDUServerNames(process.Context()); err == nil {
for _, serverName := range names { for _, serverName := range names {
serverNames[serverName] = struct{}{} serverNames[serverName] = struct{}{}
@ -148,7 +149,7 @@ type queuedEDU struct {
edu *gomatrixserverlib.EDU edu *gomatrixserverlib.EDU
} }
func (oqs *OutgoingQueues) getQueue(destination gomatrixserverlib.ServerName) *destinationQueue { func (oqs *OutgoingQueues) getQueue(destination spec.ServerName) *destinationQueue {
if oqs.statistics.ForServer(destination).Blacklisted() { if oqs.statistics.ForServer(destination).Blacklisted() {
return nil return nil
} }
@ -187,8 +188,8 @@ func (oqs *OutgoingQueues) clearQueue(oq *destinationQueue) {
// SendEvent sends an event to the destinations // SendEvent sends an event to the destinations
func (oqs *OutgoingQueues) SendEvent( func (oqs *OutgoingQueues) SendEvent(
ev *gomatrixserverlib.HeaderedEvent, origin gomatrixserverlib.ServerName, ev *gomatrixserverlib.HeaderedEvent, origin spec.ServerName,
destinations []gomatrixserverlib.ServerName, destinations []spec.ServerName,
) error { ) error {
if oqs.disabled { if oqs.disabled {
log.Trace("Federation is disabled, not sending event") log.Trace("Federation is disabled, not sending event")
@ -203,7 +204,7 @@ func (oqs *OutgoingQueues) SendEvent(
// Deduplicate destinations and remove the origin from the list of // Deduplicate destinations and remove the origin from the list of
// destinations just to be sure. // destinations just to be sure.
destmap := map[gomatrixserverlib.ServerName]struct{}{} destmap := map[spec.ServerName]struct{}{}
for _, d := range destinations { for _, d := range destinations {
destmap[d] = struct{}{} destmap[d] = struct{}{}
} }
@ -277,8 +278,8 @@ func (oqs *OutgoingQueues) SendEvent(
// SendEDU sends an EDU event to the destinations. // SendEDU sends an EDU event to the destinations.
func (oqs *OutgoingQueues) SendEDU( func (oqs *OutgoingQueues) SendEDU(
e *gomatrixserverlib.EDU, origin gomatrixserverlib.ServerName, e *gomatrixserverlib.EDU, origin spec.ServerName,
destinations []gomatrixserverlib.ServerName, destinations []spec.ServerName,
) error { ) error {
if oqs.disabled { if oqs.disabled {
log.Trace("Federation is disabled, not sending EDU") log.Trace("Federation is disabled, not sending EDU")
@ -293,7 +294,7 @@ func (oqs *OutgoingQueues) SendEDU(
// Deduplicate destinations and remove the origin from the list of // Deduplicate destinations and remove the origin from the list of
// destinations just to be sure. // destinations just to be sure.
destmap := map[gomatrixserverlib.ServerName]struct{}{} destmap := map[spec.ServerName]struct{}{}
for _, d := range destinations { for _, d := range destinations {
destmap[d] = struct{}{} destmap[d] = struct{}{}
} }
@ -376,7 +377,7 @@ func (oqs *OutgoingQueues) SendEDU(
} }
// RetryServer attempts to resend events to the given server if we had given up. // RetryServer attempts to resend events to the given server if we had given up.
func (oqs *OutgoingQueues) RetryServer(srv gomatrixserverlib.ServerName, wasBlacklisted bool) { func (oqs *OutgoingQueues) RetryServer(srv spec.ServerName, wasBlacklisted bool) {
if oqs.disabled { if oqs.disabled {
return return
} }

View File

@ -25,6 +25,7 @@ import (
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"go.uber.org/atomic" "go.uber.org/atomic"
"gotest.tools/v3/poll" "gotest.tools/v3/poll"
@ -91,7 +92,7 @@ func (f *stubFederationClient) SendTransaction(ctx context.Context, t gomatrixse
return fclient.RespSend{}, result return fclient.RespSend{}, result
} }
func (f *stubFederationClient) P2PSendTransactionToRelay(ctx context.Context, u gomatrixserverlib.UserID, t gomatrixserverlib.Transaction, forwardingServer gomatrixserverlib.ServerName) (res fclient.EmptyResp, err error) { func (f *stubFederationClient) P2PSendTransactionToRelay(ctx context.Context, u spec.UserID, t gomatrixserverlib.Transaction, forwardingServer spec.ServerName) (res fclient.EmptyResp, err error) {
var result error var result error
if !f.shouldTxRelaySucceed { if !f.shouldTxRelaySucceed {
result = fmt.Errorf("relay transaction failed") result = fmt.Errorf("relay transaction failed")
@ -113,7 +114,7 @@ func mustCreatePDU(t *testing.T) *gomatrixserverlib.HeaderedEvent {
func mustCreateEDU(t *testing.T) *gomatrixserverlib.EDU { func mustCreateEDU(t *testing.T) *gomatrixserverlib.EDU {
t.Helper() t.Helper()
return &gomatrixserverlib.EDU{Type: gomatrixserverlib.MTyping} return &gomatrixserverlib.EDU{Type: spec.MTyping}
} }
func testSetup(failuresUntilBlacklist uint32, failuresUntilAssumedOffline uint32, shouldTxSucceed bool, shouldTxRelaySucceed bool, t *testing.T, dbType test.DBType, realDatabase bool) (storage.Database, *stubFederationClient, *OutgoingQueues, *process.ProcessContext, func()) { func testSetup(failuresUntilBlacklist uint32, failuresUntilAssumedOffline uint32, shouldTxSucceed bool, shouldTxRelaySucceed bool, t *testing.T, dbType test.DBType, realDatabase bool) (storage.Database, *stubFederationClient, *OutgoingQueues, *process.ProcessContext, func()) {
@ -143,7 +144,7 @@ func testSetup(failuresUntilBlacklist uint32, failuresUntilAssumedOffline uint32
func TestSendPDUOnSuccessRemovedFromDB(t *testing.T) { func TestSendPDUOnSuccessRemovedFromDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -152,7 +153,7 @@ func TestSendPDUOnSuccessRemovedFromDB(t *testing.T) {
}() }()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -172,7 +173,7 @@ func TestSendPDUOnSuccessRemovedFromDB(t *testing.T) {
func TestSendEDUOnSuccessRemovedFromDB(t *testing.T) { func TestSendEDUOnSuccessRemovedFromDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -181,7 +182,7 @@ func TestSendEDUOnSuccessRemovedFromDB(t *testing.T) {
}() }()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -201,7 +202,7 @@ func TestSendEDUOnSuccessRemovedFromDB(t *testing.T) {
func TestSendPDUOnFailStoredInDB(t *testing.T) { func TestSendPDUOnFailStoredInDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -210,7 +211,7 @@ func TestSendPDUOnFailStoredInDB(t *testing.T) {
}() }()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -231,7 +232,7 @@ func TestSendPDUOnFailStoredInDB(t *testing.T) {
func TestSendEDUOnFailStoredInDB(t *testing.T) { func TestSendEDUOnFailStoredInDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -240,7 +241,7 @@ func TestSendEDUOnFailStoredInDB(t *testing.T) {
}() }()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -261,7 +262,7 @@ func TestSendEDUOnFailStoredInDB(t *testing.T) {
func TestSendPDUAgainDoesntInterruptBackoff(t *testing.T) { func TestSendPDUAgainDoesntInterruptBackoff(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -270,7 +271,7 @@ func TestSendPDUAgainDoesntInterruptBackoff(t *testing.T) {
}() }()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -289,7 +290,7 @@ func TestSendPDUAgainDoesntInterruptBackoff(t *testing.T) {
fc.shouldTxSucceed = true fc.shouldTxSucceed = true
ev = mustCreatePDU(t) ev = mustCreatePDU(t)
err = queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err = queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
pollEnd := time.Now().Add(1 * time.Second) pollEnd := time.Now().Add(1 * time.Second)
@ -312,7 +313,7 @@ func TestSendPDUAgainDoesntInterruptBackoff(t *testing.T) {
func TestSendEDUAgainDoesntInterruptBackoff(t *testing.T) { func TestSendEDUAgainDoesntInterruptBackoff(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -321,7 +322,7 @@ func TestSendEDUAgainDoesntInterruptBackoff(t *testing.T) {
}() }()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -340,7 +341,7 @@ func TestSendEDUAgainDoesntInterruptBackoff(t *testing.T) {
fc.shouldTxSucceed = true fc.shouldTxSucceed = true
ev = mustCreateEDU(t) ev = mustCreateEDU(t)
err = queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err = queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
pollEnd := time.Now().Add(1 * time.Second) pollEnd := time.Now().Add(1 * time.Second)
@ -363,7 +364,7 @@ func TestSendEDUAgainDoesntInterruptBackoff(t *testing.T) {
func TestSendPDUMultipleFailuresBlacklisted(t *testing.T) { func TestSendPDUMultipleFailuresBlacklisted(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(2) failuresUntilBlacklist := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -372,7 +373,7 @@ func TestSendPDUMultipleFailuresBlacklisted(t *testing.T) {
}() }()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -395,7 +396,7 @@ func TestSendPDUMultipleFailuresBlacklisted(t *testing.T) {
func TestSendEDUMultipleFailuresBlacklisted(t *testing.T) { func TestSendEDUMultipleFailuresBlacklisted(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(2) failuresUntilBlacklist := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -404,7 +405,7 @@ func TestSendEDUMultipleFailuresBlacklisted(t *testing.T) {
}() }()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -427,7 +428,7 @@ func TestSendEDUMultipleFailuresBlacklisted(t *testing.T) {
func TestSendPDUBlacklistedWithPriorExternalFailure(t *testing.T) { func TestSendPDUBlacklistedWithPriorExternalFailure(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(2) failuresUntilBlacklist := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -438,7 +439,7 @@ func TestSendPDUBlacklistedWithPriorExternalFailure(t *testing.T) {
queues.statistics.ForServer(destination).Failure() queues.statistics.ForServer(destination).Failure()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -461,7 +462,7 @@ func TestSendPDUBlacklistedWithPriorExternalFailure(t *testing.T) {
func TestSendEDUBlacklistedWithPriorExternalFailure(t *testing.T) { func TestSendEDUBlacklistedWithPriorExternalFailure(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(2) failuresUntilBlacklist := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -472,7 +473,7 @@ func TestSendEDUBlacklistedWithPriorExternalFailure(t *testing.T) {
queues.statistics.ForServer(destination).Failure() queues.statistics.ForServer(destination).Failure()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -495,7 +496,7 @@ func TestSendEDUBlacklistedWithPriorExternalFailure(t *testing.T) {
func TestRetryServerSendsPDUSuccessfully(t *testing.T) { func TestRetryServerSendsPDUSuccessfully(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(1) failuresUntilBlacklist := uint32(1)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -507,7 +508,7 @@ func TestRetryServerSendsPDUSuccessfully(t *testing.T) {
// before it is blacklisted and deleted. // before it is blacklisted and deleted.
dest := queues.getQueue(destination) dest := queues.getQueue(destination)
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
checkBlacklisted := func(log poll.LogT) poll.Result { checkBlacklisted := func(log poll.LogT) poll.Result {
@ -546,7 +547,7 @@ func TestRetryServerSendsPDUSuccessfully(t *testing.T) {
func TestRetryServerSendsEDUSuccessfully(t *testing.T) { func TestRetryServerSendsEDUSuccessfully(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(1) failuresUntilBlacklist := uint32(1)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -558,7 +559,7 @@ func TestRetryServerSendsEDUSuccessfully(t *testing.T) {
// before it is blacklisted and deleted. // before it is blacklisted and deleted.
dest := queues.getQueue(destination) dest := queues.getQueue(destination)
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
checkBlacklisted := func(log poll.LogT) poll.Result { checkBlacklisted := func(log poll.LogT) poll.Result {
@ -597,7 +598,7 @@ func TestRetryServerSendsEDUSuccessfully(t *testing.T) {
func TestSendPDUBatches(t *testing.T) { func TestSendPDUBatches(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
// test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) { // test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) {
// db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true) // db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true)
@ -608,7 +609,7 @@ func TestSendPDUBatches(t *testing.T) {
<-pc.WaitForShutdown() <-pc.WaitForShutdown()
}() }()
destinations := map[gomatrixserverlib.ServerName]struct{}{destination: {}} destinations := map[spec.ServerName]struct{}{destination: {}}
// Populate database with > maxPDUsPerTransaction // Populate database with > maxPDUsPerTransaction
pduMultiplier := uint32(3) pduMultiplier := uint32(3)
for i := 0; i < maxPDUsPerTransaction*int(pduMultiplier); i++ { for i := 0; i < maxPDUsPerTransaction*int(pduMultiplier); i++ {
@ -620,7 +621,7 @@ func TestSendPDUBatches(t *testing.T) {
} }
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -641,7 +642,7 @@ func TestSendPDUBatches(t *testing.T) {
func TestSendEDUBatches(t *testing.T) { func TestSendEDUBatches(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
// test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) { // test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) {
// db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true) // db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true)
@ -652,7 +653,7 @@ func TestSendEDUBatches(t *testing.T) {
<-pc.WaitForShutdown() <-pc.WaitForShutdown()
}() }()
destinations := map[gomatrixserverlib.ServerName]struct{}{destination: {}} destinations := map[spec.ServerName]struct{}{destination: {}}
// Populate database with > maxEDUsPerTransaction // Populate database with > maxEDUsPerTransaction
eduMultiplier := uint32(3) eduMultiplier := uint32(3)
for i := 0; i < maxEDUsPerTransaction*int(eduMultiplier); i++ { for i := 0; i < maxEDUsPerTransaction*int(eduMultiplier); i++ {
@ -664,7 +665,7 @@ func TestSendEDUBatches(t *testing.T) {
} }
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -685,7 +686,7 @@ func TestSendEDUBatches(t *testing.T) {
func TestSendPDUAndEDUBatches(t *testing.T) { func TestSendPDUAndEDUBatches(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
// test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) { // test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) {
// db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true) // db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, true, t, dbType, true)
@ -696,7 +697,7 @@ func TestSendPDUAndEDUBatches(t *testing.T) {
<-pc.WaitForShutdown() <-pc.WaitForShutdown()
}() }()
destinations := map[gomatrixserverlib.ServerName]struct{}{destination: {}} destinations := map[spec.ServerName]struct{}{destination: {}}
// Populate database with > maxEDUsPerTransaction // Populate database with > maxEDUsPerTransaction
multiplier := uint32(3) multiplier := uint32(3)
for i := 0; i < maxPDUsPerTransaction*int(multiplier)+1; i++ { for i := 0; i < maxPDUsPerTransaction*int(multiplier)+1; i++ {
@ -716,7 +717,7 @@ func TestSendPDUAndEDUBatches(t *testing.T) {
} }
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -739,7 +740,7 @@ func TestSendPDUAndEDUBatches(t *testing.T) {
func TestExternalFailureBackoffDoesntStartQueue(t *testing.T) { func TestExternalFailureBackoffDoesntStartQueue(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, true, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -749,7 +750,7 @@ func TestExternalFailureBackoffDoesntStartQueue(t *testing.T) {
dest := queues.getQueue(destination) dest := queues.getQueue(destination)
queues.statistics.ForServer(destination).Failure() queues.statistics.ForServer(destination).Failure()
destinations := map[gomatrixserverlib.ServerName]struct{}{destination: {}} destinations := map[spec.ServerName]struct{}{destination: {}}
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
headeredJSON, _ := json.Marshal(ev) headeredJSON, _ := json.Marshal(ev)
nid, _ := db.StoreJSON(pc.Context(), string(headeredJSON)) nid, _ := db.StoreJSON(pc.Context(), string(headeredJSON))
@ -775,8 +776,8 @@ func TestQueueInteractsWithRealDatabasePDUAndEDU(t *testing.T) {
// NOTE : Only one test case against real databases can be run at a time. // NOTE : Only one test case against real databases can be run at a time.
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(1) failuresUntilBlacklist := uint32(1)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
destinations := map[gomatrixserverlib.ServerName]struct{}{destination: {}} destinations := map[spec.ServerName]struct{}{destination: {}}
test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) { test.WithAllDatabases(t, func(t *testing.T, dbType test.DBType) {
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, dbType, true) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilBlacklist+1, false, false, t, dbType, true)
// NOTE : These defers aren't called if go test is killed so the dbs may not get cleaned up. // NOTE : These defers aren't called if go test is killed so the dbs may not get cleaned up.
@ -790,7 +791,7 @@ func TestQueueInteractsWithRealDatabasePDUAndEDU(t *testing.T) {
// before it is blacklisted and deleted. // before it is blacklisted and deleted.
dest := queues.getQueue(destination) dest := queues.getQueue(destination)
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
// NOTE : The server can be blacklisted before this, so manually inject the event // NOTE : The server can be blacklisted before this, so manually inject the event
@ -843,7 +844,7 @@ func TestSendPDUMultipleFailuresAssumedOffline(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(7) failuresUntilBlacklist := uint32(7)
failuresUntilAssumedOffline := uint32(2) failuresUntilAssumedOffline := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -852,7 +853,7 @@ func TestSendPDUMultipleFailuresAssumedOffline(t *testing.T) {
}() }()
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -876,7 +877,7 @@ func TestSendEDUMultipleFailuresAssumedOffline(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(7) failuresUntilBlacklist := uint32(7)
failuresUntilAssumedOffline := uint32(2) failuresUntilAssumedOffline := uint32(2)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, false, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, false, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -885,7 +886,7 @@ func TestSendEDUMultipleFailuresAssumedOffline(t *testing.T) {
}() }()
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -909,7 +910,7 @@ func TestSendPDUOnRelaySuccessRemovedFromDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
failuresUntilAssumedOffline := uint32(1) failuresUntilAssumedOffline := uint32(1)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, true, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, true, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -917,11 +918,11 @@ func TestSendPDUOnRelaySuccessRemovedFromDB(t *testing.T) {
<-pc.WaitForShutdown() <-pc.WaitForShutdown()
}() }()
relayServers := []gomatrixserverlib.ServerName{"relayserver"} relayServers := []spec.ServerName{"relayserver"}
queues.statistics.ForServer(destination).AddRelayServers(relayServers) queues.statistics.ForServer(destination).AddRelayServers(relayServers)
ev := mustCreatePDU(t) ev := mustCreatePDU(t)
err := queues.SendEvent(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEvent(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {
@ -948,7 +949,7 @@ func TestSendEDUOnRelaySuccessRemovedFromDB(t *testing.T) {
t.Parallel() t.Parallel()
failuresUntilBlacklist := uint32(16) failuresUntilBlacklist := uint32(16)
failuresUntilAssumedOffline := uint32(1) failuresUntilAssumedOffline := uint32(1)
destination := gomatrixserverlib.ServerName("remotehost") destination := spec.ServerName("remotehost")
db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, true, t, test.DBTypeSQLite, false) db, fc, queues, pc, close := testSetup(failuresUntilBlacklist, failuresUntilAssumedOffline, false, true, t, test.DBTypeSQLite, false)
defer close() defer close()
defer func() { defer func() {
@ -956,11 +957,11 @@ func TestSendEDUOnRelaySuccessRemovedFromDB(t *testing.T) {
<-pc.WaitForShutdown() <-pc.WaitForShutdown()
}() }()
relayServers := []gomatrixserverlib.ServerName{"relayserver"} relayServers := []spec.ServerName{"relayserver"}
queues.statistics.ForServer(destination).AddRelayServers(relayServers) queues.statistics.ForServer(destination).AddRelayServers(relayServers)
ev := mustCreateEDU(t) ev := mustCreateEDU(t)
err := queues.SendEDU(ev, "localhost", []gomatrixserverlib.ServerName{destination}) err := queues.SendEDU(ev, "localhost", []spec.ServerName{destination})
assert.NoError(t, err) assert.NoError(t, err)
check := func(log poll.LogT) poll.Result { check := func(log poll.LogT) poll.Result {

View File

@ -25,6 +25,8 @@ import (
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
) )
@ -32,7 +34,7 @@ import (
// https://matrix.org/docs/spec/server_server/unstable.html#get-matrix-federation-v1-backfill-roomid // https://matrix.org/docs/spec/server_server/unstable.html#get-matrix-federation-v1-backfill-roomid
func Backfill( func Backfill(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
cfg *config.FederationAPI, cfg *config.FederationAPI,
@ -126,7 +128,7 @@ func Backfill(
txn := gomatrixserverlib.Transaction{ txn := gomatrixserverlib.Transaction{
Origin: request.Destination(), Origin: request.Destination(),
PDUs: eventJSONs, PDUs: eventJSONs,
OriginServerTS: gomatrixserverlib.AsTimestamp(time.Now()), OriginServerTS: spec.AsTimestamp(time.Now()),
} }
// Send the events to the client. // Send the events to the client.

View File

@ -20,6 +20,7 @@ import (
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )
@ -91,10 +92,10 @@ func GetUserDevices(
for sourceUserID, forSourceUser := range targetKey { for sourceUserID, forSourceUser := range targetKey {
for sourceKeyID, sourceKey := range forSourceUser { for sourceKeyID, sourceKey := range forSourceUser {
if device.Keys.Signatures == nil { if device.Keys.Signatures == nil {
device.Keys.Signatures = map[string]map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{} device.Keys.Signatures = map[string]map[gomatrixserverlib.KeyID]spec.Base64Bytes{}
} }
if _, ok := device.Keys.Signatures[sourceUserID]; !ok { if _, ok := device.Keys.Signatures[sourceUserID]; !ok {
device.Keys.Signatures[sourceUserID] = map[gomatrixserverlib.KeyID]gomatrixserverlib.Base64Bytes{} device.Keys.Signatures[sourceUserID] = map[gomatrixserverlib.KeyID]spec.Base64Bytes{}
} }
device.Keys.Signatures[sourceUserID][sourceKeyID] = sourceKey device.Keys.Signatures[sourceUserID][sourceKeyID] = sourceKey
} }

View File

@ -26,7 +26,7 @@ import (
// GetEventAuth returns event auth for the roomID and eventID // GetEventAuth returns event auth for the roomID and eventID
func GetEventAuth( func GetEventAuth(
ctx context.Context, ctx context.Context,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
eventID string, eventID string,

View File

@ -21,6 +21,8 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
@ -30,10 +32,10 @@ import (
// GetEvent returns the requested event // GetEvent returns the requested event
func GetEvent( func GetEvent(
ctx context.Context, ctx context.Context,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
eventID string, eventID string,
origin gomatrixserverlib.ServerName, origin spec.ServerName,
) util.JSONResponse { ) util.JSONResponse {
err := allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID) err := allowedToSeeEvent(ctx, request.Origin(), rsAPI, eventID)
if err != nil { if err != nil {
@ -48,7 +50,7 @@ func GetEvent(
return util.JSONResponse{Code: http.StatusOK, JSON: gomatrixserverlib.Transaction{ return util.JSONResponse{Code: http.StatusOK, JSON: gomatrixserverlib.Transaction{
Origin: origin, Origin: origin,
OriginServerTS: gomatrixserverlib.AsTimestamp(time.Now()), OriginServerTS: spec.AsTimestamp(time.Now()),
PDUs: []json.RawMessage{ PDUs: []json.RawMessage{
event.JSON(), event.JSON(),
}, },
@ -59,7 +61,7 @@ func GetEvent(
// otherwise it returns an error response which can be sent to the client. // otherwise it returns an error response which can be sent to the client.
func allowedToSeeEvent( func allowedToSeeEvent(
ctx context.Context, ctx context.Context,
origin gomatrixserverlib.ServerName, origin spec.ServerName,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
eventID string, eventID string,
) *util.JSONResponse { ) *util.JSONResponse {

View File

@ -32,14 +32,14 @@ import (
// InviteV2 implements /_matrix/federation/v2/invite/{roomID}/{eventID} // InviteV2 implements /_matrix/federation/v2/invite/{roomID}/{eventID}
func InviteV2( func InviteV2(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
roomID string, roomID string,
eventID string, eventID string,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
keys gomatrixserverlib.JSONVerifier, keys gomatrixserverlib.JSONVerifier,
) util.JSONResponse { ) util.JSONResponse {
inviteReq := gomatrixserverlib.InviteV2Request{} inviteReq := fclient.InviteV2Request{}
err := json.Unmarshal(request.Content(), &inviteReq) err := json.Unmarshal(request.Content(), &inviteReq)
switch e := err.(type) { switch e := err.(type) {
case gomatrixserverlib.UnsupportedRoomVersionError: case gomatrixserverlib.UnsupportedRoomVersionError:
@ -69,7 +69,7 @@ func InviteV2(
// InviteV1 implements /_matrix/federation/v1/invite/{roomID}/{eventID} // InviteV1 implements /_matrix/federation/v1/invite/{roomID}/{eventID}
func InviteV1( func InviteV1(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
roomID string, roomID string,
eventID string, eventID string,
cfg *config.FederationAPI, cfg *config.FederationAPI,
@ -92,7 +92,7 @@ func InviteV1(
JSON: jsonerror.NotJSON("The request body could not be decoded into an invite v1 request. " + err.Error()), JSON: jsonerror.NotJSON("The request body could not be decoded into an invite v1 request. " + err.Error()),
} }
} }
var strippedState []gomatrixserverlib.InviteV2StrippedState var strippedState []fclient.InviteV2StrippedState
if err := json.Unmarshal(event.Unsigned(), &strippedState); err != nil { if err := json.Unmarshal(event.Unsigned(), &strippedState); err != nil {
// just warn, they may not have added any. // just warn, they may not have added any.
util.GetLogger(httpReq.Context()).Warnf("failed to extract stripped state from invite event") util.GetLogger(httpReq.Context()).Warnf("failed to extract stripped state from invite event")
@ -107,7 +107,7 @@ func processInvite(
isInviteV2 bool, isInviteV2 bool,
event *gomatrixserverlib.Event, event *gomatrixserverlib.Event,
roomVer gomatrixserverlib.RoomVersion, roomVer gomatrixserverlib.RoomVersion,
strippedState []gomatrixserverlib.InviteV2StrippedState, strippedState []fclient.InviteV2StrippedState,
roomID string, roomID string,
eventID string, eventID string,
cfg *config.FederationAPI, cfg *config.FederationAPI,

View File

@ -23,6 +23,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -35,7 +36,7 @@ import (
// MakeJoin implements the /make_join API // MakeJoin implements the /make_join API
func MakeJoin( func MakeJoin(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID, userID string, roomID, userID string,
@ -124,7 +125,7 @@ func MakeJoin(
StateKey: &userID, StateKey: &userID,
} }
content := gomatrixserverlib.MemberContent{ content := gomatrixserverlib.MemberContent{
Membership: gomatrixserverlib.Join, Membership: spec.Join,
AuthorisedVia: authorisedVia, AuthorisedVia: authorisedVia,
} }
if err = builder.SetContent(content); err != nil { if err = builder.SetContent(content); err != nil {
@ -190,7 +191,7 @@ func MakeJoin(
// nolint:gocyclo // nolint:gocyclo
func SendJoin( func SendJoin(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
keys gomatrixserverlib.JSONVerifier, keys gomatrixserverlib.JSONVerifier,
@ -231,7 +232,7 @@ func SendJoin(
// Check that the sender belongs to the server that is sending us // Check that the sender belongs to the server that is sending us
// the request. By this point we've already asserted that the sender // the request. By this point we've already asserted that the sender
// and the state key are equal so we don't need to check both. // and the state key are equal so we don't need to check both.
var serverName gomatrixserverlib.ServerName var serverName spec.ServerName
if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil { if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -278,7 +279,7 @@ func SendJoin(
JSON: jsonerror.BadJSON("missing content.membership key"), JSON: jsonerror.BadJSON("missing content.membership key"),
} }
} }
if membership != gomatrixserverlib.Join { if membership != spec.Join {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("membership must be 'join'"), JSON: jsonerror.BadJSON("membership must be 'join'"),
@ -349,8 +350,8 @@ func SendJoin(
continue continue
} }
if membership, merr := se.Membership(); merr == nil { if membership, merr := se.Membership(); merr == nil {
alreadyJoined = (membership == gomatrixserverlib.Join) alreadyJoined = (membership == spec.Join)
isBanned = (membership == gomatrixserverlib.Ban) isBanned = (membership == spec.Ban)
break break
} }
} }

View File

@ -26,6 +26,7 @@ import (
"github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"golang.org/x/crypto/ed25519" "golang.org/x/crypto/ed25519"
@ -38,7 +39,7 @@ type queryKeysRequest struct {
// QueryDeviceKeys returns device keys for users on this server. // QueryDeviceKeys returns device keys for users on this server.
// https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-query // https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-query
func QueryDeviceKeys( func QueryDeviceKeys(
httpReq *http.Request, request *gomatrixserverlib.FederationRequest, keyAPI api.FederationKeyAPI, thisServer gomatrixserverlib.ServerName, httpReq *http.Request, request *fclient.FederationRequest, keyAPI api.FederationKeyAPI, thisServer spec.ServerName,
) util.JSONResponse { ) util.JSONResponse {
var qkr queryKeysRequest var qkr queryKeysRequest
err := json.Unmarshal(request.Content(), &qkr) err := json.Unmarshal(request.Content(), &qkr)
@ -92,7 +93,7 @@ type claimOTKsRequest struct {
// ClaimOneTimeKeys claims OTKs for users on this server. // ClaimOneTimeKeys claims OTKs for users on this server.
// https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-claim // https://matrix.org/docs/spec/server_server/latest#post-matrix-federation-v1-user-keys-claim
func ClaimOneTimeKeys( func ClaimOneTimeKeys(
httpReq *http.Request, request *gomatrixserverlib.FederationRequest, keyAPI api.FederationKeyAPI, thisServer gomatrixserverlib.ServerName, httpReq *http.Request, request *fclient.FederationRequest, keyAPI api.FederationKeyAPI, thisServer spec.ServerName,
) util.JSONResponse { ) util.JSONResponse {
var cor claimOTKsRequest var cor claimOTKsRequest
err := json.Unmarshal(request.Content(), &cor) err := json.Unmarshal(request.Content(), &cor)
@ -135,7 +136,7 @@ func ClaimOneTimeKeys(
// LocalKeys returns the local keys for the server. // LocalKeys returns the local keys for the server.
// See https://matrix.org/docs/spec/server_server/unstable.html#publishing-keys // See https://matrix.org/docs/spec/server_server/unstable.html#publishing-keys
func LocalKeys(cfg *config.FederationAPI, serverName gomatrixserverlib.ServerName) util.JSONResponse { func LocalKeys(cfg *config.FederationAPI, serverName spec.ServerName) util.JSONResponse {
keys, err := localKeys(cfg, serverName) keys, err := localKeys(cfg, serverName)
if err != nil { if err != nil {
return util.MessageResponse(http.StatusNotFound, err.Error()) return util.MessageResponse(http.StatusNotFound, err.Error())
@ -143,7 +144,7 @@ func LocalKeys(cfg *config.FederationAPI, serverName gomatrixserverlib.ServerNam
return util.JSONResponse{Code: http.StatusOK, JSON: keys} return util.JSONResponse{Code: http.StatusOK, JSON: keys}
} }
func localKeys(cfg *config.FederationAPI, serverName gomatrixserverlib.ServerName) (*gomatrixserverlib.ServerKeys, error) { func localKeys(cfg *config.FederationAPI, serverName spec.ServerName) (*gomatrixserverlib.ServerKeys, error) {
var keys gomatrixserverlib.ServerKeys var keys gomatrixserverlib.ServerKeys
var identity *fclient.SigningIdentity var identity *fclient.SigningIdentity
var err error var err error
@ -153,10 +154,10 @@ func localKeys(cfg *config.FederationAPI, serverName gomatrixserverlib.ServerNam
} }
publicKey := cfg.Matrix.PrivateKey.Public().(ed25519.PublicKey) publicKey := cfg.Matrix.PrivateKey.Public().(ed25519.PublicKey)
keys.ServerName = cfg.Matrix.ServerName keys.ServerName = cfg.Matrix.ServerName
keys.ValidUntilTS = gomatrixserverlib.AsTimestamp(time.Now().Add(cfg.Matrix.KeyValidityPeriod)) keys.ValidUntilTS = spec.AsTimestamp(time.Now().Add(cfg.Matrix.KeyValidityPeriod))
keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{ keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{
cfg.Matrix.KeyID: { cfg.Matrix.KeyID: {
Key: gomatrixserverlib.Base64Bytes(publicKey), Key: spec.Base64Bytes(publicKey),
}, },
} }
keys.OldVerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.OldVerifyKey{} keys.OldVerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.OldVerifyKey{}
@ -174,10 +175,10 @@ func localKeys(cfg *config.FederationAPI, serverName gomatrixserverlib.ServerNam
} }
publicKey := virtualHost.PrivateKey.Public().(ed25519.PublicKey) publicKey := virtualHost.PrivateKey.Public().(ed25519.PublicKey)
keys.ServerName = virtualHost.ServerName keys.ServerName = virtualHost.ServerName
keys.ValidUntilTS = gomatrixserverlib.AsTimestamp(time.Now().Add(virtualHost.KeyValidityPeriod)) keys.ValidUntilTS = spec.AsTimestamp(time.Now().Add(virtualHost.KeyValidityPeriod))
keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{ keys.VerifyKeys = map[gomatrixserverlib.KeyID]gomatrixserverlib.VerifyKey{
virtualHost.KeyID: { virtualHost.KeyID: {
Key: gomatrixserverlib.Base64Bytes(publicKey), Key: spec.Base64Bytes(publicKey),
}, },
} }
// TODO: Virtual hosts probably want to be able to specify old signing // TODO: Virtual hosts probably want to be able to specify old signing
@ -200,7 +201,7 @@ func NotaryKeys(
fsAPI federationAPI.FederationInternalAPI, fsAPI federationAPI.FederationInternalAPI,
req *gomatrixserverlib.PublicKeyNotaryLookupRequest, req *gomatrixserverlib.PublicKeyNotaryLookupRequest,
) util.JSONResponse { ) util.JSONResponse {
serverName := gomatrixserverlib.ServerName(httpReq.Host) // TODO: this is not ideal serverName := spec.ServerName(httpReq.Host) // TODO: this is not ideal
if !cfg.Matrix.IsLocalServerName(serverName) { if !cfg.Matrix.IsLocalServerName(serverName) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusNotFound, Code: http.StatusNotFound,

View File

@ -22,6 +22,8 @@ import (
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@ -29,7 +31,7 @@ import (
// MakeLeave implements the /make_leave API // MakeLeave implements the /make_leave API
func MakeLeave( func MakeLeave(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID, userID string, roomID, userID string,
@ -55,7 +57,7 @@ func MakeLeave(
Type: "m.room.member", Type: "m.room.member",
StateKey: &userID, StateKey: &userID,
} }
err = builder.SetContent(map[string]interface{}{"membership": gomatrixserverlib.Leave}) err = builder.SetContent(map[string]interface{}{"membership": spec.Leave})
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("builder.SetContent failed") util.GetLogger(httpReq.Context()).WithError(err).Error("builder.SetContent failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
@ -95,7 +97,7 @@ func MakeLeave(
if !state.StateKeyEquals(userID) { if !state.StateKeyEquals(userID) {
continue continue
} }
if mem, merr := state.Membership(); merr == nil && mem == gomatrixserverlib.Leave { if mem, merr := state.Membership(); merr == nil && mem == spec.Leave {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
JSON: map[string]interface{}{ JSON: map[string]interface{}{
@ -132,7 +134,7 @@ func MakeLeave(
// nolint:gocyclo // nolint:gocyclo
func SendLeave( func SendLeave(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
keys gomatrixserverlib.JSONVerifier, keys gomatrixserverlib.JSONVerifier,
@ -195,7 +197,7 @@ func SendLeave(
// Check that the sender belongs to the server that is sending us // Check that the sender belongs to the server that is sending us
// the request. By this point we've already asserted that the sender // the request. By this point we've already asserted that the sender
// and the state key are equal so we don't need to check both. // and the state key are equal so we don't need to check both.
var serverName gomatrixserverlib.ServerName var serverName spec.ServerName
if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil { if _, serverName, err = gomatrixserverlib.SplitID('@', event.Sender()); err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -213,7 +215,7 @@ func SendLeave(
RoomID: roomID, RoomID: roomID,
StateToFetch: []gomatrixserverlib.StateKeyTuple{ StateToFetch: []gomatrixserverlib.StateKeyTuple{
{ {
EventType: gomatrixserverlib.MRoomMember, EventType: spec.MRoomMember,
StateKey: *event.StateKey(), StateKey: *event.StateKey(),
}, },
}, },
@ -242,7 +244,7 @@ func SendLeave(
// We are/were joined/invited/banned or something. Check if // We are/were joined/invited/banned or something. Check if
// we can no-op here. // we can no-op here.
if len(queryRes.StateEvents) == 1 { if len(queryRes.StateEvents) == 1 {
if mem, merr := queryRes.StateEvents[0].Membership(); merr == nil && mem == gomatrixserverlib.Leave { if mem, merr := queryRes.StateEvents[0].Membership(); merr == nil && mem == spec.Leave {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
JSON: struct{}{}, JSON: struct{}{},
@ -286,7 +288,7 @@ func SendLeave(
JSON: jsonerror.BadJSON("missing content.membership key"), JSON: jsonerror.BadJSON("missing content.membership key"),
} }
} }
if mem != gomatrixserverlib.Leave { if mem != spec.Leave {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.BadJSON("The membership in the event content must be set to leave"), JSON: jsonerror.BadJSON("The membership in the event content must be set to leave"),

View File

@ -34,7 +34,7 @@ type getMissingEventRequest struct {
// Events are fetched from room DAG starting from latest_events until we reach earliest_events or the limit. // Events are fetched from room DAG starting from latest_events until we reach earliest_events or the limit.
func GetMissingEvents( func GetMissingEvents(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
) util.JSONResponse { ) util.JSONResponse {

View File

@ -28,7 +28,7 @@ import (
// Peek implements the SS /peek API, handling inbound peeks // Peek implements the SS /peek API, handling inbound peeks
func Peek( func Peek(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID, peekID string, roomID, peekID string,

View File

@ -36,6 +36,8 @@ import (
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
userAPI "github.com/matrix-org/dendrite/userapi/api" userAPI "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"golang.org/x/crypto/ed25519" "golang.org/x/crypto/ed25519"
) )
@ -75,8 +77,8 @@ func TestHandleQueryProfile(t *testing.T) {
_, sk, _ := ed25519.GenerateKey(nil) _, sk, _ := ed25519.GenerateKey(nil)
keyID := signing.KeyID keyID := signing.KeyID
pk := sk.Public().(ed25519.PublicKey) pk := sk.Public().(ed25519.PublicKey)
serverName := gomatrixserverlib.ServerName(hex.EncodeToString(pk)) serverName := spec.ServerName(hex.EncodeToString(pk))
req := gomatrixserverlib.NewFederationRequest("GET", serverName, testOrigin, "/query/profile?user_id="+url.QueryEscape("@user:"+string(testOrigin))) req := fclient.NewFederationRequest("GET", serverName, testOrigin, "/query/profile?user_id="+url.QueryEscape("@user:"+string(testOrigin)))
type queryContent struct{} type queryContent struct{}
content := queryContent{} content := queryContent{}
err := req.SetContent(content) err := req.SetContent(content)

View File

@ -8,6 +8,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
@ -126,11 +127,11 @@ func fillPublicRoomsReq(httpReq *http.Request, request *PublicRoomReq) *util.JSO
func fillInRooms(ctx context.Context, roomIDs []string, rsAPI roomserverAPI.FederationRoomserverAPI) ([]fclient.PublicRoom, error) { func fillInRooms(ctx context.Context, roomIDs []string, rsAPI roomserverAPI.FederationRoomserverAPI) ([]fclient.PublicRoom, error) {
avatarTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.avatar", StateKey: ""} avatarTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.avatar", StateKey: ""}
nameTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.name", StateKey: ""} nameTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.name", StateKey: ""}
canonicalTuple := gomatrixserverlib.StateKeyTuple{EventType: gomatrixserverlib.MRoomCanonicalAlias, StateKey: ""} canonicalTuple := gomatrixserverlib.StateKeyTuple{EventType: spec.MRoomCanonicalAlias, StateKey: ""}
topicTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.topic", StateKey: ""} topicTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.topic", StateKey: ""}
guestTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.guest_access", StateKey: ""} guestTuple := gomatrixserverlib.StateKeyTuple{EventType: "m.room.guest_access", StateKey: ""}
visibilityTuple := gomatrixserverlib.StateKeyTuple{EventType: gomatrixserverlib.MRoomHistoryVisibility, StateKey: ""} visibilityTuple := gomatrixserverlib.StateKeyTuple{EventType: spec.MRoomHistoryVisibility, StateKey: ""}
joinRuleTuple := gomatrixserverlib.StateKeyTuple{EventType: gomatrixserverlib.MRoomJoinRules, StateKey: ""} joinRuleTuple := gomatrixserverlib.StateKeyTuple{EventType: spec.MRoomJoinRules, StateKey: ""}
var stateRes roomserverAPI.QueryBulkStateContentResponse var stateRes roomserverAPI.QueryBulkStateContentResponse
err := rsAPI.QueryBulkStateContent(ctx, &roomserverAPI.QueryBulkStateContentRequest{ err := rsAPI.QueryBulkStateContent(ctx, &roomserverAPI.QueryBulkStateContentRequest{
@ -138,7 +139,7 @@ func fillInRooms(ctx context.Context, roomIDs []string, rsAPI roomserverAPI.Fede
AllowWildcards: true, AllowWildcards: true,
StateTuples: []gomatrixserverlib.StateKeyTuple{ StateTuples: []gomatrixserverlib.StateKeyTuple{
nameTuple, canonicalTuple, topicTuple, guestTuple, visibilityTuple, joinRuleTuple, avatarTuple, nameTuple, canonicalTuple, topicTuple, guestTuple, visibilityTuple, joinRuleTuple, avatarTuple,
{EventType: gomatrixserverlib.MRoomMember, StateKey: "*"}, {EventType: spec.MRoomMember, StateKey: "*"},
}, },
}, &stateRes) }, &stateRes)
if err != nil { if err != nil {
@ -154,7 +155,7 @@ func fillInRooms(ctx context.Context, roomIDs []string, rsAPI roomserverAPI.Fede
joinCount := 0 joinCount := 0
var joinRule, guestAccess string var joinRule, guestAccess string
for tuple, contentVal := range data { for tuple, contentVal := range data {
if tuple.EventType == gomatrixserverlib.MRoomMember && contentVal == "join" { if tuple.EventType == spec.MRoomMember && contentVal == "join" {
joinCount++ joinCount++
continue continue
} }
@ -178,7 +179,7 @@ func fillInRooms(ctx context.Context, roomIDs []string, rsAPI roomserverAPI.Fede
guestAccess = contentVal guestAccess = contentVal
} }
} }
if joinRule == gomatrixserverlib.Public && guestAccess == "can_join" { if joinRule == spec.Public && guestAccess == "can_join" {
pub.GuestCanJoin = true pub.GuestCanJoin = true
} }
pub.JoinedMembersCount = joinCount pub.JoinedMembersCount = joinCount

View File

@ -36,6 +36,7 @@ import (
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"golang.org/x/crypto/ed25519" "golang.org/x/crypto/ed25519"
) )
@ -44,7 +45,7 @@ type fakeFedClient struct {
fedclient.FederationClient fedclient.FederationClient
} }
func (f *fakeFedClient) LookupRoomAlias(ctx context.Context, origin, s gomatrixserverlib.ServerName, roomAlias string) (res fclient.RespDirectory, err error) { func (f *fakeFedClient) LookupRoomAlias(ctx context.Context, origin, s spec.ServerName, roomAlias string) (res fclient.RespDirectory, err error) {
return return
} }
@ -75,8 +76,8 @@ func TestHandleQueryDirectory(t *testing.T) {
_, sk, _ := ed25519.GenerateKey(nil) _, sk, _ := ed25519.GenerateKey(nil)
keyID := signing.KeyID keyID := signing.KeyID
pk := sk.Public().(ed25519.PublicKey) pk := sk.Public().(ed25519.PublicKey)
serverName := gomatrixserverlib.ServerName(hex.EncodeToString(pk)) serverName := spec.ServerName(hex.EncodeToString(pk))
req := gomatrixserverlib.NewFederationRequest("GET", serverName, testOrigin, "/query/directory?room_alias="+url.QueryEscape("#room:server")) req := fclient.NewFederationRequest("GET", serverName, testOrigin, "/query/directory?room_alias="+url.QueryEscape("#room:server"))
type queryContent struct{} type queryContent struct{}
content := queryContent{} content := queryContent{}
err := req.SetContent(content) err := req.SetContent(content)

View File

@ -34,6 +34,8 @@ import (
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -85,7 +87,7 @@ func Setup(
} }
localKeys := httputil.MakeExternalAPI("localkeys", func(req *http.Request) util.JSONResponse { localKeys := httputil.MakeExternalAPI("localkeys", func(req *http.Request) util.JSONResponse {
return LocalKeys(cfg, gomatrixserverlib.ServerName(req.Host)) return LocalKeys(cfg, spec.ServerName(req.Host))
}) })
notaryKeys := httputil.MakeExternalAPI("notarykeys", func(req *http.Request) util.JSONResponse { notaryKeys := httputil.MakeExternalAPI("notarykeys", func(req *http.Request) util.JSONResponse {
@ -94,11 +96,11 @@ func Setup(
return util.ErrorResponse(err) return util.ErrorResponse(err)
} }
var pkReq *gomatrixserverlib.PublicKeyNotaryLookupRequest var pkReq *gomatrixserverlib.PublicKeyNotaryLookupRequest
serverName := gomatrixserverlib.ServerName(vars["serverName"]) serverName := spec.ServerName(vars["serverName"])
keyID := gomatrixserverlib.KeyID(vars["keyID"]) keyID := gomatrixserverlib.KeyID(vars["keyID"])
if serverName != "" && keyID != "" { if serverName != "" && keyID != "" {
pkReq = &gomatrixserverlib.PublicKeyNotaryLookupRequest{ pkReq = &gomatrixserverlib.PublicKeyNotaryLookupRequest{
ServerKeys: map[gomatrixserverlib.ServerName]map[gomatrixserverlib.KeyID]gomatrixserverlib.PublicKeyNotaryQueryCriteria{ ServerKeys: map[spec.ServerName]map[gomatrixserverlib.KeyID]gomatrixserverlib.PublicKeyNotaryQueryCriteria{
serverName: { serverName: {
keyID: gomatrixserverlib.PublicKeyNotaryQueryCriteria{}, keyID: gomatrixserverlib.PublicKeyNotaryQueryCriteria{},
}, },
@ -136,7 +138,7 @@ func Setup(
mu := internal.NewMutexByRoom() mu := internal.NewMutexByRoom()
v1fedmux.Handle("/send/{txnID}", MakeFedAPI( v1fedmux.Handle("/send/{txnID}", MakeFedAPI(
"federation_send", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_send", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return Send( return Send(
httpReq, request, gomatrixserverlib.TransactionID(vars["txnID"]), httpReq, request, gomatrixserverlib.TransactionID(vars["txnID"]),
cfg, rsAPI, userAPI, keys, federation, mu, servers, producer, cfg, rsAPI, userAPI, keys, federation, mu, servers, producer,
@ -146,7 +148,7 @@ func Setup(
v1fedmux.Handle("/invite/{roomID}/{eventID}", MakeFedAPI( v1fedmux.Handle("/invite/{roomID}/{eventID}", MakeFedAPI(
"federation_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -162,7 +164,7 @@ func Setup(
v2fedmux.Handle("/invite/{roomID}/{eventID}", MakeFedAPI( v2fedmux.Handle("/invite/{roomID}/{eventID}", MakeFedAPI(
"federation_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -184,7 +186,7 @@ func Setup(
v1fedmux.Handle("/exchange_third_party_invite/{roomID}", MakeFedAPI( v1fedmux.Handle("/exchange_third_party_invite/{roomID}", MakeFedAPI(
"exchange_third_party_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "exchange_third_party_invite", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return ExchangeThirdPartyInvite( return ExchangeThirdPartyInvite(
httpReq, request, vars["roomID"], rsAPI, cfg, federation, httpReq, request, vars["roomID"], rsAPI, cfg, federation,
) )
@ -193,7 +195,7 @@ func Setup(
v1fedmux.Handle("/event/{eventID}", MakeFedAPI( v1fedmux.Handle("/event/{eventID}", MakeFedAPI(
"federation_get_event", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_get_event", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return GetEvent( return GetEvent(
httpReq.Context(), request, rsAPI, vars["eventID"], cfg.Matrix.ServerName, httpReq.Context(), request, rsAPI, vars["eventID"], cfg.Matrix.ServerName,
) )
@ -202,7 +204,7 @@ func Setup(
v1fedmux.Handle("/state/{roomID}", MakeFedAPI( v1fedmux.Handle("/state/{roomID}", MakeFedAPI(
"federation_get_state", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_get_state", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -217,7 +219,7 @@ func Setup(
v1fedmux.Handle("/state_ids/{roomID}", MakeFedAPI( v1fedmux.Handle("/state_ids/{roomID}", MakeFedAPI(
"federation_get_state_ids", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_get_state_ids", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -232,7 +234,7 @@ func Setup(
v1fedmux.Handle("/event_auth/{roomID}/{eventID}", MakeFedAPI( v1fedmux.Handle("/event_auth/{roomID}/{eventID}", MakeFedAPI(
"federation_get_event_auth", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_get_event_auth", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -247,7 +249,7 @@ func Setup(
v1fedmux.Handle("/query/directory", MakeFedAPI( v1fedmux.Handle("/query/directory", MakeFedAPI(
"federation_query_room_alias", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_query_room_alias", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return RoomAliasToID( return RoomAliasToID(
httpReq, federation, cfg, rsAPI, fsAPI, httpReq, federation, cfg, rsAPI, fsAPI,
) )
@ -256,7 +258,7 @@ func Setup(
v1fedmux.Handle("/query/profile", MakeFedAPI( v1fedmux.Handle("/query/profile", MakeFedAPI(
"federation_query_profile", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_query_profile", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return GetProfile( return GetProfile(
httpReq, userAPI, cfg, httpReq, userAPI, cfg,
) )
@ -265,7 +267,7 @@ func Setup(
v1fedmux.Handle("/user/devices/{userID}", MakeFedAPI( v1fedmux.Handle("/user/devices/{userID}", MakeFedAPI(
"federation_user_devices", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_user_devices", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return GetUserDevices( return GetUserDevices(
httpReq, userAPI, vars["userID"], httpReq, userAPI, vars["userID"],
) )
@ -275,7 +277,7 @@ func Setup(
if mscCfg.Enabled("msc2444") { if mscCfg.Enabled("msc2444") {
v1fedmux.Handle("/peek/{roomID}/{peekID}", MakeFedAPI( v1fedmux.Handle("/peek/{roomID}/{peekID}", MakeFedAPI(
"federation_peek", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_peek", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -306,7 +308,7 @@ func Setup(
v1fedmux.Handle("/make_join/{roomID}/{userID}", MakeFedAPI( v1fedmux.Handle("/make_join/{roomID}/{userID}", MakeFedAPI(
"federation_make_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_make_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -337,7 +339,7 @@ func Setup(
v1fedmux.Handle("/send_join/{roomID}/{eventID}", MakeFedAPI( v1fedmux.Handle("/send_join/{roomID}/{eventID}", MakeFedAPI(
"federation_send_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_send_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -369,7 +371,7 @@ func Setup(
v2fedmux.Handle("/send_join/{roomID}/{eventID}", MakeFedAPI( v2fedmux.Handle("/send_join/{roomID}/{eventID}", MakeFedAPI(
"federation_send_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_send_join", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -386,7 +388,7 @@ func Setup(
v1fedmux.Handle("/make_leave/{roomID}/{eventID}", MakeFedAPI( v1fedmux.Handle("/make_leave/{roomID}/{eventID}", MakeFedAPI(
"federation_make_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_make_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -403,7 +405,7 @@ func Setup(
v1fedmux.Handle("/send_leave/{roomID}/{eventID}", MakeFedAPI( v1fedmux.Handle("/send_leave/{roomID}/{eventID}", MakeFedAPI(
"federation_send_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_send_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -435,7 +437,7 @@ func Setup(
v2fedmux.Handle("/send_leave/{roomID}/{eventID}", MakeFedAPI( v2fedmux.Handle("/send_leave/{roomID}/{eventID}", MakeFedAPI(
"federation_send_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_send_leave", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -459,7 +461,7 @@ func Setup(
v1fedmux.Handle("/get_missing_events/{roomID}", MakeFedAPI( v1fedmux.Handle("/get_missing_events/{roomID}", MakeFedAPI(
"federation_get_missing_events", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_get_missing_events", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -472,7 +474,7 @@ func Setup(
v1fedmux.Handle("/backfill/{roomID}", MakeFedAPI( v1fedmux.Handle("/backfill/{roomID}", MakeFedAPI(
"federation_backfill", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_backfill", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) { if roomserverAPI.IsServerBannedFromRoom(httpReq.Context(), rsAPI, vars["roomID"], request.Origin()) {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusForbidden, Code: http.StatusForbidden,
@ -491,14 +493,14 @@ func Setup(
v1fedmux.Handle("/user/keys/claim", MakeFedAPI( v1fedmux.Handle("/user/keys/claim", MakeFedAPI(
"federation_keys_claim", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_keys_claim", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return ClaimOneTimeKeys(httpReq, request, userAPI, cfg.Matrix.ServerName) return ClaimOneTimeKeys(httpReq, request, userAPI, cfg.Matrix.ServerName)
}, },
)).Methods(http.MethodPost) )).Methods(http.MethodPost)
v1fedmux.Handle("/user/keys/query", MakeFedAPI( v1fedmux.Handle("/user/keys/query", MakeFedAPI(
"federation_keys_query", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup, "federation_keys_query", cfg.Matrix.ServerName, cfg.Matrix.IsLocalServerName, keys, wakeup,
func(httpReq *http.Request, request *gomatrixserverlib.FederationRequest, vars map[string]string) util.JSONResponse { func(httpReq *http.Request, request *fclient.FederationRequest, vars map[string]string) util.JSONResponse {
return QueryDeviceKeys(httpReq, request, userAPI, cfg.Matrix.ServerName) return QueryDeviceKeys(httpReq, request, userAPI, cfg.Matrix.ServerName)
}, },
)).Methods(http.MethodPost) )).Methods(http.MethodPost)
@ -536,14 +538,14 @@ func ErrorIfLocalServerNotInRoom(
// MakeFedAPI makes an http.Handler that checks matrix federation authentication. // MakeFedAPI makes an http.Handler that checks matrix federation authentication.
func MakeFedAPI( func MakeFedAPI(
metricsName string, serverName gomatrixserverlib.ServerName, metricsName string, serverName spec.ServerName,
isLocalServerName func(gomatrixserverlib.ServerName) bool, isLocalServerName func(spec.ServerName) bool,
keyRing gomatrixserverlib.JSONVerifier, keyRing gomatrixserverlib.JSONVerifier,
wakeup *FederationWakeups, wakeup *FederationWakeups,
f func(*http.Request, *gomatrixserverlib.FederationRequest, map[string]string) util.JSONResponse, f func(*http.Request, *fclient.FederationRequest, map[string]string) util.JSONResponse,
) http.Handler { ) http.Handler {
h := func(req *http.Request) util.JSONResponse { h := func(req *http.Request) util.JSONResponse {
fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest( fedReq, errResp := fclient.VerifyHTTPRequest(
req, time.Now(), serverName, isLocalServerName, keyRing, req, time.Now(), serverName, isLocalServerName, keyRing,
) )
if fedReq == nil { if fedReq == nil {
@ -586,7 +588,7 @@ type FederationWakeups struct {
origins sync.Map origins sync.Map
} }
func (f *FederationWakeups) Wakeup(ctx context.Context, origin gomatrixserverlib.ServerName) { func (f *FederationWakeups) Wakeup(ctx context.Context, origin spec.ServerName) {
key, keyok := f.origins.Load(origin) key, keyok := f.origins.Load(origin)
if keyok { if keyok {
lastTime, ok := key.(time.Time) lastTime, ok := key.(time.Time)
@ -594,6 +596,6 @@ func (f *FederationWakeups) Wakeup(ctx context.Context, origin gomatrixserverlib
return return
} }
} }
f.FsAPI.MarkServersAlive([]gomatrixserverlib.ServerName{origin}) f.FsAPI.MarkServersAlive([]spec.ServerName{origin})
f.origins.Store(origin, time.Now()) f.origins.Store(origin, time.Now())
} }

View File

@ -22,6 +22,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/util" "github.com/matrix-org/util"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
@ -55,7 +56,7 @@ var inFlightTxnsPerOrigin sync.Map // transaction ID -> chan util.JSONResponse
// Send implements /_matrix/federation/v1/send/{txnID} // Send implements /_matrix/federation/v1/send/{txnID}
func Send( func Send(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
txnID gomatrixserverlib.TransactionID, txnID gomatrixserverlib.TransactionID,
cfg *config.FederationAPI, cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,

View File

@ -32,12 +32,14 @@ import (
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/dendrite/test/testrig" "github.com/matrix-org/dendrite/test/testrig"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"golang.org/x/crypto/ed25519" "golang.org/x/crypto/ed25519"
) )
const ( const (
testOrigin = gomatrixserverlib.ServerName("kaer.morhen") testOrigin = spec.ServerName("kaer.morhen")
) )
type sendContent struct { type sendContent struct {
@ -70,8 +72,8 @@ func TestHandleSend(t *testing.T) {
_, sk, _ := ed25519.GenerateKey(nil) _, sk, _ := ed25519.GenerateKey(nil)
keyID := signing.KeyID keyID := signing.KeyID
pk := sk.Public().(ed25519.PublicKey) pk := sk.Public().(ed25519.PublicKey)
serverName := gomatrixserverlib.ServerName(hex.EncodeToString(pk)) serverName := spec.ServerName(hex.EncodeToString(pk))
req := gomatrixserverlib.NewFederationRequest("PUT", serverName, testOrigin, "/send/1234") req := fclient.NewFederationRequest("PUT", serverName, testOrigin, "/send/1234")
content := sendContent{} content := sendContent{}
err := req.SetContent(content) err := req.SetContent(content)
if err != nil { if err != nil {

View File

@ -27,7 +27,7 @@ import (
// GetState returns state events & auth events for the roomID, eventID // GetState returns state events & auth events for the roomID, eventID
func GetState( func GetState(
ctx context.Context, ctx context.Context,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
) util.JSONResponse { ) util.JSONResponse {
@ -50,7 +50,7 @@ func GetState(
// GetStateIDs returns state event IDs & auth event IDs for the roomID, eventID // GetStateIDs returns state event IDs & auth event IDs for the roomID, eventID
func GetStateIDs( func GetStateIDs(
ctx context.Context, ctx context.Context,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
) util.JSONResponse { ) util.JSONResponse {
@ -75,7 +75,7 @@ func GetStateIDs(
} }
func parseEventIDParam( func parseEventIDParam(
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
) (eventID string, resErr *util.JSONResponse) { ) (eventID string, resErr *util.JSONResponse) {
URL, err := url.Parse(request.RequestURI()) URL, err := url.Parse(request.RequestURI())
if err != nil { if err != nil {
@ -97,7 +97,7 @@ func parseEventIDParam(
func getState( func getState(
ctx context.Context, ctx context.Context,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
roomID string, roomID string,
eventID string, eventID string,

View File

@ -27,6 +27,8 @@ import (
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
userapi "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/util" "github.com/matrix-org/util"
@ -114,7 +116,7 @@ func CreateInvitesFrom3PIDInvites(
// ExchangeThirdPartyInvite implements PUT /_matrix/federation/v1/exchange_third_party_invite/{roomID} // ExchangeThirdPartyInvite implements PUT /_matrix/federation/v1/exchange_third_party_invite/{roomID}
func ExchangeThirdPartyInvite( func ExchangeThirdPartyInvite(
httpReq *http.Request, httpReq *http.Request,
request *gomatrixserverlib.FederationRequest, request *fclient.FederationRequest,
roomID string, roomID string,
rsAPI api.FederationRoomserverAPI, rsAPI api.FederationRoomserverAPI,
cfg *config.FederationAPI, cfg *config.FederationAPI,
@ -184,7 +186,7 @@ func ExchangeThirdPartyInvite(
// Ask the requesting server to sign the newly created event so we know it // Ask the requesting server to sign the newly created event so we know it
// acknowledged it // acknowledged it
inviteReq, err := gomatrixserverlib.NewInviteV2Request(event.Headered(verRes.RoomVersion), nil) inviteReq, err := fclient.NewInviteV2Request(event.Headered(verRes.RoomVersion), nil)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("failed to make invite v2 request") util.GetLogger(httpReq.Context()).WithError(err).Error("failed to make invite v2 request")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
@ -194,7 +196,7 @@ func ExchangeThirdPartyInvite(
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
} }
inviteEvent, err := signedEvent.Event.UntrustedEvent(verRes.RoomVersion) inviteEvent, err := gomatrixserverlib.UntrustedEvent(signedEvent.Event, verRes.RoomVersion)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
@ -264,7 +266,7 @@ func createInviteFrom3PIDInvite(
content := gomatrixserverlib.MemberContent{ content := gomatrixserverlib.MemberContent{
AvatarURL: profile.AvatarURL, AvatarURL: profile.AvatarURL,
DisplayName: profile.DisplayName, DisplayName: profile.DisplayName,
Membership: gomatrixserverlib.Invite, Membership: spec.Invite,
ThirdPartyInvite: &gomatrixserverlib.MemberThirdPartyInvite{ ThirdPartyInvite: &gomatrixserverlib.MemberThirdPartyInvite{
Signed: inv.Signed, Signed: inv.Signed,
}, },
@ -360,7 +362,7 @@ func sendToRemoteServer(
federation federationAPI.FederationClient, cfg *config.FederationAPI, federation federationAPI.FederationClient, cfg *config.FederationAPI,
builder gomatrixserverlib.EventBuilder, builder gomatrixserverlib.EventBuilder,
) (err error) { ) (err error) {
remoteServers := make([]gomatrixserverlib.ServerName, 2) remoteServers := make([]spec.ServerName, 2)
_, remoteServers[0], err = gomatrixserverlib.SplitID('@', inv.Sender) _, remoteServers[0], err = gomatrixserverlib.SplitID('@', inv.Sender)
if err != nil { if err != nil {
return return

View File

@ -7,11 +7,11 @@ import (
"sync" "sync"
"time" "time"
"github.com/matrix-org/gomatrixserverlib"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"go.uber.org/atomic" "go.uber.org/atomic"
"github.com/matrix-org/dendrite/federationapi/storage" "github.com/matrix-org/dendrite/federationapi/storage"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// Statistics contains information about all of the remote federated // Statistics contains information about all of the remote federated
@ -19,10 +19,10 @@ import (
// wrapper. // wrapper.
type Statistics struct { type Statistics struct {
DB storage.Database DB storage.Database
servers map[gomatrixserverlib.ServerName]*ServerStatistics servers map[spec.ServerName]*ServerStatistics
mutex sync.RWMutex mutex sync.RWMutex
backoffTimers map[gomatrixserverlib.ServerName]*time.Timer backoffTimers map[spec.ServerName]*time.Timer
backoffMutex sync.RWMutex backoffMutex sync.RWMutex
// How many times should we tolerate consecutive failures before we // How many times should we tolerate consecutive failures before we
@ -45,14 +45,14 @@ func NewStatistics(
DB: db, DB: db,
FailuresUntilBlacklist: failuresUntilBlacklist, FailuresUntilBlacklist: failuresUntilBlacklist,
FailuresUntilAssumedOffline: failuresUntilAssumedOffline, FailuresUntilAssumedOffline: failuresUntilAssumedOffline,
backoffTimers: make(map[gomatrixserverlib.ServerName]*time.Timer), backoffTimers: make(map[spec.ServerName]*time.Timer),
servers: make(map[gomatrixserverlib.ServerName]*ServerStatistics), servers: make(map[spec.ServerName]*ServerStatistics),
} }
} }
// ForServer returns server statistics for the given server name. If it // ForServer returns server statistics for the given server name. If it
// does not exist, it will create empty statistics and return those. // does not exist, it will create empty statistics and return those.
func (s *Statistics) ForServer(serverName gomatrixserverlib.ServerName) *ServerStatistics { func (s *Statistics) ForServer(serverName spec.ServerName) *ServerStatistics {
// Look up if we have statistics for this server already. // Look up if we have statistics for this server already.
s.mutex.RLock() s.mutex.RLock()
server, found := s.servers[serverName] server, found := s.servers[serverName]
@ -63,7 +63,7 @@ func (s *Statistics) ForServer(serverName gomatrixserverlib.ServerName) *ServerS
server = &ServerStatistics{ server = &ServerStatistics{
statistics: s, statistics: s,
serverName: serverName, serverName: serverName,
knownRelayServers: []gomatrixserverlib.ServerName{}, knownRelayServers: []spec.ServerName{},
} }
s.servers[serverName] = server s.servers[serverName] = server
s.mutex.Unlock() s.mutex.Unlock()
@ -104,17 +104,17 @@ const (
// many times we failed etc. It also manages the backoff time and black- // many times we failed etc. It also manages the backoff time and black-
// listing a remote host if it remains uncooperative. // listing a remote host if it remains uncooperative.
type ServerStatistics struct { type ServerStatistics struct {
statistics *Statistics // statistics *Statistics //
serverName gomatrixserverlib.ServerName // serverName spec.ServerName //
blacklisted atomic.Bool // is the node blacklisted blacklisted atomic.Bool // is the node blacklisted
assumedOffline atomic.Bool // is the node assumed to be offline assumedOffline atomic.Bool // is the node assumed to be offline
backoffStarted atomic.Bool // is the backoff started backoffStarted atomic.Bool // is the backoff started
backoffUntil atomic.Value // time.Time until this backoff interval ends backoffUntil atomic.Value // time.Time until this backoff interval ends
backoffCount atomic.Uint32 // number of times BackoffDuration has been called backoffCount atomic.Uint32 // number of times BackoffDuration has been called
successCounter atomic.Uint32 // how many times have we succeeded? successCounter atomic.Uint32 // how many times have we succeeded?
backoffNotifier func() // notifies destination queue when backoff completes backoffNotifier func() // notifies destination queue when backoff completes
notifierMutex sync.Mutex notifierMutex sync.Mutex
knownRelayServers []gomatrixserverlib.ServerName knownRelayServers []spec.ServerName
relayMutex sync.Mutex relayMutex sync.Mutex
} }
@ -307,15 +307,15 @@ func (s *ServerStatistics) SuccessCount() uint32 {
// KnownRelayServers returns the list of relay servers associated with this // KnownRelayServers returns the list of relay servers associated with this
// server. // server.
func (s *ServerStatistics) KnownRelayServers() []gomatrixserverlib.ServerName { func (s *ServerStatistics) KnownRelayServers() []spec.ServerName {
s.relayMutex.Lock() s.relayMutex.Lock()
defer s.relayMutex.Unlock() defer s.relayMutex.Unlock()
return s.knownRelayServers return s.knownRelayServers
} }
func (s *ServerStatistics) AddRelayServers(relayServers []gomatrixserverlib.ServerName) { func (s *ServerStatistics) AddRelayServers(relayServers []spec.ServerName) {
seenSet := make(map[gomatrixserverlib.ServerName]bool) seenSet := make(map[spec.ServerName]bool)
uniqueList := []gomatrixserverlib.ServerName{} uniqueList := []spec.ServerName{}
for _, srv := range relayServers { for _, srv := range relayServers {
if seenSet[srv] { if seenSet[srv] {
continue continue

View File

@ -6,7 +6,7 @@ import (
"time" "time"
"github.com/matrix-org/dendrite/test" "github.com/matrix-org/dendrite/test"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -108,10 +108,10 @@ func TestBackoff(t *testing.T) {
func TestRelayServersListing(t *testing.T) { func TestRelayServersListing(t *testing.T) {
stats := NewStatistics(test.NewInMemoryFederationDatabase(), FailuresUntilBlacklist, FailuresUntilAssumedOffline) stats := NewStatistics(test.NewInMemoryFederationDatabase(), FailuresUntilBlacklist, FailuresUntilAssumedOffline)
server := ServerStatistics{statistics: &stats} server := ServerStatistics{statistics: &stats}
server.AddRelayServers([]gomatrixserverlib.ServerName{"relay1", "relay1", "relay2"}) server.AddRelayServers([]spec.ServerName{"relay1", "relay1", "relay2"})
relayServers := server.KnownRelayServers() relayServers := server.KnownRelayServers()
assert.Equal(t, []gomatrixserverlib.ServerName{"relay1", "relay2"}, relayServers) assert.Equal(t, []spec.ServerName{"relay1", "relay2"}, relayServers)
server.AddRelayServers([]gomatrixserverlib.ServerName{"relay1", "relay1", "relay2"}) server.AddRelayServers([]spec.ServerName{"relay1", "relay1", "relay2"})
relayServers = server.KnownRelayServers() relayServers = server.KnownRelayServers()
assert.Equal(t, []gomatrixserverlib.ServerName{"relay1", "relay2"}, relayServers) assert.Equal(t, []spec.ServerName{"relay1", "relay2"}, relayServers)
} }

View File

@ -6,6 +6,7 @@ import (
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
// A Database implements gomatrixserverlib.KeyDatabase and is used to store // A Database implements gomatrixserverlib.KeyDatabase and is used to store
@ -36,7 +37,7 @@ func (d KeyDatabase) FetcherName() string {
// FetchKeys implements gomatrixserverlib.KeyDatabase // FetchKeys implements gomatrixserverlib.KeyDatabase
func (d *KeyDatabase) FetchKeys( func (d *KeyDatabase) FetchKeys(
ctx context.Context, ctx context.Context,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) { ) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
results := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult) results := make(map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult)
for req, ts := range requests { for req, ts := range requests {

View File

@ -19,6 +19,7 @@ import (
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/dendrite/federationapi/storage/shared/receipt" "github.com/matrix-org/dendrite/federationapi/storage/shared/receipt"
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
@ -31,57 +32,57 @@ type Database interface {
UpdateRoom(ctx context.Context, roomID string, addHosts []types.JoinedHost, removeHosts []string, purgeRoomFirst bool) (joinedHosts []types.JoinedHost, err error) UpdateRoom(ctx context.Context, roomID string, addHosts []types.JoinedHost, removeHosts []string, purgeRoomFirst bool) (joinedHosts []types.JoinedHost, err error)
GetJoinedHosts(ctx context.Context, roomID string) ([]types.JoinedHost, error) GetJoinedHosts(ctx context.Context, roomID string) ([]types.JoinedHost, error)
GetAllJoinedHosts(ctx context.Context) ([]gomatrixserverlib.ServerName, error) GetAllJoinedHosts(ctx context.Context) ([]spec.ServerName, error)
// GetJoinedHostsForRooms returns the complete set of servers in the rooms given. // GetJoinedHostsForRooms returns the complete set of servers in the rooms given.
GetJoinedHostsForRooms(ctx context.Context, roomIDs []string, excludeSelf, excludeBlacklisted bool) ([]gomatrixserverlib.ServerName, error) GetJoinedHostsForRooms(ctx context.Context, roomIDs []string, excludeSelf, excludeBlacklisted bool) ([]spec.ServerName, error)
StoreJSON(ctx context.Context, js string) (*receipt.Receipt, error) StoreJSON(ctx context.Context, js string) (*receipt.Receipt, error)
GetPendingPDUs(ctx context.Context, serverName gomatrixserverlib.ServerName, limit int) (pdus map[*receipt.Receipt]*gomatrixserverlib.HeaderedEvent, err error) GetPendingPDUs(ctx context.Context, serverName spec.ServerName, limit int) (pdus map[*receipt.Receipt]*gomatrixserverlib.HeaderedEvent, err error)
GetPendingEDUs(ctx context.Context, serverName gomatrixserverlib.ServerName, limit int) (edus map[*receipt.Receipt]*gomatrixserverlib.EDU, err error) GetPendingEDUs(ctx context.Context, serverName spec.ServerName, limit int) (edus map[*receipt.Receipt]*gomatrixserverlib.EDU, err error)
AssociatePDUWithDestinations(ctx context.Context, destinations map[gomatrixserverlib.ServerName]struct{}, dbReceipt *receipt.Receipt) error AssociatePDUWithDestinations(ctx context.Context, destinations map[spec.ServerName]struct{}, dbReceipt *receipt.Receipt) error
AssociateEDUWithDestinations(ctx context.Context, destinations map[gomatrixserverlib.ServerName]struct{}, dbReceipt *receipt.Receipt, eduType string, expireEDUTypes map[string]time.Duration) error AssociateEDUWithDestinations(ctx context.Context, destinations map[spec.ServerName]struct{}, dbReceipt *receipt.Receipt, eduType string, expireEDUTypes map[string]time.Duration) error
CleanPDUs(ctx context.Context, serverName gomatrixserverlib.ServerName, receipts []*receipt.Receipt) error CleanPDUs(ctx context.Context, serverName spec.ServerName, receipts []*receipt.Receipt) error
CleanEDUs(ctx context.Context, serverName gomatrixserverlib.ServerName, receipts []*receipt.Receipt) error CleanEDUs(ctx context.Context, serverName spec.ServerName, receipts []*receipt.Receipt) error
GetPendingPDUServerNames(ctx context.Context) ([]gomatrixserverlib.ServerName, error) GetPendingPDUServerNames(ctx context.Context) ([]spec.ServerName, error)
GetPendingEDUServerNames(ctx context.Context) ([]gomatrixserverlib.ServerName, error) GetPendingEDUServerNames(ctx context.Context) ([]spec.ServerName, error)
// these don't have contexts passed in as we want things to happen regardless of the request context // these don't have contexts passed in as we want things to happen regardless of the request context
AddServerToBlacklist(serverName gomatrixserverlib.ServerName) error AddServerToBlacklist(serverName spec.ServerName) error
RemoveServerFromBlacklist(serverName gomatrixserverlib.ServerName) error RemoveServerFromBlacklist(serverName spec.ServerName) error
RemoveAllServersFromBlacklist() error RemoveAllServersFromBlacklist() error
IsServerBlacklisted(serverName gomatrixserverlib.ServerName) (bool, error) IsServerBlacklisted(serverName spec.ServerName) (bool, error)
// Adds the server to the list of assumed offline servers. // Adds the server to the list of assumed offline servers.
// If the server already exists in the table, nothing happens and returns success. // If the server already exists in the table, nothing happens and returns success.
SetServerAssumedOffline(ctx context.Context, serverName gomatrixserverlib.ServerName) error SetServerAssumedOffline(ctx context.Context, serverName spec.ServerName) error
// Removes the server from the list of assumed offline servers. // Removes the server from the list of assumed offline servers.
// If the server doesn't exist in the table, nothing happens and returns success. // If the server doesn't exist in the table, nothing happens and returns success.
RemoveServerAssumedOffline(ctx context.Context, serverName gomatrixserverlib.ServerName) error RemoveServerAssumedOffline(ctx context.Context, serverName spec.ServerName) error
// Purges all entries from the assumed offline table. // Purges all entries from the assumed offline table.
RemoveAllServersAssumedOffline(ctx context.Context) error RemoveAllServersAssumedOffline(ctx context.Context) error
// Gets whether the provided server is present in the table. // Gets whether the provided server is present in the table.
// If it is present, returns true. If not, returns false. // If it is present, returns true. If not, returns false.
IsServerAssumedOffline(ctx context.Context, serverName gomatrixserverlib.ServerName) (bool, error) IsServerAssumedOffline(ctx context.Context, serverName spec.ServerName) (bool, error)
AddOutboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64) error AddOutboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string, renewalInterval int64) error
RenewOutboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64) error RenewOutboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string, renewalInterval int64) error
GetOutboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string) (*types.OutboundPeek, error) GetOutboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string) (*types.OutboundPeek, error)
GetOutboundPeeks(ctx context.Context, roomID string) ([]types.OutboundPeek, error) GetOutboundPeeks(ctx context.Context, roomID string) ([]types.OutboundPeek, error)
AddInboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64) error AddInboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string, renewalInterval int64) error
RenewInboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64) error RenewInboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string, renewalInterval int64) error
GetInboundPeek(ctx context.Context, serverName gomatrixserverlib.ServerName, roomID, peekID string) (*types.InboundPeek, error) GetInboundPeek(ctx context.Context, serverName spec.ServerName, roomID, peekID string) (*types.InboundPeek, error)
GetInboundPeeks(ctx context.Context, roomID string) ([]types.InboundPeek, error) GetInboundPeeks(ctx context.Context, roomID string) ([]types.InboundPeek, error)
// Update the notary with the given server keys from the given server name. // Update the notary with the given server keys from the given server name.
UpdateNotaryKeys(ctx context.Context, serverName gomatrixserverlib.ServerName, serverKeys gomatrixserverlib.ServerKeys) error UpdateNotaryKeys(ctx context.Context, serverName spec.ServerName, serverKeys gomatrixserverlib.ServerKeys) error
// Query the notary for the server keys for the given server. If `optKeyIDs` is not empty, multiple server keys may be returned (between 1 - len(optKeyIDs)) // Query the notary for the server keys for the given server. If `optKeyIDs` is not empty, multiple server keys may be returned (between 1 - len(optKeyIDs))
// such that the combination of all server keys will include all the `optKeyIDs`. // such that the combination of all server keys will include all the `optKeyIDs`.
GetNotaryKeys(ctx context.Context, serverName gomatrixserverlib.ServerName, optKeyIDs []gomatrixserverlib.KeyID) ([]gomatrixserverlib.ServerKeys, error) GetNotaryKeys(ctx context.Context, serverName spec.ServerName, optKeyIDs []gomatrixserverlib.KeyID) ([]gomatrixserverlib.ServerKeys, error)
// DeleteExpiredEDUs cleans up expired EDUs // DeleteExpiredEDUs cleans up expired EDUs
DeleteExpiredEDUs(ctx context.Context) error DeleteExpiredEDUs(ctx context.Context) error
@ -91,17 +92,17 @@ type Database interface {
type P2PDatabase interface { type P2PDatabase interface {
// Stores the given list of servers as relay servers for the provided destination server. // Stores the given list of servers as relay servers for the provided destination server.
// Providing duplicates will only lead to a single entry and won't lead to an error. // Providing duplicates will only lead to a single entry and won't lead to an error.
P2PAddRelayServersForServer(ctx context.Context, serverName gomatrixserverlib.ServerName, relayServers []gomatrixserverlib.ServerName) error P2PAddRelayServersForServer(ctx context.Context, serverName spec.ServerName, relayServers []spec.ServerName) error
// Get the list of relay servers associated with the provided destination server. // Get the list of relay servers associated with the provided destination server.
// If no entry exists in the table, an empty list is returned and does not result in an error. // If no entry exists in the table, an empty list is returned and does not result in an error.
P2PGetRelayServersForServer(ctx context.Context, serverName gomatrixserverlib.ServerName) ([]gomatrixserverlib.ServerName, error) P2PGetRelayServersForServer(ctx context.Context, serverName spec.ServerName) ([]spec.ServerName, error)
// Deletes any entries for the provided destination server that match the provided relayServers list. // Deletes any entries for the provided destination server that match the provided relayServers list.
// If any of the provided servers don't match an entry, nothing happens and no error is returned. // If any of the provided servers don't match an entry, nothing happens and no error is returned.
P2PRemoveRelayServersForServer(ctx context.Context, serverName gomatrixserverlib.ServerName, relayServers []gomatrixserverlib.ServerName) error P2PRemoveRelayServersForServer(ctx context.Context, serverName spec.ServerName, relayServers []spec.ServerName) error
// Deletes all entries for the provided destination server. // Deletes all entries for the provided destination server.
// If the destination server doesn't exist in the table, nothing happens and no error is returned. // If the destination server doesn't exist in the table, nothing happens and no error is returned.
P2PRemoveAllRelayServersForServer(ctx context.Context, serverName gomatrixserverlib.ServerName) error P2PRemoveAllRelayServersForServer(ctx context.Context, serverName spec.ServerName) error
} }

View File

@ -19,7 +19,7 @@ import (
"database/sql" "database/sql"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const assumedOfflineSchema = ` const assumedOfflineSchema = `
@ -68,7 +68,7 @@ func NewPostgresAssumedOfflineTable(db *sql.DB) (s *assumedOfflineStatements, er
} }
func (s *assumedOfflineStatements) InsertAssumedOffline( func (s *assumedOfflineStatements) InsertAssumedOffline(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.insertAssumedOfflineStmt) stmt := sqlutil.TxStmt(txn, s.insertAssumedOfflineStmt)
_, err := stmt.ExecContext(ctx, serverName) _, err := stmt.ExecContext(ctx, serverName)
@ -76,7 +76,7 @@ func (s *assumedOfflineStatements) InsertAssumedOffline(
} }
func (s *assumedOfflineStatements) SelectAssumedOffline( func (s *assumedOfflineStatements) SelectAssumedOffline(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) (bool, error) { ) (bool, error) {
stmt := sqlutil.TxStmt(txn, s.selectAssumedOfflineStmt) stmt := sqlutil.TxStmt(txn, s.selectAssumedOfflineStmt)
res, err := stmt.QueryContext(ctx, serverName) res, err := stmt.QueryContext(ctx, serverName)
@ -91,7 +91,7 @@ func (s *assumedOfflineStatements) SelectAssumedOffline(
} }
func (s *assumedOfflineStatements) DeleteAssumedOffline( func (s *assumedOfflineStatements) DeleteAssumedOffline(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteAssumedOfflineStmt) stmt := sqlutil.TxStmt(txn, s.deleteAssumedOfflineStmt)
_, err := stmt.ExecContext(ctx, serverName) _, err := stmt.ExecContext(ctx, serverName)

View File

@ -19,7 +19,7 @@ import (
"database/sql" "database/sql"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const blacklistSchema = ` const blacklistSchema = `
@ -69,7 +69,7 @@ func NewPostgresBlacklistTable(db *sql.DB) (s *blacklistStatements, err error) {
} }
func (s *blacklistStatements) InsertBlacklist( func (s *blacklistStatements) InsertBlacklist(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.insertBlacklistStmt) stmt := sqlutil.TxStmt(txn, s.insertBlacklistStmt)
_, err := stmt.ExecContext(ctx, serverName) _, err := stmt.ExecContext(ctx, serverName)
@ -77,7 +77,7 @@ func (s *blacklistStatements) InsertBlacklist(
} }
func (s *blacklistStatements) SelectBlacklist( func (s *blacklistStatements) SelectBlacklist(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) (bool, error) { ) (bool, error) {
stmt := sqlutil.TxStmt(txn, s.selectBlacklistStmt) stmt := sqlutil.TxStmt(txn, s.selectBlacklistStmt)
res, err := stmt.QueryContext(ctx, serverName) res, err := stmt.QueryContext(ctx, serverName)
@ -92,7 +92,7 @@ func (s *blacklistStatements) SelectBlacklist(
} }
func (s *blacklistStatements) DeleteBlacklist( func (s *blacklistStatements) DeleteBlacklist(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, ctx context.Context, txn *sql.Tx, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteBlacklistStmt) stmt := sqlutil.TxStmt(txn, s.deleteBlacklistStmt)
_, err := stmt.ExecContext(ctx, serverName) _, err := stmt.ExecContext(ctx, serverName)

View File

@ -20,7 +20,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
func UpAddexpiresat(ctx context.Context, tx *sql.Tx) error { func UpAddexpiresat(ctx context.Context, tx *sql.Tx) error {
@ -28,7 +28,7 @@ func UpAddexpiresat(ctx context.Context, tx *sql.Tx) error {
if err != nil { if err != nil {
return fmt.Errorf("failed to execute upgrade: %w", err) return fmt.Errorf("failed to execute upgrade: %w", err)
} }
_, err = tx.ExecContext(ctx, "UPDATE federationsender_queue_edus SET expires_at = $1 WHERE edu_type != 'm.direct_to_device'", gomatrixserverlib.AsTimestamp(time.Now().Add(time.Hour*24))) _, err = tx.ExecContext(ctx, "UPDATE federationsender_queue_edus SET expires_at = $1 WHERE edu_type != 'm.direct_to_device'", spec.AsTimestamp(time.Now().Add(time.Hour*24)))
if err != nil { if err != nil {
return fmt.Errorf("failed to update queue_edus: %w", err) return fmt.Errorf("failed to update queue_edus: %w", err)
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const inboundPeeksSchema = ` const inboundPeeksSchema = `
@ -86,7 +86,7 @@ func NewPostgresInboundPeeksTable(db *sql.DB) (s *inboundPeeksStatements, err er
} }
func (s *inboundPeeksStatements) InsertInboundPeek( func (s *inboundPeeksStatements) InsertInboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string, renewalInterval int64,
) (err error) { ) (err error) {
nowMilli := time.Now().UnixNano() / int64(time.Millisecond) nowMilli := time.Now().UnixNano() / int64(time.Millisecond)
stmt := sqlutil.TxStmt(txn, s.insertInboundPeekStmt) stmt := sqlutil.TxStmt(txn, s.insertInboundPeekStmt)
@ -95,7 +95,7 @@ func (s *inboundPeeksStatements) InsertInboundPeek(
} }
func (s *inboundPeeksStatements) RenewInboundPeek( func (s *inboundPeeksStatements) RenewInboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string, renewalInterval int64,
) (err error) { ) (err error) {
nowMilli := time.Now().UnixNano() / int64(time.Millisecond) nowMilli := time.Now().UnixNano() / int64(time.Millisecond)
_, err = sqlutil.TxStmt(txn, s.renewInboundPeekStmt).ExecContext(ctx, nowMilli, renewalInterval, roomID, serverName, peekID) _, err = sqlutil.TxStmt(txn, s.renewInboundPeekStmt).ExecContext(ctx, nowMilli, renewalInterval, roomID, serverName, peekID)
@ -103,7 +103,7 @@ func (s *inboundPeeksStatements) RenewInboundPeek(
} }
func (s *inboundPeeksStatements) SelectInboundPeek( func (s *inboundPeeksStatements) SelectInboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string,
) (*types.InboundPeek, error) { ) (*types.InboundPeek, error) {
row := sqlutil.TxStmt(txn, s.selectInboundPeeksStmt).QueryRowContext(ctx, roomID) row := sqlutil.TxStmt(txn, s.selectInboundPeeksStmt).QueryRowContext(ctx, roomID)
inboundPeek := types.InboundPeek{} inboundPeek := types.InboundPeek{}
@ -152,7 +152,7 @@ func (s *inboundPeeksStatements) SelectInboundPeeks(
} }
func (s *inboundPeeksStatements) DeleteInboundPeek( func (s *inboundPeeksStatements) DeleteInboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string,
) (err error) { ) (err error) {
_, err = sqlutil.TxStmt(txn, s.deleteInboundPeekStmt).ExecContext(ctx, roomID, serverName, peekID) _, err = sqlutil.TxStmt(txn, s.deleteInboundPeekStmt).ExecContext(ctx, roomID, serverName, peekID)
return return

View File

@ -23,7 +23,7 @@ import (
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const joinedHostsSchema = ` const joinedHostsSchema = `
@ -105,7 +105,7 @@ func (s *joinedHostsStatements) InsertJoinedHosts(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
roomID, eventID string, roomID, eventID string,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.insertJoinedHostsStmt) stmt := sqlutil.TxStmt(txn, s.insertJoinedHostsStmt)
_, err := stmt.ExecContext(ctx, roomID, eventID, serverName) _, err := stmt.ExecContext(ctx, roomID, eventID, serverName)
@ -143,20 +143,20 @@ func (s *joinedHostsStatements) SelectJoinedHosts(
func (s *joinedHostsStatements) SelectAllJoinedHosts( func (s *joinedHostsStatements) SelectAllJoinedHosts(
ctx context.Context, ctx context.Context,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
rows, err := s.selectAllJoinedHostsStmt.QueryContext(ctx) rows, err := s.selectAllJoinedHostsStmt.QueryContext(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer internal.CloseAndLogIfError(ctx, rows, "selectAllJoinedHosts: rows.close() failed") defer internal.CloseAndLogIfError(ctx, rows, "selectAllJoinedHosts: rows.close() failed")
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for rows.Next() { for rows.Next() {
var serverName string var serverName string
if err = rows.Scan(&serverName); err != nil { if err = rows.Scan(&serverName); err != nil {
return nil, err return nil, err
} }
result = append(result, gomatrixserverlib.ServerName(serverName)) result = append(result, spec.ServerName(serverName))
} }
return result, rows.Err() return result, rows.Err()
@ -164,7 +164,7 @@ func (s *joinedHostsStatements) SelectAllJoinedHosts(
func (s *joinedHostsStatements) SelectJoinedHostsForRooms( func (s *joinedHostsStatements) SelectJoinedHostsForRooms(
ctx context.Context, roomIDs []string, excludingBlacklisted bool, ctx context.Context, roomIDs []string, excludingBlacklisted bool,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
stmt := s.selectJoinedHostsForRoomsStmt stmt := s.selectJoinedHostsForRoomsStmt
if excludingBlacklisted { if excludingBlacklisted {
stmt = s.selectJoinedHostsForRoomsExcludingBlacklistedStmt stmt = s.selectJoinedHostsForRoomsExcludingBlacklistedStmt
@ -175,13 +175,13 @@ func (s *joinedHostsStatements) SelectJoinedHostsForRooms(
} }
defer internal.CloseAndLogIfError(ctx, rows, "selectJoinedHostsForRoomsStmt: rows.close() failed") defer internal.CloseAndLogIfError(ctx, rows, "selectJoinedHostsForRoomsStmt: rows.close() failed")
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for rows.Next() { for rows.Next() {
var serverName string var serverName string
if err = rows.Scan(&serverName); err != nil { if err = rows.Scan(&serverName); err != nil {
return nil, err return nil, err
} }
result = append(result, gomatrixserverlib.ServerName(serverName)) result = append(result, spec.ServerName(serverName))
} }
return result, rows.Err() return result, rows.Err()
@ -204,7 +204,7 @@ func joinedHostsFromStmt(
} }
result = append(result, types.JoinedHost{ result = append(result, types.JoinedHost{
MemberEventID: eventID, MemberEventID: eventID,
ServerName: gomatrixserverlib.ServerName(serverName), ServerName: spec.ServerName(serverName),
}) })
} }

View File

@ -21,6 +21,7 @@ import (
"github.com/matrix-org/dendrite/federationapi/storage/tables" "github.com/matrix-org/dendrite/federationapi/storage/tables"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const notaryServerKeysJSONSchema = ` const notaryServerKeysJSONSchema = `
@ -57,7 +58,7 @@ func NewPostgresNotaryServerKeysTable(db *sql.DB) (s *notaryServerKeysStatements
} }
func (s *notaryServerKeysStatements) InsertJSONResponse( func (s *notaryServerKeysStatements) InsertJSONResponse(
ctx context.Context, txn *sql.Tx, keyQueryResponseJSON gomatrixserverlib.ServerKeys, serverName gomatrixserverlib.ServerName, validUntil gomatrixserverlib.Timestamp, ctx context.Context, txn *sql.Tx, keyQueryResponseJSON gomatrixserverlib.ServerKeys, serverName spec.ServerName, validUntil spec.Timestamp,
) (tables.NotaryID, error) { ) (tables.NotaryID, error) {
var notaryID tables.NotaryID var notaryID tables.NotaryID
return notaryID, txn.Stmt(s.insertServerKeysJSONStmt).QueryRowContext(ctx, string(keyQueryResponseJSON.Raw), serverName, validUntil).Scan(&notaryID) return notaryID, txn.Stmt(s.insertServerKeysJSONStmt).QueryRowContext(ctx, string(keyQueryResponseJSON.Raw), serverName, validUntil).Scan(&notaryID)

View File

@ -24,6 +24,7 @@ import (
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const notaryServerKeysMetadataSchema = ` const notaryServerKeysMetadataSchema = `
@ -102,12 +103,12 @@ func NewPostgresNotaryServerKeysMetadataTable(db *sql.DB) (s *notaryServerKeysMe
} }
func (s *notaryServerKeysMetadataStatements) UpsertKey( func (s *notaryServerKeysMetadataStatements) UpsertKey(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, keyID gomatrixserverlib.KeyID, newNotaryID tables.NotaryID, newValidUntil gomatrixserverlib.Timestamp, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, keyID gomatrixserverlib.KeyID, newNotaryID tables.NotaryID, newValidUntil spec.Timestamp,
) (tables.NotaryID, error) { ) (tables.NotaryID, error) {
notaryID := newNotaryID notaryID := newNotaryID
// see if the existing notary ID a) exists, b) has a longer valid_until // see if the existing notary ID a) exists, b) has a longer valid_until
var existingNotaryID tables.NotaryID var existingNotaryID tables.NotaryID
var existingValidUntil gomatrixserverlib.Timestamp var existingValidUntil spec.Timestamp
if err := txn.Stmt(s.selectNotaryKeyMetadataStmt).QueryRowContext(ctx, serverName, keyID).Scan(&existingNotaryID, &existingValidUntil); err != nil { if err := txn.Stmt(s.selectNotaryKeyMetadataStmt).QueryRowContext(ctx, serverName, keyID).Scan(&existingNotaryID, &existingValidUntil); err != nil {
if err != sql.ErrNoRows { if err != sql.ErrNoRows {
return 0, err return 0, err
@ -122,7 +123,7 @@ func (s *notaryServerKeysMetadataStatements) UpsertKey(
return notaryID, err return notaryID, err
} }
func (s *notaryServerKeysMetadataStatements) SelectKeys(ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, keyIDs []gomatrixserverlib.KeyID) ([]gomatrixserverlib.ServerKeys, error) { func (s *notaryServerKeysMetadataStatements) SelectKeys(ctx context.Context, txn *sql.Tx, serverName spec.ServerName, keyIDs []gomatrixserverlib.KeyID) ([]gomatrixserverlib.ServerKeys, error) {
var rows *sql.Rows var rows *sql.Rows
var err error var err error
if len(keyIDs) == 0 { if len(keyIDs) == 0 {

View File

@ -22,7 +22,7 @@ import (
"github.com/matrix-org/dendrite/federationapi/types" "github.com/matrix-org/dendrite/federationapi/types"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const outboundPeeksSchema = ` const outboundPeeksSchema = `
@ -85,7 +85,7 @@ func NewPostgresOutboundPeeksTable(db *sql.DB) (s *outboundPeeksStatements, err
} }
func (s *outboundPeeksStatements) InsertOutboundPeek( func (s *outboundPeeksStatements) InsertOutboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string, renewalInterval int64,
) (err error) { ) (err error) {
nowMilli := time.Now().UnixNano() / int64(time.Millisecond) nowMilli := time.Now().UnixNano() / int64(time.Millisecond)
stmt := sqlutil.TxStmt(txn, s.insertOutboundPeekStmt) stmt := sqlutil.TxStmt(txn, s.insertOutboundPeekStmt)
@ -94,7 +94,7 @@ func (s *outboundPeeksStatements) InsertOutboundPeek(
} }
func (s *outboundPeeksStatements) RenewOutboundPeek( func (s *outboundPeeksStatements) RenewOutboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, renewalInterval int64, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string, renewalInterval int64,
) (err error) { ) (err error) {
nowMilli := time.Now().UnixNano() / int64(time.Millisecond) nowMilli := time.Now().UnixNano() / int64(time.Millisecond)
_, err = sqlutil.TxStmt(txn, s.renewOutboundPeekStmt).ExecContext(ctx, nowMilli, renewalInterval, roomID, serverName, peekID) _, err = sqlutil.TxStmt(txn, s.renewOutboundPeekStmt).ExecContext(ctx, nowMilli, renewalInterval, roomID, serverName, peekID)
@ -102,7 +102,7 @@ func (s *outboundPeeksStatements) RenewOutboundPeek(
} }
func (s *outboundPeeksStatements) SelectOutboundPeek( func (s *outboundPeeksStatements) SelectOutboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string,
) (*types.OutboundPeek, error) { ) (*types.OutboundPeek, error) {
row := sqlutil.TxStmt(txn, s.selectOutboundPeeksStmt).QueryRowContext(ctx, roomID) row := sqlutil.TxStmt(txn, s.selectOutboundPeeksStmt).QueryRowContext(ctx, roomID)
outboundPeek := types.OutboundPeek{} outboundPeek := types.OutboundPeek{}
@ -151,7 +151,7 @@ func (s *outboundPeeksStatements) SelectOutboundPeeks(
} }
func (s *outboundPeeksStatements) DeleteOutboundPeek( func (s *outboundPeeksStatements) DeleteOutboundPeek(
ctx context.Context, txn *sql.Tx, serverName gomatrixserverlib.ServerName, roomID, peekID string, ctx context.Context, txn *sql.Tx, serverName spec.ServerName, roomID, peekID string,
) (err error) { ) (err error) {
_, err = sqlutil.TxStmt(txn, s.deleteOutboundPeekStmt).ExecContext(ctx, roomID, serverName, peekID) _, err = sqlutil.TxStmt(txn, s.deleteOutboundPeekStmt).ExecContext(ctx, roomID, serverName, peekID)
return return

View File

@ -19,11 +19,11 @@ import (
"database/sql" "database/sql"
"github.com/lib/pq" "github.com/lib/pq"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/dendrite/federationapi/storage/postgres/deltas" "github.com/matrix-org/dendrite/federationapi/storage/postgres/deltas"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const queueEDUsSchema = ` const queueEDUsSchema = `
@ -121,9 +121,9 @@ func (s *queueEDUsStatements) InsertQueueEDU(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
eduType string, eduType string,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
nid int64, nid int64,
expiresAt gomatrixserverlib.Timestamp, expiresAt spec.Timestamp,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.insertQueueEDUStmt) stmt := sqlutil.TxStmt(txn, s.insertQueueEDUStmt)
_, err := stmt.ExecContext( _, err := stmt.ExecContext(
@ -138,7 +138,7 @@ func (s *queueEDUsStatements) InsertQueueEDU(
func (s *queueEDUsStatements) DeleteQueueEDUs( func (s *queueEDUsStatements) DeleteQueueEDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
jsonNIDs []int64, jsonNIDs []int64,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteQueueEDUStmt) stmt := sqlutil.TxStmt(txn, s.deleteQueueEDUStmt)
@ -148,7 +148,7 @@ func (s *queueEDUsStatements) DeleteQueueEDUs(
func (s *queueEDUsStatements) SelectQueueEDUs( func (s *queueEDUsStatements) SelectQueueEDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
limit int, limit int,
) ([]int64, error) { ) ([]int64, error) {
stmt := sqlutil.TxStmt(txn, s.selectQueueEDUStmt) stmt := sqlutil.TxStmt(txn, s.selectQueueEDUStmt)
@ -182,16 +182,16 @@ func (s *queueEDUsStatements) SelectQueueEDUReferenceJSONCount(
func (s *queueEDUsStatements) SelectQueueEDUServerNames( func (s *queueEDUsStatements) SelectQueueEDUServerNames(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
stmt := sqlutil.TxStmt(txn, s.selectQueueEDUServerNamesStmt) stmt := sqlutil.TxStmt(txn, s.selectQueueEDUServerNamesStmt)
rows, err := stmt.QueryContext(ctx) rows, err := stmt.QueryContext(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer internal.CloseAndLogIfError(ctx, rows, "queueFromStmt: rows.close() failed") defer internal.CloseAndLogIfError(ctx, rows, "queueFromStmt: rows.close() failed")
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for rows.Next() { for rows.Next() {
var serverName gomatrixserverlib.ServerName var serverName spec.ServerName
if err = rows.Scan(&serverName); err != nil { if err = rows.Scan(&serverName); err != nil {
return nil, err return nil, err
} }
@ -203,7 +203,7 @@ func (s *queueEDUsStatements) SelectQueueEDUServerNames(
func (s *queueEDUsStatements) SelectExpiredEDUs( func (s *queueEDUsStatements) SelectExpiredEDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
expiredBefore gomatrixserverlib.Timestamp, expiredBefore spec.Timestamp,
) ([]int64, error) { ) ([]int64, error) {
stmt := sqlutil.TxStmt(txn, s.selectExpiredEDUsStmt) stmt := sqlutil.TxStmt(txn, s.selectExpiredEDUsStmt)
rows, err := stmt.QueryContext(ctx, expiredBefore) rows, err := stmt.QueryContext(ctx, expiredBefore)
@ -224,7 +224,7 @@ func (s *queueEDUsStatements) SelectExpiredEDUs(
func (s *queueEDUsStatements) DeleteExpiredEDUs( func (s *queueEDUsStatements) DeleteExpiredEDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
expiredBefore gomatrixserverlib.Timestamp, expiredBefore spec.Timestamp,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteExpiredEDUsStmt) stmt := sqlutil.TxStmt(txn, s.deleteExpiredEDUsStmt)
_, err := stmt.ExecContext(ctx, expiredBefore) _, err := stmt.ExecContext(ctx, expiredBefore)

View File

@ -22,6 +22,7 @@ import (
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const queuePDUsSchema = ` const queuePDUsSchema = `
@ -91,7 +92,7 @@ func (s *queuePDUsStatements) InsertQueuePDU(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
transactionID gomatrixserverlib.TransactionID, transactionID gomatrixserverlib.TransactionID,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
nid int64, nid int64,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.insertQueuePDUStmt) stmt := sqlutil.TxStmt(txn, s.insertQueuePDUStmt)
@ -106,7 +107,7 @@ func (s *queuePDUsStatements) InsertQueuePDU(
func (s *queuePDUsStatements) DeleteQueuePDUs( func (s *queuePDUsStatements) DeleteQueuePDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
jsonNIDs []int64, jsonNIDs []int64,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteQueuePDUsStmt) stmt := sqlutil.TxStmt(txn, s.deleteQueuePDUsStmt)
@ -131,7 +132,7 @@ func (s *queuePDUsStatements) SelectQueuePDUReferenceJSONCount(
func (s *queuePDUsStatements) SelectQueuePDUs( func (s *queuePDUsStatements) SelectQueuePDUs(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
limit int, limit int,
) ([]int64, error) { ) ([]int64, error) {
stmt := sqlutil.TxStmt(txn, s.selectQueuePDUsStmt) stmt := sqlutil.TxStmt(txn, s.selectQueuePDUsStmt)
@ -154,16 +155,16 @@ func (s *queuePDUsStatements) SelectQueuePDUs(
func (s *queuePDUsStatements) SelectQueuePDUServerNames( func (s *queuePDUsStatements) SelectQueuePDUServerNames(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
stmt := sqlutil.TxStmt(txn, s.selectQueuePDUServerNamesStmt) stmt := sqlutil.TxStmt(txn, s.selectQueuePDUServerNamesStmt)
rows, err := stmt.QueryContext(ctx) rows, err := stmt.QueryContext(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer internal.CloseAndLogIfError(ctx, rows, "queueFromStmt: rows.close() failed") defer internal.CloseAndLogIfError(ctx, rows, "queueFromStmt: rows.close() failed")
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for rows.Next() { for rows.Next() {
var serverName gomatrixserverlib.ServerName var serverName spec.ServerName
if err = rows.Scan(&serverName); err != nil { if err = rows.Scan(&serverName); err != nil {
return nil, err return nil, err
} }

View File

@ -21,7 +21,7 @@ import (
"github.com/lib/pq" "github.com/lib/pq"
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
const relayServersSchema = ` const relayServersSchema = `
@ -78,8 +78,8 @@ func NewPostgresRelayServersTable(db *sql.DB) (s *relayServersStatements, err er
func (s *relayServersStatements) InsertRelayServers( func (s *relayServersStatements) InsertRelayServers(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
relayServers []gomatrixserverlib.ServerName, relayServers []spec.ServerName,
) error { ) error {
for _, relayServer := range relayServers { for _, relayServer := range relayServers {
stmt := sqlutil.TxStmt(txn, s.insertRelayServersStmt) stmt := sqlutil.TxStmt(txn, s.insertRelayServersStmt)
@ -93,8 +93,8 @@ func (s *relayServersStatements) InsertRelayServers(
func (s *relayServersStatements) SelectRelayServers( func (s *relayServersStatements) SelectRelayServers(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
stmt := sqlutil.TxStmt(txn, s.selectRelayServersStmt) stmt := sqlutil.TxStmt(txn, s.selectRelayServersStmt)
rows, err := stmt.QueryContext(ctx, serverName) rows, err := stmt.QueryContext(ctx, serverName)
if err != nil { if err != nil {
@ -102,13 +102,13 @@ func (s *relayServersStatements) SelectRelayServers(
} }
defer internal.CloseAndLogIfError(ctx, rows, "SelectRelayServers: rows.close() failed") defer internal.CloseAndLogIfError(ctx, rows, "SelectRelayServers: rows.close() failed")
var result []gomatrixserverlib.ServerName var result []spec.ServerName
for rows.Next() { for rows.Next() {
var relayServer string var relayServer string
if err = rows.Scan(&relayServer); err != nil { if err = rows.Scan(&relayServer); err != nil {
return nil, err return nil, err
} }
result = append(result, gomatrixserverlib.ServerName(relayServer)) result = append(result, spec.ServerName(relayServer))
} }
return result, nil return result, nil
} }
@ -116,8 +116,8 @@ func (s *relayServersStatements) SelectRelayServers(
func (s *relayServersStatements) DeleteRelayServers( func (s *relayServersStatements) DeleteRelayServers(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
relayServers []gomatrixserverlib.ServerName, relayServers []spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteRelayServersStmt) stmt := sqlutil.TxStmt(txn, s.deleteRelayServersStmt)
_, err := stmt.ExecContext(ctx, serverName, pq.Array(relayServers)) _, err := stmt.ExecContext(ctx, serverName, pq.Array(relayServers))
@ -127,7 +127,7 @@ func (s *relayServersStatements) DeleteRelayServers(
func (s *relayServersStatements) DeleteAllRelayServers( func (s *relayServersStatements) DeleteAllRelayServers(
ctx context.Context, ctx context.Context,
txn *sql.Tx, txn *sql.Tx,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
stmt := sqlutil.TxStmt(txn, s.deleteAllRelayServersStmt) stmt := sqlutil.TxStmt(txn, s.deleteAllRelayServersStmt)
if _, err := stmt.ExecContext(ctx, serverName); err != nil { if _, err := stmt.ExecContext(ctx, serverName); err != nil {

View File

@ -23,6 +23,7 @@ import (
"github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
const serverSigningKeysSchema = ` const serverSigningKeysSchema = `
@ -80,7 +81,7 @@ func NewPostgresServerSigningKeysTable(db *sql.DB) (s *serverSigningKeyStatement
func (s *serverSigningKeyStatements) BulkSelectServerKeys( func (s *serverSigningKeyStatements) BulkSelectServerKeys(
ctx context.Context, txn *sql.Tx, ctx context.Context, txn *sql.Tx,
requests map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp, requests map[gomatrixserverlib.PublicKeyLookupRequest]spec.Timestamp,
) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) { ) (map[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.PublicKeyLookupResult, error) {
var nameAndKeyIDs []string var nameAndKeyIDs []string
for request := range requests { for request := range requests {
@ -103,7 +104,7 @@ func (s *serverSigningKeyStatements) BulkSelectServerKeys(
return nil, err return nil, err
} }
r := gomatrixserverlib.PublicKeyLookupRequest{ r := gomatrixserverlib.PublicKeyLookupRequest{
ServerName: gomatrixserverlib.ServerName(serverName), ServerName: spec.ServerName(serverName),
KeyID: gomatrixserverlib.KeyID(keyID), KeyID: gomatrixserverlib.KeyID(keyID),
} }
vk := gomatrixserverlib.VerifyKey{} vk := gomatrixserverlib.VerifyKey{}
@ -113,8 +114,8 @@ func (s *serverSigningKeyStatements) BulkSelectServerKeys(
} }
results[r] = gomatrixserverlib.PublicKeyLookupResult{ results[r] = gomatrixserverlib.PublicKeyLookupResult{
VerifyKey: vk, VerifyKey: vk,
ValidUntilTS: gomatrixserverlib.Timestamp(validUntilTS), ValidUntilTS: spec.Timestamp(validUntilTS),
ExpiredTS: gomatrixserverlib.Timestamp(expiredTS), ExpiredTS: spec.Timestamp(expiredTS),
} }
} }
return results, rows.Err() return results, rows.Err()

View File

@ -25,7 +25,7 @@ import (
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib/spec"
) )
// Database stores information needed by the federation sender // Database stores information needed by the federation sender
@ -36,7 +36,7 @@ type Database struct {
} }
// NewDatabase opens a new database // NewDatabase opens a new database
func NewDatabase(ctx context.Context, conMan sqlutil.Connections, dbProperties *config.DatabaseOptions, cache caching.FederationCache, isLocalServerName func(gomatrixserverlib.ServerName) bool) (*Database, error) { func NewDatabase(ctx context.Context, conMan sqlutil.Connections, dbProperties *config.DatabaseOptions, cache caching.FederationCache, isLocalServerName func(spec.ServerName) bool) (*Database, error) {
var d Database var d Database
var err error var err error
if d.db, d.writer, err = conMan.Connection(dbProperties); err != nil { if d.db, d.writer, err = conMan.Connection(dbProperties); err != nil {

View File

@ -26,11 +26,12 @@ import (
"github.com/matrix-org/dendrite/internal/caching" "github.com/matrix-org/dendrite/internal/caching"
"github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/spec"
) )
type Database struct { type Database struct {
DB *sql.DB DB *sql.DB
IsLocalServerName func(gomatrixserverlib.ServerName) bool IsLocalServerName func(spec.ServerName) bool
Cache caching.FederationCache Cache caching.FederationCache
Writer sqlutil.Writer Writer sqlutil.Writer
FederationQueuePDUs tables.FederationQueuePDUs FederationQueuePDUs tables.FederationQueuePDUs
@ -102,7 +103,7 @@ func (d *Database) GetJoinedHosts(
// Returns an error if something goes wrong. // Returns an error if something goes wrong.
func (d *Database) GetAllJoinedHosts( func (d *Database) GetAllJoinedHosts(
ctx context.Context, ctx context.Context,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
return d.FederationJoinedHosts.SelectAllJoinedHosts(ctx) return d.FederationJoinedHosts.SelectAllJoinedHosts(ctx)
} }
@ -111,7 +112,7 @@ func (d *Database) GetJoinedHostsForRooms(
roomIDs []string, roomIDs []string,
excludeSelf, excludeSelf,
excludeBlacklisted bool, excludeBlacklisted bool,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
servers, err := d.FederationJoinedHosts.SelectJoinedHostsForRooms(ctx, roomIDs, excludeBlacklisted) servers, err := d.FederationJoinedHosts.SelectJoinedHostsForRooms(ctx, roomIDs, excludeBlacklisted)
if err != nil { if err != nil {
return nil, err return nil, err
@ -148,7 +149,7 @@ func (d *Database) StoreJSON(
} }
func (d *Database) AddServerToBlacklist( func (d *Database) AddServerToBlacklist(
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationBlacklist.InsertBlacklist(context.TODO(), txn, serverName) return d.FederationBlacklist.InsertBlacklist(context.TODO(), txn, serverName)
@ -156,7 +157,7 @@ func (d *Database) AddServerToBlacklist(
} }
func (d *Database) RemoveServerFromBlacklist( func (d *Database) RemoveServerFromBlacklist(
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationBlacklist.DeleteBlacklist(context.TODO(), txn, serverName) return d.FederationBlacklist.DeleteBlacklist(context.TODO(), txn, serverName)
@ -170,14 +171,14 @@ func (d *Database) RemoveAllServersFromBlacklist() error {
} }
func (d *Database) IsServerBlacklisted( func (d *Database) IsServerBlacklisted(
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) (bool, error) { ) (bool, error) {
return d.FederationBlacklist.SelectBlacklist(context.TODO(), nil, serverName) return d.FederationBlacklist.SelectBlacklist(context.TODO(), nil, serverName)
} }
func (d *Database) SetServerAssumedOffline( func (d *Database) SetServerAssumedOffline(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationAssumedOffline.InsertAssumedOffline(ctx, txn, serverName) return d.FederationAssumedOffline.InsertAssumedOffline(ctx, txn, serverName)
@ -186,7 +187,7 @@ func (d *Database) SetServerAssumedOffline(
func (d *Database) RemoveServerAssumedOffline( func (d *Database) RemoveServerAssumedOffline(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationAssumedOffline.DeleteAssumedOffline(ctx, txn, serverName) return d.FederationAssumedOffline.DeleteAssumedOffline(ctx, txn, serverName)
@ -203,15 +204,15 @@ func (d *Database) RemoveAllServersAssumedOffline(
func (d *Database) IsServerAssumedOffline( func (d *Database) IsServerAssumedOffline(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) (bool, error) { ) (bool, error) {
return d.FederationAssumedOffline.SelectAssumedOffline(ctx, nil, serverName) return d.FederationAssumedOffline.SelectAssumedOffline(ctx, nil, serverName)
} }
func (d *Database) P2PAddRelayServersForServer( func (d *Database) P2PAddRelayServersForServer(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
relayServers []gomatrixserverlib.ServerName, relayServers []spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationRelayServers.InsertRelayServers(ctx, txn, serverName, relayServers) return d.FederationRelayServers.InsertRelayServers(ctx, txn, serverName, relayServers)
@ -220,15 +221,15 @@ func (d *Database) P2PAddRelayServersForServer(
func (d *Database) P2PGetRelayServersForServer( func (d *Database) P2PGetRelayServersForServer(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) ([]gomatrixserverlib.ServerName, error) { ) ([]spec.ServerName, error) {
return d.FederationRelayServers.SelectRelayServers(ctx, nil, serverName) return d.FederationRelayServers.SelectRelayServers(ctx, nil, serverName)
} }
func (d *Database) P2PRemoveRelayServersForServer( func (d *Database) P2PRemoveRelayServersForServer(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
relayServers []gomatrixserverlib.ServerName, relayServers []spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationRelayServers.DeleteRelayServers(ctx, txn, serverName, relayServers) return d.FederationRelayServers.DeleteRelayServers(ctx, txn, serverName, relayServers)
@ -237,7 +238,7 @@ func (d *Database) P2PRemoveRelayServersForServer(
func (d *Database) P2PRemoveAllRelayServersForServer( func (d *Database) P2PRemoveAllRelayServersForServer(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
return d.FederationRelayServers.DeleteAllRelayServers(ctx, txn, serverName) return d.FederationRelayServers.DeleteAllRelayServers(ctx, txn, serverName)
@ -246,7 +247,7 @@ func (d *Database) P2PRemoveAllRelayServersForServer(
func (d *Database) AddOutboundPeek( func (d *Database) AddOutboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID string, roomID string,
peekID string, peekID string,
renewalInterval int64, renewalInterval int64,
@ -258,7 +259,7 @@ func (d *Database) AddOutboundPeek(
func (d *Database) RenewOutboundPeek( func (d *Database) RenewOutboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID string, roomID string,
peekID string, peekID string,
renewalInterval int64, renewalInterval int64,
@ -270,7 +271,7 @@ func (d *Database) RenewOutboundPeek(
func (d *Database) GetOutboundPeek( func (d *Database) GetOutboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID, roomID,
peekID string, peekID string,
) (*types.OutboundPeek, error) { ) (*types.OutboundPeek, error) {
@ -286,7 +287,7 @@ func (d *Database) GetOutboundPeeks(
func (d *Database) AddInboundPeek( func (d *Database) AddInboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID string, roomID string,
peekID string, peekID string,
renewalInterval int64, renewalInterval int64,
@ -298,7 +299,7 @@ func (d *Database) AddInboundPeek(
func (d *Database) RenewInboundPeek( func (d *Database) RenewInboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID string, roomID string,
peekID string, peekID string,
renewalInterval int64, renewalInterval int64,
@ -310,7 +311,7 @@ func (d *Database) RenewInboundPeek(
func (d *Database) GetInboundPeek( func (d *Database) GetInboundPeek(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
roomID string, roomID string,
peekID string, peekID string,
) (*types.InboundPeek, error) { ) (*types.InboundPeek, error) {
@ -326,7 +327,7 @@ func (d *Database) GetInboundPeeks(
func (d *Database) UpdateNotaryKeys( func (d *Database) UpdateNotaryKeys(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
serverKeys gomatrixserverlib.ServerKeys, serverKeys gomatrixserverlib.ServerKeys,
) error { ) error {
return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { return d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {
@ -337,7 +338,7 @@ func (d *Database) UpdateNotaryKeys(
// https://spec.matrix.org/unstable/server-server-api/#querying-keys-through-another-server // https://spec.matrix.org/unstable/server-server-api/#querying-keys-through-another-server
weekIntoFuture := time.Now().Add(7 * 24 * time.Hour) weekIntoFuture := time.Now().Add(7 * 24 * time.Hour)
if weekIntoFuture.Before(validUntil.Time()) { if weekIntoFuture.Before(validUntil.Time()) {
validUntil = gomatrixserverlib.AsTimestamp(weekIntoFuture) validUntil = spec.AsTimestamp(weekIntoFuture)
} }
notaryID, err := d.NotaryServerKeysJSON.InsertJSONResponse(ctx, txn, serverKeys, serverName, validUntil) notaryID, err := d.NotaryServerKeysJSON.InsertJSONResponse(ctx, txn, serverKeys, serverName, validUntil)
if err != nil { if err != nil {
@ -364,7 +365,7 @@ func (d *Database) UpdateNotaryKeys(
func (d *Database) GetNotaryKeys( func (d *Database) GetNotaryKeys(
ctx context.Context, ctx context.Context,
serverName gomatrixserverlib.ServerName, serverName spec.ServerName,
optKeyIDs []gomatrixserverlib.KeyID, optKeyIDs []gomatrixserverlib.KeyID,
) (sks []gomatrixserverlib.ServerKeys, err error) { ) (sks []gomatrixserverlib.ServerKeys, err error) {
err = d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error { err = d.Writer.Do(d.DB, nil, func(txn *sql.Tx) error {

Some files were not shown because too many files have changed in this diff Show More