From 17824f74dc2757c746e251c90d6008f764d8169a Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Thu, 18 Aug 2016 14:15:15 +0100 Subject: [PATCH] Don't spam github with webhook creation requests which uses up our request rate limits --- .../go-neb/services/github/github.go | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/github.com/matrix-org/go-neb/services/github/github.go b/src/github.com/matrix-org/go-neb/services/github/github.go index 893e869..4a4d982 100644 --- a/src/github.com/matrix-org/go-neb/services/github/github.go +++ b/src/github.com/matrix-org/go-neb/services/github/github.go @@ -13,6 +13,7 @@ import ( "github.com/matrix-org/go-neb/types" "net/http" "regexp" + "sort" "strconv" "strings" ) @@ -221,6 +222,7 @@ func (s *githubService) PostRegister(oldService types.Service) { log.Errorf("PostRegister: %s does not have a github session", s.ClientUserID) return } + if oldService != nil { old, ok := oldService.(*githubService) if !ok { @@ -228,6 +230,12 @@ func (s *githubService) PostRegister(oldService types.Service) { return } + // Don't spam github webhook requests if we can help it. + if sameRepos(s, old) { + log.Print("PostRegister: old and new services have the same repo set. Nooping.") + return + } + // TODO: We should be adding webhooks in Register() then removing old hooks in PostRegister() // // By doing both operations in PostRegister(), if some of the requests fail we can end up in @@ -289,6 +297,37 @@ func modifyWebhooks(s *githubService, cli *github.Client, removeHooks bool) { } } +func sameRepos(a *githubService, b *githubService) bool { + getRepos := func(s *githubService) []string { + r := make(map[string]bool) + for _, roomConfig := range s.Rooms { + for ownerRepo, _ := range roomConfig.Repos { + r[ownerRepo] = true + } + } + var rs []string + for k, _ := range r { + rs = append(rs, k) + } + return rs + } + aRepos := getRepos(a) + bRepos := getRepos(b) + + if len(aRepos) != len(bRepos) { + return false + } + + sort.Strings(aRepos) + sort.Strings(bRepos) + for i := 0; i < len(aRepos); i += 1 { + if aRepos[i] != bRepos[i] { + return false + } + } + return true +} + func (s *githubService) githubClientFor(userID string, allowUnauth bool) *github.Client { token, err := getTokenForUser(s.RealmID, userID) if err != nil {