-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
114 lines (91 loc) · 2.21 KB
/
watcher.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
// Copyright 2020 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package main
import (
"fmt"
"sync"
"time"
"github.com/google/uuid"
)
// The active watcher data structure
type activeWatcher struct {
watcherID string
target string
event *Event
buf []byte
}
var watchers = []activeWatcher{}
var watcherLock sync.RWMutex
// Create a new watcher
func watcherCreate(target string) (watcherID string) {
watcherID = uuid.New().String()
watcher := activeWatcher{}
watcher.watcherID = watcherID
watcher.target = target
watcher.event = EventNew()
watcherLock.Lock()
watchers = append(watchers, watcher)
fmt.Printf("watchers: %s added (now %d)\n", watcher.target, len(watchers))
watcherLock.Unlock()
return
}
// Delete a watcher
func watcherDelete(watcherID string) {
watcherLock.Lock()
numWatchers := len(watchers)
for i, watcher := range watchers {
if watcher.watcherID == watcherID {
if i == numWatchers-1 {
watchers = watchers[0:i]
} else {
watchers = append(watchers[0:i], watchers[i+1:]...)
}
fmt.Printf("watchers: %s removed (now %d)\n", watcher.target, len(watchers))
break
}
}
watcherLock.Unlock()
}
// Get data from a watcher
func watcherGet(watcherID string, timeout time.Duration) (data []byte, err error) {
var watcher activeWatcher
// Find the watcher
watcherLock.Lock()
for _, watcher = range watchers {
if watcher.watcherID == watcherID {
break
}
}
watcherLock.Unlock()
// If not found, we're done
if watcher.watcherID != watcherID {
err = fmt.Errorf("watcher not found")
return
}
// Wait with timeout
watcher.event.Wait(timeout)
// Get the buffer
watcherLock.Lock()
for i := range watchers {
if watchers[i].watcherID == watcherID {
data = watchers[i].buf
watchers[i].buf = []byte{}
break
}
}
watcherLock.Unlock()
return
}
// Append data from a watcher
func watcherPut(target string, data []byte) {
// Scan all watchers
watcherLock.Lock()
for i := range watchers {
if watchers[i].target == target {
watchers[i].buf = append(watchers[i].buf, data...)
watchers[i].event.Signal()
}
}
watcherLock.Unlock()
}