1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00

server: simplify long poll implementation

This commit is contained in:
wdvxdr 2022-05-25 14:19:59 +08:00
parent 111a5506b9
commit 810c781c25
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6

View File

@ -50,33 +50,37 @@ func longPolling(bot *coolq.CQBot, maxSize int) api.Handler {
return nil return nil
} }
var ( var (
once sync.Once ch = make(chan []interface{})
ch = make(chan []interface{}, 1)
timeout = time.Duration(p.Get("timeout").Int()) * time.Second timeout = time.Duration(p.Get("timeout").Int()) * time.Second
) )
defer close(ch)
go func() { go func() {
mutex.Lock() mutex.Lock()
defer mutex.Unlock() defer mutex.Unlock()
if queue.Len() == 0 { for queue.Len() == 0 {
cond.Wait() cond.Wait()
} }
once.Do(func() { limit := int(p.Get("limit").Int())
limit := int(p.Get("limit").Int()) if limit <= 0 || queue.Len() < limit {
if limit <= 0 || queue.Len() < limit { limit = queue.Len()
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())
} }
ret := make([]interface{}, limit) default:
for i := 0; i < limit; i++ { // don't block if parent already return due to timeout
ret[i] = queue.Remove(queue.Front()) }
}
ch <- ret
})
}() }()
if timeout != 0 { if timeout != 0 {
select { select {
case <-time.After(timeout): case <-time.After(timeout):
once.Do(func() {})
return coolq.OK([]interface{}{}) return coolq.OK([]interface{}{})
case ret := <-ch: case ret := <-ch:
return coolq.OK(ret) return coolq.OK(ret)