js.go 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815
  1. // Copyright 2020-2023 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package nats
  14. import (
  15. "bytes"
  16. "context"
  17. "crypto/sha256"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "math/rand"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/nats-io/nats.go/internal/parser"
  28. "github.com/nats-io/nuid"
  29. )
  30. // JetStream allows persistent messaging through JetStream.
  31. type JetStream interface {
  32. // Publish publishes a message to JetStream.
  33. Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error)
  34. // PublishMsg publishes a Msg to JetStream.
  35. PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error)
  36. // PublishAsync publishes a message to JetStream and returns a PubAckFuture.
  37. // The data should not be changed until the PubAckFuture has been processed.
  38. PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error)
  39. // PublishMsgAsync publishes a Msg to JetStream and returns a PubAckFuture.
  40. // The message should not be changed until the PubAckFuture has been processed.
  41. PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error)
  42. // PublishAsyncPending returns the number of async publishes outstanding for this context.
  43. PublishAsyncPending() int
  44. // PublishAsyncComplete returns a channel that will be closed when all outstanding messages are ack'd.
  45. PublishAsyncComplete() <-chan struct{}
  46. // Subscribe creates an async Subscription for JetStream.
  47. // The stream and consumer names can be provided with the nats.Bind() option.
  48. // For creating an ephemeral (where the consumer name is picked by the server),
  49. // you can provide the stream name with nats.BindStream().
  50. // If no stream name is specified, the library will attempt to figure out which
  51. // stream the subscription is for. See important notes below for more details.
  52. //
  53. // IMPORTANT NOTES:
  54. // * If none of the options Bind() nor Durable() are specified, the library will
  55. // send a request to the server to create an ephemeral JetStream consumer,
  56. // which will be deleted after an Unsubscribe() or Drain(), or automatically
  57. // by the server after a short period of time after the NATS subscription is
  58. // gone.
  59. // * If Durable() option is specified, the library will attempt to lookup a JetStream
  60. // consumer with this name, and if found, will bind to it and not attempt to
  61. // delete it. However, if not found, the library will send a request to
  62. // create such durable JetStream consumer. Note that the library will delete
  63. // the JetStream consumer after an Unsubscribe() or Drain() only if it
  64. // created the durable consumer while subscribing. If the durable consumer
  65. // already existed prior to subscribing it won't be deleted.
  66. // * If Bind() option is provided, the library will attempt to lookup the
  67. // consumer with the given name, and if successful, bind to it. If the lookup fails,
  68. // then the Subscribe() call will return an error.
  69. Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
  70. // SubscribeSync creates a Subscription that can be used to process messages synchronously.
  71. // See important note in Subscribe()
  72. SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error)
  73. // ChanSubscribe creates channel based Subscription.
  74. // See important note in Subscribe()
  75. ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error)
  76. // ChanQueueSubscribe creates channel based Subscription with a queue group.
  77. // See important note in QueueSubscribe()
  78. ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error)
  79. // QueueSubscribe creates a Subscription with a queue group.
  80. // If no optional durable name nor binding options are specified, the queue name will be used as a durable name.
  81. // See important note in Subscribe()
  82. QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error)
  83. // QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously.
  84. // See important note in QueueSubscribe()
  85. QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error)
  86. // PullSubscribe creates a Subscription that can fetch messages.
  87. // See important note in Subscribe(). Additionally, for an ephemeral pull consumer, the "durable" value must be
  88. // set to an empty string.
  89. PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error)
  90. }
  91. // JetStreamContext allows JetStream messaging and stream management.
  92. type JetStreamContext interface {
  93. JetStream
  94. JetStreamManager
  95. KeyValueManager
  96. ObjectStoreManager
  97. }
  98. // Request API subjects for JetStream.
  99. const (
  100. // defaultAPIPrefix is the default prefix for the JetStream API.
  101. defaultAPIPrefix = "$JS.API."
  102. // jsDomainT is used to create JetStream API prefix by specifying only Domain
  103. jsDomainT = "$JS.%s.API."
  104. // jsExtDomainT is used to create a StreamSource External APIPrefix
  105. jsExtDomainT = "$JS.%s.API"
  106. // apiAccountInfo is for obtaining general information about JetStream.
  107. apiAccountInfo = "INFO"
  108. // apiConsumerCreateT is used to create consumers.
  109. // it accepts stream name and consumer name.
  110. apiConsumerCreateT = "CONSUMER.CREATE.%s.%s"
  111. // apiConsumerCreateT is used to create consumers.
  112. // it accepts stream name, consumer name and filter subject
  113. apiConsumerCreateWithFilterSubjectT = "CONSUMER.CREATE.%s.%s.%s"
  114. // apiLegacyConsumerCreateT is used to create consumers.
  115. // this is a legacy endpoint to support creating ephemerals before nats-server v2.9.0.
  116. apiLegacyConsumerCreateT = "CONSUMER.CREATE.%s"
  117. // apiDurableCreateT is used to create durable consumers.
  118. // this is a legacy endpoint to support creating durable consumers before nats-server v2.9.0.
  119. apiDurableCreateT = "CONSUMER.DURABLE.CREATE.%s.%s"
  120. // apiConsumerInfoT is used to create consumers.
  121. apiConsumerInfoT = "CONSUMER.INFO.%s.%s"
  122. // apiRequestNextT is the prefix for the request next message(s) for a consumer in worker/pull mode.
  123. apiRequestNextT = "CONSUMER.MSG.NEXT.%s.%s"
  124. // apiConsumerDeleteT is used to delete consumers.
  125. apiConsumerDeleteT = "CONSUMER.DELETE.%s.%s"
  126. // apiConsumerListT is used to return all detailed consumer information
  127. apiConsumerListT = "CONSUMER.LIST.%s"
  128. // apiConsumerNamesT is used to return a list with all consumer names for the stream.
  129. apiConsumerNamesT = "CONSUMER.NAMES.%s"
  130. // apiStreams can lookup a stream by subject.
  131. apiStreams = "STREAM.NAMES"
  132. // apiStreamCreateT is the endpoint to create new streams.
  133. apiStreamCreateT = "STREAM.CREATE.%s"
  134. // apiStreamInfoT is the endpoint to get information on a stream.
  135. apiStreamInfoT = "STREAM.INFO.%s"
  136. // apiStreamUpdateT is the endpoint to update existing streams.
  137. apiStreamUpdateT = "STREAM.UPDATE.%s"
  138. // apiStreamDeleteT is the endpoint to delete streams.
  139. apiStreamDeleteT = "STREAM.DELETE.%s"
  140. // apiStreamPurgeT is the endpoint to purge streams.
  141. apiStreamPurgeT = "STREAM.PURGE.%s"
  142. // apiStreamListT is the endpoint that will return all detailed stream information
  143. apiStreamListT = "STREAM.LIST"
  144. // apiMsgGetT is the endpoint to get a message.
  145. apiMsgGetT = "STREAM.MSG.GET.%s"
  146. // apiMsgGetT is the endpoint to perform a direct get of a message.
  147. apiDirectMsgGetT = "DIRECT.GET.%s"
  148. // apiDirectMsgGetLastBySubjectT is the endpoint to perform a direct get of a message by subject.
  149. apiDirectMsgGetLastBySubjectT = "DIRECT.GET.%s.%s"
  150. // apiMsgDeleteT is the endpoint to remove a message.
  151. apiMsgDeleteT = "STREAM.MSG.DELETE.%s"
  152. // orderedHeartbeatsInterval is how fast we want HBs from the server during idle.
  153. orderedHeartbeatsInterval = 5 * time.Second
  154. // Scale for threshold of missed HBs or lack of activity.
  155. hbcThresh = 2
  156. // For ChanSubscription, we can't update sub.delivered as we do for other
  157. // type of subscriptions, since the channel is user provided.
  158. // With flow control in play, we will check for flow control on incoming
  159. // messages (as opposed to when they are delivered), but also from a go
  160. // routine. Without this, the subscription would possibly stall until
  161. // a new message or heartbeat/fc are received.
  162. chanSubFCCheckInterval = 250 * time.Millisecond
  163. // Default time wait between retries on Publish iff err is NoResponders.
  164. DefaultPubRetryWait = 250 * time.Millisecond
  165. // Default number of retries
  166. DefaultPubRetryAttempts = 2
  167. // defaultAsyncPubAckInflight is the number of async pub acks inflight.
  168. defaultAsyncPubAckInflight = 4000
  169. )
  170. // Types of control messages, so far heartbeat and flow control
  171. const (
  172. jsCtrlHB = 1
  173. jsCtrlFC = 2
  174. )
  175. // js is an internal struct from a JetStreamContext.
  176. type js struct {
  177. nc *Conn
  178. opts *jsOpts
  179. // For async publish context.
  180. mu sync.RWMutex
  181. rpre string
  182. rsub *Subscription
  183. pafs map[string]*pubAckFuture
  184. stc chan struct{}
  185. dch chan struct{}
  186. rr *rand.Rand
  187. connStatusCh chan (Status)
  188. }
  189. type jsOpts struct {
  190. ctx context.Context
  191. // For importing JetStream from other accounts.
  192. pre string
  193. // Amount of time to wait for API requests.
  194. wait time.Duration
  195. // For async publish error handling.
  196. aecb MsgErrHandler
  197. // Max async pub ack in flight
  198. maxpa int
  199. // the domain that produced the pre
  200. domain string
  201. // enables protocol tracing
  202. ctrace ClientTrace
  203. shouldTrace bool
  204. // purgeOpts contains optional stream purge options
  205. purgeOpts *StreamPurgeRequest
  206. // streamInfoOpts contains optional stream info options
  207. streamInfoOpts *StreamInfoRequest
  208. // streamListSubject is used for subject filtering when listing streams / stream names
  209. streamListSubject string
  210. // For direct get message requests
  211. directGet bool
  212. // For direct get next message
  213. directNextFor string
  214. // featureFlags are used to enable/disable specific JetStream features
  215. featureFlags featureFlags
  216. }
  217. const (
  218. defaultRequestWait = 5 * time.Second
  219. defaultAccountCheck = 20 * time.Second
  220. )
  221. // JetStream returns a JetStreamContext for messaging and stream management.
  222. // Errors are only returned if inconsistent options are provided.
  223. func (nc *Conn) JetStream(opts ...JSOpt) (JetStreamContext, error) {
  224. js := &js{
  225. nc: nc,
  226. opts: &jsOpts{
  227. pre: defaultAPIPrefix,
  228. wait: defaultRequestWait,
  229. maxpa: defaultAsyncPubAckInflight,
  230. },
  231. }
  232. for _, opt := range opts {
  233. if err := opt.configureJSContext(js.opts); err != nil {
  234. return nil, err
  235. }
  236. }
  237. return js, nil
  238. }
  239. // JSOpt configures a JetStreamContext.
  240. type JSOpt interface {
  241. configureJSContext(opts *jsOpts) error
  242. }
  243. // jsOptFn configures an option for the JetStreamContext.
  244. type jsOptFn func(opts *jsOpts) error
  245. func (opt jsOptFn) configureJSContext(opts *jsOpts) error {
  246. return opt(opts)
  247. }
  248. type featureFlags struct {
  249. useDurableConsumerCreate bool
  250. }
  251. // UseLegacyDurableConsumers makes JetStream use the legacy (pre nats-server v2.9.0) subjects for consumer creation.
  252. // If this option is used when creating JetStremContext, $JS.API.CONSUMER.DURABLE.CREATE.<stream>.<consumer> will be used
  253. // to create a consumer with Durable provided, rather than $JS.API.CONSUMER.CREATE.<stream>.<consumer>.
  254. func UseLegacyDurableConsumers() JSOpt {
  255. return jsOptFn(func(opts *jsOpts) error {
  256. opts.featureFlags.useDurableConsumerCreate = true
  257. return nil
  258. })
  259. }
  260. // ClientTrace can be used to trace API interactions for the JetStream Context.
  261. type ClientTrace struct {
  262. RequestSent func(subj string, payload []byte)
  263. ResponseReceived func(subj string, payload []byte, hdr Header)
  264. }
  265. func (ct ClientTrace) configureJSContext(js *jsOpts) error {
  266. js.ctrace = ct
  267. js.shouldTrace = true
  268. return nil
  269. }
  270. // Domain changes the domain part of JetStream API prefix.
  271. func Domain(domain string) JSOpt {
  272. if domain == _EMPTY_ {
  273. return APIPrefix(_EMPTY_)
  274. }
  275. return jsOptFn(func(js *jsOpts) error {
  276. js.domain = domain
  277. js.pre = fmt.Sprintf(jsDomainT, domain)
  278. return nil
  279. })
  280. }
  281. func (s *StreamPurgeRequest) configureJSContext(js *jsOpts) error {
  282. js.purgeOpts = s
  283. return nil
  284. }
  285. func (s *StreamInfoRequest) configureJSContext(js *jsOpts) error {
  286. js.streamInfoOpts = s
  287. return nil
  288. }
  289. // APIPrefix changes the default prefix used for the JetStream API.
  290. func APIPrefix(pre string) JSOpt {
  291. return jsOptFn(func(js *jsOpts) error {
  292. if pre == _EMPTY_ {
  293. return nil
  294. }
  295. js.pre = pre
  296. if !strings.HasSuffix(js.pre, ".") {
  297. js.pre = js.pre + "."
  298. }
  299. return nil
  300. })
  301. }
  302. // DirectGet is an option that can be used to make GetMsg() or GetLastMsg()
  303. // retrieve message directly from a group of servers (leader and replicas)
  304. // if the stream was created with the AllowDirect option.
  305. func DirectGet() JSOpt {
  306. return jsOptFn(func(js *jsOpts) error {
  307. js.directGet = true
  308. return nil
  309. })
  310. }
  311. // DirectGetNext is an option that can be used to make GetMsg() retrieve message
  312. // directly from a group of servers (leader and replicas) if the stream was
  313. // created with the AllowDirect option.
  314. // The server will find the next message matching the filter `subject` starting
  315. // at the start sequence (argument in GetMsg()). The filter `subject` can be a
  316. // wildcard.
  317. func DirectGetNext(subject string) JSOpt {
  318. return jsOptFn(func(js *jsOpts) error {
  319. js.directGet = true
  320. js.directNextFor = subject
  321. return nil
  322. })
  323. }
  324. // StreamListFilter is an option that can be used to configure `StreamsInfo()` and `StreamNames()` requests.
  325. // It allows filtering the returned streams by subject associated with each stream.
  326. // Wildcards can be used. For example, `StreamListFilter(FOO.*.A) will return
  327. // all streams which have at least one subject matching the provided pattern (e.g. FOO.TEST.A).
  328. func StreamListFilter(subject string) JSOpt {
  329. return jsOptFn(func(opts *jsOpts) error {
  330. opts.streamListSubject = subject
  331. return nil
  332. })
  333. }
  334. func (js *js) apiSubj(subj string) string {
  335. if js.opts.pre == _EMPTY_ {
  336. return subj
  337. }
  338. var b strings.Builder
  339. b.WriteString(js.opts.pre)
  340. b.WriteString(subj)
  341. return b.String()
  342. }
  343. // PubOpt configures options for publishing JetStream messages.
  344. type PubOpt interface {
  345. configurePublish(opts *pubOpts) error
  346. }
  347. // pubOptFn is a function option used to configure JetStream Publish.
  348. type pubOptFn func(opts *pubOpts) error
  349. func (opt pubOptFn) configurePublish(opts *pubOpts) error {
  350. return opt(opts)
  351. }
  352. type pubOpts struct {
  353. ctx context.Context
  354. ttl time.Duration
  355. id string
  356. lid string // Expected last msgId
  357. str string // Expected stream name
  358. seq *uint64 // Expected last sequence
  359. lss *uint64 // Expected last sequence per subject
  360. // Publish retries for NoResponders err.
  361. rwait time.Duration // Retry wait between attempts
  362. rnum int // Retry attempts
  363. // stallWait is the max wait of a async pub ack.
  364. stallWait time.Duration
  365. }
  366. // pubAckResponse is the ack response from the JetStream API when publishing a message.
  367. type pubAckResponse struct {
  368. apiResponse
  369. *PubAck
  370. }
  371. // PubAck is an ack received after successfully publishing a message.
  372. type PubAck struct {
  373. Stream string `json:"stream"`
  374. Sequence uint64 `json:"seq"`
  375. Duplicate bool `json:"duplicate,omitempty"`
  376. Domain string `json:"domain,omitempty"`
  377. }
  378. // Headers for published messages.
  379. const (
  380. MsgIdHdr = "Nats-Msg-Id"
  381. ExpectedStreamHdr = "Nats-Expected-Stream"
  382. ExpectedLastSeqHdr = "Nats-Expected-Last-Sequence"
  383. ExpectedLastSubjSeqHdr = "Nats-Expected-Last-Subject-Sequence"
  384. ExpectedLastMsgIdHdr = "Nats-Expected-Last-Msg-Id"
  385. MsgRollup = "Nats-Rollup"
  386. )
  387. // Headers for republished messages and direct gets.
  388. const (
  389. JSStream = "Nats-Stream"
  390. JSSequence = "Nats-Sequence"
  391. JSTimeStamp = "Nats-Time-Stamp"
  392. JSSubject = "Nats-Subject"
  393. JSLastSequence = "Nats-Last-Sequence"
  394. )
  395. // MsgSize is a header that will be part of a consumer's delivered message if HeadersOnly requested.
  396. const MsgSize = "Nats-Msg-Size"
  397. // Rollups, can be subject only or all messages.
  398. const (
  399. MsgRollupSubject = "sub"
  400. MsgRollupAll = "all"
  401. )
  402. // PublishMsg publishes a Msg to a stream from JetStream.
  403. func (js *js) PublishMsg(m *Msg, opts ...PubOpt) (*PubAck, error) {
  404. var o = pubOpts{rwait: DefaultPubRetryWait, rnum: DefaultPubRetryAttempts}
  405. if len(opts) > 0 {
  406. if m.Header == nil {
  407. m.Header = Header{}
  408. }
  409. for _, opt := range opts {
  410. if err := opt.configurePublish(&o); err != nil {
  411. return nil, err
  412. }
  413. }
  414. }
  415. // Check for option collisions. Right now just timeout and context.
  416. if o.ctx != nil && o.ttl != 0 {
  417. return nil, ErrContextAndTimeout
  418. }
  419. if o.ttl == 0 && o.ctx == nil {
  420. o.ttl = js.opts.wait
  421. }
  422. if o.stallWait > 0 {
  423. return nil, fmt.Errorf("nats: stall wait cannot be set to sync publish")
  424. }
  425. if o.id != _EMPTY_ {
  426. m.Header.Set(MsgIdHdr, o.id)
  427. }
  428. if o.lid != _EMPTY_ {
  429. m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
  430. }
  431. if o.str != _EMPTY_ {
  432. m.Header.Set(ExpectedStreamHdr, o.str)
  433. }
  434. if o.seq != nil {
  435. m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10))
  436. }
  437. if o.lss != nil {
  438. m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10))
  439. }
  440. var resp *Msg
  441. var err error
  442. if o.ttl > 0 {
  443. resp, err = js.nc.RequestMsg(m, time.Duration(o.ttl))
  444. } else {
  445. resp, err = js.nc.RequestMsgWithContext(o.ctx, m)
  446. }
  447. if err != nil {
  448. for r, ttl := 0, o.ttl; err == ErrNoResponders && (r < o.rnum || o.rnum < 0); r++ {
  449. // To protect against small blips in leadership changes etc, if we get a no responders here retry.
  450. if o.ctx != nil {
  451. select {
  452. case <-o.ctx.Done():
  453. case <-time.After(o.rwait):
  454. }
  455. } else {
  456. time.Sleep(o.rwait)
  457. }
  458. if o.ttl > 0 {
  459. ttl -= o.rwait
  460. if ttl <= 0 {
  461. err = ErrTimeout
  462. break
  463. }
  464. resp, err = js.nc.RequestMsg(m, time.Duration(ttl))
  465. } else {
  466. resp, err = js.nc.RequestMsgWithContext(o.ctx, m)
  467. }
  468. }
  469. if err != nil {
  470. if err == ErrNoResponders {
  471. err = ErrNoStreamResponse
  472. }
  473. return nil, err
  474. }
  475. }
  476. var pa pubAckResponse
  477. if err := json.Unmarshal(resp.Data, &pa); err != nil {
  478. return nil, ErrInvalidJSAck
  479. }
  480. if pa.Error != nil {
  481. return nil, pa.Error
  482. }
  483. if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
  484. return nil, ErrInvalidJSAck
  485. }
  486. return pa.PubAck, nil
  487. }
  488. // Publish publishes a message to a stream from JetStream.
  489. func (js *js) Publish(subj string, data []byte, opts ...PubOpt) (*PubAck, error) {
  490. return js.PublishMsg(&Msg{Subject: subj, Data: data}, opts...)
  491. }
  492. // PubAckFuture is a future for a PubAck.
  493. type PubAckFuture interface {
  494. // Ok returns a receive only channel that can be used to get a PubAck.
  495. Ok() <-chan *PubAck
  496. // Err returns a receive only channel that can be used to get the error from an async publish.
  497. Err() <-chan error
  498. // Msg returns the message that was sent to the server.
  499. Msg() *Msg
  500. }
  501. type pubAckFuture struct {
  502. js *js
  503. msg *Msg
  504. pa *PubAck
  505. st time.Time
  506. err error
  507. errCh chan error
  508. doneCh chan *PubAck
  509. }
  510. func (paf *pubAckFuture) Ok() <-chan *PubAck {
  511. paf.js.mu.Lock()
  512. defer paf.js.mu.Unlock()
  513. if paf.doneCh == nil {
  514. paf.doneCh = make(chan *PubAck, 1)
  515. if paf.pa != nil {
  516. paf.doneCh <- paf.pa
  517. }
  518. }
  519. return paf.doneCh
  520. }
  521. func (paf *pubAckFuture) Err() <-chan error {
  522. paf.js.mu.Lock()
  523. defer paf.js.mu.Unlock()
  524. if paf.errCh == nil {
  525. paf.errCh = make(chan error, 1)
  526. if paf.err != nil {
  527. paf.errCh <- paf.err
  528. }
  529. }
  530. return paf.errCh
  531. }
  532. func (paf *pubAckFuture) Msg() *Msg {
  533. paf.js.mu.RLock()
  534. defer paf.js.mu.RUnlock()
  535. return paf.msg
  536. }
  537. // For quick token lookup etc.
  538. const aReplyPreLen = 14
  539. const aReplyTokensize = 6
  540. func (js *js) newAsyncReply() string {
  541. js.mu.Lock()
  542. if js.rsub == nil {
  543. // Create our wildcard reply subject.
  544. sha := sha256.New()
  545. sha.Write([]byte(nuid.Next()))
  546. b := sha.Sum(nil)
  547. for i := 0; i < aReplyTokensize; i++ {
  548. b[i] = rdigits[int(b[i]%base)]
  549. }
  550. inboxPrefix := InboxPrefix
  551. if js.nc.Opts.InboxPrefix != _EMPTY_ {
  552. inboxPrefix = js.nc.Opts.InboxPrefix + "."
  553. }
  554. js.rpre = fmt.Sprintf("%s%s.", inboxPrefix, b[:aReplyTokensize])
  555. sub, err := js.nc.Subscribe(fmt.Sprintf("%s*", js.rpre), js.handleAsyncReply)
  556. if err != nil {
  557. js.mu.Unlock()
  558. return _EMPTY_
  559. }
  560. js.rsub = sub
  561. js.rr = rand.New(rand.NewSource(time.Now().UnixNano()))
  562. }
  563. if js.connStatusCh == nil {
  564. js.connStatusCh = js.nc.StatusChanged(RECONNECTING, CLOSED)
  565. go js.resetPendingAcksOnReconnect()
  566. }
  567. var sb strings.Builder
  568. sb.WriteString(js.rpre)
  569. rn := js.rr.Int63()
  570. var b [aReplyTokensize]byte
  571. for i, l := 0, rn; i < len(b); i++ {
  572. b[i] = rdigits[l%base]
  573. l /= base
  574. }
  575. sb.Write(b[:])
  576. js.mu.Unlock()
  577. return sb.String()
  578. }
  579. func (js *js) resetPendingAcksOnReconnect() {
  580. js.mu.Lock()
  581. connStatusCh := js.connStatusCh
  582. js.mu.Unlock()
  583. for {
  584. newStatus, ok := <-connStatusCh
  585. if !ok || newStatus == CLOSED {
  586. return
  587. }
  588. js.mu.Lock()
  589. for _, paf := range js.pafs {
  590. paf.err = ErrDisconnected
  591. }
  592. js.pafs = nil
  593. if js.dch != nil {
  594. close(js.dch)
  595. js.dch = nil
  596. }
  597. js.mu.Unlock()
  598. }
  599. }
  600. func (js *js) cleanupReplySub() {
  601. js.mu.Lock()
  602. if js.rsub != nil {
  603. js.rsub.Unsubscribe()
  604. js.rsub = nil
  605. }
  606. if js.connStatusCh != nil {
  607. close(js.connStatusCh)
  608. js.connStatusCh = nil
  609. }
  610. js.mu.Unlock()
  611. }
  612. // registerPAF will register for a PubAckFuture.
  613. func (js *js) registerPAF(id string, paf *pubAckFuture) (int, int) {
  614. js.mu.Lock()
  615. if js.pafs == nil {
  616. js.pafs = make(map[string]*pubAckFuture)
  617. }
  618. paf.js = js
  619. js.pafs[id] = paf
  620. np := len(js.pafs)
  621. maxpa := js.opts.maxpa
  622. js.mu.Unlock()
  623. return np, maxpa
  624. }
  625. // Lock should be held.
  626. func (js *js) getPAF(id string) *pubAckFuture {
  627. if js.pafs == nil {
  628. return nil
  629. }
  630. return js.pafs[id]
  631. }
  632. // clearPAF will remove a PubAckFuture that was registered.
  633. func (js *js) clearPAF(id string) {
  634. js.mu.Lock()
  635. delete(js.pafs, id)
  636. js.mu.Unlock()
  637. }
  638. // PublishAsyncPending returns how many PubAckFutures are pending.
  639. func (js *js) PublishAsyncPending() int {
  640. js.mu.RLock()
  641. defer js.mu.RUnlock()
  642. return len(js.pafs)
  643. }
  644. func (js *js) asyncStall() <-chan struct{} {
  645. js.mu.Lock()
  646. if js.stc == nil {
  647. js.stc = make(chan struct{})
  648. }
  649. stc := js.stc
  650. js.mu.Unlock()
  651. return stc
  652. }
  653. // Handle an async reply from PublishAsync.
  654. func (js *js) handleAsyncReply(m *Msg) {
  655. if len(m.Subject) <= aReplyPreLen {
  656. return
  657. }
  658. id := m.Subject[aReplyPreLen:]
  659. js.mu.Lock()
  660. paf := js.getPAF(id)
  661. if paf == nil {
  662. js.mu.Unlock()
  663. return
  664. }
  665. // Remove
  666. delete(js.pafs, id)
  667. // Check on anyone stalled and waiting.
  668. if js.stc != nil && len(js.pafs) < js.opts.maxpa {
  669. close(js.stc)
  670. js.stc = nil
  671. }
  672. // Check on anyone one waiting on done status.
  673. if js.dch != nil && len(js.pafs) == 0 {
  674. dch := js.dch
  675. js.dch = nil
  676. // Defer here so error is processed and can be checked.
  677. defer close(dch)
  678. }
  679. doErr := func(err error) {
  680. paf.err = err
  681. if paf.errCh != nil {
  682. paf.errCh <- paf.err
  683. }
  684. cb := js.opts.aecb
  685. js.mu.Unlock()
  686. if cb != nil {
  687. cb(paf.js, paf.msg, err)
  688. }
  689. }
  690. // Process no responders etc.
  691. if len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
  692. doErr(ErrNoResponders)
  693. return
  694. }
  695. var pa pubAckResponse
  696. if err := json.Unmarshal(m.Data, &pa); err != nil {
  697. doErr(ErrInvalidJSAck)
  698. return
  699. }
  700. if pa.Error != nil {
  701. doErr(pa.Error)
  702. return
  703. }
  704. if pa.PubAck == nil || pa.PubAck.Stream == _EMPTY_ {
  705. doErr(ErrInvalidJSAck)
  706. return
  707. }
  708. // So here we have received a proper puback.
  709. paf.pa = pa.PubAck
  710. if paf.doneCh != nil {
  711. paf.doneCh <- paf.pa
  712. }
  713. js.mu.Unlock()
  714. }
  715. // MsgErrHandler is used to process asynchronous errors from
  716. // JetStream PublishAsync. It will return the original
  717. // message sent to the server for possible retransmitting and the error encountered.
  718. type MsgErrHandler func(JetStream, *Msg, error)
  719. // PublishAsyncErrHandler sets the error handler for async publishes in JetStream.
  720. func PublishAsyncErrHandler(cb MsgErrHandler) JSOpt {
  721. return jsOptFn(func(js *jsOpts) error {
  722. js.aecb = cb
  723. return nil
  724. })
  725. }
  726. // PublishAsyncMaxPending sets the maximum outstanding async publishes that can be inflight at one time.
  727. func PublishAsyncMaxPending(max int) JSOpt {
  728. return jsOptFn(func(js *jsOpts) error {
  729. if max < 1 {
  730. return errors.New("nats: max ack pending should be >= 1")
  731. }
  732. js.maxpa = max
  733. return nil
  734. })
  735. }
  736. // PublishAsync publishes a message to JetStream and returns a PubAckFuture
  737. func (js *js) PublishAsync(subj string, data []byte, opts ...PubOpt) (PubAckFuture, error) {
  738. return js.PublishMsgAsync(&Msg{Subject: subj, Data: data}, opts...)
  739. }
  740. const defaultStallWait = 200 * time.Millisecond
  741. func (js *js) PublishMsgAsync(m *Msg, opts ...PubOpt) (PubAckFuture, error) {
  742. var o pubOpts
  743. if len(opts) > 0 {
  744. if m.Header == nil {
  745. m.Header = Header{}
  746. }
  747. for _, opt := range opts {
  748. if err := opt.configurePublish(&o); err != nil {
  749. return nil, err
  750. }
  751. }
  752. }
  753. // Timeouts and contexts do not make sense for these.
  754. if o.ttl != 0 || o.ctx != nil {
  755. return nil, ErrContextAndTimeout
  756. }
  757. stallWait := defaultStallWait
  758. if o.stallWait > 0 {
  759. stallWait = o.stallWait
  760. }
  761. // FIXME(dlc) - Make common.
  762. if o.id != _EMPTY_ {
  763. m.Header.Set(MsgIdHdr, o.id)
  764. }
  765. if o.lid != _EMPTY_ {
  766. m.Header.Set(ExpectedLastMsgIdHdr, o.lid)
  767. }
  768. if o.str != _EMPTY_ {
  769. m.Header.Set(ExpectedStreamHdr, o.str)
  770. }
  771. if o.seq != nil {
  772. m.Header.Set(ExpectedLastSeqHdr, strconv.FormatUint(*o.seq, 10))
  773. }
  774. if o.lss != nil {
  775. m.Header.Set(ExpectedLastSubjSeqHdr, strconv.FormatUint(*o.lss, 10))
  776. }
  777. // Reply
  778. if m.Reply != _EMPTY_ {
  779. return nil, errors.New("nats: reply subject should be empty")
  780. }
  781. reply := m.Reply
  782. m.Reply = js.newAsyncReply()
  783. defer func() { m.Reply = reply }()
  784. if m.Reply == _EMPTY_ {
  785. return nil, errors.New("nats: error creating async reply handler")
  786. }
  787. id := m.Reply[aReplyPreLen:]
  788. paf := &pubAckFuture{msg: m, st: time.Now()}
  789. numPending, maxPending := js.registerPAF(id, paf)
  790. if maxPending > 0 && numPending >= maxPending {
  791. select {
  792. case <-js.asyncStall():
  793. case <-time.After(stallWait):
  794. js.clearPAF(id)
  795. return nil, errors.New("nats: stalled with too many outstanding async published messages")
  796. }
  797. }
  798. if err := js.nc.PublishMsg(m); err != nil {
  799. js.clearPAF(id)
  800. return nil, err
  801. }
  802. return paf, nil
  803. }
  804. // PublishAsyncComplete returns a channel that will be closed when all outstanding messages have been ack'd.
  805. func (js *js) PublishAsyncComplete() <-chan struct{} {
  806. js.mu.Lock()
  807. defer js.mu.Unlock()
  808. if js.dch == nil {
  809. js.dch = make(chan struct{})
  810. }
  811. dch := js.dch
  812. if len(js.pafs) == 0 {
  813. close(js.dch)
  814. js.dch = nil
  815. }
  816. return dch
  817. }
  818. // MsgId sets the message ID used for deduplication.
  819. func MsgId(id string) PubOpt {
  820. return pubOptFn(func(opts *pubOpts) error {
  821. opts.id = id
  822. return nil
  823. })
  824. }
  825. // ExpectStream sets the expected stream to respond from the publish.
  826. func ExpectStream(stream string) PubOpt {
  827. return pubOptFn(func(opts *pubOpts) error {
  828. opts.str = stream
  829. return nil
  830. })
  831. }
  832. // ExpectLastSequence sets the expected sequence in the response from the publish.
  833. func ExpectLastSequence(seq uint64) PubOpt {
  834. return pubOptFn(func(opts *pubOpts) error {
  835. opts.seq = &seq
  836. return nil
  837. })
  838. }
  839. // ExpectLastSequencePerSubject sets the expected sequence per subject in the response from the publish.
  840. func ExpectLastSequencePerSubject(seq uint64) PubOpt {
  841. return pubOptFn(func(opts *pubOpts) error {
  842. opts.lss = &seq
  843. return nil
  844. })
  845. }
  846. // ExpectLastMsgId sets the expected last msgId in the response from the publish.
  847. func ExpectLastMsgId(id string) PubOpt {
  848. return pubOptFn(func(opts *pubOpts) error {
  849. opts.lid = id
  850. return nil
  851. })
  852. }
  853. // RetryWait sets the retry wait time when ErrNoResponders is encountered.
  854. func RetryWait(dur time.Duration) PubOpt {
  855. return pubOptFn(func(opts *pubOpts) error {
  856. opts.rwait = dur
  857. return nil
  858. })
  859. }
  860. // RetryAttempts sets the retry number of attempts when ErrNoResponders is encountered.
  861. func RetryAttempts(num int) PubOpt {
  862. return pubOptFn(func(opts *pubOpts) error {
  863. opts.rnum = num
  864. return nil
  865. })
  866. }
  867. // StallWait sets the max wait when the producer becomes stall producing messages.
  868. func StallWait(ttl time.Duration) PubOpt {
  869. return pubOptFn(func(opts *pubOpts) error {
  870. if ttl <= 0 {
  871. return fmt.Errorf("nats: stall wait should be more than 0")
  872. }
  873. opts.stallWait = ttl
  874. return nil
  875. })
  876. }
  877. type ackOpts struct {
  878. ttl time.Duration
  879. ctx context.Context
  880. nakDelay time.Duration
  881. }
  882. // AckOpt are the options that can be passed when acknowledge a message.
  883. type AckOpt interface {
  884. configureAck(opts *ackOpts) error
  885. }
  886. // MaxWait sets the maximum amount of time we will wait for a response.
  887. type MaxWait time.Duration
  888. func (ttl MaxWait) configureJSContext(js *jsOpts) error {
  889. js.wait = time.Duration(ttl)
  890. return nil
  891. }
  892. func (ttl MaxWait) configurePull(opts *pullOpts) error {
  893. opts.ttl = time.Duration(ttl)
  894. return nil
  895. }
  896. // AckWait sets the maximum amount of time we will wait for an ack.
  897. type AckWait time.Duration
  898. func (ttl AckWait) configurePublish(opts *pubOpts) error {
  899. opts.ttl = time.Duration(ttl)
  900. return nil
  901. }
  902. func (ttl AckWait) configureSubscribe(opts *subOpts) error {
  903. opts.cfg.AckWait = time.Duration(ttl)
  904. return nil
  905. }
  906. func (ttl AckWait) configureAck(opts *ackOpts) error {
  907. opts.ttl = time.Duration(ttl)
  908. return nil
  909. }
  910. // ContextOpt is an option used to set a context.Context.
  911. type ContextOpt struct {
  912. context.Context
  913. }
  914. func (ctx ContextOpt) configureJSContext(opts *jsOpts) error {
  915. opts.ctx = ctx
  916. return nil
  917. }
  918. func (ctx ContextOpt) configurePublish(opts *pubOpts) error {
  919. opts.ctx = ctx
  920. return nil
  921. }
  922. func (ctx ContextOpt) configureSubscribe(opts *subOpts) error {
  923. opts.ctx = ctx
  924. return nil
  925. }
  926. func (ctx ContextOpt) configurePull(opts *pullOpts) error {
  927. opts.ctx = ctx
  928. return nil
  929. }
  930. func (ctx ContextOpt) configureAck(opts *ackOpts) error {
  931. opts.ctx = ctx
  932. return nil
  933. }
  934. // Context returns an option that can be used to configure a context for APIs
  935. // that are context aware such as those part of the JetStream interface.
  936. func Context(ctx context.Context) ContextOpt {
  937. return ContextOpt{ctx}
  938. }
  939. type nakDelay time.Duration
  940. func (d nakDelay) configureAck(opts *ackOpts) error {
  941. opts.nakDelay = time.Duration(d)
  942. return nil
  943. }
  944. // Subscribe
  945. // ConsumerConfig is the configuration of a JetStream consumer.
  946. type ConsumerConfig struct {
  947. Durable string `json:"durable_name,omitempty"`
  948. Name string `json:"name,omitempty"`
  949. Description string `json:"description,omitempty"`
  950. DeliverPolicy DeliverPolicy `json:"deliver_policy"`
  951. OptStartSeq uint64 `json:"opt_start_seq,omitempty"`
  952. OptStartTime *time.Time `json:"opt_start_time,omitempty"`
  953. AckPolicy AckPolicy `json:"ack_policy"`
  954. AckWait time.Duration `json:"ack_wait,omitempty"`
  955. MaxDeliver int `json:"max_deliver,omitempty"`
  956. BackOff []time.Duration `json:"backoff,omitempty"`
  957. FilterSubject string `json:"filter_subject,omitempty"`
  958. FilterSubjects []string `json:"filter_subjects,omitempty"`
  959. ReplayPolicy ReplayPolicy `json:"replay_policy"`
  960. RateLimit uint64 `json:"rate_limit_bps,omitempty"` // Bits per sec
  961. SampleFrequency string `json:"sample_freq,omitempty"`
  962. MaxWaiting int `json:"max_waiting,omitempty"`
  963. MaxAckPending int `json:"max_ack_pending,omitempty"`
  964. FlowControl bool `json:"flow_control,omitempty"`
  965. Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
  966. HeadersOnly bool `json:"headers_only,omitempty"`
  967. // Pull based options.
  968. MaxRequestBatch int `json:"max_batch,omitempty"`
  969. MaxRequestExpires time.Duration `json:"max_expires,omitempty"`
  970. MaxRequestMaxBytes int `json:"max_bytes,omitempty"`
  971. // Push based consumers.
  972. DeliverSubject string `json:"deliver_subject,omitempty"`
  973. DeliverGroup string `json:"deliver_group,omitempty"`
  974. // Inactivity threshold.
  975. InactiveThreshold time.Duration `json:"inactive_threshold,omitempty"`
  976. // Generally inherited by parent stream and other markers, now can be configured directly.
  977. Replicas int `json:"num_replicas"`
  978. // Force memory storage.
  979. MemoryStorage bool `json:"mem_storage,omitempty"`
  980. // Metadata is additional metadata for the Consumer.
  981. // Keys starting with `_nats` are reserved.
  982. // NOTE: Metadata requires nats-server v2.10.0+
  983. Metadata map[string]string `json:"metadata,omitempty"`
  984. }
  985. // ConsumerInfo is the info from a JetStream consumer.
  986. type ConsumerInfo struct {
  987. Stream string `json:"stream_name"`
  988. Name string `json:"name"`
  989. Created time.Time `json:"created"`
  990. Config ConsumerConfig `json:"config"`
  991. Delivered SequenceInfo `json:"delivered"`
  992. AckFloor SequenceInfo `json:"ack_floor"`
  993. NumAckPending int `json:"num_ack_pending"`
  994. NumRedelivered int `json:"num_redelivered"`
  995. NumWaiting int `json:"num_waiting"`
  996. NumPending uint64 `json:"num_pending"`
  997. Cluster *ClusterInfo `json:"cluster,omitempty"`
  998. PushBound bool `json:"push_bound,omitempty"`
  999. }
  1000. // SequenceInfo has both the consumer and the stream sequence and last activity.
  1001. type SequenceInfo struct {
  1002. Consumer uint64 `json:"consumer_seq"`
  1003. Stream uint64 `json:"stream_seq"`
  1004. Last *time.Time `json:"last_active,omitempty"`
  1005. }
  1006. // SequencePair includes the consumer and stream sequence info from a JetStream consumer.
  1007. type SequencePair struct {
  1008. Consumer uint64 `json:"consumer_seq"`
  1009. Stream uint64 `json:"stream_seq"`
  1010. }
  1011. // nextRequest is for getting next messages for pull based consumers from JetStream.
  1012. type nextRequest struct {
  1013. Expires time.Duration `json:"expires,omitempty"`
  1014. Batch int `json:"batch,omitempty"`
  1015. NoWait bool `json:"no_wait,omitempty"`
  1016. MaxBytes int `json:"max_bytes,omitempty"`
  1017. Heartbeat time.Duration `json:"idle_heartbeat,omitempty"`
  1018. }
  1019. // jsSub includes JetStream subscription info.
  1020. type jsSub struct {
  1021. js *js
  1022. // For pull subscribers, this is the next message subject to send requests to.
  1023. nms string
  1024. psubj string // the subject that was passed by user to the subscribe calls
  1025. consumer string
  1026. stream string
  1027. deliver string
  1028. pull bool
  1029. dc bool // Delete JS consumer
  1030. ackNone bool
  1031. // This is ConsumerInfo's Pending+Consumer.Delivered that we get from the
  1032. // add consumer response. Note that some versions of the server gather the
  1033. // consumer info *after* the creation of the consumer, which means that
  1034. // some messages may have been already delivered. So the sum of the two
  1035. // is a more accurate representation of the number of messages pending or
  1036. // in the process of being delivered to the subscription when created.
  1037. pending uint64
  1038. // Ordered consumers
  1039. ordered bool
  1040. dseq uint64
  1041. sseq uint64
  1042. ccreq *createConsumerRequest
  1043. // Heartbeats and Flow Control handling from push consumers.
  1044. hbc *time.Timer
  1045. hbi time.Duration
  1046. active bool
  1047. cmeta string
  1048. fcr string
  1049. fcd uint64
  1050. fciseq uint64
  1051. csfct *time.Timer
  1052. // Cancellation function to cancel context on drain/unsubscribe.
  1053. cancel func()
  1054. }
  1055. // Deletes the JS Consumer.
  1056. // No connection nor subscription lock must be held on entry.
  1057. func (sub *Subscription) deleteConsumer() error {
  1058. sub.mu.Lock()
  1059. jsi := sub.jsi
  1060. if jsi == nil {
  1061. sub.mu.Unlock()
  1062. return nil
  1063. }
  1064. stream, consumer := jsi.stream, jsi.consumer
  1065. js := jsi.js
  1066. sub.mu.Unlock()
  1067. return js.DeleteConsumer(stream, consumer)
  1068. }
  1069. // SubOpt configures options for subscribing to JetStream consumers.
  1070. type SubOpt interface {
  1071. configureSubscribe(opts *subOpts) error
  1072. }
  1073. // subOptFn is a function option used to configure a JetStream Subscribe.
  1074. type subOptFn func(opts *subOpts) error
  1075. func (opt subOptFn) configureSubscribe(opts *subOpts) error {
  1076. return opt(opts)
  1077. }
  1078. // Subscribe creates an async Subscription for JetStream.
  1079. // The stream and consumer names can be provided with the nats.Bind() option.
  1080. // For creating an ephemeral (where the consumer name is picked by the server),
  1081. // you can provide the stream name with nats.BindStream().
  1082. // If no stream name is specified, the library will attempt to figure out which
  1083. // stream the subscription is for. See important notes below for more details.
  1084. //
  1085. // IMPORTANT NOTES:
  1086. // * If none of the options Bind() nor Durable() are specified, the library will
  1087. // send a request to the server to create an ephemeral JetStream consumer,
  1088. // which will be deleted after an Unsubscribe() or Drain(), or automatically
  1089. // by the server after a short period of time after the NATS subscription is
  1090. // gone.
  1091. // * If Durable() option is specified, the library will attempt to lookup a JetStream
  1092. // consumer with this name, and if found, will bind to it and not attempt to
  1093. // delete it. However, if not found, the library will send a request to create
  1094. // such durable JetStream consumer. The library will delete the JetStream consumer
  1095. // after an Unsubscribe() or Drain().
  1096. // * If Bind() option is provided, the library will attempt to lookup the
  1097. // consumer with the given name, and if successful, bind to it. If the lookup fails,
  1098. // then the Subscribe() call will return an error.
  1099. func (js *js) Subscribe(subj string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
  1100. if cb == nil {
  1101. return nil, ErrBadSubscription
  1102. }
  1103. return js.subscribe(subj, _EMPTY_, cb, nil, false, false, opts)
  1104. }
  1105. // SubscribeSync creates a Subscription that can be used to process messages synchronously.
  1106. // See important note in Subscribe()
  1107. func (js *js) SubscribeSync(subj string, opts ...SubOpt) (*Subscription, error) {
  1108. mch := make(chan *Msg, js.nc.Opts.SubChanLen)
  1109. return js.subscribe(subj, _EMPTY_, nil, mch, true, false, opts)
  1110. }
  1111. // QueueSubscribe creates a Subscription with a queue group.
  1112. // If no optional durable name nor binding options are specified, the queue name will be used as a durable name.
  1113. // See important note in Subscribe()
  1114. func (js *js) QueueSubscribe(subj, queue string, cb MsgHandler, opts ...SubOpt) (*Subscription, error) {
  1115. if cb == nil {
  1116. return nil, ErrBadSubscription
  1117. }
  1118. return js.subscribe(subj, queue, cb, nil, false, false, opts)
  1119. }
  1120. // QueueSubscribeSync creates a Subscription with a queue group that can be used to process messages synchronously.
  1121. // See important note in QueueSubscribe()
  1122. func (js *js) QueueSubscribeSync(subj, queue string, opts ...SubOpt) (*Subscription, error) {
  1123. mch := make(chan *Msg, js.nc.Opts.SubChanLen)
  1124. return js.subscribe(subj, queue, nil, mch, true, false, opts)
  1125. }
  1126. // ChanSubscribe creates channel based Subscription.
  1127. // Using ChanSubscribe without buffered capacity is not recommended since
  1128. // it will be prone to dropping messages with a slow consumer error. Make sure to give the channel enough
  1129. // capacity to handle bursts in traffic, for example other Subscribe APIs use a default of 512k capacity in comparison.
  1130. // See important note in Subscribe()
  1131. func (js *js) ChanSubscribe(subj string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) {
  1132. return js.subscribe(subj, _EMPTY_, nil, ch, false, false, opts)
  1133. }
  1134. // ChanQueueSubscribe creates channel based Subscription with a queue group.
  1135. // See important note in QueueSubscribe()
  1136. func (js *js) ChanQueueSubscribe(subj, queue string, ch chan *Msg, opts ...SubOpt) (*Subscription, error) {
  1137. return js.subscribe(subj, queue, nil, ch, false, false, opts)
  1138. }
  1139. // PullSubscribe creates a Subscription that can fetch messages.
  1140. // See important note in Subscribe()
  1141. func (js *js) PullSubscribe(subj, durable string, opts ...SubOpt) (*Subscription, error) {
  1142. mch := make(chan *Msg, js.nc.Opts.SubChanLen)
  1143. if durable != "" {
  1144. opts = append(opts, Durable(durable))
  1145. }
  1146. return js.subscribe(subj, _EMPTY_, nil, mch, true, true, opts)
  1147. }
  1148. func processConsInfo(info *ConsumerInfo, userCfg *ConsumerConfig, isPullMode bool, subj, queue string) (string, error) {
  1149. ccfg := &info.Config
  1150. // Make sure this new subject matches or is a subset.
  1151. if ccfg.FilterSubject != _EMPTY_ && subj != ccfg.FilterSubject {
  1152. return _EMPTY_, ErrSubjectMismatch
  1153. }
  1154. // Prevent binding a subscription against incompatible consumer types.
  1155. if isPullMode && ccfg.DeliverSubject != _EMPTY_ {
  1156. return _EMPTY_, ErrPullSubscribeToPushConsumer
  1157. } else if !isPullMode && ccfg.DeliverSubject == _EMPTY_ {
  1158. return _EMPTY_, ErrPullSubscribeRequired
  1159. }
  1160. // If pull mode, nothing else to check here.
  1161. if isPullMode {
  1162. return _EMPTY_, checkConfig(ccfg, userCfg)
  1163. }
  1164. // At this point, we know the user wants push mode, and the JS consumer is
  1165. // really push mode.
  1166. dg := info.Config.DeliverGroup
  1167. if dg == _EMPTY_ {
  1168. // Prevent an user from attempting to create a queue subscription on
  1169. // a JS consumer that was not created with a deliver group.
  1170. if queue != _EMPTY_ {
  1171. return _EMPTY_, fmt.Errorf("cannot create a queue subscription for a consumer without a deliver group")
  1172. } else if info.PushBound {
  1173. // Need to reject a non queue subscription to a non queue consumer
  1174. // if the consumer is already bound.
  1175. return _EMPTY_, fmt.Errorf("consumer is already bound to a subscription")
  1176. }
  1177. } else {
  1178. // If the JS consumer has a deliver group, we need to fail a non queue
  1179. // subscription attempt:
  1180. if queue == _EMPTY_ {
  1181. return _EMPTY_, fmt.Errorf("cannot create a subscription for a consumer with a deliver group %q", dg)
  1182. } else if queue != dg {
  1183. // Here the user's queue group name does not match the one associated
  1184. // with the JS consumer.
  1185. return _EMPTY_, fmt.Errorf("cannot create a queue subscription %q for a consumer with a deliver group %q",
  1186. queue, dg)
  1187. }
  1188. }
  1189. if err := checkConfig(ccfg, userCfg); err != nil {
  1190. return _EMPTY_, err
  1191. }
  1192. return ccfg.DeliverSubject, nil
  1193. }
  1194. func checkConfig(s, u *ConsumerConfig) error {
  1195. makeErr := func(fieldName string, usrVal, srvVal any) error {
  1196. return fmt.Errorf("configuration requests %s to be %v, but consumer's value is %v", fieldName, usrVal, srvVal)
  1197. }
  1198. if u.Durable != _EMPTY_ && u.Durable != s.Durable {
  1199. return makeErr("durable", u.Durable, s.Durable)
  1200. }
  1201. if u.Description != _EMPTY_ && u.Description != s.Description {
  1202. return makeErr("description", u.Description, s.Description)
  1203. }
  1204. if u.DeliverPolicy != deliverPolicyNotSet && u.DeliverPolicy != s.DeliverPolicy {
  1205. return makeErr("deliver policy", u.DeliverPolicy, s.DeliverPolicy)
  1206. }
  1207. if u.OptStartSeq > 0 && u.OptStartSeq != s.OptStartSeq {
  1208. return makeErr("optional start sequence", u.OptStartSeq, s.OptStartSeq)
  1209. }
  1210. if u.OptStartTime != nil && !u.OptStartTime.IsZero() && !(*u.OptStartTime).Equal(*s.OptStartTime) {
  1211. return makeErr("optional start time", u.OptStartTime, s.OptStartTime)
  1212. }
  1213. if u.AckPolicy != ackPolicyNotSet && u.AckPolicy != s.AckPolicy {
  1214. return makeErr("ack policy", u.AckPolicy, s.AckPolicy)
  1215. }
  1216. if u.AckWait > 0 && u.AckWait != s.AckWait {
  1217. return makeErr("ack wait", u.AckWait, s.AckWait)
  1218. }
  1219. if u.MaxDeliver > 0 && u.MaxDeliver != s.MaxDeliver {
  1220. return makeErr("max deliver", u.MaxDeliver, s.MaxDeliver)
  1221. }
  1222. if u.ReplayPolicy != replayPolicyNotSet && u.ReplayPolicy != s.ReplayPolicy {
  1223. return makeErr("replay policy", u.ReplayPolicy, s.ReplayPolicy)
  1224. }
  1225. if u.RateLimit > 0 && u.RateLimit != s.RateLimit {
  1226. return makeErr("rate limit", u.RateLimit, s.RateLimit)
  1227. }
  1228. if u.SampleFrequency != _EMPTY_ && u.SampleFrequency != s.SampleFrequency {
  1229. return makeErr("sample frequency", u.SampleFrequency, s.SampleFrequency)
  1230. }
  1231. if u.MaxWaiting > 0 && u.MaxWaiting != s.MaxWaiting {
  1232. return makeErr("max waiting", u.MaxWaiting, s.MaxWaiting)
  1233. }
  1234. if u.MaxAckPending > 0 && u.MaxAckPending != s.MaxAckPending {
  1235. return makeErr("max ack pending", u.MaxAckPending, s.MaxAckPending)
  1236. }
  1237. // For flow control, we want to fail if the user explicit wanted it, but
  1238. // it is not set in the existing consumer. If it is not asked by the user,
  1239. // the library still handles it and so no reason to fail.
  1240. if u.FlowControl && !s.FlowControl {
  1241. return makeErr("flow control", u.FlowControl, s.FlowControl)
  1242. }
  1243. if u.Heartbeat > 0 && u.Heartbeat != s.Heartbeat {
  1244. return makeErr("heartbeat", u.Heartbeat, s.Heartbeat)
  1245. }
  1246. if u.Replicas > 0 && u.Replicas != s.Replicas {
  1247. return makeErr("replicas", u.Replicas, s.Replicas)
  1248. }
  1249. if u.MemoryStorage && !s.MemoryStorage {
  1250. return makeErr("memory storage", u.MemoryStorage, s.MemoryStorage)
  1251. }
  1252. return nil
  1253. }
  1254. func (js *js) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync, isPullMode bool, opts []SubOpt) (*Subscription, error) {
  1255. cfg := ConsumerConfig{
  1256. DeliverPolicy: deliverPolicyNotSet,
  1257. AckPolicy: ackPolicyNotSet,
  1258. ReplayPolicy: replayPolicyNotSet,
  1259. }
  1260. o := subOpts{cfg: &cfg}
  1261. if len(opts) > 0 {
  1262. for _, opt := range opts {
  1263. if opt == nil {
  1264. continue
  1265. }
  1266. if err := opt.configureSubscribe(&o); err != nil {
  1267. return nil, err
  1268. }
  1269. }
  1270. }
  1271. // If no stream name is specified, the subject cannot be empty.
  1272. if subj == _EMPTY_ && o.stream == _EMPTY_ {
  1273. return nil, fmt.Errorf("nats: subject required")
  1274. }
  1275. // Note that these may change based on the consumer info response we may get.
  1276. hasHeartbeats := o.cfg.Heartbeat > 0
  1277. hasFC := o.cfg.FlowControl
  1278. // Some checks for pull subscribers
  1279. if isPullMode {
  1280. // No deliver subject should be provided
  1281. if o.cfg.DeliverSubject != _EMPTY_ {
  1282. return nil, ErrPullSubscribeToPushConsumer
  1283. }
  1284. }
  1285. // Some check/setting specific to queue subs
  1286. if queue != _EMPTY_ {
  1287. // Queue subscriber cannot have HB or FC (since messages will be randomly dispatched
  1288. // to members). We may in the future have a separate NATS subscription that all members
  1289. // would subscribe to and server would send on.
  1290. if o.cfg.Heartbeat > 0 || o.cfg.FlowControl {
  1291. // Not making this a public ErrXXX in case we allow in the future.
  1292. return nil, fmt.Errorf("nats: queue subscription doesn't support idle heartbeat nor flow control")
  1293. }
  1294. // If this is a queue subscription and no consumer nor durable name was specified,
  1295. // then we will use the queue name as a durable name.
  1296. if o.consumer == _EMPTY_ && o.cfg.Durable == _EMPTY_ {
  1297. if err := checkConsumerName(queue); err != nil {
  1298. return nil, err
  1299. }
  1300. o.cfg.Durable = queue
  1301. }
  1302. }
  1303. var (
  1304. err error
  1305. shouldCreate bool
  1306. info *ConsumerInfo
  1307. deliver string
  1308. stream = o.stream
  1309. consumer = o.consumer
  1310. isDurable = o.cfg.Durable != _EMPTY_
  1311. consumerBound = o.bound
  1312. ctx = o.ctx
  1313. skipCInfo = o.skipCInfo
  1314. notFoundErr bool
  1315. lookupErr bool
  1316. nc = js.nc
  1317. nms string
  1318. hbi time.Duration
  1319. ccreq *createConsumerRequest // In case we need to hold onto it for ordered consumers.
  1320. maxap int
  1321. )
  1322. // Do some quick checks here for ordered consumers. We do these here instead of spread out
  1323. // in the individual SubOpts.
  1324. if o.ordered {
  1325. // Make sure we are not durable.
  1326. if isDurable {
  1327. return nil, fmt.Errorf("nats: durable can not be set for an ordered consumer")
  1328. }
  1329. // Check ack policy.
  1330. if o.cfg.AckPolicy != ackPolicyNotSet {
  1331. return nil, fmt.Errorf("nats: ack policy can not be set for an ordered consumer")
  1332. }
  1333. // Check max deliver.
  1334. if o.cfg.MaxDeliver != 1 && o.cfg.MaxDeliver != 0 {
  1335. return nil, fmt.Errorf("nats: max deliver can not be set for an ordered consumer")
  1336. }
  1337. // No deliver subject, we pick our own.
  1338. if o.cfg.DeliverSubject != _EMPTY_ {
  1339. return nil, fmt.Errorf("nats: deliver subject can not be set for an ordered consumer")
  1340. }
  1341. // Queue groups not allowed.
  1342. if queue != _EMPTY_ {
  1343. return nil, fmt.Errorf("nats: queues not be set for an ordered consumer")
  1344. }
  1345. // Check for bound consumers.
  1346. if consumer != _EMPTY_ {
  1347. return nil, fmt.Errorf("nats: can not bind existing consumer for an ordered consumer")
  1348. }
  1349. // Check for pull mode.
  1350. if isPullMode {
  1351. return nil, fmt.Errorf("nats: can not use pull mode for an ordered consumer")
  1352. }
  1353. // Setup how we need it to be here.
  1354. o.cfg.FlowControl = true
  1355. o.cfg.AckPolicy = AckNonePolicy
  1356. o.cfg.MaxDeliver = 1
  1357. o.cfg.AckWait = 22 * time.Hour // Just set to something known, not utilized.
  1358. // Force R1 and MemoryStorage for these.
  1359. o.cfg.Replicas = 1
  1360. o.cfg.MemoryStorage = true
  1361. if !hasHeartbeats {
  1362. o.cfg.Heartbeat = orderedHeartbeatsInterval
  1363. }
  1364. hasFC, hasHeartbeats = true, true
  1365. o.mack = true // To avoid auto-ack wrapping call below.
  1366. hbi = o.cfg.Heartbeat
  1367. }
  1368. // In case a consumer has not been set explicitly, then the
  1369. // durable name will be used as the consumer name.
  1370. if consumer == _EMPTY_ {
  1371. consumer = o.cfg.Durable
  1372. }
  1373. // Find the stream mapped to the subject if not bound to a stream already.
  1374. if stream == _EMPTY_ {
  1375. stream, err = js.StreamNameBySubject(subj)
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. }
  1380. // With an explicit durable name, we can lookup the consumer first
  1381. // to which it should be attaching to.
  1382. // If SkipConsumerLookup was used, do not call consumer info.
  1383. if consumer != _EMPTY_ && !o.skipCInfo {
  1384. info, err = js.ConsumerInfo(stream, consumer)
  1385. notFoundErr = errors.Is(err, ErrConsumerNotFound)
  1386. lookupErr = err == ErrJetStreamNotEnabled || err == ErrTimeout || err == context.DeadlineExceeded
  1387. }
  1388. switch {
  1389. case info != nil:
  1390. deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue)
  1391. if err != nil {
  1392. return nil, err
  1393. }
  1394. icfg := &info.Config
  1395. hasFC, hbi = icfg.FlowControl, icfg.Heartbeat
  1396. hasHeartbeats = hbi > 0
  1397. maxap = icfg.MaxAckPending
  1398. case (err != nil && !notFoundErr) || (notFoundErr && consumerBound):
  1399. // If the consumer is being bound and we got an error on pull subscribe then allow the error.
  1400. if !(isPullMode && lookupErr && consumerBound) {
  1401. return nil, err
  1402. }
  1403. case skipCInfo:
  1404. // When skipping consumer info, need to rely on the manually passed sub options
  1405. // to match the expected behavior from the subscription.
  1406. hasFC, hbi = o.cfg.FlowControl, o.cfg.Heartbeat
  1407. hasHeartbeats = hbi > 0
  1408. maxap = o.cfg.MaxAckPending
  1409. deliver = o.cfg.DeliverSubject
  1410. if consumerBound {
  1411. break
  1412. }
  1413. // When not bound to a consumer already, proceed to create.
  1414. fallthrough
  1415. default:
  1416. // Attempt to create consumer if not found nor using Bind.
  1417. shouldCreate = true
  1418. if o.cfg.DeliverSubject != _EMPTY_ {
  1419. deliver = o.cfg.DeliverSubject
  1420. } else if !isPullMode {
  1421. deliver = nc.NewInbox()
  1422. cfg.DeliverSubject = deliver
  1423. }
  1424. // Do filtering always, server will clear as needed.
  1425. cfg.FilterSubject = subj
  1426. // Pass the queue to the consumer config
  1427. if queue != _EMPTY_ {
  1428. cfg.DeliverGroup = queue
  1429. }
  1430. // If not set, default to deliver all
  1431. if cfg.DeliverPolicy == deliverPolicyNotSet {
  1432. cfg.DeliverPolicy = DeliverAllPolicy
  1433. }
  1434. // If not set, default to ack explicit.
  1435. if cfg.AckPolicy == ackPolicyNotSet {
  1436. cfg.AckPolicy = AckExplicitPolicy
  1437. }
  1438. // If not set, default to instant
  1439. if cfg.ReplayPolicy == replayPolicyNotSet {
  1440. cfg.ReplayPolicy = ReplayInstantPolicy
  1441. }
  1442. // If we have acks at all and the MaxAckPending is not set go ahead
  1443. // and set to the internal max for channel based consumers
  1444. if cfg.MaxAckPending == 0 && ch != nil && cfg.AckPolicy != AckNonePolicy {
  1445. cfg.MaxAckPending = cap(ch)
  1446. }
  1447. // Create request here.
  1448. ccreq = &createConsumerRequest{
  1449. Stream: stream,
  1450. Config: &cfg,
  1451. }
  1452. hbi = cfg.Heartbeat
  1453. }
  1454. if isPullMode {
  1455. nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, consumer)
  1456. deliver = nc.NewInbox()
  1457. // for pull consumers, create a wildcard subscription to differentiate pull requests
  1458. deliver += ".*"
  1459. }
  1460. // In case this has a context, then create a child context that
  1461. // is possible to cancel via unsubscribe / drain.
  1462. var cancel func()
  1463. if ctx != nil {
  1464. ctx, cancel = context.WithCancel(ctx)
  1465. }
  1466. jsi := &jsSub{
  1467. js: js,
  1468. stream: stream,
  1469. consumer: consumer,
  1470. deliver: deliver,
  1471. hbi: hbi,
  1472. ordered: o.ordered,
  1473. ccreq: ccreq,
  1474. dseq: 1,
  1475. pull: isPullMode,
  1476. nms: nms,
  1477. psubj: subj,
  1478. cancel: cancel,
  1479. ackNone: o.cfg.AckPolicy == AckNonePolicy,
  1480. }
  1481. // Auto acknowledge unless manual ack is set or policy is set to AckNonePolicy
  1482. if cb != nil && !o.mack && o.cfg.AckPolicy != AckNonePolicy {
  1483. ocb := cb
  1484. cb = func(m *Msg) { ocb(m); m.Ack() }
  1485. }
  1486. sub, err := nc.subscribe(deliver, queue, cb, ch, isSync, jsi)
  1487. if err != nil {
  1488. return nil, err
  1489. }
  1490. // If we fail and we had the sub we need to cleanup, but can't just do a straight Unsubscribe or Drain.
  1491. // We need to clear the jsi so we do not remove any durables etc.
  1492. cleanUpSub := func() {
  1493. if sub != nil {
  1494. sub.mu.Lock()
  1495. sub.jsi = nil
  1496. sub.mu.Unlock()
  1497. sub.Unsubscribe()
  1498. }
  1499. }
  1500. // If we are creating or updating let's process that request.
  1501. consName := o.cfg.Name
  1502. if shouldCreate {
  1503. if cfg.Durable != "" {
  1504. consName = cfg.Durable
  1505. } else if consName == "" {
  1506. consName = getHash(nuid.Next())
  1507. }
  1508. info, err := js.upsertConsumer(stream, consName, ccreq.Config)
  1509. if err != nil {
  1510. var apiErr *APIError
  1511. if ok := errors.As(err, &apiErr); !ok {
  1512. cleanUpSub()
  1513. return nil, err
  1514. }
  1515. if consumer == _EMPTY_ ||
  1516. (apiErr.ErrorCode != JSErrCodeConsumerAlreadyExists && apiErr.ErrorCode != JSErrCodeConsumerNameExists) {
  1517. cleanUpSub()
  1518. if errors.Is(apiErr, ErrStreamNotFound) {
  1519. return nil, ErrStreamNotFound
  1520. }
  1521. return nil, err
  1522. }
  1523. // We will not be using this sub here if we were push based.
  1524. if !isPullMode {
  1525. cleanUpSub()
  1526. }
  1527. info, err = js.ConsumerInfo(stream, consumer)
  1528. if err != nil {
  1529. return nil, err
  1530. }
  1531. deliver, err = processConsInfo(info, o.cfg, isPullMode, subj, queue)
  1532. if err != nil {
  1533. return nil, err
  1534. }
  1535. if !isPullMode {
  1536. // We can't reuse the channel, so if one was passed, we need to create a new one.
  1537. if isSync {
  1538. ch = make(chan *Msg, cap(ch))
  1539. } else if ch != nil {
  1540. // User provided (ChanSubscription), simply try to drain it.
  1541. for done := false; !done; {
  1542. select {
  1543. case <-ch:
  1544. default:
  1545. done = true
  1546. }
  1547. }
  1548. }
  1549. jsi.deliver = deliver
  1550. jsi.hbi = info.Config.Heartbeat
  1551. // Recreate the subscription here.
  1552. sub, err = nc.subscribe(jsi.deliver, queue, cb, ch, isSync, jsi)
  1553. if err != nil {
  1554. return nil, err
  1555. }
  1556. hasFC = info.Config.FlowControl
  1557. hasHeartbeats = info.Config.Heartbeat > 0
  1558. }
  1559. } else {
  1560. // Since the library created the JS consumer, it will delete it on Unsubscribe()/Drain()
  1561. sub.mu.Lock()
  1562. sub.jsi.dc = true
  1563. sub.jsi.pending = info.NumPending + info.Delivered.Consumer
  1564. // If this is an ephemeral, we did not have a consumer name, we get it from the info
  1565. // after the AddConsumer returns.
  1566. if consumer == _EMPTY_ {
  1567. sub.jsi.consumer = info.Name
  1568. if isPullMode {
  1569. sub.jsi.nms = fmt.Sprintf(js.apiSubj(apiRequestNextT), stream, info.Name)
  1570. }
  1571. }
  1572. sub.mu.Unlock()
  1573. }
  1574. // Capture max ack pending from the info response here which covers both
  1575. // success and failure followed by consumer lookup.
  1576. maxap = info.Config.MaxAckPending
  1577. }
  1578. // If maxap is greater than the default sub's pending limit, use that.
  1579. if maxap > DefaultSubPendingMsgsLimit {
  1580. // For bytes limit, use the min of maxp*1MB or DefaultSubPendingBytesLimit
  1581. bl := maxap * 1024 * 1024
  1582. if bl < DefaultSubPendingBytesLimit {
  1583. bl = DefaultSubPendingBytesLimit
  1584. }
  1585. sub.SetPendingLimits(maxap, bl)
  1586. }
  1587. // Do heartbeats last if needed.
  1588. if hasHeartbeats {
  1589. sub.scheduleHeartbeatCheck()
  1590. }
  1591. // For ChanSubscriptions, if we know that there is flow control, we will
  1592. // start a go routine that evaluates the number of delivered messages
  1593. // and process flow control.
  1594. if sub.Type() == ChanSubscription && hasFC {
  1595. sub.chanSubcheckForFlowControlResponse()
  1596. }
  1597. // Wait for context to get canceled if there is one.
  1598. if ctx != nil {
  1599. go func() {
  1600. <-ctx.Done()
  1601. sub.Unsubscribe()
  1602. }()
  1603. }
  1604. return sub, nil
  1605. }
  1606. // InitialConsumerPending returns the number of messages pending to be
  1607. // delivered to the consumer when the subscription was created.
  1608. func (sub *Subscription) InitialConsumerPending() (uint64, error) {
  1609. sub.mu.Lock()
  1610. defer sub.mu.Unlock()
  1611. if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ {
  1612. return 0, fmt.Errorf("%w: not a JetStream subscription", ErrTypeSubscription)
  1613. }
  1614. return sub.jsi.pending, nil
  1615. }
  1616. // This long-lived routine is used per ChanSubscription to check
  1617. // on the number of delivered messages and check for flow control response.
  1618. func (sub *Subscription) chanSubcheckForFlowControlResponse() {
  1619. sub.mu.Lock()
  1620. // We don't use defer since if we need to send an RC reply, we need
  1621. // to do it outside the sub's lock. So doing explicit unlock...
  1622. if sub.closed {
  1623. sub.mu.Unlock()
  1624. return
  1625. }
  1626. var fcReply string
  1627. var nc *Conn
  1628. jsi := sub.jsi
  1629. if jsi.csfct == nil {
  1630. jsi.csfct = time.AfterFunc(chanSubFCCheckInterval, sub.chanSubcheckForFlowControlResponse)
  1631. } else {
  1632. fcReply = sub.checkForFlowControlResponse()
  1633. nc = sub.conn
  1634. // Do the reset here under the lock, it's ok...
  1635. jsi.csfct.Reset(chanSubFCCheckInterval)
  1636. }
  1637. sub.mu.Unlock()
  1638. // This call will return an error (which we don't care here)
  1639. // if nc is nil or fcReply is empty.
  1640. nc.Publish(fcReply, nil)
  1641. }
  1642. // ErrConsumerSequenceMismatch represents an error from a consumer
  1643. // that received a Heartbeat including sequence different to the
  1644. // one expected from the view of the client.
  1645. type ErrConsumerSequenceMismatch struct {
  1646. // StreamResumeSequence is the stream sequence from where the consumer
  1647. // should resume consuming from the stream.
  1648. StreamResumeSequence uint64
  1649. // ConsumerSequence is the sequence of the consumer that is behind.
  1650. ConsumerSequence uint64
  1651. // LastConsumerSequence is the sequence of the consumer when the heartbeat
  1652. // was received.
  1653. LastConsumerSequence uint64
  1654. }
  1655. func (ecs *ErrConsumerSequenceMismatch) Error() string {
  1656. return fmt.Sprintf("nats: sequence mismatch for consumer at sequence %d (%d sequences behind), should restart consumer from stream sequence %d",
  1657. ecs.ConsumerSequence,
  1658. ecs.LastConsumerSequence-ecs.ConsumerSequence,
  1659. ecs.StreamResumeSequence,
  1660. )
  1661. }
  1662. // isJSControlMessage will return true if this is an empty control status message
  1663. // and indicate what type of control message it is, say jsCtrlHB or jsCtrlFC
  1664. func isJSControlMessage(msg *Msg) (bool, int) {
  1665. if len(msg.Data) > 0 || msg.Header.Get(statusHdr) != controlMsg {
  1666. return false, 0
  1667. }
  1668. val := msg.Header.Get(descrHdr)
  1669. if strings.HasPrefix(val, "Idle") {
  1670. return true, jsCtrlHB
  1671. }
  1672. if strings.HasPrefix(val, "Flow") {
  1673. return true, jsCtrlFC
  1674. }
  1675. return true, 0
  1676. }
  1677. // Keeps track of the incoming message's reply subject so that the consumer's
  1678. // state (deliver sequence, etc..) can be checked against heartbeats.
  1679. // We will also bump the incoming data message sequence that is used in FC cases.
  1680. // Runs under the subscription lock
  1681. func (sub *Subscription) trackSequences(reply string) {
  1682. // For flow control, keep track of incoming message sequence.
  1683. sub.jsi.fciseq++
  1684. sub.jsi.cmeta = reply
  1685. }
  1686. // Check to make sure messages are arriving in order.
  1687. // Returns true if the sub had to be replaced. Will cause upper layers to return.
  1688. // The caller has verified that sub.jsi != nil and that this is not a control message.
  1689. // Lock should be held.
  1690. func (sub *Subscription) checkOrderedMsgs(m *Msg) bool {
  1691. // Ignore msgs with no reply like HBs and flow control, they are handled elsewhere.
  1692. if m.Reply == _EMPTY_ {
  1693. return false
  1694. }
  1695. // Normal message here.
  1696. tokens, err := parser.GetMetadataFields(m.Reply)
  1697. if err != nil {
  1698. return false
  1699. }
  1700. sseq, dseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos]), parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos])
  1701. jsi := sub.jsi
  1702. if dseq != jsi.dseq {
  1703. sub.resetOrderedConsumer(jsi.sseq + 1)
  1704. return true
  1705. }
  1706. // Update our tracking here.
  1707. jsi.dseq, jsi.sseq = dseq+1, sseq
  1708. return false
  1709. }
  1710. // Update and replace sid.
  1711. // Lock should be held on entry but will be unlocked to prevent lock inversion.
  1712. func (sub *Subscription) applyNewSID() (osid int64) {
  1713. nc := sub.conn
  1714. sub.mu.Unlock()
  1715. nc.subsMu.Lock()
  1716. osid = sub.sid
  1717. delete(nc.subs, osid)
  1718. // Place new one.
  1719. nc.ssid++
  1720. nsid := nc.ssid
  1721. nc.subs[nsid] = sub
  1722. nc.subsMu.Unlock()
  1723. sub.mu.Lock()
  1724. sub.sid = nsid
  1725. return osid
  1726. }
  1727. // We are here if we have detected a gap with an ordered consumer.
  1728. // We will create a new consumer and rewire the low level subscription.
  1729. // Lock should be held.
  1730. func (sub *Subscription) resetOrderedConsumer(sseq uint64) {
  1731. nc := sub.conn
  1732. if sub.jsi == nil || nc == nil || sub.closed {
  1733. return
  1734. }
  1735. var maxStr string
  1736. // If there was an AUTO_UNSUB done, we need to adjust the new value
  1737. // to send after the SUB for the new sid.
  1738. if sub.max > 0 {
  1739. if sub.jsi.fciseq < sub.max {
  1740. adjustedMax := sub.max - sub.jsi.fciseq
  1741. maxStr = strconv.Itoa(int(adjustedMax))
  1742. } else {
  1743. // We are already at the max, so we should just unsub the
  1744. // existing sub and be done
  1745. go func(sid int64) {
  1746. nc.mu.Lock()
  1747. nc.bw.appendString(fmt.Sprintf(unsubProto, sid, _EMPTY_))
  1748. nc.kickFlusher()
  1749. nc.mu.Unlock()
  1750. }(sub.sid)
  1751. return
  1752. }
  1753. }
  1754. // Quick unsubscribe. Since we know this is a simple push subscriber we do in place.
  1755. osid := sub.applyNewSID()
  1756. // Grab new inbox.
  1757. newDeliver := nc.NewInbox()
  1758. sub.Subject = newDeliver
  1759. // Snapshot the new sid under sub lock.
  1760. nsid := sub.sid
  1761. // We are still in the low level readLoop for the connection so we need
  1762. // to spin a go routine to try to create the new consumer.
  1763. go func() {
  1764. // Unsubscribe and subscribe with new inbox and sid.
  1765. // Remap a new low level sub into this sub since its client accessible.
  1766. // This is done here in this go routine to prevent lock inversion.
  1767. nc.mu.Lock()
  1768. nc.bw.appendString(fmt.Sprintf(unsubProto, osid, _EMPTY_))
  1769. nc.bw.appendString(fmt.Sprintf(subProto, newDeliver, _EMPTY_, nsid))
  1770. if maxStr != _EMPTY_ {
  1771. nc.bw.appendString(fmt.Sprintf(unsubProto, nsid, maxStr))
  1772. }
  1773. nc.kickFlusher()
  1774. nc.mu.Unlock()
  1775. pushErr := func(err error) {
  1776. nc.handleConsumerSequenceMismatch(sub, fmt.Errorf("%w: recreating ordered consumer", err))
  1777. nc.unsubscribe(sub, 0, true)
  1778. }
  1779. sub.mu.Lock()
  1780. jsi := sub.jsi
  1781. // Reset some items in jsi.
  1782. jsi.dseq = 1
  1783. jsi.cmeta = _EMPTY_
  1784. jsi.fcr, jsi.fcd = _EMPTY_, 0
  1785. jsi.deliver = newDeliver
  1786. // Reset consumer request for starting policy.
  1787. cfg := jsi.ccreq.Config
  1788. cfg.DeliverSubject = newDeliver
  1789. cfg.DeliverPolicy = DeliverByStartSequencePolicy
  1790. cfg.OptStartSeq = sseq
  1791. // In case the consumer was created with a start time, we need to clear it
  1792. // since we are now using a start sequence.
  1793. cfg.OptStartTime = nil
  1794. js := jsi.js
  1795. sub.mu.Unlock()
  1796. consName := nuid.Next()
  1797. cinfo, err := js.upsertConsumer(jsi.stream, consName, cfg)
  1798. if err != nil {
  1799. var apiErr *APIError
  1800. if errors.Is(err, ErrJetStreamNotEnabled) || errors.Is(err, ErrTimeout) || errors.Is(err, context.DeadlineExceeded) {
  1801. // if creating consumer failed, retry
  1802. return
  1803. } else if errors.As(err, &apiErr) && apiErr.ErrorCode == JSErrCodeInsufficientResourcesErr {
  1804. // retry for insufficient resources, as it may mean that client is connected to a running
  1805. // server in cluster while the server hosting R1 JetStream resources is restarting
  1806. return
  1807. }
  1808. pushErr(err)
  1809. return
  1810. }
  1811. sub.mu.Lock()
  1812. jsi.consumer = cinfo.Name
  1813. sub.mu.Unlock()
  1814. }()
  1815. }
  1816. // For jetstream subscriptions, returns the number of delivered messages.
  1817. // For ChanSubscription, this value is computed based on the known number
  1818. // of messages added to the channel minus the current size of that channel.
  1819. // Lock held on entry
  1820. func (sub *Subscription) getJSDelivered() uint64 {
  1821. if sub.typ == ChanSubscription {
  1822. return sub.jsi.fciseq - uint64(len(sub.mch))
  1823. }
  1824. return sub.delivered
  1825. }
  1826. // checkForFlowControlResponse will check to see if we should send a flow control response
  1827. // based on the subscription current delivered index and the target.
  1828. // Runs under subscription lock
  1829. func (sub *Subscription) checkForFlowControlResponse() string {
  1830. // Caller has verified that there is a sub.jsi and fc
  1831. jsi := sub.jsi
  1832. jsi.active = true
  1833. if sub.getJSDelivered() >= jsi.fcd {
  1834. fcr := jsi.fcr
  1835. jsi.fcr, jsi.fcd = _EMPTY_, 0
  1836. return fcr
  1837. }
  1838. return _EMPTY_
  1839. }
  1840. // Record an inbound flow control message.
  1841. // Runs under subscription lock
  1842. func (sub *Subscription) scheduleFlowControlResponse(reply string) {
  1843. sub.jsi.fcr, sub.jsi.fcd = reply, sub.jsi.fciseq
  1844. }
  1845. // Checks for activity from our consumer.
  1846. // If we do not think we are active send an async error.
  1847. func (sub *Subscription) activityCheck() {
  1848. sub.mu.Lock()
  1849. jsi := sub.jsi
  1850. if jsi == nil || sub.closed {
  1851. sub.mu.Unlock()
  1852. return
  1853. }
  1854. active := jsi.active
  1855. jsi.hbc.Reset(jsi.hbi * hbcThresh)
  1856. jsi.active = false
  1857. nc := sub.conn
  1858. sub.mu.Unlock()
  1859. if !active {
  1860. if !jsi.ordered || nc.Status() != CONNECTED {
  1861. nc.mu.Lock()
  1862. if errCB := nc.Opts.AsyncErrorCB; errCB != nil {
  1863. nc.ach.push(func() { errCB(nc, sub, ErrConsumerNotActive) })
  1864. }
  1865. nc.mu.Unlock()
  1866. return
  1867. }
  1868. sub.mu.Lock()
  1869. sub.resetOrderedConsumer(jsi.sseq + 1)
  1870. sub.mu.Unlock()
  1871. }
  1872. }
  1873. // scheduleHeartbeatCheck sets up the timer check to make sure we are active
  1874. // or receiving idle heartbeats..
  1875. func (sub *Subscription) scheduleHeartbeatCheck() {
  1876. sub.mu.Lock()
  1877. defer sub.mu.Unlock()
  1878. jsi := sub.jsi
  1879. if jsi == nil {
  1880. return
  1881. }
  1882. if jsi.hbc == nil {
  1883. jsi.hbc = time.AfterFunc(jsi.hbi*hbcThresh, sub.activityCheck)
  1884. } else {
  1885. jsi.hbc.Reset(jsi.hbi * hbcThresh)
  1886. }
  1887. }
  1888. // handleConsumerSequenceMismatch will send an async error that can be used to restart a push based consumer.
  1889. func (nc *Conn) handleConsumerSequenceMismatch(sub *Subscription, err error) {
  1890. nc.mu.Lock()
  1891. errCB := nc.Opts.AsyncErrorCB
  1892. if errCB != nil {
  1893. nc.ach.push(func() { errCB(nc, sub, err) })
  1894. }
  1895. nc.mu.Unlock()
  1896. }
  1897. // checkForSequenceMismatch will make sure we have not missed any messages since last seen.
  1898. func (nc *Conn) checkForSequenceMismatch(msg *Msg, s *Subscription, jsi *jsSub) {
  1899. // Process heartbeat received, get latest control metadata if present.
  1900. s.mu.Lock()
  1901. ctrl, ordered := jsi.cmeta, jsi.ordered
  1902. jsi.active = true
  1903. s.mu.Unlock()
  1904. if ctrl == _EMPTY_ {
  1905. return
  1906. }
  1907. tokens, err := parser.GetMetadataFields(ctrl)
  1908. if err != nil {
  1909. return
  1910. }
  1911. // Consumer sequence.
  1912. var ldseq string
  1913. dseq := tokens[parser.AckConsumerSeqTokenPos]
  1914. hdr := msg.Header[lastConsumerSeqHdr]
  1915. if len(hdr) == 1 {
  1916. ldseq = hdr[0]
  1917. }
  1918. // Detect consumer sequence mismatch and whether
  1919. // should restart the consumer.
  1920. if ldseq != dseq {
  1921. // Dispatch async error including details such as
  1922. // from where the consumer could be restarted.
  1923. sseq := parser.ParseNum(tokens[parser.AckStreamSeqTokenPos])
  1924. if ordered {
  1925. s.mu.Lock()
  1926. s.resetOrderedConsumer(jsi.sseq + 1)
  1927. s.mu.Unlock()
  1928. } else {
  1929. ecs := &ErrConsumerSequenceMismatch{
  1930. StreamResumeSequence: uint64(sseq),
  1931. ConsumerSequence: parser.ParseNum(dseq),
  1932. LastConsumerSequence: parser.ParseNum(ldseq),
  1933. }
  1934. nc.handleConsumerSequenceMismatch(s, ecs)
  1935. }
  1936. }
  1937. }
  1938. type streamRequest struct {
  1939. Subject string `json:"subject,omitempty"`
  1940. }
  1941. type streamNamesResponse struct {
  1942. apiResponse
  1943. apiPaged
  1944. Streams []string `json:"streams"`
  1945. }
  1946. type subOpts struct {
  1947. // For attaching.
  1948. stream, consumer string
  1949. // For creating or updating.
  1950. cfg *ConsumerConfig
  1951. // For binding a subscription to a consumer without creating it.
  1952. bound bool
  1953. // For manual ack
  1954. mack bool
  1955. // For an ordered consumer.
  1956. ordered bool
  1957. ctx context.Context
  1958. // To disable calling ConsumerInfo
  1959. skipCInfo bool
  1960. }
  1961. // SkipConsumerLookup will omit looking up consumer when [Bind], [Durable]
  1962. // or [ConsumerName] are provided.
  1963. //
  1964. // NOTE: This setting may cause an existing consumer to be overwritten. Also,
  1965. // because consumer lookup is skipped, all consumer options like AckPolicy,
  1966. // DeliverSubject etc. need to be provided even if consumer already exists.
  1967. func SkipConsumerLookup() SubOpt {
  1968. return subOptFn(func(opts *subOpts) error {
  1969. opts.skipCInfo = true
  1970. return nil
  1971. })
  1972. }
  1973. // OrderedConsumer will create a FIFO direct/ephemeral consumer for in order delivery of messages.
  1974. // There are no redeliveries and no acks, and flow control and heartbeats will be added but
  1975. // will be taken care of without additional client code.
  1976. func OrderedConsumer() SubOpt {
  1977. return subOptFn(func(opts *subOpts) error {
  1978. opts.ordered = true
  1979. return nil
  1980. })
  1981. }
  1982. // ManualAck disables auto ack functionality for async subscriptions.
  1983. func ManualAck() SubOpt {
  1984. return subOptFn(func(opts *subOpts) error {
  1985. opts.mack = true
  1986. return nil
  1987. })
  1988. }
  1989. // Description will set the description for the created consumer.
  1990. func Description(description string) SubOpt {
  1991. return subOptFn(func(opts *subOpts) error {
  1992. opts.cfg.Description = description
  1993. return nil
  1994. })
  1995. }
  1996. // Durable defines the consumer name for JetStream durable subscribers.
  1997. // This function will return ErrInvalidConsumerName if the name contains
  1998. // any dot ".".
  1999. func Durable(consumer string) SubOpt {
  2000. return subOptFn(func(opts *subOpts) error {
  2001. if opts.cfg.Durable != _EMPTY_ {
  2002. return fmt.Errorf("nats: option Durable set more than once")
  2003. }
  2004. if opts.consumer != _EMPTY_ && opts.consumer != consumer {
  2005. return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.consumer, consumer)
  2006. }
  2007. if err := checkConsumerName(consumer); err != nil {
  2008. return err
  2009. }
  2010. opts.cfg.Durable = consumer
  2011. return nil
  2012. })
  2013. }
  2014. // DeliverAll will configure a Consumer to receive all the
  2015. // messages from a Stream.
  2016. func DeliverAll() SubOpt {
  2017. return subOptFn(func(opts *subOpts) error {
  2018. opts.cfg.DeliverPolicy = DeliverAllPolicy
  2019. return nil
  2020. })
  2021. }
  2022. // DeliverLast configures a Consumer to receive messages
  2023. // starting with the latest one.
  2024. func DeliverLast() SubOpt {
  2025. return subOptFn(func(opts *subOpts) error {
  2026. opts.cfg.DeliverPolicy = DeliverLastPolicy
  2027. return nil
  2028. })
  2029. }
  2030. // DeliverLastPerSubject configures a Consumer to receive messages
  2031. // starting with the latest one for each filtered subject.
  2032. func DeliverLastPerSubject() SubOpt {
  2033. return subOptFn(func(opts *subOpts) error {
  2034. opts.cfg.DeliverPolicy = DeliverLastPerSubjectPolicy
  2035. return nil
  2036. })
  2037. }
  2038. // DeliverNew configures a Consumer to receive messages
  2039. // published after the subscription.
  2040. func DeliverNew() SubOpt {
  2041. return subOptFn(func(opts *subOpts) error {
  2042. opts.cfg.DeliverPolicy = DeliverNewPolicy
  2043. return nil
  2044. })
  2045. }
  2046. // StartSequence configures a Consumer to receive
  2047. // messages from a start sequence.
  2048. func StartSequence(seq uint64) SubOpt {
  2049. return subOptFn(func(opts *subOpts) error {
  2050. opts.cfg.DeliverPolicy = DeliverByStartSequencePolicy
  2051. opts.cfg.OptStartSeq = seq
  2052. return nil
  2053. })
  2054. }
  2055. // StartTime configures a Consumer to receive
  2056. // messages from a start time.
  2057. func StartTime(startTime time.Time) SubOpt {
  2058. return subOptFn(func(opts *subOpts) error {
  2059. opts.cfg.DeliverPolicy = DeliverByStartTimePolicy
  2060. opts.cfg.OptStartTime = &startTime
  2061. return nil
  2062. })
  2063. }
  2064. // AckNone requires no acks for delivered messages.
  2065. func AckNone() SubOpt {
  2066. return subOptFn(func(opts *subOpts) error {
  2067. opts.cfg.AckPolicy = AckNonePolicy
  2068. return nil
  2069. })
  2070. }
  2071. // AckAll when acking a sequence number, this implicitly acks all sequences
  2072. // below this one as well.
  2073. func AckAll() SubOpt {
  2074. return subOptFn(func(opts *subOpts) error {
  2075. opts.cfg.AckPolicy = AckAllPolicy
  2076. return nil
  2077. })
  2078. }
  2079. // AckExplicit requires ack or nack for all messages.
  2080. func AckExplicit() SubOpt {
  2081. return subOptFn(func(opts *subOpts) error {
  2082. opts.cfg.AckPolicy = AckExplicitPolicy
  2083. return nil
  2084. })
  2085. }
  2086. // MaxDeliver sets the number of redeliveries for a message.
  2087. func MaxDeliver(n int) SubOpt {
  2088. return subOptFn(func(opts *subOpts) error {
  2089. opts.cfg.MaxDeliver = n
  2090. return nil
  2091. })
  2092. }
  2093. // MaxAckPending sets the number of outstanding acks that are allowed before
  2094. // message delivery is halted.
  2095. func MaxAckPending(n int) SubOpt {
  2096. return subOptFn(func(opts *subOpts) error {
  2097. opts.cfg.MaxAckPending = n
  2098. return nil
  2099. })
  2100. }
  2101. // ReplayOriginal replays the messages at the original speed.
  2102. func ReplayOriginal() SubOpt {
  2103. return subOptFn(func(opts *subOpts) error {
  2104. opts.cfg.ReplayPolicy = ReplayOriginalPolicy
  2105. return nil
  2106. })
  2107. }
  2108. // ReplayInstant replays the messages as fast as possible.
  2109. func ReplayInstant() SubOpt {
  2110. return subOptFn(func(opts *subOpts) error {
  2111. opts.cfg.ReplayPolicy = ReplayInstantPolicy
  2112. return nil
  2113. })
  2114. }
  2115. // RateLimit is the Bits per sec rate limit applied to a push consumer.
  2116. func RateLimit(n uint64) SubOpt {
  2117. return subOptFn(func(opts *subOpts) error {
  2118. opts.cfg.RateLimit = n
  2119. return nil
  2120. })
  2121. }
  2122. // BackOff is an array of time durations that represent the time to delay based on delivery count.
  2123. func BackOff(backOff []time.Duration) SubOpt {
  2124. return subOptFn(func(opts *subOpts) error {
  2125. opts.cfg.BackOff = backOff
  2126. return nil
  2127. })
  2128. }
  2129. // BindStream binds a consumer to a stream explicitly based on a name.
  2130. // When a stream name is not specified, the library uses the subscribe
  2131. // subject as a way to find the stream name. It is done by making a request
  2132. // to the server to get list of stream names that have a filter for this
  2133. // subject. If the returned list contains a single stream, then this
  2134. // stream name will be used, otherwise the `ErrNoMatchingStream` is returned.
  2135. // To avoid the stream lookup, provide the stream name with this function.
  2136. // See also `Bind()`.
  2137. func BindStream(stream string) SubOpt {
  2138. return subOptFn(func(opts *subOpts) error {
  2139. if opts.stream != _EMPTY_ && opts.stream != stream {
  2140. return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream)
  2141. }
  2142. opts.stream = stream
  2143. return nil
  2144. })
  2145. }
  2146. // Bind binds a subscription to an existing consumer from a stream without attempting to create.
  2147. // The first argument is the stream name and the second argument will be the consumer name.
  2148. func Bind(stream, consumer string) SubOpt {
  2149. return subOptFn(func(opts *subOpts) error {
  2150. if stream == _EMPTY_ {
  2151. return ErrStreamNameRequired
  2152. }
  2153. if consumer == _EMPTY_ {
  2154. return ErrConsumerNameRequired
  2155. }
  2156. // In case of pull subscribers, the durable name is a required parameter
  2157. // so check that they are not different.
  2158. if opts.cfg.Durable != _EMPTY_ && opts.cfg.Durable != consumer {
  2159. return fmt.Errorf("nats: duplicate consumer names (%s and %s)", opts.cfg.Durable, consumer)
  2160. }
  2161. if opts.stream != _EMPTY_ && opts.stream != stream {
  2162. return fmt.Errorf("nats: duplicate stream name (%s and %s)", opts.stream, stream)
  2163. }
  2164. opts.stream = stream
  2165. opts.consumer = consumer
  2166. opts.bound = true
  2167. return nil
  2168. })
  2169. }
  2170. // EnableFlowControl enables flow control for a push based consumer.
  2171. func EnableFlowControl() SubOpt {
  2172. return subOptFn(func(opts *subOpts) error {
  2173. opts.cfg.FlowControl = true
  2174. return nil
  2175. })
  2176. }
  2177. // IdleHeartbeat enables push based consumers to have idle heartbeats delivered.
  2178. // For pull consumers, idle heartbeat has to be set on each [Fetch] call.
  2179. func IdleHeartbeat(duration time.Duration) SubOpt {
  2180. return subOptFn(func(opts *subOpts) error {
  2181. opts.cfg.Heartbeat = duration
  2182. return nil
  2183. })
  2184. }
  2185. // DeliverSubject specifies the JetStream consumer deliver subject.
  2186. //
  2187. // This option is used only in situations where the consumer does not exist
  2188. // and a creation request is sent to the server. If not provided, an inbox
  2189. // will be selected.
  2190. // If a consumer exists, then the NATS subscription will be created on
  2191. // the JetStream consumer's DeliverSubject, not necessarily this subject.
  2192. func DeliverSubject(subject string) SubOpt {
  2193. return subOptFn(func(opts *subOpts) error {
  2194. opts.cfg.DeliverSubject = subject
  2195. return nil
  2196. })
  2197. }
  2198. // HeadersOnly() will instruct the consumer to only deliver headers and no payloads.
  2199. func HeadersOnly() SubOpt {
  2200. return subOptFn(func(opts *subOpts) error {
  2201. opts.cfg.HeadersOnly = true
  2202. return nil
  2203. })
  2204. }
  2205. // MaxRequestBatch sets the maximum pull consumer batch size that a Fetch()
  2206. // can request.
  2207. func MaxRequestBatch(max int) SubOpt {
  2208. return subOptFn(func(opts *subOpts) error {
  2209. opts.cfg.MaxRequestBatch = max
  2210. return nil
  2211. })
  2212. }
  2213. // MaxRequestExpires sets the maximum pull consumer request expiration that a
  2214. // Fetch() can request (using the Fetch's timeout value).
  2215. func MaxRequestExpires(max time.Duration) SubOpt {
  2216. return subOptFn(func(opts *subOpts) error {
  2217. opts.cfg.MaxRequestExpires = max
  2218. return nil
  2219. })
  2220. }
  2221. // MaxRequesMaxBytes sets the maximum pull consumer request bytes that a
  2222. // Fetch() can receive.
  2223. func MaxRequestMaxBytes(bytes int) SubOpt {
  2224. return subOptFn(func(opts *subOpts) error {
  2225. opts.cfg.MaxRequestMaxBytes = bytes
  2226. return nil
  2227. })
  2228. }
  2229. // InactiveThreshold indicates how long the server should keep a consumer
  2230. // after detecting a lack of activity. In NATS Server 2.8.4 and earlier, this
  2231. // option only applies to ephemeral consumers. In NATS Server 2.9.0 and later,
  2232. // this option applies to both ephemeral and durable consumers, allowing durable
  2233. // consumers to also be deleted automatically after the inactivity threshold has
  2234. // passed.
  2235. func InactiveThreshold(threshold time.Duration) SubOpt {
  2236. return subOptFn(func(opts *subOpts) error {
  2237. if threshold < 0 {
  2238. return fmt.Errorf("invalid InactiveThreshold value (%v), needs to be greater or equal to 0", threshold)
  2239. }
  2240. opts.cfg.InactiveThreshold = threshold
  2241. return nil
  2242. })
  2243. }
  2244. // ConsumerReplicas sets the number of replica count for a consumer.
  2245. func ConsumerReplicas(replicas int) SubOpt {
  2246. return subOptFn(func(opts *subOpts) error {
  2247. if replicas < 1 {
  2248. return fmt.Errorf("invalid ConsumerReplicas value (%v), needs to be greater than 0", replicas)
  2249. }
  2250. opts.cfg.Replicas = replicas
  2251. return nil
  2252. })
  2253. }
  2254. // ConsumerMemoryStorage sets the memory storage to true for a consumer.
  2255. func ConsumerMemoryStorage() SubOpt {
  2256. return subOptFn(func(opts *subOpts) error {
  2257. opts.cfg.MemoryStorage = true
  2258. return nil
  2259. })
  2260. }
  2261. // ConsumerName sets the name for a consumer.
  2262. func ConsumerName(name string) SubOpt {
  2263. return subOptFn(func(opts *subOpts) error {
  2264. opts.cfg.Name = name
  2265. return nil
  2266. })
  2267. }
  2268. // ConsumerFilterSubjects can be used to set multiple subject filters on the consumer.
  2269. // It has to be used in conjunction with [nats.BindStream] and
  2270. // with empty 'subject' parameter.
  2271. func ConsumerFilterSubjects(subjects ...string) SubOpt {
  2272. return subOptFn(func(opts *subOpts) error {
  2273. opts.cfg.FilterSubjects = subjects
  2274. return nil
  2275. })
  2276. }
  2277. func (sub *Subscription) ConsumerInfo() (*ConsumerInfo, error) {
  2278. sub.mu.Lock()
  2279. // TODO(dlc) - Better way to mark especially if we attach.
  2280. if sub.jsi == nil || sub.jsi.consumer == _EMPTY_ {
  2281. sub.mu.Unlock()
  2282. return nil, ErrTypeSubscription
  2283. }
  2284. // Consumer info lookup should fail if in direct mode.
  2285. js := sub.jsi.js
  2286. stream, consumer := sub.jsi.stream, sub.jsi.consumer
  2287. sub.mu.Unlock()
  2288. return js.getConsumerInfo(stream, consumer)
  2289. }
  2290. type pullOpts struct {
  2291. maxBytes int
  2292. ttl time.Duration
  2293. ctx context.Context
  2294. hb time.Duration
  2295. }
  2296. // PullOpt are the options that can be passed when pulling a batch of messages.
  2297. type PullOpt interface {
  2298. configurePull(opts *pullOpts) error
  2299. }
  2300. // PullMaxWaiting defines the max inflight pull requests.
  2301. func PullMaxWaiting(n int) SubOpt {
  2302. return subOptFn(func(opts *subOpts) error {
  2303. opts.cfg.MaxWaiting = n
  2304. return nil
  2305. })
  2306. }
  2307. type PullHeartbeat time.Duration
  2308. func (h PullHeartbeat) configurePull(opts *pullOpts) error {
  2309. if h <= 0 {
  2310. return fmt.Errorf("%w: idle heartbeat has to be greater than 0", ErrInvalidArg)
  2311. }
  2312. opts.hb = time.Duration(h)
  2313. return nil
  2314. }
  2315. // PullMaxBytes defines the max bytes allowed for a fetch request.
  2316. type PullMaxBytes int
  2317. func (n PullMaxBytes) configurePull(opts *pullOpts) error {
  2318. opts.maxBytes = int(n)
  2319. return nil
  2320. }
  2321. var (
  2322. // errNoMessages is an error that a Fetch request using no_wait can receive to signal
  2323. // that there are no more messages available.
  2324. errNoMessages = errors.New("nats: no messages")
  2325. // errRequestsPending is an error that represents a sub.Fetch requests that was using
  2326. // no_wait and expires time got discarded by the server.
  2327. errRequestsPending = errors.New("nats: requests pending")
  2328. )
  2329. // Returns if the given message is a user message or not, and if
  2330. // `checkSts` is true, returns appropriate error based on the
  2331. // content of the status (404, etc..)
  2332. func checkMsg(msg *Msg, checkSts, isNoWait bool) (usrMsg bool, err error) {
  2333. // Assume user message
  2334. usrMsg = true
  2335. // If payload or no header, consider this a user message
  2336. if len(msg.Data) > 0 || len(msg.Header) == 0 {
  2337. return
  2338. }
  2339. // Look for status header
  2340. val := msg.Header.Get(statusHdr)
  2341. // If not present, then this is considered a user message
  2342. if val == _EMPTY_ {
  2343. return
  2344. }
  2345. // At this point, this is not a user message since there is
  2346. // no payload and a "Status" header.
  2347. usrMsg = false
  2348. // If we don't care about status, we are done.
  2349. if !checkSts {
  2350. return
  2351. }
  2352. // if it's a heartbeat message, report as not user msg
  2353. if isHb, _ := isJSControlMessage(msg); isHb {
  2354. return
  2355. }
  2356. switch val {
  2357. case noResponders:
  2358. err = ErrNoResponders
  2359. case noMessagesSts:
  2360. // 404 indicates that there are no messages.
  2361. err = errNoMessages
  2362. case reqTimeoutSts:
  2363. // In case of a fetch request with no wait request and expires time,
  2364. // need to skip 408 errors and retry.
  2365. if isNoWait {
  2366. err = errRequestsPending
  2367. } else {
  2368. // Older servers may send a 408 when a request in the server was expired
  2369. // and interest is still found, which will be the case for our
  2370. // implementation. Regardless, ignore 408 errors until receiving at least
  2371. // one message when making requests without no_wait.
  2372. err = ErrTimeout
  2373. }
  2374. case jetStream409Sts:
  2375. if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "consumer deleted") {
  2376. err = ErrConsumerDeleted
  2377. break
  2378. }
  2379. if strings.Contains(strings.ToLower(msg.Header.Get(descrHdr)), "leadership change") {
  2380. err = ErrConsumerLeadershipChanged
  2381. break
  2382. }
  2383. fallthrough
  2384. default:
  2385. err = fmt.Errorf("nats: %s", msg.Header.Get(descrHdr))
  2386. }
  2387. return
  2388. }
  2389. // Fetch pulls a batch of messages from a stream for a pull consumer.
  2390. func (sub *Subscription) Fetch(batch int, opts ...PullOpt) ([]*Msg, error) {
  2391. if sub == nil {
  2392. return nil, ErrBadSubscription
  2393. }
  2394. if batch < 1 {
  2395. return nil, ErrInvalidArg
  2396. }
  2397. var o pullOpts
  2398. for _, opt := range opts {
  2399. if err := opt.configurePull(&o); err != nil {
  2400. return nil, err
  2401. }
  2402. }
  2403. if o.ctx != nil && o.ttl != 0 {
  2404. return nil, ErrContextAndTimeout
  2405. }
  2406. sub.mu.Lock()
  2407. jsi := sub.jsi
  2408. // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription,
  2409. // so check for jsi.pull boolean instead.
  2410. if jsi == nil || !jsi.pull {
  2411. sub.mu.Unlock()
  2412. return nil, ErrTypeSubscription
  2413. }
  2414. nc := sub.conn
  2415. nms := sub.jsi.nms
  2416. rply, _ := newFetchInbox(jsi.deliver)
  2417. js := sub.jsi.js
  2418. pmc := len(sub.mch) > 0
  2419. // All fetch requests have an expiration, in case of no explicit expiration
  2420. // then the default timeout of the JetStream context is used.
  2421. ttl := o.ttl
  2422. if ttl == 0 {
  2423. ttl = js.opts.wait
  2424. }
  2425. sub.mu.Unlock()
  2426. // Use the given context or setup a default one for the span
  2427. // of the pull batch request.
  2428. var (
  2429. ctx = o.ctx
  2430. err error
  2431. cancel context.CancelFunc
  2432. )
  2433. if ctx == nil {
  2434. ctx, cancel = context.WithTimeout(context.Background(), ttl)
  2435. } else if _, hasDeadline := ctx.Deadline(); !hasDeadline {
  2436. // Prevent from passing the background context which will just block
  2437. // and cannot be canceled either.
  2438. if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() {
  2439. return nil, ErrNoDeadlineContext
  2440. }
  2441. // If the context did not have a deadline, then create a new child context
  2442. // that will use the default timeout from the JS context.
  2443. ctx, cancel = context.WithTimeout(ctx, ttl)
  2444. } else {
  2445. ctx, cancel = context.WithCancel(ctx)
  2446. }
  2447. defer cancel()
  2448. // if heartbeat is set, validate it against the context timeout
  2449. if o.hb > 0 {
  2450. deadline, _ := ctx.Deadline()
  2451. if 2*o.hb >= time.Until(deadline) {
  2452. return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg)
  2453. }
  2454. }
  2455. // Check if context not done already before making the request.
  2456. select {
  2457. case <-ctx.Done():
  2458. if o.ctx != nil { // Timeout or Cancel triggered by context object option
  2459. err = ctx.Err()
  2460. } else { // Timeout triggered by timeout option
  2461. err = ErrTimeout
  2462. }
  2463. default:
  2464. }
  2465. if err != nil {
  2466. return nil, err
  2467. }
  2468. var (
  2469. msgs = make([]*Msg, 0, batch)
  2470. msg *Msg
  2471. )
  2472. for pmc && len(msgs) < batch {
  2473. // Check next msg with booleans that say that this is an internal call
  2474. // for a pull subscribe (so don't reject it) and don't wait if there
  2475. // are no messages.
  2476. msg, err = sub.nextMsgWithContext(ctx, true, false)
  2477. if err != nil {
  2478. if err == errNoMessages {
  2479. err = nil
  2480. }
  2481. break
  2482. }
  2483. // Check msg but just to determine if this is a user message
  2484. // or status message, however, we don't care about values of status
  2485. // messages at this point in the Fetch() call, so checkMsg can't
  2486. // return an error.
  2487. if usrMsg, _ := checkMsg(msg, false, false); usrMsg {
  2488. msgs = append(msgs, msg)
  2489. }
  2490. }
  2491. var hbTimer *time.Timer
  2492. var hbErr error
  2493. if err == nil && len(msgs) < batch {
  2494. // For batch real size of 1, it does not make sense to set no_wait in
  2495. // the request.
  2496. noWait := batch-len(msgs) > 1
  2497. var nr nextRequest
  2498. sendReq := func() error {
  2499. // The current deadline for the context will be used
  2500. // to set the expires TTL for a fetch request.
  2501. deadline, _ := ctx.Deadline()
  2502. ttl = time.Until(deadline)
  2503. // Check if context has already been canceled or expired.
  2504. select {
  2505. case <-ctx.Done():
  2506. return ctx.Err()
  2507. default:
  2508. }
  2509. // Make our request expiration a bit shorter than the current timeout.
  2510. expires := ttl
  2511. if ttl >= 20*time.Millisecond {
  2512. expires = ttl - 10*time.Millisecond
  2513. }
  2514. nr.Batch = batch - len(msgs)
  2515. nr.Expires = expires
  2516. nr.NoWait = noWait
  2517. nr.MaxBytes = o.maxBytes
  2518. if 2*o.hb < expires {
  2519. nr.Heartbeat = o.hb
  2520. } else {
  2521. nr.Heartbeat = 0
  2522. }
  2523. req, _ := json.Marshal(nr)
  2524. if err := nc.PublishRequest(nms, rply, req); err != nil {
  2525. return err
  2526. }
  2527. if o.hb > 0 {
  2528. if hbTimer == nil {
  2529. hbTimer = time.AfterFunc(2*o.hb, func() {
  2530. hbErr = ErrNoHeartbeat
  2531. cancel()
  2532. })
  2533. } else {
  2534. hbTimer.Reset(2 * o.hb)
  2535. }
  2536. }
  2537. return nil
  2538. }
  2539. err = sendReq()
  2540. for err == nil && len(msgs) < batch {
  2541. // Ask for next message and wait if there are no messages
  2542. msg, err = sub.nextMsgWithContext(ctx, true, true)
  2543. if err == nil {
  2544. if hbTimer != nil {
  2545. hbTimer.Reset(2 * o.hb)
  2546. }
  2547. var usrMsg bool
  2548. usrMsg, err = checkMsg(msg, true, noWait)
  2549. if err == nil && usrMsg {
  2550. msgs = append(msgs, msg)
  2551. } else if noWait && (err == errNoMessages || err == errRequestsPending) && len(msgs) == 0 {
  2552. // If we have a 404/408 for our "no_wait" request and have
  2553. // not collected any message, then resend request to
  2554. // wait this time.
  2555. noWait = false
  2556. err = sendReq()
  2557. } else if err == ErrTimeout && len(msgs) == 0 {
  2558. // If we get a 408, we will bail if we already collected some
  2559. // messages, otherwise ignore and go back calling nextMsg.
  2560. err = nil
  2561. }
  2562. }
  2563. }
  2564. if hbTimer != nil {
  2565. hbTimer.Stop()
  2566. }
  2567. }
  2568. // If there is at least a message added to msgs, then need to return OK and no error
  2569. if err != nil && len(msgs) == 0 {
  2570. if hbErr != nil {
  2571. return nil, hbErr
  2572. }
  2573. return nil, o.checkCtxErr(err)
  2574. }
  2575. return msgs, nil
  2576. }
  2577. // newFetchInbox returns subject used as reply subject when sending pull requests
  2578. // as well as request ID. For non-wildcard subject, request ID is empty and
  2579. // passed subject is not transformed
  2580. func newFetchInbox(subj string) (string, string) {
  2581. if !strings.HasSuffix(subj, ".*") {
  2582. return subj, ""
  2583. }
  2584. reqID := nuid.Next()
  2585. var sb strings.Builder
  2586. sb.WriteString(subj[:len(subj)-1])
  2587. sb.WriteString(reqID)
  2588. return sb.String(), reqID
  2589. }
  2590. func subjectMatchesReqID(subject, reqID string) bool {
  2591. subjectParts := strings.Split(subject, ".")
  2592. if len(subjectParts) < 2 {
  2593. return false
  2594. }
  2595. return subjectParts[len(subjectParts)-1] == reqID
  2596. }
  2597. // MessageBatch provides methods to retrieve messages consumed using [Subscribe.FetchBatch].
  2598. type MessageBatch interface {
  2599. // Messages returns a channel on which messages will be published.
  2600. Messages() <-chan *Msg
  2601. // Error returns an error encountered when fetching messages.
  2602. Error() error
  2603. // Done signals end of execution.
  2604. Done() <-chan struct{}
  2605. }
  2606. type messageBatch struct {
  2607. msgs chan *Msg
  2608. err error
  2609. done chan struct{}
  2610. }
  2611. func (mb *messageBatch) Messages() <-chan *Msg {
  2612. return mb.msgs
  2613. }
  2614. func (mb *messageBatch) Error() error {
  2615. return mb.err
  2616. }
  2617. func (mb *messageBatch) Done() <-chan struct{} {
  2618. return mb.done
  2619. }
  2620. // FetchBatch pulls a batch of messages from a stream for a pull consumer.
  2621. // Unlike [Subscription.Fetch], it is non blocking and returns [MessageBatch],
  2622. // allowing to retrieve incoming messages from a channel.
  2623. // The returned channel is always closed after all messages for a batch have been
  2624. // delivered by the server - it is safe to iterate over it using range.
  2625. //
  2626. // To avoid using default JetStream timeout as fetch expiry time, use [nats.MaxWait]
  2627. // or [nats.Context] (with deadline set).
  2628. //
  2629. // This method will not return error in case of pull request expiry (even if there are no messages).
  2630. // Any other error encountered when receiving messages will cause FetchBatch to stop receiving new messages.
  2631. func (sub *Subscription) FetchBatch(batch int, opts ...PullOpt) (MessageBatch, error) {
  2632. if sub == nil {
  2633. return nil, ErrBadSubscription
  2634. }
  2635. if batch < 1 {
  2636. return nil, ErrInvalidArg
  2637. }
  2638. var o pullOpts
  2639. for _, opt := range opts {
  2640. if err := opt.configurePull(&o); err != nil {
  2641. return nil, err
  2642. }
  2643. }
  2644. if o.ctx != nil && o.ttl != 0 {
  2645. return nil, ErrContextAndTimeout
  2646. }
  2647. sub.mu.Lock()
  2648. jsi := sub.jsi
  2649. // Reject if this is not a pull subscription. Note that sub.typ is SyncSubscription,
  2650. // so check for jsi.pull boolean instead.
  2651. if jsi == nil || !jsi.pull {
  2652. sub.mu.Unlock()
  2653. return nil, ErrTypeSubscription
  2654. }
  2655. nc := sub.conn
  2656. nms := sub.jsi.nms
  2657. rply, reqID := newFetchInbox(sub.jsi.deliver)
  2658. js := sub.jsi.js
  2659. pmc := len(sub.mch) > 0
  2660. // All fetch requests have an expiration, in case of no explicit expiration
  2661. // then the default timeout of the JetStream context is used.
  2662. ttl := o.ttl
  2663. if ttl == 0 {
  2664. ttl = js.opts.wait
  2665. }
  2666. sub.mu.Unlock()
  2667. // Use the given context or setup a default one for the span
  2668. // of the pull batch request.
  2669. var (
  2670. ctx = o.ctx
  2671. cancel context.CancelFunc
  2672. cancelContext = true
  2673. )
  2674. if ctx == nil {
  2675. ctx, cancel = context.WithTimeout(context.Background(), ttl)
  2676. } else if _, hasDeadline := ctx.Deadline(); !hasDeadline {
  2677. // Prevent from passing the background context which will just block
  2678. // and cannot be canceled either.
  2679. if octx, ok := ctx.(ContextOpt); ok && octx.Context == context.Background() {
  2680. return nil, ErrNoDeadlineContext
  2681. }
  2682. // If the context did not have a deadline, then create a new child context
  2683. // that will use the default timeout from the JS context.
  2684. ctx, cancel = context.WithTimeout(ctx, ttl)
  2685. } else {
  2686. ctx, cancel = context.WithCancel(ctx)
  2687. }
  2688. defer func() {
  2689. // only cancel the context here if we are sure the fetching goroutine has not been started yet
  2690. if cancelContext {
  2691. cancel()
  2692. }
  2693. }()
  2694. // if heartbeat is set, validate it against the context timeout
  2695. if o.hb > 0 {
  2696. deadline, _ := ctx.Deadline()
  2697. if 2*o.hb >= time.Until(deadline) {
  2698. return nil, fmt.Errorf("%w: idle heartbeat value too large", ErrInvalidArg)
  2699. }
  2700. }
  2701. // Check if context not done already before making the request.
  2702. select {
  2703. case <-ctx.Done():
  2704. if o.ctx != nil { // Timeout or Cancel triggered by context object option
  2705. return nil, ctx.Err()
  2706. } else { // Timeout triggered by timeout option
  2707. return nil, ErrTimeout
  2708. }
  2709. default:
  2710. }
  2711. result := &messageBatch{
  2712. msgs: make(chan *Msg, batch),
  2713. done: make(chan struct{}, 1),
  2714. }
  2715. var msg *Msg
  2716. for pmc && len(result.msgs) < batch {
  2717. // Check next msg with booleans that say that this is an internal call
  2718. // for a pull subscribe (so don't reject it) and don't wait if there
  2719. // are no messages.
  2720. msg, err := sub.nextMsgWithContext(ctx, true, false)
  2721. if err != nil {
  2722. if err == errNoMessages {
  2723. err = nil
  2724. }
  2725. result.err = err
  2726. break
  2727. }
  2728. // Check msg but just to determine if this is a user message
  2729. // or status message, however, we don't care about values of status
  2730. // messages at this point in the Fetch() call, so checkMsg can't
  2731. // return an error.
  2732. if usrMsg, _ := checkMsg(msg, false, false); usrMsg {
  2733. result.msgs <- msg
  2734. }
  2735. }
  2736. if len(result.msgs) == batch || result.err != nil {
  2737. close(result.msgs)
  2738. result.done <- struct{}{}
  2739. return result, nil
  2740. }
  2741. deadline, _ := ctx.Deadline()
  2742. ttl = time.Until(deadline)
  2743. // Make our request expiration a bit shorter than the current timeout.
  2744. expires := ttl
  2745. if ttl >= 20*time.Millisecond {
  2746. expires = ttl - 10*time.Millisecond
  2747. }
  2748. requestBatch := batch - len(result.msgs)
  2749. req := nextRequest{
  2750. Expires: expires,
  2751. Batch: requestBatch,
  2752. MaxBytes: o.maxBytes,
  2753. Heartbeat: o.hb,
  2754. }
  2755. reqJSON, err := json.Marshal(req)
  2756. if err != nil {
  2757. close(result.msgs)
  2758. result.done <- struct{}{}
  2759. result.err = err
  2760. return result, nil
  2761. }
  2762. if err := nc.PublishRequest(nms, rply, reqJSON); err != nil {
  2763. if len(result.msgs) == 0 {
  2764. return nil, err
  2765. }
  2766. close(result.msgs)
  2767. result.done <- struct{}{}
  2768. result.err = err
  2769. return result, nil
  2770. }
  2771. var hbTimer *time.Timer
  2772. var hbErr error
  2773. if o.hb > 0 {
  2774. hbTimer = time.AfterFunc(2*o.hb, func() {
  2775. hbErr = ErrNoHeartbeat
  2776. cancel()
  2777. })
  2778. }
  2779. cancelContext = false
  2780. go func() {
  2781. defer cancel()
  2782. var requestMsgs int
  2783. for requestMsgs < requestBatch {
  2784. // Ask for next message and wait if there are no messages
  2785. msg, err = sub.nextMsgWithContext(ctx, true, true)
  2786. if err != nil {
  2787. break
  2788. }
  2789. if hbTimer != nil {
  2790. hbTimer.Reset(2 * o.hb)
  2791. }
  2792. var usrMsg bool
  2793. usrMsg, err = checkMsg(msg, true, false)
  2794. if err != nil {
  2795. if err == ErrTimeout {
  2796. if reqID != "" && !subjectMatchesReqID(msg.Subject, reqID) {
  2797. // ignore timeout message from server if it comes from a different pull request
  2798. continue
  2799. }
  2800. err = nil
  2801. }
  2802. break
  2803. }
  2804. if usrMsg {
  2805. result.msgs <- msg
  2806. requestMsgs++
  2807. }
  2808. }
  2809. if err != nil {
  2810. if hbErr != nil {
  2811. result.err = hbErr
  2812. } else {
  2813. result.err = o.checkCtxErr(err)
  2814. }
  2815. }
  2816. close(result.msgs)
  2817. result.done <- struct{}{}
  2818. }()
  2819. return result, nil
  2820. }
  2821. // checkCtxErr is used to determine whether ErrTimeout should be returned in case of context timeout
  2822. func (o *pullOpts) checkCtxErr(err error) error {
  2823. if o.ctx == nil && err == context.DeadlineExceeded {
  2824. return ErrTimeout
  2825. }
  2826. return err
  2827. }
  2828. func (js *js) getConsumerInfo(stream, consumer string) (*ConsumerInfo, error) {
  2829. ctx, cancel := context.WithTimeout(context.Background(), js.opts.wait)
  2830. defer cancel()
  2831. return js.getConsumerInfoContext(ctx, stream, consumer)
  2832. }
  2833. func (js *js) getConsumerInfoContext(ctx context.Context, stream, consumer string) (*ConsumerInfo, error) {
  2834. ccInfoSubj := fmt.Sprintf(apiConsumerInfoT, stream, consumer)
  2835. resp, err := js.apiRequestWithContext(ctx, js.apiSubj(ccInfoSubj), nil)
  2836. if err != nil {
  2837. if err == ErrNoResponders {
  2838. err = ErrJetStreamNotEnabled
  2839. }
  2840. return nil, err
  2841. }
  2842. var info consumerResponse
  2843. if err := json.Unmarshal(resp.Data, &info); err != nil {
  2844. return nil, err
  2845. }
  2846. if info.Error != nil {
  2847. if errors.Is(info.Error, ErrConsumerNotFound) {
  2848. return nil, ErrConsumerNotFound
  2849. }
  2850. if errors.Is(info.Error, ErrStreamNotFound) {
  2851. return nil, ErrStreamNotFound
  2852. }
  2853. return nil, info.Error
  2854. }
  2855. if info.Error == nil && info.ConsumerInfo == nil {
  2856. return nil, ErrConsumerNotFound
  2857. }
  2858. return info.ConsumerInfo, nil
  2859. }
  2860. // a RequestWithContext with tracing via TraceCB
  2861. func (js *js) apiRequestWithContext(ctx context.Context, subj string, data []byte) (*Msg, error) {
  2862. if js.opts.shouldTrace {
  2863. ctrace := js.opts.ctrace
  2864. if ctrace.RequestSent != nil {
  2865. ctrace.RequestSent(subj, data)
  2866. }
  2867. }
  2868. resp, err := js.nc.RequestWithContext(ctx, subj, data)
  2869. if err != nil {
  2870. return nil, err
  2871. }
  2872. if js.opts.shouldTrace {
  2873. ctrace := js.opts.ctrace
  2874. if ctrace.RequestSent != nil {
  2875. ctrace.ResponseReceived(subj, resp.Data, resp.Header)
  2876. }
  2877. }
  2878. return resp, nil
  2879. }
  2880. func (m *Msg) checkReply() error {
  2881. if m == nil || m.Sub == nil {
  2882. return ErrMsgNotBound
  2883. }
  2884. if m.Reply == _EMPTY_ {
  2885. return ErrMsgNoReply
  2886. }
  2887. return nil
  2888. }
  2889. // ackReply handles all acks. Will do the right thing for pull and sync mode.
  2890. // It ensures that an ack is only sent a single time, regardless of
  2891. // how many times it is being called to avoid duplicated acks.
  2892. func (m *Msg) ackReply(ackType []byte, sync bool, opts ...AckOpt) error {
  2893. var o ackOpts
  2894. for _, opt := range opts {
  2895. if err := opt.configureAck(&o); err != nil {
  2896. return err
  2897. }
  2898. }
  2899. if err := m.checkReply(); err != nil {
  2900. return err
  2901. }
  2902. var ackNone bool
  2903. var js *js
  2904. sub := m.Sub
  2905. sub.mu.Lock()
  2906. nc := sub.conn
  2907. if jsi := sub.jsi; jsi != nil {
  2908. js = jsi.js
  2909. ackNone = jsi.ackNone
  2910. }
  2911. sub.mu.Unlock()
  2912. // Skip if already acked.
  2913. if atomic.LoadUint32(&m.ackd) == 1 {
  2914. return ErrMsgAlreadyAckd
  2915. }
  2916. if ackNone {
  2917. return ErrCantAckIfConsumerAckNone
  2918. }
  2919. usesCtx := o.ctx != nil
  2920. usesWait := o.ttl > 0
  2921. // Only allow either AckWait or Context option to set the timeout.
  2922. if usesWait && usesCtx {
  2923. return ErrContextAndTimeout
  2924. }
  2925. sync = sync || usesCtx || usesWait
  2926. ctx := o.ctx
  2927. wait := defaultRequestWait
  2928. if usesWait {
  2929. wait = o.ttl
  2930. } else if js != nil {
  2931. wait = js.opts.wait
  2932. }
  2933. var body []byte
  2934. var err error
  2935. // This will be > 0 only when called from NakWithDelay()
  2936. if o.nakDelay > 0 {
  2937. body = []byte(fmt.Sprintf("%s {\"delay\": %d}", ackType, o.nakDelay.Nanoseconds()))
  2938. } else {
  2939. body = ackType
  2940. }
  2941. if sync {
  2942. if usesCtx {
  2943. _, err = nc.RequestWithContext(ctx, m.Reply, body)
  2944. } else {
  2945. _, err = nc.Request(m.Reply, body, wait)
  2946. }
  2947. } else {
  2948. err = nc.Publish(m.Reply, body)
  2949. }
  2950. // Mark that the message has been acked unless it is ackProgress
  2951. // which can be sent many times.
  2952. if err == nil && !bytes.Equal(ackType, ackProgress) {
  2953. atomic.StoreUint32(&m.ackd, 1)
  2954. }
  2955. return err
  2956. }
  2957. // Ack acknowledges a message. This tells the server that the message was
  2958. // successfully processed and it can move on to the next message.
  2959. func (m *Msg) Ack(opts ...AckOpt) error {
  2960. return m.ackReply(ackAck, false, opts...)
  2961. }
  2962. // AckSync is the synchronous version of Ack. This indicates successful message
  2963. // processing.
  2964. func (m *Msg) AckSync(opts ...AckOpt) error {
  2965. return m.ackReply(ackAck, true, opts...)
  2966. }
  2967. // Nak negatively acknowledges a message. This tells the server to redeliver
  2968. // the message. You can configure the number of redeliveries by passing
  2969. // nats.MaxDeliver when you Subscribe. The default is infinite redeliveries.
  2970. func (m *Msg) Nak(opts ...AckOpt) error {
  2971. return m.ackReply(ackNak, false, opts...)
  2972. }
  2973. // Nak negatively acknowledges a message. This tells the server to redeliver
  2974. // the message after the give `delay` duration. You can configure the number
  2975. // of redeliveries by passing nats.MaxDeliver when you Subscribe.
  2976. // The default is infinite redeliveries.
  2977. func (m *Msg) NakWithDelay(delay time.Duration, opts ...AckOpt) error {
  2978. if delay > 0 {
  2979. opts = append(opts, nakDelay(delay))
  2980. }
  2981. return m.ackReply(ackNak, false, opts...)
  2982. }
  2983. // Term tells the server to not redeliver this message, regardless of the value
  2984. // of nats.MaxDeliver.
  2985. func (m *Msg) Term(opts ...AckOpt) error {
  2986. return m.ackReply(ackTerm, false, opts...)
  2987. }
  2988. // InProgress tells the server that this message is being worked on. It resets
  2989. // the redelivery timer on the server.
  2990. func (m *Msg) InProgress(opts ...AckOpt) error {
  2991. return m.ackReply(ackProgress, false, opts...)
  2992. }
  2993. // MsgMetadata is the JetStream metadata associated with received messages.
  2994. type MsgMetadata struct {
  2995. Sequence SequencePair
  2996. NumDelivered uint64
  2997. NumPending uint64
  2998. Timestamp time.Time
  2999. Stream string
  3000. Consumer string
  3001. Domain string
  3002. }
  3003. // Metadata retrieves the metadata from a JetStream message. This method will
  3004. // return an error for non-JetStream Msgs.
  3005. func (m *Msg) Metadata() (*MsgMetadata, error) {
  3006. if err := m.checkReply(); err != nil {
  3007. return nil, err
  3008. }
  3009. tokens, err := parser.GetMetadataFields(m.Reply)
  3010. if err != nil {
  3011. return nil, err
  3012. }
  3013. meta := &MsgMetadata{
  3014. Domain: tokens[parser.AckDomainTokenPos],
  3015. NumDelivered: parser.ParseNum(tokens[parser.AckNumDeliveredTokenPos]),
  3016. NumPending: parser.ParseNum(tokens[parser.AckNumPendingTokenPos]),
  3017. Timestamp: time.Unix(0, int64(parser.ParseNum(tokens[parser.AckTimestampSeqTokenPos]))),
  3018. Stream: tokens[parser.AckStreamTokenPos],
  3019. Consumer: tokens[parser.AckConsumerTokenPos],
  3020. }
  3021. meta.Sequence.Stream = parser.ParseNum(tokens[parser.AckStreamSeqTokenPos])
  3022. meta.Sequence.Consumer = parser.ParseNum(tokens[parser.AckConsumerSeqTokenPos])
  3023. return meta, nil
  3024. }
  3025. // AckPolicy determines how the consumer should acknowledge delivered messages.
  3026. type AckPolicy int
  3027. const (
  3028. // AckNonePolicy requires no acks for delivered messages.
  3029. AckNonePolicy AckPolicy = iota
  3030. // AckAllPolicy when acking a sequence number, this implicitly acks all
  3031. // sequences below this one as well.
  3032. AckAllPolicy
  3033. // AckExplicitPolicy requires ack or nack for all messages.
  3034. AckExplicitPolicy
  3035. // For configuration mismatch check
  3036. ackPolicyNotSet = 99
  3037. )
  3038. func jsonString(s string) string {
  3039. return "\"" + s + "\""
  3040. }
  3041. func (p *AckPolicy) UnmarshalJSON(data []byte) error {
  3042. switch string(data) {
  3043. case jsonString("none"):
  3044. *p = AckNonePolicy
  3045. case jsonString("all"):
  3046. *p = AckAllPolicy
  3047. case jsonString("explicit"):
  3048. *p = AckExplicitPolicy
  3049. default:
  3050. return fmt.Errorf("nats: can not unmarshal %q", data)
  3051. }
  3052. return nil
  3053. }
  3054. func (p AckPolicy) MarshalJSON() ([]byte, error) {
  3055. switch p {
  3056. case AckNonePolicy:
  3057. return json.Marshal("none")
  3058. case AckAllPolicy:
  3059. return json.Marshal("all")
  3060. case AckExplicitPolicy:
  3061. return json.Marshal("explicit")
  3062. default:
  3063. return nil, fmt.Errorf("nats: unknown acknowledgement policy %v", p)
  3064. }
  3065. }
  3066. func (p AckPolicy) String() string {
  3067. switch p {
  3068. case AckNonePolicy:
  3069. return "AckNone"
  3070. case AckAllPolicy:
  3071. return "AckAll"
  3072. case AckExplicitPolicy:
  3073. return "AckExplicit"
  3074. case ackPolicyNotSet:
  3075. return "Not Initialized"
  3076. default:
  3077. return "Unknown AckPolicy"
  3078. }
  3079. }
  3080. // ReplayPolicy determines how the consumer should replay messages it already has queued in the stream.
  3081. type ReplayPolicy int
  3082. const (
  3083. // ReplayInstantPolicy will replay messages as fast as possible.
  3084. ReplayInstantPolicy ReplayPolicy = iota
  3085. // ReplayOriginalPolicy will maintain the same timing as the messages were received.
  3086. ReplayOriginalPolicy
  3087. // For configuration mismatch check
  3088. replayPolicyNotSet = 99
  3089. )
  3090. func (p *ReplayPolicy) UnmarshalJSON(data []byte) error {
  3091. switch string(data) {
  3092. case jsonString("instant"):
  3093. *p = ReplayInstantPolicy
  3094. case jsonString("original"):
  3095. *p = ReplayOriginalPolicy
  3096. default:
  3097. return fmt.Errorf("nats: can not unmarshal %q", data)
  3098. }
  3099. return nil
  3100. }
  3101. func (p ReplayPolicy) MarshalJSON() ([]byte, error) {
  3102. switch p {
  3103. case ReplayOriginalPolicy:
  3104. return json.Marshal("original")
  3105. case ReplayInstantPolicy:
  3106. return json.Marshal("instant")
  3107. default:
  3108. return nil, fmt.Errorf("nats: unknown replay policy %v", p)
  3109. }
  3110. }
  3111. var (
  3112. ackAck = []byte("+ACK")
  3113. ackNak = []byte("-NAK")
  3114. ackProgress = []byte("+WPI")
  3115. ackTerm = []byte("+TERM")
  3116. )
  3117. // DeliverPolicy determines how the consumer should select the first message to deliver.
  3118. type DeliverPolicy int
  3119. const (
  3120. // DeliverAllPolicy starts delivering messages from the very beginning of a
  3121. // stream. This is the default.
  3122. DeliverAllPolicy DeliverPolicy = iota
  3123. // DeliverLastPolicy will start the consumer with the last sequence
  3124. // received.
  3125. DeliverLastPolicy
  3126. // DeliverNewPolicy will only deliver new messages that are sent after the
  3127. // consumer is created.
  3128. DeliverNewPolicy
  3129. // DeliverByStartSequencePolicy will deliver messages starting from a given
  3130. // sequence.
  3131. DeliverByStartSequencePolicy
  3132. // DeliverByStartTimePolicy will deliver messages starting from a given
  3133. // time.
  3134. DeliverByStartTimePolicy
  3135. // DeliverLastPerSubjectPolicy will start the consumer with the last message
  3136. // for all subjects received.
  3137. DeliverLastPerSubjectPolicy
  3138. // For configuration mismatch check
  3139. deliverPolicyNotSet = 99
  3140. )
  3141. func (p *DeliverPolicy) UnmarshalJSON(data []byte) error {
  3142. switch string(data) {
  3143. case jsonString("all"), jsonString("undefined"):
  3144. *p = DeliverAllPolicy
  3145. case jsonString("last"):
  3146. *p = DeliverLastPolicy
  3147. case jsonString("new"):
  3148. *p = DeliverNewPolicy
  3149. case jsonString("by_start_sequence"):
  3150. *p = DeliverByStartSequencePolicy
  3151. case jsonString("by_start_time"):
  3152. *p = DeliverByStartTimePolicy
  3153. case jsonString("last_per_subject"):
  3154. *p = DeliverLastPerSubjectPolicy
  3155. }
  3156. return nil
  3157. }
  3158. func (p DeliverPolicy) MarshalJSON() ([]byte, error) {
  3159. switch p {
  3160. case DeliverAllPolicy:
  3161. return json.Marshal("all")
  3162. case DeliverLastPolicy:
  3163. return json.Marshal("last")
  3164. case DeliverNewPolicy:
  3165. return json.Marshal("new")
  3166. case DeliverByStartSequencePolicy:
  3167. return json.Marshal("by_start_sequence")
  3168. case DeliverByStartTimePolicy:
  3169. return json.Marshal("by_start_time")
  3170. case DeliverLastPerSubjectPolicy:
  3171. return json.Marshal("last_per_subject")
  3172. default:
  3173. return nil, fmt.Errorf("nats: unknown deliver policy %v", p)
  3174. }
  3175. }
  3176. // RetentionPolicy determines how messages in a set are retained.
  3177. type RetentionPolicy int
  3178. const (
  3179. // LimitsPolicy (default) means that messages are retained until any given limit is reached.
  3180. // This could be one of MaxMsgs, MaxBytes, or MaxAge.
  3181. LimitsPolicy RetentionPolicy = iota
  3182. // InterestPolicy specifies that when all known observables have acknowledged a message it can be removed.
  3183. InterestPolicy
  3184. // WorkQueuePolicy specifies that when the first worker or subscriber acknowledges the message it can be removed.
  3185. WorkQueuePolicy
  3186. )
  3187. // DiscardPolicy determines how to proceed when limits of messages or bytes are
  3188. // reached.
  3189. type DiscardPolicy int
  3190. const (
  3191. // DiscardOld will remove older messages to return to the limits. This is
  3192. // the default.
  3193. DiscardOld DiscardPolicy = iota
  3194. //DiscardNew will fail to store new messages.
  3195. DiscardNew
  3196. )
  3197. const (
  3198. limitsPolicyString = "limits"
  3199. interestPolicyString = "interest"
  3200. workQueuePolicyString = "workqueue"
  3201. )
  3202. func (rp RetentionPolicy) String() string {
  3203. switch rp {
  3204. case LimitsPolicy:
  3205. return "Limits"
  3206. case InterestPolicy:
  3207. return "Interest"
  3208. case WorkQueuePolicy:
  3209. return "WorkQueue"
  3210. default:
  3211. return "Unknown Retention Policy"
  3212. }
  3213. }
  3214. func (rp RetentionPolicy) MarshalJSON() ([]byte, error) {
  3215. switch rp {
  3216. case LimitsPolicy:
  3217. return json.Marshal(limitsPolicyString)
  3218. case InterestPolicy:
  3219. return json.Marshal(interestPolicyString)
  3220. case WorkQueuePolicy:
  3221. return json.Marshal(workQueuePolicyString)
  3222. default:
  3223. return nil, fmt.Errorf("nats: can not marshal %v", rp)
  3224. }
  3225. }
  3226. func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error {
  3227. switch string(data) {
  3228. case jsonString(limitsPolicyString):
  3229. *rp = LimitsPolicy
  3230. case jsonString(interestPolicyString):
  3231. *rp = InterestPolicy
  3232. case jsonString(workQueuePolicyString):
  3233. *rp = WorkQueuePolicy
  3234. default:
  3235. return fmt.Errorf("nats: can not unmarshal %q", data)
  3236. }
  3237. return nil
  3238. }
  3239. func (dp DiscardPolicy) String() string {
  3240. switch dp {
  3241. case DiscardOld:
  3242. return "DiscardOld"
  3243. case DiscardNew:
  3244. return "DiscardNew"
  3245. default:
  3246. return "Unknown Discard Policy"
  3247. }
  3248. }
  3249. func (dp DiscardPolicy) MarshalJSON() ([]byte, error) {
  3250. switch dp {
  3251. case DiscardOld:
  3252. return json.Marshal("old")
  3253. case DiscardNew:
  3254. return json.Marshal("new")
  3255. default:
  3256. return nil, fmt.Errorf("nats: can not marshal %v", dp)
  3257. }
  3258. }
  3259. func (dp *DiscardPolicy) UnmarshalJSON(data []byte) error {
  3260. switch strings.ToLower(string(data)) {
  3261. case jsonString("old"):
  3262. *dp = DiscardOld
  3263. case jsonString("new"):
  3264. *dp = DiscardNew
  3265. default:
  3266. return fmt.Errorf("nats: can not unmarshal %q", data)
  3267. }
  3268. return nil
  3269. }
  3270. // StorageType determines how messages are stored for retention.
  3271. type StorageType int
  3272. const (
  3273. // FileStorage specifies on disk storage. It's the default.
  3274. FileStorage StorageType = iota
  3275. // MemoryStorage specifies in memory only.
  3276. MemoryStorage
  3277. )
  3278. const (
  3279. memoryStorageString = "memory"
  3280. fileStorageString = "file"
  3281. )
  3282. func (st StorageType) String() string {
  3283. switch st {
  3284. case MemoryStorage:
  3285. return "Memory"
  3286. case FileStorage:
  3287. return "File"
  3288. default:
  3289. return "Unknown Storage Type"
  3290. }
  3291. }
  3292. func (st StorageType) MarshalJSON() ([]byte, error) {
  3293. switch st {
  3294. case MemoryStorage:
  3295. return json.Marshal(memoryStorageString)
  3296. case FileStorage:
  3297. return json.Marshal(fileStorageString)
  3298. default:
  3299. return nil, fmt.Errorf("nats: can not marshal %v", st)
  3300. }
  3301. }
  3302. func (st *StorageType) UnmarshalJSON(data []byte) error {
  3303. switch string(data) {
  3304. case jsonString(memoryStorageString):
  3305. *st = MemoryStorage
  3306. case jsonString(fileStorageString):
  3307. *st = FileStorage
  3308. default:
  3309. return fmt.Errorf("nats: can not unmarshal %q", data)
  3310. }
  3311. return nil
  3312. }
  3313. type StoreCompression uint8
  3314. const (
  3315. NoCompression StoreCompression = iota
  3316. S2Compression
  3317. )
  3318. func (alg StoreCompression) String() string {
  3319. switch alg {
  3320. case NoCompression:
  3321. return "None"
  3322. case S2Compression:
  3323. return "S2"
  3324. default:
  3325. return "Unknown StoreCompression"
  3326. }
  3327. }
  3328. func (alg StoreCompression) MarshalJSON() ([]byte, error) {
  3329. var str string
  3330. switch alg {
  3331. case S2Compression:
  3332. str = "s2"
  3333. case NoCompression:
  3334. str = "none"
  3335. default:
  3336. return nil, fmt.Errorf("unknown compression algorithm")
  3337. }
  3338. return json.Marshal(str)
  3339. }
  3340. func (alg *StoreCompression) UnmarshalJSON(b []byte) error {
  3341. var str string
  3342. if err := json.Unmarshal(b, &str); err != nil {
  3343. return err
  3344. }
  3345. switch str {
  3346. case "s2":
  3347. *alg = S2Compression
  3348. case "none":
  3349. *alg = NoCompression
  3350. default:
  3351. return fmt.Errorf("unknown compression algorithm")
  3352. }
  3353. return nil
  3354. }
  3355. // Length of our hash used for named consumers.
  3356. const nameHashLen = 8
  3357. // Computes a hash for the given `name`.
  3358. func getHash(name string) string {
  3359. sha := sha256.New()
  3360. sha.Write([]byte(name))
  3361. b := sha.Sum(nil)
  3362. for i := 0; i < nameHashLen; i++ {
  3363. b[i] = rdigits[int(b[i]%base)]
  3364. }
  3365. return string(b[:nameHashLen])
  3366. }