summaryrefslogtreecommitdiff
path: root/vendor/codeberg.org/gruf/go-runners/service.go
blob: fe41807f9670d3e8a8ded96813c4c40402a92888 (plain)
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
216
217
218
219
220
221
222
package runners

import (
	"context"
	"sync"
	"sync/atomic"
	"unsafe"
)

// Service provides a means of tracking a single long-running Service, provided protected state
// changes and preventing multiple instances running. Also providing Service state information.
type Service struct{ p atomic_pointer }

// Run will run the supplied function until completion, using given context to propagate cancel.
// Immediately returns false if the Service is already running, and true after completed run.
func (svc *Service) Run(fn func(context.Context)) (ok bool) {
	var ptr *svc_instance

	// Attempt to start.
	ptr, ok = svc.start()
	if !ok {
		return
	}

	// Run given function.
	defer svc.on_done(ptr)
	fn(CancelCtx(ptr.done))
	return
}

// GoRun will run the supplied function until completion in a goroutine, using given context to
// propagate cancel. Immediately returns boolean indicating success, or that service is already running.
func (svc *Service) GoRun(fn func(context.Context)) (ok bool) {
	var ptr *svc_instance

	// Attempt to start.
	ptr, ok = svc.start()
	if !ok {
		return
	}

	go func() {
		// Run given function.
		defer svc.on_done(ptr)
		fn(CancelCtx(ptr.done))
	}()

	return
}

// RunWait is functionally the same as .Run(), but blocks until the first instance of .Run() returns.
func (svc *Service) RunWait(fn func(context.Context)) (ok bool) {
	var ptr *svc_instance

	// Attempt to start.
	ptr, ok = svc.start()
	if !ok {
		<-ptr.done
		return
	}

	// Run given function.
	defer svc.on_done(ptr)
	fn(CancelCtx(ptr.done))
	return
}

// GoRunWait is functionally the same as .RunWait(), but blocks until the first instance of RunWait() returns.
func (svc *Service) GoRunWait(fn func(context.Context)) (ok bool) {
	var ptr *svc_instance

	// Attempt to start.
	ptr, ok = svc.start()
	if !ok {
		<-ptr.done
		return
	}

	go func() {
		// Run given function.
		defer svc.on_done(ptr)
		fn(CancelCtx(ptr.done))
	}()

	return
}

// Stop will attempt to stop the service, cancelling the running function's context. Immediately
// returns false if not running, and true only after Service is fully stopped.
func (svc *Service) Stop() bool {
	return svc.must_get().stop()
}

// Running returns if Service is running (i.e. NOT fully stopped, but may be *stopping*).
func (svc *Service) Running() bool {
	return svc.must_get().running()
}

// Done returns a channel that's closed when Service.Stop() is called. It is
// the same channel provided to the currently running service function.
func (svc *Service) Done() <-chan struct{} {
	return svc.must_get().done
}

func (svc *Service) start() (*svc_instance, bool) {
	ptr := svc.must_get()
	return ptr, ptr.start()
}

func (svc *Service) on_done(ptr *svc_instance) {
	// Ensure stopped.
	ptr.stop_private()

	// Free service.
	svc.p.Store(nil)
}

func (svc *Service) must_get() *svc_instance {
	var newptr *svc_instance

	for {
		// Try to load existing instance.
		ptr := (*svc_instance)(svc.p.Load())
		if ptr != nil {
			return ptr
		}

		if newptr == nil {
			// Allocate new instance.
			newptr = new(svc_instance)
			newptr.done = make(chan struct{})
		}

		// Attempt to acquire slot by setting our ptr.
		if !svc.p.CAS(nil, unsafe.Pointer(newptr)) {
			continue
		}

		return newptr
	}
}

type svc_instance struct {
	wait  sync.WaitGroup
	done  chan struct{}
	state atomic.Uint32
}

const (
	started_bit  = uint32(1) << 0
	stopping_bit = uint32(1) << 1
	finished_bit = uint32(1) << 2
)

func (i *svc_instance) start() (ok bool) {
	// Acquire start by setting 'started' bit.
	switch old := i.state.Or(started_bit); {

	case old&finished_bit != 0:
		// Already finished.

	case old&started_bit == 0:
		// Successfully started!
		i.wait.Add(1)
		ok = true
	}

	return
}

// NOTE: MAY ONLY BE CALLED BY STARTING GOROUTINE.
func (i *svc_instance) stop_private() {
	// Attempt set both stopping and finished bits.
	old := i.state.Or(stopping_bit | finished_bit)

	// Only if we weren't already
	// stopping do we close channel.
	if old&stopping_bit == 0 {
		close(i.done)
	}

	// Release
	// waiters.
	i.wait.Done()
}

func (i *svc_instance) stop() (ok bool) {
	// Attempt to set the 'stopping' bit.
	switch old := i.state.Or(stopping_bit); {

	case old&finished_bit != 0:
		// Already finished.
		return

	case old&started_bit == 0:
		// This was never started
		// to begin with, just mark
		// as fully finished here.
		_ = i.state.Or(finished_bit)
		return

	case old&stopping_bit == 0:
		// We succesfully stopped
		// instance, close channel.
		close(i.done)
		ok = true
	}

	// Wait on stop.
	i.wait.Wait()
	return
}

// running returns whether service was started and
// is not yet finished. that indicates that it may
// have been started and not yet stopped, or that
// it was started, stopped and not yet returned.
func (i *svc_instance) running() bool {
	val := i.state.Load()
	return val&started_bit != 0 &&
		val&finished_bit == 0
}