-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
middlewares.go
91 lines (85 loc) · 2.01 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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"
)
// MiddleWares 通信中间件
type MiddleWares struct {
AccessToken string `yaml:"access-token"`
Filter string `yaml:"filter"`
RateLimit struct {
Enabled bool `yaml:"enabled"`
Frequency float64 `yaml:"frequency"`
Bucket int `yaml:"bucket"`
} `yaml:"rate-limit"`
}
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.Raw)
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 (
ch = make(chan []interface{})
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
)
go func() {
mutex.Lock()
defer mutex.Unlock()
for queue.Len() == 0 {
cond.Wait()
}
limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit {
limit = queue.Len()
}
ret := make([]interface{}, limit)
elem := queue.Front()
for i := 0; i < limit; i++ {
ret[i] = elem.Value
elem = elem.Next()
}
select {
case ch <- ret:
for i := 0; i < limit; i++ { // remove sent msg
queue.Remove(queue.Front())
}
default:
// don't block if parent already return due to timeout
}
}()
if timeout != 0 {
select {
case <-time.After(timeout):
return coolq.OK([]interface{}{})
case ret := <-ch:
return coolq.OK(ret)
}
}
return coolq.OK(<-ch)
}
}