1 Star 0 Fork 0

祝雨昕 / go-bitswap

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
notifications.go 2.64 KB
一键复制 编辑 原始数据 按行查看 历史
祝雨昕 提交于 2022-04-05 12:55 . origin
package notifications
import (
"context"
"sync"
pubsub "github.com/cskr/pubsub"
blocks "github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid"
)
const bufferSize = 16
// PubSub is a simple interface for publishing blocks and being able to subscribe
// for cids. It's used internally by bitswap to decouple receiving blocks
// and actually providing them back to the GetBlocks caller.
type PubSub interface {
Publish(block blocks.Block)
Subscribe(ctx context.Context, keys ...cid.Cid) <-chan blocks.Block
Shutdown()
}
// New generates a new PubSub interface.
func New() PubSub {
return &impl{
wrapped: *pubsub.New(bufferSize),
closed: make(chan struct{}),
}
}
type impl struct {
lk sync.RWMutex
wrapped pubsub.PubSub
closed chan struct{}
}
func (ps *impl) Publish(block blocks.Block) {
ps.lk.RLock()
defer ps.lk.RUnlock()
select {
case <-ps.closed:
return
default:
}
ps.wrapped.Pub(block, block.Cid().KeyString())
}
func (ps *impl) Shutdown() {
ps.lk.Lock()
defer ps.lk.Unlock()
select {
case <-ps.closed:
return
default:
}
close(ps.closed)
ps.wrapped.Shutdown()
}
// Subscribe returns a channel of blocks for the given |keys|. |blockChannel|
// is closed if the |ctx| times out or is cancelled, or after receiving the blocks
// corresponding to |keys|.
func (ps *impl) Subscribe(ctx context.Context, keys ...cid.Cid) <-chan blocks.Block {
blocksCh := make(chan blocks.Block, len(keys))
valuesCh := make(chan interface{}, len(keys)) // provide our own channel to control buffer, prevent blocking
if len(keys) == 0 {
close(blocksCh)
return blocksCh
}
// prevent shutdown
ps.lk.RLock()
defer ps.lk.RUnlock()
select {
case <-ps.closed:
close(blocksCh)
return blocksCh
default:
}
// AddSubOnceEach listens for each key in the list, and closes the channel
// once all keys have been received
ps.wrapped.AddSubOnceEach(valuesCh, toStrings(keys)...)
go func() {
defer func() {
close(blocksCh)
ps.lk.RLock()
defer ps.lk.RUnlock()
// Don't touch the pubsub instance if we're
// already closed.
select {
case <-ps.closed:
return
default:
}
ps.wrapped.Unsub(valuesCh)
}()
for {
select {
case <-ctx.Done():
return
case <-ps.closed:
case val, ok := <-valuesCh:
if !ok {
return
}
block, ok := val.(blocks.Block)
if !ok {
return
}
select {
case <-ctx.Done():
return
case blocksCh <- block: // continue
case <-ps.closed:
}
}
}
}()
return blocksCh
}
func toStrings(keys []cid.Cid) []string {
strs := make([]string, 0, len(keys))
for _, key := range keys {
strs = append(strs, key.KeyString())
}
return strs
}
1
https://gitee.com/yuviazhu/go-bitswap.git
git@gitee.com:yuviazhu/go-bitswap.git
yuviazhu
go-bitswap
go-bitswap
f20a32d77e37

搜索帮助

53164aa7 5694891 3bd8fe86 5694891