Albirew/nyaa-pantsu
Archivé
1
0
Bifurcation 0
Ce dépôt a été archivé le 2022-05-07. Vous pouvez voir ses fichiers ou le cloner, mais pas ouvrir de ticket ou de demandes d'ajout, ni soumettre de changements.
nyaa-pantsu/service/scraper/bucket.go

84 lignes
1,4 Kio
Go
Brut Vue normale Historique

2017-05-10 19:29:35 +02:00
package scraperService
import (
"math/rand"
"net"
2017-05-11 00:06:21 +02:00
"sync"
2017-05-10 19:29:35 +02:00
"github.com/ewhal/nyaa/model"
)
const InitialConnectionID = 0x41727101980
type Bucket struct {
Addr net.Addr
2017-05-11 00:06:21 +02:00
access sync.Mutex
2017-05-10 19:29:35 +02:00
transactions map[uint32]*Transaction
}
func (b *Bucket) NewTransaction(swarms []model.Torrent) (t *Transaction) {
id := rand.Uint32()
// get good id
2017-05-11 00:06:21 +02:00
b.access.Lock()
2017-05-10 19:29:35 +02:00
_, ok := b.transactions[id]
for ok {
2017-05-10 19:29:35 +02:00
id = rand.Uint32()
_, ok = b.transactions[id]
}
t = &Transaction{
TransactionID: id,
2017-05-11 00:06:21 +02:00
bucket: b,
swarms: make([]model.Torrent, len(swarms)),
2017-05-10 19:29:35 +02:00
state: stateSendID,
}
copy(t.swarms[:], swarms[:])
2017-05-10 19:29:35 +02:00
b.transactions[id] = t
2017-05-11 00:06:21 +02:00
b.access.Unlock()
2017-05-10 19:29:35 +02:00
return
}
func (b *Bucket) ForEachTransaction(v func(uint32, *Transaction)) {
clone := make(map[uint32]*Transaction)
b.access.Lock()
for k := range b.transactions {
clone[k] = b.transactions[k]
}
b.access.Unlock()
for k := range clone {
v(k, clone[k])
}
}
func (b *Bucket) Forget(tid uint32) {
b.access.Lock()
_, ok := b.transactions[tid]
if ok {
delete(b.transactions, tid)
}
b.access.Unlock()
}
2017-05-10 19:29:35 +02:00
func (b *Bucket) VisitTransaction(tid uint32, v func(*Transaction)) {
2017-05-11 00:06:21 +02:00
b.access.Lock()
2017-05-10 19:29:35 +02:00
t, ok := b.transactions[tid]
2017-05-11 00:06:21 +02:00
b.access.Unlock()
2017-05-10 19:29:35 +02:00
if ok {
2017-05-11 00:06:21 +02:00
v(t)
2017-05-10 19:29:35 +02:00
} else {
v(nil)
}
}
func NewBucket(a net.Addr) *Bucket {
return &Bucket{
transactions: make(map[uint32]*Transaction),
Addr: a,
}
}