2014-07-10 12:19:39 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2014-07-16 18:57:54 +00:00
|
|
|
"sync"
|
2014-07-10 12:19:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Request struct {
|
|
|
|
Queues []string
|
|
|
|
Callback func(*Response)
|
2014-07-16 17:50:05 +00:00
|
|
|
Abort chan bool
|
2014-07-16 18:57:54 +00:00
|
|
|
Dead bool
|
2014-07-10 12:19:39 +00:00
|
|
|
}
|
|
|
|
Response struct {
|
|
|
|
Queue string
|
|
|
|
Message Message
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2014-07-16 18:57:54 +00:00
|
|
|
pool struct {
|
|
|
|
Requests []*Request
|
|
|
|
mutex sync.Mutex
|
|
|
|
}
|
2014-07-10 12:19:39 +00:00
|
|
|
)
|
|
|
|
|
2014-07-16 18:57:54 +00:00
|
|
|
func RegisterPublication(q string, msg Message) bool {
|
|
|
|
pool.mutex.Lock()
|
|
|
|
for i, r := range pool.Requests {
|
2014-07-10 12:19:39 +00:00
|
|
|
for _, queueName := range r.Queues {
|
|
|
|
if queueName == q {
|
|
|
|
go r.Callback(&Response{Queue: queueName, Message: msg})
|
2014-07-16 18:57:54 +00:00
|
|
|
pool.Requests = append(pool.Requests[:i], pool.Requests[i+1:]...)
|
|
|
|
defer pool.mutex.Unlock()
|
2014-07-16 17:50:05 +00:00
|
|
|
|
|
|
|
return true
|
2014-07-10 12:19:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-07-16 18:57:54 +00:00
|
|
|
pool.mutex.Unlock()
|
2014-07-16 17:50:05 +00:00
|
|
|
|
|
|
|
ok := GetQueue(q).Push(msg)
|
|
|
|
return ok
|
2014-07-10 12:19:39 +00:00
|
|
|
}
|
|
|
|
|
2014-07-16 18:57:54 +00:00
|
|
|
func RegisterSubscription(r *Request) {
|
2014-07-10 12:19:39 +00:00
|
|
|
for _, queueName := range r.Queues {
|
|
|
|
q := GetQueue(queueName)
|
2014-07-16 17:50:05 +00:00
|
|
|
msg, ok := q.TryFetch(r.Abort)
|
2014-07-12 10:42:26 +00:00
|
|
|
if ok {
|
|
|
|
go r.Callback(&Response{Queue: queueName, Message: msg})
|
2014-07-10 12:19:39 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2014-07-16 18:57:54 +00:00
|
|
|
|
|
|
|
pool.mutex.Lock()
|
|
|
|
pool.Requests = append(pool.Requests, r)
|
|
|
|
pool.mutex.Unlock()
|
2014-07-10 12:19:39 +00:00
|
|
|
}
|
|
|
|
|
2014-07-16 18:57:54 +00:00
|
|
|
func (r *Request) Purge() {
|
|
|
|
pool.mutex.Lock()
|
|
|
|
defer pool.mutex.Unlock()
|
|
|
|
|
|
|
|
r.Dead = true
|
|
|
|
deleted := 0
|
|
|
|
for i, req := range pool.Requests {
|
|
|
|
if req.Dead {
|
|
|
|
pool.Requests = append(pool.Requests[:i-deleted], pool.Requests[i-deleted+1:]...)
|
|
|
|
deleted++
|
2014-07-10 12:19:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|