1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package app
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
41type maintEntry struct {
42 timer *time.Timer // pending run, nil while running or idle
43 running bool
44 again bool // scheduled during a run
45}
46
47// NewMaintainer builds a maintainer. ctx carries the logger; its cancellation
48// is not followed, call Close. A zero delay means MaintenanceDelay.
49func NewMaintainer(ctx context.Context, git ports.GitRepos, delay time.Duration) *Maintainer {
50 if delay <= 0 {
51 delay = MaintenanceDelay
52 }
53 run, stop := context.WithCancel(context.WithoutCancel(ctx))
54 return &Maintainer{git: git, delay: delay, ctx: run, stop: stop, entries: make(map[domain.RepoName]*maintEntry)}
55}
56
57// WithFreshener makes every run tell the reader, when it ends, that the
58// repository changed: the commit-graph it wrote is for the reader to pick up.
59// Call it before the first Schedule; it returns m.
60func (m *Maintainer) WithFreshener(f ports.RepoFreshener) *Maintainer {
61 m.fresh = f
62 return m
63}
64
65// Schedule queues maintenance of the repository.
66func (m *Maintainer) Schedule(ctx context.Context, name domain.RepoName) {
67 m.mu.Lock()
68 defer m.mu.Unlock()
69 if m.closed {
70 return
71 }
72 e := m.entries[name]
73 switch {
74 case e == nil:
75 e = &maintEntry{}
76 m.entries[name] = e
77 m.arm(name, e)
78 log := zerowrap.FromCtx(ctx)
79 log.Debug().Str("repo", name.String()).Dur("delay", m.delay).Msg("repository maintenance scheduled")
80 case e.running:
81 e.again = true
82 }
83 // A timer is already pending: this push joins it.
84}
85
86// arm starts the timer of e. The caller holds mu.
87func (m *Maintainer) arm(name domain.RepoName, e *maintEntry) {
88 m.wg.Add(1) // released when the timer fires or is stopped by Close
89 e.timer = time.AfterFunc(m.delay, func() { m.run(name, e) })
90}
91
92func (m *Maintainer) run(name domain.RepoName, e *maintEntry) {
93 defer m.wg.Done()
94 m.mu.Lock()
95 if m.closed {
96 delete(m.entries, name)
97 m.mu.Unlock()
98 return
99 }
100 e.timer, e.running = nil, true
101 m.mu.Unlock()
102
103 log := zerowrap.FromCtx(m.ctx)
104 start := time.Now()
105 if err := m.git.Maintain(m.ctx, name); err != nil {
106 log.Warn().Err(err).Str("repo", name.String()).Msg("repository maintenance failed")
107 } else {
108 log.Debug().Str("repo", name.String()).Dur("duration", time.Since(start)).Msg("repository maintained")
109 }
110 if m.fresh != nil {
111 m.fresh.Refresh(m.ctx, name) // whatever the outcome: git may have written something
112 }
113
114 m.mu.Lock()
115 defer m.mu.Unlock()
116 e.running = false
117 if e.again && !m.closed {
118 e.again = false
119 m.arm(name, e)
120 return
121 }
122 delete(m.entries, name)
123}
124
125// Close stops pending runs, cancels the one in progress and waits for it.
126func (m *Maintainer) Close(_ context.Context) {
127 m.mu.Lock()
128 m.closed = true
129 for _, e := range m.entries {
130 if e.timer != nil && e.timer.Stop() {
131 m.wg.Done() // the timer will never fire
132 e.timer = nil
133 }
134 }
135 m.mu.Unlock()
136 m.stop()
137 m.wg.Wait()
138}