2017-08-08 13:58:51 +02:00
|
|
|
package dht
|
|
|
|
|
2018-12-30 06:24:14 +01:00
|
|
|
import (
|
2019-01-05 19:35:13 +01:00
|
|
|
"net"
|
2018-12-30 06:24:14 +01:00
|
|
|
"time"
|
2019-01-05 19:35:13 +01:00
|
|
|
|
|
|
|
"go.uber.org/zap"
|
|
|
|
|
|
|
|
"github.com/boramalper/magnetico/cmd/magneticod/dht/mainline"
|
2018-12-30 06:24:14 +01:00
|
|
|
)
|
2017-08-08 13:58:51 +02:00
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
type Service interface {
|
|
|
|
Start()
|
|
|
|
Terminate()
|
2017-08-08 13:58:51 +02:00
|
|
|
}
|
|
|
|
|
2019-01-05 19:35:13 +01:00
|
|
|
type Result interface {
|
|
|
|
InfoHash() [20]byte
|
2019-05-19 01:07:37 +02:00
|
|
|
PeerAddrs() []net.TCPAddr
|
2019-01-05 19:35:13 +01:00
|
|
|
}
|
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
type Manager struct {
|
|
|
|
output chan Result
|
|
|
|
indexingServices []Service
|
|
|
|
}
|
2017-08-08 13:58:51 +02:00
|
|
|
|
2019-05-21 14:31:01 +02:00
|
|
|
func NewManager(addrs []string, interval time.Duration, maxNeighbors uint) *Manager {
|
2019-05-19 01:07:37 +02:00
|
|
|
manager := new(Manager)
|
|
|
|
manager.output = make(chan Result, 20)
|
2017-08-08 13:58:51 +02:00
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
for _, addr := range addrs {
|
2019-05-21 14:31:01 +02:00
|
|
|
service := mainline.NewIndexingService(addr, interval, maxNeighbors, mainline.IndexingServiceEventHandlers{
|
2019-05-15 14:18:42 +02:00
|
|
|
OnResult: manager.onIndexingResult,
|
|
|
|
})
|
|
|
|
manager.indexingServices = append(manager.indexingServices, service)
|
2017-08-08 13:58:51 +02:00
|
|
|
service.Start()
|
|
|
|
}
|
|
|
|
|
|
|
|
return manager
|
|
|
|
}
|
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
func (m *Manager) onIndexingResult(res mainline.IndexingResult) {
|
2019-05-15 14:18:42 +02:00
|
|
|
select {
|
|
|
|
case m.output <- res:
|
|
|
|
default:
|
|
|
|
zap.L().Debug("DHT manager output ch is full, idx result dropped!")
|
2019-01-05 19:35:13 +01:00
|
|
|
}
|
2017-08-08 13:58:51 +02:00
|
|
|
}
|
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
func (m *Manager) Output() <-chan Result {
|
2017-08-08 13:58:51 +02:00
|
|
|
return m.output
|
|
|
|
}
|
|
|
|
|
2019-05-19 01:07:37 +02:00
|
|
|
func (m *Manager) Terminate() {
|
|
|
|
for _, service := range m.indexingServices {
|
2017-08-08 13:58:51 +02:00
|
|
|
service.Terminate()
|
|
|
|
}
|
|
|
|
}
|