Debian Codegraph @

context.go

raw
1 // Copyright 2016-2023 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
14 package nats
15
16 import (
17 "context"
18 "reflect"
19 )
20
21 // RequestMsgWithContext takes a context, a subject and payload
22 // in bytes and request expecting a single response.
23 func (nc *Conn) RequestMsgWithContext(ctx context.Context, msg *Msg) (*Msg, error) {
24 if msg == nil {
25 return nil, ErrInvalidMsg
26 }
27 hdr, err := msg.headerBytes()
28 if err != nil {
29 return nil, err
30 }
31 return nc.requestWithContext(ctx, msg.Subject, hdr, msg.Data)
32 }
33
34 // RequestWithContext takes a context, a subject and payload
35 // in bytes and request expecting a single response.
36 func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
37 return nc.requestWithContext(ctx, subj, nil, data)
38 }
39
40 func (nc *Conn) requestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) {
41 if ctx == nil {
42 return nil, ErrInvalidContext
43 }
44 if nc == nil {
45 return nil, ErrInvalidConnection
46 }
47 // Check whether the context is done already before making
48 // the request.
49 if ctx.Err() != nil {
50 return nil, ctx.Err()
51 }
52
53 var m *Msg
54 var err error
55
56 // If user wants the old style.
57 if nc.useOldRequestStyle() {
58 m, err = nc.oldRequestWithContext(ctx, subj, hdr, data)
59 } else {
60 mch, token, err := nc.createNewRequestAndSend(subj, hdr, data)
61 if err != nil {
62 return nil, err
63 }
64
65 var ok bool
66
67 select {
68 case m, ok = <-mch:
69 if !ok {
70 return nil, ErrConnectionClosed
71 }
72 case <-ctx.Done():
73 nc.mu.Lock()
74 delete(nc.respMap, token)
75 nc.mu.Unlock()
76 return nil, ctx.Err()
77 }
78 }
79 // Check for no responder status.
80 if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
81 m, err = nil, ErrNoResponders
82 }
83 return m, err
84 }
85
86 // oldRequestWithContext utilizes inbox and subscription per request.
87 func (nc *Conn) oldRequestWithContext(ctx context.Context, subj string, hdr, data []byte) (*Msg, error) {
88 inbox := nc.NewInbox()
89 ch := make(chan *Msg, RequestChanLen)
90
91 s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, nil, true, nil)
92 if err != nil {
93 return nil, err
94 }
95 s.AutoUnsubscribe(1)
96 defer s.Unsubscribe()
97
98 err = nc.publish(subj, inbox, false, hdr, data)
99 if err != nil {
100 return nil, err
101 }
102
103 return s.NextMsgWithContext(ctx)
104 }
105
106 func (s *Subscription) nextMsgWithContext(ctx context.Context, pullSubInternal, waitIfNoMsg bool) (*Msg, error) {
107 if ctx == nil {
108 return nil, ErrInvalidContext
109 }
110 if s == nil {
111 return nil, ErrBadSubscription
112 }
113 if ctx.Err() != nil {
114 return nil, ctx.Err()
115 }
116
117 s.mu.Lock()
118 err := s.validateNextMsgState(pullSubInternal)
119 if err != nil {
120 s.mu.Unlock()
121 return nil, err
122 }
123
124 // snapshot
125 mch := s.mch
126 s.mu.Unlock()
127
128 var ok bool
129 var msg *Msg
130
131 // If something is available right away, let's optimize that case.
132 select {
133 case msg, ok = <-mch:
134 if !ok {
135 return nil, s.getNextMsgErr()
136 }
137 if err := s.processNextMsgDelivered(msg); err != nil {
138 return nil, err
139 }
140 return msg, nil
141 default:
142 // If internal and we don't want to wait, signal that there is no
143 // message in the internal queue.
144 if pullSubInternal && !waitIfNoMsg {
145 return nil, errNoMessages
146 }
147 }
148
149 select {
150 case msg, ok = <-mch:
151 if !ok {
152 return nil, s.getNextMsgErr()
153 }
154 if err := s.processNextMsgDelivered(msg); err != nil {
155 return nil, err
156 }
157 case <-ctx.Done():
158 return nil, ctx.Err()
159 }
160
161 return msg, nil
162 }
163
164 // NextMsgWithContext takes a context and returns the next message
165 // available to a synchronous subscriber, blocking until it is delivered
166 // or context gets canceled.
167 func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
168 return s.nextMsgWithContext(ctx, false, true)
169 }
170
171 // FlushWithContext will allow a context to control the duration
172 // of a Flush() call. This context should be non-nil and should
173 // have a deadline set. We will return an error if none is present.
174 func (nc *Conn) FlushWithContext(ctx context.Context) error {
175 if nc == nil {
176 return ErrInvalidConnection
177 }
178 if ctx == nil {
179 return ErrInvalidContext
180 }
181 _, ok := ctx.Deadline()
182 if !ok {
183 return ErrNoDeadlineContext
184 }
185
186 nc.mu.Lock()
187 if nc.isClosed() {
188 nc.mu.Unlock()
189 return ErrConnectionClosed
190 }
191 // Create a buffered channel to prevent chan send to block
192 // in processPong()
193 ch := make(chan struct{}, 1)
194 nc.sendPing(ch)
195 nc.mu.Unlock()
196
197 var err error
198
199 select {
200 case _, ok := <-ch:
201 if !ok {
202 err = ErrConnectionClosed
203 } else {
204 close(ch)
205 }
206 case <-ctx.Done():
207 err = ctx.Err()
208 }
209
210 if err != nil {
211 nc.removeFlushEntry(ch)
212 }
213
214 return err
215 }
216
217 // RequestWithContext will create an Inbox and perform a Request
218 // using the provided cancellation context with the Inbox reply
219 // for the data v. A response will be decoded into the vPtr last parameter.
220 //
221 // Deprecated: Encoded connections are no longer supported.
222 func (c *EncodedConn) RequestWithContext(ctx context.Context, subject string, v any, vPtr any) error {
223 if ctx == nil {
224 return ErrInvalidContext
225 }
226
227 b, err := c.Enc.Encode(subject, v)
228 if err != nil {
229 return err
230 }
231 m, err := c.Conn.RequestWithContext(ctx, subject, b)
232 if err != nil {
233 return err
234 }
235 if reflect.TypeOf(vPtr) == emptyMsgType {
236 mPtr := vPtr.(*Msg)
237 *mPtr = *m
238 } else {
239 err := c.Enc.Decode(m.Subject, m.Data, vPtr)
240 if err != nil {
241 return err
242 }
243 }
244
245 return nil
246 }