diff options
author | Ryan W <twentybitdev@gmail.com> | 2021-09-08 17:31:03 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-09-08 17:31:03 +0100 |
commit | a624eab309ee6ee7b3540dfba884a42c9a4f4ad9 (patch) | |
tree | 92ec39ba2d0f512891dcb20635ee9bc660b45b18 | |
parent | 7dc8fb1fe780888d5758bf665949e9e09d21e56a (diff) |
- Removed double imports (#1989)
- Lower cased error messages
Signed-off-by: Ryan Whittington <twentybitdev@gmail.com>
Co-authored-by: kegsay <kegan@matrix.org>
38 files changed, 162 insertions, 177 deletions
diff --git a/build/gobind-pinecone/monolith.go b/build/gobind-pinecone/monolith.go index 20228404..310e3a04 100644 --- a/build/gobind-pinecone/monolith.go +++ b/build/gobind-pinecone/monolith.go @@ -40,7 +40,6 @@ import ( "golang.org/x/net/http2/h2c" pineconeMulticast "github.com/matrix-org/pinecone/multicast" - "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router" pineconeSessions "github.com/matrix-org/pinecone/sessions" "github.com/matrix-org/pinecone/types" @@ -196,7 +195,7 @@ func (m *DendriteMonolith) RegisterDevice(localpart, deviceID string) (string, e func (m *DendriteMonolith) staticPeerConnect() { attempt := func() { - if m.PineconeRouter.PeerCount(router.PeerTypeRemote) == 0 { + if m.PineconeRouter.PeerCount(pineconeRouter.PeerTypeRemote) == 0 { m.staticPeerMutex.RLock() uri := m.staticPeerURI m.staticPeerMutex.RUnlock() diff --git a/clientapi/httputil/parse.go b/clientapi/httputil/parse.go index ee603341..c8358334 100644 --- a/clientapi/httputil/parse.go +++ b/clientapi/httputil/parse.go @@ -32,7 +32,7 @@ func ParseTSParam(req *http.Request) (time.Time, error) { // The parameter exists, parse into a Time object ts, err := strconv.ParseInt(tsStr, 10, 64) if err != nil { - return time.Time{}, fmt.Errorf("Param 'ts' is no valid int (%s)", err.Error()) + return time.Time{}, fmt.Errorf("param 'ts' is no valid int (%s)", err.Error()) } return time.Unix(ts/1000, 0), nil diff --git a/clientapi/routing/device.go b/clientapi/routing/device.go index 6adaa769..9f54a625 100644 --- a/clientapi/routing/device.go +++ b/clientapi/routing/device.go @@ -23,7 +23,6 @@ import ( "github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/userapi/api" - userapi "github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/util" ) @@ -50,18 +49,18 @@ type devicesDeleteJSON struct { // GetDeviceByID handles /devices/{deviceID} func GetDeviceByID( - req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, + req *http.Request, userAPI api.UserInternalAPI, device *api.Device, deviceID string, ) util.JSONResponse { - var queryRes userapi.QueryDevicesResponse - err := userAPI.QueryDevices(req.Context(), &userapi.QueryDevicesRequest{ + var queryRes api.QueryDevicesResponse + err := userAPI.QueryDevices(req.Context(), &api.QueryDevicesRequest{ UserID: device.UserID, }, &queryRes) if err != nil { util.GetLogger(req.Context()).WithError(err).Error("QueryDevices failed") return jsonerror.InternalServerError() } - var targetDevice *userapi.Device + var targetDevice *api.Device for _, device := range queryRes.Devices { if device.ID == deviceID { targetDevice = &device @@ -88,10 +87,10 @@ func GetDeviceByID( // GetDevicesByLocalpart handles /devices func GetDevicesByLocalpart( - req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, + req *http.Request, userAPI api.UserInternalAPI, device *api.Device, ) util.JSONResponse { - var queryRes userapi.QueryDevicesResponse - err := userAPI.QueryDevices(req.Context(), &userapi.QueryDevicesRequest{ + var queryRes api.QueryDevicesResponse + err := userAPI.QueryDevices(req.Context(), &api.QueryDevicesRequest{ UserID: device.UserID, }, &queryRes) if err != nil { diff --git a/clientapi/routing/directory.go b/clientapi/routing/directory.go index ae466065..96cb0262 100644 --- a/clientapi/routing/directory.go +++ b/clientapi/routing/directory.go @@ -23,7 +23,6 @@ import ( federationSenderAPI "github.com/matrix-org/dendrite/federationsender/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/setup/config" - "github.com/matrix-org/dendrite/userapi/api" userapi "github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/util" @@ -115,7 +114,7 @@ func DirectoryRoom( // SetLocalAlias implements PUT /directory/room/{roomAlias} func SetLocalAlias( req *http.Request, - device *api.Device, + device *userapi.Device, alias string, cfg *config.ClientAPI, rsAPI roomserverAPI.RoomserverInternalAPI, @@ -192,7 +191,7 @@ func SetLocalAlias( // RemoveLocalAlias implements DELETE /directory/room/{roomAlias} func RemoveLocalAlias( req *http.Request, - device *api.Device, + device *userapi.Device, alias string, rsAPI roomserverAPI.RoomserverInternalAPI, ) util.JSONResponse { diff --git a/clientapi/routing/logout.go b/clientapi/routing/logout.go index cb300e9f..cfbb6f9f 100644 --- a/clientapi/routing/logout.go +++ b/clientapi/routing/logout.go @@ -19,16 +19,15 @@ import ( "github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/userapi/api" - userapi "github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/util" ) // Logout handles POST /logout func Logout( - req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, + req *http.Request, userAPI api.UserInternalAPI, device *api.Device, ) util.JSONResponse { - var performRes userapi.PerformDeviceDeletionResponse - err := userAPI.PerformDeviceDeletion(req.Context(), &userapi.PerformDeviceDeletionRequest{ + var performRes api.PerformDeviceDeletionResponse + err := userAPI.PerformDeviceDeletion(req.Context(), &api.PerformDeviceDeletionRequest{ UserID: device.UserID, DeviceIDs: []string{device.ID}, }, &performRes) @@ -45,10 +44,10 @@ func Logout( // LogoutAll handles POST /logout/all func LogoutAll( - req *http.Request, userAPI userapi.UserInternalAPI, device *api.Device, + req *http.Request, userAPI api.UserInternalAPI, device *api.Device, ) util.JSONResponse { - var performRes userapi.PerformDeviceDeletionResponse - err := userAPI.PerformDeviceDeletion(req.Context(), &userapi.PerformDeviceDeletionRequest{ + var performRes api.PerformDeviceDeletionResponse + err := userAPI.PerformDeviceDeletion(req.Context(), &api.PerformDeviceDeletionRequest{ UserID: device.UserID, DeviceIDs: nil, }, &performRes) diff --git a/clientapi/routing/membership.go b/clientapi/routing/membership.go index b85cfde0..33fb3883 100644 --- a/clientapi/routing/membership.go +++ b/clientapi/routing/membership.go @@ -26,7 +26,6 @@ import ( "github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/threepid" "github.com/matrix-org/dendrite/internal/eventutil" - "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/setup/config" userapi "github.com/matrix-org/dendrite/userapi/api" @@ -107,7 +106,7 @@ func sendMembership(ctx context.Context, accountDB accounts.Database, device *us if err = roomserverAPI.SendEvents( ctx, rsAPI, - api.KindNew, + roomserverAPI.KindNew, []*gomatrixserverlib.HeaderedEvent{event.Event.Headered(roomVer)}, cfg.Matrix.ServerName, nil, @@ -328,11 +327,11 @@ func loadProfile( return profile, err } -func extractRequestData(req *http.Request, roomID string, rsAPI api.RoomserverInternalAPI) ( +func extractRequestData(req *http.Request, roomID string, rsAPI roomserverAPI.RoomserverInternalAPI) ( body *threepid.MembershipRequest, evTime time.Time, roomVer gomatrixserverlib.RoomVersion, resErr *util.JSONResponse, ) { - verReq := api.QueryRoomVersionForRoomRequest{RoomID: roomID} - verRes := api.QueryRoomVersionForRoomResponse{} + verReq := roomserverAPI.QueryRoomVersionForRoomRequest{RoomID: roomID} + verRes := roomserverAPI.QueryRoomVersionForRoomResponse{} if err := rsAPI.QueryRoomVersionForRoom(req.Context(), &verReq, &verRes); err != nil { resErr = &util.JSONResponse{ Code: http.StatusBadRequest, @@ -402,13 +401,13 @@ func checkAndProcessThreepid( return } -func checkMemberInRoom(ctx context.Context, rsAPI api.RoomserverInternalAPI, userID, roomID string) *util.JSONResponse { +func checkMemberInRoom(ctx context.Context, rsAPI roomserverAPI.RoomserverInternalAPI, userID, roomID string) *util.JSONResponse { tuple := gomatrixserverlib.StateKeyTuple{ EventType: gomatrixserverlib.MRoomMember, StateKey: userID, } - var membershipRes api.QueryCurrentStateResponse - err := rsAPI.QueryCurrentState(ctx, &api.QueryCurrentStateRequest{ + var membershipRes roomserverAPI.QueryCurrentStateResponse + err := rsAPI.QueryCurrentState(ctx, &roomserverAPI.QueryCurrentStateRequest{ RoomID: roomID, StateTuples: []gomatrixserverlib.StateKeyTuple{tuple}, }, &membershipRes) @@ -445,8 +444,8 @@ func SendForget( ) util.JSONResponse { ctx := req.Context() logger := util.GetLogger(ctx).WithField("roomID", roomID).WithField("userID", device.UserID) - var membershipRes api.QueryMembershipForUserResponse - membershipReq := api.QueryMembershipForUserRequest{ + var membershipRes roomserverAPI.QueryMembershipForUserResponse + membershipReq := roomserverAPI.QueryMembershipForUserRequest{ RoomID: roomID, UserID: device.UserID, } @@ -468,11 +467,11 @@ func SendForget( } } - request := api.PerformForgetRequest{ + request := roomserverAPI.PerformForgetRequest{ RoomID: roomID, UserID: device.UserID, } - response := api.PerformForgetResponse{} + response := roomserverAPI.PerformForgetResponse{} if err := rsAPI.PerformForget(ctx, &request, &response); err != nil { logger.WithError(err).Error("PerformForget: unable to forget room") return jsonerror.InternalServerError() diff --git a/clientapi/routing/password.go b/clientapi/routing/password.go index 87d5f8ff..b2442443 100644 --- a/clientapi/routing/password.go +++ b/clientapi/routing/password.go @@ -9,7 +9,6 @@ import ( "github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/userapi/api" - userapi "github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/storage/accounts" "github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/util" @@ -29,7 +28,7 @@ type newPasswordAuth struct { func Password( req *http.Request, - userAPI userapi.UserInternalAPI, + userAPI api.UserInternalAPI, accountDB accounts.Database, device *api.Device, cfg *config.ClientAPI, @@ -90,11 +89,11 @@ func Password( } // Ask the user API to perform the password change. - passwordReq := &userapi.PerformPasswordUpdateRequest{ + passwordReq := &api.PerformPasswordUpdateRequest{ Localpart: localpart, Password: r.NewPassword, } - passwordRes := &userapi.PerformPasswordUpdateResponse{} + passwordRes := &api.PerformPasswordUpdateResponse{} if err := userAPI.PerformPasswordUpdate(req.Context(), passwordReq, passwordRes); err != nil { util.GetLogger(req.Context()).WithError(err).Error("PerformPasswordUpdate failed") return jsonerror.InternalServerError() @@ -107,12 +106,12 @@ func Password( // If the request asks us to log out all other devices then // ask the user API to do that. if r.LogoutDevices { - logoutReq := &userapi.PerformDeviceDeletionRequest{ + logoutReq := &api.PerformDeviceDeletionRequest{ UserID: device.UserID, DeviceIDs: nil, ExceptDeviceID: device.ID, } - logoutRes := &userapi.PerformDeviceDeletionResponse{} + logoutRes := &api.PerformDeviceDeletionResponse{} if err := userAPI.PerformDeviceDeletion(req.Context(), logoutReq, logoutRes); err != nil { util.GetLogger(req.Context()).WithError(err).Error("PerformDeviceDeletion failed") return jsonerror.InternalServerError() diff --git a/clientapi/routing/redaction.go b/clientapi/routing/redaction.go index 92375974..c25ca4ef 100644 --- a/clientapi/routing/redaction.go +++ b/clientapi/routing/redaction.go @@ -22,7 +22,6 @@ import ( "github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/internal/eventutil" - "github.com/matrix-org/dendrite/roomserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/setup/config" userapi "github.com/matrix-org/dendrite/userapi/api" @@ -113,7 +112,7 @@ func SendRedaction( return jsonerror.InternalServerError() } - var queryRes api.QueryLatestEventsAndStateResponse + var queryRes roomserverAPI.QueryLatestEventsAndStateResponse e, err := eventutil.QueryAndBuildEvent(req.Context(), &builder, cfg.Matrix, time.Now(), rsAPI, &queryRes) if err == eventutil.ErrRoomNoExists { return util.JSONResponse{ @@ -121,7 +120,7 @@ func SendRedaction( JSON: jsonerror.NotFound("Room does not exist"), } } - if err = roomserverAPI.SendEvents(context.Background(), rsAPI, api.KindNew, []*gomatrixserverlib.HeaderedEvent{e}, cfg.Matrix.ServerName, nil); err != nil { + if err = roomserverAPI.SendEvents(context.Background(), rsAPI, roomserverAPI.KindNew, []*gomatrixserverlib.HeaderedEvent{e}, cfg.Matrix.ServerName, nil); err != nil { util.GetLogger(req.Context()).WithError(err).Errorf("failed to SendEvents") return jsonerror.InternalServerError() } diff --git a/clientapi/routing/register_secret.go b/clientapi/routing/register_secret.go index f0436e32..1a974b77 100644 --- a/clientapi/routing/register_secret.go +++ b/clientapi/routing/register_secret.go @@ -68,18 +68,18 @@ func (r *SharedSecretRegistration) IsValidMacLogin( ) (bool, error) { // Check that shared secret registration isn't disabled. if r.sharedSecret == "" { - return false, errors.New("Shared secret registration is disabled") + return false, errors.New("shared secret registration is disabled") } if !r.validNonce(nonce) { - return false, fmt.Errorf("Incorrect or expired nonce: %s", nonce) + return false, fmt.Errorf("incorrect or expired nonce: %s", nonce) } // Check that username/password don't contain the HMAC delimiters. if strings.Contains(username, "\x00") { - return false, errors.New("Username contains invalid character") + return false, errors.New("username contains invalid character") } if strings.Contains(password, "\x00") { - return false, errors.New("Password contains invalid character") + return false, errors.New("password contains invalid character") } adminString := "notadmin" diff --git a/clientapi/threepid/threepid.go b/clientapi/threepid/threepid.go index 2f817ef4..1e64e303 100644 --- a/clientapi/threepid/threepid.go +++ b/clientapi/threepid/threepid.go @@ -81,7 +81,7 @@ func CreateSession( // Error if the status isn't OK if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("Could not create a session on the server %s", req.IDServer) + return "", fmt.Errorf("could not create a session on the server %s", req.IDServer) } // Extract the SID from the response and return it @@ -168,7 +168,7 @@ func PublishAssociation(creds Credentials, userID string, cfg *config.ClientAPI) // Error if the status isn't OK if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Could not publish the association on the server %s", creds.IDServer) + return fmt.Errorf("could not publish the association on the server %s", creds.IDServer) } return nil diff --git a/clientapi/userutil/userutil.go b/clientapi/userutil/userutil.go index 4cea3c18..7e909ffa 100644 --- a/clientapi/userutil/userutil.go +++ b/clientapi/userutil/userutil.go @@ -31,11 +31,11 @@ func ParseUsernameParam(usernameParam string, expectedServerName *gomatrixserver lp, domain, err := gomatrixserverlib.SplitID('@', usernameParam) if err != nil { - return "", errors.New("Invalid username") + return "", errors.New("invalid username") } if expectedServerName != nil && domain != *expectedServerName { - return "", errors.New("User ID does not belong to this server") + return "", errors.New("user ID does not belong to this server") } localpart = lp diff --git a/cmd/dendrite-demo-pinecone/main.go b/cmd/dendrite-demo-pinecone/main.go index 1933c5ad..e919e749 100644 --- a/cmd/dendrite-demo-pinecone/main.go +++ b/cmd/dendrite-demo-pinecone/main.go @@ -49,7 +49,6 @@ import ( "github.com/matrix-org/gomatrixserverlib" pineconeMulticast "github.com/matrix-org/pinecone/multicast" - "github.com/matrix-org/pinecone/router" pineconeRouter "github.com/matrix-org/pinecone/router" pineconeSessions "github.com/matrix-org/pinecone/sessions" @@ -125,7 +124,7 @@ func main() { connectToStaticPeer := func() { attempt := func() { - if pRouter.PeerCount(router.PeerTypeRemote) == 0 { + if pRouter.PeerCount(pineconeRouter.PeerTypeRemote) == 0 { uri := *instancePeer if uri == "" { return diff --git a/cmd/dendrite-upgrade-tests/main.go b/cmd/dendrite-upgrade-tests/main.go index a6cc2d3f..aa8c7fdc 100644 --- a/cmd/dendrite-upgrade-tests/main.go +++ b/cmd/dendrite-upgrade-tests/main.go @@ -148,7 +148,7 @@ func buildDendrite(httpClient *http.Client, dockerClient *client.Client, tmpDir, // add top level Dockerfile err = ioutil.WriteFile(path.Join(*flagHead, "Dockerfile"), []byte(Dockerfile), os.ModePerm) if err != nil { - return "", fmt.Errorf("Custom HEAD: failed to inject /Dockerfile: %w", err) + return "", fmt.Errorf("custom HEAD: failed to inject /Dockerfile: %w", err) } // now tarball it var buffer bytes.Buffer diff --git a/federationapi/routing/send.go b/federationapi/routing/send.go index aacc8a91..d31d38dc 100644 --- a/federationapi/routing/send.go +++ b/federationapi/routing/send.go @@ -711,7 +711,7 @@ withNextEvent: } if missing := len(missingAuthEvents); missing > 0 { - return fmt.Errorf("Event refers to %d auth_events which we failed to fetch", missing) + return fmt.Errorf("event refers to %d auth_events which we failed to fetch", missing) } return nil } diff --git a/federationsender/consumers/keychange.go b/federationsender/consumers/keychange.go index 675328df..a9f6d0f8 100644 --- a/federationsender/consumers/keychange.go +++ b/federationsender/consumers/keychange.go @@ -30,7 +30,6 @@ import ( "github.com/matrix-org/dendrite/setup/process" "github.com/matrix-org/gomatrixserverlib" "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" ) // KeyChangeConsumer consumes events that originate in key server. @@ -82,7 +81,7 @@ func (t *KeyChangeConsumer) Start() error { func (t *KeyChangeConsumer) onMessage(msg *sarama.ConsumerMessage) error { var m api.DeviceMessage if err := json.Unmarshal(msg.Value, &m); err != nil { - log.WithError(err).Errorf("failed to read device message from key change topic") + logrus.WithError(err).Errorf("failed to read device message from key change topic") return nil } switch m.Type { @@ -96,7 +95,7 @@ func (t *KeyChangeConsumer) onMessage(msg *sarama.ConsumerMessage) error { } func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) error { - logger := log.WithField("user_id", m.UserID) + logger := logrus.WithField("user_id", m.UserID) // only send key change events which originated from us _, originServerName, err := gomatrixserverlib.SplitID('@', m.UserID) @@ -142,7 +141,7 @@ func (t *KeyChangeConsumer) onDeviceKeyMessage(m api.DeviceMessage) error { return err } - log.Infof("Sending device list update message to %q", destinations) + logrus.Infof("Sending device list update message to %q", destinations) return t.queues.SendEDU(edu, t.serverName, destinations) } @@ -158,7 +157,7 @@ func (t *KeyChangeConsumer) onCrossSigningMessage(m api.DeviceMessage) error { // end up parroting information we received from other servers. return nil } - logger := log.WithField("user_id", output.UserID) + logger := logrus.WithField("user_id", output.UserID) var queryRes roomserverAPI.QueryRoomsForUserResponse err = t.rsAPI.QueryRoomsForUser(context.Background(), &roomserverAPI.QueryRoomsForUserRequest{ diff --git a/federationsender/internal/perform.go b/federationsender/internal/perform.go index 968df247..2df936e3 100644 --- a/federationsender/internal/perform.go +++ b/federationsender/internal/perform.go @@ -409,7 +409,7 @@ func (r *FederationSenderInternalAPI) performOutboundPeekUsingServer( return fmt.Errorf("sanityCheckAuthChain: %w", err) } if err = respState.Check(ctx, r.keyRing, federatedAuthProvider(ctx, r.federation, r.keyRing, serverName)); err != nil { - return fmt.Errorf("Error checking state returned from peeking: %w", err) + return fmt.Errorf("error checking state returned from peeking: %w", err) } // If we've got this far, the remote server is peeking. @@ -523,7 +523,7 @@ func (r *FederationSenderInternalAPI) PerformLeave( // If we reach here then we didn't complete a leave for some reason. return fmt.Errorf( - "Failed to leave room %q through %d server(s)", + "failed to leave room %q through %d server(s)", request.RoomID, len(request.ServerNames), ) } diff --git a/federationsender/queue/destinationqueue.go b/federationsender/queue/destinationqueue.go index 33f77a42..0123fa24 100644 --- a/federationsender/queue/destinationqueue.go +++ b/federationsender/queue/destinationqueue.go @@ -29,7 +29,6 @@ import ( "github.com/matrix-org/gomatrix" "github.com/matrix-org/gomatrixserverlib" "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" "go.uber.org/atomic" ) @@ -72,7 +71,7 @@ type destinationQueue struct { // start sending events to that destination. func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, receipt *shared.Receipt) { if event == nil { - log.Errorf("attempt to send nil PDU with destination %q", oq.destination) + logrus.Errorf("attempt to send nil PDU with destination %q", oq.destination) return } // Create a database entry that associates the given PDU NID with @@ -84,7 +83,7 @@ func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, re oq.destination, // the destination server name receipt, // NIDs from federationsender_queue_json table ); err != nil { - log.WithError(err).Errorf("failed to associate PDU %q with destination %q", event.EventID(), oq.destination) + logrus.WithError(err).Errorf("failed to associate PDU %q with destination %q", event.EventID(), oq.destination) return } // Check if the destination is blacklisted. If it isn't then wake @@ -116,7 +115,7 @@ func (oq *destinationQueue) sendEvent(event *gomatrixserverlib.HeaderedEvent, re // start sending events to that destination. func (oq *destinationQueue) sendEDU(event *gomatrixserverlib.EDU, receipt *shared.Receipt) { if event == nil { - log.Errorf("attempt to send nil EDU with destination %q", oq.destination) + logrus.Errorf("attempt to send nil EDU with destination %q", oq.destination) return } // Create a database entry that associates the given PDU NID with @@ -127,7 +126,7 @@ func (oq *destinationQueue) sendEDU(event *gomatrixserverlib.EDU, receipt *share oq.destination, // the destination server name receipt, // NIDs from federationsender_queue_json table ); err != nil { - log.WithError(err).Errorf("failed to associate EDU with destination %q", oq.destination) + logrus.WithError(err).Errorf("failed to associate EDU with destination %q", oq.destination) return } // Check if the destination is blacklisted. If it isn't then wake @@ -281,7 +280,7 @@ func (oq *destinationQueue) backgroundSend() { // It's been suggested that we should give up because the backoff // has exceeded a maximum allowable value. Clean up the in-memory // buffers at this point. The PDU clean-up is already on a defer. - log.Warnf("Blacklisting %q due to exceeding backoff threshold", oq.destination) + logrus.Warnf("Blacklisting %q due to exceeding backoff threshold", oq.destination) oq.pendingMutex.Lock() for i := range oq.pendingPDUs { oq.pendingPDUs[i] = nil @@ -298,7 +297,7 @@ func (oq *destinationQueue) backgroundSend() { // We haven't backed off yet, so wait for the suggested amount of // time. duration := time.Until(*until) - log.Warnf("Backing off %q for %s", oq.destination, duration) + logrus.Warnf("Backing off %q for %s", oq.destination, duration) oq.backingOff.Store(true) destinationQueueBackingOff.Inc() select { @@ -421,13 +420,13 @@ func (oq *destinationQueue) nextTransaction( if pduReceipts != nil { //logrus.Infof("Cleaning PDUs %q", pduReceipt.String()) if err = oq.db.CleanPDUs(context.Background(), oq.destination, pduReceipts); err != nil { - log.WithError(err).Errorf("Failed to clean PDUs for server %q", t.Destination) + logrus.WithError(err).Errorf("Failed to clean PDUs for server %q", t.Destination) } } if eduReceipts != nil { //logrus.Infof("Cleaning EDUs %q", eduReceipt.String()) if err = oq.db.CleanEDUs(context.Background(), oq.destination, eduReceipts); err != nil { - log.WithError(err).Errorf("Failed to clean EDUs for server %q", t.Destination) + logrus.WithError(err).Errorf("Failed to clean EDUs for server %q", t.Destination) } } // Reset the transaction ID. @@ -440,9 +439,9 @@ func (oq *destinationQueue) nextTransaction( // will retry again, subject to backoff. return false, 0, 0, err default: - log.WithFields(log.Fields{ - "destination": oq.destination, - log.ErrorKey: err, + logrus.WithFields(logrus.Fields{ + "destination": oq.destination, + logrus.ErrorKey: err, }).Debugf("Failed to send transaction %q", t.TransactionID) return false, 0, 0, err } diff --git a/internal/eventutil/events.go b/internal/eventutil/events.go index b8691c50..47c83d51 100644 --- a/internal/eventutil/events.go +++ b/internal/eventutil/events.go @@ -28,7 +28,7 @@ import ( // ErrRoomNoExists is returned when trying to lookup the state of a room that // doesn't exist -var ErrRoomNoExists = errors.New("Room does not exist") +var ErrRoomNoExists = errors.New("room does not exist") // QueryAndBuildEvent builds a Matrix event using the event builder and roomserver query // API client provided. If also fills roomserver query API response (if provided) diff --git a/internal/httputil/http.go b/internal/httputil/http.go index 9197371a..a469c8ac 100644 --- a/internal/httputil/http.go +++ b/internal/httputil/http.go @@ -73,9 +73,9 @@ func PostJSON( Message string `json:"message"` } if msgerr := json.NewDecoder(res.Body).Decode(&errorBody); msgerr == nil { - return fmt.Errorf("Internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message) + return fmt.Errorf("internal API: %d from %s: %s", res.StatusCode, apiURL, errorBody.Message) } - return fmt.Errorf("Internal API: %d from %s", res.StatusCode, apiURL) + return fmt.Errorf("internal API: %d from %s", res.StatusCode, apiURL) } return json.NewDecoder(res.Body).Decode(response) } diff --git a/internal/sqlutil/migrate.go b/internal/sqlutil/migrate.go index 62b1c8fa..7518df3c 100644 --- a/internal/sqlutil/migrate.go +++ b/internal/sqlutil/migrate.go @@ -46,7 +46,7 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error minVer := int64(0) migrations, err := m.collect(minVer, maxVer) if err != nil { - return fmt.Errorf("RunDeltas: Failed to collect migrations: %w", err) + return fmt.Errorf("runDeltas: Failed to collect migrations: %w", err) } if props.ConnectionString.IsPostgres() { if err = goose.SetDialect("postgres"); err != nil { @@ -57,12 +57,12 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error return err } } else { - return fmt.Errorf("Unknown connection string: %s", props.ConnectionString) + return fmt.Errorf("unknown connection string: %s", props.ConnectionString) } for { current, err := goose.EnsureDBVersion(db) if err != nil { - return fmt.Errorf("RunDeltas: Failed to EnsureDBVersion: %w", err) + return fmt.Errorf("runDeltas: Failed to EnsureDBVersion: %w", err) } next, err := migrations.Next(current) @@ -71,11 +71,11 @@ func (m *Migrations) RunDeltas(db *sql.DB, props *config.DatabaseOptions) error return nil } - return fmt.Errorf("RunDeltas: Failed to load next migration to %+v : %w", next, err) + return fmt.Errorf("runDeltas: Failed to load next migration to %+v : %w", next, err) } if err = next.Up(db); err != nil { - return fmt.Errorf("RunDeltas: Failed run migration: %w", err) + return fmt.Errorf("runDeltas: Failed run migration: %w", err) } } } diff --git a/internal/sqlutil/sql.go b/internal/sqlutil/sql.go index 98cc396a..8d0d2dfa 100644 --- a/internal/sqlutil/sql.go +++ b/internal/sqlutil/sql.go @@ -25,7 +25,7 @@ import ( ) // ErrUserExists is returned if a username already exists in the database. -var ErrUserExists = errors.New("Username already exists") +var ErrUserExists = errors.New("username already exists") // A Transaction is something that can be committed or rolledback. type Transaction interface { diff --git a/mediaapi/fileutils/fileutils.go b/mediaapi/fileutils/fileutils.go index 7309cb88..754e4644 100644 --- a/mediaapi/fileutils/fileutils.go +++ b/mediaapi/fileutils/fileutils.go @@ -37,10 +37,10 @@ import ( // For example, if Base64Hash is 'qwerty', the path will be 'q/w/erty/file'. func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path) (string, error) { if len(base64Hash) < 3 { - return "", fmt.Errorf("Invalid filePath (Base64Hash too short - min 3 characters): %q", base64Hash) + return "", fmt.Errorf("invalid filePath (Base64Hash too short - min 3 characters): %q", base64Hash) } if len(base64Hash) > 255 { - return "", fmt.Errorf("Invalid filePath (Base64Hash too long - max 255 characters): %q", base64Hash) + return "", fmt.Errorf("invalid filePath (Base64Hash too long - max 255 characters): %q", base64Hash) } filePath, err := filepath.Abs(filepath.Join( @@ -51,14 +51,14 @@ func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path) "file", )) if err != nil { - return "", fmt.Errorf("Unable to construct filePath: %w", err) + return "", fmt.Errorf("unable to construct filePath: %w", err) } // check if the absolute absBasePath is a prefix of the absolute filePath // if so, no directory escape has occurred and the filePath is valid // Note: absBasePath is already absolute if !strings.HasPrefix(filePath, string(absBasePath)) { - return "", fmt.Errorf("Invalid filePath (not within absBasePath %v): %v", absBasePath, filePath) + return "", fmt.Errorf("invalid filePath (not within absBasePath %v): %v", absBasePath, filePath) } return filePath, nil @@ -102,7 +102,7 @@ func MoveFileWithHashCheck(tmpDir types.Path, mediaMetadata *types.MediaMetadata func RemoveDir(dir types.Path, logger *log.Entry) { dirErr := os.RemoveAll(string(dir)) if dirErr != nil { - logger.WithError(dirErr).WithField("dir", dir).Warn("Failed to remove directory") + logger.WithError(dirErr).WithField("dir", dir).Warn("failed to remove directory") } } @@ -153,11 +153,11 @@ func moveFile(src types.Path, dst types.Path) error { err := os.MkdirAll(dstDir, 0770) if err != nil { - return fmt.Errorf("Failed to make directory: %w", err) + return fmt.Errorf("failed to make directory: %w", err) } err = os.Rename(string(src), string(dst)) if err != nil { - return fmt.Errorf("Failed to move directory: %w", err) + return fmt.Errorf("failed to move directory: %w", err) } return nil } @@ -165,11 +165,11 @@ func moveFile(src types.Path, dst types.Path) error { func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, types.Path, error) { tmpDir, err := createTempDir(absBasePath) if err != nil { - return nil, nil, "", fmt.Errorf("Failed to create temp dir: %w", err) + return nil, nil, "", fmt.Errorf("failed to create temp dir: %w", err) } writer, tmpFile, err := createFileWriter(tmpDir) if err != nil { - return nil, nil, "", fmt.Errorf("Failed to create file writer: %w", err) + return nil, nil, "", fmt.Errorf("failed to create file writer: %w", err) } return writer, tmpFile, tmpDir, nil } @@ -178,11 +178,11 @@ func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, typ func createTempDir(baseDirectory config.Path) (types.Path, error) { baseTmpDir := filepath.Join(string(baseDirectory), "tmp") if err := os.MkdirAll(baseTmpDir, 0770); err != nil { - return "", fmt.Errorf("Failed to create base temp dir: %w", err) + return "", fmt.Errorf("failed to create base temp dir: %w", err) } tmpDir, err := ioutil.TempDir(baseTmpDir, "") if err != nil { - return "", fmt.Errorf("Failed to create temp dir: %w", err) + return "", fmt.Errorf("failed to create temp dir: %w", err) } return types.Path(tmpDir), nil } @@ -194,7 +194,7 @@ func createFileWriter(directory types.Path) (*bufio.Writer, *os.File, error) { filePath := filepath.Join(string(directory), "content") file, err := os.Create(filePath) if err != nil { - return nil, nil, fmt.Errorf("Failed to create file: %w", err) + return nil, nil, fmt.Errorf("failed to create file: %w", err) } return bufio.NewWriter(file), file, nil diff --git a/roomserver/internal/perform/perform_invite.go b/roomserver/internal/perform/perform_invite.go index c6ad79d9..024c0930 100644 --- a/roomserver/internal/perform/perform_invite.go +++ b/roomserver/internal/perform/perform_invite.go @@ -51,7 +51,7 @@ func (r *Inviter) PerformInvite( targetUserID := *event.StateKey() info, err := r.DB.RoomInfo(ctx, roomID) if err != nil { - return nil, fmt.Errorf("Failed to load RoomInfo: %w", err) + return nil, fmt.Errorf("failed to load RoomInfo: %w", err) } log.WithFields(log.Fields{ diff --git a/roomserver/internal/perform/perform_join.go b/roomserver/internal/perform/perform_join.go index 876888e2..772c9d7d 100644 --- a/roomserver/internal/perform/perform_join.go +++ b/roomserver/internal/perform/perform_join.go @@ -24,7 +24,6 @@ import ( "github.com/getsentry/sentry-go" fsAPI "github.com/matrix-org/dendrite/federationsender/api" "github.com/matrix-org/dendrite/internal/eventutil" - "github.com/matrix-org/dendrite/roomserver/api" rsAPI "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/internal/helpers" "github.com/matrix-org/dendrite/roomserver/internal/input" @@ -49,17 +48,17 @@ type Joiner struct { // PerformJoin handles joining matrix rooms, including over federation by talking to the federationsender. func (r *Joiner) PerformJoin( ctx context.Context, - req *api.PerformJoinRequest, - res *api.PerformJoinResponse, + req *rsAPI.PerformJoinRequest, + res *rsAPI.PerformJoinResponse, ) { roomID, joinedVia, err := r.performJoin(ctx, req) if err != nil { sentry.CaptureException(err) - perr, ok := err.(*api.PerformError) + perr, ok := err.(*rsAPI.PerformError) if ok { res.Error = perr } else { - res.Error = &api.PerformError{ + res.Error = &rsAPI.PerformError{ Msg: err.Error(), } } @@ -70,18 +69,18 @@ func (r *Joiner) PerformJoin( func (r *Joiner) performJoin( ctx context.Context, - req *api.PerformJoinRequest, + req *rsAPI.PerformJoinRequest, ) (string, gomatrixserverlib.ServerName, error) { _, domain, err := gomatrixserverlib.SplitID('@', req.UserID) if err != nil { - return "", "", &api.PerformError{ - Code: api.PerformErrorBadRequest, + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorBadRequest, Msg: fmt.Sprintf("Supplied user ID %q in incorrect format", req.UserID), } } if domain != r.Cfg.Matrix.ServerName { - return "", "", &api.PerformError{ - Code: api.PerformErrorBadRequest, + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorBadRequest, Msg: fmt.Sprintf("User %q does not belong to this homeserver", req.UserID), } } @@ -91,20 +90,20 @@ func (r *Joiner) performJoin( if strings.HasPrefix(req.RoomIDOrAlias, "#") { return r.performJoinRoomByAlias(ctx, req) } - return "", "", &api.PerformError{ - Code: api.PerformErrorBadRequest, + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorBadRequest, Msg: fmt.Sprintf("Room ID or alias %q is invalid", req.RoomIDOrAlias), } } func (r *Joiner) performJoinRoomByAlias( ctx context.Context, - req *api.PerformJoinRequest, + req *rsAPI.PerformJoinRequest, ) (string, gomatrixserverlib.ServerName, error) { // Get the domain part of the room alias. _, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias) if err != nil { - return "", "", fmt.Errorf("Alias %q is not in the correct format", req.RoomIDOrAlias) + return "", "", fmt.Errorf("alias %q is not in the correct format", req.RoomIDOrAlias) } req.ServerNames = append(req.ServerNames, domain) @@ -122,7 +121,7 @@ func (r *Joiner) performJoinRoomByAlias( err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes) if err != nil { logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias) - return "", "", fmt.Errorf("Looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) + return "", "", fmt.Errorf("looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) } roomID = dirRes.RoomID req.ServerNames = append(req.ServerNames, dirRes.ServerNames...) @@ -135,14 +134,14 @@ func (r *Joiner) performJoinRoomByAlias( // Otherwise, look up if we know this room alias locally. err = r.RSAPI.GetRoomIDForAlias(ctx, &getRoomReq, &getRoomRes) if err != nil { - return "", "", fmt.Errorf("Lookup room alias %q failed: %w", req.RoomIDOrAlias, err) + return "", "", fmt.Errorf("lookup room alias %q failed: %w", req.RoomIDOrAlias, err) } roomID = getRoomRes.RoomID } // If the room ID is empty then we failed to look up the alias. if roomID == "" { - return "", "", fmt.Errorf("Alias %q not found", req.RoomIDOrAlias) + return "", "", fmt.Errorf("alias %q not found", req.RoomIDOrAlias) } // If we do, then pluck out the room ID and continue the join. @@ -153,7 +152,7 @@ func (r *Joiner) performJoinRoomByAlias( // TODO: Break this function up a bit func (r *Joiner) performJoinRoomByID( ctx context.Context, - req *api.PerformJoinRequest, + req *rsAPI.PerformJoinRequest, ) (string, gomatrixserverlib.ServerName, error) { // The original client request ?server_name=... may include this HS so filter that out so we // don't attempt to make_join with ourselves @@ -168,8 +167,8 @@ func (r *Joiner) performJoinRoomByID( // Get the domain part of the room ID. _, domain, err := gomatrixserverlib.SplitID('!', req.RoomIDOrAlias) if err != nil { - return "", "", &api.PerformError{ - Code: api.PerformErrorBadRequest, + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorBadRequest, Msg: fmt.Sprintf("Room ID %q is invalid: %s", req.RoomIDOrAlias, err), } } @@ -207,10 +206,10 @@ func (r *Joiner) performJoinRoomByID( // Force a federated join if we aren't in the room and we've been // given some server names to try joining by. - inRoomReq := &api.QueryServerJoinedToRoomRequest{ + inRoomReq := &rsAPI.QueryServerJoinedToRoomRequest{ RoomID: req.RoomIDOrAlias, } - inRoomRes := &api.QueryServerJoinedToRoomResponse{} + inRoomRes := &rsAPI.QueryServerJoinedToRoomResponse{} if err = r.Queryer.QueryServerJoinedToRoom(ctx, inRoomReq, inRoomRes); err != nil { return "", "", fmt.Errorf("r.Queryer.QueryServerJoinedToRoom: %w", err) } @@ -267,21 +266,21 @@ func (r *Joiner) performJoinRoomByID( // If we haven't already joined the room then send an event // into the room changing our membership status. if !alreadyJoined { - inputReq := api.InputRoomEventsRequest{ - InputRoomEvents: []api.InputRoomEvent{ + inputReq := rsAPI.InputRoomEventsRequest{ + InputRoomEvents: []rsAPI.InputRoomEvent{ { - Kind: api.KindNew, + Kind: rsAPI.KindNew, Event: event.Headered(buildRes.RoomVersion), AuthEventIDs: event.AuthEventIDs(), SendAsServer: string(r.Cfg.Matrix.ServerName), }, }, } - inputRes := api.InputRoomEventsResponse{} + inputRes := rsAPI.InputRoomEventsResponse{} r.Inputer.InputRoomEvents(ctx, &inputReq, &inputRes) if err = inputRes.Err(); err != nil { - return "", "", &api.PerformError{ - Code: api.PerformErrorNotAllowed, + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorNotAllowed, Msg: fmt.Sprintf("InputRoomEvents auth failed: %s", err), } } @@ -296,9 +295,9 @@ func (r *Joiner) performJoinRoomByID( // Otherwise we'll try a federated join as normal, since it's quite // possible that the room still exists on other servers. if len(req.ServerNames) == 0 { - return "", "", &api.PerformError{ - Code: api.PerformErrorNoRoom, - Msg: fmt.Sprintf("Room ID %q does not exist", req.RoomIDOrAlias), + return "", "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrorNoRoom, + Msg: fmt.Sprintf("room ID %q does not exist", req.RoomIDOrAlias), } } } @@ -309,7 +308,7 @@ func (r *Joiner) performJoinRoomByID( default: // Something else went wrong. - return "", "", fmt.Errorf("Error joining local room: %q", err) + return "", "", fmt.Errorf("error joining local room: %q", err) } // By this point, if req.RoomIDOrAlias contained an alias, then @@ -321,7 +320,7 @@ func (r *Joiner) performJoinRoomByID( func (r *Joiner) performFederatedJoinRoomByID( ctx context.Context, - req *api.PerformJoinRequest, + req *rsAPI.PerformJoinRequest, ) (gomatrixserverlib.ServerName, error) { // Try joining by all of the supplied server names. fedReq := fsAPI.PerformJoinRequest{ @@ -333,8 +332,8 @@ func (r *Joiner) performFederatedJoinRoomByID( fedRes := fsAPI.PerformJoinResponse{} r.FSAPI.PerformJoin(ctx, &fedReq, &fedRes) if fedRes.LastError != nil { - return "", &api.PerformError{ - Code: api.PerformErrRemote, + return "", &rsAPI.PerformError{ + Code: rsAPI.PerformErrRemote, Msg: fedRes.LastError.Message, RemoteCode: fedRes.LastError.Code, } @@ -344,7 +343,7 @@ func (r *Joiner) performFederatedJoinRoomByID( func buildEvent( ctx context.Context, db storage.Database, cfg *config.Global, builder *gomatrixserverlib.EventBuilder, -) (*gomatrixserverlib.HeaderedEvent, *api.QueryLatestEventsAndStateResponse, error) { +) (*gomatrixserverlib.HeaderedEvent, *rsAPI.QueryLatestEventsAndStateResponse, error) { eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder) if err != nil { return nil, nil, fmt.Errorf("gomatrixserverlib.StateNeededForEventBuilder: %w", err) @@ -354,8 +353,8 @@ func buildEvent( return nil, nil, errors.New("expecting state tuples for event builder, got none") } - var queryRes api.QueryLatestEventsAndStateResponse - err = helpers.QueryLatestEventsAndState(ctx, db, &api.QueryLatestEventsAndStateRequest{ + var queryRes rsAPI.QueryLatestEventsAndStateResponse + err = helpers.QueryLatestEventsAndState(ctx, db, &rsAPI.QueryLatestEventsAndStateRequest{ RoomID: builder.RoomID, StateToFetch: eventsNeeded.Tuples(), }, &queryRes) diff --git a/roomserver/internal/perform/perform_leave.go b/roomserver/internal/perform/perform_leave.go index 88eb7e1e..a51de546 100644 --- a/roomserver/internal/perform/perform_leave.go +++ b/roomserver/internal/perform/perform_leave.go @@ -45,15 +45,15 @@ func (r *Leaver) PerformLeave( ) ([]api.OutputEvent, error) { _, domain, err := gomatrixserverlib.SplitID('@', req.UserID) if err != nil { - return nil, fmt.Errorf("Supplied user ID %q in incorrect format", req.UserID) + return nil, fmt.Errorf("supplied user ID %q in incorrect format", req.UserID) } if domain != r.Cfg.Matrix.ServerName { - return nil, fmt.Errorf("User %q does not belong to this homeserver", req.UserID) + return nil, fmt.Errorf("user %q does not belong to this homeserver", req.UserID) } if strings.HasPrefix(req.RoomID, "!") { return r.performLeaveRoomByID(ctx, req, res) } - return nil, fmt.Errorf("Room ID %q is invalid", req.RoomID) + return nil, fmt.Errorf("room ID %q is invalid", req.RoomID) } func (r *Leaver) performLeaveRoomByID( @@ -68,7 +68,7 @@ func (r *Leaver) performLeaveRoomByID( var host gomatrixserverlib.ServerName _, host, err = gomatrixserverlib.SplitID('@', senderUser) if err != nil { - return nil, fmt.Errorf("Sender %q is invalid", senderUser) + return nil, fmt.Errorf("sender %q is invalid", senderUser) } if host != r.Cfg.Matrix.ServerName { return r.performFederatedRejectInvite(ctx, req, res, senderUser, eventID) @@ -91,19 +91,19 @@ func (r *Leaver) performLeaveRoomByID( return nil, err } if !latestRes.RoomExists { - return nil, fmt.Errorf("Room %q does not exist", req.RoomID) + return nil, fmt.Errorf("room %q does not exist", req.RoomID) } // Now let's see if the user is in the room. if len(latestRes.StateEvents) == 0 { - return nil, fmt.Errorf("User %q is not a member of room %q", req.UserID, req.RoomID) + return nil, fmt.Errorf("user %q is not a member of room %q", req.UserID, req.RoomID) } membership, err := latestRes.StateEvents[0].Membership() if err != nil { - return nil, fmt.Errorf("Error getting membership: %w", err) + return nil, fmt.Errorf("error getting membership: %w", err) } if membership != gomatrixserverlib.Join && membership != gomatrixserverlib.Invite { - return nil, fmt.Errorf("User %q is not joined to the room (membership is %q)", req.UserID, membership) + return nil, fmt.Errorf("user %q is not joined to the room (membership is %q)", req.UserID, membership) } // Prepare the template for the leave event. @@ -161,7 +161,7 @@ func (r *Leaver) performFederatedRejectInvite( ) ([]api.OutputEvent, error) { _, domain, err := gomatrixserverlib.SplitID('@', senderUser) if err != nil { - return nil, fmt.Errorf("User ID %q invalid: %w", senderUser, err) + return nil, fmt.Errorf("user ID %q invalid: %w", senderUser, err) } // Ask the federation sender to perform a federated leave for us. diff --git a/roomserver/internal/perform/perform_peek.go b/roomserver/internal/perform/perform_peek.go index 443276cd..bd799667 100644 --- a/roomserver/internal/perform/perform_peek.go +++ b/roomserver/internal/perform/perform_peek.go @@ -96,7 +96,7 @@ func (r *Peeker) performPeekRoomByAlias( // Get the domain part of the room alias. _, domain, err := gomatrixserverlib.SplitID('#', req.RoomIDOrAlias) if err != nil { - return "", fmt.Errorf("Alias %q is not in the correct format", req.RoomIDOrAlias) + return "", fmt.Errorf("alias %q is not in the correct format", req.RoomIDOrAlias) } req.ServerNames = append(req.ServerNames, domain) @@ -114,7 +114,7 @@ func (r *Peeker) performPeekRoomByAlias( err = r.FSAPI.PerformDirectoryLookup(ctx, &dirReq, &dirRes) if err != nil { logrus.WithError(err).Errorf("error looking up alias %q", req.RoomIDOrAlias) - return "", fmt.Errorf("Looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) + return "", fmt.Errorf("looking up alias %q over federation failed: %w", req.RoomIDOrAlias, err) } roomID = dirRes.RoomID req.ServerNames = append(req.ServerNames, dirRes.ServerNames...) @@ -122,13 +122,13 @@ func (r *Peeker) performPeekRoomByAlias( // Otherwise, look up if we know this room alias locally. roomID, err = r.DB.GetRoomIDForAlias(ctx, req.RoomIDOrAlias) if err != nil { - return "", fmt.Errorf("Lookup room alias %q failed: %w", req.RoomIDOrAlias, err) + return "", fmt.Errorf("lookup room alias %q failed: %w", req.RoomIDOrAlias, err) } } // If the room ID is empty then we failed to look up the alias. if roomID == "" { - return "", fmt.Errorf("Alias %q not found", req.RoomIDOrAlias) + return "", fmt.Errorf("alias %q not found", req.RoomIDOrAlias) } // If we do, then pluck out the room ID and continue the peek. diff --git a/roomserver/state/state.go b/roomserver/state/state.go index 3d71dbb6..bae8b24c 100644 --- a/roomserver/state/state.go +++ b/roomserver/state/state.go @@ -71,7 +71,7 @@ func (v *StateResolution) LoadStateAtSnapshot( if !ok { // This should only get hit if the database is corrupt. // It should be impossible for an event to reference a NID that doesn't exist - panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) + panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID)) } fullState = append(fullState, entries...) } @@ -146,7 +146,7 @@ func (v *StateResolution) LoadCombinedStateAfterEvents( if !ok { // This should only get hit if the database is corrupt. // It should be impossible for an event to reference a NID that doesn't exist - panic(fmt.Errorf("Corrupt DB: Missing state snapshot numeric ID %d", prevState.BeforeStateSnapshotNID)) + panic(fmt.Errorf("corrupt DB: Missing state snapshot numeric ID %d", prevState.BeforeStateSnapshotNID)) } // Combine all the state entries for this snapshot. @@ -157,7 +157,7 @@ func (v *StateResolution) LoadCombinedStateAfterEvents( if !ok { // This should only get hit if the database is corrupt. // It should be impossible for an event to reference a NID that doesn't exist - panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) + panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID)) } fullState = append(fullState, entries...) } @@ -757,7 +757,7 @@ func (v *StateResolution) resolveConflictsV1( for _, resolvedEvent := range resolvedEvents { entry, ok := eventIDMap[resolvedEvent.EventID()] if !ok { - panic(fmt.Errorf("Missing state entry for event ID %q", resolvedEvent.EventID())) + panic(fmt.Errorf("missing state entry for event ID %q", resolvedEvent.EventID())) } notConflicted = append(notConflicted, entry) } @@ -880,7 +880,7 @@ func (v *StateResolution) resolveConflictsV2( for _, resolvedEvent := range resolvedEvents { entry, ok := eventIDMap[resolvedEvent.EventID()] if !ok { - panic(fmt.Errorf("Missing state entry for event ID %q", resolvedEvent.EventID())) + panic(fmt.Errorf("missing state entry for event ID %q", resolvedEvent.EventID())) } notConflicted = append(notConflicted, entry) } @@ -958,7 +958,7 @@ func (v *StateResolution) loadStateEvents( for _, entry := range eventEntries { event, ok := eventMap(events).lookup(entry.EventNID) if !ok { - panic(fmt.Errorf("Corrupt DB: Missing event numeric ID %d", entry.EventNID)) + panic(fmt.Errorf("corrupt DB: Missing event numeric ID %d", entry.EventNID)) } result = append(result, event.Event) eventIDMap[event.Event.EventID()] = entry diff --git a/roomserver/storage/shared/storage.go b/roomserver/storage/shared/storage.go index e1851679..b4fc15f1 100644 --- a/roomserver/storage/shared/storage.go +++ b/roomserver/storage/shared/storage.go @@ -1136,7 +1136,7 @@ func (d *Database) loadStateAtSnapshot( if !ok { // This should only get hit if the database is corrupt. // It should be impossible for an event to reference a NID that doesn't exist - panic(fmt.Errorf("Corrupt DB: Missing state block numeric ID %d", stateBlockNID)) + panic(fmt.Errorf("corrupt DB: Missing state block numeric ID %d", stateBlockNID)) } fullState = append(fullState, entries...) } diff --git a/setup/mscs/msc2836/msc2836.go b/setup/mscs/msc2836/msc2836.go index f47a42d9..a538299d 100644 --- a/setup/mscs/msc2836/msc2836.go +++ b/setup/mscs/msc2836/msc2836.go @@ -98,7 +98,7 @@ func Enable( ) error { db, err := NewDatabase(&base.Cfg.MSCs.Database) if err != nil { - return fmt.Errorf("Cannot enable MSC2836: %w", err) + return fmt.Errorf("cannot enable MSC2836: %w", err) } hooks.Enable() hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) { diff --git a/setup/mscs/msc2946/msc2946.go b/setup/mscs/msc2946/msc2946.go index 08a54f75..121a73fd 100644 --- a/setup/mscs/msc2946/msc2946.go +++ b/setup/mscs/msc2946/msc2946.go @@ -57,7 +57,7 @@ func Enable( ) error { db, err := NewDatabase(&base.Cfg.MSCs.Database) if err != nil { - return fmt.Errorf("Cannot enable MSC2946: %w", err) + return fmt.Errorf("cannot enable MSC2946: %w", err) } hooks.Enable() hooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) { diff --git a/syncapi/consumers/keychange.go b/syncapi/consumers/keychange.go index 05fcf37d..1938ff9b 100644 --- a/syncapi/consumers/keychange.go +++ b/syncapi/consumers/keychange.go @@ -30,7 +30,6 @@ import ( "github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/gomatrixserverlib" "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" ) // OutputKeyChangeEventConsumer consumes events that originated in the key server. @@ -128,7 +127,7 @@ func (s *OutputKeyChangeEventConsumer) onDeviceKeyMessage(m api.DeviceMessage, o UserID: output.UserID, }, &queryRes) if err != nil { - log.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") + logrus.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") sentry.CaptureException(err) return err } @@ -155,7 +154,7 @@ func (s *OutputKeyChangeEventConsumer) onCrossSigningMessage(m api.DeviceMessage UserID: output.UserID, }, &queryRes) if err != nil { - log.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") + logrus.WithError(err).Error("syncapi: failed to QuerySharedUsers for key change event from key server") sentry.CaptureException(err) return err } diff --git a/syncapi/internal/keychange.go b/syncapi/internal/keychange.go index 0bbaf31e..56a438fb 100644 --- a/syncapi/internal/keychange.go +++ b/syncapi/internal/keychange.go @@ -19,7 +19,6 @@ import ( "strings" "github.com/Shopify/sarama" - "github.com/matrix-org/dendrite/keyserver/api" keyapi "github.com/matrix-org/dendrite/keyserver/api" roomserverAPI "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/syncapi/types" @@ -31,8 +30,8 @@ const DeviceListLogName = "dl" // DeviceOTKCounts adds one-time key counts to the /sync response func DeviceOTKCounts(ctx context.Context, keyAPI keyapi.KeyInternalAPI, userID, deviceID string, res *types.Response) error { - var queryRes api.QueryOneTimeKeysResponse - keyAPI.QueryOneTimeKeys(ctx, &api.QueryOneTimeKeysRequest{ + var queryRes keyapi.QueryOneTimeKeysResponse + keyAPI.QueryOneTimeKeys(ctx, &keyapi.QueryOneTimeKeysRequest{ UserID: userID, DeviceID: deviceID, }, &queryRes) @@ -81,8 +80,8 @@ func DeviceListCatchup( if toLog := to; toLog.Partition == partition && toLog.Offset > 0 { toOffset = toLog.Offset } - var queryRes api.QueryKeyChangesResponse - keyAPI.QueryKeyChanges(ctx, &api.QueryKeyChangesRequest{ + var queryRes keyapi.QueryKeyChangesResponse + keyAPI.QueryKeyChanges(ctx, &keyapi.QueryKeyChangesRequest{ Partition: partition, Offset: offset, ToOffset: toOffset, diff --git a/syncapi/storage/shared/syncserver.go b/syncapi/storage/shared/syncserver.go index b8271877..e6c68183 100644 --- a/syncapi/storage/shared/syncserver.go +++ b/syncapi/storage/shared/syncserver.go @@ -30,7 +30,6 @@ import ( "github.com/matrix-org/dendrite/syncapi/types" "github.com/matrix-org/gomatrixserverlib" "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" ) // Database is a temporary struct until we have made syncserver.go the same for both pq/sqlite @@ -309,7 +308,7 @@ func (d *Database) StreamEventsToEvents(device *userapi.Device, in []types.Strea "transaction_id", in[i].TransactionID.TransactionID, ) if err != nil { - log.WithFields(log.Fields{ + logrus.WithFields(logrus.Fields{ "event_id": out[i].EventID(), }).WithError(err).Warnf("Failed to add transaction ID to event") } @@ -529,7 +528,7 @@ func (d *Database) RedactEvent(ctx context.Context, redactedEventID string, reda return err } if len(redactedEvents) == 0 { - log.WithField("event_id", redactedEventID).WithField("redaction_event", redactedBecause.EventID()).Warnf("missing redacted event for redaction") + logrus.WithField("event_id", redactedEventID).WithField("redaction_event", redactedBecause.EventID()).Warnf("missing redacted event for redaction") return nil } eventToRedact := redactedEvents[0].Unwrap() @@ -645,7 +644,7 @@ func (d *Database) fetchMissingStateEvents( return nil, err } if len(stateEvents) != len(missing) { - log.WithContext(ctx).Warnf("Failed to map all event IDs to events (got %d, wanted %d)", len(stateEvents), len(missing)) + logrus.WithContext(ctx).Warnf("Failed to map all event IDs to events (got %d, wanted %d)", len(stateEvents), len(missing)) // TODO: Why is this happening? It's probably the roomserver. Uncomment // this error again when we work out what it is and fix it, otherwise we diff --git a/syncapi/types/types.go b/syncapi/types/types.go index 49fa1a16..44e718b3 100644 --- a/syncapi/types/types.go +++ b/syncapi/types/types.go @@ -29,10 +29,10 @@ var ( // ErrInvalidSyncTokenType is returned when an attempt at creating a // new instance of SyncToken with an invalid type (i.e. neither "s" // nor "t"). - ErrInvalidSyncTokenType = fmt.Errorf("Sync token has an unknown prefix (should be either s or t)") + ErrInvalidSyncTokenType = fmt.Errorf("sync token has an unknown prefix (should be either s or t)") // ErrInvalidSyncTokenLen is returned when the pagination token is an // invalid length - ErrInvalidSyncTokenLen = fmt.Errorf("Sync token has an invalid length") + ErrInvalidSyncTokenLen = fmt.Errorf("sync token has an invalid length") ) type StateDelta struct { diff --git a/userapi/internal/api.go b/userapi/internal/api.go index 518edef4..4ff8f51d 100644 --- a/userapi/internal/api.go +++ b/userapi/internal/api.go @@ -177,10 +177,10 @@ func (a *UserInternalAPI) deviceListUpdate(userID string, deviceIDs []string) er DeviceKeys: deviceKeys, }, &uploadRes) if uploadRes.Error != nil { - return fmt.Errorf("Failed to delete device keys: %v", uploadRes.Error) + return fmt.Errorf("failed to delete device keys: %v", uploadRes.Error) } if len(uploadRes.KeyErrors) > 0 { - return fmt.Errorf("Failed to delete device keys, key errors: %+v", uploadRes.KeyErrors) + return fmt.Errorf("failed to delete device keys, key errors: %+v", uploadRes.KeyErrors) } return nil } @@ -242,10 +242,10 @@ func (a *UserInternalAPI) PerformDeviceUpdate(ctx context.Context, req *api.Perf OnlyDisplayNameUpdates: true, }, &uploadRes) if uploadRes.Error != nil { - return fmt.Errorf("Failed to update device key display name: %v", uploadRes.Error) + return fmt.Errorf("failed to update device key display name: %v", uploadRes.Error) } if len(uploadRes.KeyErrors) > 0 { - return fmt.Errorf("Failed to update device key display name, key errors: %+v", uploadRes.KeyErrors) + return fmt.Errorf("failed to update device key display name, key errors: %+v", uploadRes.KeyErrors) } } return nil diff --git a/userapi/storage/accounts/interface.go b/userapi/storage/accounts/interface.go index 887f7193..7af2f15f 100644 --- a/userapi/storage/accounts/interface.go +++ b/userapi/storage/accounts/interface.go @@ -67,4 +67,4 @@ type Database interface { // Err3PIDInUse is the error returned when trying to save an association involving // a third-party identifier which is already associated to a local user. -var Err3PIDInUse = errors.New("This third-party identifier is already in use") +var Err3PIDInUse = errors.New("this third-party identifier is already in use") diff --git a/userapi/storage/accounts/postgres/storage.go b/userapi/storage/accounts/postgres/storage.go index 6bddbfc3..2f829062 100644 --- a/userapi/storage/accounts/postgres/storage.go +++ b/userapi/storage/accounts/postgres/storage.go @@ -28,7 +28,6 @@ import ( "github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/userapi/api" "github.com/matrix-org/dendrite/userapi/storage/accounts/postgres/deltas" - _ "github.com/matrix-org/dendrite/userapi/storage/accounts/postgres/deltas" "github.com/matrix-org/gomatrixserverlib" "golang.org/x/crypto/bcrypt" @@ -271,7 +270,7 @@ func (d *Database) hashPassword(plaintext string) (hash string, err error) { // Err3PIDInUse is the error returned when trying to save an association involving // a third-party identifier which is already associated to a local user. -var Err3PIDInUse = errors.New("This third-party identifier is already in use") +var Err3PIDInUse = errors.New("this third-party identifier is already in use") // SaveThreePIDAssociation saves the association between a third party identifier // and a local Matrix user (identified by the user's ID's local part). diff --git a/userapi/storage/accounts/sqlite3/storage.go b/userapi/storage/accounts/sqlite3/storage.go index d752e3db..2b731b75 100644 --- a/userapi/storage/accounts/sqlite3/storage.go +++ b/userapi/storage/accounts/sqlite3/storage.go @@ -304,7 +304,7 @@ func (d *Database) hashPassword(plaintext string) (hash string, err error) { // Err3PIDInUse is the error returned when trying to save an association involving // a third-party identifier which is already associated to a local user. -var Err3PIDInUse = errors.New("This third-party identifier is already in use") +var Err3PIDInUse = errors.New("this third-party identifier is already in use") // SaveThreePIDAssociation saves the association between a third party identifier // and a local Matrix user (identified by the user's ID's local part). |