Cache reports generated by the collector.

This commit is contained in:
Tom Wilkie
2016-01-26 16:31:31 -08:00
parent 57f5a8bb04
commit 8af839ce26

View File

@@ -36,6 +36,7 @@ type collector struct {
mtx sync.Mutex
reports []timestampReport
window time.Duration
cached *report.Report
waitableCondition
}
@@ -86,6 +87,7 @@ func (c *collector) Add(rpt report.Report) {
defer c.mtx.Unlock()
c.reports = append(c.reports, timestampReport{now(), rpt})
c.reports = clean(c.reports, c.window)
c.cached = nil
if rpt.Shortcut {
c.Broadcast()
}
@@ -97,6 +99,14 @@ func (c *collector) Report() report.Report {
c.mtx.Lock()
defer c.mtx.Unlock()
// If the oldest report is still within range,
// and there is a cached report, return that.
if c.cached != nil && len(c.reports) > 0 {
oldest := now().Add(-c.window)
if c.reports[0].timestamp.Before(oldest) {
return *c.cached
}
}
c.reports = clean(c.reports, c.window)
rpt := report.MakeReport()
@@ -106,6 +116,7 @@ func (c *collector) Report() report.Report {
id.Write([]byte(tr.report.ID))
}
rpt.ID = fmt.Sprintf("%x", id.Sum64())
c.cached = &rpt
return rpt
}