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
2017-05-17 07:58:40 +02:00
"github.com/NyaaPantsu/nyaa/model"
2017-05-10 19:29:35 +02:00
)
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 ]
2017-05-10 19:54:59 +02:00
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 ,
2017-05-11 13:40:50 +02:00
swarms : make ( [ ] model . Torrent , len ( swarms ) ) ,
2017-05-10 19:29:35 +02:00
state : stateSendID ,
}
2017-05-11 21:06:47 +02:00
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
}
2017-05-11 13:40:50 +02:00
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 ,
}
}