conn.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package mux
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "sync"
  7. "time"
  8. "github.com/cnlh/nps/lib/common"
  9. )
  10. type conn struct {
  11. net.Conn
  12. getStatusCh chan struct{}
  13. connStatusOkCh chan struct{}
  14. connStatusFailCh chan struct{}
  15. readTimeOut time.Time
  16. writeTimeOut time.Time
  17. connId int32
  18. isClose bool
  19. closeFlag bool // close conn flag
  20. receiveWindow *window
  21. sendWindow *window
  22. readCh waitingCh
  23. writeCh waitingCh
  24. mux *Mux
  25. once sync.Once
  26. }
  27. func NewConn(connId int32, mux *Mux) *conn {
  28. c := &conn{
  29. getStatusCh: make(chan struct{}),
  30. connStatusOkCh: make(chan struct{}),
  31. connStatusFailCh: make(chan struct{}),
  32. connId: connId,
  33. receiveWindow: new(window),
  34. sendWindow: new(window),
  35. mux: mux,
  36. once: sync.Once{},
  37. }
  38. c.receiveWindow.NewReceive()
  39. c.sendWindow.NewSend()
  40. c.readCh.new()
  41. c.writeCh.new()
  42. return c
  43. }
  44. func (s *conn) Read(buf []byte) (n int, err error) {
  45. if s.isClose || buf == nil {
  46. return 0, errors.New("the conn has closed")
  47. }
  48. // waiting for takeout from receive window finish or timeout
  49. go s.readWindow(buf, s.readCh.nCh, s.readCh.errCh)
  50. if t := s.readTimeOut.Sub(time.Now()); t > 0 {
  51. timer := time.NewTimer(t)
  52. defer timer.Stop()
  53. select {
  54. case <-timer.C:
  55. return 0, errors.New("read timeout")
  56. case n = <-s.readCh.nCh:
  57. err = <-s.readCh.errCh
  58. }
  59. } else {
  60. n = <-s.readCh.nCh
  61. err = <-s.readCh.errCh
  62. }
  63. return
  64. }
  65. func (s *conn) readWindow(buf []byte, nCh chan int, errCh chan error) {
  66. n, err := s.receiveWindow.Read(buf)
  67. //logs.Warn("readwindow goroutine status n err buf", n, err, string(buf[:15]))
  68. if s.receiveWindow.WindowFull {
  69. if s.receiveWindow.Size() > 0 {
  70. // window.Read may be invoked before window.Write, and WindowFull flag change to true
  71. // so make sure that receiveWindow is free some space
  72. s.receiveWindow.WindowFull = false
  73. s.mux.sendInfo(common.MUX_MSG_SEND_OK, s.connId, s.receiveWindow.Size())
  74. // acknowledge other side, have empty some receive window space
  75. }
  76. }
  77. nCh <- n
  78. errCh <- err
  79. }
  80. func (s *conn) Write(buf []byte) (n int, err error) {
  81. if s.isClose {
  82. return 0, errors.New("the conn has closed")
  83. }
  84. if s.closeFlag {
  85. //s.Close()
  86. return 0, errors.New("io: write on closed conn")
  87. }
  88. s.sendWindow.SetSendBuf(buf) // set the buf to send window
  89. go s.write(s.writeCh.nCh, s.writeCh.errCh)
  90. // waiting for send to other side or timeout
  91. if t := s.writeTimeOut.Sub(time.Now()); t > 0 {
  92. timer := time.NewTimer(t)
  93. defer timer.Stop()
  94. select {
  95. case <-timer.C:
  96. return 0, errors.New("write timeout")
  97. case n = <-s.writeCh.nCh:
  98. err = <-s.writeCh.errCh
  99. }
  100. } else {
  101. n = <-s.writeCh.nCh
  102. err = <-s.writeCh.errCh
  103. }
  104. return
  105. }
  106. func (s *conn) write(nCh chan int, errCh chan error) {
  107. var n int
  108. var err error
  109. for {
  110. buf, err := s.sendWindow.WriteTo()
  111. // get the usable window size buf from send window
  112. if buf == nil && err == io.EOF {
  113. // send window is drain, break the loop
  114. err = nil
  115. break
  116. }
  117. if err != nil {
  118. break
  119. }
  120. n += len(buf)
  121. s.mux.sendInfo(common.MUX_NEW_MSG, s.connId, buf)
  122. // send to other side, not send nil data to other side
  123. }
  124. nCh <- n
  125. errCh <- err
  126. }
  127. func (s *conn) Close() (err error) {
  128. s.once.Do(s.closeProcess)
  129. return
  130. }
  131. func (s *conn) closeProcess() {
  132. s.isClose = true
  133. s.mux.connMap.Delete(s.connId)
  134. if !s.mux.IsClose {
  135. // if server or user close the conn while reading, will get a io.EOF
  136. // and this Close method will be invoke, send this signal to close other side
  137. s.mux.sendInfo(common.MUX_CONN_CLOSE, s.connId, nil)
  138. }
  139. s.sendWindow.CloseWindow()
  140. s.receiveWindow.CloseWindow()
  141. return
  142. }
  143. func (s *conn) LocalAddr() net.Addr {
  144. return s.mux.conn.LocalAddr()
  145. }
  146. func (s *conn) RemoteAddr() net.Addr {
  147. return s.mux.conn.RemoteAddr()
  148. }
  149. func (s *conn) SetDeadline(t time.Time) error {
  150. s.readTimeOut = t
  151. s.writeTimeOut = t
  152. return nil
  153. }
  154. func (s *conn) SetReadDeadline(t time.Time) error {
  155. s.readTimeOut = t
  156. return nil
  157. }
  158. func (s *conn) SetWriteDeadline(t time.Time) error {
  159. s.writeTimeOut = t
  160. return nil
  161. }
  162. type window struct {
  163. windowBuff []byte
  164. off uint16
  165. readOp chan struct{}
  166. readWait bool
  167. WindowFull bool
  168. usableReceiveWindow chan uint16
  169. WriteWg sync.WaitGroup
  170. closeOp bool
  171. closeOpCh chan struct{}
  172. WriteEndOp chan struct{}
  173. mutex sync.Mutex
  174. }
  175. func (Self *window) NewReceive() {
  176. // initial a window for receive
  177. Self.windowBuff = common.WindowBuff.Get()
  178. Self.readOp = make(chan struct{})
  179. Self.WriteEndOp = make(chan struct{})
  180. Self.closeOpCh = make(chan struct{}, 3)
  181. }
  182. func (Self *window) NewSend() {
  183. // initial a window for send
  184. Self.usableReceiveWindow = make(chan uint16)
  185. Self.closeOpCh = make(chan struct{}, 3)
  186. }
  187. func (Self *window) SetSendBuf(buf []byte) {
  188. // send window buff from conn write method, set it to send window
  189. Self.mutex.Lock()
  190. Self.windowBuff = buf
  191. Self.off = 0
  192. Self.mutex.Unlock()
  193. }
  194. func (Self *window) fullSlide() {
  195. // slide by allocate
  196. newBuf := common.WindowBuff.Get()
  197. Self.liteSlide()
  198. n := copy(newBuf[:Self.len()], Self.windowBuff)
  199. common.WindowBuff.Put(Self.windowBuff)
  200. Self.windowBuff = newBuf[:n]
  201. return
  202. }
  203. func (Self *window) liteSlide() {
  204. // slide by re slice
  205. Self.windowBuff = Self.windowBuff[Self.off:]
  206. Self.off = 0
  207. return
  208. }
  209. func (Self *window) Size() (n int) {
  210. // receive Window remaining
  211. n = common.PoolSizeWindow - Self.len()
  212. return
  213. }
  214. func (Self *window) len() (n int) {
  215. n = len(Self.windowBuff[Self.off:])
  216. return
  217. }
  218. func (Self *window) cap() (n int) {
  219. n = cap(Self.windowBuff[Self.off:])
  220. return
  221. }
  222. func (Self *window) grow(n int) {
  223. Self.windowBuff = Self.windowBuff[:Self.len()+n]
  224. }
  225. func (Self *window) Write(p []byte) (n int, err error) {
  226. if Self.closeOp {
  227. return 0, errors.New("conn.receiveWindow: write on closed window")
  228. }
  229. if len(p) > Self.Size() {
  230. return 0, errors.New("conn.receiveWindow: write too large")
  231. }
  232. Self.mutex.Lock()
  233. // slide the offset
  234. if len(p) > Self.cap()-Self.len() {
  235. // not enough space, need to allocate
  236. Self.fullSlide()
  237. } else {
  238. // have enough space, re slice
  239. Self.liteSlide()
  240. }
  241. length := Self.len() // length before grow
  242. Self.grow(len(p)) // grow for copy
  243. n = copy(Self.windowBuff[length:], p) // must copy data before allow Read
  244. if Self.readWait {
  245. // if there condition is length == 0 and
  246. // Read method just take away all the windowBuff,
  247. // this method will block until windowBuff is empty again
  248. // allow continue read
  249. defer Self.allowRead()
  250. }
  251. Self.mutex.Unlock()
  252. return n, nil
  253. }
  254. func (Self *window) allowRead() (closed bool) {
  255. if Self.closeOp {
  256. close(Self.readOp)
  257. return true
  258. }
  259. Self.mutex.Lock()
  260. Self.readWait = false
  261. Self.mutex.Unlock()
  262. select {
  263. case <-Self.closeOpCh:
  264. close(Self.readOp)
  265. return true
  266. case Self.readOp <- struct{}{}:
  267. return false
  268. }
  269. }
  270. func (Self *window) Read(p []byte) (n int, err error) {
  271. if Self.closeOp {
  272. return 0, io.EOF // Write method receive close signal, returns eof
  273. }
  274. Self.mutex.Lock()
  275. length := Self.len() // protect the length data, it invokes
  276. // before Write lock and after Write unlock
  277. if length == 0 {
  278. // window is empty, waiting for Write method send a success readOp signal
  279. // or get timeout or close
  280. Self.readWait = true
  281. Self.mutex.Unlock()
  282. ticker := time.NewTicker(2 * time.Minute)
  283. defer ticker.Stop()
  284. select {
  285. case _, ok := <-Self.readOp:
  286. if !ok {
  287. return 0, errors.New("conn.receiveWindow: window closed")
  288. }
  289. case <-Self.WriteEndOp:
  290. return 0, io.EOF // receive eof signal, returns eof
  291. case <-ticker.C:
  292. return 0, errors.New("conn.receiveWindow: read time out")
  293. case <-Self.closeOpCh:
  294. close(Self.readOp)
  295. return 0, io.EOF // receive close signal, returns eof
  296. }
  297. } else {
  298. Self.mutex.Unlock()
  299. }
  300. minCopy := 512
  301. for {
  302. Self.mutex.Lock()
  303. if len(p) == n || Self.len() == 0 {
  304. Self.mutex.Unlock()
  305. break
  306. }
  307. if n+minCopy > len(p) {
  308. minCopy = len(p) - n
  309. }
  310. i := copy(p[n:n+minCopy], Self.windowBuff[Self.off:])
  311. Self.off += uint16(i)
  312. n += i
  313. Self.mutex.Unlock()
  314. }
  315. p = p[:n]
  316. return
  317. }
  318. func (Self *window) WriteTo() (p []byte, err error) {
  319. if Self.closeOp {
  320. return nil, errors.New("conn.writeWindow: window closed")
  321. }
  322. if Self.len() == 0 {
  323. return nil, io.EOF
  324. // send window buff is drain, return eof and get another one
  325. }
  326. var windowSize uint16
  327. var ok bool
  328. waiting:
  329. ticker := time.NewTicker(2 * time.Minute)
  330. defer ticker.Stop()
  331. // waiting for receive usable window size, or timeout
  332. select {
  333. case windowSize, ok = <-Self.usableReceiveWindow:
  334. if !ok {
  335. return nil, errors.New("conn.writeWindow: window closed")
  336. }
  337. case <-ticker.C:
  338. return nil, errors.New("conn.writeWindow: write to time out")
  339. case <-Self.closeOpCh:
  340. return nil, errors.New("conn.writeWindow: window closed")
  341. }
  342. if windowSize == 0 {
  343. goto waiting // waiting for another usable window size
  344. }
  345. Self.mutex.Lock()
  346. if windowSize > uint16(Self.len()) {
  347. // usable window size is bigger than window buff size, send the full buff
  348. windowSize = uint16(Self.len())
  349. }
  350. p = Self.windowBuff[Self.off : windowSize+Self.off]
  351. Self.off += windowSize
  352. Self.mutex.Unlock()
  353. return
  354. }
  355. func (Self *window) SetAllowSize(value uint16) (closed bool) {
  356. defer func() {
  357. if recover() != nil {
  358. closed = true
  359. }
  360. }()
  361. if Self.closeOp {
  362. close(Self.usableReceiveWindow)
  363. return true
  364. }
  365. select {
  366. case Self.usableReceiveWindow <- value:
  367. return false
  368. case <-Self.closeOpCh:
  369. close(Self.usableReceiveWindow)
  370. return true
  371. }
  372. }
  373. func (Self *window) CloseWindow() {
  374. Self.closeOp = true
  375. Self.closeOpCh <- struct{}{}
  376. Self.closeOpCh <- struct{}{}
  377. Self.closeOpCh <- struct{}{}
  378. close(Self.closeOpCh)
  379. return
  380. }
  381. type waitingCh struct {
  382. nCh chan int
  383. errCh chan error
  384. }
  385. func (Self *waitingCh) new() {
  386. Self.nCh = make(chan int)
  387. Self.errCh = make(chan error)
  388. }
  389. func (Self *waitingCh) close() {
  390. close(Self.nCh)
  391. close(Self.errCh)
  392. }