channel.go 47 KB

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