Skip to content

Commit 380c81d

Browse files
committed
generator
1 parent 15ede21 commit 380c81d

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package reports
2+
3+
import (
4+
"context"
5+
"io"
6+
"log/slog"
7+
"time"
8+
9+
"github.com/coder/coder/v2/coderd/database"
10+
"github.com/coder/coder/v2/coderd/database/dbauthz"
11+
"github.com/coder/coder/v2/coderd/database/dbtime"
12+
"github.com/coder/quartz"
13+
)
14+
15+
const (
16+
delay = 5 * time.Minute
17+
)
18+
19+
func NewReportGenerator(ctx context.Context, logger slog.Logger, db database.Store, clk quartz.Clock) io.Closer {
20+
closed := make(chan struct{})
21+
22+
ctx, cancelFunc := context.WithCancel(ctx)
23+
//nolint:gocritic // The system generates periodic reports without direct user input.
24+
ctx = dbauthz.AsSystemRestricted(ctx)
25+
26+
// Start the ticker with the initial delay.
27+
ticker := clk.NewTicker(delay)
28+
doTick := func(start time.Time) {
29+
defer ticker.Reset(delay)
30+
}
31+
32+
go func() {
33+
defer close(closed)
34+
defer ticker.Stop()
35+
// Force an initial tick.
36+
doTick(dbtime.Time(clk.Now()).UTC())
37+
for {
38+
select {
39+
case <-ctx.Done():
40+
return
41+
case tick := <-ticker.C:
42+
ticker.Stop()
43+
doTick(dbtime.Time(tick).UTC())
44+
}
45+
}
46+
}()
47+
return &reportGenerator{
48+
cancel: cancelFunc,
49+
closed: closed,
50+
}
51+
}
52+
53+
type reportGenerator struct {
54+
cancel context.CancelFunc
55+
closed chan struct{}
56+
}
57+
58+
func (i *reportGenerator) Close() error {
59+
i.cancel()
60+
<-i.closed
61+
return nil
62+
}

0 commit comments

Comments
 (0)