1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-09-10 14:34:24 +08:00
Files
kubo/notifications/query.go
Lars Gierth 00ec976e1d Use extracted go-libp2p-crypto, -secio, -peer packages
License: MIT
Signed-off-by: Lars Gierth <larsg@systemli.org>
2016-04-16 21:48:06 -07:00

85 lines
1.6 KiB
Go

package notifications
import (
"encoding/json"
peer "gx/ipfs/QmZwZjMVGss5rqYsJVGy18gNbkTJffFyq2x1uJ4e4p3ZAt/go-libp2p-peer"
context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
)
const RoutingQueryKey = "RoutingQueryEvent"
type QueryEventType int
const (
SendingQuery QueryEventType = iota
PeerResponse
FinalPeer
QueryError
Provider
Value
AddingPeer
DialingPeer
)
type QueryEvent struct {
ID peer.ID
Type QueryEventType
Responses []*peer.PeerInfo
Extra string
}
func RegisterForQueryEvents(ctx context.Context, ch chan<- *QueryEvent) context.Context {
return context.WithValue(ctx, RoutingQueryKey, ch)
}
func PublishQueryEvent(ctx context.Context, ev *QueryEvent) {
ich := ctx.Value(RoutingQueryKey)
if ich == nil {
return
}
ch, ok := ich.(chan<- *QueryEvent)
if !ok {
return
}
select {
case ch <- ev:
case <-ctx.Done():
}
}
func (qe *QueryEvent) MarshalJSON() ([]byte, error) {
out := make(map[string]interface{})
out["ID"] = peer.IDB58Encode(qe.ID)
out["Type"] = int(qe.Type)
out["Responses"] = qe.Responses
out["Extra"] = qe.Extra
return json.Marshal(out)
}
func (qe *QueryEvent) UnmarshalJSON(b []byte) error {
temp := struct {
ID string
Type int
Responses []*peer.PeerInfo
Extra string
}{}
err := json.Unmarshal(b, &temp)
if err != nil {
return err
}
if len(temp.ID) > 0 {
pid, err := peer.IDB58Decode(temp.ID)
if err != nil {
return err
}
qe.ID = pid
}
qe.Type = QueryEventType(temp.Type)
qe.Responses = temp.Responses
qe.Extra = temp.Extra
return nil
}