refactor(metrics): replace hardcoded time with contants, merge three tickers into one

This commit is contained in:
yusing
2025-10-03 22:48:18 +08:00
parent 4852efcf9c
commit ba8edb160f
2 changed files with 39 additions and 27 deletions

View File

@@ -18,16 +18,22 @@ const (
MetricsPeriod1h Filter = "1h" // @name MetricsPeriod1h
MetricsPeriod1d Filter = "1d" // @name MetricsPeriod1d
MetricsPeriod1mo Filter = "1mo" // @name MetricsPeriod1mo
Duration5m = 5 * time.Minute
Duration15m = 15 * time.Minute
Duration1h = 1 * time.Hour
Duration1d = 24 * time.Hour
Duration30d = 30 * 24 * time.Hour
)
func NewPeriod[T any]() *Period[T] {
return &Period[T]{
Entries: map[Filter]*Entries[T]{
MetricsPeriod5m: newEntries[T](5 * time.Minute),
MetricsPeriod15m: newEntries[T](15 * time.Minute),
MetricsPeriod1h: newEntries[T](1 * time.Hour),
MetricsPeriod1d: newEntries[T](24 * time.Hour),
MetricsPeriod1mo: newEntries[T](30 * 24 * time.Hour),
MetricsPeriod5m: newEntries[T](Duration5m),
MetricsPeriod15m: newEntries[T](Duration15m),
MetricsPeriod1h: newEntries[T](Duration1h),
MetricsPeriod1d: newEntries[T](Duration1d),
MetricsPeriod1mo: newEntries[T](Duration30d),
},
}
}
@@ -68,11 +74,11 @@ func (p *Period[T]) ValidateAndFixIntervals() {
defer p.mu.Unlock()
durations := map[Filter]time.Duration{
MetricsPeriod5m: 5 * time.Minute,
MetricsPeriod15m: 15 * time.Minute,
MetricsPeriod1h: 1 * time.Hour,
MetricsPeriod1d: 24 * time.Hour,
MetricsPeriod1mo: 30 * 24 * time.Hour,
MetricsPeriod5m: Duration5m,
MetricsPeriod15m: Duration15m,
MetricsPeriod1h: Duration1h,
MetricsPeriod1d: Duration1d,
MetricsPeriod1mo: Duration30d,
}
for filter, entries := range p.Entries {

View File

@@ -41,6 +41,9 @@ const (
gatherErrsInterval = 30 * time.Second
saveInterval = 5 * time.Minute
gatherErrsTicks = int(gatherErrsInterval / PollInterval) // 30
saveTicks = int(saveInterval / PollInterval) // 300
saveBaseDir = "data/metrics"
)
@@ -152,15 +155,12 @@ func (p *Poller[T, AggregateT]) Start() {
}
go func() {
pollTicker := time.NewTicker(PollInterval)
gatherErrsTicker := time.NewTicker(gatherErrsInterval)
saveTicker := time.NewTicker(saveInterval)
ticker := time.NewTicker(PollInterval)
defer ticker.Stop()
var tickCount int
defer func() {
pollTicker.Stop()
gatherErrsTicker.Stop()
saveTicker.Stop()
err := p.save()
if err != nil {
l.Err(err).Msg("failed to save metrics data")
@@ -176,19 +176,25 @@ func (p *Poller[T, AggregateT]) Start() {
select {
case <-t.Context().Done():
return
case <-pollTicker.C:
case <-ticker.C:
p.pollWithTimeout(t.Context())
case <-saveTicker.C:
err := p.save()
if err != nil {
p.appendErr(err)
tickCount++
if tickCount%gatherErrsTicks == 0 {
errs, ok := p.gatherErrs()
if ok {
log.Error().Msg(errs)
}
p.clearErrs()
}
case <-gatherErrsTicker.C:
errs, ok := p.gatherErrs()
if ok {
log.Error().Msg(errs)
if tickCount%saveTicks == 0 {
err := p.save()
if err != nil {
p.appendErr(err)
}
}
p.clearErrs()
}
}
}()