1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase
4
5import (
6 "context"
7 "sync"
8 "time"
9
10 "github.com/bnema/zerowrap"
11
12 "bnema.dev/ermite/internal/domain"
13 "bnema.dev/ermite/internal/ports"
14)
15
16// MaintenanceDelay is how long maintenance waits after the first push of a
17// burst, so that pushes in quick succession share one run.
18const MaintenanceDelay = 5 * time.Second
19
20// Maintainer runs repository maintenance after pushes, debounced per
21// repository: the first Schedule starts a timer, further ones before it fires
22// join the same run, and a repository is maintained by one run at a time. A
23// Schedule during a run queues exactly one more run.
24//
25// Its goroutines use the logger of the context given to NewMaintainer and
26// live until Close. A run is cancelled by Close, and Git bounds it otherwise
27// (gitcli applies its command timeout to a context without deadline).
28type Maintainer struct {
29 git ports.GitRepos
30 fresh ports.RepoFreshener // nil: the reader needs no telling
31 delay time.Duration
32 ctx context.Context
33 stop context.CancelFunc
34
35 mu sync.Mutex
36 closed bool
37 entries map[domain.RepoName]*maintEntry
38 wg sync.WaitGroup
39}
40
41var _ ports.MaintenanceScheduler = (*Maintainer)(nil)
42
43type maintEntry struct {
44 timer *time.Timer // pending run, nil while running or idle
45 running bool
46 again bool // scheduled during a run
47}
48
49// NewMaintainer builds a maintainer. ctx carries the logger; its cancellation
50// is not followed, call Close. A zero delay means MaintenanceDelay.
51func NewMaintainer(ctx context.Context, git ports.GitRepos, delay time.Duration) *Maintainer {
52 if delay <= 0 {
53 delay = MaintenanceDelay
54 }
55 run, stop := context.WithCancel(context.WithoutCancel(ctx))
56 return &Maintainer{git: git, delay: delay, ctx: run, stop: stop, entries: make(map[domain.RepoName]*maintEntry)}
57}
58
59// WithFreshener makes every run tell the reader, when it ends, that the
60// repository changed: the commit-graph it wrote is for the reader to pick up.
61// Call it before the first Schedule; it returns m.
62func (m *Maintainer) WithFreshener(f ports.RepoFreshener) *Maintainer {
63 m.fresh = f
64 return m
65}
66
67// Schedule queues maintenance of the repository.
68func (m *Maintainer) Schedule(ctx context.Context, name domain.RepoName) {
69 m.mu.Lock()
70 defer m.mu.Unlock()
71 if m.closed {
72 return
73 }
74 e := m.entries[name]
75 switch {
76 case e == nil:
77 e = &maintEntry{}
78 m.entries[name] = e
79 m.arm(name, e)
80 log := zerowrap.FromCtx(ctx)
81 log.Debug().Str("repo", name.String()).Dur("delay", m.delay).Msg("repository maintenance scheduled")
82 case e.running:
83 e.again = true
84 }
85 // A timer is already pending: this push joins it.
86}
87
88// arm starts the timer of e. The caller holds mu.
89func (m *Maintainer) arm(name domain.RepoName, e *maintEntry) {
90 m.wg.Add(1) // released when the timer fires or is stopped by Close
91 e.timer = time.AfterFunc(m.delay, func() { m.run(name, e) })
92}
93
94func (m *Maintainer) run(name domain.RepoName, e *maintEntry) {
95 defer m.wg.Done()
96 m.mu.Lock()
97 if m.closed {
98 delete(m.entries, name)
99 m.mu.Unlock()
100 return
101 }
102 e.timer, e.running = nil, true
103 m.mu.Unlock()
104
105 log := zerowrap.FromCtx(m.ctx)
106 start := time.Now()
107 if err := m.git.Maintain(m.ctx, name); err != nil {
108 log.Warn().Err(err).Str("repo", name.String()).Msg("repository maintenance failed")
109 } else {
110 log.Debug().Str("repo", name.String()).Dur("duration", time.Since(start)).Msg("repository maintained")
111 }
112 if m.fresh != nil {
113 m.fresh.Refresh(m.ctx, name) // whatever the outcome: git may have written something
114 }
115
116 m.mu.Lock()
117 defer m.mu.Unlock()
118 e.running = false
119 if e.again && !m.closed {
120 e.again = false
121 m.arm(name, e)
122 return
123 }
124 delete(m.entries, name)
125}
126
127// Close stops pending runs, cancels the one in progress and waits for it.
128func (m *Maintainer) Close(_ context.Context) {
129 m.mu.Lock()
130 m.closed = true
131 for _, e := range m.entries {
132 if e.timer != nil && e.timer.Stop() {
133 m.wg.Done() // the timer will never fire
134 e.timer = nil
135 }
136 }
137 m.mu.Unlock()
138 m.stop()
139 m.wg.Wait()
140}