forked from urnetwork/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
334 lines (292 loc) · 6.57 KB
/
util.go
File metadata and controls
334 lines (292 loc) · 6.57 KB
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
package connect
import (
"context"
"os"
"os/signal"
"slices"
"sync"
"syscall"
"time"
// "fmt"
// "runtime/debug"
// "strings"
// "encoding/json"
// "reflect"
mathrand "math/rand"
)
type Monitor struct {
mutex sync.Mutex
notify chan struct{}
}
func NewMonitor() *Monitor {
return &Monitor{
notify: make(chan struct{}),
}
}
func (self *Monitor) NotifyChannel() chan struct{} {
self.mutex.Lock()
defer self.mutex.Unlock()
return self.notify
}
func (self *Monitor) NotifyAll() chan struct{} {
self.mutex.Lock()
defer self.mutex.Unlock()
close(self.notify)
self.notify = make(chan struct{})
return self.notify
}
// makes a copy of the list on update
type CallbackList[T any] struct {
mutex sync.Mutex
// `callbacks` and `callbackIds` are parallel arrays
callbacks []T
callbackIds []int
nextCallbackId int
}
func NewCallbackList[T any]() *CallbackList[T] {
return &CallbackList[T]{
callbacks: []T{},
callbackIds: []int{},
nextCallbackId: 0,
}
}
func (self *CallbackList[T]) Get() []T {
self.mutex.Lock()
defer self.mutex.Unlock()
return self.callbacks
}
func (self *CallbackList[T]) Add(callback T) int {
self.mutex.Lock()
defer self.mutex.Unlock()
callbackId := self.nextCallbackId
self.nextCallbackId += 1
nextCallbacks := slices.Clone(self.callbacks)
nextCallbacks = append(nextCallbacks, callback)
self.callbacks = nextCallbacks
nextCallbackIds := slices.Clone(self.callbackIds)
nextCallbackIds = append(nextCallbackIds, callbackId)
self.callbackIds = nextCallbackIds
return callbackId
}
func (self *CallbackList[T]) Remove(callbackId int) {
self.mutex.Lock()
defer self.mutex.Unlock()
i, found := slices.BinarySearch(self.callbackIds, callbackId)
if !found {
// not present
return
}
nextCallbacks := slices.Clone(self.callbacks)
nextCallbacks = slices.Delete(nextCallbacks, i, i+1)
self.callbacks = nextCallbacks
nextCallbackIds := slices.Clone(self.callbackIds)
nextCallbackIds = slices.Delete(nextCallbackIds, i, i+1)
self.callbackIds = nextCallbackIds
}
// this coordinates and idle shutdown when the shutdown and adding to the work channel are on separate goroutines
type IdleCondition struct {
mutex *sync.Mutex
condition *sync.Cond
modId uint64
updateOpenCount int
closed bool
}
func NewIdleCondition() *IdleCondition {
mutex := &sync.Mutex{}
condition := sync.NewCond(mutex)
return &IdleCondition{
mutex: mutex,
condition: condition,
modId: 0,
updateOpenCount: 0,
closed: false,
}
}
func (self *IdleCondition) Checkpoint() uint64 {
self.mutex.Lock()
defer self.mutex.Unlock()
return self.modId
}
func (self *IdleCondition) Close(checkpointId uint64) bool {
self.mutex.Lock()
defer self.mutex.Unlock()
if self.modId != checkpointId {
return false
}
if 0 < self.updateOpenCount {
return false
}
self.closed = true
return true
}
func (self *IdleCondition) WaitForClose() bool {
self.mutex.Lock()
defer self.mutex.Unlock()
for 0 < self.updateOpenCount {
self.condition.Wait()
}
self.closed = true
return true
}
func (self *IdleCondition) UpdateOpen() bool {
self.mutex.Lock()
defer self.mutex.Unlock()
if self.closed {
return false
}
self.modId += 1
self.updateOpenCount += 1
return true
}
func (self *IdleCondition) UpdateClose() {
self.mutex.Lock()
defer self.mutex.Unlock()
self.updateOpenCount -= 1
self.condition.Signal()
}
func MinTime(a time.Time, bs ...time.Time) time.Time {
min := a
for _, b := range bs {
if b.Before(min) {
min = b
}
}
return min
}
type Event struct {
ctx context.Context
cancel context.CancelFunc
}
func NewEvent() *Event {
return NewEventWithContext(context.Background())
}
func NewEventWithContext(ctx context.Context) *Event {
cancelCtx, cancel := context.WithCancel(ctx)
return &Event{
ctx: cancelCtx,
cancel: cancel,
}
}
func (self *Event) Ctx() context.Context {
return self.ctx
}
func (self *Event) Set() {
self.cancel()
}
func (self *Event) IsSet() bool {
select {
case <-self.ctx.Done():
return true
default:
return false
}
}
func (self *Event) WaitForSet(timeout time.Duration) bool {
select {
case <-self.ctx.Done():
return true
case <-time.After(timeout):
return false
}
}
func (self *Event) SetOnSignals(signalValues ...syscall.Signal) func() {
stopSignal := make(chan os.Signal, len(signalValues))
for _, signalValue := range signalValues {
signal.Notify(stopSignal, signalValue)
}
go func() {
for {
select {
case _, ok := <-stopSignal:
if !ok {
return
}
self.Set()
}
}
}()
return func() {
signal.Stop(stopSignal)
close(stopSignal)
}
}
func WeightedShuffle[T comparable](values []T, weights map[T]float32) {
WeightedShuffleWithEntropy[T](values, weights, 0)
}
func WeightedShuffleWithEntropy[T comparable](values []T, weights map[T]float32, entropy float32) {
mathrand.Shuffle(len(values), func(i int, j int) {
values[i], values[j] = values[j], values[i]
})
n := len(values)
for i := 0; i < n-1; i += 1 {
j := func() int {
var net float32
net = 0
for j := i; j < n; j += 1 {
net += weights[values[j]]
}
r := mathrand.Float32()
rnet := r * net
net = entropy * net
for j := i; j < n; j += 1 {
net += weights[values[j]]
if rnet < net {
return j
}
}
// zero weights, use the last value
return n - 1
}()
values[i], values[j] = values[j], values[i]
}
}
func WeightedShuffleFunc[T comparable](values []T, weight func(T) float32) {
WeightedShuffleFuncWithEntropy[T](values, weight, 0)
}
func WeightedShuffleFuncWithEntropy[T comparable](values []T, weight func(T) float32, entropy float32) {
mathrand.Shuffle(len(values), func(i int, j int) {
values[i], values[j] = values[j], values[i]
})
n := len(values)
for i := 0; i < n-1; i += 1 {
j := func() int {
var net float32
net = 0
for j := i; j < n; j += 1 {
net += weight(values[j])
}
r := mathrand.Float32()
rnet := r * net
net = entropy * net
for j := i; j < n; j += 1 {
net += weight(values[j])
if rnet < net {
return j
}
}
// zero weights, use the last value
return n - 1
}()
values[i], values[j] = values[j], values[i]
}
}
type Reconnect struct {
startTime time.Time
minTimeout time.Duration
}
func NewReconnect(minTimeout time.Duration) *Reconnect {
return &Reconnect{
startTime: time.Now(),
minTimeout: minTimeout,
}
}
func (self *Reconnect) After() <-chan time.Time {
timeout := self.minTimeout - time.Now().Sub(self.startTime)
if timeout <= 0 {
c := make(chan time.Time)
close(c)
return c
} else {
return time.After(timeout)
}
}