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.

719 lines
19 KiB

9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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
8 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. descCopy := *desc // copy the desc else unsafe access across connections
  126. channel := newChannel(mconn, &descCopy)
  127. channelsIdx[channel.id] = channel
  128. channels = append(channels, channel)
  129. }
  130. mconn.channels = channels
  131. mconn.channelsIdx = channelsIdx
  132. mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn)
  133. return mconn
  134. }
  135. // OnStart implements BaseService
  136. func (c *MConnection) OnStart() error {
  137. c.BaseService.OnStart()
  138. c.quit = make(chan struct{})
  139. c.flushTimer = cmn.NewThrottleTimer("flush", c.config.flushThrottle)
  140. c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeout)
  141. c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateState)
  142. go c.sendRoutine()
  143. go c.recvRoutine()
  144. return nil
  145. }
  146. // OnStop implements BaseService
  147. func (c *MConnection) OnStop() {
  148. c.BaseService.OnStop()
  149. c.flushTimer.Stop()
  150. c.pingTimer.Stop()
  151. c.chStatsTimer.Stop()
  152. if c.quit != nil {
  153. close(c.quit)
  154. }
  155. c.conn.Close()
  156. // We can't close pong safely here because
  157. // recvRoutine may write to it after we've stopped.
  158. // Though it doesn't need to get closed at all,
  159. // we close it @ recvRoutine.
  160. // close(c.pong)
  161. }
  162. func (c *MConnection) String() string {
  163. return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr())
  164. }
  165. func (c *MConnection) flush() {
  166. c.Logger.Debug("Flush", "conn", c)
  167. err := c.bufWriter.Flush()
  168. if err != nil {
  169. c.Logger.Error("MConnection flush failed", "err", err)
  170. }
  171. }
  172. // Catch panics, usually caused by remote disconnects.
  173. func (c *MConnection) _recover() {
  174. if r := recover(); r != nil {
  175. stack := debug.Stack()
  176. err := cmn.StackError{r, stack}
  177. c.stopForError(err)
  178. }
  179. }
  180. func (c *MConnection) stopForError(r interface{}) {
  181. c.Stop()
  182. if atomic.CompareAndSwapUint32(&c.errored, 0, 1) {
  183. if c.onError != nil {
  184. c.onError(r)
  185. }
  186. }
  187. }
  188. // Queues a message to be sent to channel.
  189. func (c *MConnection) Send(chID byte, msg interface{}) bool {
  190. if !c.IsRunning() {
  191. return false
  192. }
  193. c.Logger.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg))
  194. // Send message to channel.
  195. channel, ok := c.channelsIdx[chID]
  196. if !ok {
  197. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  198. return false
  199. }
  200. success := channel.sendBytes(wire.BinaryBytes(msg))
  201. if success {
  202. // Wake up sendRoutine if necessary
  203. select {
  204. case c.send <- struct{}{}:
  205. default:
  206. }
  207. } else {
  208. c.Logger.Error("Send failed", "channel", chID, "conn", c, "msg", msg)
  209. }
  210. return success
  211. }
  212. // Queues a message to be sent to channel.
  213. // Nonblocking, returns true if successful.
  214. func (c *MConnection) TrySend(chID byte, msg interface{}) bool {
  215. if !c.IsRunning() {
  216. return false
  217. }
  218. c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msg", msg)
  219. // Send message to channel.
  220. channel, ok := c.channelsIdx[chID]
  221. if !ok {
  222. c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID))
  223. return false
  224. }
  225. ok = channel.trySendBytes(wire.BinaryBytes(msg))
  226. if ok {
  227. // Wake up sendRoutine if necessary
  228. select {
  229. case c.send <- struct{}{}:
  230. default:
  231. }
  232. }
  233. return ok
  234. }
  235. // CanSend returns true if you can send more data onto the chID, false
  236. // otherwise. Use only as a heuristic.
  237. func (c *MConnection) CanSend(chID byte) bool {
  238. if !c.IsRunning() {
  239. return false
  240. }
  241. channel, ok := c.channelsIdx[chID]
  242. if !ok {
  243. c.Logger.Error(cmn.Fmt("Unknown channel %X", chID))
  244. return false
  245. }
  246. return channel.canSend()
  247. }
  248. // sendRoutine polls for packets to send from channels.
  249. func (c *MConnection) sendRoutine() {
  250. defer c._recover()
  251. FOR_LOOP:
  252. for {
  253. var n int
  254. var err error
  255. select {
  256. case <-c.flushTimer.Ch:
  257. // NOTE: flushTimer.Set() must be called every time
  258. // something is written to .bufWriter.
  259. c.flush()
  260. case <-c.chStatsTimer.Ch:
  261. for _, channel := range c.channels {
  262. channel.updateStats()
  263. }
  264. case <-c.pingTimer.Ch:
  265. c.Logger.Debug("Send Ping")
  266. legacy.WriteOctet(packetTypePing, c.bufWriter, &n, &err)
  267. c.sendMonitor.Update(int(n))
  268. c.flush()
  269. case <-c.pong:
  270. c.Logger.Debug("Send Pong")
  271. legacy.WriteOctet(packetTypePong, c.bufWriter, &n, &err)
  272. c.sendMonitor.Update(int(n))
  273. c.flush()
  274. case <-c.quit:
  275. break FOR_LOOP
  276. case <-c.send:
  277. // Send some msgPackets
  278. eof := c.sendSomeMsgPackets()
  279. if !eof {
  280. // Keep sendRoutine awake.
  281. select {
  282. case c.send <- struct{}{}:
  283. default:
  284. }
  285. }
  286. }
  287. if !c.IsRunning() {
  288. break FOR_LOOP
  289. }
  290. if err != nil {
  291. c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "err", err)
  292. c.stopForError(err)
  293. break FOR_LOOP
  294. }
  295. }
  296. // Cleanup
  297. }
  298. // Returns true if messages from channels were exhausted.
  299. // Blocks in accordance to .sendMonitor throttling.
  300. func (c *MConnection) sendSomeMsgPackets() bool {
  301. // Block until .sendMonitor says we can write.
  302. // Once we're ready we send more than we asked for,
  303. // but amortized it should even out.
  304. c.sendMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.SendRate), true)
  305. // Now send some msgPackets.
  306. for i := 0; i < numBatchMsgPackets; i++ {
  307. if c.sendMsgPacket() {
  308. return true
  309. }
  310. }
  311. return false
  312. }
  313. // Returns true if messages from channels were exhausted.
  314. func (c *MConnection) sendMsgPacket() bool {
  315. // Choose a channel to create a msgPacket from.
  316. // The chosen channel will be the one whose recentlySent/priority is the least.
  317. var leastRatio float32 = math.MaxFloat32
  318. var leastChannel *Channel
  319. for _, channel := range c.channels {
  320. // If nothing to send, skip this channel
  321. if !channel.isSendPending() {
  322. continue
  323. }
  324. // Get ratio, and keep track of lowest ratio.
  325. ratio := float32(channel.recentlySent) / float32(channel.priority)
  326. if ratio < leastRatio {
  327. leastRatio = ratio
  328. leastChannel = channel
  329. }
  330. }
  331. // Nothing to send?
  332. if leastChannel == nil {
  333. return true
  334. } else {
  335. // c.Logger.Info("Found a msgPacket to send")
  336. }
  337. // Make & send a msgPacket from this channel
  338. n, err := leastChannel.writeMsgPacketTo(c.bufWriter)
  339. if err != nil {
  340. c.Logger.Error("Failed to write msgPacket", "err", err)
  341. c.stopForError(err)
  342. return true
  343. }
  344. c.sendMonitor.Update(int(n))
  345. c.flushTimer.Set()
  346. return false
  347. }
  348. // recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer.
  349. // After a whole message has been assembled, it's pushed to onReceive().
  350. // Blocks depending on how the connection is throttled.
  351. func (c *MConnection) recvRoutine() {
  352. defer c._recover()
  353. FOR_LOOP:
  354. for {
  355. // Block until .recvMonitor says we can read.
  356. c.recvMonitor.Limit(c.config.maxMsgPacketTotalSize(), atomic.LoadInt64(&c.config.RecvRate), true)
  357. /*
  358. // Peek into bufReader for debugging
  359. if numBytes := c.bufReader.Buffered(); numBytes > 0 {
  360. log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte {
  361. bytes, err := c.bufReader.Peek(cmn.MinInt(numBytes, 100))
  362. if err == nil {
  363. return bytes
  364. } else {
  365. log.Warn("Error peeking connection buffer", "err", err)
  366. return nil
  367. }
  368. }})
  369. }
  370. */
  371. // Read packet type
  372. var n int
  373. var err error
  374. pktType := wire.ReadByte(c.bufReader, &n, &err)
  375. c.recvMonitor.Update(int(n))
  376. if err != nil {
  377. if c.IsRunning() {
  378. c.Logger.Error("Connection failed @ recvRoutine (reading byte)", "conn", c, "err", err)
  379. c.stopForError(err)
  380. }
  381. break FOR_LOOP
  382. }
  383. // Read more depending on packet type.
  384. switch pktType {
  385. case packetTypePing:
  386. // TODO: prevent abuse, as they cause flush()'s.
  387. c.Logger.Debug("Receive Ping")
  388. c.pong <- struct{}{}
  389. case packetTypePong:
  390. // do nothing
  391. c.Logger.Debug("Receive Pong")
  392. case packetTypeMsg:
  393. pkt, n, err := msgPacket{}, int(0), error(nil)
  394. wire.ReadBinaryPtr(&pkt, c.bufReader, c.config.maxMsgPacketTotalSize(), &n, &err)
  395. c.recvMonitor.Update(int(n))
  396. if err != nil {
  397. if c.IsRunning() {
  398. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  399. c.stopForError(err)
  400. }
  401. break FOR_LOOP
  402. }
  403. channel, ok := c.channelsIdx[pkt.ChannelID]
  404. if !ok || channel == nil {
  405. err := fmt.Errorf("Unknown channel %X", pkt.ChannelID)
  406. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  407. c.stopForError(err)
  408. }
  409. msgBytes, err := channel.recvMsgPacket(pkt)
  410. if err != nil {
  411. if c.IsRunning() {
  412. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  413. c.stopForError(err)
  414. }
  415. break FOR_LOOP
  416. }
  417. if msgBytes != nil {
  418. c.Logger.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes)
  419. // NOTE: This means the reactor.Receive runs in the same thread as the p2p recv routine
  420. c.onReceive(pkt.ChannelID, msgBytes)
  421. }
  422. default:
  423. err := fmt.Errorf("Unknown message type %X", pktType)
  424. c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "err", err)
  425. c.stopForError(err)
  426. }
  427. // TODO: shouldn't this go in the sendRoutine?
  428. // Better to send a ping packet when *we* haven't sent anything for a while.
  429. c.pingTimer.Reset()
  430. }
  431. // Cleanup
  432. close(c.pong)
  433. for range c.pong {
  434. // Drain
  435. }
  436. }
  437. type ConnectionStatus struct {
  438. SendMonitor flow.Status
  439. RecvMonitor flow.Status
  440. Channels []ChannelStatus
  441. }
  442. type ChannelStatus struct {
  443. ID byte
  444. SendQueueCapacity int
  445. SendQueueSize int
  446. Priority int
  447. RecentlySent int64
  448. }
  449. func (c *MConnection) Status() ConnectionStatus {
  450. var status ConnectionStatus
  451. status.SendMonitor = c.sendMonitor.Status()
  452. status.RecvMonitor = c.recvMonitor.Status()
  453. status.Channels = make([]ChannelStatus, len(c.channels))
  454. for i, channel := range c.channels {
  455. status.Channels[i] = ChannelStatus{
  456. ID: channel.id,
  457. SendQueueCapacity: cap(channel.sendQueue),
  458. SendQueueSize: int(channel.sendQueueSize), // TODO use atomic
  459. Priority: channel.priority,
  460. RecentlySent: channel.recentlySent,
  461. }
  462. }
  463. return status
  464. }
  465. //-----------------------------------------------------------------------------
  466. type ChannelDescriptor struct {
  467. ID byte
  468. Priority int
  469. SendQueueCapacity int
  470. RecvBufferCapacity int
  471. RecvMessageCapacity int
  472. }
  473. func (chDesc *ChannelDescriptor) FillDefaults() {
  474. if chDesc.SendQueueCapacity == 0 {
  475. chDesc.SendQueueCapacity = defaultSendQueueCapacity
  476. }
  477. if chDesc.RecvBufferCapacity == 0 {
  478. chDesc.RecvBufferCapacity = defaultRecvBufferCapacity
  479. }
  480. if chDesc.RecvMessageCapacity == 0 {
  481. chDesc.RecvMessageCapacity = defaultRecvMessageCapacity
  482. }
  483. }
  484. // TODO: lowercase.
  485. // NOTE: not goroutine-safe.
  486. type Channel struct {
  487. conn *MConnection
  488. desc *ChannelDescriptor
  489. id byte
  490. sendQueue chan []byte
  491. sendQueueSize int32 // atomic.
  492. recving []byte
  493. sending []byte
  494. priority int
  495. recentlySent int64 // exponential moving average
  496. maxMsgPacketPayloadSize int
  497. }
  498. func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel {
  499. desc.FillDefaults()
  500. if desc.Priority <= 0 {
  501. cmn.PanicSanity("Channel default priority must be a postive integer")
  502. }
  503. return &Channel{
  504. conn: conn,
  505. desc: desc,
  506. id: desc.ID,
  507. sendQueue: make(chan []byte, desc.SendQueueCapacity),
  508. recving: make([]byte, 0, desc.RecvBufferCapacity),
  509. priority: desc.Priority,
  510. maxMsgPacketPayloadSize: conn.config.maxMsgPacketPayloadSize,
  511. }
  512. }
  513. // Queues message to send to this channel.
  514. // Goroutine-safe
  515. // Times out (and returns false) after defaultSendTimeout
  516. func (ch *Channel) sendBytes(bytes []byte) bool {
  517. select {
  518. case ch.sendQueue <- bytes:
  519. atomic.AddInt32(&ch.sendQueueSize, 1)
  520. return true
  521. case <-time.After(defaultSendTimeout):
  522. return false
  523. }
  524. }
  525. // Queues message to send to this channel.
  526. // Nonblocking, returns true if successful.
  527. // Goroutine-safe
  528. func (ch *Channel) trySendBytes(bytes []byte) bool {
  529. select {
  530. case ch.sendQueue <- bytes:
  531. atomic.AddInt32(&ch.sendQueueSize, 1)
  532. return true
  533. default:
  534. return false
  535. }
  536. }
  537. // Goroutine-safe
  538. func (ch *Channel) loadSendQueueSize() (size int) {
  539. return int(atomic.LoadInt32(&ch.sendQueueSize))
  540. }
  541. // Goroutine-safe
  542. // Use only as a heuristic.
  543. func (ch *Channel) canSend() bool {
  544. return ch.loadSendQueueSize() < defaultSendQueueCapacity
  545. }
  546. // Returns true if any msgPackets are pending to be sent.
  547. // Call before calling nextMsgPacket()
  548. // Goroutine-safe
  549. func (ch *Channel) isSendPending() bool {
  550. if len(ch.sending) == 0 {
  551. if len(ch.sendQueue) == 0 {
  552. return false
  553. }
  554. ch.sending = <-ch.sendQueue
  555. }
  556. return true
  557. }
  558. // Creates a new msgPacket to send.
  559. // Not goroutine-safe
  560. func (ch *Channel) nextMsgPacket() msgPacket {
  561. packet := msgPacket{}
  562. packet.ChannelID = byte(ch.id)
  563. maxSize := ch.maxMsgPacketPayloadSize
  564. packet.Bytes = ch.sending[:cmn.MinInt(maxSize, len(ch.sending))]
  565. if len(ch.sending) <= maxSize {
  566. packet.EOF = byte(0x01)
  567. ch.sending = nil
  568. atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize
  569. } else {
  570. packet.EOF = byte(0x00)
  571. ch.sending = ch.sending[cmn.MinInt(maxSize, len(ch.sending)):]
  572. }
  573. return packet
  574. }
  575. // Writes next msgPacket to w.
  576. // Not goroutine-safe
  577. func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) {
  578. packet := ch.nextMsgPacket()
  579. // log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet)
  580. writeMsgPacketTo(packet, w, &n, &err)
  581. if err == nil {
  582. ch.recentlySent += int64(n)
  583. }
  584. return
  585. }
  586. func writeMsgPacketTo(packet msgPacket, w io.Writer, n *int, err *error) {
  587. legacy.WriteOctet(packetTypeMsg, w, n, err)
  588. wire.WriteBinary(packet, w, n, err)
  589. }
  590. // Handles incoming msgPackets. Returns a msg bytes if msg is complete.
  591. // Not goroutine-safe
  592. func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) {
  593. // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet)
  594. if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) {
  595. return nil, wire.ErrBinaryReadOverflow
  596. }
  597. ch.recving = append(ch.recving, packet.Bytes...)
  598. if packet.EOF == byte(0x01) {
  599. msgBytes := ch.recving
  600. // clear the slice without re-allocating.
  601. // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go
  602. // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes,
  603. // at which point the recving slice stops being used and should be garbage collected
  604. ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity)
  605. return msgBytes, nil
  606. }
  607. return nil, nil
  608. }
  609. // Call this periodically to update stats for throttling purposes.
  610. // Not goroutine-safe
  611. func (ch *Channel) updateStats() {
  612. // Exponential decay of stats.
  613. // TODO: optimize.
  614. ch.recentlySent = int64(float64(ch.recentlySent) * 0.8)
  615. }
  616. //-----------------------------------------------------------------------------
  617. const (
  618. defaultMaxMsgPacketPayloadSize = 1024
  619. maxMsgPacketOverheadSize = 10 // It's actually lower but good enough
  620. packetTypePing = byte(0x01)
  621. packetTypePong = byte(0x02)
  622. packetTypeMsg = byte(0x03)
  623. )
  624. // Messages in channels are chopped into smaller msgPackets for multiplexing.
  625. type msgPacket struct {
  626. ChannelID byte
  627. EOF byte // 1 means message ends here.
  628. Bytes []byte
  629. }
  630. func (p msgPacket) String() string {
  631. return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF)
  632. }