Debian Codegraph @

go/pkg/electron/sender.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package electron
21
22 // #include <proton/disposition.h>
23 import "C"
24
25 import (
26 "fmt"
27 "time"
28
29 "github.com/apache/qpid-proton/go/pkg/amqp"
30 "github.com/apache/qpid-proton/go/pkg/proton"
31 )
32
33 // Sender is a Link that sends messages.
34 //
35 // The result of sending a message is provided by an Outcome value.
36 //
37 // A sender can buffer messages up to the credit limit provided by the remote receiver.
38 // All the Send* methods will block if the buffer is full until there is space.
39 // Send*Timeout methods will give up after the timeout and set Timeout as Outcome.Error.
40 //
41 type Sender interface {
42 Endpoint
43 LinkSettings
44
45 // SendSync sends a message and blocks until the message is acknowledged by the remote receiver.
46 // Returns an Outcome, which may contain an error if the message could not be sent.
47 SendSync(m amqp.Message) Outcome
48
49 // SendWaitable puts a message in the send buffer and returns a channel that
50 // you can use to wait for the Outcome of just that message. The channel is
51 // buffered so you can receive from it whenever you want without blocking.
52 //
53 // Note: can block if there is no space to buffer the message.
54 SendWaitable(m amqp.Message) <-chan Outcome
55
56 // SendForget buffers a message for sending and returns, with no notification of the outcome.
57 //
58 // Note: can block if there is no space to buffer the message.
59 SendForget(m amqp.Message)
60
61 // SendAsync puts a message in the send buffer and returns immediately. An
62 // Outcome with Value = value will be sent to the ack channel when the remote
63 // receiver has acknowledged the message or if there is an error.
64 //
65 // You can use the same ack channel for many calls to SendAsync(), possibly on
66 // many Senders. The channel will receive the outcomes in the order they
67 // become available. The channel should be buffered and/or served by dedicated
68 // goroutines to avoid blocking the connection.
69 //
70 // If ack == nil no Outcome is sent.
71 //
72 // Note: can block if there is no space to buffer the message.
73 SendAsync(m amqp.Message, ack chan<- Outcome, value interface{})
74
75 SendAsyncTimeout(m amqp.Message, ack chan<- Outcome, value interface{}, timeout time.Duration)
76
77 SendWaitableTimeout(m amqp.Message, timeout time.Duration) <-chan Outcome
78
79 SendForgetTimeout(m amqp.Message, timeout time.Duration)
80
81 SendSyncTimeout(m amqp.Message, timeout time.Duration) Outcome
82 }
83
84 // Outcome provides information about the outcome of sending a message.
85 type Outcome struct {
86 // Status of the message: was it sent, how was it acknowledged.
87 Status SentStatus
88 // Error is a local error if Status is Unsent or Unacknowledged, a remote error otherwise.
89 Error error
90 // Value provided by the application in SendAsync()
91 Value interface{}
92 }
93
94 func (o Outcome) send(ack chan<- Outcome) {
95 if ack != nil {
96 ack <- o
97 }
98 }
99
100 // SentStatus indicates the status of a sent message.
101 type SentStatus int
102
103 const (
104 // Message was never sent
105 Unsent SentStatus = iota
106 // Message was sent but never acknowledged. It may or may not have been received.
107 Unacknowledged
108 // Message was accepted by the receiver (or was sent pre-settled, accept is assumed)
109 Accepted
110 // Message was rejected as invalid by the receiver
111 Rejected
112 // Message was not processed by the receiver but may be valid for a different receiver
113 Released
114 // Receiver responded with an unrecognized status.
115 Unknown
116 )
117
118 // String human readable name for SentStatus.
119 func (s SentStatus) String() string {
120 switch s {
121 case Unsent:
122 return "unsent"
123 case Unacknowledged:
124 return "unacknowledged"
125 case Accepted:
126 return "accepted"
127 case Rejected:
128 return "rejected"
129 case Released:
130 return "released"
131 case Unknown:
132 return "unknown"
133 default:
134 return fmt.Sprintf("invalid(%d)", s)
135 }
136 }
137
138 // Convert proton delivery state code to SentStatus value
139 func sentStatus(d uint64) SentStatus {
140 switch d {
141 case proton.Accepted:
142 return Accepted
143 case proton.Rejected:
144 return Rejected
145 case proton.Released, proton.Modified:
146 return Released
147 default:
148 return Unknown
149 }
150 }
151
152 type sendable struct {
153 m amqp.Message
154 ack chan<- Outcome // Channel for acknowledgement of m
155 v interface{} // Correlation value
156 sent chan struct{} // Closed when m is encoded and will be sent
157 }
158
159 func (sm *sendable) unsent(err error) {
160 Outcome{Unsent, err, sm.v}.send(sm.ack)
161 }
162
163 type sender struct {
164 link
165 sending []*sendable
166 }
167
168 func newSender(ls linkSettings) *sender {
169 s := &sender{link: link{linkSettings: ls}}
170 s.endpoint.init(s.link.pLink.String())
171 s.handler().addLink(s.pLink, s)
172 s.link.pLink.Open()
173 return s
174 }
175
176 // Called in handler goroutine
177 func (s *sender) startSend(sm *sendable) {
178 s.sending = append(s.sending, sm)
179 s.trySend()
180 }
181
182 // Called in handler goroutine
183 func (s *sender) trySend() {
184 for s.pLink.Credit() > 0 && len(s.sending) > 0 {
185 sm := s.sending[0]
186 s.sending = s.sending[1:]
187 s.send(sm)
188 }
189 }
190
191 // Called in handler goroutine with credit > 0
192 func (s *sender) send(sm *sendable) {
193 if err := s.Error(); err != nil {
194 sm.unsent(err)
195 return
196 }
197 bytes, err := s.session.connection.mc.Encode(sm.m, nil)
198 close(sm.sent) // Safe to re-use sm.m now
199 if err != nil {
200 sm.unsent(err)
201 return
202 }
203 d, err := s.pLink.SendMessageBytes(bytes)
204 if err != nil {
205 sm.unsent(err)
206 return
207 }
208 if s.SndSettle() == SndSettled || (s.SndSettle() == SndMixed && sm.ack == nil) {
209 d.Settle() // Pre-settled
210 Outcome{Accepted, nil, sm.v}.send(sm.ack) // Assume accepted
211 } else {
212 // Register with handler to receive the remote outcome
213 s.handler().sent[d] = sm
214 }
215 }
216
217 func (s *sender) timeoutSend(sm *sendable) {
218 for i, sm2 := range s.sending {
219 if sm2 == sm {
220 n := copy(s.sending[i:], s.sending[i+1:])
221 s.sending = s.sending[:i+n] // delete
222 close(sm.sent)
223 return
224 }
225 }
226 }
227
228 func (s *sender) SendAsyncTimeout(m amqp.Message, ack chan<- Outcome, v interface{}, t time.Duration) {
229 sm := &sendable{m, ack, v, make(chan struct{})}
230 s.engine().Inject(func() { s.startSend(sm) })
231 select {
232 case <-sm.sent: // OK
233 case <-After(t): // Try to timeout sm
234 s.engine().Inject(func() { s.timeoutSend(sm) })
235 }
236 }
237
238 func (s *sender) SendWaitableTimeout(m amqp.Message, t time.Duration) <-chan Outcome {
239 out := make(chan Outcome, 1)
240 s.SendAsyncTimeout(m, out, nil, t)
241 return out
242 }
243
244 func (s *sender) SendForgetTimeout(m amqp.Message, t time.Duration) {
245 s.SendAsyncTimeout(m, nil, nil, t)
246 }
247
248 func (s *sender) SendSyncTimeout(m amqp.Message, t time.Duration) Outcome {
249 deadline := time.Now().Add(t)
250 ack := s.SendWaitableTimeout(m, t)
251 t = deadline.Sub(time.Now()) // Adjust for time already spent.
252 if t < 0 {
253 t = 0
254 }
255 if out, err := timedReceive(ack, t); err == nil {
256 return out.(Outcome)
257 } else {
258 if err == Closed && s.Error() != nil {
259 err = s.Error()
260 }
261 return Outcome{Unacknowledged, err, nil}
262 }
263 }
264
265 func (s *sender) SendAsync(m amqp.Message, ack chan<- Outcome, v interface{}) {
266 s.SendAsyncTimeout(m, ack, v, Forever)
267 }
268
269 func (s *sender) SendWaitable(m amqp.Message) <-chan Outcome {
270 return s.SendWaitableTimeout(m, Forever)
271 }
272
273 func (s *sender) SendForget(m amqp.Message) {
274 s.SendForgetTimeout(m, Forever)
275 }
276
277 func (s *sender) SendSync(m amqp.Message) Outcome {
278 return <-s.SendWaitable(m)
279 }
280
281 // handler goroutine
282 func (s *sender) closed(err error) error {
283 for _, sm := range s.sending {
284 close(sm.sent)
285 }
286 s.sending = nil
287 return s.link.closed(err)
288 }
289
290 // IncomingSender is sent on the Connection.Incoming() channel when there is
291 // an incoming request to open a sender link.
292 type IncomingSender struct {
293 incoming
294 linkSettings
295 }
296
297 func newIncomingSender(sn *session, pLink proton.Link) *IncomingSender {
298 return &IncomingSender{
299 incoming: makeIncoming(pLink),
300 linkSettings: makeIncomingLinkSettings(pLink, sn),
301 }
302 }
303
304 // Accept accepts an incoming sender endpoint
305 func (in *IncomingSender) Accept() Endpoint {
306 return in.accept(func() Endpoint { return newSender(in.linkSettings) })
307 }
308
309 // Call in injected functions to check if the sender is valid.
310 func (s *sender) valid() bool {
311 s2, ok := s.handler().links[s.pLink].(*sender)
312 return ok && s2 == s
313 }