Skip to content

Commit

Permalink
Use a dedicated store for test results
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashkovsky committed Apr 16, 2022
1 parent 02c6c81 commit 5619626
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 22 deletions.
12 changes: 2 additions & 10 deletions cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func runWatch(cmd *cobra.Command, args []string) {
resMap := sync.Map{}
printer := core.NewPrinter()
watcher := core.NewWatcher(&watchConfig)
store := core.NewStore()

go func() {
for {
Expand All @@ -51,16 +52,7 @@ func runWatch(cmd *cobra.Command, args []string) {
}
}()

watcher.Watch(func(res core.TestResult) {
if res.InProgress {
_, ok := resMap.Load(res.Id)
if !ok {
resMap.Store(res.Id, res)
}
} else {
resMap.Store(res.Id, res)
}
})
watcher.Watch(store.AddOrUpdate)
}

func init() {
Expand Down
20 changes: 8 additions & 12 deletions core/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"os"
"os/exec"
"runtime"
"sync"

"github.com/jedib0t/go-pretty/v6/table"
)
Expand Down Expand Up @@ -42,19 +41,16 @@ func NewPrinter() Printer {
return Printer{clearFns: clear, t: t}
}

func (p *Printer) ToTable(results *sync.Map) {
func (p *Printer) ToTable(results *Store) {
p.Clear()
p.t.ResetRows()
results.Range(func(k any, r interface{}) bool {
testResult, ok := r.(TestResult)
if ok {
p.t.AppendRow(table.Row{
k,
testResult.Tcp,
testResult.HttpStatus,
testResult.Duration,
})
}
results.ForEach(func(r TestResult) bool {
p.t.AppendRow(table.Row{
r.Id,
r.Tcp,
r.HttpStatus,
r.Duration,
})
return true
})
p.t.SortBy([]table.SortBy{{Name: "Address"}})
Expand Down
45 changes: 45 additions & 0 deletions core/store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package core

import "sync"

type Store struct {
results sync.Map
}

func NewStore() Store {
syncMap := sync.Map{}

return Store{
results: syncMap,
}
}

func (s *Store) AddOrUpdate(res TestResult) {
if res.InProgress {
existing, ok := s.results.Load(res.Id)
if !ok {
s.results.Store(res.Id, res)
} else {
prev := existing.(TestResult)
s.results.Store(res.Id, TestResult{
Id: prev.Id,
InProgress: true,
Tcp: prev.Tcp,
HttpStatus: prev.HttpStatus,
Duration: prev.Duration,
})
}
} else {
s.results.Store(res.Id, res)
}
}

func (s *Store) Clear() {
s.results = sync.Map{}
}

func (s *Store) ForEach(f func(TestResult) bool) {
s.results.Range(func(key, value any) bool {
return f(value.(TestResult))
})
}

0 comments on commit 5619626

Please sign in to comment.