conn.go 9.7 KB

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