You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

716 lines
19 KiB

9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
7 years ago
7 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package p2p
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net"
  8. "runtime/debug"
  9. "sync/atomic"
  10. "time"
  11. wire "github.com/tendermint/go-wire"
  12. tmencoding "github.com/tendermint/go-wire/nowriter/tmencoding"
  13. cmn "github.com/tendermint/tmlibs/common"
  14. flow "github.com/tendermint/tmlibs/flowrate"
  15. )
  16. var legacy = tmencoding.Legacy
  17. const (
  18. numBatchMsgPackets = 10
  19. minReadBufferSize = 1024
  20. minWriteBufferSize = 65536
  21. updateState = 2 * time.Second
  22. pingTimeout = 40 * time.Second
  23. // some of these defaults are written in the user config
  24. // flushThrottle, sendRate, recvRate
  25. // TODO: remove values present in config
  26. defaultFlushThrottle = 100 * time.Millisecond
  27. defaultSendQueueCapacity = 1
  28. defaultRecvBufferCapacity = 4096
  29. defaultRecvMessageCapacity = 22020096 // 21MB
  30. defaultSendRate = int64(512000) // 500KB/s
  31. defaultRecvRate = int64(512000) // 500KB/s
  32. defaultSendTimeout = 10 * time.Second
  33. )
  34. type receiveCbFunc func(chID byte, msgBytes []byte)
  35. type errorCbFunc func(interface{})
  36. /*
  37. Each peer has one `MConnection` (multiplex connection) instance.
  38. __multiplex__ *noun* a system or signal involving simultaneous transmission of
  39. several messages along a single channel of communication.
  40. Each `MConnection` handles message transmission on multiple abstract communication
  41. `Channel`s. Each channel has a globally unique byte id.
  42. The byte id and the relative priorities of each `Channel` are configured upon
  43. initialization of the connection.
  44. There are two methods for sending messages:
  45. func (m MConnection) Send(chID byte, msg interface{}) bool {}
  46. func (m MConnection) TrySend(chID byte, msg interface{}) bool {}
  47. `Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued
  48. for the channel with the given id byte `chID`, or until the request times out.
  49. The message `msg` is serialized using the `tendermint/wire` submodule's
  50. `WriteBinary()` reflection routine.
  51. `TrySend(chID, msg)` is a nonblocking call that returns false if the channel's
  52. queue is full.
  53. Inbound message bytes are handled with an onReceive callback function.
  54. */
  55. type MConnection struct {
  56. cmn.BaseService
  57. conn net.Conn
  58. bufReader *bufio.Reader
  59. bufWriter *bufio.Writer
  60. sendMonitor *flow.Monitor
  61. recvMonitor *flow.Monitor
  62. send chan struct{}
  63. pong chan struct{}
  64. channels []*Channel
  65. channelsIdx map[byte]*Channel
  66. onReceive receiveCbFunc
  67. onError errorCbFunc
  68. errored uint32
  69. config *MConnConfig
  70. quit chan struct{}
  71. flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled.
  72. pingTimer *cmn.RepeatTimer // send pings periodically
  73. chStatsTimer *cmn.RepeatTimer // update channel stats periodically
  74. LocalAddress *NetAddress
  75. RemoteAddress *NetAddress
  76. }
  77. // MConnConfig is a MConnection configuration.
  78. type MConnConfig struct {
  79. SendRate int64 `mapstructure:"send_rate"`
  80. RecvRate int64 `mapstructure:"recv_rate"`
  81. maxMsgPacketPayloadSize int
  82. flushThrottle time.Duration
  83. }
  84. func (cfg *MConnConfig) maxMsgPacketTotalSize() int {
  85. return cfg.maxMsgPacketPayloadSize + maxMsgPacketOverheadSize
  86. }
  87. // DefaultMConnConfig returns the default config.
  88. func DefaultMConnConfig() *MConnConfig {
  89. return &MConnConfig{
  90. SendRate: defaultSendRate,
  91. RecvRate: defaultRecvRate,
  92. maxMsgPacketPayloadSize: defaultMaxMsgPacketPayloadSize,
  93. flushThrottle: defaultFlushThrottle,
  94. }
  95. }
  96. // NewMConnection wraps net.Conn and creates multiplex connection
  97. func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection {
  98. return NewMConnectionWithConfig(
  99. conn,
  100. chDescs,
  101. onReceive,
  102. onError,
  103. DefaultMConnConfig())
  104. }
  105. // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config
  106. func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection {
  107. mconn := &MConnection{
  108. conn: conn,
  109. bufReader: bufio.NewReaderSize(conn, minReadBufferSize),
  110. bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize),
  111. sendMonitor: flow.New(0, 0),
  112. recvMonitor: flow.New(0, 0),
  113. send: make(chan struct{}, 1),
  114. pong: make(chan struct{}),
  115. onReceive: onReceive,
  116. onError: onError,
  117. config: config,
  118. LocalAddress: NewNetAddress(conn.LocalAddr()),
  119. RemoteAddress: NewNetAddress(conn.RemoteAddr()),
  120. }
  121. // Create channels
  122. var channelsIdx = map[byte]*Channel{}
  123. var channels = []*Channel{}
  124. for _, desc := range chDescs {
  125. channel := newChannel(mconn, *desc)
  126. channelsIdx[channel.desc.ID] = channel
  127. channels = append(channels, channel)
  128. }
  129. mconn.channels = channels
  130. mconn.channelsIdx = channelsIdx
  131. mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn)
  132. return mconn
  133. }
  134. // OnStart implements BaseService
  135. func (c *MConnection) OnStart() error {
  136. c.BaseService.OnStart()
  137. c.quit = make(chan struct{})
  138. c.flushTimer = cmn.NewThrottleTimer("flush", c.config.flushThrottle)
  139. c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeout)
  140. c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateState)
  141. go c.sendRoutine()
  142. go c.recvRoutine()
  143. return nil
  144. }
  145. // OnStop implements BaseService
  146. func (c *MConnection) OnStop() {
  147. c.BaseService.OnStop()
  148. c.flushTimer.Stop()
  149. c.pingTimer.Stop()
  150. c.chStatsTimer.Stop()
  151. if c.quit != nil {
  152. close(c.quit)
  153. }
  154. c.conn.Close()
  155. // We can't close pong safely here because
  156. // recvRoutine may write to it after we've stopped.
  157. // Though it doesn't need to get closed at all,
  158. // we close it @ recvRoutine.
  159. // close(c.pong)
  160. }
  161. func (c *MConnection) String() string {
  162. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  163. }
  164. func (c *MConnection) flush() {
  165. c.Logger.Debug("Flush", "conn", c)
  166. err := c.bufWriter.Flush()
  167. if err != nil {
  168. c.Logger.Error("MConnection flush failed", "err", err)
  169. }
  170. }
  171. // Catch panics, usually caused by remote disconnects.
  172. func (c *MConnection) _recover() {
  173. if r := recover(); r != nil {
  174. stack := debug.Stack()
  175. err := cmn.StackError{r, stack}
  176. c.stopForError(err)
  177. }
  178. }
  179. func (c *MConnection) stopForError(r interface{}) {
  180. c.Stop()
  181. if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
  182. if c.onError != nil {
  183. c.onError(r)
  184. }
  185. }
  186. }
  187. // Queues a message to be sent to channel.
  188. func (c *MConnection) Send(chID byte, msg interface{}) bool {
  189. if !c.IsRunning() {
  190. return false
  191. }
  192. c.Logger.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg))
  193. // Send message to channel.
  194. channel, ok := c.channelsIdx[chID]
  195. if !ok {
  196. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  197. return false
  198. }
  199. success := channel.sendBytes(wire.BinaryBytes(msg))
  200. if success {
  201. // Wake up sendRoutine if necessary
  202. select {
  203. case c.send <- struct{}{}:
  204. default:
  205. }
  206. } else {
  207. c.Logger.Error("Send failed", "channel", chID, "conn", c, "msg", msg)
  208. }
  209. return success
  210. }
  211. // Queues a message to be sent to channel.
  212. // Nonblocking, returns true if successful.
  213. func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
  214. if !c.IsRunning() {
  215. return false
  216. }
  217. c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msg", msg)
  218. // Send message to channel.
  219. channel, ok := c.channelsIdx[chID]
  220. if !ok {
  221. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  222. return false
  223. }
  224. ok = channel.trySendBytes(wire.BinaryBytes(msg))
  225. if ok {
  226. // Wake up sendRoutine if necessary
  227. select {
  228. case c.send <- struct{}{}:
  229. default:
  230. }
  231. }
  232. return ok
  233. }
  234. // CanSend returns true if you can send more data onto the chID, false
  235. // otherwise. Use only as a heuristic.
  236. func (c *MConnection) CanSend(chID byte) bool {
  237. if !c.IsRunning() {
  238. return false
  239. }
  240. channel, ok := c.channelsIdx[chID]
  241. if !ok {
  242. c.Logger.Error(cmn.Fmt("Unknown channel %X", chID))
  243. return false
  244. }
  245. return channel.canSend()
  246. }
  247. // sendRoutine polls for packets to send from channels.
  248. func (c *MConnection) sendRoutine() {
  249. defer c._recover()
  250. FOR_LOOP:
  251. for {
  252. var n int
  253. var err error
  254. select {
  255. case <-c.flushTimer.Ch:
  256. // NOTE: flushTimer.Set() must be called every time
  257. // something is written to .bufWriter.
  258. c.flush()
  259. case <-c.chStatsTimer.Ch:
  260. for _, channel := range c.channels {
  261. channel.updateStats()
  262. }
  263. case <-c.pingTimer.Ch:
  264. c.Logger.Debug("Send Ping")
  265. legacy.WriteOctet(packetTypePing, c.bufWriter, &n, &err)
  266. c.sendMonitor.Update(int(n))
  267. c.flush()
  268. case <-c.pong:
  269. c.Logger.Debug("Send Pong")
  270. legacy.WriteOctet(packetTypePong, c.bufWriter, &n, &err)
  271. c.sendMonitor.Update(int(n))
  272. c.flush()
  273. case <-c.quit:
  274. break FOR_LOOP
  275. case <-c.send:
  276. // Send some msgPackets
  277. eof := c.sendSomeMsgPackets()
  278. if !eof {
  279. // Keep sendRoutine awake.
  280. select {
  281. case c.send <- struct{}{}:
  282. default:
  283. }
  284. }
  285. }
  286. if !c.IsRunning() {
  287. break FOR_LOOP
  288. }
  289. if err != nil {
  290. c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
  291. c.stopForError(err)
  292. break FOR_LOOP
  293. }
  294. }
  295. // Cleanup
  296. }
  297. // Returns true if messages from channels were exhausted.
  298. // Blocks in accordance to .sendMonitor throttling.
  299. func (c *MConnection) sendSomeMsgPackets() bool {
  300. // Block until .sendMonitor says we can write.
  301. // Once we're ready we send more than we asked for,
  302. // but amortized it should even out.
  303. c.sendMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.SendRate), true)
  304. // Now send some msgPackets.
  305. for i := 0; i < numBatchMsgPackets; i++ {
  306. if c.sendMsgPacket() {
  307. return true
  308. }
  309. }
  310. return false
  311. }
  312. // Returns true if messages from channels were exhausted.
  313. func (c *MConnection) sendMsgPacket() bool {
  314. // Choose a channel to create a msgPacket from.
  315. // The chosen channel will be the one whose recentlySent/priority is the least.
  316. var leastRatio float32 = math.MaxFloat32
  317. var leastChannel *Channel
  318. for _, channel := range c.channels {
  319. // If nothing to send, skip this channel
  320. if !channel.isSendPending() {
  321. continue
  322. }
  323. // Get ratio, and keep track of lowest ratio.
  324. ratio := float32(channel.recentlySent) / float32(channel.desc.Priority)
  325. if ratio < leastRatio {
  326. leastRatio = ratio
  327. leastChannel = channel
  328. }
  329. }
  330. // Nothing to send?
  331. if leastChannel == nil {
  332. return true
  333. } else {
  334. // c.Logger.Info("Found a msgPacket to send")
  335. }
  336. // Make & send a msgPacket from this channel
  337. n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
  338. if err != nil {
  339. c.Logger.Error("Failed to write msgPacket", "err", err)
  340. c.stopForError(err)
  341. return true
  342. }
  343. c.sendMonitor.Update(int(n))
  344. c.flushTimer.Set()
  345. return false
  346. }
  347. // recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
  348. // After a whole message has been assembled, it's pushed to onReceive().
  349. // Blocks depending on how the connection is throttled.
  350. func (c *MConnection) recvRoutine() {
  351. defer c._recover()
  352. FOR_LOOP:
  353. for {
  354. // Block until .recvMonitor says we can read.
  355. c.recvMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.RecvRate), true)
  356. /*
  357. // Peek into bufReader for debugging
  358. if numBytes := c.bufReader.Buffered(); numBytes > 0 {
  359. log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte {
  360. bytes, err := c.bufReader.Peek(cmn.MinInt(numBytes, 100))
  361. if err == nil {
  362. return bytes
  363. } else {
  364. log.Warn("Error peeking connection buffer", "err", err)
  365. return nil
  366. }
  367. }})
  368. }
  369. */
  370. // Read packet type
  371. var n int
  372. var err error
  373. pktType := wire.ReadByte(c.bufReader, &n, &err)
  374. c.recvMonitor.Update(int(n))
  375. if err != nil {
  376. if c.IsRunning() {
  377. c.Logger.Error("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
  378. c.stopForError(err)
  379. }
  380. break FOR_LOOP
  381. }
  382. // Read more depending on packet type.
  383. switch pktType {
  384. case packetTypePing:
  385. // TODO: prevent abuse, as they cause flush()'s.
  386. c.Logger.Debug("Receive Ping")
  387. c.pong <- struct{}{}
  388. case packetTypePong:
  389. // do nothing
  390. c.Logger.Debug("Receive Pong")
  391. case packetTypeMsg:
  392. pkt, n, err := msgPacket{}, int(0), error(nil)
  393. wire.ReadBinaryPtr(&pkt, c.bufReader, c.config.maxMsgPacketTotalSize(), &n, &err)
  394. c.recvMonitor.Update(int(n))
  395. if err != nil {
  396. if c.IsRunning() {
  397. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  398. c.stopForError(err)
  399. }
  400. break FOR_LOOP
  401. }
  402. channel, ok := c.channelsIdx[pkt.ChannelID]
  403. if !ok || channel == nil {
  404. err := fmt.Errorf("Unknown channel %X", pkt.ChannelID)
  405. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  406. c.stopForError(err)
  407. }
  408. msgBytes, err := channel.recvMsgPacket(pkt)
  409. if err != nil {
  410. if c.IsRunning() {
  411. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  412. c.stopForError(err)
  413. }
  414. break FOR_LOOP
  415. }
  416. if msgBytes != nil {
  417. c.Logger.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes)
  418. // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
  419. c.onReceive(pkt.ChannelID, msgBytes)
  420. }
  421. default:
  422. err := fmt.Errorf("Unknown message type %X", pktType)
  423. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  424. c.stopForError(err)
  425. }
  426. // TODO: shouldn't this go in the sendRoutine?
  427. // Better to send a ping packet when *we* haven't sent anything for a while.
  428. c.pingTimer.Reset()
  429. }
  430. // Cleanup
  431. close(c.pong)
  432. for range c.pong {
  433. // Drain
  434. }
  435. }
  436. type ConnectionStatus struct {
  437. SendMonitor flow.Status
  438. RecvMonitor flow.Status
  439. Channels []ChannelStatus
  440. }
  441. type ChannelStatus struct {
  442. ID byte
  443. SendQueueCapacity int
  444. SendQueueSize int
  445. Priority int
  446. RecentlySent int64
  447. }
  448. func (c *MConnection) Status() ConnectionStatus {
  449. var status ConnectionStatus
  450. status.SendMonitor = c.sendMonitor.Status()
  451. status.RecvMonitor = c.recvMonitor.Status()
  452. status.Channels = make([]ChannelStatus, len(c.channels))
  453. for i, channel := range c.channels {
  454. status.Channels[i] = ChannelStatus{
  455. ID: channel.desc.ID,
  456. SendQueueCapacity: cap(channel.sendQueue),
  457. SendQueueSize: int(channel.sendQueueSize), // TODO use atomic
  458. Priority: channel.desc.Priority,
  459. RecentlySent: channel.recentlySent,
  460. }
  461. }
  462. return status
  463. }
  464. //-----------------------------------------------------------------------------
  465. type ChannelDescriptor struct {
  466. ID byte
  467. Priority int
  468. SendQueueCapacity int
  469. RecvBufferCapacity int
  470. RecvMessageCapacity int
  471. }
  472. func (chDesc ChannelDescriptor) FillDefaults() (filled ChannelDescriptor) {
  473. if chDesc.SendQueueCapacity == 0 {
  474. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  475. }
  476. if chDesc.RecvBufferCapacity == 0 {
  477. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  478. }
  479. if chDesc.RecvMessageCapacity == 0 {
  480. chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
  481. }
  482. filled = chDesc
  483. return
  484. }
  485. // TODO: lowercase.
  486. // NOTE: not goroutine-safe.
  487. type Channel struct {
  488. conn *MConnection
  489. desc ChannelDescriptor
  490. sendQueue chan []byte
  491. sendQueueSize int32 // atomic.
  492. recving []byte
  493. sending []byte
  494. recentlySent int64 // exponential moving average
  495. maxMsgPacketPayloadSize int
  496. }
  497. func newChannel(conn *MConnection, desc ChannelDescriptor) *Channel {
  498. desc = desc.FillDefaults()
  499. if desc.Priority <= 0 {
  500. cmn.PanicSanity("Channel default priority must be a postive integer")
  501. }
  502. return &Channel{
  503. conn: conn,
  504. desc: desc,
  505. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  506. recving: make([]byte, 0, desc.RecvBufferCapacity),
  507. maxMsgPacketPayloadSize: conn.config.maxMsgPacketPayloadSize,
  508. }
  509. }
  510. // Queues message to send to this channel.
  511. // Goroutine-safe
  512. // Times out (and returns false) after defaultSendTimeout
  513. func (ch *Channel) sendBytes(bytes []byte) bool {
  514. select {
  515. case ch.sendQueue <- bytes:
  516. atomic.AddInt32(&ch.sendQueueSize, 1)
  517. return true
  518. case <-time.After(defaultSendTimeout):
  519. return false
  520. }
  521. }
  522. // Queues message to send to this channel.
  523. // Nonblocking, returns true if successful.
  524. // Goroutine-safe
  525. func (ch *Channel) trySendBytes(bytes []byte) bool {
  526. select {
  527. case ch.sendQueue <- bytes:
  528. atomic.AddInt32(&ch.sendQueueSize, 1)
  529. return true
  530. default:
  531. return false
  532. }
  533. }
  534. // Goroutine-safe
  535. func (ch *Channel) loadSendQueueSize() (size int) {
  536. return int(atomic.LoadInt32(&ch.sendQueueSize))
  537. }
  538. // Goroutine-safe
  539. // Use only as a heuristic.
  540. func (ch *Channel) canSend() bool {
  541. return ch.loadSendQueueSize() < defaultSendQueueCapacity
  542. }
  543. // Returns true if any msgPackets are pending to be sent.
  544. // Call before calling nextMsgPacket()
  545. // Goroutine-safe
  546. func (ch *Channel) isSendPending() bool {
  547. if len(ch.sending) == 0 {
  548. if len(ch.sendQueue) == 0 {
  549. return false
  550. }
  551. ch.sending = <-ch.sendQueue
  552. }
  553. return true
  554. }
  555. // Creates a new msgPacket to send.
  556. // Not goroutine-safe
  557. func (ch *Channel) nextMsgPacket() msgPacket {
  558. packet := msgPacket{}
  559. packet.ChannelID = byte(ch.desc.ID)
  560. maxSize := ch.maxMsgPacketPayloadSize
  561. packet.Bytes = ch.sending[:cmn.MinInt(maxSize, len(ch.sending))]
  562. if len(ch.sending) <= maxSize {
  563. packet.EOF = byte(0x01)
  564. ch.sending = nil
  565. atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
  566. } else {
  567. packet.EOF = byte(0x00)
  568. ch.sending = ch.sending[cmn.MinInt(maxSize, len(ch.sending)):]
  569. }
  570. return packet
  571. }
  572. // Writes next msgPacket to w.
  573. // Not goroutine-safe
  574. func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) {
  575. packet := ch.nextMsgPacket()
  576. // log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet)
  577. writeMsgPacketTo(packet, w, &n, &err)
  578. if err == nil {
  579. ch.recentlySent += int64(n)
  580. }
  581. return
  582. }
  583. func writeMsgPacketTo(packet msgPacket, w io.Writer, n *int, err *error) {
  584. legacy.WriteOctet(packetTypeMsg, w, n, err)
  585. wire.WriteBinary(packet, w, n, err)
  586. }
  587. // Handles incoming msgPackets. Returns a msg bytes if msg is complete.
  588. // Not goroutine-safe
  589. func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) {
  590. // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet)
  591. if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) {
  592. return nil, wire.ErrBinaryReadOverflow
  593. }
  594. ch.recving = append(ch.recving, packet.Bytes...)
  595. if packet.EOF == byte(0x01) {
  596. msgBytes := ch.recving
  597. // clear the slice without re-allocating.
  598. // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
  599. // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
  600. // at which point the recving slice stops being used and should be garbage collected
  601. ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
  602. return msgBytes, nil
  603. }
  604. return nil, nil
  605. }
  606. // Call this periodically to update stats for throttling purposes.
  607. // Not goroutine-safe
  608. func (ch *Channel) updateStats() {
  609. // Exponential decay of stats.
  610. // TODO: optimize.
  611. ch.recentlySent = int64(float64(ch.recentlySent) * 0.8)
  612. }
  613. //-----------------------------------------------------------------------------
  614. const (
  615. defaultMaxMsgPacketPayloadSize = 1024
  616. maxMsgPacketOverheadSize = 10 // It's actually lower but good enough
  617. packetTypePing = byte(0x01)
  618. packetTypePong = byte(0x02)
  619. packetTypeMsg = byte(0x03)
  620. )
  621. // Messages in channels are chopped into smaller msgPackets for multiplexing.
  622. type msgPacket struct {
  623. ChannelID byte
  624. EOF byte // 1 means message ends here.
  625. Bytes []byte
  626. }
  627. func (p msgPacket) String() string {
  628. return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF)
  629. }