File: group.go

package info (click to toggle)
golang-github-protonmail-gluon 0.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,020 kB
  • sloc: sh: 55; makefile: 5
file content (215 lines) | stat: -rw-r--r-- 4,648 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package async

import (
	"context"
	"math/rand"
	"sync"
	"time"
)

// Group is forked and improved version of "github.com/bradenaw/juniper/xsync.Group".
//
// It manages a group of goroutines. The main change to original is posibility
// to wait passed function to finish without canceling it's context and adding
// PanicHandler.
type Group struct {
	baseCtx context.Context
	ctx     context.Context
	jobCtx  context.Context
	cancel  context.CancelFunc
	finish  context.CancelFunc
	wg      sync.WaitGroup

	panicHandler PanicHandler
}

// NewGroup returns a Group ready for use. The context passed to any of the f functions will be a
// descendant of ctx.
func NewGroup(ctx context.Context, panicHandler PanicHandler) *Group {
	bgCtx, cancel := context.WithCancel(ctx)
	jobCtx, finish := context.WithCancel(ctx)

	return &Group{
		baseCtx:      ctx,
		ctx:          bgCtx,
		jobCtx:       jobCtx,
		cancel:       cancel,
		finish:       finish,
		panicHandler: panicHandler,
	}
}

// Once calls f once from another goroutine.
func (g *Group) Once(f func(ctx context.Context)) {
	g.wg.Add(1)

	go func() {
		defer HandlePanic(g.panicHandler)

		defer g.wg.Done()

		f(g.ctx)
	}()
}

// jitterDuration returns a random duration in [d - jitter, d + jitter].
func jitterDuration(d time.Duration, jitter time.Duration) time.Duration {
	return d + time.Duration(float64(jitter)*((rand.Float64()*2)-1)) //nolint:gosec
}

// Periodic spawns a goroutine that calls f once per interval +/- jitter.
func (g *Group) Periodic(
	interval time.Duration,
	jitter time.Duration,
	f func(ctx context.Context),
) {
	g.wg.Add(1)

	go func() {
		defer HandlePanic(g.panicHandler)

		defer g.wg.Done()

		t := time.NewTimer(jitterDuration(interval, jitter))
		defer t.Stop()

		for {
			if g.ctx.Err() != nil {
				return
			}

			select {
			case <-g.jobCtx.Done():
				return
			case <-t.C:
			}

			t.Reset(jitterDuration(interval, jitter))
			f(g.ctx)
		}
	}()
}

// Trigger spawns a goroutine which calls f whenever the returned function is called. If f is
// already running when triggered, f will run again immediately when it finishes.
func (g *Group) Trigger(f func(ctx context.Context)) func() {
	c := make(chan struct{}, 1)

	g.wg.Add(1)

	go func() {
		defer HandlePanic(g.panicHandler)

		defer g.wg.Done()

		for {
			if g.ctx.Err() != nil {
				return
			}
			select {
			case <-g.jobCtx.Done():
				return
			case <-c:
			}
			f(g.ctx)
		}
	}()

	return func() {
		select {
		case c <- struct{}{}:
		default:
		}
	}
}

// PeriodicOrTrigger spawns a goroutine which calls f whenever the returned function is called.  If
// f is already running when triggered, f will run again immediately when it finishes. Also calls f
// when it has been interval+/-jitter since the last trigger.
func (g *Group) PeriodicOrTrigger(
	interval time.Duration,
	jitter time.Duration,
	f func(ctx context.Context),
) func() {
	c := make(chan struct{}, 1)

	g.wg.Add(1)

	go func() {
		defer HandlePanic(g.panicHandler)

		defer g.wg.Done()

		t := time.NewTimer(jitterDuration(interval, jitter))
		defer t.Stop()

		for {
			if g.ctx.Err() != nil {
				return
			}
			select {
			case <-g.jobCtx.Done():
				return
			case <-t.C:
				t.Reset(jitterDuration(interval, jitter))
			case <-c:
				if !t.Stop() {
					<-t.C
				}

				t.Reset(jitterDuration(interval, jitter))
			}
			f(g.ctx)
		}
	}()

	return func() {
		select {
		case c <- struct{}{}:
		default:
		}
	}
}

func (g *Group) resetCtx() {
	g.jobCtx, g.finish = context.WithCancel(g.baseCtx)
	g.ctx, g.cancel = context.WithCancel(g.baseCtx)
}

// Cancel is send to all of the spawn goroutines and ends periodic
// or trigger routines.
func (g *Group) Cancel() {
	g.cancel()
	g.finish()
	g.resetCtx()
}

// Finish will ends all periodic or polls routines. It will let
// currently running functions to finish (cancel is not sent).
//
// It is not safe to call Wait concurrently with any other method on g.
func (g *Group) Finish() {
	g.finish()
	g.jobCtx, g.finish = context.WithCancel(g.baseCtx)
}

// CancelAndWait cancels the context passed to any of the spawned goroutines and waits for all spawned
// goroutines to exit.
//
// It is not safe to call Wait concurrently with any other method on g.
func (g *Group) CancelAndWait() {
	g.finish()
	g.cancel()
	g.wg.Wait()
	g.resetCtx()
}

// WaitToFinish will ends all periodic or polls routines. It will wait for
// currently running functions to finish (cancel is not sent).
//
// It is not safe to call Wait concurrently with any other method on g.
func (g *Group) WaitToFinish() {
	g.finish()
	g.wg.Wait()
	g.jobCtx, g.finish = context.WithCancel(g.baseCtx)
}