-
Notifications
You must be signed in to change notification settings - Fork 17
/
machine.go
337 lines (305 loc) · 7.95 KB
/
machine.go
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package machine
import (
"context"
"log"
"math/rand"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
// Handler is a first class that is executed against the inbound message in a subscription.
// Return false to indicate that the subscription should end
type MessageHandlerFunc func(ctx context.Context, msg Message) (bool, error)
// Filter is a first class function to filter out messages before they reach a subscriptions primary Handler
// Return true to indicate that a message passes the filter
type MessageFilterFunc func(ctx context.Context, msg Message) (bool, error)
// Func is a first class function that is asynchronously executed.
type Func func(ctx context.Context) error
// CronFunc is a first class function that is asynchronously executed on a timed interval.
// Return false to indicate that the cron should end
type CronFunc func(ctx context.Context) (bool, error)
// LoopFunc is a first class function that is asynchronously executed over and over again.
// Return false to indicate that the loop should end
type LoopFunc func(ctx context.Context) (bool, error)
// Machine is an interface for highly asynchronous Go applications
type Machine interface {
// Publish synchronously publishes the Message
Publish(ctx context.Context, msg Message)
// Subscribe synchronously subscribes to messages on a given channel, executing the given HandlerFunc UNTIL the context cancels OR false is returned by the HandlerFunc.
// Glob matching IS supported for subscribing to multiple channels at once.
Subscribe(ctx context.Context, channel string, handler MessageHandlerFunc, opts ...SubscriptionOpt)
// Go asynchronously executes the given Func
Go(ctx context.Context, fn Func)
// Cron asynchronously executes the given function on a timed interval UNTIL the context cancels OR false is returned by the CronFunc
Cron(ctx context.Context, interval time.Duration, fn CronFunc)
// Loop asynchronously executes the given function repeatedly UNTIL the context cancels OR false is returned by the LoopFunc
Loop(ctx context.Context, fn LoopFunc)
// Wait blocks until all active async functions(Loop, Go, Cron) exit
Wait()
// Close blocks until all active routine's exit(calls Wait) then closes all active subscriptions
Close()
}
// SubscriptionOptions holds config options for a subscription
type SubscriptionOptions struct {
filter MessageFilterFunc
}
// SubscriptionOpt configures a subscription
type SubscriptionOpt func(options *SubscriptionOptions)
// WithFilter is a subscription option that filters messages
func WithFilter(filter MessageFilterFunc) SubscriptionOpt {
return func(options *SubscriptionOptions) {
options.filter = filter
}
}
type machine struct {
errHandler func(err error)
started int64
finished int64
max int
subscriptions map[string]map[int]chan Message
subMu sync.RWMutex
errChan chan error
wg sync.WaitGroup
}
// Options holds config options for a machine instance
type Options struct {
maxRoutines int
errHandler func(err error)
}
// Opt configures a machine instance
type Opt func(o *Options)
// WithThrottledRoutines throttles the max number of active routine's spawned by the Machine.
func WithThrottledRoutines(max int) Opt {
return func(o *Options) {
o.maxRoutines = max
}
}
// WithErrHandler overrides the default machine error handler
func WithErrHandler(errHandler func(err error)) Opt {
return func(o *Options) {
o.errHandler = errHandler
}
}
// New creates a new Machine instance with the given options(if present)
func New(opts ...Opt) Machine {
options := &Options{}
for _, o := range opts {
o(options)
}
if options.errHandler != nil {
logger := log.New(os.Stderr, "machine/v2", log.Flags())
options.errHandler = func(err error) {
logger.Printf("runtime error: %v", err)
}
}
return &machine{
errHandler: options.errHandler,
started: 0,
finished: 0,
max: options.maxRoutines,
subscriptions: map[string]map[int]chan Message{},
subMu: sync.RWMutex{},
errChan: make(chan error),
wg: sync.WaitGroup{},
}
}
func (m *machine) Go(ctx context.Context, fn Func) {
if m.max > 0 {
for x := m.activeRoutines(); x >= m.max; x = m.activeRoutines() {
if ctx.Err() != nil {
return
}
}
}
atomic.AddInt64(&m.started, 1)
m.wg.Add(1)
go func() {
defer m.wg.Done()
defer atomic.AddInt64(&m.finished, 1)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if err := fn(ctx); err != nil {
m.errChan <- err
}
}()
}
func (m *machine) activeRoutines() int {
return int(atomic.LoadInt64(&m.started) - atomic.LoadInt64(&m.finished))
}
type Msg struct {
Channel string
Body interface{}
}
func (m Msg) GetChannel() string {
return m.Channel
}
func (m Msg) GetBody() interface{} {
return m.Body
}
type Message interface {
GetChannel() string
GetBody() interface{}
}
func (p *machine) Subscribe(ctx context.Context, channel string, handler MessageHandlerFunc, options ...SubscriptionOpt) {
opts := &SubscriptionOptions{}
for _, o := range options {
o(opts)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ch, closer := p.setupSubscription(channel)
defer closer()
for {
select {
case <-ctx.Done():
return
case msg := <-ch:
if opts.filter != nil {
res, err := opts.filter(ctx, msg)
if err != nil {
p.errChan <- err
}
if !res {
continue
}
}
contin, err := handler(ctx, msg)
if err != nil {
p.errChan <- err
continue
}
if !contin {
return
}
}
}
}
func (p *machine) Publish(ctx context.Context, msg Message) {
p.subMu.RLock()
subscribers := p.subscriptions
p.subMu.RUnlock()
for k, channelSubscribers := range subscribers {
if globMatch(k, msg.GetChannel()) {
for _, ch := range channelSubscribers {
if ctx.Err() != nil {
return
}
ch <- msg
}
}
}
return
}
func (m *machine) Wait() {
done := make(chan struct{}, 1)
go func() {
for {
select {
case <-done:
return
case err := <-m.errChan:
if m.errHandler != nil {
m.errHandler(err)
}
}
}
}()
m.wg.Wait()
done <- struct{}{}
}
func (p *machine) Close() {
p.wg.Wait()
p.subMu.Lock()
defer p.subMu.Unlock()
for k, _ := range p.subscriptions {
delete(p.subscriptions, k)
}
close(p.errChan)
}
func (m *machine) Cron(ctx context.Context, timeout time.Duration, fn CronFunc) {
m.Go(ctx, func(ctx context.Context) error {
ticker := time.NewTicker(timeout)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
contin, err := fn(ctx)
if err != nil {
m.errChan <- err
}
if !contin {
return nil
}
}
}
})
}
func (m *machine) Loop(ctx context.Context, fn LoopFunc) {
m.Go(ctx, func(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
default:
contin, err := fn(ctx)
if err != nil {
m.errChan <- err
}
if !contin {
return nil
}
}
}
})
}
func (p *machine) setupSubscription(channel string) (chan Message, func()) {
subId := rand.Int()
ch := make(chan Message, 10)
p.subMu.Lock()
if p.subscriptions[channel] == nil {
p.subscriptions[channel] = map[int]chan Message{}
}
p.subscriptions[channel][subId] = ch
p.subMu.Unlock()
return ch, func() {
p.subMu.Lock()
delete(p.subscriptions[channel], subId)
p.subMu.Unlock()
close(ch)
}
}
func globMatch(pattern string, subj string) bool {
const matchAll = "*"
if pattern == subj {
return true
}
if pattern == matchAll {
return true
}
parts := strings.Split(pattern, matchAll)
if len(parts) == 1 {
return subj == pattern
}
leadingGlob := strings.HasPrefix(pattern, matchAll)
trailingGlob := strings.HasSuffix(pattern, matchAll)
end := len(parts) - 1
for i := 0; i < end; i++ {
idx := strings.Index(subj, parts[i])
switch i {
case 0:
if !leadingGlob && idx != 0 {
return false
}
default:
if idx < 0 {
return false
}
}
subj = subj[idx+len(parts[i]):]
}
return trailingGlob || strings.HasSuffix(subj, parts[end])
}