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.

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