2019-08-19 21:20:56 +00:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-08-22 23:02:46 +00:00
|
|
|
"reflect"
|
|
|
|
"time"
|
2019-08-19 21:20:56 +00:00
|
|
|
|
2019-08-22 23:02:46 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/network"
|
2019-08-19 21:20:56 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
2019-08-22 23:02:46 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/protocol"
|
2019-08-19 21:20:56 +00:00
|
|
|
)
|
|
|
|
|
2019-08-22 23:02:46 +00:00
|
|
|
// Send a message to a specific peer. The returned stream may be used for reading, but has been
|
|
|
|
// closed for writing.
|
2019-09-16 17:54:46 +00:00
|
|
|
func (s *Service) Send(ctx context.Context, message interface{}, pid peer.ID) (network.Stream, error) {
|
2019-08-22 23:02:46 +00:00
|
|
|
topic := RPCTypeMapping[reflect.TypeOf(message)] + s.Encoding().ProtocolSuffix()
|
|
|
|
|
|
|
|
// TTFB_TIME (5s) + RESP_TIMEOUT (10s).
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
stream, err := s.host.NewStream(ctx, pid, protocol.ID(topic))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-09-09 02:34:52 +00:00
|
|
|
if _, err := s.Encoding().EncodeWithLength(stream, message); err != nil {
|
2019-08-22 23:02:46 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close stream for writing.
|
|
|
|
if err := stream.Close(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return stream, nil
|
2019-08-19 21:20:56 +00:00
|
|
|
}
|