From 38d3c5ef88de1402e35e747781a44cf65f040289 Mon Sep 17 00:00:00 2001 From: Manfred Touron Date: Thu, 22 Nov 2018 17:03:17 +0100 Subject: [PATCH] feat: avoid having duplicates --- server/handler.go | 4 ++-- server/server.go | 34 +++++++++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/server/handler.go b/server/handler.go index 24bae681..c8f58507 100644 --- a/server/handler.go +++ b/server/handler.go @@ -138,7 +138,7 @@ func (s *Server) ListReleaseIOSJson(c echo.Context) error { ManifestURL: manifestURL, } } - for _, build := range s.cache.builds { + for _, build := range s.cache.builds.Sorted() { if build.BuildParameters["CIRCLE_JOB"] != "client.rn.ios" { continue } @@ -173,7 +173,7 @@ func (s *Server) ListReleaseIOS(c echo.Context) error { oncePerBranch := map[string]bool{} previousDate := "" now := time.Now().Truncate(time.Hour * 24) - for _, build := range s.cache.builds { + for _, build := range s.cache.builds.Sorted() { if build.BuildParameters["CIRCLE_JOB"] != "client.rn.ios" { continue } diff --git a/server/server.go b/server/server.go index fd4941e2..8af04213 100644 --- a/server/server.go +++ b/server/server.go @@ -8,6 +8,8 @@ import ( "math/rand" "net/http" "regexp" + "sort" + "sync" "time" "github.com/berty/staff/tools/release/pkg/circle" @@ -30,8 +32,25 @@ type ServerConfig struct { Password string } +type buildMap map[int]*circleci.Build + +func (m buildMap) Sorted() []*circleci.Build { + buildMapMutex.Lock() + defer buildMapMutex.Unlock() + keys := []int{} + for k := range m { + keys = append(keys, k) + } + sort.Sort(sort.Reverse(sort.IntSlice(keys))) + slice := []*circleci.Build{} + for _, k := range keys { + slice = append(slice, m[k]) + } + return slice +} + type Cache struct { - builds []*circleci.Build + builds buildMap mostRecentBuild time.Time } @@ -150,7 +169,7 @@ func (s *Server) Start() error { func (s *Server) refreshCache() error { var ( - allBuilds []*circleci.Build + allBuilds = make(buildMap, 0) mostRecentBuild = s.cache.mostRecentBuild ) @@ -166,7 +185,9 @@ func (s *Server) refreshCache() error { mostRecentBuild = *build.StopTime } } - allBuilds = append(allBuilds, builds...) + for _, build := range builds { + allBuilds[build.BuildNum] = build + } if len(builds) < 100 { break } @@ -193,7 +214,7 @@ func (s *Server) refreshCache() error { mostRecentBuild = *updateTime } if updateTime.After(previousMostRecentBuild) { - allBuilds = append([]*circleci.Build{build}, allBuilds...) + allBuilds[build.BuildNum] = build hasChanged = true } } @@ -202,8 +223,11 @@ func (s *Server) refreshCache() error { } } - // FIXME: lock + buildMapMutex.Lock() + defer buildMapMutex.Unlock() s.cache.builds = allBuilds s.cache.mostRecentBuild = mostRecentBuild return nil } + +var buildMapMutex sync.Mutex