context.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Copyright 2016-2018 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // +build go1.7
  14. // A Go client for the NATS messaging system (https://nats.io).
  15. package nats
  16. import (
  17. "context"
  18. "reflect"
  19. )
  20. // RequestWithContext takes a context, a subject and payload
  21. // in bytes and request expecting a single response.
  22. func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
  23. if ctx == nil {
  24. return nil, ErrInvalidContext
  25. }
  26. if nc == nil {
  27. return nil, ErrInvalidConnection
  28. }
  29. // Check whether the context is done already before making
  30. // the request.
  31. if ctx.Err() != nil {
  32. return nil, ctx.Err()
  33. }
  34. nc.mu.Lock()
  35. // If user wants the old style.
  36. if nc.Opts.UseOldRequestStyle {
  37. nc.mu.Unlock()
  38. return nc.oldRequestWithContext(ctx, subj, data)
  39. }
  40. // Do setup for the new style.
  41. if nc.respMap == nil {
  42. nc.initNewResp()
  43. }
  44. // Create literal Inbox and map to a chan msg.
  45. mch := make(chan *Msg, RequestChanLen)
  46. respInbox := nc.newRespInbox()
  47. token := respToken(respInbox)
  48. nc.respMap[token] = mch
  49. createSub := nc.respMux == nil
  50. ginbox := nc.respSub
  51. nc.mu.Unlock()
  52. if createSub {
  53. // Make sure scoped subscription is setup only once.
  54. var err error
  55. nc.respSetup.Do(func() { err = nc.createRespMux(ginbox) })
  56. if err != nil {
  57. return nil, err
  58. }
  59. }
  60. err := nc.PublishRequest(subj, respInbox, data)
  61. if err != nil {
  62. return nil, err
  63. }
  64. var ok bool
  65. var msg *Msg
  66. select {
  67. case msg, ok = <-mch:
  68. if !ok {
  69. return nil, ErrConnectionClosed
  70. }
  71. case <-ctx.Done():
  72. nc.mu.Lock()
  73. delete(nc.respMap, token)
  74. nc.mu.Unlock()
  75. return nil, ctx.Err()
  76. }
  77. return msg, nil
  78. }
  79. // oldRequestWithContext utilizes inbox and subscription per request.
  80. func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
  81. inbox := NewInbox()
  82. ch := make(chan *Msg, RequestChanLen)
  83. s, err := nc.subscribe(inbox, _EMPTY_, nil, ch)
  84. if err != nil {
  85. return nil, err
  86. }
  87. s.AutoUnsubscribe(1)
  88. defer s.Unsubscribe()
  89. err = nc.PublishRequest(subj, inbox, data)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return s.NextMsgWithContext(ctx)
  94. }
  95. // NextMsgWithContext takes a context and returns the next message
  96. // available to a synchronous subscriber, blocking until it is delivered
  97. // or context gets canceled.
  98. func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
  99. if ctx == nil {
  100. return nil, ErrInvalidContext
  101. }
  102. if s == nil {
  103. return nil, ErrBadSubscription
  104. }
  105. if ctx.Err() != nil {
  106. return nil, ctx.Err()
  107. }
  108. s.mu.Lock()
  109. err := s.validateNextMsgState()
  110. if err != nil {
  111. s.mu.Unlock()
  112. return nil, err
  113. }
  114. // snapshot
  115. mch := s.mch
  116. s.mu.Unlock()
  117. var ok bool
  118. var msg *Msg
  119. // If something is available right away, let's optimize that case.
  120. select {
  121. case msg, ok = <-mch:
  122. if !ok {
  123. return nil, ErrConnectionClosed
  124. }
  125. if err := s.processNextMsgDelivered(msg); err != nil {
  126. return nil, err
  127. } else {
  128. return msg, nil
  129. }
  130. default:
  131. }
  132. select {
  133. case msg, ok = <-mch:
  134. if !ok {
  135. return nil, ErrConnectionClosed
  136. }
  137. if err := s.processNextMsgDelivered(msg); err != nil {
  138. return nil, err
  139. }
  140. case <-ctx.Done():
  141. return nil, ctx.Err()
  142. }
  143. return msg, nil
  144. }
  145. // FlushWithContext will allow a context to control the duration
  146. // of a Flush() call. This context should be non-nil and should
  147. // have a deadline set. We will return an error if none is present.
  148. func (nc *Conn) FlushWithContext(ctx context.Context) error {
  149. if nc == nil {
  150. return ErrInvalidConnection
  151. }
  152. if ctx == nil {
  153. return ErrInvalidContext
  154. }
  155. _, ok := ctx.Deadline()
  156. if !ok {
  157. return ErrNoDeadlineContext
  158. }
  159. nc.mu.Lock()
  160. if nc.isClosed() {
  161. nc.mu.Unlock()
  162. return ErrConnectionClosed
  163. }
  164. // Create a buffered channel to prevent chan send to block
  165. // in processPong()
  166. ch := make(chan struct{}, 1)
  167. nc.sendPing(ch)
  168. nc.mu.Unlock()
  169. var err error
  170. select {
  171. case _, ok := <-ch:
  172. if !ok {
  173. err = ErrConnectionClosed
  174. } else {
  175. close(ch)
  176. }
  177. case <-ctx.Done():
  178. err = ctx.Err()
  179. }
  180. if err != nil {
  181. nc.removeFlushEntry(ch)
  182. }
  183. return err
  184. }
  185. // RequestWithContext will create an Inbox and perform a Request
  186. // using the provided cancellation context with the Inbox reply
  187. // for the data v. A response will be decoded into the vPtrResponse.
  188. func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v interface{}, vPtr interface{}) error {
  189. if ctx == nil {
  190. return ErrInvalidContext
  191. }
  192. b, err := c.Enc.Encode(subject, v)
  193. if err != nil {
  194. return err
  195. }
  196. m, err := c.Conn.RequestWithContext(ctx, subject, b)
  197. if err != nil {
  198. return err
  199. }
  200. if reflect.TypeOf(vPtr) == emptyMsgType {
  201. mPtr := vPtr.(*Msg)
  202. *mPtr = *m
  203. } else {
  204. err := c.Enc.Decode(m.Subject, m.Data, vPtr)
  205. if err != nil {
  206. return err
  207. }
  208. }
  209. return nil
  210. }