1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use std::io::{self,Error,ErrorKind};
use futures::{Async,Future,future,Poll,Stream,task};
use tokio_io::{AsyncRead,AsyncWrite};
use std::sync::{Arc,Mutex};
use lapin_async;
use lapin_async::api::{ChannelState, RequestId};
use lapin_async::connection::Connection;
use lapin_async::generated::basic;
use transport::*;
use message::BasicGetMessage;
use types::FieldTable;
use consumer::Consumer;
use queue::Queue;
pub struct Channel<T> {
pub transport: Arc<Mutex<AMQPTransport<T>>>,
pub id: u16,
}
impl<T> Clone for Channel<T>
where T: Send {
fn clone(&self) -> Channel<T> {
Channel {
transport: self.transport.clone(),
id: self.id,
}
}
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct AccessRequestOptions {
pub exclusive: bool,
pub passive: bool,
pub active: bool,
pub write: bool,
pub read: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ExchangeDeclareOptions {
pub ticket: u16,
pub passive: bool,
pub durable: bool,
pub auto_delete: bool,
pub internal: bool,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ExchangeDeleteOptions {
pub ticket: u16,
pub if_unused: bool,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ExchangeBindOptions {
pub ticket: u16,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ExchangeUnbindOptions {
pub ticket: u16,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct QueueDeclareOptions {
pub ticket: u16,
pub passive: bool,
pub durable: bool,
pub exclusive: bool,
pub auto_delete: bool,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct QueueUnbindOptions {
pub ticket: u16
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ConfirmSelectOptions {
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct QueueBindOptions {
pub ticket: u16,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct QueuePurgeOptions {
pub ticket: u16,
pub nowait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct BasicPublishOptions {
pub ticket: u16,
pub mandatory: bool,
pub immediate: bool,
}
pub type BasicProperties = basic::Properties;
#[derive(Clone,Debug,Default,PartialEq)]
pub struct BasicConsumeOptions {
pub ticket: u16,
pub no_local: bool,
pub no_ack: bool,
pub exclusive: bool,
pub no_wait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct BasicGetOptions {
pub ticket: u16,
pub no_ack: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct BasicQosOptions {
pub prefetch_size: u32,
pub prefetch_count: u16,
pub global: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct QueueDeleteOptions {
pub ticket: u16,
pub if_unused: bool,
pub if_empty: bool,
pub no_wait: bool,
}
#[derive(Clone,Debug,Default,PartialEq)]
pub struct ChannelFlowOptions {
pub active: bool,
}
impl<T: AsyncRead+AsyncWrite+Send+'static> Channel<T> {
pub fn create(transport: Arc<Mutex<AMQPTransport<T>>>) -> Box<Future<Item = Self, Error = io::Error> + Send + 'static> {
let channel_transport = transport.clone();
Box::new(future::poll_fn(move || {
let mut transport = lock_transport!(channel_transport);
if let Some(id) = transport.conn.create_channel() {
return Ok(Async::Ready(Channel {
id,
transport: channel_transport.clone(),
}))
} else {
return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "The maximum number of channels for this connection has been reached"));
}
}).and_then(|channel| {
let channel_id = channel.id;
channel.run_on_locked_transport("create", "Could not create channel", move |transport| {
transport.conn.channel_open(channel_id, "".to_string()).map(Some)
}).and_then(move |_| {
future::poll_fn(move || {
let transport = lock_transport!(transport);
match transport.conn.get_state(channel_id) {
Some(ChannelState::Connected) => return Ok(Async::Ready(())),
Some(ChannelState::Error) => return Err(io::Error::new(io::ErrorKind::Other, format!("Failed to open channel"))),
Some(ChannelState::Closed) => return Err(io::Error::new(io::ErrorKind::Other, format!("Failed to open channel"))),
_ => {
task::current().notify();
return Ok(Async::NotReady);
}
}
})
}).map(move |_| {
channel
})
}))
}
pub fn access_request(&self, realm: &str, options: AccessRequestOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let realm = realm.to_string();
Box::new(self.run_on_locked_transport("access_request", "Could not request access", move |transport| {
transport.conn.access_request(channel_id, realm,
options.exclusive, options.passive, options.active, options.write, options.read).map(Some)
}).map(|_| ()))
}
pub fn exchange_declare(&self, name: &str, exchange_type: &str, options: ExchangeDeclareOptions, arguments: FieldTable) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let name = name.to_string();
let exchange_type = exchange_type.to_string();
Box::new(self.run_on_locked_transport("exchange_declare", "Could not declare exchange", move |transport| {
transport.conn.exchange_declare(channel_id, options.ticket, name, exchange_type,
options.passive, options.durable, options.auto_delete, options.internal, options.nowait, arguments).map(Some)
}).map(|_| ()))
}
pub fn exchange_delete(&self, name: &str, options: ExchangeDeleteOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let name = name.to_string();
Box::new(self.run_on_locked_transport("exchange_delete", "Could not delete exchange", move |transport| {
transport.conn.exchange_delete(channel_id, options.ticket, name,
options.if_unused, options.nowait).map(Some)
}).map(|_| ()))
}
pub fn exchange_bind(&self, destination: &str, source: &str, routing_key: &str, options: ExchangeBindOptions, arguments: FieldTable) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let destination = destination.to_string();
let source = source.to_string();
let routing_key = routing_key.to_string();
Box::new(self.run_on_locked_transport("exchange_bind", "Could not bind exchange", move |transport| {
transport.conn.exchange_bind(channel_id, options.ticket, destination, source, routing_key,
options.nowait, arguments).map(Some)
}).map(|_| ()))
}
pub fn exchange_unbind(&self, destination: &str, source: &str, routing_key: &str, options: ExchangeUnbindOptions, arguments: FieldTable) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let destination = destination.to_string();
let source = source.to_string();
let routing_key = routing_key.to_string();
Box::new(self.run_on_locked_transport("exchange_unbind", "Could not unbind exchange", move |transport| {
transport.conn.exchange_unbind(channel_id, options.ticket, destination, source, routing_key,
options.nowait, arguments).map(Some)
}).map(|_| ()))
}
pub fn queue_declare(&self, name: &str, options: QueueDeclareOptions, arguments: FieldTable) -> Box<Future<Item = Queue, Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let name = name.to_string();
let transport = self.transport.clone();
Box::new(self.run_on_locked_transport("queue_declare", "Could not declare queue", move |transport| {
transport.conn.queue_declare(channel_id, options.ticket, name,
options.passive, options.durable, options.exclusive, options.auto_delete, options.nowait, arguments).map(Some)
}).and_then(|request_id| {
future::poll_fn(move || {
let mut transport = lock_transport!(transport);
if let Some(queue) = transport.conn.get_generated_name(request_id.expect("expected request_id")) {
return Ok(Async::Ready(queue))
} else {
task::current().notify();
return Ok(Async::NotReady)
}
})
}).map(Queue::new))
}
pub fn queue_bind(&self, name: &str, exchange: &str, routing_key: &str, options: QueueBindOptions, arguments: FieldTable) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let name = name.to_string();
let exchange = exchange.to_string();
let routing_key = routing_key.to_string();
Box::new(self.run_on_locked_transport("queue_bind", "Could not bind queue", move |transport| {
transport.conn.queue_bind(channel_id, options.ticket, name, exchange, routing_key,
options.nowait, arguments).map(Some)
}).map(|_| ()))
}
pub fn queue_unbind(&self, name: &str, exchange: &str, routing_key: &str, options: QueueUnbindOptions, arguments: FieldTable) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let name = name.to_string();
let exchange = exchange.to_string();
let routing_key = routing_key.to_string();
Box::new(self.run_on_locked_transport("queue_unbind", "Could not unbind queue from the exchange", move |transport| {
transport.conn.queue_unbind(channel_id, options.ticket, name, exchange, routing_key, arguments).map(Some)
}).map(|_| ()))
}
pub fn confirm_select(&self, options: ConfirmSelectOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("confirm_select", "Could not activate confirm extension", move |transport| {
transport.conn.confirm_select(channel_id, options.nowait).map(Some)
}).map(|_| ()))
}
pub fn basic_qos(&self, options: BasicQosOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("basic_qos", "Could not setup qos", move |transport| {
transport.conn.basic_qos(channel_id, options.prefetch_size, options.prefetch_count, options.global).map(|_| None)
}).map(|_| ()))
}
pub fn basic_publish(&self, exchange: &str, routing_key: &str, payload: &[u8], options: BasicPublishOptions, properties: BasicProperties) -> Box<Future<Item = Option<RequestId>, Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let exchange = exchange.to_string();
let routing_key = routing_key.to_string();
Box::new(self.run_on_locked_transport_full("basic_publish", "Could not publish", move |transport| {
transport.conn.basic_publish(channel_id, options.ticket, exchange, routing_key,
options.mandatory, options.immediate).map(Some)
}, move |conn, delivery_tag| {
conn.channels.get_mut(&channel_id).and_then(|c| {
if c.confirm {
if c.acked.remove(&delivery_tag) {
Some(Ok(Async::Ready(Some(delivery_tag))))
} else if c.nacked.remove(&delivery_tag) {
Some(Ok(Async::Ready(None)))
} else {
info!("message with tag {} still in unacked: {:?}", delivery_tag, c.unacked);
task::current().notify();
Some(Ok(Async::NotReady))
}
} else {
None
}
}).unwrap_or(Ok(Async::Ready(None)))
}, Some((payload.to_vec(), properties))))
}
pub fn basic_consume(&self, queue: &Queue, consumer_tag: &str, options: BasicConsumeOptions, arguments: FieldTable) -> Box<Future<Item = Consumer<T>, Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let transport = self.transport.clone();
let consumer_tag = consumer_tag.to_string();
let queue_name = queue.name();
let mut consumer = Consumer {
transport: self.transport.clone(),
channel_id: self.id,
queue: queue.name(),
consumer_tag: consumer_tag.to_string(),
registered: false,
};
Box::new(self.run_on_locked_transport("basic_consume", "Could not start consumer", move |transport| {
transport.conn.basic_consume(channel_id, options.ticket, queue_name, consumer_tag,
options.no_local, options.no_ack, options.exclusive, options.no_wait, arguments).map(Some)
}).and_then(move |request_id| {
future::poll_fn(move || {
let mut transport = lock_transport!(transport);
if let Some(consumer_tag) = transport.conn.get_generated_name(request_id.expect("expected request_id")) {
return Ok(Async::Ready(consumer_tag))
} else {
task::current().notify();
return Ok(Async::NotReady)
}
})
}).map(|consumer_tag| {
trace!("basic_consume received response, returning consumer");
consumer.consumer_tag = consumer_tag;
consumer
}))
}
pub fn basic_ack(&self, delivery_tag: u64) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("basic_ack", "Could not ack message", move |transport| {
transport.conn.basic_ack(channel_id, delivery_tag, false).map(|_| None)
}).map(|_| ()))
}
pub fn basic_nack(&self, delivery_tag: u64, requeue: bool) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("basic_nack", "Could not nack message", move |transport| {
transport.conn.basic_nack(channel_id, delivery_tag, false, requeue).map(|_| None)
}).map(|_| ()))
}
pub fn basic_reject(&self, delivery_tag: u64, requeue: bool) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("basic_reject", "Could not reject message", move |transport| {
transport.conn.basic_reject(channel_id, delivery_tag, requeue).map(|_| None)
}).map(|_| ()))
}
pub fn basic_get(&self, queue: &str, options: BasicGetOptions) -> Box<Future<Item = BasicGetMessage, Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let _queue = queue.to_string();
let queue = queue.to_string();
let receive_transport = self.transport.clone();
let receive_future = future::poll_fn(move || {
let mut transport = lock_transport!(receive_transport);
transport.poll()?;
if let Some(message) = transport.conn.next_basic_get_message(channel_id, &_queue) {
return Ok(Async::Ready(message));
}
Ok(Async::NotReady)
});
Box::new(self.run_on_locked_transport_full("basic_get", "Could not get message", move |transport| {
transport.conn.basic_get(channel_id, options.ticket, queue, options.no_ack).map(Some)
}, |conn, request_id| {
match conn.finished_get_result(request_id) {
Some(answer) => if answer {
Ok(Async::Ready(Some(request_id)))
} else {
Err(Error::new(ErrorKind::Other, "basic get returned empty"))
},
None => {
task::current().notify();
Ok(Async::NotReady)
}
}
}, None).and_then(|_| receive_future))
}
pub fn queue_purge(&self, queue_name: &str, options: QueuePurgeOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let queue_name = queue_name.to_string();
Box::new(self.run_on_locked_transport("queue_purge", "Could not purge queue", move |transport| {
transport.conn.queue_purge(channel_id, options.ticket, queue_name, options.nowait).map(Some)
}).map(|_| ()))
}
pub fn queue_delete(&self, queue_name: &str, options: QueueDeleteOptions) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let queue_name = queue_name.to_string();
Box::new(self.run_on_locked_transport("queue_purge", "Could not purge queue", move |transport| {
transport.conn.queue_delete(channel_id, options.ticket, queue_name, options.if_unused, options.if_empty, options.no_wait).map(Some)
}).map(|_| ()))
}
pub fn close(&self, code: u16, message: &str) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
let message = message.to_string();
Box::new(self.run_on_locked_transport("close", "Could not close channel", move |transport| {
transport.conn.channel_close(channel_id, code, message, 0, 0).map(|_| None)
}).map(|_| ()))
}
pub fn close_ok(&self) -> Box<Future<Item = (), Error = io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("close_ok", "Could not ack closed channel", move |transport| {
transport.conn.channel_close_ok(channel_id).map(|_| None)
}).map(|_| ()))
}
pub fn channel_flow(&self, options: ChannelFlowOptions) -> Box<Future<Item = (), Error=io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("channel_flow", "Could not update channel flow", move |transport| {
transport.conn.channel_flow(channel_id, options.active).map(|_| None)
}).map(|_| ()))
}
pub fn channel_flow_ok(&self, options: ChannelFlowOptions) -> Box<Future<Item = (), Error=io::Error> + Send + 'static> {
let channel_id = self.id;
Box::new(self.run_on_locked_transport("channel_flow_ok", "Could not ack update to channel flow", move |transport| {
transport.conn.channel_flow_ok(channel_id, options.active).map(|_| None)
}).map(|_| ()))
}
fn run_on_locked_transport_full<Action, Finished>(&self, method: &str, error: &str, action: Action, finished: Finished, payload: Option<(Vec<u8>, BasicProperties)>) -> Box<Future<Item = Option<RequestId>, Error = io::Error> + Send + 'static>
where Action: 'static + Send + FnOnce(&mut AMQPTransport<T>) -> Result<Option<RequestId>, lapin_async::error::Error>,
Finished: 'static + Send + Fn(&mut Connection, RequestId) -> Poll<Option<RequestId>, io::Error> {
trace!("run on locked transport; method={:?}", method);
let channel_id = self.id;
let transport = self.transport.clone();
let _transport = self.transport.clone();
let _method = method.to_string();
let method = method.to_string();
let error = error.to_string();
let mut action = Some(action);
let mut payload = Some(payload);
Box::new(future::poll_fn(move || {
let mut transport = lock_transport!(transport);
match action.take().unwrap()(&mut transport) {
Err(e) => Err(Error::new(ErrorKind::Other, format!("{}: {:?}", error, e))),
Ok(request_id) => {
trace!("run on locked transport; method={:?} request_id={:?}", _method, request_id);
if let Some((payload, mut properties)) = payload.take().unwrap() {
transport.send_content_frames(channel_id, payload.as_slice(), properties);
}
Ok(Async::Ready(request_id))
},
}
}).and_then(move |request_id| {
if request_id.is_some() {
trace!("{} returning closure", method);
}
Box::new(future::poll_fn(move || {
let mut transport = lock_transport!(_transport);
if let Some(request_id) = request_id {
Self::wait_for_answer(&mut transport, request_id, &finished)
} else {
transport.poll().map(|r| r.map(|_| None))
}
}))
}))
}
fn run_on_lock_transport_basic_finished(conn: &mut Connection, request_id: RequestId) -> Poll<Option<RequestId>, io::Error> {
match conn.is_finished(request_id) {
Some(answer) if answer => Ok(Async::Ready(Some(request_id))),
_ => {
task::current().notify();
Ok(Async::NotReady)
}
}
}
fn run_on_locked_transport<Action>(&self, method: &str, error: &str, action: Action) -> Box<Future<Item = Option<RequestId>, Error = io::Error> + Send + 'static>
where Action: 'static + Send + FnOnce(&mut AMQPTransport<T>) -> Result<Option<RequestId>, lapin_async::error::Error> {
self.run_on_locked_transport_full(method, error, action, Self::run_on_lock_transport_basic_finished, None)
}
pub fn wait_for_answer<Finished>(tr: &mut AMQPTransport<T>, request_id: RequestId, finished: &Finished) -> Poll<Option<RequestId>, io::Error>
where Finished: 'static + Send + Fn(&mut Connection, RequestId) -> Poll<Option<RequestId>, io::Error> {
trace!("wait for answer; request_id={:?}", request_id);
tr.poll()?;
trace!("wait for answer transport poll; request_id={:?} status=NotReady", request_id);
if let Async::Ready(r) = finished(&mut tr.conn, request_id)? {
trace!("wait for answer; request_id={:?} status=Ready result={:?}", request_id, r);
return Ok(Async::Ready(r));
}
trace!("wait for answer; request_id={:?} status=NotReady", request_id);
task::current().notify();
Ok(Async::NotReady)
}
}