channel.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. // Copyright (c) 2012, Sean Treadway, SoundCloud Ltd.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Source code and contact info at http://github.com/streadway/amqp
  5. package amqp
  6. import (
  7. "reflect"
  8. "sync"
  9. )
  10. // 0 1 3 7 size+7 size+8
  11. // +------+---------+-------------+ +------------+ +-----------+
  12. // | type | channel | size | | payload | | frame-end |
  13. // +------+---------+-------------+ +------------+ +-----------+
  14. // octet short long size octets octet
  15. const frameHeaderSize = 1 + 2 + 4 + 1
  16. /*
  17. Channel represents an AMQP channel. Used as a context for valid message
  18. exchange. Errors on methods with this Channel as a receiver means this channel
  19. should be discarded and a new channel established.
  20. */
  21. type Channel struct {
  22. destructor sync.Once
  23. sendM sync.Mutex // sequence channel frames
  24. m sync.Mutex // struct field mutex
  25. connection *Connection
  26. rpc chan message
  27. consumers *consumers
  28. id uint16
  29. // true when we will never notify again
  30. noNotify bool
  31. // Channel and Connection exceptions will be broadcast on these listeners.
  32. closes []chan *Error
  33. // Listeners for active=true flow control. When true is sent to a listener,
  34. // publishing should pause until false is sent to listeners.
  35. flows []chan bool
  36. // Listeners for returned publishings for unroutable messages on mandatory
  37. // publishings or undeliverable messages on immediate publishings.
  38. returns []chan Return
  39. // Listeners for when the server notifies the client that
  40. // a consumer has been cancelled.
  41. cancels []chan string
  42. // Allocated when in confirm mode in order to track publish counter and order confirms
  43. confirms *confirms
  44. confirming bool
  45. // Selects on any errors from shutdown during RPC
  46. errors chan *Error
  47. // State machine that manages frame order, must only be mutated by the connection
  48. recv func(*Channel, frame) error
  49. // State that manages the send behavior after before and after shutdown, must
  50. // only be mutated in shutdown()
  51. send func(*Channel, message) error
  52. // Current state for frame re-assembly, only mutated from recv
  53. message messageWithContent
  54. header *headerFrame
  55. body []byte
  56. }
  57. // Constructs a new channel with the given framing rules
  58. func newChannel(c *Connection, id uint16) *Channel {
  59. return &Channel{
  60. connection: c,
  61. id: id,
  62. rpc: make(chan message),
  63. consumers: makeConsumers(),
  64. confirms: newConfirms(),
  65. recv: (*Channel).recvMethod,
  66. send: (*Channel).sendOpen,
  67. errors: make(chan *Error, 1),
  68. }
  69. }
  70. // shutdown is called by Connection after the channel has been removed from the
  71. // connection registry.
  72. func (me *Channel) shutdown(e *Error) {
  73. me.destructor.Do(func() {
  74. me.m.Lock()
  75. defer me.m.Unlock()
  76. // Broadcast abnormal shutdown
  77. if e != nil {
  78. for _, c := range me.closes {
  79. c <- e
  80. }
  81. }
  82. me.send = (*Channel).sendClosed
  83. // Notify RPC if we're selecting
  84. if e != nil {
  85. me.errors <- e
  86. }
  87. me.consumers.closeAll()
  88. for _, c := range me.closes {
  89. close(c)
  90. }
  91. for _, c := range me.flows {
  92. close(c)
  93. }
  94. for _, c := range me.returns {
  95. close(c)
  96. }
  97. for _, c := range me.cancels {
  98. close(c)
  99. }
  100. if me.confirms != nil {
  101. me.confirms.Close()
  102. }
  103. me.noNotify = true
  104. })
  105. }
  106. func (me *Channel) open() error {
  107. return me.call(&channelOpen{}, &channelOpenOk{})
  108. }
  109. // Performs a request/response call for when the message is not NoWait and is
  110. // specified as Synchronous.
  111. func (me *Channel) call(req message, res ...message) error {
  112. if err := me.send(me, req); err != nil {
  113. return err
  114. }
  115. if req.wait() {
  116. select {
  117. case e := <-me.errors:
  118. return e
  119. case msg := <-me.rpc:
  120. if msg != nil {
  121. for _, try := range res {
  122. if reflect.TypeOf(msg) == reflect.TypeOf(try) {
  123. // *res = *msg
  124. vres := reflect.ValueOf(try).Elem()
  125. vmsg := reflect.ValueOf(msg).Elem()
  126. vres.Set(vmsg)
  127. return nil
  128. }
  129. }
  130. return ErrCommandInvalid
  131. } else {
  132. // RPC channel has been closed without an error, likely due to a hard
  133. // error on the Connection. This indicates we have already been
  134. // shutdown and if were waiting, will have returned from the errors chan.
  135. return ErrClosed
  136. }
  137. }
  138. }
  139. return nil
  140. }
  141. func (me *Channel) sendClosed(msg message) (err error) {
  142. me.sendM.Lock()
  143. defer me.sendM.Unlock()
  144. // After a 'channel.close' is sent or received the only valid response is
  145. // channel.close-ok
  146. if _, ok := msg.(*channelCloseOk); ok {
  147. return me.connection.send(&methodFrame{
  148. ChannelId: me.id,
  149. Method: msg,
  150. })
  151. }
  152. return ErrClosed
  153. }
  154. func (me *Channel) sendOpen(msg message) (err error) {
  155. me.sendM.Lock()
  156. defer me.sendM.Unlock()
  157. if content, ok := msg.(messageWithContent); ok {
  158. props, body := content.getContent()
  159. class, _ := content.id()
  160. // catch client max frame size==0 and server max frame size==0
  161. // set size to length of what we're trying to publish
  162. var size int
  163. if me.connection.Config.FrameSize > 0 {
  164. size = me.connection.Config.FrameSize - frameHeaderSize
  165. } else {
  166. size = len(body)
  167. }
  168. if err = me.connection.send(&methodFrame{
  169. ChannelId: me.id,
  170. Method: content,
  171. }); err != nil {
  172. return
  173. }
  174. if err = me.connection.send(&headerFrame{
  175. ChannelId: me.id,
  176. ClassId: class,
  177. Size: uint64(len(body)),
  178. Properties: props,
  179. }); err != nil {
  180. return
  181. }
  182. // chunk body into size (max frame size - frame header size)
  183. for i, j := 0, size; i < len(body); i, j = j, j+size {
  184. if j > len(body) {
  185. j = len(body)
  186. }
  187. if err = me.connection.send(&bodyFrame{
  188. ChannelId: me.id,
  189. Body: body[i:j],
  190. }); err != nil {
  191. return
  192. }
  193. }
  194. } else {
  195. err = me.connection.send(&methodFrame{
  196. ChannelId: me.id,
  197. Method: msg,
  198. })
  199. }
  200. return
  201. }
  202. // Eventually called via the state machine from the connection's reader
  203. // goroutine, so assumes serialized access.
  204. func (me *Channel) dispatch(msg message) {
  205. switch m := msg.(type) {
  206. case *channelClose:
  207. me.connection.closeChannel(me, newError(m.ReplyCode, m.ReplyText))
  208. me.send(me, &channelCloseOk{})
  209. case *channelFlow:
  210. for _, c := range me.flows {
  211. c <- m.Active
  212. }
  213. me.send(me, &channelFlowOk{Active: m.Active})
  214. case *basicCancel:
  215. for _, c := range me.cancels {
  216. c <- m.ConsumerTag
  217. }
  218. me.send(me, &basicCancelOk{ConsumerTag: m.ConsumerTag})
  219. case *basicReturn:
  220. ret := newReturn(*m)
  221. for _, c := range me.returns {
  222. c <- *ret
  223. }
  224. case *basicAck:
  225. if me.confirming {
  226. if m.Multiple {
  227. me.confirms.Multiple(Confirmation{m.DeliveryTag, true})
  228. } else {
  229. me.confirms.One(Confirmation{m.DeliveryTag, true})
  230. }
  231. }
  232. case *basicNack:
  233. if me.confirming {
  234. if m.Multiple {
  235. me.confirms.Multiple(Confirmation{m.DeliveryTag, false})
  236. } else {
  237. me.confirms.One(Confirmation{m.DeliveryTag, false})
  238. }
  239. }
  240. case *basicDeliver:
  241. me.consumers.send(m.ConsumerTag, newDelivery(me, m))
  242. // TODO log failed consumer and close channel, this can happen when
  243. // deliveries are in flight and a no-wait cancel has happened
  244. default:
  245. me.rpc <- msg
  246. }
  247. }
  248. func (me *Channel) transition(f func(*Channel, frame) error) error {
  249. me.recv = f
  250. return nil
  251. }
  252. func (me *Channel) recvMethod(f frame) error {
  253. switch frame := f.(type) {
  254. case *methodFrame:
  255. if msg, ok := frame.Method.(messageWithContent); ok {
  256. me.body = make([]byte, 0)
  257. me.message = msg
  258. return me.transition((*Channel).recvHeader)
  259. }
  260. me.dispatch(frame.Method) // termination state
  261. return me.transition((*Channel).recvMethod)
  262. case *headerFrame:
  263. // drop
  264. return me.transition((*Channel).recvMethod)
  265. case *bodyFrame:
  266. // drop
  267. return me.transition((*Channel).recvMethod)
  268. default:
  269. panic("unexpected frame type")
  270. }
  271. panic("unreachable")
  272. }
  273. func (me *Channel) recvHeader(f frame) error {
  274. switch frame := f.(type) {
  275. case *methodFrame:
  276. // interrupt content and handle method
  277. return me.recvMethod(f)
  278. case *headerFrame:
  279. // start collecting if we expect body frames
  280. me.header = frame
  281. if frame.Size == 0 {
  282. me.message.setContent(me.header.Properties, me.body)
  283. me.dispatch(me.message) // termination state
  284. return me.transition((*Channel).recvMethod)
  285. } else {
  286. return me.transition((*Channel).recvContent)
  287. }
  288. case *bodyFrame:
  289. // drop and reset
  290. return me.transition((*Channel).recvMethod)
  291. default:
  292. panic("unexpected frame type")
  293. }
  294. panic("unreachable")
  295. }
  296. // state after method + header and before the length
  297. // defined by the header has been reached
  298. func (me *Channel) recvContent(f frame) error {
  299. switch frame := f.(type) {
  300. case *methodFrame:
  301. // interrupt content and handle method
  302. return me.recvMethod(f)
  303. case *headerFrame:
  304. // drop and reset
  305. return me.transition((*Channel).recvMethod)
  306. case *bodyFrame:
  307. me.body = append(me.body, frame.Body...)
  308. if uint64(len(me.body)) >= me.header.Size {
  309. me.message.setContent(me.header.Properties, me.body)
  310. me.dispatch(me.message) // termination state
  311. return me.transition((*Channel).recvMethod)
  312. }
  313. return me.transition((*Channel).recvContent)
  314. default:
  315. panic("unexpected frame type")
  316. }
  317. panic("unreachable")
  318. }
  319. /*
  320. Close initiate a clean channel closure by sending a close message with the error
  321. code set to '200'.
  322. It is safe to call this method multiple times.
  323. */
  324. func (me *Channel) Close() error {
  325. defer me.connection.closeChannel(me, nil)
  326. return me.call(
  327. &channelClose{ReplyCode: replySuccess},
  328. &channelCloseOk{},
  329. )
  330. }
  331. /*
  332. NotifyClose registers a listener for when the server sends a channel or
  333. connection exception in the form of a Connection.Close or Channel.Close method.
  334. Connection exceptions will be broadcast to all open channels and all channels
  335. will be closed, where channel exceptions will only be broadcast to listeners to
  336. this channel.
  337. The chan provided will be closed when the Channel is closed and on a
  338. graceful close, no error will be sent.
  339. */
  340. func (me *Channel) NotifyClose(c chan *Error) chan *Error {
  341. me.m.Lock()
  342. defer me.m.Unlock()
  343. if me.noNotify {
  344. close(c)
  345. } else {
  346. me.closes = append(me.closes, c)
  347. }
  348. return c
  349. }
  350. /*
  351. NotifyFlow registers a listener for basic.flow methods sent by the server.
  352. When `true` is sent on one of the listener channels, all publishers should
  353. pause until a `false` is sent.
  354. The server may ask the producer to pause or restart the flow of Publishings
  355. sent by on a channel. This is a simple flow-control mechanism that a server can
  356. use to avoid overflowing its queues or otherwise finding itself receiving more
  357. messages than it can process. Note that this method is not intended for window
  358. control. It does not affect contents returned by basic.get-ok methods.
  359. When a new channel is opened, it is active (flow is active). Some
  360. applications assume that channels are inactive until started. To emulate
  361. this behavior a client MAY open the channel, then pause it.
  362. Publishers should respond to a flow messages as rapidly as possible and the
  363. server may disconnect over producing channels that do not respect these
  364. messages.
  365. basic.flow-ok methods will always be returned to the server regardless of
  366. the number of listeners there are.
  367. To control the flow of deliveries from the server. Use the Channel.Flow()
  368. method instead.
  369. Note: RabbitMQ will rather use TCP pushback on the network connection instead
  370. of sending basic.flow. This means that if a single channel is producing too
  371. much on the same connection, all channels using that connection will suffer,
  372. including acknowledgments from deliveries. Use different Connections if you
  373. desire to interleave consumers and producers in the same process to avoid your
  374. basic.ack messages from getting rate limited with your basic.publish messages.
  375. */
  376. func (me *Channel) NotifyFlow(c chan bool) chan bool {
  377. me.m.Lock()
  378. defer me.m.Unlock()
  379. if me.noNotify {
  380. close(c)
  381. } else {
  382. me.flows = append(me.flows, c)
  383. }
  384. return c
  385. }
  386. /*
  387. NotifyReturn registers a listener for basic.return methods. These can be sent
  388. from the server when a publish is undeliverable either from the mandatory or
  389. immediate flags.
  390. A return struct has a copy of the Publishing along with some error
  391. information about why the publishing failed.
  392. */
  393. func (me *Channel) NotifyReturn(c chan Return) chan Return {
  394. me.m.Lock()
  395. defer me.m.Unlock()
  396. if me.noNotify {
  397. close(c)
  398. } else {
  399. me.returns = append(me.returns, c)
  400. }
  401. return c
  402. }
  403. /*
  404. NotifyCancel registers a listener for basic.cancel methods. These can be sent
  405. from the server when a queue is deleted or when consuming from a mirrored queue
  406. where the master has just failed (and was moved to another node)
  407. The subscription tag is returned to the listener.
  408. */
  409. func (me *Channel) NotifyCancel(c chan string) chan string {
  410. me.m.Lock()
  411. defer me.m.Unlock()
  412. if me.noNotify {
  413. close(c)
  414. } else {
  415. me.cancels = append(me.cancels, c)
  416. }
  417. return c
  418. }
  419. /*
  420. NotifyConfirm calls NotifyPublish and starts a goroutines sending
  421. ordered Ack and Nack DeliveryTag to the respective channels.
  422. For strict ordering, use NotifyPublish instead.
  423. */
  424. func (me *Channel) NotifyConfirm(ack, nack chan uint64) (chan uint64, chan uint64) {
  425. confirms := me.NotifyPublish(make(chan Confirmation, len(ack)+len(nack)))
  426. go func() {
  427. for c := range confirms {
  428. if c.Ack {
  429. ack <- c.DeliveryTag
  430. } else {
  431. nack <- c.DeliveryTag
  432. }
  433. }
  434. close(ack)
  435. if nack != ack {
  436. close(nack)
  437. }
  438. }()
  439. return ack, nack
  440. }
  441. /*
  442. NotifyPublish registers a listener for reliable publishing. Receives from this
  443. chan for every publish after Channel.Confirm will be in order starting with
  444. DeliveryTag 1.
  445. There will be one and only one Confimration Publishing starting with the
  446. delviery tag of 1 and progressing sequentially until the total number of
  447. Publishings have been seen by the server.
  448. Acknowledgments will be received in the order of delivery from the
  449. NotifyPublish channels even if the server acknowledges them out of order.
  450. The listener chan will be closed when the Channel is closed.
  451. The capacity of the chan Confirmation must be at least as large as the
  452. number of outstanding publishings. Not having enough buffered chans will
  453. create a deadlock if you attempt to perform other operations on the Connection
  454. or Channel while confirms are in-flight.
  455. It's advisable to wait for all Confirmations to arrive before calling
  456. Channel.Close() or Connection.Close().
  457. */
  458. func (me *Channel) NotifyPublish(confirm chan Confirmation) chan Confirmation {
  459. me.m.Lock()
  460. defer me.m.Unlock()
  461. if me.noNotify {
  462. close(confirm)
  463. } else {
  464. me.confirms.Listen(confirm)
  465. }
  466. return confirm
  467. }
  468. /*
  469. Qos controls how many messages or how many bytes the server will try to keep on
  470. the network for consumers before receiving delivery acks. The intent of Qos is
  471. to make sure the network buffers stay full between the server and client.
  472. With a prefetch count greater than zero, the server will deliver that many
  473. messages to consumers before acknowledgments are received. The server ignores
  474. this option when consumers are started with noAck because no acknowledgments
  475. are expected or sent.
  476. With a prefetch size greater than zero, the server will try to keep at least
  477. that many bytes of deliveries flushed to the network before receiving
  478. acknowledgments from the consumers. This option is ignored when consumers are
  479. started with noAck.
  480. When global is true, these Qos settings apply to all existing and future
  481. consumers on all channels on the same connection. When false, the Channel.Qos
  482. settings will apply to all existing and future consumers on this channel.
  483. RabbitMQ does not implement the global flag.
  484. To get round-robin behavior between consumers consuming from the same queue on
  485. different connections, set the prefetch count to 1, and the next available
  486. message on the server will be delivered to the next available consumer.
  487. If your consumer work time is reasonably consistent and not much greater
  488. than two times your network round trip time, you will see significant
  489. throughput improvements starting with a prefetch count of 2 or slightly
  490. greater as described by benchmarks on RabbitMQ.
  491. http://www.rabbitmq.com/blog/2012/04/25/rabbitmq-performance-measurements-part-2/
  492. */
  493. func (me *Channel) Qos(prefetchCount, prefetchSize int, global bool) error {
  494. return me.call(
  495. &basicQos{
  496. PrefetchCount: uint16(prefetchCount),
  497. PrefetchSize: uint32(prefetchSize),
  498. Global: global,
  499. },
  500. &basicQosOk{},
  501. )
  502. }
  503. /*
  504. Cancel stops deliveries to the consumer chan established in Channel.Consume and
  505. identified by consumer.
  506. Only use this method to cleanly stop receiving deliveries from the server and
  507. cleanly shut down the consumer chan identified by this tag. Using this method
  508. and waiting for remaining messages to flush from the consumer chan will ensure
  509. all messages received on the network will be delivered to the receiver of your
  510. consumer chan.
  511. Continue consuming from the chan Delivery provided by Channel.Consume until the
  512. chan closes.
  513. When noWait is true, do not wait for the server to acknowledge the cancel.
  514. Only use this when you are certain there are no deliveries requiring
  515. acknowledgment are in-flight otherwise they will arrive and be dropped in the
  516. client without an ack and will not be redelivered to other consumers.
  517. */
  518. func (me *Channel) Cancel(consumer string, noWait bool) error {
  519. req := &basicCancel{
  520. ConsumerTag: consumer,
  521. NoWait: noWait,
  522. }
  523. res := &basicCancelOk{}
  524. if err := me.call(req, res); err != nil {
  525. return err
  526. }
  527. if req.wait() {
  528. me.consumers.close(res.ConsumerTag)
  529. } else {
  530. // Potentially could drop deliveries in flight
  531. me.consumers.close(consumer)
  532. }
  533. return nil
  534. }
  535. /*
  536. QueueDeclare declares a queue to hold messages and deliver to consumers.
  537. Declaring creates a queue if it doesn't already exist, or ensures that an
  538. existing queue matches the same parameters.
  539. Every queue declared gets a default binding to the empty exchange "" which has
  540. the type "direct" with the routing key matching the queue's name. With this
  541. default binding, it is possible to publish messages that route directly to
  542. this queue by publishing to "" with the routing key of the queue name.
  543. QueueDeclare("alerts", true, false, false false, false, nil)
  544. Publish("", "alerts", false, false, Publishing{Body: []byte("...")})
  545. Delivery Exchange Key Queue
  546. -----------------------------------------------
  547. key: alerts -> "" -> alerts -> alerts
  548. The queue name may be empty, in which the server will generate a unique name
  549. which will be returned in the Name field of Queue struct.
  550. Durable and Non-Auto-Deleted queues will survive server restarts and remain
  551. when there are no remaining consumers or bindings. Persistent publishings will
  552. be restored in this queue on server restart. These queues are only able to be
  553. bound to durable exchanges.
  554. Non-Durable and Auto-Deleted queues will not be redeclared on server restart
  555. and will be deleted by the server after a short time when the last consumer is
  556. canceled or the last consumer's channel is closed. Queues with this lifetime
  557. can also be deleted normally with QueueDelete. These durable queues can only
  558. be bound to non-durable exchanges.
  559. Non-Durable and Non-Auto-Deleted queues will remain declared as long as the
  560. server is running regardless of how many consumers. This lifetime is useful
  561. for temporary topologies that may have long delays between consumer activity.
  562. These queues can only be bound to non-durable exchanges.
  563. Durable and Auto-Deleted queues will be restored on server restart, but without
  564. active consumers, will not survive and be removed. This Lifetime is unlikely
  565. to be useful.
  566. Exclusive queues are only accessible by the connection that declares them and
  567. will be deleted when the connection closes. Channels on other connections
  568. will receive an error when attempting declare, bind, consume, purge or delete a
  569. queue with the same name.
  570. When noWait is true, the queue will assume to be declared on the server. A
  571. channel exception will arrive if the conditions are met for existing queues
  572. or attempting to modify an existing queue from a different connection.
  573. When the error return value is not nil, you can assume the queue could not be
  574. declared with these parameters and the channel will be closed.
  575. */
  576. func (me *Channel) QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args Table) (Queue, error) {
  577. if err := args.Validate(); err != nil {
  578. return Queue{}, err
  579. }
  580. req := &queueDeclare{
  581. Queue: name,
  582. Passive: false,
  583. Durable: durable,
  584. AutoDelete: autoDelete,
  585. Exclusive: exclusive,
  586. NoWait: noWait,
  587. Arguments: args,
  588. }
  589. res := &queueDeclareOk{}
  590. if err := me.call(req, res); err != nil {
  591. return Queue{}, err
  592. }
  593. if req.wait() {
  594. return Queue{
  595. Name: res.Queue,
  596. Messages: int(res.MessageCount),
  597. Consumers: int(res.ConsumerCount),
  598. }, nil
  599. }
  600. return Queue{
  601. Name: name,
  602. }, nil
  603. panic("unreachable")
  604. }
  605. /*
  606. QueueDeclarePassive is functionally and parametrically equivalent to
  607. QueueDeclare, except that it sets the "passive" attribute to true. A passive
  608. queue is assumed by RabbitMQ to already exist, and attempting to connect to a
  609. non-existent queue will cause RabbitMQ to throw an exception. This function
  610. can be used to test for the existence of a queue.
  611. */
  612. func (me *Channel) QueueDeclarePassive(name string, durable, autoDelete, exclusive, noWait bool, args Table) (Queue, error) {
  613. if err := args.Validate(); err != nil {
  614. return Queue{}, err
  615. }
  616. req := &queueDeclare{
  617. Queue: name,
  618. Passive: true,
  619. Durable: durable,
  620. AutoDelete: autoDelete,
  621. Exclusive: exclusive,
  622. NoWait: noWait,
  623. Arguments: args,
  624. }
  625. res := &queueDeclareOk{}
  626. if err := me.call(req, res); err != nil {
  627. return Queue{}, err
  628. }
  629. if req.wait() {
  630. return Queue{
  631. Name: res.Queue,
  632. Messages: int(res.MessageCount),
  633. Consumers: int(res.ConsumerCount),
  634. }, nil
  635. }
  636. return Queue{
  637. Name: name,
  638. }, nil
  639. panic("unreachable")
  640. }
  641. /*
  642. QueueInspect passively declares a queue by name to inspect the current message
  643. count, consumer count.
  644. Use this method to check how many unacknowledged messages reside in the queue
  645. and how many consumers are receiving deliveries and whether a queue by this
  646. name already exists.
  647. If the queue by this name exists, use Channel.QueueDeclare check if it is
  648. declared with specific parameters.
  649. If a queue by this name does not exist, an error will be returned and the
  650. channel will be closed.
  651. */
  652. func (me *Channel) QueueInspect(name string) (Queue, error) {
  653. req := &queueDeclare{
  654. Queue: name,
  655. Passive: true,
  656. }
  657. res := &queueDeclareOk{}
  658. err := me.call(req, res)
  659. state := Queue{
  660. Name: name,
  661. Messages: int(res.MessageCount),
  662. Consumers: int(res.ConsumerCount),
  663. }
  664. return state, err
  665. }
  666. /*
  667. QueueBind binds an exchange to a queue so that publishings to the exchange will
  668. be routed to the queue when the publishing routing key matches the binding
  669. routing key.
  670. QueueBind("pagers", "alert", "log", false, nil)
  671. QueueBind("emails", "info", "log", false, nil)
  672. Delivery Exchange Key Queue
  673. -----------------------------------------------
  674. key: alert --> log ----> alert --> pagers
  675. key: info ---> log ----> info ---> emails
  676. key: debug --> log (none) (dropped)
  677. If a binding with the same key and arguments already exists between the
  678. exchange and queue, the attempt to rebind will be ignored and the existing
  679. binding will be retained.
  680. In the case that multiple bindings may cause the message to be routed to the
  681. same queue, the server will only route the publishing once. This is possible
  682. with topic exchanges.
  683. QueueBind("pagers", "alert", "amq.topic", false, nil)
  684. QueueBind("emails", "info", "amq.topic", false, nil)
  685. QueueBind("emails", "#", "amq.topic", false, nil) // match everything
  686. Delivery Exchange Key Queue
  687. -----------------------------------------------
  688. key: alert --> amq.topic ----> alert --> pagers
  689. key: info ---> amq.topic ----> # ------> emails
  690. \---> info ---/
  691. key: debug --> amq.topic ----> # ------> emails
  692. It is only possible to bind a durable queue to a durable exchange regardless of
  693. whether the queue or exchange is auto-deleted. Bindings between durable queues
  694. and exchanges will also be restored on server restart.
  695. If the binding could not complete, an error will be returned and the channel
  696. will be closed.
  697. When noWait is true and the queue could not be bound, the channel will be
  698. closed with an error.
  699. */
  700. func (me *Channel) QueueBind(name, key, exchange string, noWait bool, args Table) error {
  701. if err := args.Validate(); err != nil {
  702. return err
  703. }
  704. return me.call(
  705. &queueBind{
  706. Queue: name,
  707. Exchange: exchange,
  708. RoutingKey: key,
  709. NoWait: noWait,
  710. Arguments: args,
  711. },
  712. &queueBindOk{},
  713. )
  714. }
  715. /*
  716. QueueUnbind removes a binding between an exchange and queue matching the key and
  717. arguments.
  718. It is possible to send and empty string for the exchange name which means to
  719. unbind the queue from the default exchange.
  720. */
  721. func (me *Channel) QueueUnbind(name, key, exchange string, args Table) error {
  722. if err := args.Validate(); err != nil {
  723. return err
  724. }
  725. return me.call(
  726. &queueUnbind{
  727. Queue: name,
  728. Exchange: exchange,
  729. RoutingKey: key,
  730. Arguments: args,
  731. },
  732. &queueUnbindOk{},
  733. )
  734. }
  735. /*
  736. QueuePurge removes all messages from the named queue which are not waiting to
  737. be acknowledged. Messages that have been delivered but have not yet been
  738. acknowledged will not be removed.
  739. When successful, returns the number of messages purged.
  740. If noWait is true, do not wait for the server response and the number of
  741. messages purged will not be meaningful.
  742. */
  743. func (me *Channel) QueuePurge(name string, noWait bool) (int, error) {
  744. req := &queuePurge{
  745. Queue: name,
  746. NoWait: noWait,
  747. }
  748. res := &queuePurgeOk{}
  749. err := me.call(req, res)
  750. return int(res.MessageCount), err
  751. }
  752. /*
  753. QueueDelete removes the queue from the server including all bindings then
  754. purges the messages based on server configuration, returning the number of
  755. messages purged.
  756. When ifUnused is true, the queue will not be deleted if there are any
  757. consumers on the queue. If there are consumers, an error will be returned and
  758. the channel will be closed.
  759. When ifEmpty is true, the queue will not be deleted if there are any messages
  760. remaining on the queue. If there are messages, an error will be returned and
  761. the channel will be closed.
  762. When noWait is true, the queue will be deleted without waiting for a response
  763. from the server. The purged message count will not be meaningful. If the queue
  764. could not be deleted, a channel exception will be raised and the channel will
  765. be closed.
  766. */
  767. func (me *Channel) QueueDelete(name string, ifUnused, ifEmpty, noWait bool) (int, error) {
  768. req := &queueDelete{
  769. Queue: name,
  770. IfUnused: ifUnused,
  771. IfEmpty: ifEmpty,
  772. NoWait: noWait,
  773. }
  774. res := &queueDeleteOk{}
  775. err := me.call(req, res)
  776. return int(res.MessageCount), err
  777. }
  778. /*
  779. Consume immediately starts delivering queued messages.
  780. Begin receiving on the returned chan Delivery before any other operation on the
  781. Connection or Channel.
  782. Continues deliveries to the returned chan Delivery until Channel.Cancel,
  783. Connection.Close, Channel.Close, or an AMQP exception occurs. Consumers must
  784. range over the chan to ensure all deliveries are received. Unreceived
  785. deliveries will block all methods on the same connection.
  786. All deliveries in AMQP must be acknowledged. It is expected of the consumer to
  787. call Delivery.Ack after it has successfully processed the delivery. If the
  788. consumer is cancelled or the channel or connection is closed any unacknowledged
  789. deliveries will be requeued at the end of the same queue.
  790. The consumer is identified by a string that is unique and scoped for all
  791. consumers on this channel. If you wish to eventually cancel the consumer, use
  792. the same non-empty idenfitier in Channel.Cancel. An empty string will cause
  793. the library to generate a unique identity. The consumer identity will be
  794. included in every Delivery in the ConsumerTag field
  795. When autoAck (also known as noAck) is true, the server will acknowledge
  796. deliveries to this consumer prior to writing the delivery to the network. When
  797. autoAck is true, the consumer should not call Delivery.Ack. Automatically
  798. acknowledging deliveries means that some deliveries may get lost if the
  799. consumer is unable to process them after the server delivers them.
  800. When exclusive is true, the server will ensure that this is the sole consumer
  801. from this queue. When exclusive is false, the server will fairly distribute
  802. deliveries across multiple consumers.
  803. When noLocal is true, the server will not deliver publishing sent from the same
  804. connection to this consumer. It's advisable to use separate connections for
  805. Channel.Publish and Channel.Consume so not to have TCP pushback on publishing
  806. affect the ability to consume messages, so this parameter is here mostly for
  807. completeness.
  808. When noWait is true, do not wait for the server to confirm the request and
  809. immediately begin deliveries. If it is not possible to consume, a channel
  810. exception will be raised and the channel will be closed.
  811. Optional arguments can be provided that have specific semantics for the queue
  812. or server.
  813. When the channel or connection closes, all delivery chans will also close.
  814. Deliveries on the returned chan will be buffered indefinitely. To limit memory
  815. of this buffer, use the Channel.Qos method to limit the amount of
  816. unacknowledged/buffered deliveries the server will deliver on this Channel.
  817. */
  818. func (me *Channel) Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args Table) (<-chan Delivery, error) {
  819. // When we return from me.call, there may be a delivery already for the
  820. // consumer that hasn't been added to the consumer hash yet. Because of
  821. // this, we never rely on the server picking a consumer tag for us.
  822. if err := args.Validate(); err != nil {
  823. return nil, err
  824. }
  825. if consumer == "" {
  826. consumer = uniqueConsumerTag()
  827. }
  828. req := &basicConsume{
  829. Queue: queue,
  830. ConsumerTag: consumer,
  831. NoLocal: noLocal,
  832. NoAck: autoAck,
  833. Exclusive: exclusive,
  834. NoWait: noWait,
  835. Arguments: args,
  836. }
  837. res := &basicConsumeOk{}
  838. deliveries := make(chan Delivery)
  839. me.consumers.add(consumer, deliveries)
  840. if err := me.call(req, res); err != nil {
  841. me.consumers.close(consumer)
  842. return nil, err
  843. }
  844. return (<-chan Delivery)(deliveries), nil
  845. }
  846. /*
  847. ExchangeDeclare declares an exchange on the server. If the exchange does not
  848. already exist, the server will create it. If the exchange exists, the server
  849. verifies that it is of the provided type, durability and auto-delete flags.
  850. Errors returned from this method will close the channel.
  851. Exchange names starting with "amq." are reserved for pre-declared and
  852. standardized exchanges. The client MAY declare an exchange starting with
  853. "amq." if the passive option is set, or the exchange already exists. Names can
  854. consists of a non-empty sequence of letters, digits, hyphen, underscore,
  855. period, or colon.
  856. Each exchange belongs to one of a set of exchange kinds/types implemented by
  857. the server. The exchange types define the functionality of the exchange - i.e.
  858. how messages are routed through it. Once an exchange is declared, its type
  859. cannot be changed. The common types are "direct", "fanout", "topic" and
  860. "headers".
  861. Durable and Non-Auto-Deleted exchanges will survive server restarts and remain
  862. declared when there are no remaining bindings. This is the best lifetime for
  863. long-lived exchange configurations like stable routes and default exchanges.
  864. Non-Durable and Auto-Deleted exchanges will be deleted when there are no
  865. remaining bindings and not restored on server restart. This lifetime is
  866. useful for temporary topologies that should not pollute the virtual host on
  867. failure or after the consumers have completed.
  868. Non-Durable and Non-Auto-deleted exchanges will remain as long as the server is
  869. running including when there are no remaining bindings. This is useful for
  870. temporary topologies that may have long delays between bindings.
  871. Durable and Auto-Deleted exchanges will survive server restarts and will be
  872. removed before and after server restarts when there are no remaining bindings.
  873. These exchanges are useful for robust temporary topologies or when you require
  874. binding durable queues to auto-deleted exchanges.
  875. Note: RabbitMQ declares the default exchange types like 'amq.fanout' as
  876. durable, so queues that bind to these pre-declared exchanges must also be
  877. durable.
  878. Exchanges declared as `internal` do not accept accept publishings. Internal
  879. exchanges are useful for when you wish to implement inter-exchange topologies
  880. that should not be exposed to users of the broker.
  881. When noWait is true, declare without waiting for a confirmation from the server.
  882. The channel may be closed as a result of an error. Add a NotifyClose listener
  883. to respond to any exceptions.
  884. Optional amqp.Table of arguments that are specific to the server's implementation of
  885. the exchange can be sent for exchange types that require extra parameters.
  886. */
  887. func (me *Channel) ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args Table) error {
  888. if err := args.Validate(); err != nil {
  889. return err
  890. }
  891. return me.call(
  892. &exchangeDeclare{
  893. Exchange: name,
  894. Type: kind,
  895. Passive: false,
  896. Durable: durable,
  897. AutoDelete: autoDelete,
  898. Internal: internal,
  899. NoWait: noWait,
  900. Arguments: args,
  901. },
  902. &exchangeDeclareOk{},
  903. )
  904. }
  905. /*
  906. ExchangeDeclarePassive is functionally and parametrically equivalent to
  907. ExchangeDeclare, except that it sets the "passive" attribute to true. A passive
  908. exchange is assumed by RabbitMQ to already exist, and attempting to connect to a
  909. non-existent exchange will cause RabbitMQ to throw an exception. This function
  910. can be used to detect the existence of an exchange.
  911. */
  912. func (me *Channel) ExchangeDeclarePassive(name, kind string, durable, autoDelete, internal, noWait bool, args Table) error {
  913. if err := args.Validate(); err != nil {
  914. return err
  915. }
  916. return me.call(
  917. &exchangeDeclare{
  918. Exchange: name,
  919. Type: kind,
  920. Passive: true,
  921. Durable: durable,
  922. AutoDelete: autoDelete,
  923. Internal: internal,
  924. NoWait: noWait,
  925. Arguments: args,
  926. },
  927. &exchangeDeclareOk{},
  928. )
  929. }
  930. /*
  931. ExchangeDelete removes the named exchange from the server. When an exchange is
  932. deleted all queue bindings on the exchange are also deleted. If this exchange
  933. does not exist, the channel will be closed with an error.
  934. When ifUnused is true, the server will only delete the exchange if it has no queue
  935. bindings. If the exchange has queue bindings the server does not delete it
  936. but close the channel with an exception instead. Set this to true if you are
  937. not the sole owner of the exchange.
  938. When noWait is true, do not wait for a server confirmation that the exchange has
  939. been deleted. Failing to delete the channel could close the channel. Add a
  940. NotifyClose listener to respond to these channel exceptions.
  941. */
  942. func (me *Channel) ExchangeDelete(name string, ifUnused, noWait bool) error {
  943. return me.call(
  944. &exchangeDelete{
  945. Exchange: name,
  946. IfUnused: ifUnused,
  947. NoWait: noWait,
  948. },
  949. &exchangeDeleteOk{},
  950. )
  951. }
  952. /*
  953. ExchangeBind binds an exchange to another exchange to create inter-exchange
  954. routing topologies on the server. This can decouple the private topology and
  955. routing exchanges from exchanges intended solely for publishing endpoints.
  956. Binding two exchanges with identical arguments will not create duplicate
  957. bindings.
  958. Binding one exchange to another with multiple bindings will only deliver a
  959. message once. For example if you bind your exchange to `amq.fanout` with two
  960. different binding keys, only a single message will be delivered to your
  961. exchange even though multiple bindings will match.
  962. Given a message delivered to the source exchange, the message will be forwarded
  963. to the destination exchange when the routing key is matched.
  964. ExchangeBind("sell", "MSFT", "trade", false, nil)
  965. ExchangeBind("buy", "AAPL", "trade", false, nil)
  966. Delivery Source Key Destination
  967. example exchange exchange
  968. -----------------------------------------------
  969. key: AAPL --> trade ----> MSFT sell
  970. \---> AAPL --> buy
  971. When noWait is true, do not wait for the server to confirm the binding. If any
  972. error occurs the channel will be closed. Add a listener to NotifyClose to
  973. handle these errors.
  974. Optional arguments specific to the exchanges bound can also be specified.
  975. */
  976. func (me *Channel) ExchangeBind(destination, key, source string, noWait bool, args Table) error {
  977. if err := args.Validate(); err != nil {
  978. return err
  979. }
  980. return me.call(
  981. &exchangeBind{
  982. Destination: destination,
  983. Source: source,
  984. RoutingKey: key,
  985. NoWait: noWait,
  986. Arguments: args,
  987. },
  988. &exchangeBindOk{},
  989. )
  990. }
  991. /*
  992. ExchangeUnbind unbinds the destination exchange from the source exchange on the
  993. server by removing the routing key between them. This is the inverse of
  994. ExchangeBind. If the binding does not currently exist, an error will be
  995. returned.
  996. When noWait is true, do not wait for the server to confirm the deletion of the
  997. binding. If any error occurs the channel will be closed. Add a listener to
  998. NotifyClose to handle these errors.
  999. Optional arguments that are specific to the type of exchanges bound can also be
  1000. provided. These must match the same arguments specified in ExchangeBind to
  1001. identify the binding.
  1002. */
  1003. func (me *Channel) ExchangeUnbind(destination, key, source string, noWait bool, args Table) error {
  1004. if err := args.Validate(); err != nil {
  1005. return err
  1006. }
  1007. return me.call(
  1008. &exchangeUnbind{
  1009. Destination: destination,
  1010. Source: source,
  1011. RoutingKey: key,
  1012. NoWait: noWait,
  1013. Arguments: args,
  1014. },
  1015. &exchangeUnbindOk{},
  1016. )
  1017. }
  1018. /*
  1019. Publish sends a Publishing from the client to an exchange on the server.
  1020. When you want a single message to be delivered to a single queue, you can
  1021. publish to the default exchange with the routingKey of the queue name. This is
  1022. because every declared queue gets an implicit route to the default exchange.
  1023. Since publishings are asynchronous, any undeliverable message will get returned
  1024. by the server. Add a listener with Channel.NotifyReturn to handle any
  1025. undeliverable message when calling publish with either the mandatory or
  1026. immediate parameters as true.
  1027. Publishings can be undeliverable when the mandatory flag is true and no queue is
  1028. bound that matches the routing key, or when the immediate flag is true and no
  1029. consumer on the matched queue is ready to accept the delivery.
  1030. This can return an error when the channel, connection or socket is closed. The
  1031. error or lack of an error does not indicate whether the server has received this
  1032. publishing.
  1033. It is possible for publishing to not reach the broker if the underlying socket
  1034. is shutdown without pending publishing packets being flushed from the kernel
  1035. buffers. The easy way of making it probable that all publishings reach the
  1036. server is to always call Connection.Close before terminating your publishing
  1037. application. The way to ensure that all publishings reach the server is to add
  1038. a listener to Channel.NotifyPublish and put the channel in confirm mode with
  1039. Channel.Confirm. Publishing delivery tags and their corresponding
  1040. confirmations start at 1. Exit when all publishings are confirmed.
  1041. When Publish does not return an error and the channel is in confirm mode, the
  1042. internal counter for DeliveryTags with the first confirmation starting at 1.
  1043. */
  1044. func (me *Channel) Publish(exchange, key string, mandatory, immediate bool, msg Publishing) error {
  1045. if err := msg.Headers.Validate(); err != nil {
  1046. return err
  1047. }
  1048. me.m.Lock()
  1049. defer me.m.Unlock()
  1050. if err := me.send(me, &basicPublish{
  1051. Exchange: exchange,
  1052. RoutingKey: key,
  1053. Mandatory: mandatory,
  1054. Immediate: immediate,
  1055. Body: msg.Body,
  1056. Properties: properties{
  1057. Headers: msg.Headers,
  1058. ContentType: msg.ContentType,
  1059. ContentEncoding: msg.ContentEncoding,
  1060. DeliveryMode: msg.DeliveryMode,
  1061. Priority: msg.Priority,
  1062. CorrelationId: msg.CorrelationId,
  1063. ReplyTo: msg.ReplyTo,
  1064. Expiration: msg.Expiration,
  1065. MessageId: msg.MessageId,
  1066. Timestamp: msg.Timestamp,
  1067. Type: msg.Type,
  1068. UserId: msg.UserId,
  1069. AppId: msg.AppId,
  1070. },
  1071. }); err != nil {
  1072. return err
  1073. }
  1074. if me.confirming {
  1075. me.confirms.Publish()
  1076. }
  1077. return nil
  1078. }
  1079. /*
  1080. Get synchronously receives a single Delivery from the head of a queue from the
  1081. server to the client. In almost all cases, using Channel.Consume will be
  1082. preferred.
  1083. If there was a delivery waiting on the queue and that delivery was received the
  1084. second return value will be true. If there was no delivery waiting or an error
  1085. occured, the ok bool will be false.
  1086. All deliveries must be acknowledged including those from Channel.Get. Call
  1087. Delivery.Ack on the returned delivery when you have fully processed this
  1088. delivery.
  1089. When autoAck is true, the server will automatically acknowledge this message so
  1090. you don't have to. But if you are unable to fully process this message before
  1091. the channel or connection is closed, the message will not get requeued.
  1092. */
  1093. func (me *Channel) Get(queue string, autoAck bool) (msg Delivery, ok bool, err error) {
  1094. req := &basicGet{Queue: queue, NoAck: autoAck}
  1095. res := &basicGetOk{}
  1096. empty := &basicGetEmpty{}
  1097. if err := me.call(req, res, empty); err != nil {
  1098. return Delivery{}, false, err
  1099. }
  1100. if res.DeliveryTag > 0 {
  1101. return *(newDelivery(me, res)), true, nil
  1102. }
  1103. return Delivery{}, false, nil
  1104. }
  1105. /*
  1106. Tx puts the channel into transaction mode on the server. All publishings and
  1107. acknowledgments following this method will be atomically committed or rolled
  1108. back for a single queue. Call either Channel.TxCommit or Channel.TxRollback to
  1109. leave a this transaction and immediately start a new transaction.
  1110. The atomicity across multiple queues is not defined as queue declarations and
  1111. bindings are not included in the transaction.
  1112. The behavior of publishings that are delivered as mandatory or immediate while
  1113. the channel is in a transaction is not defined.
  1114. Once a channel has been put into transaction mode, it cannot be taken out of
  1115. transaction mode. Use a different channel for non-transactional semantics.
  1116. */
  1117. func (me *Channel) Tx() error {
  1118. return me.call(
  1119. &txSelect{},
  1120. &txSelectOk{},
  1121. )
  1122. }
  1123. /*
  1124. TxCommit atomically commits all publishings and acknowledgments for a single
  1125. queue and immediately start a new transaction.
  1126. Calling this method without having called Channel.Tx is an error.
  1127. */
  1128. func (me *Channel) TxCommit() error {
  1129. return me.call(
  1130. &txCommit{},
  1131. &txCommitOk{},
  1132. )
  1133. }
  1134. /*
  1135. TxRollback atomically rolls back all publishings and acknowledgments for a
  1136. single queue and immediately start a new transaction.
  1137. Calling this method without having called Channel.Tx is an error.
  1138. */
  1139. func (me *Channel) TxRollback() error {
  1140. return me.call(
  1141. &txRollback{},
  1142. &txRollbackOk{},
  1143. )
  1144. }
  1145. /*
  1146. Flow pauses the delivery of messages to consumers on this channel. Channels
  1147. are opened with flow control not active, to open a channel with paused
  1148. deliveries immediately call this method with true after calling
  1149. Connection.Channel.
  1150. When active is true, this method asks the server to temporarily pause deliveries
  1151. until called again with active as false.
  1152. Channel.Get methods will not be affected by flow control.
  1153. This method is not intended to act as window control. Use Channel.Qos to limit
  1154. the number of unacknowledged messages or bytes in flight instead.
  1155. The server may also send us flow methods to throttle our publishings. A well
  1156. behaving publishing client should add a listener with Channel.NotifyFlow and
  1157. pause its publishings when true is sent on that channel.
  1158. Note: RabbitMQ prefers to use TCP push back to control flow for all channels on
  1159. a connection, so under high volume scenarios, it's wise to open separate
  1160. Connections for publishings and deliveries.
  1161. */
  1162. func (me *Channel) Flow(active bool) error {
  1163. return me.call(
  1164. &channelFlow{Active: active},
  1165. &channelFlowOk{},
  1166. )
  1167. }
  1168. /*
  1169. Confirm puts this channel into confirm mode so that the client can ensure all
  1170. publishings have successfully been received by the server. After entering this
  1171. mode, the server will send a basic.ack or basic.nack message with the deliver
  1172. tag set to a 1 based incrementing index corresponding to every publishing
  1173. received after the this method returns.
  1174. Add a listener to Channel.NotifyPublish to respond to the Confirmations. If
  1175. Channel.NotifyPublish is not called, the Confirmations will be silently
  1176. ignored.
  1177. The order of acknowledgments is not bound to the order of deliveries.
  1178. Ack and Nack confirmations will arrive at some point in the future.
  1179. Unroutable mandatory or immediate messages are acknowledged immediately after
  1180. any Channel.NotifyReturn listeners have been notified. Other messages are
  1181. acknowledged when all queues that should have the message routed to them have
  1182. either have received acknowledgment of delivery or have enqueued the message,
  1183. persisting the message if necessary.
  1184. When noWait is true, the client will not wait for a response. A channel
  1185. exception could occur if the server does not support this method.
  1186. */
  1187. func (me *Channel) Confirm(noWait bool) error {
  1188. me.m.Lock()
  1189. defer me.m.Unlock()
  1190. if err := me.call(
  1191. &confirmSelect{Nowait: noWait},
  1192. &confirmSelectOk{},
  1193. ); err != nil {
  1194. return err
  1195. }
  1196. me.confirming = true
  1197. return nil
  1198. }
  1199. /*
  1200. Recover redelivers all unacknowledged deliveries on this channel.
  1201. When requeue is false, messages will be redelivered to the original consumer.
  1202. When requeue is true, messages will be redelivered to any available consumer,
  1203. potentially including the original.
  1204. If the deliveries cannot be recovered, an error will be returned and the channel
  1205. will be closed.
  1206. Note: this method is not implemented on RabbitMQ, use Delivery.Nack instead
  1207. */
  1208. func (me *Channel) Recover(requeue bool) error {
  1209. return me.call(
  1210. &basicRecover{Requeue: requeue},
  1211. &basicRecoverOk{},
  1212. )
  1213. }
  1214. /*
  1215. Ack acknowledges a delivery by its delivery tag when having been consumed with
  1216. Channel.Consume or Channel.Get.
  1217. Ack acknowledges all message received prior to the delivery tag when multiple
  1218. is true.
  1219. See also Delivery.Ack
  1220. */
  1221. func (me *Channel) Ack(tag uint64, multiple bool) error {
  1222. return me.send(me, &basicAck{
  1223. DeliveryTag: tag,
  1224. Multiple: multiple,
  1225. })
  1226. }
  1227. /*
  1228. Nack negatively acknowledges a delivery by its delivery tag. Prefer this
  1229. method to notify the server that you were not able to process this delivery and
  1230. it must be redelivered or dropped.
  1231. See also Delivery.Nack
  1232. */
  1233. func (me *Channel) Nack(tag uint64, multiple bool, requeue bool) error {
  1234. return me.send(me, &basicNack{
  1235. DeliveryTag: tag,
  1236. Multiple: multiple,
  1237. Requeue: requeue,
  1238. })
  1239. }
  1240. /*
  1241. Reject negatively acknowledges a delivery by its delivery tag. Prefer Nack
  1242. over Reject when communicating with a RabbitMQ server because you can Nack
  1243. multiple messages, reducing the amount of protocol messages to exchange.
  1244. See also Delivery.Reject
  1245. */
  1246. func (me *Channel) Reject(tag uint64, requeue bool) error {
  1247. return me.send(me, &basicReject{
  1248. DeliveryTag: tag,
  1249. Requeue: requeue,
  1250. })
  1251. }