-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcomm_http.go
219 lines (192 loc) · 5.56 KB
/
comm_http.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
// OneBot Connect - 通信方式 - HTTP
// https://12.onebot.dev/connect/communication/http/
package libonebot
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/tevino/abool/v2"
)
type httpComm struct {
ob *OneBot
config ConfigCommHTTP
authorizer *httpAuthorizer
eventEnabled bool
eventBufferSize uint32
latestEvents []marshaledEvent
latestEventsLock *sync.Mutex
latestEventsCond *sync.Cond
}
func (comm *httpComm) handle(w http.ResponseWriter, r *http.Request) {
comm.ob.Logger.Debugf("HTTP request: %v", r)
// reject unsupported methods
if r.Method != "POST" {
comm.ob.Logger.Errorf("动作请求不支持通过 %v 方式请求", r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// authorization
if !comm.authorizer.authorize(r) {
comm.ob.Logger.Errorf("请求鉴权失败")
w.WriteHeader(http.StatusUnauthorized)
return
}
var isBinary bool
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
isBinary = false
contentType = "application/json"
} else if strings.HasPrefix(contentType, "application/msgpack") {
isBinary = true
contentType = "application/msgpack"
} else {
// reject unsupported content types
comm.ob.Logger.Errorf("请求头中的 Content-Type 不支持")
w.WriteHeader(http.StatusUnsupportedMediaType)
return
}
// once we got the action HTTP request, we respond "200 OK"
w.Header().Set("Content-Type", contentType)
w.WriteHeader(http.StatusOK)
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
comm.fail(w, RetCodeBadRequest, "动作请求读取失败, 错误: %v", err)
return
}
request, err := decodeRequest(bodyBytes, isBinary, RequestComm{
Method: CommMethodHTTP,
Config: comm.config,
})
if err != nil {
comm.fail(w, RetCodeBadRequest, "动作请求解析失败, 错误: %v", err)
return
}
var response Response
if comm.eventEnabled && request.Action == ActionGetLatestEvents {
// special action: get_latest_events
response = comm.handleGetLatestEvents(&request)
} else {
response = comm.ob.handleRequest(&request)
}
respBytes, _ := comm.ob.encodeResponse(response, isBinary)
w.Write(respBytes)
}
func (comm *httpComm) handleGetLatestEvents(r *Request) (resp Response) {
resp.Echo = r.Echo
w := ResponseWriter{resp: &resp}
timeout, err := r.Params.GetInt64("timeout")
if err != nil {
timeout = 0 // 0 for no wait
}
if timeout < 0 {
w.WriteFailed(RetCodeBadParam, errors.New("`timeout` 参数值无效"))
return
}
limit, err := r.Params.GetInt64("limit")
if err != nil {
limit = 0 // 0 for no limit
}
if limit < 0 {
w.WriteFailed(RetCodeBadParam, errors.New("`limit` 参数值无效"))
return
}
comm.latestEventsLock.Lock()
defer comm.latestEventsLock.Unlock()
if timeout > 0 && len(comm.latestEvents) == 0 {
// wait for new events or timeout
isTimeout := abool.New()
timer := time.AfterFunc(time.Duration(timeout)*time.Millisecond, func() {
isTimeout.Set()
comm.latestEventsCond.Broadcast() // wake up everyone because everyone may be out of time
// but note, calling get_latest_events concurrently is undefined behavior
})
for {
comm.latestEventsCond.Wait()
if len(comm.latestEvents) > 0 || isTimeout.IsSet() {
break
}
}
timer.Stop()
}
eventCount := int64(len(comm.latestEvents))
if limit == 0 || limit > eventCount {
// if no limit, return all events
limit = eventCount
}
events := make([]AnyEvent, 0)
for _, event := range comm.latestEvents[:limit] {
events = append(events, event.raw)
}
comm.latestEvents = comm.latestEvents[limit:]
w.WriteData(events)
return
}
func (comm *httpComm) fail(w http.ResponseWriter, retcode int, errFormat string, args ...interface{}) {
err := fmt.Errorf(errFormat, args...)
comm.ob.Logger.Warn(err)
json.NewEncoder(w).Encode(failedResponse(retcode, err))
}
func commRunHTTP(c ConfigCommHTTP, ob *OneBot, ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
addr := fmt.Sprintf("%s:%d", c.Host, c.Port)
ob.Logger.Infof("正在启动 HTTP (%v)...", addr)
comm := &httpComm{
ob: ob,
config: c,
authorizer: &httpAuthorizer{
accessToken: c.AccessToken,
},
eventEnabled: c.EventEnabled,
eventBufferSize: c.EventBufferSize,
latestEvents: make([]marshaledEvent, 0),
latestEventsLock: &sync.Mutex{},
}
comm.latestEventsCond = sync.NewCond(comm.latestEventsLock)
mux := http.NewServeMux()
mux.HandleFunc("/", comm.handle)
server := &http.Server{
Addr: addr,
Handler: mux,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
ob.Logger.Errorf("HTTP (%v) 启动失败, 错误: %v", addr, err)
}
}()
if comm.eventEnabled {
eventChan := ob.openEventListenChan()
defer ob.closeEventListenChan(eventChan)
loop:
for {
select {
case event := <-eventChan:
if _, ok := event.raw.(*HeartbeatMetaEvent); ok {
// ignore heartbeat event
continue
}
comm.latestEventsLock.Lock()
if comm.eventBufferSize > 0 && len(comm.latestEvents) >= int(comm.eventBufferSize) {
comm.latestEvents = append(comm.latestEvents[1:], event)
} else {
comm.latestEvents = append(comm.latestEvents, event)
}
comm.latestEventsLock.Unlock()
comm.latestEventsCond.Signal() // notify someone to take the events
case <-ctx.Done():
break loop
}
}
} else {
<-ctx.Done()
}
if err := server.Shutdown(context.TODO()); err != nil {
ob.Logger.Errorf("HTTP (%v) 关闭失败, 错误: %v", addr, err)
}
ob.Logger.Infof("HTTP (%v) 已关闭", addr)
}