-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
middlewares.go
76 lines (71 loc) · 1.61 KB
/
middlewares.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
package server
import (
"container/list"
"context"
"sync"
"time"
"github.com/Mrs4s/go-cqhttp/coolq"
"github.com/Mrs4s/go-cqhttp/global"
"github.com/Mrs4s/go-cqhttp/modules/api"
"golang.org/x/time/rate"
)
func rateLimit(frequency float64, bucketSize int) api.Handler {
limiter := rate.NewLimiter(rate.Limit(frequency), bucketSize)
return func(_ string, _ api.Getter) global.MSG {
_ = limiter.Wait(context.Background())
return nil
}
}
func longPolling(bot *coolq.CQBot, maxSize int) api.Handler {
var mutex sync.Mutex
cond := sync.NewCond(&mutex)
queue := list.New()
bot.OnEventPush(func(event *coolq.Event) {
mutex.Lock()
defer mutex.Unlock()
queue.PushBack(event.RawMsg)
for maxSize != 0 && queue.Len() > maxSize {
queue.Remove(queue.Front())
}
cond.Signal()
})
return func(action string, p api.Getter) global.MSG {
if action != "get_updates" {
return nil
}
var (
once sync.Once
ch = make(chan []interface{}, 1)
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
)
defer close(ch)
go func() {
mutex.Lock()
defer mutex.Unlock()
if queue.Len() == 0 {
cond.Wait()
}
once.Do(func() {
limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit {
limit = queue.Len()
}
ret := make([]interface{}, limit)
for i := 0; i < limit; i++ {
ret[i] = queue.Remove(queue.Front())
}
ch <- ret
})
}()
if timeout != 0 {
select {
case <-time.After(timeout):
once.Do(func() {})
return coolq.OK([]interface{}{})
case ret := <-ch:
return coolq.OK(ret)
}
}
return coolq.OK(<-ch)
}
}