nats.go 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975
  1. // Copyright 2012-2021 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. // A Go client for the NATS messaging system (https://nats.io).
  14. package nats
  15. import (
  16. "bufio"
  17. "bytes"
  18. "crypto/tls"
  19. "crypto/x509"
  20. "encoding/base64"
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "math/rand"
  27. "net"
  28. "net/http"
  29. "net/textproto"
  30. "net/url"
  31. "os"
  32. "path/filepath"
  33. "runtime"
  34. "strconv"
  35. "strings"
  36. "sync"
  37. "sync/atomic"
  38. "time"
  39. "github.com/nats-io/nats.go/util"
  40. "github.com/nats-io/nkeys"
  41. "github.com/nats-io/nuid"
  42. )
  43. // Default Constants
  44. const (
  45. Version = "1.11.0"
  46. DefaultURL = "nats://127.0.0.1:4222"
  47. DefaultPort = 4222
  48. DefaultMaxReconnect = 60
  49. DefaultReconnectWait = 2 * time.Second
  50. DefaultReconnectJitter = 100 * time.Millisecond
  51. DefaultReconnectJitterTLS = time.Second
  52. DefaultTimeout = 2 * time.Second
  53. DefaultPingInterval = 2 * time.Minute
  54. DefaultMaxPingOut = 2
  55. DefaultMaxChanLen = 64 * 1024 // 64k
  56. DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB
  57. RequestChanLen = 8
  58. DefaultDrainTimeout = 30 * time.Second
  59. LangString = "go"
  60. )
  61. const (
  62. // STALE_CONNECTION is for detection and proper handling of stale connections.
  63. STALE_CONNECTION = "stale connection"
  64. // PERMISSIONS_ERR is for when nats server subject authorization has failed.
  65. PERMISSIONS_ERR = "permissions violation"
  66. // AUTHORIZATION_ERR is for when nats server user authorization has failed.
  67. AUTHORIZATION_ERR = "authorization violation"
  68. // AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
  69. AUTHENTICATION_EXPIRED_ERR = "user authentication expired"
  70. // AUTHENTICATION_REVOKED_ERR is for when user authorization has been revoked.
  71. AUTHENTICATION_REVOKED_ERR = "user authentication revoked"
  72. // ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired.
  73. ACCOUNT_AUTHENTICATION_EXPIRED_ERR = "account authentication expired"
  74. )
  75. // Errors
  76. var (
  77. ErrConnectionClosed = errors.New("nats: connection closed")
  78. ErrConnectionDraining = errors.New("nats: connection draining")
  79. ErrDrainTimeout = errors.New("nats: draining connection timed out")
  80. ErrConnectionReconnecting = errors.New("nats: connection reconnecting")
  81. ErrSecureConnRequired = errors.New("nats: secure connection required")
  82. ErrSecureConnWanted = errors.New("nats: secure connection not available")
  83. ErrBadSubscription = errors.New("nats: invalid subscription")
  84. ErrTypeSubscription = errors.New("nats: invalid subscription type")
  85. ErrBadSubject = errors.New("nats: invalid subject")
  86. ErrBadQueueName = errors.New("nats: invalid queue name")
  87. ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped")
  88. ErrTimeout = errors.New("nats: timeout")
  89. ErrBadTimeout = errors.New("nats: timeout invalid")
  90. ErrAuthorization = errors.New("nats: authorization violation")
  91. ErrAuthExpired = errors.New("nats: authentication expired")
  92. ErrAuthRevoked = errors.New("nats: authentication revoked")
  93. ErrAccountAuthExpired = errors.New("nats: account authentication expired")
  94. ErrNoServers = errors.New("nats: no servers available for connection")
  95. ErrJsonParse = errors.New("nats: connect message, json parse error")
  96. ErrChanArg = errors.New("nats: argument needs to be a channel type")
  97. ErrMaxPayload = errors.New("nats: maximum payload exceeded")
  98. ErrMaxMessages = errors.New("nats: maximum messages delivered")
  99. ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription")
  100. ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed")
  101. ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received")
  102. ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded")
  103. ErrInvalidConnection = errors.New("nats: invalid connection")
  104. ErrInvalidMsg = errors.New("nats: invalid message or message nil")
  105. ErrInvalidArg = errors.New("nats: invalid argument")
  106. ErrInvalidContext = errors.New("nats: invalid context")
  107. ErrNoDeadlineContext = errors.New("nats: context requires a deadline")
  108. ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server")
  109. ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server")
  110. ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler")
  111. ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler")
  112. ErrNoUserCB = errors.New("nats: user callback not defined")
  113. ErrNkeyAndUser = errors.New("nats: user callback and nkey defined")
  114. ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server")
  115. ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION)
  116. ErrTokenAlreadySet = errors.New("nats: token and token handler both set")
  117. ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection")
  118. ErrMsgNoReply = errors.New("nats: message does not have a reply")
  119. ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server")
  120. ErrDisconnected = errors.New("nats: server is disconnected")
  121. ErrHeadersNotSupported = errors.New("nats: headers not supported by this server")
  122. ErrBadHeaderMsg = errors.New("nats: message could not decode headers")
  123. ErrNoResponders = errors.New("nats: no responders available for request")
  124. ErrNoContextOrTimeout = errors.New("nats: no context or timeout given")
  125. ErrPullModeNotAllowed = errors.New("nats: pull based not supported")
  126. ErrJetStreamNotEnabled = errors.New("nats: jetstream not enabled")
  127. ErrJetStreamBadPre = errors.New("nats: jetstream api prefix not valid")
  128. ErrNoStreamResponse = errors.New("nats: no response from stream")
  129. ErrNotJSMessage = errors.New("nats: not a jetstream message")
  130. ErrInvalidStreamName = errors.New("nats: invalid stream name")
  131. ErrInvalidDurableName = errors.New("nats: invalid durable name")
  132. ErrNoMatchingStream = errors.New("nats: no stream matches subject")
  133. ErrSubjectMismatch = errors.New("nats: subject does not match consumer")
  134. ErrContextAndTimeout = errors.New("nats: context and timeout can not both be set")
  135. ErrInvalidJSAck = errors.New("nats: invalid jetstream publish response")
  136. ErrMultiStreamUnsupported = errors.New("nats: multiple streams are not supported")
  137. ErrStreamNameRequired = errors.New("nats: stream name is required")
  138. ErrConsumerConfigRequired = errors.New("nats: consumer configuration is required")
  139. ErrStreamSnapshotConfigRequired = errors.New("nats: stream snapshot configuration is required")
  140. ErrDeliverSubjectRequired = errors.New("nats: deliver subject is required")
  141. )
  142. func init() {
  143. rand.Seed(time.Now().UnixNano())
  144. }
  145. // GetDefaultOptions returns default configuration options for the client.
  146. func GetDefaultOptions() Options {
  147. return Options{
  148. AllowReconnect: true,
  149. MaxReconnect: DefaultMaxReconnect,
  150. ReconnectWait: DefaultReconnectWait,
  151. ReconnectJitter: DefaultReconnectJitter,
  152. ReconnectJitterTLS: DefaultReconnectJitterTLS,
  153. Timeout: DefaultTimeout,
  154. PingInterval: DefaultPingInterval,
  155. MaxPingsOut: DefaultMaxPingOut,
  156. SubChanLen: DefaultMaxChanLen,
  157. ReconnectBufSize: DefaultReconnectBufSize,
  158. DrainTimeout: DefaultDrainTimeout,
  159. }
  160. }
  161. // DEPRECATED: Use GetDefaultOptions() instead.
  162. // DefaultOptions is not safe for use by multiple clients.
  163. // For details see #308.
  164. var DefaultOptions = GetDefaultOptions()
  165. // Status represents the state of the connection.
  166. type Status int
  167. const (
  168. DISCONNECTED = Status(iota)
  169. CONNECTED
  170. CLOSED
  171. RECONNECTING
  172. CONNECTING
  173. DRAINING_SUBS
  174. DRAINING_PUBS
  175. )
  176. // ConnHandler is used for asynchronous events such as
  177. // disconnected and closed connections.
  178. type ConnHandler func(*Conn)
  179. // ConnErrHandler is used to process asynchronous events like
  180. // disconnected connection with the error (if any).
  181. type ConnErrHandler func(*Conn, error)
  182. // ErrHandler is used to process asynchronous errors encountered
  183. // while processing inbound messages.
  184. type ErrHandler func(*Conn, *Subscription, error)
  185. // UserJWTHandler is used to fetch and return the account signed
  186. // JWT for this user.
  187. type UserJWTHandler func() (string, error)
  188. // SignatureHandler is used to sign a nonce from the server while
  189. // authenticating with nkeys. The user should sign the nonce and
  190. // return the raw signature. The client will base64 encode this to
  191. // send to the server.
  192. type SignatureHandler func([]byte) ([]byte, error)
  193. // AuthTokenHandler is used to generate a new token.
  194. type AuthTokenHandler func() string
  195. // ReconnectDelayHandler is used to get from the user the desired
  196. // delay the library should pause before attempting to reconnect
  197. // again. Note that this is invoked after the library tried the
  198. // whole list of URLs and failed to reconnect.
  199. type ReconnectDelayHandler func(attempts int) time.Duration
  200. // asyncCB is used to preserve order for async callbacks.
  201. type asyncCB struct {
  202. f func()
  203. next *asyncCB
  204. }
  205. type asyncCallbacksHandler struct {
  206. mu sync.Mutex
  207. cond *sync.Cond
  208. head *asyncCB
  209. tail *asyncCB
  210. }
  211. // Option is a function on the options for a connection.
  212. type Option func(*Options) error
  213. // CustomDialer can be used to specify any dialer, not necessarily
  214. // a *net.Dialer.
  215. type CustomDialer interface {
  216. Dial(network, address string) (net.Conn, error)
  217. }
  218. // Options can be used to create a customized connection.
  219. type Options struct {
  220. // Url represents a single NATS server url to which the client
  221. // will be connecting. If the Servers option is also set, it
  222. // then becomes the first server in the Servers array.
  223. Url string
  224. // Servers is a configured set of servers which this client
  225. // will use when attempting to connect.
  226. Servers []string
  227. // NoRandomize configures whether we will randomize the
  228. // server pool.
  229. NoRandomize bool
  230. // NoEcho configures whether the server will echo back messages
  231. // that are sent on this connection if we also have matching subscriptions.
  232. // Note this is supported on servers >= version 1.2. Proto 1 or greater.
  233. NoEcho bool
  234. // Name is an optional name label which will be sent to the server
  235. // on CONNECT to identify the client.
  236. Name string
  237. // Verbose signals the server to send an OK ack for commands
  238. // successfully processed by the server.
  239. Verbose bool
  240. // Pedantic signals the server whether it should be doing further
  241. // validation of subjects.
  242. Pedantic bool
  243. // Secure enables TLS secure connections that skip server
  244. // verification by default. NOT RECOMMENDED.
  245. Secure bool
  246. // TLSConfig is a custom TLS configuration to use for secure
  247. // transports.
  248. TLSConfig *tls.Config
  249. // AllowReconnect enables reconnection logic to be used when we
  250. // encounter a disconnect from the current server.
  251. AllowReconnect bool
  252. // MaxReconnect sets the number of reconnect attempts that will be
  253. // tried before giving up. If negative, then it will never give up
  254. // trying to reconnect.
  255. MaxReconnect int
  256. // ReconnectWait sets the time to backoff after attempting a reconnect
  257. // to a server that we were already connected to previously.
  258. ReconnectWait time.Duration
  259. // CustomReconnectDelayCB is invoked after the library tried every
  260. // URL in the server list and failed to reconnect. It passes to the
  261. // user the current number of attempts. This function returns the
  262. // amount of time the library will sleep before attempting to reconnect
  263. // again. It is strongly recommended that this value contains some
  264. // jitter to prevent all connections to attempt reconnecting at the same time.
  265. CustomReconnectDelayCB ReconnectDelayHandler
  266. // ReconnectJitter sets the upper bound for a random delay added to
  267. // ReconnectWait during a reconnect when no TLS is used.
  268. // Note that any jitter is capped with ReconnectJitterMax.
  269. ReconnectJitter time.Duration
  270. // ReconnectJitterTLS sets the upper bound for a random delay added to
  271. // ReconnectWait during a reconnect when TLS is used.
  272. // Note that any jitter is capped with ReconnectJitterMax.
  273. ReconnectJitterTLS time.Duration
  274. // Timeout sets the timeout for a Dial operation on a connection.
  275. Timeout time.Duration
  276. // DrainTimeout sets the timeout for a Drain Operation to complete.
  277. DrainTimeout time.Duration
  278. // FlusherTimeout is the maximum time to wait for write operations
  279. // to the underlying connection to complete (including the flusher loop).
  280. FlusherTimeout time.Duration
  281. // PingInterval is the period at which the client will be sending ping
  282. // commands to the server, disabled if 0 or negative.
  283. PingInterval time.Duration
  284. // MaxPingsOut is the maximum number of pending ping commands that can
  285. // be awaiting a response before raising an ErrStaleConnection error.
  286. MaxPingsOut int
  287. // ClosedCB sets the closed handler that is called when a client will
  288. // no longer be connected.
  289. ClosedCB ConnHandler
  290. // DisconnectedCB sets the disconnected handler that is called
  291. // whenever the connection is disconnected.
  292. // Will not be called if DisconnectedErrCB is set
  293. // DEPRECATED. Use DisconnectedErrCB which passes error that caused
  294. // the disconnect event.
  295. DisconnectedCB ConnHandler
  296. // DisconnectedErrCB sets the disconnected error handler that is called
  297. // whenever the connection is disconnected.
  298. // Disconnected error could be nil, for instance when user explicitly closes the connection.
  299. // DisconnectedCB will not be called if DisconnectedErrCB is set
  300. DisconnectedErrCB ConnErrHandler
  301. // ReconnectedCB sets the reconnected handler called whenever
  302. // the connection is successfully reconnected.
  303. ReconnectedCB ConnHandler
  304. // DiscoveredServersCB sets the callback that is invoked whenever a new
  305. // server has joined the cluster.
  306. DiscoveredServersCB ConnHandler
  307. // AsyncErrorCB sets the async error handler (e.g. slow consumer errors)
  308. AsyncErrorCB ErrHandler
  309. // ReconnectBufSize is the size of the backing bufio during reconnect.
  310. // Once this has been exhausted publish operations will return an error.
  311. ReconnectBufSize int
  312. // SubChanLen is the size of the buffered channel used between the socket
  313. // Go routine and the message delivery for SyncSubscriptions.
  314. // NOTE: This does not affect AsyncSubscriptions which are
  315. // dictated by PendingLimits()
  316. SubChanLen int
  317. // UserJWT sets the callback handler that will fetch a user's JWT.
  318. UserJWT UserJWTHandler
  319. // Nkey sets the public nkey that will be used to authenticate
  320. // when connecting to the server. UserJWT and Nkey are mutually exclusive
  321. // and if defined, UserJWT will take precedence.
  322. Nkey string
  323. // SignatureCB designates the function used to sign the nonce
  324. // presented from the server.
  325. SignatureCB SignatureHandler
  326. // User sets the username to be used when connecting to the server.
  327. User string
  328. // Password sets the password to be used when connecting to a server.
  329. Password string
  330. // Token sets the token to be used when connecting to a server.
  331. Token string
  332. // TokenHandler designates the function used to generate the token to be used when connecting to a server.
  333. TokenHandler AuthTokenHandler
  334. // Dialer allows a custom net.Dialer when forming connections.
  335. // DEPRECATED: should use CustomDialer instead.
  336. Dialer *net.Dialer
  337. // CustomDialer allows to specify a custom dialer (not necessarily
  338. // a *net.Dialer).
  339. CustomDialer CustomDialer
  340. // UseOldRequestStyle forces the old method of Requests that utilize
  341. // a new Inbox and a new Subscription for each request.
  342. UseOldRequestStyle bool
  343. // NoCallbacksAfterClientClose allows preventing the invocation of
  344. // callbacks after Close() is called. Client won't receive notifications
  345. // when Close is invoked by user code. Default is to invoke the callbacks.
  346. NoCallbacksAfterClientClose bool
  347. // LameDuckModeHandler sets the callback to invoke when the server notifies
  348. // the connection that it entered lame duck mode, that is, going to
  349. // gradually disconnect all its connections before shuting down. This is
  350. // often used in deployments when upgrading NATS Servers.
  351. LameDuckModeHandler ConnHandler
  352. // RetryOnFailedConnect sets the connection in reconnecting state right
  353. // away if it can't connect to a server in the initial set. The
  354. // MaxReconnect and ReconnectWait options are used for this process,
  355. // similarly to when an established connection is disconnected.
  356. // If a ReconnectHandler is set, it will be invoked when the connection
  357. // is established, and if a ClosedHandler is set, it will be invoked if
  358. // it fails to connect (after exhausting the MaxReconnect attempts).
  359. RetryOnFailedConnect bool
  360. // For websocket connections, indicates to the server that the connection
  361. // supports compression. If the server does too, then data will be compressed.
  362. Compression bool
  363. }
  364. const (
  365. // Scratch storage for assembling protocol headers
  366. scratchSize = 512
  367. // The size of the bufio reader/writer on top of the socket.
  368. defaultBufSize = 32768
  369. // The buffered size of the flush "kick" channel
  370. flushChanSize = 1
  371. // Default server pool size
  372. srvPoolSize = 4
  373. // NUID size
  374. nuidSize = 22
  375. // Default port used if none is specified in given URL(s)
  376. defaultPortString = "4222"
  377. )
  378. // A Conn represents a bare connection to a nats-server.
  379. // It can send and receive []byte payloads.
  380. // The connection is safe to use in multiple Go routines concurrently.
  381. type Conn struct {
  382. // Keep all members for which we use atomic at the beginning of the
  383. // struct and make sure they are all 64bits (or use padding if necessary).
  384. // atomic.* functions crash on 32bit machines if operand is not aligned
  385. // at 64bit. See https://github.com/golang/go/issues/599
  386. Statistics
  387. mu sync.RWMutex
  388. // Opts holds the configuration of the Conn.
  389. // Modifying the configuration of a running Conn is a race.
  390. Opts Options
  391. wg sync.WaitGroup
  392. srvPool []*srv
  393. current *srv
  394. urls map[string]struct{} // Keep track of all known URLs (used by processInfo)
  395. conn net.Conn
  396. bw *natsWriter
  397. br *natsReader
  398. fch chan struct{}
  399. info serverInfo
  400. ssid int64
  401. subsMu sync.RWMutex
  402. subs map[int64]*Subscription
  403. ach *asyncCallbacksHandler
  404. pongs []chan struct{}
  405. scratch [scratchSize]byte
  406. status Status
  407. initc bool // true if the connection is performing the initial connect
  408. err error
  409. ps *parseState
  410. ptmr *time.Timer
  411. pout int
  412. ar bool // abort reconnect
  413. rqch chan struct{}
  414. ws bool // true if a websocket connection
  415. // New style response handler
  416. respSub string // The wildcard subject
  417. respScanf string // The scanf template to extract mux token
  418. respMux *Subscription // A single response subscription
  419. respMap map[string]chan *Msg // Request map for the response msg channels
  420. respRand *rand.Rand // Used for generating suffix
  421. // JetStream Contexts last account check.
  422. jsLastCheck time.Time
  423. }
  424. type natsReader struct {
  425. r io.Reader
  426. buf []byte
  427. off int
  428. n int
  429. }
  430. type natsWriter struct {
  431. w io.Writer
  432. bufs []byte
  433. limit int
  434. pending *bytes.Buffer
  435. plimit int
  436. }
  437. // Subscription represents interest in a given subject.
  438. type Subscription struct {
  439. mu sync.Mutex
  440. sid int64
  441. // Subject that represents this subscription. This can be different
  442. // than the received subject inside a Msg if this is a wildcard.
  443. Subject string
  444. // Optional queue group name. If present, all subscriptions with the
  445. // same name will form a distributed queue, and each message will
  446. // only be processed by one member of the group.
  447. Queue string
  448. // For holding information about a JetStream consumer.
  449. jsi *jsSub
  450. delivered uint64
  451. max uint64
  452. conn *Conn
  453. mcb MsgHandler
  454. mch chan *Msg
  455. closed bool
  456. sc bool
  457. connClosed bool
  458. // Type of Subscription
  459. typ SubscriptionType
  460. // Async linked list
  461. pHead *Msg
  462. pTail *Msg
  463. pCond *sync.Cond
  464. // Pending stats, async subscriptions, high-speed etc.
  465. pMsgs int
  466. pBytes int
  467. pMsgsMax int
  468. pBytesMax int
  469. pMsgsLimit int
  470. pBytesLimit int
  471. dropped int
  472. }
  473. // Msg represents a message delivered by NATS. This structure is used
  474. // by Subscribers and PublishMsg().
  475. //
  476. // Types of Acknowledgements
  477. //
  478. // In case using JetStream, there are multiple ways to ack a Msg:
  479. //
  480. // // Acknowledgement that a message has been processed.
  481. // msg.Ack()
  482. //
  483. // // Negatively acknowledges a message.
  484. // msg.Nak()
  485. //
  486. // // Terminate a message so that it is not redelivered further.
  487. // msg.Term()
  488. //
  489. // // Signal the server that the message is being worked on and reset redelivery timer.
  490. // msg.InProgress()
  491. //
  492. type Msg struct {
  493. Subject string
  494. Reply string
  495. Header Header
  496. Data []byte
  497. Sub *Subscription
  498. next *Msg
  499. barrier *barrierInfo
  500. ackd uint32
  501. }
  502. func (m *Msg) headerBytes() ([]byte, error) {
  503. var hdr []byte
  504. if len(m.Header) == 0 {
  505. return hdr, nil
  506. }
  507. var b bytes.Buffer
  508. _, err := b.WriteString(hdrLine)
  509. if err != nil {
  510. return nil, ErrBadHeaderMsg
  511. }
  512. err = http.Header(m.Header).Write(&b)
  513. if err != nil {
  514. return nil, ErrBadHeaderMsg
  515. }
  516. _, err = b.WriteString(crlf)
  517. if err != nil {
  518. return nil, ErrBadHeaderMsg
  519. }
  520. return b.Bytes(), nil
  521. }
  522. type barrierInfo struct {
  523. refs int64
  524. f func()
  525. }
  526. // Tracks various stats received and sent on this connection,
  527. // including counts for messages and bytes.
  528. type Statistics struct {
  529. InMsgs uint64
  530. OutMsgs uint64
  531. InBytes uint64
  532. OutBytes uint64
  533. Reconnects uint64
  534. }
  535. // Tracks individual backend servers.
  536. type srv struct {
  537. url *url.URL
  538. didConnect bool
  539. reconnects int
  540. lastErr error
  541. isImplicit bool
  542. tlsName string
  543. }
  544. // The INFO block received from the server.
  545. type serverInfo struct {
  546. ID string `json:"server_id"`
  547. Name string `json:"server_name"`
  548. Proto int `json:"proto"`
  549. Host string `json:"host"`
  550. Port int `json:"port"`
  551. Headers bool `json:"headers"`
  552. AuthRequired bool `json:"auth_required,omitempty"`
  553. TLSRequired bool `json:"tls_required,omitempty"`
  554. TLSAvailable bool `json:"tls_available,omitempty"`
  555. MaxPayload int64 `json:"max_payload"`
  556. CID uint64 `json:"client_id,omitempty"`
  557. ClientIP string `json:"client_ip,omitempty"`
  558. Nonce string `json:"nonce,omitempty"`
  559. Cluster string `json:"cluster,omitempty"`
  560. ConnectURLs []string `json:"connect_urls,omitempty"`
  561. LameDuckMode bool `json:"ldm,omitempty"`
  562. }
  563. const (
  564. // clientProtoZero is the original client protocol from 2009.
  565. // http://nats.io/documentation/internals/nats-protocol/
  566. /* clientProtoZero */ _ = iota
  567. // clientProtoInfo signals a client can receive more then the original INFO block.
  568. // This can be used to update clients on other cluster members, etc.
  569. clientProtoInfo
  570. )
  571. type connectInfo struct {
  572. Verbose bool `json:"verbose"`
  573. Pedantic bool `json:"pedantic"`
  574. UserJWT string `json:"jwt,omitempty"`
  575. Nkey string `json:"nkey,omitempty"`
  576. Signature string `json:"sig,omitempty"`
  577. User string `json:"user,omitempty"`
  578. Pass string `json:"pass,omitempty"`
  579. Token string `json:"auth_token,omitempty"`
  580. TLS bool `json:"tls_required"`
  581. Name string `json:"name"`
  582. Lang string `json:"lang"`
  583. Version string `json:"version"`
  584. Protocol int `json:"protocol"`
  585. Echo bool `json:"echo"`
  586. Headers bool `json:"headers"`
  587. NoResponders bool `json:"no_responders"`
  588. }
  589. // MsgHandler is a callback function that processes messages delivered to
  590. // asynchronous subscribers.
  591. type MsgHandler func(msg *Msg)
  592. // Connect will attempt to connect to the NATS system.
  593. // The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
  594. // Comma separated arrays are also supported, e.g. urlA, urlB.
  595. // Options start with the defaults but can be overridden.
  596. // To connect to a NATS Server's websocket port, use the `ws` or `wss` scheme, such as
  597. // `ws://localhost:8080`. Note that websocket schemes cannot be mixed with others (nats/tls).
  598. func Connect(url string, options ...Option) (*Conn, error) {
  599. opts := GetDefaultOptions()
  600. opts.Servers = processUrlString(url)
  601. for _, opt := range options {
  602. if opt != nil {
  603. if err := opt(&opts); err != nil {
  604. return nil, err
  605. }
  606. }
  607. }
  608. return opts.Connect()
  609. }
  610. // Options that can be passed to Connect.
  611. // Name is an Option to set the client name.
  612. func Name(name string) Option {
  613. return func(o *Options) error {
  614. o.Name = name
  615. return nil
  616. }
  617. }
  618. // Secure is an Option to enable TLS secure connections that skip server verification by default.
  619. // Pass a TLS Configuration for proper TLS.
  620. // NOTE: This should NOT be used in a production setting.
  621. func Secure(tls ...*tls.Config) Option {
  622. return func(o *Options) error {
  623. o.Secure = true
  624. // Use of variadic just simplifies testing scenarios. We only take the first one.
  625. if len(tls) > 1 {
  626. return ErrMultipleTLSConfigs
  627. }
  628. if len(tls) == 1 {
  629. o.TLSConfig = tls[0]
  630. }
  631. return nil
  632. }
  633. }
  634. // RootCAs is a helper option to provide the RootCAs pool from a list of filenames.
  635. // If Secure is not already set this will set it as well.
  636. func RootCAs(file ...string) Option {
  637. return func(o *Options) error {
  638. pool := x509.NewCertPool()
  639. for _, f := range file {
  640. rootPEM, err := ioutil.ReadFile(f)
  641. if err != nil || rootPEM == nil {
  642. return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err)
  643. }
  644. ok := pool.AppendCertsFromPEM(rootPEM)
  645. if !ok {
  646. return fmt.Errorf("nats: failed to parse root certificate from %q", f)
  647. }
  648. }
  649. if o.TLSConfig == nil {
  650. o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  651. }
  652. o.TLSConfig.RootCAs = pool
  653. o.Secure = true
  654. return nil
  655. }
  656. }
  657. // ClientCert is a helper option to provide the client certificate from a file.
  658. // If Secure is not already set this will set it as well.
  659. func ClientCert(certFile, keyFile string) Option {
  660. return func(o *Options) error {
  661. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  662. if err != nil {
  663. return fmt.Errorf("nats: error loading client certificate: %v", err)
  664. }
  665. cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
  666. if err != nil {
  667. return fmt.Errorf("nats: error parsing client certificate: %v", err)
  668. }
  669. if o.TLSConfig == nil {
  670. o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  671. }
  672. o.TLSConfig.Certificates = []tls.Certificate{cert}
  673. o.Secure = true
  674. return nil
  675. }
  676. }
  677. // NoReconnect is an Option to turn off reconnect behavior.
  678. func NoReconnect() Option {
  679. return func(o *Options) error {
  680. o.AllowReconnect = false
  681. return nil
  682. }
  683. }
  684. // DontRandomize is an Option to turn off randomizing the server pool.
  685. func DontRandomize() Option {
  686. return func(o *Options) error {
  687. o.NoRandomize = true
  688. return nil
  689. }
  690. }
  691. // NoEcho is an Option to turn off messages echoing back from a server.
  692. // Note this is supported on servers >= version 1.2. Proto 1 or greater.
  693. func NoEcho() Option {
  694. return func(o *Options) error {
  695. o.NoEcho = true
  696. return nil
  697. }
  698. }
  699. // ReconnectWait is an Option to set the wait time between reconnect attempts.
  700. func ReconnectWait(t time.Duration) Option {
  701. return func(o *Options) error {
  702. o.ReconnectWait = t
  703. return nil
  704. }
  705. }
  706. // MaxReconnects is an Option to set the maximum number of reconnect attempts.
  707. func MaxReconnects(max int) Option {
  708. return func(o *Options) error {
  709. o.MaxReconnect = max
  710. return nil
  711. }
  712. }
  713. // ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait.
  714. func ReconnectJitter(jitter, jitterForTLS time.Duration) Option {
  715. return func(o *Options) error {
  716. o.ReconnectJitter = jitter
  717. o.ReconnectJitterTLS = jitterForTLS
  718. return nil
  719. }
  720. }
  721. // CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option.
  722. // See CustomReconnectDelayCB Option for more details.
  723. func CustomReconnectDelay(cb ReconnectDelayHandler) Option {
  724. return func(o *Options) error {
  725. o.CustomReconnectDelayCB = cb
  726. return nil
  727. }
  728. }
  729. // PingInterval is an Option to set the period for client ping commands.
  730. func PingInterval(t time.Duration) Option {
  731. return func(o *Options) error {
  732. o.PingInterval = t
  733. return nil
  734. }
  735. }
  736. // MaxPingsOutstanding is an Option to set the maximum number of ping requests
  737. // that can go un-answered by the server before closing the connection.
  738. func MaxPingsOutstanding(max int) Option {
  739. return func(o *Options) error {
  740. o.MaxPingsOut = max
  741. return nil
  742. }
  743. }
  744. // ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
  745. func ReconnectBufSize(size int) Option {
  746. return func(o *Options) error {
  747. o.ReconnectBufSize = size
  748. return nil
  749. }
  750. }
  751. // Timeout is an Option to set the timeout for Dial on a connection.
  752. func Timeout(t time.Duration) Option {
  753. return func(o *Options) error {
  754. o.Timeout = t
  755. return nil
  756. }
  757. }
  758. // FlusherTimeout is an Option to set the write (and flush) timeout on a connection.
  759. func FlusherTimeout(t time.Duration) Option {
  760. return func(o *Options) error {
  761. o.FlusherTimeout = t
  762. return nil
  763. }
  764. }
  765. // DrainTimeout is an Option to set the timeout for draining a connection.
  766. func DrainTimeout(t time.Duration) Option {
  767. return func(o *Options) error {
  768. o.DrainTimeout = t
  769. return nil
  770. }
  771. }
  772. // DisconnectErrHandler is an Option to set the disconnected error handler.
  773. func DisconnectErrHandler(cb ConnErrHandler) Option {
  774. return func(o *Options) error {
  775. o.DisconnectedErrCB = cb
  776. return nil
  777. }
  778. }
  779. // DisconnectHandler is an Option to set the disconnected handler.
  780. // DEPRECATED: Use DisconnectErrHandler.
  781. func DisconnectHandler(cb ConnHandler) Option {
  782. return func(o *Options) error {
  783. o.DisconnectedCB = cb
  784. return nil
  785. }
  786. }
  787. // ReconnectHandler is an Option to set the reconnected handler.
  788. func ReconnectHandler(cb ConnHandler) Option {
  789. return func(o *Options) error {
  790. o.ReconnectedCB = cb
  791. return nil
  792. }
  793. }
  794. // ClosedHandler is an Option to set the closed handler.
  795. func ClosedHandler(cb ConnHandler) Option {
  796. return func(o *Options) error {
  797. o.ClosedCB = cb
  798. return nil
  799. }
  800. }
  801. // DiscoveredServersHandler is an Option to set the new servers handler.
  802. func DiscoveredServersHandler(cb ConnHandler) Option {
  803. return func(o *Options) error {
  804. o.DiscoveredServersCB = cb
  805. return nil
  806. }
  807. }
  808. // ErrorHandler is an Option to set the async error handler.
  809. func ErrorHandler(cb ErrHandler) Option {
  810. return func(o *Options) error {
  811. o.AsyncErrorCB = cb
  812. return nil
  813. }
  814. }
  815. // UserInfo is an Option to set the username and password to
  816. // use when not included directly in the URLs.
  817. func UserInfo(user, password string) Option {
  818. return func(o *Options) error {
  819. o.User = user
  820. o.Password = password
  821. return nil
  822. }
  823. }
  824. // Token is an Option to set the token to use
  825. // when a token is not included directly in the URLs
  826. // and when a token handler is not provided.
  827. func Token(token string) Option {
  828. return func(o *Options) error {
  829. if o.TokenHandler != nil {
  830. return ErrTokenAlreadySet
  831. }
  832. o.Token = token
  833. return nil
  834. }
  835. }
  836. // TokenHandler is an Option to set the token handler to use
  837. // when a token is not included directly in the URLs
  838. // and when a token is not set.
  839. func TokenHandler(cb AuthTokenHandler) Option {
  840. return func(o *Options) error {
  841. if o.Token != "" {
  842. return ErrTokenAlreadySet
  843. }
  844. o.TokenHandler = cb
  845. return nil
  846. }
  847. }
  848. // UserCredentials is a convenience function that takes a filename
  849. // for a user's JWT and a filename for the user's private Nkey seed.
  850. func UserCredentials(userOrChainedFile string, seedFiles ...string) Option {
  851. userCB := func() (string, error) {
  852. return userFromFile(userOrChainedFile)
  853. }
  854. var keyFile string
  855. if len(seedFiles) > 0 {
  856. keyFile = seedFiles[0]
  857. } else {
  858. keyFile = userOrChainedFile
  859. }
  860. sigCB := func(nonce []byte) ([]byte, error) {
  861. return sigHandler(nonce, keyFile)
  862. }
  863. return UserJWT(userCB, sigCB)
  864. }
  865. // UserJWT will set the callbacks to retrieve the user's JWT and
  866. // the signature callback to sign the server nonce. This an the Nkey
  867. // option are mutually exclusive.
  868. func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option {
  869. return func(o *Options) error {
  870. if userCB == nil {
  871. return ErrNoUserCB
  872. }
  873. if sigCB == nil {
  874. return ErrUserButNoSigCB
  875. }
  876. o.UserJWT = userCB
  877. o.SignatureCB = sigCB
  878. return nil
  879. }
  880. }
  881. // Nkey will set the public Nkey and the signature callback to
  882. // sign the server nonce.
  883. func Nkey(pubKey string, sigCB SignatureHandler) Option {
  884. return func(o *Options) error {
  885. o.Nkey = pubKey
  886. o.SignatureCB = sigCB
  887. if pubKey != "" && sigCB == nil {
  888. return ErrNkeyButNoSigCB
  889. }
  890. return nil
  891. }
  892. }
  893. // SyncQueueLen will set the maximum queue len for the internal
  894. // channel used for SubscribeSync().
  895. func SyncQueueLen(max int) Option {
  896. return func(o *Options) error {
  897. o.SubChanLen = max
  898. return nil
  899. }
  900. }
  901. // Dialer is an Option to set the dialer which will be used when
  902. // attempting to establish a connection.
  903. // DEPRECATED: Should use CustomDialer instead.
  904. func Dialer(dialer *net.Dialer) Option {
  905. return func(o *Options) error {
  906. o.Dialer = dialer
  907. return nil
  908. }
  909. }
  910. // SetCustomDialer is an Option to set a custom dialer which will be
  911. // used when attempting to establish a connection. If both Dialer
  912. // and CustomDialer are specified, CustomDialer takes precedence.
  913. func SetCustomDialer(dialer CustomDialer) Option {
  914. return func(o *Options) error {
  915. o.CustomDialer = dialer
  916. return nil
  917. }
  918. }
  919. // UseOldRequestStyle is an Option to force usage of the old Request style.
  920. func UseOldRequestStyle() Option {
  921. return func(o *Options) error {
  922. o.UseOldRequestStyle = true
  923. return nil
  924. }
  925. }
  926. // NoCallbacksAfterClientClose is an Option to disable callbacks when user code
  927. // calls Close(). If close is initiated by any other condition, callbacks
  928. // if any will be invoked.
  929. func NoCallbacksAfterClientClose() Option {
  930. return func(o *Options) error {
  931. o.NoCallbacksAfterClientClose = true
  932. return nil
  933. }
  934. }
  935. // LameDuckModeHandler sets the callback to invoke when the server notifies
  936. // the connection that it entered lame duck mode, that is, going to
  937. // gradually disconnect all its connections before shuting down. This is
  938. // often used in deployments when upgrading NATS Servers.
  939. func LameDuckModeHandler(cb ConnHandler) Option {
  940. return func(o *Options) error {
  941. o.LameDuckModeHandler = cb
  942. return nil
  943. }
  944. }
  945. // RetryOnFailedConnect sets the connection in reconnecting state right away
  946. // if it can't connect to a server in the initial set.
  947. // See RetryOnFailedConnect option for more details.
  948. func RetryOnFailedConnect(retry bool) Option {
  949. return func(o *Options) error {
  950. o.RetryOnFailedConnect = retry
  951. return nil
  952. }
  953. }
  954. // Compression is an Option to indicate if this connection supports
  955. // compression. Currently only supported for Websocket connections.
  956. func Compression(enabled bool) Option {
  957. return func(o *Options) error {
  958. o.Compression = enabled
  959. return nil
  960. }
  961. }
  962. // Handler processing
  963. // SetDisconnectHandler will set the disconnect event handler.
  964. // DEPRECATED: Use SetDisconnectErrHandler
  965. func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
  966. if nc == nil {
  967. return
  968. }
  969. nc.mu.Lock()
  970. defer nc.mu.Unlock()
  971. nc.Opts.DisconnectedCB = dcb
  972. }
  973. // SetDisconnectErrHandler will set the disconnect event handler.
  974. func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler) {
  975. if nc == nil {
  976. return
  977. }
  978. nc.mu.Lock()
  979. defer nc.mu.Unlock()
  980. nc.Opts.DisconnectedErrCB = dcb
  981. }
  982. // SetReconnectHandler will set the reconnect event handler.
  983. func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
  984. if nc == nil {
  985. return
  986. }
  987. nc.mu.Lock()
  988. defer nc.mu.Unlock()
  989. nc.Opts.ReconnectedCB = rcb
  990. }
  991. // SetDiscoveredServersHandler will set the discovered servers handler.
  992. func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
  993. if nc == nil {
  994. return
  995. }
  996. nc.mu.Lock()
  997. defer nc.mu.Unlock()
  998. nc.Opts.DiscoveredServersCB = dscb
  999. }
  1000. // SetClosedHandler will set the reconnect event handler.
  1001. func (nc *Conn) SetClosedHandler(cb ConnHandler) {
  1002. if nc == nil {
  1003. return
  1004. }
  1005. nc.mu.Lock()
  1006. defer nc.mu.Unlock()
  1007. nc.Opts.ClosedCB = cb
  1008. }
  1009. // SetErrorHandler will set the async error handler.
  1010. func (nc *Conn) SetErrorHandler(cb ErrHandler) {
  1011. if nc == nil {
  1012. return
  1013. }
  1014. nc.mu.Lock()
  1015. defer nc.mu.Unlock()
  1016. nc.Opts.AsyncErrorCB = cb
  1017. }
  1018. // Process the url string argument to Connect.
  1019. // Return an array of urls, even if only one.
  1020. func processUrlString(url string) []string {
  1021. urls := strings.Split(url, ",")
  1022. for i, s := range urls {
  1023. urls[i] = strings.TrimSpace(s)
  1024. }
  1025. return urls
  1026. }
  1027. // Connect will attempt to connect to a NATS server with multiple options.
  1028. func (o Options) Connect() (*Conn, error) {
  1029. nc := &Conn{Opts: o}
  1030. // Some default options processing.
  1031. if nc.Opts.MaxPingsOut == 0 {
  1032. nc.Opts.MaxPingsOut = DefaultMaxPingOut
  1033. }
  1034. // Allow old default for channel length to work correctly.
  1035. if nc.Opts.SubChanLen == 0 {
  1036. nc.Opts.SubChanLen = DefaultMaxChanLen
  1037. }
  1038. // Default ReconnectBufSize
  1039. if nc.Opts.ReconnectBufSize == 0 {
  1040. nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
  1041. }
  1042. // Ensure that Timeout is not 0
  1043. if nc.Opts.Timeout == 0 {
  1044. nc.Opts.Timeout = DefaultTimeout
  1045. }
  1046. // Check first for user jwt callback being defined and nkey.
  1047. if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
  1048. return nil, ErrNkeyAndUser
  1049. }
  1050. // Check if we have an nkey but no signature callback defined.
  1051. if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
  1052. return nil, ErrNkeyButNoSigCB
  1053. }
  1054. // Allow custom Dialer for connecting using DialTimeout by default
  1055. if nc.Opts.Dialer == nil {
  1056. nc.Opts.Dialer = &net.Dialer{
  1057. Timeout: nc.Opts.Timeout,
  1058. }
  1059. }
  1060. if err := nc.setupServerPool(); err != nil {
  1061. return nil, err
  1062. }
  1063. // Create the async callback handler.
  1064. nc.ach = &asyncCallbacksHandler{}
  1065. nc.ach.cond = sync.NewCond(&nc.ach.mu)
  1066. // Set a default error handler that will print to stderr.
  1067. if nc.Opts.AsyncErrorCB == nil {
  1068. nc.Opts.AsyncErrorCB = defaultErrHandler
  1069. }
  1070. // Create reader/writer
  1071. nc.newReaderWriter()
  1072. if err := nc.connect(); err != nil {
  1073. return nil, err
  1074. }
  1075. // Spin up the async cb dispatcher on success
  1076. go nc.ach.asyncCBDispatcher()
  1077. return nc, nil
  1078. }
  1079. func defaultErrHandler(nc *Conn, sub *Subscription, err error) {
  1080. var cid uint64
  1081. if nc != nil {
  1082. nc.mu.RLock()
  1083. cid = nc.info.CID
  1084. nc.mu.RUnlock()
  1085. }
  1086. var errStr string
  1087. if sub != nil {
  1088. errStr = fmt.Sprintf("%s on connection [%d] for subscription on %q\n", err.Error(), cid, sub.Subject)
  1089. } else {
  1090. errStr = fmt.Sprintf("%s on connection [%d]\n", err.Error(), cid)
  1091. }
  1092. os.Stderr.WriteString(errStr)
  1093. }
  1094. const (
  1095. _CRLF_ = "\r\n"
  1096. _EMPTY_ = ""
  1097. _SPC_ = " "
  1098. _PUB_P_ = "PUB "
  1099. _HPUB_P_ = "HPUB "
  1100. )
  1101. var _CRLF_BYTES_ = []byte(_CRLF_)
  1102. const (
  1103. _OK_OP_ = "+OK"
  1104. _ERR_OP_ = "-ERR"
  1105. _PONG_OP_ = "PONG"
  1106. _INFO_OP_ = "INFO"
  1107. )
  1108. const (
  1109. connectProto = "CONNECT %s" + _CRLF_
  1110. pingProto = "PING" + _CRLF_
  1111. pongProto = "PONG" + _CRLF_
  1112. subProto = "SUB %s %s %d" + _CRLF_
  1113. unsubProto = "UNSUB %d %s" + _CRLF_
  1114. okProto = _OK_OP_ + _CRLF_
  1115. )
  1116. // Return the currently selected server
  1117. func (nc *Conn) currentServer() (int, *srv) {
  1118. for i, s := range nc.srvPool {
  1119. if s == nil {
  1120. continue
  1121. }
  1122. if s == nc.current {
  1123. return i, s
  1124. }
  1125. }
  1126. return -1, nil
  1127. }
  1128. // Pop the current server and put onto the end of the list. Select head of list as long
  1129. // as number of reconnect attempts under MaxReconnect.
  1130. func (nc *Conn) selectNextServer() (*srv, error) {
  1131. i, s := nc.currentServer()
  1132. if i < 0 {
  1133. return nil, ErrNoServers
  1134. }
  1135. sp := nc.srvPool
  1136. num := len(sp)
  1137. copy(sp[i:num-1], sp[i+1:num])
  1138. maxReconnect := nc.Opts.MaxReconnect
  1139. if maxReconnect < 0 || s.reconnects < maxReconnect {
  1140. nc.srvPool[num-1] = s
  1141. } else {
  1142. nc.srvPool = sp[0 : num-1]
  1143. }
  1144. if len(nc.srvPool) <= 0 {
  1145. nc.current = nil
  1146. return nil, ErrNoServers
  1147. }
  1148. nc.current = nc.srvPool[0]
  1149. return nc.srvPool[0], nil
  1150. }
  1151. // Will assign the correct server to nc.current
  1152. func (nc *Conn) pickServer() error {
  1153. nc.current = nil
  1154. if len(nc.srvPool) <= 0 {
  1155. return ErrNoServers
  1156. }
  1157. for _, s := range nc.srvPool {
  1158. if s != nil {
  1159. nc.current = s
  1160. return nil
  1161. }
  1162. }
  1163. return ErrNoServers
  1164. }
  1165. const tlsScheme = "tls"
  1166. // Create the server pool using the options given.
  1167. // We will place a Url option first, followed by any
  1168. // Server Options. We will randomize the server pool unless
  1169. // the NoRandomize flag is set.
  1170. func (nc *Conn) setupServerPool() error {
  1171. nc.srvPool = make([]*srv, 0, srvPoolSize)
  1172. nc.urls = make(map[string]struct{}, srvPoolSize)
  1173. // Create srv objects from each url string in nc.Opts.Servers
  1174. // and add them to the pool.
  1175. for _, urlString := range nc.Opts.Servers {
  1176. if err := nc.addURLToPool(urlString, false, false); err != nil {
  1177. return err
  1178. }
  1179. }
  1180. // Randomize if allowed to
  1181. if !nc.Opts.NoRandomize {
  1182. nc.shufflePool(0)
  1183. }
  1184. // Normally, if this one is set, Options.Servers should not be,
  1185. // but we always allowed that, so continue to do so.
  1186. if nc.Opts.Url != _EMPTY_ {
  1187. // Add to the end of the array
  1188. if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
  1189. return err
  1190. }
  1191. // Then swap it with first to guarantee that Options.Url is tried first.
  1192. last := len(nc.srvPool) - 1
  1193. if last > 0 {
  1194. nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
  1195. }
  1196. } else if len(nc.srvPool) <= 0 {
  1197. // Place default URL if pool is empty.
  1198. if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
  1199. return err
  1200. }
  1201. }
  1202. // Check for Scheme hint to move to TLS mode.
  1203. for _, srv := range nc.srvPool {
  1204. if srv.url.Scheme == tlsScheme {
  1205. // FIXME(dlc), this is for all in the pool, should be case by case.
  1206. nc.Opts.Secure = true
  1207. if nc.Opts.TLSConfig == nil {
  1208. nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  1209. }
  1210. }
  1211. }
  1212. return nc.pickServer()
  1213. }
  1214. // Helper function to return scheme
  1215. func (nc *Conn) connScheme() string {
  1216. if nc.ws {
  1217. if nc.Opts.Secure {
  1218. return wsSchemeTLS
  1219. }
  1220. return wsScheme
  1221. }
  1222. if nc.Opts.Secure {
  1223. return tlsScheme
  1224. }
  1225. return "nats"
  1226. }
  1227. // Return true iff u.Hostname() is an IP address.
  1228. func hostIsIP(u *url.URL) bool {
  1229. return net.ParseIP(u.Hostname()) != nil
  1230. }
  1231. // addURLToPool adds an entry to the server pool
  1232. func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
  1233. if !strings.Contains(sURL, "://") {
  1234. sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
  1235. }
  1236. var (
  1237. u *url.URL
  1238. err error
  1239. )
  1240. for i := 0; i < 2; i++ {
  1241. u, err = url.Parse(sURL)
  1242. if err != nil {
  1243. return err
  1244. }
  1245. if u.Port() != "" {
  1246. break
  1247. }
  1248. // In case given URL is of the form "localhost:", just add
  1249. // the port number at the end, otherwise, add ":4222".
  1250. if sURL[len(sURL)-1] != ':' {
  1251. sURL += ":"
  1252. }
  1253. sURL += defaultPortString
  1254. }
  1255. isWS := isWebsocketScheme(u)
  1256. // We don't support mix and match of websocket and non websocket URLs.
  1257. // If this is the first URL, then we accept and switch the global state
  1258. // to websocket. After that, we will know how to reject mixed URLs.
  1259. if len(nc.srvPool) == 0 {
  1260. nc.ws = isWS
  1261. } else if isWS && !nc.ws || !isWS && nc.ws {
  1262. return fmt.Errorf("mixing of websocket and non websocket URLs is not allowed")
  1263. }
  1264. var tlsName string
  1265. if implicit {
  1266. curl := nc.current.url
  1267. // Check to see if we do not have a url.User but current connected
  1268. // url does. If so copy over.
  1269. if u.User == nil && curl.User != nil {
  1270. u.User = curl.User
  1271. }
  1272. // We are checking to see if we have a secure connection and are
  1273. // adding an implicit server that just has an IP. If so we will remember
  1274. // the current hostname we are connected to.
  1275. if saveTLSName && hostIsIP(u) {
  1276. tlsName = curl.Hostname()
  1277. }
  1278. }
  1279. s := &srv{url: u, isImplicit: implicit, tlsName: tlsName}
  1280. nc.srvPool = append(nc.srvPool, s)
  1281. nc.urls[u.Host] = struct{}{}
  1282. return nil
  1283. }
  1284. // shufflePool swaps randomly elements in the server pool
  1285. // The `offset` value indicates that the shuffling should start at
  1286. // this offset and leave the elements from [0..offset) intact.
  1287. func (nc *Conn) shufflePool(offset int) {
  1288. if len(nc.srvPool) <= offset+1 {
  1289. return
  1290. }
  1291. source := rand.NewSource(time.Now().UnixNano())
  1292. r := rand.New(source)
  1293. for i := offset; i < len(nc.srvPool); i++ {
  1294. j := offset + r.Intn(i+1-offset)
  1295. nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
  1296. }
  1297. }
  1298. func (nc *Conn) newReaderWriter() {
  1299. nc.br = &natsReader{
  1300. buf: make([]byte, defaultBufSize),
  1301. off: -1,
  1302. }
  1303. nc.bw = &natsWriter{
  1304. limit: defaultBufSize,
  1305. plimit: nc.Opts.ReconnectBufSize,
  1306. }
  1307. }
  1308. func (nc *Conn) bindToNewConn() {
  1309. bw := nc.bw
  1310. bw.w, bw.bufs = nc.newWriter(), nil
  1311. br := nc.br
  1312. br.r, br.n, br.off = nc.conn, 0, -1
  1313. }
  1314. func (nc *Conn) newWriter() io.Writer {
  1315. var w io.Writer = nc.conn
  1316. if nc.Opts.FlusherTimeout > 0 {
  1317. w = &timeoutWriter{conn: nc.conn, timeout: nc.Opts.FlusherTimeout}
  1318. }
  1319. return w
  1320. }
  1321. func (w *natsWriter) appendString(str string) error {
  1322. return w.appendBufs([]byte(str))
  1323. }
  1324. func (w *natsWriter) appendBufs(bufs ...[]byte) error {
  1325. for _, buf := range bufs {
  1326. if len(buf) == 0 {
  1327. continue
  1328. }
  1329. if w.pending != nil {
  1330. w.pending.Write(buf)
  1331. } else {
  1332. w.bufs = append(w.bufs, buf...)
  1333. }
  1334. }
  1335. if w.pending == nil && len(w.bufs) >= w.limit {
  1336. return w.flush()
  1337. }
  1338. return nil
  1339. }
  1340. func (w *natsWriter) writeDirect(strs ...string) error {
  1341. for _, str := range strs {
  1342. if _, err := w.w.Write([]byte(str)); err != nil {
  1343. return err
  1344. }
  1345. }
  1346. return nil
  1347. }
  1348. func (w *natsWriter) flush() error {
  1349. // If a pending buffer is set, we don't flush. Code that needs to
  1350. // write directly to the socket, by-passing buffers during (re)connect,
  1351. // will use the writeDirect() API.
  1352. if w.pending != nil {
  1353. return nil
  1354. }
  1355. // Do not skip calling w.w.Write() here if len(w.bufs) is 0 because
  1356. // the actual writer (if websocket for instance) may have things
  1357. // to do such as sending control frames, etc..
  1358. _, err := w.w.Write(w.bufs)
  1359. w.bufs = w.bufs[:0]
  1360. return err
  1361. }
  1362. func (w *natsWriter) buffered() int {
  1363. if w.pending != nil {
  1364. return w.pending.Len()
  1365. }
  1366. return len(w.bufs)
  1367. }
  1368. func (w *natsWriter) switchToPending() {
  1369. w.pending = new(bytes.Buffer)
  1370. }
  1371. func (w *natsWriter) flushPendingBuffer() error {
  1372. if w.pending == nil || w.pending.Len() == 0 {
  1373. return nil
  1374. }
  1375. _, err := w.w.Write(w.pending.Bytes())
  1376. // Reset the pending buffer at this point because we don't want
  1377. // to take the risk of sending duplicates or partials.
  1378. w.pending.Reset()
  1379. return err
  1380. }
  1381. func (w *natsWriter) atLimitIfUsingPending() bool {
  1382. if w.pending == nil {
  1383. return false
  1384. }
  1385. return w.pending.Len() >= w.plimit
  1386. }
  1387. func (w *natsWriter) doneWithPending() {
  1388. w.pending = nil
  1389. }
  1390. func (r *natsReader) Read() ([]byte, error) {
  1391. if r.off >= 0 {
  1392. off := r.off
  1393. r.off = -1
  1394. return r.buf[off:r.n], nil
  1395. }
  1396. var err error
  1397. r.n, err = r.r.Read(r.buf)
  1398. return r.buf[:r.n], err
  1399. }
  1400. func (r *natsReader) ReadString(delim byte) (string, error) {
  1401. var s string
  1402. build_string:
  1403. // First look if we have something in the buffer
  1404. if r.off >= 0 {
  1405. i := bytes.IndexByte(r.buf[r.off:r.n], delim)
  1406. if i >= 0 {
  1407. end := r.off + i + 1
  1408. s += string(r.buf[r.off:end])
  1409. r.off = end
  1410. if r.off >= r.n {
  1411. r.off = -1
  1412. }
  1413. return s, nil
  1414. }
  1415. // We did not find the delim, so will have to read more.
  1416. s += string(r.buf[r.off:r.n])
  1417. r.off = -1
  1418. }
  1419. if _, err := r.Read(); err != nil {
  1420. return s, err
  1421. }
  1422. r.off = 0
  1423. goto build_string
  1424. }
  1425. // createConn will connect to the server and wrap the appropriate
  1426. // bufio structures. It will do the right thing when an existing
  1427. // connection is in place.
  1428. func (nc *Conn) createConn() (err error) {
  1429. if nc.Opts.Timeout < 0 {
  1430. return ErrBadTimeout
  1431. }
  1432. if _, cur := nc.currentServer(); cur == nil {
  1433. return ErrNoServers
  1434. }
  1435. // We will auto-expand host names if they resolve to multiple IPs
  1436. hosts := []string{}
  1437. u := nc.current.url
  1438. if net.ParseIP(u.Hostname()) == nil {
  1439. addrs, _ := net.LookupHost(u.Hostname())
  1440. for _, addr := range addrs {
  1441. hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
  1442. }
  1443. }
  1444. // Fall back to what we were given.
  1445. if len(hosts) == 0 {
  1446. hosts = append(hosts, u.Host)
  1447. }
  1448. // CustomDialer takes precedence. If not set, use Opts.Dialer which
  1449. // is set to a default *net.Dialer (in Connect()) if not explicitly
  1450. // set by the user.
  1451. dialer := nc.Opts.CustomDialer
  1452. if dialer == nil {
  1453. // We will copy and shorten the timeout if we have multiple hosts to try.
  1454. copyDialer := *nc.Opts.Dialer
  1455. copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
  1456. dialer = &copyDialer
  1457. }
  1458. if len(hosts) > 1 && !nc.Opts.NoRandomize {
  1459. rand.Shuffle(len(hosts), func(i, j int) {
  1460. hosts[i], hosts[j] = hosts[j], hosts[i]
  1461. })
  1462. }
  1463. for _, host := range hosts {
  1464. nc.conn, err = dialer.Dial("tcp", host)
  1465. if err == nil {
  1466. break
  1467. }
  1468. }
  1469. if err != nil {
  1470. return err
  1471. }
  1472. // If scheme starts with "ws" then branch out to websocket code.
  1473. if isWebsocketScheme(u) {
  1474. return nc.wsInitHandshake(u)
  1475. }
  1476. // Reset reader/writer to this new TCP connection
  1477. nc.bindToNewConn()
  1478. return nil
  1479. }
  1480. // makeTLSConn will wrap an existing Conn using TLS
  1481. func (nc *Conn) makeTLSConn() error {
  1482. // Allow the user to configure their own tls.Config structure.
  1483. var tlsCopy *tls.Config
  1484. if nc.Opts.TLSConfig != nil {
  1485. tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
  1486. } else {
  1487. tlsCopy = &tls.Config{}
  1488. }
  1489. // If its blank we will override it with the current host
  1490. if tlsCopy.ServerName == _EMPTY_ {
  1491. if nc.current.tlsName != _EMPTY_ {
  1492. tlsCopy.ServerName = nc.current.tlsName
  1493. } else {
  1494. h, _, _ := net.SplitHostPort(nc.current.url.Host)
  1495. tlsCopy.ServerName = h
  1496. }
  1497. }
  1498. nc.conn = tls.Client(nc.conn, tlsCopy)
  1499. conn := nc.conn.(*tls.Conn)
  1500. if err := conn.Handshake(); err != nil {
  1501. return err
  1502. }
  1503. nc.bindToNewConn()
  1504. return nil
  1505. }
  1506. // waitForExits will wait for all socket watcher Go routines to
  1507. // be shutdown before proceeding.
  1508. func (nc *Conn) waitForExits() {
  1509. // Kick old flusher forcefully.
  1510. select {
  1511. case nc.fch <- struct{}{}:
  1512. default:
  1513. }
  1514. // Wait for any previous go routines.
  1515. nc.wg.Wait()
  1516. }
  1517. // ConnectedUrl reports the connected server's URL
  1518. func (nc *Conn) ConnectedUrl() string {
  1519. if nc == nil {
  1520. return _EMPTY_
  1521. }
  1522. nc.mu.RLock()
  1523. defer nc.mu.RUnlock()
  1524. if nc.status != CONNECTED {
  1525. return _EMPTY_
  1526. }
  1527. return nc.current.url.String()
  1528. }
  1529. // ConnectedAddr returns the connected server's IP
  1530. func (nc *Conn) ConnectedAddr() string {
  1531. if nc == nil {
  1532. return _EMPTY_
  1533. }
  1534. nc.mu.RLock()
  1535. defer nc.mu.RUnlock()
  1536. if nc.status != CONNECTED {
  1537. return _EMPTY_
  1538. }
  1539. return nc.conn.RemoteAddr().String()
  1540. }
  1541. // ConnectedServerId reports the connected server's Id
  1542. func (nc *Conn) ConnectedServerId() string {
  1543. if nc == nil {
  1544. return _EMPTY_
  1545. }
  1546. nc.mu.RLock()
  1547. defer nc.mu.RUnlock()
  1548. if nc.status != CONNECTED {
  1549. return _EMPTY_
  1550. }
  1551. return nc.info.ID
  1552. }
  1553. // ConnectedServerName reports the connected server's name
  1554. func (nc *Conn) ConnectedServerName() string {
  1555. if nc == nil {
  1556. return _EMPTY_
  1557. }
  1558. nc.mu.RLock()
  1559. defer nc.mu.RUnlock()
  1560. if nc.status != CONNECTED {
  1561. return _EMPTY_
  1562. }
  1563. return nc.info.Name
  1564. }
  1565. // ConnectedClusterName reports the connected server's cluster name if any
  1566. func (nc *Conn) ConnectedClusterName() string {
  1567. if nc == nil {
  1568. return _EMPTY_
  1569. }
  1570. nc.mu.RLock()
  1571. defer nc.mu.RUnlock()
  1572. if nc.status != CONNECTED {
  1573. return _EMPTY_
  1574. }
  1575. return nc.info.Cluster
  1576. }
  1577. // Low level setup for structs, etc
  1578. func (nc *Conn) setup() {
  1579. nc.subs = make(map[int64]*Subscription)
  1580. nc.pongs = make([]chan struct{}, 0, 8)
  1581. nc.fch = make(chan struct{}, flushChanSize)
  1582. nc.rqch = make(chan struct{})
  1583. // Setup scratch outbound buffer for PUB/HPUB
  1584. pub := nc.scratch[:len(_HPUB_P_)]
  1585. copy(pub, _HPUB_P_)
  1586. }
  1587. // Process a connected connection and initialize properly.
  1588. func (nc *Conn) processConnectInit() error {
  1589. // Set our deadline for the whole connect process
  1590. nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
  1591. defer nc.conn.SetDeadline(time.Time{})
  1592. // Set our status to connecting.
  1593. nc.status = CONNECTING
  1594. // Process the INFO protocol received from the server
  1595. err := nc.processExpectedInfo()
  1596. if err != nil {
  1597. return err
  1598. }
  1599. // Send the CONNECT protocol along with the initial PING protocol.
  1600. // Wait for the PONG response (or any error that we get from the server).
  1601. err = nc.sendConnect()
  1602. if err != nil {
  1603. return err
  1604. }
  1605. // Reset the number of PING sent out
  1606. nc.pout = 0
  1607. // Start or reset Timer
  1608. if nc.Opts.PingInterval > 0 {
  1609. if nc.ptmr == nil {
  1610. nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
  1611. } else {
  1612. nc.ptmr.Reset(nc.Opts.PingInterval)
  1613. }
  1614. }
  1615. // Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
  1616. nc.wg.Add(2)
  1617. go nc.readLoop()
  1618. go nc.flusher()
  1619. return nil
  1620. }
  1621. // Main connect function. Will connect to the nats-server
  1622. func (nc *Conn) connect() error {
  1623. var err error
  1624. // Create actual socket connection
  1625. // For first connect we walk all servers in the pool and try
  1626. // to connect immediately.
  1627. nc.mu.Lock()
  1628. defer nc.mu.Unlock()
  1629. nc.initc = true
  1630. // The pool may change inside the loop iteration due to INFO protocol.
  1631. for i := 0; i < len(nc.srvPool); i++ {
  1632. nc.current = nc.srvPool[i]
  1633. if err = nc.createConn(); err == nil {
  1634. // This was moved out of processConnectInit() because
  1635. // that function is now invoked from doReconnect() too.
  1636. nc.setup()
  1637. err = nc.processConnectInit()
  1638. if err == nil {
  1639. nc.current.didConnect = true
  1640. nc.current.reconnects = 0
  1641. nc.current.lastErr = nil
  1642. break
  1643. } else {
  1644. nc.mu.Unlock()
  1645. nc.close(DISCONNECTED, false, err)
  1646. nc.mu.Lock()
  1647. // Do not reset nc.current here since it would prevent
  1648. // RetryOnFailedConnect to work should this be the last server
  1649. // to try before starting doReconnect().
  1650. }
  1651. } else {
  1652. // Cancel out default connection refused, will trigger the
  1653. // No servers error conditional
  1654. if strings.Contains(err.Error(), "connection refused") {
  1655. err = nil
  1656. }
  1657. }
  1658. }
  1659. if err == nil && nc.status != CONNECTED {
  1660. err = ErrNoServers
  1661. }
  1662. if err == nil {
  1663. nc.initc = false
  1664. } else if nc.Opts.RetryOnFailedConnect {
  1665. nc.setup()
  1666. nc.status = RECONNECTING
  1667. nc.bw.switchToPending()
  1668. go nc.doReconnect(ErrNoServers)
  1669. err = nil
  1670. } else {
  1671. nc.current = nil
  1672. }
  1673. return err
  1674. }
  1675. // This will check to see if the connection should be
  1676. // secure. This can be dictated from either end and should
  1677. // only be called after the INIT protocol has been received.
  1678. func (nc *Conn) checkForSecure() error {
  1679. // Check to see if we need to engage TLS
  1680. o := nc.Opts
  1681. // Check for mismatch in setups
  1682. if o.Secure && !nc.info.TLSRequired && !nc.info.TLSAvailable {
  1683. return ErrSecureConnWanted
  1684. } else if nc.info.TLSRequired && !o.Secure {
  1685. // Switch to Secure since server needs TLS.
  1686. o.Secure = true
  1687. }
  1688. // Need to rewrap with bufio
  1689. if o.Secure {
  1690. if err := nc.makeTLSConn(); err != nil {
  1691. return err
  1692. }
  1693. }
  1694. return nil
  1695. }
  1696. // processExpectedInfo will look for the expected first INFO message
  1697. // sent when a connection is established. The lock should be held entering.
  1698. func (nc *Conn) processExpectedInfo() error {
  1699. c := &control{}
  1700. // Read the protocol
  1701. err := nc.readOp(c)
  1702. if err != nil {
  1703. return err
  1704. }
  1705. // The nats protocol should send INFO first always.
  1706. if c.op != _INFO_OP_ {
  1707. return ErrNoInfoReceived
  1708. }
  1709. // Parse the protocol
  1710. if err := nc.processInfo(c.args); err != nil {
  1711. return err
  1712. }
  1713. if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
  1714. return ErrNkeysNotSupported
  1715. }
  1716. // For websocket connections, we already switched to TLS if need be,
  1717. // so we are done here.
  1718. if nc.ws {
  1719. return nil
  1720. }
  1721. return nc.checkForSecure()
  1722. }
  1723. // Sends a protocol control message by queuing into the bufio writer
  1724. // and kicking the flush Go routine. These writes are protected.
  1725. func (nc *Conn) sendProto(proto string) {
  1726. nc.mu.Lock()
  1727. nc.bw.appendString(proto)
  1728. nc.kickFlusher()
  1729. nc.mu.Unlock()
  1730. }
  1731. // Generate a connect protocol message, issuing user/password if
  1732. // applicable. The lock is assumed to be held upon entering.
  1733. func (nc *Conn) connectProto() (string, error) {
  1734. o := nc.Opts
  1735. var nkey, sig, user, pass, token, ujwt string
  1736. u := nc.current.url.User
  1737. if u != nil {
  1738. // if no password, assume username is authToken
  1739. if _, ok := u.Password(); !ok {
  1740. token = u.Username()
  1741. } else {
  1742. user = u.Username()
  1743. pass, _ = u.Password()
  1744. }
  1745. } else {
  1746. // Take from options (possibly all empty strings)
  1747. user = o.User
  1748. pass = o.Password
  1749. token = o.Token
  1750. nkey = o.Nkey
  1751. }
  1752. // Look for user jwt.
  1753. if o.UserJWT != nil {
  1754. if jwt, err := o.UserJWT(); err != nil {
  1755. return _EMPTY_, err
  1756. } else {
  1757. ujwt = jwt
  1758. }
  1759. if nkey != _EMPTY_ {
  1760. return _EMPTY_, ErrNkeyAndUser
  1761. }
  1762. }
  1763. if ujwt != _EMPTY_ || nkey != _EMPTY_ {
  1764. if o.SignatureCB == nil {
  1765. if ujwt == _EMPTY_ {
  1766. return _EMPTY_, ErrNkeyButNoSigCB
  1767. }
  1768. return _EMPTY_, ErrUserButNoSigCB
  1769. }
  1770. sigraw, err := o.SignatureCB([]byte(nc.info.Nonce))
  1771. if err != nil {
  1772. return _EMPTY_, err
  1773. }
  1774. sig = base64.RawURLEncoding.EncodeToString(sigraw)
  1775. }
  1776. if nc.Opts.TokenHandler != nil {
  1777. if token != _EMPTY_ {
  1778. return _EMPTY_, ErrTokenAlreadySet
  1779. }
  1780. token = nc.Opts.TokenHandler()
  1781. }
  1782. // If our server does not support headers then we can't do them or no responders.
  1783. hdrs := nc.info.Headers
  1784. cinfo := connectInfo{o.Verbose, o.Pedantic, ujwt, nkey, sig, user, pass, token,
  1785. o.Secure, o.Name, LangString, Version, clientProtoInfo, !o.NoEcho, hdrs, hdrs}
  1786. b, err := json.Marshal(cinfo)
  1787. if err != nil {
  1788. return _EMPTY_, ErrJsonParse
  1789. }
  1790. // Check if NoEcho is set and we have a server that supports it.
  1791. if o.NoEcho && nc.info.Proto < 1 {
  1792. return _EMPTY_, ErrNoEchoNotSupported
  1793. }
  1794. return fmt.Sprintf(connectProto, b), nil
  1795. }
  1796. // normalizeErr removes the prefix -ERR, trim spaces and remove the quotes.
  1797. func normalizeErr(line string) string {
  1798. s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
  1799. s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
  1800. return s
  1801. }
  1802. // Send a connect protocol message to the server, issue user/password if
  1803. // applicable. Will wait for a flush to return from the server for error
  1804. // processing.
  1805. func (nc *Conn) sendConnect() error {
  1806. // Construct the CONNECT protocol string
  1807. cProto, err := nc.connectProto()
  1808. if err != nil {
  1809. return err
  1810. }
  1811. // Write the protocol and PING directly to the underlying writer.
  1812. if err := nc.bw.writeDirect(cProto, pingProto); err != nil {
  1813. return err
  1814. }
  1815. // We don't want to read more than we need here, otherwise
  1816. // we would need to transfer the excess read data to the readLoop.
  1817. // Since in normal situations we just are looking for a PONG\r\n,
  1818. // reading byte-by-byte here is ok.
  1819. proto, err := nc.readProto()
  1820. if err != nil {
  1821. return err
  1822. }
  1823. // If opts.Verbose is set, handle +OK
  1824. if nc.Opts.Verbose && proto == okProto {
  1825. // Read the rest now...
  1826. proto, err = nc.readProto()
  1827. if err != nil {
  1828. return err
  1829. }
  1830. }
  1831. // We expect a PONG
  1832. if proto != pongProto {
  1833. // But it could be something else, like -ERR
  1834. // Since we no longer use ReadLine(), trim the trailing "\r\n"
  1835. proto = strings.TrimRight(proto, "\r\n")
  1836. // If it's a server error...
  1837. if strings.HasPrefix(proto, _ERR_OP_) {
  1838. // Remove -ERR, trim spaces and quotes, and convert to lower case.
  1839. proto = normalizeErr(proto)
  1840. // Check if this is an auth error
  1841. if authErr := checkAuthError(strings.ToLower(proto)); authErr != nil {
  1842. // This will schedule an async error if we are in reconnect,
  1843. // and keep track of the auth error for the current server.
  1844. // If we have got the same error twice, this sets nc.ar to true to
  1845. // indicate that the reconnect should be aborted (will be checked
  1846. // in doReconnect()).
  1847. nc.processAuthError(authErr)
  1848. }
  1849. return errors.New("nats: " + proto)
  1850. }
  1851. // Notify that we got an unexpected protocol.
  1852. return fmt.Errorf("nats: expected '%s', got '%s'", _PONG_OP_, proto)
  1853. }
  1854. // This is where we are truly connected.
  1855. nc.status = CONNECTED
  1856. return nil
  1857. }
  1858. // reads a protocol line.
  1859. func (nc *Conn) readProto() (string, error) {
  1860. return nc.br.ReadString('\n')
  1861. }
  1862. // A control protocol line.
  1863. type control struct {
  1864. op, args string
  1865. }
  1866. // Read a control line and process the intended op.
  1867. func (nc *Conn) readOp(c *control) error {
  1868. line, err := nc.readProto()
  1869. if err != nil {
  1870. return err
  1871. }
  1872. parseControl(line, c)
  1873. return nil
  1874. }
  1875. // Parse a control line from the server.
  1876. func parseControl(line string, c *control) {
  1877. toks := strings.SplitN(line, _SPC_, 2)
  1878. if len(toks) == 1 {
  1879. c.op = strings.TrimSpace(toks[0])
  1880. c.args = _EMPTY_
  1881. } else if len(toks) == 2 {
  1882. c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
  1883. } else {
  1884. c.op = _EMPTY_
  1885. }
  1886. }
  1887. // flushReconnectPending will push the pending items that were
  1888. // gathered while we were in a RECONNECTING state to the socket.
  1889. func (nc *Conn) flushReconnectPendingItems() error {
  1890. return nc.bw.flushPendingBuffer()
  1891. }
  1892. // Stops the ping timer if set.
  1893. // Connection lock is held on entry.
  1894. func (nc *Conn) stopPingTimer() {
  1895. if nc.ptmr != nil {
  1896. nc.ptmr.Stop()
  1897. }
  1898. }
  1899. // Try to reconnect using the option parameters.
  1900. // This function assumes we are allowed to reconnect.
  1901. func (nc *Conn) doReconnect(err error) {
  1902. // We want to make sure we have the other watchers shutdown properly
  1903. // here before we proceed past this point.
  1904. nc.waitForExits()
  1905. // FIXME(dlc) - We have an issue here if we have
  1906. // outstanding flush points (pongs) and they were not
  1907. // sent out, but are still in the pipe.
  1908. // Hold the lock manually and release where needed below,
  1909. // can't do defer here.
  1910. nc.mu.Lock()
  1911. // Clear any errors.
  1912. nc.err = nil
  1913. // Perform appropriate callback if needed for a disconnect.
  1914. // DisconnectedErrCB has priority over deprecated DisconnectedCB
  1915. if !nc.initc {
  1916. if nc.Opts.DisconnectedErrCB != nil {
  1917. nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) })
  1918. } else if nc.Opts.DisconnectedCB != nil {
  1919. nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
  1920. }
  1921. }
  1922. // This is used to wait on go routines exit if we start them in the loop
  1923. // but an error occurs after that.
  1924. waitForGoRoutines := false
  1925. var rt *time.Timer
  1926. // Channel used to kick routine out of sleep when conn is closed.
  1927. rqch := nc.rqch
  1928. // Counter that is increased when the whole list of servers has been tried.
  1929. var wlf int
  1930. var jitter time.Duration
  1931. var rw time.Duration
  1932. // If a custom reconnect delay handler is set, this takes precedence.
  1933. crd := nc.Opts.CustomReconnectDelayCB
  1934. if crd == nil {
  1935. rw = nc.Opts.ReconnectWait
  1936. // TODO: since we sleep only after the whole list has been tried, we can't
  1937. // rely on individual *srv to know if it is a TLS or non-TLS url.
  1938. // We have to pick which type of jitter to use, for now, we use these hints:
  1939. jitter = nc.Opts.ReconnectJitter
  1940. if nc.Opts.Secure || nc.Opts.TLSConfig != nil {
  1941. jitter = nc.Opts.ReconnectJitterTLS
  1942. }
  1943. }
  1944. for i := 0; len(nc.srvPool) > 0; {
  1945. cur, err := nc.selectNextServer()
  1946. if err != nil {
  1947. nc.err = err
  1948. break
  1949. }
  1950. doSleep := i+1 >= len(nc.srvPool)
  1951. nc.mu.Unlock()
  1952. if !doSleep {
  1953. i++
  1954. // Release the lock to give a chance to a concurrent nc.Close() to break the loop.
  1955. runtime.Gosched()
  1956. } else {
  1957. i = 0
  1958. var st time.Duration
  1959. if crd != nil {
  1960. wlf++
  1961. st = crd(wlf)
  1962. } else {
  1963. st = rw
  1964. if jitter > 0 {
  1965. st += time.Duration(rand.Int63n(int64(jitter)))
  1966. }
  1967. }
  1968. if rt == nil {
  1969. rt = time.NewTimer(st)
  1970. } else {
  1971. rt.Reset(st)
  1972. }
  1973. select {
  1974. case <-rqch:
  1975. rt.Stop()
  1976. case <-rt.C:
  1977. }
  1978. }
  1979. // If the readLoop, etc.. go routines were started, wait for them to complete.
  1980. if waitForGoRoutines {
  1981. nc.waitForExits()
  1982. waitForGoRoutines = false
  1983. }
  1984. nc.mu.Lock()
  1985. // Check if we have been closed first.
  1986. if nc.isClosed() {
  1987. break
  1988. }
  1989. // Mark that we tried a reconnect
  1990. cur.reconnects++
  1991. // Try to create a new connection
  1992. err = nc.createConn()
  1993. // Not yet connected, retry...
  1994. // Continue to hold the lock
  1995. if err != nil {
  1996. nc.err = nil
  1997. continue
  1998. }
  1999. // We are reconnected
  2000. nc.Reconnects++
  2001. // Process connect logic
  2002. if nc.err = nc.processConnectInit(); nc.err != nil {
  2003. // Check if we should abort reconnect. If so, break out
  2004. // of the loop and connection will be closed.
  2005. if nc.ar {
  2006. break
  2007. }
  2008. nc.status = RECONNECTING
  2009. continue
  2010. }
  2011. // Clear possible lastErr under the connection lock after
  2012. // a successful processConnectInit().
  2013. nc.current.lastErr = nil
  2014. // Clear out server stats for the server we connected to..
  2015. cur.didConnect = true
  2016. cur.reconnects = 0
  2017. // Send existing subscription state
  2018. nc.resendSubscriptions()
  2019. // Now send off and clear pending buffer
  2020. nc.err = nc.flushReconnectPendingItems()
  2021. if nc.err != nil {
  2022. nc.status = RECONNECTING
  2023. // Stop the ping timer (if set)
  2024. nc.stopPingTimer()
  2025. // Since processConnectInit() returned without error, the
  2026. // go routines were started, so wait for them to return
  2027. // on the next iteration (after releasing the lock).
  2028. waitForGoRoutines = true
  2029. continue
  2030. }
  2031. // Done with the pending buffer
  2032. nc.bw.doneWithPending()
  2033. // This is where we are truly connected.
  2034. nc.status = CONNECTED
  2035. // If we are here with a retry on failed connect, indicate that the
  2036. // initial connect is now complete.
  2037. nc.initc = false
  2038. // Queue up the reconnect callback.
  2039. if nc.Opts.ReconnectedCB != nil {
  2040. nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) })
  2041. }
  2042. // Release lock here, we will return below.
  2043. nc.mu.Unlock()
  2044. // Make sure to flush everything
  2045. nc.Flush()
  2046. return
  2047. }
  2048. // Call into close.. We have no servers left..
  2049. if nc.err == nil {
  2050. nc.err = ErrNoServers
  2051. }
  2052. nc.mu.Unlock()
  2053. nc.close(CLOSED, true, nil)
  2054. }
  2055. // processOpErr handles errors from reading or parsing the protocol.
  2056. // The lock should not be held entering this function.
  2057. func (nc *Conn) processOpErr(err error) {
  2058. nc.mu.Lock()
  2059. if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
  2060. nc.mu.Unlock()
  2061. return
  2062. }
  2063. if nc.Opts.AllowReconnect && nc.status == CONNECTED {
  2064. // Set our new status
  2065. nc.status = RECONNECTING
  2066. // Stop ping timer if set
  2067. nc.stopPingTimer()
  2068. if nc.conn != nil {
  2069. nc.conn.Close()
  2070. nc.conn = nil
  2071. }
  2072. // Create pending buffer before reconnecting.
  2073. nc.bw.switchToPending()
  2074. // Clear any queued pongs, e.g. pending flush calls.
  2075. nc.clearPendingFlushCalls()
  2076. go nc.doReconnect(err)
  2077. nc.mu.Unlock()
  2078. return
  2079. }
  2080. nc.status = DISCONNECTED
  2081. nc.err = err
  2082. nc.mu.Unlock()
  2083. nc.close(CLOSED, true, nil)
  2084. }
  2085. // dispatch is responsible for calling any async callbacks
  2086. func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
  2087. for {
  2088. ac.mu.Lock()
  2089. // Protect for spurious wakeups. We should get out of the
  2090. // wait only if there is an element to pop from the list.
  2091. for ac.head == nil {
  2092. ac.cond.Wait()
  2093. }
  2094. cur := ac.head
  2095. ac.head = cur.next
  2096. if cur == ac.tail {
  2097. ac.tail = nil
  2098. }
  2099. ac.mu.Unlock()
  2100. // This signals that the dispatcher has been closed and all
  2101. // previous callbacks have been dispatched.
  2102. if cur.f == nil {
  2103. return
  2104. }
  2105. // Invoke callback outside of handler's lock
  2106. cur.f()
  2107. }
  2108. }
  2109. // Add the given function to the tail of the list and
  2110. // signals the dispatcher.
  2111. func (ac *asyncCallbacksHandler) push(f func()) {
  2112. ac.pushOrClose(f, false)
  2113. }
  2114. // Signals that we are closing...
  2115. func (ac *asyncCallbacksHandler) close() {
  2116. ac.pushOrClose(nil, true)
  2117. }
  2118. // Add the given function to the tail of the list and
  2119. // signals the dispatcher.
  2120. func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
  2121. ac.mu.Lock()
  2122. defer ac.mu.Unlock()
  2123. // Make sure that library is not calling push with nil function,
  2124. // since this is used to notify the dispatcher that it should stop.
  2125. if !close && f == nil {
  2126. panic("pushing a nil callback")
  2127. }
  2128. cb := &asyncCB{f: f}
  2129. if ac.tail != nil {
  2130. ac.tail.next = cb
  2131. } else {
  2132. ac.head = cb
  2133. }
  2134. ac.tail = cb
  2135. if close {
  2136. ac.cond.Broadcast()
  2137. } else {
  2138. ac.cond.Signal()
  2139. }
  2140. }
  2141. // readLoop() will sit on the socket reading and processing the
  2142. // protocol from the server. It will dispatch appropriately based
  2143. // on the op type.
  2144. func (nc *Conn) readLoop() {
  2145. // Release the wait group on exit
  2146. defer nc.wg.Done()
  2147. // Create a parseState if needed.
  2148. nc.mu.Lock()
  2149. if nc.ps == nil {
  2150. nc.ps = &parseState{}
  2151. }
  2152. conn := nc.conn
  2153. br := nc.br
  2154. nc.mu.Unlock()
  2155. if conn == nil {
  2156. return
  2157. }
  2158. for {
  2159. buf, err := br.Read()
  2160. if err == nil {
  2161. err = nc.parse(buf)
  2162. }
  2163. if err != nil {
  2164. nc.processOpErr(err)
  2165. break
  2166. }
  2167. }
  2168. // Clear the parseState here..
  2169. nc.mu.Lock()
  2170. nc.ps = nil
  2171. nc.mu.Unlock()
  2172. }
  2173. // waitForMsgs waits on the conditional shared with readLoop and processMsg.
  2174. // It is used to deliver messages to asynchronous subscribers.
  2175. func (nc *Conn) waitForMsgs(s *Subscription) {
  2176. var closed bool
  2177. var delivered, max uint64
  2178. // Used to account for adjustments to sub.pBytes when we wrap back around.
  2179. msgLen := -1
  2180. for {
  2181. s.mu.Lock()
  2182. // Do accounting for last msg delivered here so we only lock once
  2183. // and drain state trips after callback has returned.
  2184. if msgLen >= 0 {
  2185. s.pMsgs--
  2186. s.pBytes -= msgLen
  2187. msgLen = -1
  2188. }
  2189. if s.pHead == nil && !s.closed {
  2190. s.pCond.Wait()
  2191. }
  2192. // Pop the msg off the list
  2193. m := s.pHead
  2194. if m != nil {
  2195. s.pHead = m.next
  2196. if s.pHead == nil {
  2197. s.pTail = nil
  2198. }
  2199. if m.barrier != nil {
  2200. s.mu.Unlock()
  2201. if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
  2202. m.barrier.f()
  2203. }
  2204. continue
  2205. }
  2206. msgLen = len(m.Data)
  2207. }
  2208. mcb := s.mcb
  2209. max = s.max
  2210. closed = s.closed
  2211. if !s.closed {
  2212. s.delivered++
  2213. delivered = s.delivered
  2214. if s.jsi != nil && s.jsi.fc && len(s.jsi.fcs) > 0 {
  2215. s.checkForFlowControlResponse(delivered)
  2216. }
  2217. }
  2218. s.mu.Unlock()
  2219. if closed {
  2220. break
  2221. }
  2222. // Deliver the message.
  2223. if m != nil && (max == 0 || delivered <= max) {
  2224. mcb(m)
  2225. }
  2226. // If we have hit the max for delivered msgs, remove sub.
  2227. if max > 0 && delivered >= max {
  2228. nc.mu.Lock()
  2229. nc.removeSub(s)
  2230. nc.mu.Unlock()
  2231. break
  2232. }
  2233. }
  2234. // Check for barrier messages
  2235. s.mu.Lock()
  2236. for m := s.pHead; m != nil; m = s.pHead {
  2237. if m.barrier != nil {
  2238. s.mu.Unlock()
  2239. if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
  2240. m.barrier.f()
  2241. }
  2242. s.mu.Lock()
  2243. }
  2244. s.pHead = m.next
  2245. }
  2246. s.mu.Unlock()
  2247. }
  2248. // processMsg is called by parse and will place the msg on the
  2249. // appropriate channel/pending queue for processing. If the channel is full,
  2250. // or the pending queue is over the pending limits, the connection is
  2251. // considered a slow consumer.
  2252. func (nc *Conn) processMsg(data []byte) {
  2253. // Stats
  2254. atomic.AddUint64(&nc.InMsgs, 1)
  2255. atomic.AddUint64(&nc.InBytes, uint64(len(data)))
  2256. // Don't lock the connection to avoid server cutting us off if the
  2257. // flusher is holding the connection lock, trying to send to the server
  2258. // that is itself trying to send data to us.
  2259. nc.subsMu.RLock()
  2260. sub := nc.subs[nc.ps.ma.sid]
  2261. nc.subsMu.RUnlock()
  2262. if sub == nil {
  2263. return
  2264. }
  2265. // Copy them into string
  2266. subj := string(nc.ps.ma.subject)
  2267. reply := string(nc.ps.ma.reply)
  2268. // Doing message create outside of the sub's lock to reduce contention.
  2269. // It's possible that we end-up not using the message, but that's ok.
  2270. // FIXME(dlc): Need to copy, should/can do COW?
  2271. msgPayload := make([]byte, len(data))
  2272. copy(msgPayload, data)
  2273. // Check if we have headers encoded here.
  2274. var h Header
  2275. var err error
  2276. var ctrlMsg bool
  2277. var hasFC bool
  2278. var hasHBs bool
  2279. if nc.ps.ma.hdr > 0 {
  2280. hbuf := msgPayload[:nc.ps.ma.hdr]
  2281. msgPayload = msgPayload[nc.ps.ma.hdr:]
  2282. h, err = decodeHeadersMsg(hbuf)
  2283. if err != nil {
  2284. // We will pass the message through but send async error.
  2285. nc.mu.Lock()
  2286. nc.err = ErrBadHeaderMsg
  2287. if nc.Opts.AsyncErrorCB != nil {
  2288. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrBadHeaderMsg) })
  2289. }
  2290. nc.mu.Unlock()
  2291. }
  2292. }
  2293. // FIXME(dlc): Should we recycle these containers?
  2294. m := &Msg{Header: h, Data: msgPayload, Subject: subj, Reply: reply, Sub: sub}
  2295. sub.mu.Lock()
  2296. // Check if closed.
  2297. if sub.closed {
  2298. sub.mu.Unlock()
  2299. return
  2300. }
  2301. // Skip flow control messages in case of using a JetStream context.
  2302. jsi := sub.jsi
  2303. if jsi != nil {
  2304. ctrlMsg, hasHBs, hasFC = isControlMessage(m), jsi.hbs, jsi.fc
  2305. }
  2306. // Skip processing if this is a control message.
  2307. if !ctrlMsg {
  2308. // Subscription internal stats (applicable only for non ChanSubscription's)
  2309. if sub.typ != ChanSubscription {
  2310. sub.pMsgs++
  2311. if sub.pMsgs > sub.pMsgsMax {
  2312. sub.pMsgsMax = sub.pMsgs
  2313. }
  2314. sub.pBytes += len(m.Data)
  2315. if sub.pBytes > sub.pBytesMax {
  2316. sub.pBytesMax = sub.pBytes
  2317. }
  2318. // Check for a Slow Consumer
  2319. if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) ||
  2320. (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) {
  2321. goto slowConsumer
  2322. }
  2323. }
  2324. // We have two modes of delivery. One is the channel, used by channel
  2325. // subscribers and syncSubscribers, the other is a linked list for async.
  2326. if sub.mch != nil {
  2327. select {
  2328. case sub.mch <- m:
  2329. default:
  2330. goto slowConsumer
  2331. }
  2332. } else {
  2333. // Push onto the async pList
  2334. if sub.pHead == nil {
  2335. sub.pHead = m
  2336. sub.pTail = m
  2337. if sub.pCond != nil {
  2338. sub.pCond.Signal()
  2339. }
  2340. } else {
  2341. sub.pTail.next = m
  2342. sub.pTail = m
  2343. }
  2344. }
  2345. if jsi != nil && hasHBs {
  2346. // Store the ACK metadata from the message to
  2347. // compare later on with the received heartbeat.
  2348. jsi.trackSequences(m.Reply)
  2349. }
  2350. } else if hasFC && m.Reply != _EMPTY_ {
  2351. // This is a flow control message.
  2352. // If we have no pending, go ahead and send in place.
  2353. if sub.pMsgs == 0 {
  2354. nc.Publish(m.Reply, nil)
  2355. } else {
  2356. // Schedule a reply after the previous message is delivered.
  2357. jsi.scheduleFlowControlResponse(sub.delivered+uint64(sub.pMsgs), m.Reply)
  2358. }
  2359. }
  2360. // Clear SlowConsumer status.
  2361. sub.sc = false
  2362. sub.mu.Unlock()
  2363. // Handle control heartbeat messages.
  2364. if ctrlMsg && hasHBs && m.Reply == _EMPTY_ {
  2365. nc.processSequenceMismatch(m, sub, jsi)
  2366. }
  2367. return
  2368. slowConsumer:
  2369. sub.dropped++
  2370. sc := !sub.sc
  2371. sub.sc = true
  2372. // Undo stats from above
  2373. if sub.typ != ChanSubscription {
  2374. sub.pMsgs--
  2375. sub.pBytes -= len(m.Data)
  2376. }
  2377. sub.mu.Unlock()
  2378. if sc {
  2379. // Now we need connection's lock and we may end-up in the situation
  2380. // that we were trying to avoid, except that in this case, the client
  2381. // is already experiencing client-side slow consumer situation.
  2382. nc.mu.Lock()
  2383. nc.err = ErrSlowConsumer
  2384. if nc.Opts.AsyncErrorCB != nil {
  2385. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrSlowConsumer) })
  2386. }
  2387. nc.mu.Unlock()
  2388. }
  2389. }
  2390. // processPermissionsViolation is called when the server signals a subject
  2391. // permissions violation on either publish or subscribe.
  2392. func (nc *Conn) processPermissionsViolation(err string) {
  2393. nc.mu.Lock()
  2394. // create error here so we can pass it as a closure to the async cb dispatcher.
  2395. e := errors.New("nats: " + err)
  2396. nc.err = e
  2397. if nc.Opts.AsyncErrorCB != nil {
  2398. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) })
  2399. }
  2400. nc.mu.Unlock()
  2401. }
  2402. // processAuthError generally processing for auth errors. We want to do retries
  2403. // unless we get the same error again. This allows us for instance to swap credentials
  2404. // and have the app reconnect, but if nothing is changing we should bail.
  2405. // This function will return true if the connection should be closed, false otherwise.
  2406. // Connection lock is held on entry
  2407. func (nc *Conn) processAuthError(err error) bool {
  2408. nc.err = err
  2409. if !nc.initc && nc.Opts.AsyncErrorCB != nil {
  2410. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2411. }
  2412. // We should give up if we tried twice on this server and got the
  2413. // same error.
  2414. if nc.current.lastErr == err {
  2415. nc.ar = true
  2416. } else {
  2417. nc.current.lastErr = err
  2418. }
  2419. return nc.ar
  2420. }
  2421. // flusher is a separate Go routine that will process flush requests for the write
  2422. // bufio. This allows coalescing of writes to the underlying socket.
  2423. func (nc *Conn) flusher() {
  2424. // Release the wait group
  2425. defer nc.wg.Done()
  2426. // snapshot the bw and conn since they can change from underneath of us.
  2427. nc.mu.Lock()
  2428. bw := nc.bw
  2429. conn := nc.conn
  2430. fch := nc.fch
  2431. nc.mu.Unlock()
  2432. if conn == nil || bw == nil {
  2433. return
  2434. }
  2435. for {
  2436. if _, ok := <-fch; !ok {
  2437. return
  2438. }
  2439. nc.mu.Lock()
  2440. // Check to see if we should bail out.
  2441. if !nc.isConnected() || nc.isConnecting() || conn != nc.conn {
  2442. nc.mu.Unlock()
  2443. return
  2444. }
  2445. if bw.buffered() > 0 {
  2446. if err := bw.flush(); err != nil {
  2447. if nc.err == nil {
  2448. nc.err = err
  2449. }
  2450. }
  2451. }
  2452. nc.mu.Unlock()
  2453. }
  2454. }
  2455. // processPing will send an immediate pong protocol response to the
  2456. // server. The server uses this mechanism to detect dead clients.
  2457. func (nc *Conn) processPing() {
  2458. nc.sendProto(pongProto)
  2459. }
  2460. // processPong is used to process responses to the client's ping
  2461. // messages. We use pings for the flush mechanism as well.
  2462. func (nc *Conn) processPong() {
  2463. var ch chan struct{}
  2464. nc.mu.Lock()
  2465. if len(nc.pongs) > 0 {
  2466. ch = nc.pongs[0]
  2467. nc.pongs = append(nc.pongs[:0], nc.pongs[1:]...)
  2468. }
  2469. nc.pout = 0
  2470. nc.mu.Unlock()
  2471. if ch != nil {
  2472. ch <- struct{}{}
  2473. }
  2474. }
  2475. // processOK is a placeholder for processing OK messages.
  2476. func (nc *Conn) processOK() {
  2477. // do nothing
  2478. }
  2479. // processInfo is used to parse the info messages sent
  2480. // from the server.
  2481. // This function may update the server pool.
  2482. func (nc *Conn) processInfo(info string) error {
  2483. if info == _EMPTY_ {
  2484. return nil
  2485. }
  2486. ncInfo := serverInfo{}
  2487. if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
  2488. return err
  2489. }
  2490. // Copy content into connection's info structure.
  2491. nc.info = ncInfo
  2492. // The array could be empty/not present on initial connect,
  2493. // if advertise is disabled on that server, or servers that
  2494. // did not include themselves in the async INFO protocol.
  2495. // If empty, do not remove the implicit servers from the pool.
  2496. if len(nc.info.ConnectURLs) == 0 {
  2497. if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil {
  2498. nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) })
  2499. }
  2500. return nil
  2501. }
  2502. // Note about pool randomization: when the pool was first created,
  2503. // it was randomized (if allowed). We keep the order the same (removing
  2504. // implicit servers that are no longer sent to us). New URLs are sent
  2505. // to us in no specific order so don't need extra randomization.
  2506. hasNew := false
  2507. // This is what we got from the server we are connected to.
  2508. urls := nc.info.ConnectURLs
  2509. // Transform that to a map for easy lookups
  2510. tmp := make(map[string]struct{}, len(urls))
  2511. for _, curl := range urls {
  2512. tmp[curl] = struct{}{}
  2513. }
  2514. // Walk the pool and removed the implicit servers that are no longer in the
  2515. // given array/map
  2516. sp := nc.srvPool
  2517. for i := 0; i < len(sp); i++ {
  2518. srv := sp[i]
  2519. curl := srv.url.Host
  2520. // Check if this URL is in the INFO protocol
  2521. _, inInfo := tmp[curl]
  2522. // Remove from the temp map so that at the end we are left with only
  2523. // new (or restarted) servers that need to be added to the pool.
  2524. delete(tmp, curl)
  2525. // Keep servers that were set through Options, but also the one that
  2526. // we are currently connected to (even if it is a discovered server).
  2527. if !srv.isImplicit || srv.url == nc.current.url {
  2528. continue
  2529. }
  2530. if !inInfo {
  2531. // Remove from server pool. Keep current order.
  2532. copy(sp[i:], sp[i+1:])
  2533. nc.srvPool = sp[:len(sp)-1]
  2534. sp = nc.srvPool
  2535. i--
  2536. }
  2537. }
  2538. // Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
  2539. saveTLS := nc.current != nil && !hostIsIP(nc.current.url)
  2540. // If there are any left in the tmp map, these are new (or restarted) servers
  2541. // and need to be added to the pool.
  2542. for curl := range tmp {
  2543. // Before adding, check if this is a new (as in never seen) URL.
  2544. // This is used to figure out if we invoke the DiscoveredServersCB
  2545. if _, present := nc.urls[curl]; !present {
  2546. hasNew = true
  2547. }
  2548. nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
  2549. }
  2550. if hasNew {
  2551. // Randomize the pool if allowed but leave the first URL in place.
  2552. if !nc.Opts.NoRandomize {
  2553. nc.shufflePool(1)
  2554. }
  2555. if !nc.initc && nc.Opts.DiscoveredServersCB != nil {
  2556. nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
  2557. }
  2558. }
  2559. if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil {
  2560. nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) })
  2561. }
  2562. return nil
  2563. }
  2564. // processAsyncInfo does the same than processInfo, but is called
  2565. // from the parser. Calls processInfo under connection's lock
  2566. // protection.
  2567. func (nc *Conn) processAsyncInfo(info []byte) {
  2568. nc.mu.Lock()
  2569. // Ignore errors, we will simply not update the server pool...
  2570. nc.processInfo(string(info))
  2571. nc.mu.Unlock()
  2572. }
  2573. // LastError reports the last error encountered via the connection.
  2574. // It can be used reliably within ClosedCB in order to find out reason
  2575. // why connection was closed for example.
  2576. func (nc *Conn) LastError() error {
  2577. if nc == nil {
  2578. return ErrInvalidConnection
  2579. }
  2580. nc.mu.RLock()
  2581. err := nc.err
  2582. nc.mu.RUnlock()
  2583. return err
  2584. }
  2585. // Check if the given error string is an auth error, and if so returns
  2586. // the corresponding ErrXXX error, nil otherwise
  2587. func checkAuthError(e string) error {
  2588. if strings.HasPrefix(e, AUTHORIZATION_ERR) {
  2589. return ErrAuthorization
  2590. }
  2591. if strings.HasPrefix(e, AUTHENTICATION_EXPIRED_ERR) {
  2592. return ErrAuthExpired
  2593. }
  2594. if strings.HasPrefix(e, AUTHENTICATION_REVOKED_ERR) {
  2595. return ErrAuthRevoked
  2596. }
  2597. if strings.HasPrefix(e, ACCOUNT_AUTHENTICATION_EXPIRED_ERR) {
  2598. return ErrAccountAuthExpired
  2599. }
  2600. return nil
  2601. }
  2602. // processErr processes any error messages from the server and
  2603. // sets the connection's lastError.
  2604. func (nc *Conn) processErr(ie string) {
  2605. // Trim, remove quotes
  2606. ne := normalizeErr(ie)
  2607. // convert to lower case.
  2608. e := strings.ToLower(ne)
  2609. close := false
  2610. // FIXME(dlc) - process Slow Consumer signals special.
  2611. if e == STALE_CONNECTION {
  2612. nc.processOpErr(ErrStaleConnection)
  2613. } else if strings.HasPrefix(e, PERMISSIONS_ERR) {
  2614. nc.processPermissionsViolation(ne)
  2615. } else if authErr := checkAuthError(e); authErr != nil {
  2616. nc.mu.Lock()
  2617. close = nc.processAuthError(authErr)
  2618. nc.mu.Unlock()
  2619. } else {
  2620. close = true
  2621. nc.mu.Lock()
  2622. nc.err = errors.New("nats: " + ne)
  2623. nc.mu.Unlock()
  2624. }
  2625. if close {
  2626. nc.close(CLOSED, true, nil)
  2627. }
  2628. }
  2629. // kickFlusher will send a bool on a channel to kick the
  2630. // flush Go routine to flush data to the server.
  2631. func (nc *Conn) kickFlusher() {
  2632. if nc.bw != nil {
  2633. select {
  2634. case nc.fch <- struct{}{}:
  2635. default:
  2636. }
  2637. }
  2638. }
  2639. // Publish publishes the data argument to the given subject. The data
  2640. // argument is left untouched and needs to be correctly interpreted on
  2641. // the receiver.
  2642. func (nc *Conn) Publish(subj string, data []byte) error {
  2643. return nc.publish(subj, _EMPTY_, nil, data)
  2644. }
  2645. // Header represents the optional Header for a NATS message,
  2646. // based on the implementation of http.Header.
  2647. type Header map[string][]string
  2648. // Add adds the key, value pair to the header. It is case-sensitive
  2649. // and appends to any existing values associated with key.
  2650. func (h Header) Add(key, value string) {
  2651. h[key] = append(h[key], value)
  2652. }
  2653. // Set sets the header entries associated with key to the single
  2654. // element value. It is case-sensitive and replaces any existing
  2655. // values associated with key.
  2656. func (h Header) Set(key, value string) {
  2657. h[key] = []string{value}
  2658. }
  2659. // Get gets the first value associated with the given key.
  2660. // It is case-sensitive.
  2661. func (h Header) Get(key string) string {
  2662. if h == nil {
  2663. return _EMPTY_
  2664. }
  2665. if v := h[key]; v != nil {
  2666. return v[0]
  2667. }
  2668. return _EMPTY_
  2669. }
  2670. // Values returns all values associated with the given key.
  2671. // It is case-sensitive.
  2672. func (h Header) Values(key string) []string {
  2673. return h[key]
  2674. }
  2675. // Del deletes the values associated with a key.
  2676. // It is case-sensitive.
  2677. func (h Header) Del(key string) {
  2678. delete(h, key)
  2679. }
  2680. // NewMsg creates a message for publishing that will use headers.
  2681. func NewMsg(subject string) *Msg {
  2682. return &Msg{
  2683. Subject: subject,
  2684. Header: make(Header),
  2685. }
  2686. }
  2687. const (
  2688. hdrLine = "NATS/1.0\r\n"
  2689. crlf = "\r\n"
  2690. hdrPreEnd = len(hdrLine) - len(crlf)
  2691. statusHdr = "Status"
  2692. descrHdr = "Description"
  2693. lastConsumerSeqHdr = "Nats-Last-Consumer"
  2694. lastStreamSeqHdr = "Nats-Last-Stream"
  2695. noResponders = "503"
  2696. noMessages = "404"
  2697. controlMsg = "100"
  2698. statusLen = 3 // e.g. 20x, 40x, 50x
  2699. )
  2700. // decodeHeadersMsg will decode and headers.
  2701. func decodeHeadersMsg(data []byte) (Header, error) {
  2702. tp := textproto.NewReader(bufio.NewReader(bytes.NewReader(data)))
  2703. l, err := tp.ReadLine()
  2704. if err != nil || len(l) < hdrPreEnd || l[:hdrPreEnd] != hdrLine[:hdrPreEnd] {
  2705. return nil, ErrBadHeaderMsg
  2706. }
  2707. mh, err := readMIMEHeader(tp)
  2708. if err != nil {
  2709. return nil, err
  2710. }
  2711. // Check if we have an inlined status.
  2712. if len(l) > hdrPreEnd {
  2713. var description string
  2714. status := strings.TrimSpace(l[hdrPreEnd:])
  2715. if len(status) != statusLen {
  2716. description = strings.TrimSpace(status[statusLen:])
  2717. status = status[:statusLen]
  2718. }
  2719. mh.Add(statusHdr, status)
  2720. if len(description) > 0 {
  2721. mh.Add(descrHdr, description)
  2722. }
  2723. }
  2724. return Header(mh), nil
  2725. }
  2726. // readMIMEHeader returns a MIMEHeader that preserves the
  2727. // original case of the MIME header, based on the implementation
  2728. // of textproto.ReadMIMEHeader.
  2729. //
  2730. // https://golang.org/pkg/net/textproto/#Reader.ReadMIMEHeader
  2731. func readMIMEHeader(tp *textproto.Reader) (textproto.MIMEHeader, error) {
  2732. var (
  2733. m = make(textproto.MIMEHeader)
  2734. strs []string
  2735. )
  2736. for {
  2737. kv, err := tp.ReadLine()
  2738. if len(kv) == 0 {
  2739. return m, err
  2740. }
  2741. // Process key fetching original case.
  2742. i := bytes.IndexByte([]byte(kv), ':')
  2743. if i < 0 {
  2744. return nil, ErrBadHeaderMsg
  2745. }
  2746. key := kv[:i]
  2747. if key == "" {
  2748. // Skip empty keys.
  2749. continue
  2750. }
  2751. i++
  2752. for i < len(kv) && (kv[i] == ' ' || kv[i] == '\t') {
  2753. i++
  2754. }
  2755. value := string(kv[i:])
  2756. vv := m[key]
  2757. if vv == nil && len(strs) > 0 {
  2758. // Single value header.
  2759. vv, strs = strs[:1:1], strs[1:]
  2760. vv[0] = value
  2761. m[key] = vv
  2762. } else {
  2763. // Multi value header.
  2764. m[key] = append(vv, value)
  2765. }
  2766. if err != nil {
  2767. return m, err
  2768. }
  2769. }
  2770. }
  2771. // PublishMsg publishes the Msg structure, which includes the
  2772. // Subject, an optional Reply and an optional Data field.
  2773. func (nc *Conn) PublishMsg(m *Msg) error {
  2774. if m == nil {
  2775. return ErrInvalidMsg
  2776. }
  2777. var hdr []byte
  2778. var err error
  2779. if len(m.Header) > 0 {
  2780. if !nc.info.Headers {
  2781. return ErrHeadersNotSupported
  2782. }
  2783. hdr, err = m.headerBytes()
  2784. if err != nil {
  2785. return err
  2786. }
  2787. }
  2788. return nc.publish(m.Subject, m.Reply, hdr, m.Data)
  2789. }
  2790. // PublishRequest will perform a Publish() expecting a response on the
  2791. // reply subject. Use Request() for automatically waiting for a response
  2792. // inline.
  2793. func (nc *Conn) PublishRequest(subj, reply string, data []byte) error {
  2794. return nc.publish(subj, reply, nil, data)
  2795. }
  2796. // Used for handrolled itoa
  2797. const digits = "0123456789"
  2798. // publish is the internal function to publish messages to a nats-server.
  2799. // Sends a protocol data message by queuing into the bufio writer
  2800. // and kicking the flush go routine. These writes should be protected.
  2801. func (nc *Conn) publish(subj, reply string, hdr, data []byte) error {
  2802. if nc == nil {
  2803. return ErrInvalidConnection
  2804. }
  2805. if subj == "" {
  2806. return ErrBadSubject
  2807. }
  2808. nc.mu.Lock()
  2809. if nc.isClosed() {
  2810. nc.mu.Unlock()
  2811. return ErrConnectionClosed
  2812. }
  2813. if nc.isDrainingPubs() {
  2814. nc.mu.Unlock()
  2815. return ErrConnectionDraining
  2816. }
  2817. // Proactively reject payloads over the threshold set by server.
  2818. msgSize := int64(len(data) + len(hdr))
  2819. // Skip this check if we are not yet connected (RetryOnFailedConnect)
  2820. if !nc.initc && msgSize > nc.info.MaxPayload {
  2821. nc.mu.Unlock()
  2822. return ErrMaxPayload
  2823. }
  2824. // Check if we are reconnecting, and if so check if
  2825. // we have exceeded our reconnect outbound buffer limits.
  2826. if nc.bw.atLimitIfUsingPending() {
  2827. nc.mu.Unlock()
  2828. return ErrReconnectBufExceeded
  2829. }
  2830. var mh []byte
  2831. if hdr != nil {
  2832. mh = nc.scratch[:len(_HPUB_P_)]
  2833. } else {
  2834. mh = nc.scratch[1:len(_HPUB_P_)]
  2835. }
  2836. mh = append(mh, subj...)
  2837. mh = append(mh, ' ')
  2838. if reply != "" {
  2839. mh = append(mh, reply...)
  2840. mh = append(mh, ' ')
  2841. }
  2842. // We could be smarter here, but simple loop is ok,
  2843. // just avoid strconv in fast path.
  2844. // FIXME(dlc) - Find a better way here.
  2845. // msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
  2846. // go 1.14 some values strconv faster, may be able to switch over.
  2847. var b [12]byte
  2848. var i = len(b)
  2849. if hdr != nil {
  2850. if len(hdr) > 0 {
  2851. for l := len(hdr); l > 0; l /= 10 {
  2852. i--
  2853. b[i] = digits[l%10]
  2854. }
  2855. } else {
  2856. i--
  2857. b[i] = digits[0]
  2858. }
  2859. mh = append(mh, b[i:]...)
  2860. mh = append(mh, ' ')
  2861. // reset for below.
  2862. i = len(b)
  2863. }
  2864. if msgSize > 0 {
  2865. for l := msgSize; l > 0; l /= 10 {
  2866. i--
  2867. b[i] = digits[l%10]
  2868. }
  2869. } else {
  2870. i--
  2871. b[i] = digits[0]
  2872. }
  2873. mh = append(mh, b[i:]...)
  2874. mh = append(mh, _CRLF_...)
  2875. if err := nc.bw.appendBufs(mh, hdr, data, _CRLF_BYTES_); err != nil {
  2876. nc.mu.Unlock()
  2877. return err
  2878. }
  2879. nc.OutMsgs++
  2880. nc.OutBytes += uint64(len(data) + len(hdr))
  2881. if len(nc.fch) == 0 {
  2882. nc.kickFlusher()
  2883. }
  2884. nc.mu.Unlock()
  2885. return nil
  2886. }
  2887. // respHandler is the global response handler. It will look up
  2888. // the appropriate channel based on the last token and place
  2889. // the message on the channel if possible.
  2890. func (nc *Conn) respHandler(m *Msg) {
  2891. nc.mu.Lock()
  2892. // Just return if closed.
  2893. if nc.isClosed() {
  2894. nc.mu.Unlock()
  2895. return
  2896. }
  2897. var mch chan *Msg
  2898. // Grab mch
  2899. rt := nc.respToken(m.Subject)
  2900. if rt != _EMPTY_ {
  2901. mch = nc.respMap[rt]
  2902. // Delete the key regardless, one response only.
  2903. delete(nc.respMap, rt)
  2904. } else if len(nc.respMap) == 1 {
  2905. // If the server has rewritten the subject, the response token (rt)
  2906. // will not match (could be the case with JetStream). If that is the
  2907. // case and there is a single entry, use that.
  2908. for k, v := range nc.respMap {
  2909. mch = v
  2910. delete(nc.respMap, k)
  2911. break
  2912. }
  2913. }
  2914. nc.mu.Unlock()
  2915. // Don't block, let Request timeout instead, mch is
  2916. // buffered and we should delete the key before a
  2917. // second response is processed.
  2918. select {
  2919. case mch <- m:
  2920. default:
  2921. return
  2922. }
  2923. }
  2924. // Helper to setup and send new request style requests. Return the chan to receive the response.
  2925. func (nc *Conn) createNewRequestAndSend(subj string, hdr, data []byte) (chan *Msg, string, error) {
  2926. nc.mu.Lock()
  2927. // Do setup for the new style if needed.
  2928. if nc.respMap == nil {
  2929. nc.initNewResp()
  2930. }
  2931. // Create new literal Inbox and map to a chan msg.
  2932. mch := make(chan *Msg, RequestChanLen)
  2933. respInbox := nc.newRespInbox()
  2934. token := respInbox[respInboxPrefixLen:]
  2935. nc.respMap[token] = mch
  2936. if nc.respMux == nil {
  2937. // Create the response subscription we will use for all new style responses.
  2938. // This will be on an _INBOX with an additional terminal token. The subscription
  2939. // will be on a wildcard.
  2940. s, err := nc.subscribeLocked(nc.respSub, _EMPTY_, nc.respHandler, nil, false, nil)
  2941. if err != nil {
  2942. nc.mu.Unlock()
  2943. return nil, token, err
  2944. }
  2945. nc.respScanf = strings.Replace(nc.respSub, "*", "%s", -1)
  2946. nc.respMux = s
  2947. }
  2948. nc.mu.Unlock()
  2949. if err := nc.publish(subj, respInbox, hdr, data); err != nil {
  2950. return nil, token, err
  2951. }
  2952. return mch, token, nil
  2953. }
  2954. // RequestMsg will send a request payload including optional headers and deliver
  2955. // the response message, or an error, including a timeout if no message was received properly.
  2956. func (nc *Conn) RequestMsg(msg *Msg, timeout time.Duration) (*Msg, error) {
  2957. var hdr []byte
  2958. var err error
  2959. if len(msg.Header) > 0 {
  2960. if !nc.info.Headers {
  2961. return nil, ErrHeadersNotSupported
  2962. }
  2963. hdr, err = msg.headerBytes()
  2964. if err != nil {
  2965. return nil, err
  2966. }
  2967. }
  2968. return nc.request(msg.Subject, hdr, msg.Data, timeout)
  2969. }
  2970. // Request will send a request payload and deliver the response message,
  2971. // or an error, including a timeout if no message was received properly.
  2972. func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
  2973. return nc.request(subj, nil, data, timeout)
  2974. }
  2975. func (nc *Conn) useOldRequestStyle() bool {
  2976. nc.mu.RLock()
  2977. r := nc.Opts.UseOldRequestStyle
  2978. nc.mu.RUnlock()
  2979. return r
  2980. }
  2981. func (nc *Conn) request(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  2982. if nc == nil {
  2983. return nil, ErrInvalidConnection
  2984. }
  2985. var m *Msg
  2986. var err error
  2987. if nc.useOldRequestStyle() {
  2988. m, err = nc.oldRequest(subj, hdr, data, timeout)
  2989. } else {
  2990. m, err = nc.newRequest(subj, hdr, data, timeout)
  2991. }
  2992. // Check for no responder status.
  2993. if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
  2994. m, err = nil, ErrNoResponders
  2995. }
  2996. return m, err
  2997. }
  2998. func (nc *Conn) newRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  2999. mch, token, err := nc.createNewRequestAndSend(subj, hdr, data)
  3000. if err != nil {
  3001. return nil, err
  3002. }
  3003. t := globalTimerPool.Get(timeout)
  3004. defer globalTimerPool.Put(t)
  3005. var ok bool
  3006. var msg *Msg
  3007. select {
  3008. case msg, ok = <-mch:
  3009. if !ok {
  3010. return nil, ErrConnectionClosed
  3011. }
  3012. case <-t.C:
  3013. nc.mu.Lock()
  3014. delete(nc.respMap, token)
  3015. nc.mu.Unlock()
  3016. return nil, ErrTimeout
  3017. }
  3018. return msg, nil
  3019. }
  3020. // oldRequest will create an Inbox and perform a Request() call
  3021. // with the Inbox reply and return the first reply received.
  3022. // This is optimized for the case of multiple responses.
  3023. func (nc *Conn) oldRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  3024. inbox := NewInbox()
  3025. ch := make(chan *Msg, RequestChanLen)
  3026. s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true, nil)
  3027. if err != nil {
  3028. return nil, err
  3029. }
  3030. s.AutoUnsubscribe(1)
  3031. defer s.Unsubscribe()
  3032. err = nc.publish(subj, inbox, hdr, data)
  3033. if err != nil {
  3034. return nil, err
  3035. }
  3036. return s.NextMsg(timeout)
  3037. }
  3038. // InboxPrefix is the prefix for all inbox subjects.
  3039. const (
  3040. InboxPrefix = "_INBOX."
  3041. inboxPrefixLen = len(InboxPrefix)
  3042. respInboxPrefixLen = inboxPrefixLen + nuidSize + 1
  3043. replySuffixLen = 8 // Gives us 62^8
  3044. rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  3045. base = 62
  3046. )
  3047. // NewInbox will return an inbox string which can be used for directed replies from
  3048. // subscribers. These are guaranteed to be unique, but can be shared and subscribed
  3049. // to by others.
  3050. func NewInbox() string {
  3051. var b [inboxPrefixLen + nuidSize]byte
  3052. pres := b[:inboxPrefixLen]
  3053. copy(pres, InboxPrefix)
  3054. ns := b[inboxPrefixLen:]
  3055. copy(ns, nuid.Next())
  3056. return string(b[:])
  3057. }
  3058. // Function to init new response structures.
  3059. func (nc *Conn) initNewResp() {
  3060. // _INBOX wildcard
  3061. nc.respSub = fmt.Sprintf("%s.*", NewInbox())
  3062. nc.respMap = make(map[string]chan *Msg)
  3063. nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
  3064. }
  3065. // newRespInbox creates a new literal response subject
  3066. // that will trigger the mux subscription handler.
  3067. // Lock should be held.
  3068. func (nc *Conn) newRespInbox() string {
  3069. if nc.respMap == nil {
  3070. nc.initNewResp()
  3071. }
  3072. var b [respInboxPrefixLen + replySuffixLen]byte
  3073. pres := b[:respInboxPrefixLen]
  3074. copy(pres, nc.respSub)
  3075. rn := nc.respRand.Int63()
  3076. for i, l := respInboxPrefixLen, rn; i < len(b); i++ {
  3077. b[i] = rdigits[l%base]
  3078. l /= base
  3079. }
  3080. return string(b[:])
  3081. }
  3082. // NewRespInbox is the new format used for _INBOX.
  3083. func (nc *Conn) NewRespInbox() string {
  3084. nc.mu.Lock()
  3085. s := nc.newRespInbox()
  3086. nc.mu.Unlock()
  3087. return s
  3088. }
  3089. // respToken will return the last token of a literal response inbox
  3090. // which we use for the message channel lookup. This needs to do a
  3091. // scan to protect itself against the server changing the subject.
  3092. // Lock should be held.
  3093. func (nc *Conn) respToken(respInbox string) string {
  3094. var token string
  3095. n, err := fmt.Sscanf(respInbox, nc.respScanf, &token)
  3096. if err != nil || n != 1 {
  3097. return ""
  3098. }
  3099. return token
  3100. }
  3101. // Subscribe will express interest in the given subject. The subject
  3102. // can have wildcards (partial:*, full:>). Messages will be delivered
  3103. // to the associated MsgHandler.
  3104. func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) {
  3105. return nc.subscribe(subj, _EMPTY_, cb, nil, false, nil)
  3106. }
  3107. // ChanSubscribe will express interest in the given subject and place
  3108. // all messages received on the channel.
  3109. // You should not close the channel until sub.Unsubscribe() has been called.
  3110. func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) {
  3111. return nc.subscribe(subj, _EMPTY_, nil, ch, false, nil)
  3112. }
  3113. // ChanQueueSubscribe will express interest in the given subject.
  3114. // All subscribers with the same queue name will form the queue group
  3115. // and only one member of the group will be selected to receive any given message,
  3116. // which will be placed on the channel.
  3117. // You should not close the channel until sub.Unsubscribe() has been called.
  3118. // Note: This is the same than QueueSubscribeSyncWithChan.
  3119. func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) {
  3120. return nc.subscribe(subj, group, nil, ch, false, nil)
  3121. }
  3122. // SubscribeSync will express interest on the given subject. Messages will
  3123. // be received synchronously using Subscription.NextMsg().
  3124. func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) {
  3125. if nc == nil {
  3126. return nil, ErrInvalidConnection
  3127. }
  3128. mch := make(chan *Msg, nc.Opts.SubChanLen)
  3129. return nc.subscribe(subj, _EMPTY_, nil, mch, true, nil)
  3130. }
  3131. // QueueSubscribe creates an asynchronous queue subscriber on the given subject.
  3132. // All subscribers with the same queue name will form the queue group and
  3133. // only one member of the group will be selected to receive any given
  3134. // message asynchronously.
  3135. func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
  3136. return nc.subscribe(subj, queue, cb, nil, false, nil)
  3137. }
  3138. // QueueSubscribeSync creates a synchronous queue subscriber on the given
  3139. // subject. All subscribers with the same queue name will form the queue
  3140. // group and only one member of the group will be selected to receive any
  3141. // given message synchronously using Subscription.NextMsg().
  3142. func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) {
  3143. mch := make(chan *Msg, nc.Opts.SubChanLen)
  3144. return nc.subscribe(subj, queue, nil, mch, true, nil)
  3145. }
  3146. // QueueSubscribeSyncWithChan will express interest in the given subject.
  3147. // All subscribers with the same queue name will form the queue group
  3148. // and only one member of the group will be selected to receive any given message,
  3149. // which will be placed on the channel.
  3150. // You should not close the channel until sub.Unsubscribe() has been called.
  3151. // Note: This is the same than ChanQueueSubscribe.
  3152. func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) {
  3153. return nc.subscribe(subj, queue, nil, ch, false, nil)
  3154. }
  3155. // badSubject will do quick test on whether a subject is acceptable.
  3156. // Spaces are not allowed and all tokens should be > 0 in len.
  3157. func badSubject(subj string) bool {
  3158. if strings.ContainsAny(subj, " \t\r\n") {
  3159. return true
  3160. }
  3161. tokens := strings.Split(subj, ".")
  3162. for _, t := range tokens {
  3163. if len(t) == 0 {
  3164. return true
  3165. }
  3166. }
  3167. return false
  3168. }
  3169. // badQueue will check a queue name for whitespace.
  3170. func badQueue(qname string) bool {
  3171. return strings.ContainsAny(qname, " \t\r\n")
  3172. }
  3173. // subscribe is the internal subscribe function that indicates interest in a subject.
  3174. func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) {
  3175. if nc == nil {
  3176. return nil, ErrInvalidConnection
  3177. }
  3178. nc.mu.Lock()
  3179. defer nc.mu.Unlock()
  3180. return nc.subscribeLocked(subj, queue, cb, ch, isSync, js)
  3181. }
  3182. func (nc *Conn) subscribeLocked(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) {
  3183. if nc == nil {
  3184. return nil, ErrInvalidConnection
  3185. }
  3186. if badSubject(subj) {
  3187. return nil, ErrBadSubject
  3188. }
  3189. if queue != "" && badQueue(queue) {
  3190. return nil, ErrBadQueueName
  3191. }
  3192. // Check for some error conditions.
  3193. if nc.isClosed() {
  3194. return nil, ErrConnectionClosed
  3195. }
  3196. if nc.isDraining() {
  3197. return nil, ErrConnectionDraining
  3198. }
  3199. if cb == nil && ch == nil {
  3200. return nil, ErrBadSubscription
  3201. }
  3202. sub := &Subscription{Subject: subj, Queue: queue, mcb: cb, conn: nc, jsi: js}
  3203. // Set pending limits.
  3204. if ch != nil {
  3205. sub.pMsgsLimit = cap(ch)
  3206. } else {
  3207. sub.pMsgsLimit = DefaultSubPendingMsgsLimit
  3208. }
  3209. sub.pBytesLimit = DefaultSubPendingBytesLimit
  3210. // If we have an async callback, start up a sub specific
  3211. // Go routine to deliver the messages.
  3212. var sr bool
  3213. if cb != nil {
  3214. sub.typ = AsyncSubscription
  3215. sub.pCond = sync.NewCond(&sub.mu)
  3216. sr = true
  3217. } else if !isSync {
  3218. sub.typ = ChanSubscription
  3219. sub.mch = ch
  3220. } else { // Sync Subscription
  3221. sub.typ = SyncSubscription
  3222. sub.mch = ch
  3223. }
  3224. nc.subsMu.Lock()
  3225. nc.ssid++
  3226. sub.sid = nc.ssid
  3227. nc.subs[sub.sid] = sub
  3228. nc.subsMu.Unlock()
  3229. // Let's start the go routine now that it is fully setup and registered.
  3230. if sr {
  3231. go nc.waitForMsgs(sub)
  3232. }
  3233. // We will send these for all subs when we reconnect
  3234. // so that we can suppress here if reconnecting.
  3235. if !nc.isReconnecting() {
  3236. nc.bw.appendString(fmt.Sprintf(subProto, subj, queue, sub.sid))
  3237. nc.kickFlusher()
  3238. }
  3239. return sub, nil
  3240. }
  3241. // NumSubscriptions returns active number of subscriptions.
  3242. func (nc *Conn) NumSubscriptions() int {
  3243. nc.mu.RLock()
  3244. defer nc.mu.RUnlock()
  3245. return len(nc.subs)
  3246. }
  3247. // Lock for nc should be held here upon entry
  3248. func (nc *Conn) removeSub(s *Subscription) {
  3249. nc.subsMu.Lock()
  3250. delete(nc.subs, s.sid)
  3251. nc.subsMu.Unlock()
  3252. s.mu.Lock()
  3253. defer s.mu.Unlock()
  3254. // Release callers on NextMsg for SyncSubscription only
  3255. if s.mch != nil && s.typ == SyncSubscription {
  3256. close(s.mch)
  3257. }
  3258. s.mch = nil
  3259. // Mark as invalid
  3260. s.closed = true
  3261. if s.pCond != nil {
  3262. s.pCond.Broadcast()
  3263. }
  3264. }
  3265. // SubscriptionType is the type of the Subscription.
  3266. type SubscriptionType int
  3267. // The different types of subscription types.
  3268. const (
  3269. AsyncSubscription = SubscriptionType(iota)
  3270. SyncSubscription
  3271. ChanSubscription
  3272. NilSubscription
  3273. PullSubscription
  3274. )
  3275. // Type returns the type of Subscription.
  3276. func (s *Subscription) Type() SubscriptionType {
  3277. if s == nil {
  3278. return NilSubscription
  3279. }
  3280. s.mu.Lock()
  3281. defer s.mu.Unlock()
  3282. return s.typ
  3283. }
  3284. // IsValid returns a boolean indicating whether the subscription
  3285. // is still active. This will return false if the subscription has
  3286. // already been closed.
  3287. func (s *Subscription) IsValid() bool {
  3288. if s == nil {
  3289. return false
  3290. }
  3291. s.mu.Lock()
  3292. defer s.mu.Unlock()
  3293. return s.conn != nil && !s.closed
  3294. }
  3295. // Drain will remove interest but continue callbacks until all messages
  3296. // have been processed.
  3297. func (s *Subscription) Drain() error {
  3298. if s == nil {
  3299. return ErrBadSubscription
  3300. }
  3301. s.mu.Lock()
  3302. conn := s.conn
  3303. s.mu.Unlock()
  3304. if conn == nil {
  3305. return ErrBadSubscription
  3306. }
  3307. return conn.unsubscribe(s, 0, true)
  3308. }
  3309. // Unsubscribe will remove interest in the given subject.
  3310. func (s *Subscription) Unsubscribe() error {
  3311. if s == nil {
  3312. return ErrBadSubscription
  3313. }
  3314. s.mu.Lock()
  3315. conn := s.conn
  3316. closed := s.closed
  3317. s.mu.Unlock()
  3318. if conn == nil || conn.IsClosed() {
  3319. return ErrConnectionClosed
  3320. }
  3321. if closed {
  3322. return ErrBadSubscription
  3323. }
  3324. if conn.IsDraining() {
  3325. return ErrConnectionDraining
  3326. }
  3327. return conn.unsubscribe(s, 0, false)
  3328. }
  3329. // checkDrained will watch for a subscription to be fully drained
  3330. // and then remove it.
  3331. func (nc *Conn) checkDrained(sub *Subscription) {
  3332. if nc == nil || sub == nil {
  3333. return
  3334. }
  3335. // This allows us to know that whatever we have in the client pending
  3336. // is correct and the server will not send additional information.
  3337. nc.Flush()
  3338. // Once we are here we just wait for Pending to reach 0 or
  3339. // any other state to exit this go routine.
  3340. for {
  3341. // check connection is still valid.
  3342. if nc.IsClosed() {
  3343. return
  3344. }
  3345. // Check subscription state
  3346. sub.mu.Lock()
  3347. conn := sub.conn
  3348. closed := sub.closed
  3349. pMsgs := sub.pMsgs
  3350. sub.mu.Unlock()
  3351. if conn == nil || closed || pMsgs == 0 {
  3352. nc.mu.Lock()
  3353. nc.removeSub(sub)
  3354. nc.mu.Unlock()
  3355. return
  3356. }
  3357. time.Sleep(100 * time.Millisecond)
  3358. }
  3359. }
  3360. // AutoUnsubscribe will issue an automatic Unsubscribe that is
  3361. // processed by the server when max messages have been received.
  3362. // This can be useful when sending a request to an unknown number
  3363. // of subscribers.
  3364. func (s *Subscription) AutoUnsubscribe(max int) error {
  3365. if s == nil {
  3366. return ErrBadSubscription
  3367. }
  3368. s.mu.Lock()
  3369. conn := s.conn
  3370. closed := s.closed
  3371. s.mu.Unlock()
  3372. if conn == nil || closed {
  3373. return ErrBadSubscription
  3374. }
  3375. return conn.unsubscribe(s, max, false)
  3376. }
  3377. // unsubscribe performs the low level unsubscribe to the server.
  3378. // Use Subscription.Unsubscribe()
  3379. func (nc *Conn) unsubscribe(sub *Subscription, max int, drainMode bool) error {
  3380. // For JetStream consumers, need to clean up ephemeral consumers
  3381. // or delete durable ones if called with Unsubscribe.
  3382. sub.mu.Lock()
  3383. jsi := sub.jsi
  3384. sub.mu.Unlock()
  3385. if jsi != nil {
  3386. err := jsi.unsubscribe(drainMode)
  3387. if err != nil {
  3388. return err
  3389. }
  3390. }
  3391. nc.mu.Lock()
  3392. // ok here, but defer is expensive
  3393. defer nc.mu.Unlock()
  3394. defer nc.kickFlusher()
  3395. if nc.isClosed() {
  3396. return ErrConnectionClosed
  3397. }
  3398. nc.subsMu.RLock()
  3399. s := nc.subs[sub.sid]
  3400. nc.subsMu.RUnlock()
  3401. // Already unsubscribed
  3402. if s == nil {
  3403. return nil
  3404. }
  3405. maxStr := _EMPTY_
  3406. if max > 0 {
  3407. s.mu.Lock()
  3408. s.max = uint64(max)
  3409. s.mu.Unlock()
  3410. maxStr = strconv.Itoa(max)
  3411. } else if !drainMode {
  3412. nc.removeSub(s)
  3413. }
  3414. if drainMode {
  3415. go nc.checkDrained(sub)
  3416. }
  3417. // We will send these for all subs when we reconnect
  3418. // so that we can suppress here.
  3419. if !nc.isReconnecting() {
  3420. nc.bw.appendString(fmt.Sprintf(unsubProto, s.sid, maxStr))
  3421. nc.kickFlusher()
  3422. }
  3423. return nil
  3424. }
  3425. // NextMsg will return the next message available to a synchronous subscriber
  3426. // or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription),
  3427. // the connection is closed (ErrConnectionClosed), the timeout is reached (ErrTimeout),
  3428. // or if there were no responders (ErrNoResponders) when used in the context of a request/reply.
  3429. func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
  3430. if s == nil {
  3431. return nil, ErrBadSubscription
  3432. }
  3433. s.mu.Lock()
  3434. err := s.validateNextMsgState()
  3435. if err != nil {
  3436. s.mu.Unlock()
  3437. return nil, err
  3438. }
  3439. // snapshot
  3440. mch := s.mch
  3441. s.mu.Unlock()
  3442. var ok bool
  3443. var msg *Msg
  3444. // If something is available right away, let's optimize that case.
  3445. select {
  3446. case msg, ok = <-mch:
  3447. if !ok {
  3448. return nil, s.getNextMsgErr()
  3449. }
  3450. if err := s.processNextMsgDelivered(msg); err != nil {
  3451. return nil, err
  3452. } else {
  3453. return msg, nil
  3454. }
  3455. default:
  3456. }
  3457. // If we are here a message was not immediately available, so lets loop
  3458. // with a timeout.
  3459. t := globalTimerPool.Get(timeout)
  3460. defer globalTimerPool.Put(t)
  3461. select {
  3462. case msg, ok = <-mch:
  3463. if !ok {
  3464. return nil, s.getNextMsgErr()
  3465. }
  3466. if err := s.processNextMsgDelivered(msg); err != nil {
  3467. return nil, err
  3468. }
  3469. case <-t.C:
  3470. return nil, ErrTimeout
  3471. }
  3472. return msg, nil
  3473. }
  3474. // validateNextMsgState checks whether the subscription is in a valid
  3475. // state to call NextMsg and be delivered another message synchronously.
  3476. // This should be called while holding the lock.
  3477. func (s *Subscription) validateNextMsgState() error {
  3478. if s.connClosed {
  3479. return ErrConnectionClosed
  3480. }
  3481. if s.mch == nil {
  3482. if s.max > 0 && s.delivered >= s.max {
  3483. return ErrMaxMessages
  3484. } else if s.closed {
  3485. return ErrBadSubscription
  3486. }
  3487. }
  3488. if s.mcb != nil {
  3489. return ErrSyncSubRequired
  3490. }
  3491. if s.sc {
  3492. s.sc = false
  3493. return ErrSlowConsumer
  3494. }
  3495. return nil
  3496. }
  3497. // This is called when the sync channel has been closed.
  3498. // The error returned will be either connection or subscription
  3499. // closed depending on what caused NextMsg() to fail.
  3500. func (s *Subscription) getNextMsgErr() error {
  3501. s.mu.Lock()
  3502. defer s.mu.Unlock()
  3503. if s.connClosed {
  3504. return ErrConnectionClosed
  3505. }
  3506. return ErrBadSubscription
  3507. }
  3508. // processNextMsgDelivered takes a message and applies the needed
  3509. // accounting to the stats from the subscription, returning an
  3510. // error in case we have the maximum number of messages have been
  3511. // delivered already. It should not be called while holding the lock.
  3512. func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
  3513. s.mu.Lock()
  3514. nc := s.conn
  3515. max := s.max
  3516. // Update some stats.
  3517. s.delivered++
  3518. delivered := s.delivered
  3519. if s.jsi != nil && s.jsi.fc && len(s.jsi.fcs) > 0 {
  3520. s.checkForFlowControlResponse(delivered)
  3521. }
  3522. if s.typ == SyncSubscription {
  3523. s.pMsgs--
  3524. s.pBytes -= len(msg.Data)
  3525. }
  3526. s.mu.Unlock()
  3527. if max > 0 {
  3528. if delivered > max {
  3529. return ErrMaxMessages
  3530. }
  3531. // Remove subscription if we have reached max.
  3532. if delivered == max {
  3533. nc.mu.Lock()
  3534. nc.removeSub(s)
  3535. nc.mu.Unlock()
  3536. }
  3537. }
  3538. if len(msg.Data) == 0 && msg.Header.Get(statusHdr) == noResponders {
  3539. return ErrNoResponders
  3540. }
  3541. return nil
  3542. }
  3543. // Queued returns the number of queued messages in the client for this subscription.
  3544. // DEPRECATED: Use Pending()
  3545. func (s *Subscription) QueuedMsgs() (int, error) {
  3546. m, _, err := s.Pending()
  3547. return int(m), err
  3548. }
  3549. // Pending returns the number of queued messages and queued bytes in the client for this subscription.
  3550. func (s *Subscription) Pending() (int, int, error) {
  3551. if s == nil {
  3552. return -1, -1, ErrBadSubscription
  3553. }
  3554. s.mu.Lock()
  3555. defer s.mu.Unlock()
  3556. if s.conn == nil || s.closed {
  3557. return -1, -1, ErrBadSubscription
  3558. }
  3559. if s.typ == ChanSubscription {
  3560. return -1, -1, ErrTypeSubscription
  3561. }
  3562. return s.pMsgs, s.pBytes, nil
  3563. }
  3564. // MaxPending returns the maximum number of queued messages and queued bytes seen so far.
  3565. func (s *Subscription) MaxPending() (int, int, error) {
  3566. if s == nil {
  3567. return -1, -1, ErrBadSubscription
  3568. }
  3569. s.mu.Lock()
  3570. defer s.mu.Unlock()
  3571. if s.conn == nil || s.closed {
  3572. return -1, -1, ErrBadSubscription
  3573. }
  3574. if s.typ == ChanSubscription {
  3575. return -1, -1, ErrTypeSubscription
  3576. }
  3577. return s.pMsgsMax, s.pBytesMax, nil
  3578. }
  3579. // ClearMaxPending resets the maximums seen so far.
  3580. func (s *Subscription) ClearMaxPending() error {
  3581. if s == nil {
  3582. return ErrBadSubscription
  3583. }
  3584. s.mu.Lock()
  3585. defer s.mu.Unlock()
  3586. if s.conn == nil || s.closed {
  3587. return ErrBadSubscription
  3588. }
  3589. if s.typ == ChanSubscription {
  3590. return ErrTypeSubscription
  3591. }
  3592. s.pMsgsMax, s.pBytesMax = 0, 0
  3593. return nil
  3594. }
  3595. // Pending Limits
  3596. const (
  3597. // DefaultSubPendingMsgsLimit will be 512k msgs.
  3598. DefaultSubPendingMsgsLimit = 512 * 1024
  3599. // DefaultSubPendingBytesLimit is 64MB
  3600. DefaultSubPendingBytesLimit = 64 * 1024 * 1024
  3601. )
  3602. // PendingLimits returns the current limits for this subscription.
  3603. // If no error is returned, a negative value indicates that the
  3604. // given metric is not limited.
  3605. func (s *Subscription) PendingLimits() (int, int, error) {
  3606. if s == nil {
  3607. return -1, -1, ErrBadSubscription
  3608. }
  3609. s.mu.Lock()
  3610. defer s.mu.Unlock()
  3611. if s.conn == nil || s.closed {
  3612. return -1, -1, ErrBadSubscription
  3613. }
  3614. if s.typ == ChanSubscription {
  3615. return -1, -1, ErrTypeSubscription
  3616. }
  3617. return s.pMsgsLimit, s.pBytesLimit, nil
  3618. }
  3619. // SetPendingLimits sets the limits for pending msgs and bytes for this subscription.
  3620. // Zero is not allowed. Any negative value means that the given metric is not limited.
  3621. func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error {
  3622. if s == nil {
  3623. return ErrBadSubscription
  3624. }
  3625. s.mu.Lock()
  3626. defer s.mu.Unlock()
  3627. if s.conn == nil || s.closed {
  3628. return ErrBadSubscription
  3629. }
  3630. if s.typ == ChanSubscription {
  3631. return ErrTypeSubscription
  3632. }
  3633. if msgLimit == 0 || bytesLimit == 0 {
  3634. return ErrInvalidArg
  3635. }
  3636. s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit
  3637. return nil
  3638. }
  3639. // Delivered returns the number of delivered messages for this subscription.
  3640. func (s *Subscription) Delivered() (int64, error) {
  3641. if s == nil {
  3642. return -1, ErrBadSubscription
  3643. }
  3644. s.mu.Lock()
  3645. defer s.mu.Unlock()
  3646. if s.conn == nil || s.closed {
  3647. return -1, ErrBadSubscription
  3648. }
  3649. return int64(s.delivered), nil
  3650. }
  3651. // Dropped returns the number of known dropped messages for this subscription.
  3652. // This will correspond to messages dropped by violations of PendingLimits. If
  3653. // the server declares the connection a SlowConsumer, this number may not be
  3654. // valid.
  3655. func (s *Subscription) Dropped() (int, error) {
  3656. if s == nil {
  3657. return -1, ErrBadSubscription
  3658. }
  3659. s.mu.Lock()
  3660. defer s.mu.Unlock()
  3661. if s.conn == nil || s.closed {
  3662. return -1, ErrBadSubscription
  3663. }
  3664. return s.dropped, nil
  3665. }
  3666. // Respond allows a convenient way to respond to requests in service based subscriptions.
  3667. func (m *Msg) Respond(data []byte) error {
  3668. if m == nil || m.Sub == nil {
  3669. return ErrMsgNotBound
  3670. }
  3671. if m.Reply == "" {
  3672. return ErrMsgNoReply
  3673. }
  3674. m.Sub.mu.Lock()
  3675. nc := m.Sub.conn
  3676. m.Sub.mu.Unlock()
  3677. // No need to check the connection here since the call to publish will do all the checking.
  3678. return nc.Publish(m.Reply, data)
  3679. }
  3680. // RespondMsg allows a convenient way to respond to requests in service based subscriptions that might include headers
  3681. func (m *Msg) RespondMsg(msg *Msg) error {
  3682. if m == nil || m.Sub == nil {
  3683. return ErrMsgNotBound
  3684. }
  3685. if m.Reply == "" {
  3686. return ErrMsgNoReply
  3687. }
  3688. msg.Subject = m.Reply
  3689. m.Sub.mu.Lock()
  3690. nc := m.Sub.conn
  3691. m.Sub.mu.Unlock()
  3692. // No need to check the connection here since the call to publish will do all the checking.
  3693. return nc.PublishMsg(msg)
  3694. }
  3695. // FIXME: This is a hack
  3696. // removeFlushEntry is needed when we need to discard queued up responses
  3697. // for our pings as part of a flush call. This happens when we have a flush
  3698. // call outstanding and we call close.
  3699. func (nc *Conn) removeFlushEntry(ch chan struct{}) bool {
  3700. nc.mu.Lock()
  3701. defer nc.mu.Unlock()
  3702. if nc.pongs == nil {
  3703. return false
  3704. }
  3705. for i, c := range nc.pongs {
  3706. if c == ch {
  3707. nc.pongs[i] = nil
  3708. return true
  3709. }
  3710. }
  3711. return false
  3712. }
  3713. // The lock must be held entering this function.
  3714. func (nc *Conn) sendPing(ch chan struct{}) {
  3715. nc.pongs = append(nc.pongs, ch)
  3716. nc.bw.appendString(pingProto)
  3717. // Flush in place.
  3718. nc.bw.flush()
  3719. }
  3720. // This will fire periodically and send a client origin
  3721. // ping to the server. Will also check that we have received
  3722. // responses from the server.
  3723. func (nc *Conn) processPingTimer() {
  3724. nc.mu.Lock()
  3725. if nc.status != CONNECTED {
  3726. nc.mu.Unlock()
  3727. return
  3728. }
  3729. // Check for violation
  3730. nc.pout++
  3731. if nc.pout > nc.Opts.MaxPingsOut {
  3732. nc.mu.Unlock()
  3733. nc.processOpErr(ErrStaleConnection)
  3734. return
  3735. }
  3736. nc.sendPing(nil)
  3737. nc.ptmr.Reset(nc.Opts.PingInterval)
  3738. nc.mu.Unlock()
  3739. }
  3740. // FlushTimeout allows a Flush operation to have an associated timeout.
  3741. func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) {
  3742. if nc == nil {
  3743. return ErrInvalidConnection
  3744. }
  3745. if timeout <= 0 {
  3746. return ErrBadTimeout
  3747. }
  3748. nc.mu.Lock()
  3749. if nc.isClosed() {
  3750. nc.mu.Unlock()
  3751. return ErrConnectionClosed
  3752. }
  3753. t := globalTimerPool.Get(timeout)
  3754. defer globalTimerPool.Put(t)
  3755. // Create a buffered channel to prevent chan send to block
  3756. // in processPong() if this code here times out just when
  3757. // PONG was received.
  3758. ch := make(chan struct{}, 1)
  3759. nc.sendPing(ch)
  3760. nc.mu.Unlock()
  3761. select {
  3762. case _, ok := <-ch:
  3763. if !ok {
  3764. err = ErrConnectionClosed
  3765. } else {
  3766. close(ch)
  3767. }
  3768. case <-t.C:
  3769. err = ErrTimeout
  3770. }
  3771. if err != nil {
  3772. nc.removeFlushEntry(ch)
  3773. }
  3774. return
  3775. }
  3776. // RTT calculates the round trip time between this client and the server.
  3777. func (nc *Conn) RTT() (time.Duration, error) {
  3778. if nc.IsClosed() {
  3779. return 0, ErrConnectionClosed
  3780. }
  3781. if nc.IsReconnecting() {
  3782. return 0, ErrDisconnected
  3783. }
  3784. start := time.Now()
  3785. if err := nc.FlushTimeout(10 * time.Second); err != nil {
  3786. return 0, err
  3787. }
  3788. return time.Since(start), nil
  3789. }
  3790. // Flush will perform a round trip to the server and return when it
  3791. // receives the internal reply.
  3792. func (nc *Conn) Flush() error {
  3793. return nc.FlushTimeout(10 * time.Second)
  3794. }
  3795. // Buffered will return the number of bytes buffered to be sent to the server.
  3796. // FIXME(dlc) take into account disconnected state.
  3797. func (nc *Conn) Buffered() (int, error) {
  3798. nc.mu.RLock()
  3799. defer nc.mu.RUnlock()
  3800. if nc.isClosed() || nc.bw == nil {
  3801. return -1, ErrConnectionClosed
  3802. }
  3803. return nc.bw.buffered(), nil
  3804. }
  3805. // resendSubscriptions will send our subscription state back to the
  3806. // server. Used in reconnects
  3807. func (nc *Conn) resendSubscriptions() {
  3808. // Since we are going to send protocols to the server, we don't want to
  3809. // be holding the subsMu lock (which is used in processMsg). So copy
  3810. // the subscriptions in a temporary array.
  3811. nc.subsMu.RLock()
  3812. subs := make([]*Subscription, 0, len(nc.subs))
  3813. for _, s := range nc.subs {
  3814. subs = append(subs, s)
  3815. }
  3816. nc.subsMu.RUnlock()
  3817. for _, s := range subs {
  3818. adjustedMax := uint64(0)
  3819. s.mu.Lock()
  3820. if s.max > 0 {
  3821. if s.delivered < s.max {
  3822. adjustedMax = s.max - s.delivered
  3823. }
  3824. // adjustedMax could be 0 here if the number of delivered msgs
  3825. // reached the max, if so unsubscribe.
  3826. if adjustedMax == 0 {
  3827. s.mu.Unlock()
  3828. nc.bw.writeDirect(fmt.Sprintf(unsubProto, s.sid, _EMPTY_))
  3829. continue
  3830. }
  3831. }
  3832. s.mu.Unlock()
  3833. nc.bw.writeDirect(fmt.Sprintf(subProto, s.Subject, s.Queue, s.sid))
  3834. if adjustedMax > 0 {
  3835. maxStr := strconv.Itoa(int(adjustedMax))
  3836. nc.bw.writeDirect(fmt.Sprintf(unsubProto, s.sid, maxStr))
  3837. }
  3838. }
  3839. }
  3840. // This will clear any pending flush calls and release pending calls.
  3841. // Lock is assumed to be held by the caller.
  3842. func (nc *Conn) clearPendingFlushCalls() {
  3843. // Clear any queued pongs, e.g. pending flush calls.
  3844. for _, ch := range nc.pongs {
  3845. if ch != nil {
  3846. close(ch)
  3847. }
  3848. }
  3849. nc.pongs = nil
  3850. }
  3851. // This will clear any pending Request calls.
  3852. // Lock is assumed to be held by the caller.
  3853. func (nc *Conn) clearPendingRequestCalls() {
  3854. if nc.respMap == nil {
  3855. return
  3856. }
  3857. for key, ch := range nc.respMap {
  3858. if ch != nil {
  3859. close(ch)
  3860. delete(nc.respMap, key)
  3861. }
  3862. }
  3863. }
  3864. // Low level close call that will do correct cleanup and set
  3865. // desired status. Also controls whether user defined callbacks
  3866. // will be triggered. The lock should not be held entering this
  3867. // function. This function will handle the locking manually.
  3868. func (nc *Conn) close(status Status, doCBs bool, err error) {
  3869. nc.mu.Lock()
  3870. if nc.isClosed() {
  3871. nc.status = status
  3872. nc.mu.Unlock()
  3873. return
  3874. }
  3875. nc.status = CLOSED
  3876. // Kick the Go routines so they fall out.
  3877. nc.kickFlusher()
  3878. // If the reconnect timer is waiting between a reconnect attempt,
  3879. // this will kick it out.
  3880. if nc.rqch != nil {
  3881. close(nc.rqch)
  3882. nc.rqch = nil
  3883. }
  3884. // Clear any queued pongs, e.g. pending flush calls.
  3885. nc.clearPendingFlushCalls()
  3886. // Clear any queued and blocking Requests.
  3887. nc.clearPendingRequestCalls()
  3888. // Stop ping timer if set.
  3889. nc.stopPingTimer()
  3890. nc.ptmr = nil
  3891. // Need to close and set tcp conn to nil if reconnect loop has stopped,
  3892. // otherwise we would incorrectly invoke Disconnect handler (if set)
  3893. // down below.
  3894. if nc.ar && nc.conn != nil {
  3895. nc.conn.Close()
  3896. nc.conn = nil
  3897. } else if nc.conn != nil {
  3898. // Go ahead and make sure we have flushed the outbound
  3899. nc.bw.flush()
  3900. defer nc.conn.Close()
  3901. }
  3902. // Close sync subscriber channels and release any
  3903. // pending NextMsg() calls.
  3904. nc.subsMu.Lock()
  3905. for _, s := range nc.subs {
  3906. s.mu.Lock()
  3907. // Release callers on NextMsg for SyncSubscription only
  3908. if s.mch != nil && s.typ == SyncSubscription {
  3909. close(s.mch)
  3910. }
  3911. s.mch = nil
  3912. // Mark as invalid, for signaling to deliverMsgs
  3913. s.closed = true
  3914. // Mark connection closed in subscription
  3915. s.connClosed = true
  3916. // If we have an async subscription, signals it to exit
  3917. if s.typ == AsyncSubscription && s.pCond != nil {
  3918. s.pCond.Signal()
  3919. }
  3920. s.mu.Unlock()
  3921. }
  3922. nc.subs = nil
  3923. nc.subsMu.Unlock()
  3924. nc.status = status
  3925. // Perform appropriate callback if needed for a disconnect.
  3926. if doCBs {
  3927. if nc.conn != nil {
  3928. if nc.Opts.DisconnectedErrCB != nil {
  3929. nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) })
  3930. } else if nc.Opts.DisconnectedCB != nil {
  3931. nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
  3932. }
  3933. }
  3934. if nc.Opts.ClosedCB != nil {
  3935. nc.ach.push(func() { nc.Opts.ClosedCB(nc) })
  3936. }
  3937. }
  3938. // If this is terminal, then we have to notify the asyncCB handler that
  3939. // it can exit once all async cbs have been dispatched.
  3940. if status == CLOSED {
  3941. nc.ach.close()
  3942. }
  3943. nc.mu.Unlock()
  3944. }
  3945. // Close will close the connection to the server. This call will release
  3946. // all blocking calls, such as Flush() and NextMsg()
  3947. func (nc *Conn) Close() {
  3948. if nc != nil {
  3949. // This will be a no-op if the connection was not websocket.
  3950. // We do this here as opposed to inside close() because we want
  3951. // to do this only for the final user-driven close of the client.
  3952. // Otherwise, we would need to change close() to pass a boolean
  3953. // indicating that this is the case.
  3954. nc.wsClose()
  3955. nc.close(CLOSED, !nc.Opts.NoCallbacksAfterClientClose, nil)
  3956. }
  3957. }
  3958. // IsClosed tests if a Conn has been closed.
  3959. func (nc *Conn) IsClosed() bool {
  3960. nc.mu.RLock()
  3961. defer nc.mu.RUnlock()
  3962. return nc.isClosed()
  3963. }
  3964. // IsReconnecting tests if a Conn is reconnecting.
  3965. func (nc *Conn) IsReconnecting() bool {
  3966. nc.mu.RLock()
  3967. defer nc.mu.RUnlock()
  3968. return nc.isReconnecting()
  3969. }
  3970. // IsConnected tests if a Conn is connected.
  3971. func (nc *Conn) IsConnected() bool {
  3972. nc.mu.RLock()
  3973. defer nc.mu.RUnlock()
  3974. return nc.isConnected()
  3975. }
  3976. // drainConnection will run in a separate Go routine and will
  3977. // flush all publishes and drain all active subscriptions.
  3978. func (nc *Conn) drainConnection() {
  3979. // Snapshot subs list.
  3980. nc.mu.Lock()
  3981. // Check again here if we are in a state to not process.
  3982. if nc.isClosed() {
  3983. nc.mu.Unlock()
  3984. return
  3985. }
  3986. if nc.isConnecting() || nc.isReconnecting() {
  3987. nc.mu.Unlock()
  3988. // Move to closed state.
  3989. nc.Close()
  3990. return
  3991. }
  3992. subs := make([]*Subscription, 0, len(nc.subs))
  3993. for _, s := range nc.subs {
  3994. if s == nc.respMux {
  3995. // Skip since might be in use while messages
  3996. // are being processed (can miss responses).
  3997. continue
  3998. }
  3999. subs = append(subs, s)
  4000. }
  4001. errCB := nc.Opts.AsyncErrorCB
  4002. drainWait := nc.Opts.DrainTimeout
  4003. respMux := nc.respMux
  4004. nc.mu.Unlock()
  4005. // for pushing errors with context.
  4006. pushErr := func(err error) {
  4007. nc.mu.Lock()
  4008. nc.err = err
  4009. if errCB != nil {
  4010. nc.ach.push(func() { errCB(nc, nil, err) })
  4011. }
  4012. nc.mu.Unlock()
  4013. }
  4014. // Do subs first, skip request handler if present.
  4015. for _, s := range subs {
  4016. if err := s.Drain(); err != nil {
  4017. // We will notify about these but continue.
  4018. pushErr(err)
  4019. }
  4020. }
  4021. // Wait for the subscriptions to drop to zero.
  4022. timeout := time.Now().Add(drainWait)
  4023. var min int
  4024. if respMux != nil {
  4025. min = 1
  4026. } else {
  4027. min = 0
  4028. }
  4029. for time.Now().Before(timeout) {
  4030. if nc.NumSubscriptions() == min {
  4031. break
  4032. }
  4033. time.Sleep(10 * time.Millisecond)
  4034. }
  4035. // In case there was a request/response handler
  4036. // then need to call drain at the end.
  4037. if respMux != nil {
  4038. if err := respMux.Drain(); err != nil {
  4039. // We will notify about these but continue.
  4040. pushErr(err)
  4041. }
  4042. for time.Now().Before(timeout) {
  4043. if nc.NumSubscriptions() == 0 {
  4044. break
  4045. }
  4046. time.Sleep(10 * time.Millisecond)
  4047. }
  4048. }
  4049. // Check if we timed out.
  4050. if nc.NumSubscriptions() != 0 {
  4051. pushErr(ErrDrainTimeout)
  4052. }
  4053. // Flip State
  4054. nc.mu.Lock()
  4055. nc.status = DRAINING_PUBS
  4056. nc.mu.Unlock()
  4057. // Do publish drain via Flush() call.
  4058. err := nc.FlushTimeout(5 * time.Second)
  4059. if err != nil {
  4060. pushErr(err)
  4061. }
  4062. // Move to closed state.
  4063. nc.Close()
  4064. }
  4065. // Drain will put a connection into a drain state. All subscriptions will
  4066. // immediately be put into a drain state. Upon completion, the publishers
  4067. // will be drained and can not publish any additional messages. Upon draining
  4068. // of the publishers, the connection will be closed. Use the ClosedCB()
  4069. // option to know when the connection has moved from draining to closed.
  4070. func (nc *Conn) Drain() error {
  4071. nc.mu.Lock()
  4072. if nc.isClosed() {
  4073. nc.mu.Unlock()
  4074. return ErrConnectionClosed
  4075. }
  4076. if nc.isConnecting() || nc.isReconnecting() {
  4077. nc.mu.Unlock()
  4078. nc.Close()
  4079. return ErrConnectionReconnecting
  4080. }
  4081. if nc.isDraining() {
  4082. nc.mu.Unlock()
  4083. return nil
  4084. }
  4085. nc.status = DRAINING_SUBS
  4086. go nc.drainConnection()
  4087. nc.mu.Unlock()
  4088. return nil
  4089. }
  4090. // IsDraining tests if a Conn is in the draining state.
  4091. func (nc *Conn) IsDraining() bool {
  4092. nc.mu.RLock()
  4093. defer nc.mu.RUnlock()
  4094. return nc.isDraining()
  4095. }
  4096. // caller must lock
  4097. func (nc *Conn) getServers(implicitOnly bool) []string {
  4098. poolSize := len(nc.srvPool)
  4099. var servers = make([]string, 0)
  4100. for i := 0; i < poolSize; i++ {
  4101. if implicitOnly && !nc.srvPool[i].isImplicit {
  4102. continue
  4103. }
  4104. url := nc.srvPool[i].url
  4105. servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
  4106. }
  4107. return servers
  4108. }
  4109. // Servers returns the list of known server urls, including additional
  4110. // servers discovered after a connection has been established. If
  4111. // authentication is enabled, use UserInfo or Token when connecting with
  4112. // these urls.
  4113. func (nc *Conn) Servers() []string {
  4114. nc.mu.RLock()
  4115. defer nc.mu.RUnlock()
  4116. return nc.getServers(false)
  4117. }
  4118. // DiscoveredServers returns only the server urls that have been discovered
  4119. // after a connection has been established. If authentication is enabled,
  4120. // use UserInfo or Token when connecting with these urls.
  4121. func (nc *Conn) DiscoveredServers() []string {
  4122. nc.mu.RLock()
  4123. defer nc.mu.RUnlock()
  4124. return nc.getServers(true)
  4125. }
  4126. // Status returns the current state of the connection.
  4127. func (nc *Conn) Status() Status {
  4128. nc.mu.RLock()
  4129. defer nc.mu.RUnlock()
  4130. return nc.status
  4131. }
  4132. // Test if Conn has been closed Lock is assumed held.
  4133. func (nc *Conn) isClosed() bool {
  4134. return nc.status == CLOSED
  4135. }
  4136. // Test if Conn is in the process of connecting
  4137. func (nc *Conn) isConnecting() bool {
  4138. return nc.status == CONNECTING
  4139. }
  4140. // Test if Conn is being reconnected.
  4141. func (nc *Conn) isReconnecting() bool {
  4142. return nc.status == RECONNECTING
  4143. }
  4144. // Test if Conn is connected or connecting.
  4145. func (nc *Conn) isConnected() bool {
  4146. return nc.status == CONNECTED || nc.isDraining()
  4147. }
  4148. // Test if Conn is in the draining state.
  4149. func (nc *Conn) isDraining() bool {
  4150. return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
  4151. }
  4152. // Test if Conn is in the draining state for pubs.
  4153. func (nc *Conn) isDrainingPubs() bool {
  4154. return nc.status == DRAINING_PUBS
  4155. }
  4156. // Stats will return a race safe copy of the Statistics section for the connection.
  4157. func (nc *Conn) Stats() Statistics {
  4158. // Stats are updated either under connection's mu or with atomic operations
  4159. // for inbound stats in processMsg().
  4160. nc.mu.Lock()
  4161. stats := Statistics{
  4162. InMsgs: atomic.LoadUint64(&nc.InMsgs),
  4163. InBytes: atomic.LoadUint64(&nc.InBytes),
  4164. OutMsgs: nc.OutMsgs,
  4165. OutBytes: nc.OutBytes,
  4166. Reconnects: nc.Reconnects,
  4167. }
  4168. nc.mu.Unlock()
  4169. return stats
  4170. }
  4171. // MaxPayload returns the size limit that a message payload can have.
  4172. // This is set by the server configuration and delivered to the client
  4173. // upon connect.
  4174. func (nc *Conn) MaxPayload() int64 {
  4175. nc.mu.RLock()
  4176. defer nc.mu.RUnlock()
  4177. return nc.info.MaxPayload
  4178. }
  4179. // HeadersSupported will return if the server supports headers
  4180. func (nc *Conn) HeadersSupported() bool {
  4181. nc.mu.RLock()
  4182. defer nc.mu.RUnlock()
  4183. return nc.info.Headers
  4184. }
  4185. // AuthRequired will return if the connected server requires authorization.
  4186. func (nc *Conn) AuthRequired() bool {
  4187. nc.mu.RLock()
  4188. defer nc.mu.RUnlock()
  4189. return nc.info.AuthRequired
  4190. }
  4191. // TLSRequired will return if the connected server requires TLS connections.
  4192. func (nc *Conn) TLSRequired() bool {
  4193. nc.mu.RLock()
  4194. defer nc.mu.RUnlock()
  4195. return nc.info.TLSRequired
  4196. }
  4197. // Barrier schedules the given function `f` to all registered asynchronous
  4198. // subscriptions.
  4199. // Only the last subscription to see this barrier will invoke the function.
  4200. // If no subscription is registered at the time of this call, `f()` is invoked
  4201. // right away.
  4202. // ErrConnectionClosed is returned if the connection is closed prior to
  4203. // the call.
  4204. func (nc *Conn) Barrier(f func()) error {
  4205. nc.mu.Lock()
  4206. if nc.isClosed() {
  4207. nc.mu.Unlock()
  4208. return ErrConnectionClosed
  4209. }
  4210. nc.subsMu.Lock()
  4211. // Need to figure out how many non chan subscriptions there are
  4212. numSubs := 0
  4213. for _, sub := range nc.subs {
  4214. if sub.typ == AsyncSubscription {
  4215. numSubs++
  4216. }
  4217. }
  4218. if numSubs == 0 {
  4219. nc.subsMu.Unlock()
  4220. nc.mu.Unlock()
  4221. f()
  4222. return nil
  4223. }
  4224. barrier := &barrierInfo{refs: int64(numSubs), f: f}
  4225. for _, sub := range nc.subs {
  4226. sub.mu.Lock()
  4227. if sub.mch == nil {
  4228. msg := &Msg{barrier: barrier}
  4229. // Push onto the async pList
  4230. if sub.pTail != nil {
  4231. sub.pTail.next = msg
  4232. } else {
  4233. sub.pHead = msg
  4234. sub.pCond.Signal()
  4235. }
  4236. sub.pTail = msg
  4237. }
  4238. sub.mu.Unlock()
  4239. }
  4240. nc.subsMu.Unlock()
  4241. nc.mu.Unlock()
  4242. return nil
  4243. }
  4244. // GetClientIP returns the client IP as known by the server.
  4245. // Supported as of server version 2.1.6.
  4246. func (nc *Conn) GetClientIP() (net.IP, error) {
  4247. nc.mu.RLock()
  4248. defer nc.mu.RUnlock()
  4249. if nc.isClosed() {
  4250. return nil, ErrConnectionClosed
  4251. }
  4252. if nc.info.ClientIP == "" {
  4253. return nil, ErrClientIPNotSupported
  4254. }
  4255. ip := net.ParseIP(nc.info.ClientIP)
  4256. return ip, nil
  4257. }
  4258. // GetClientID returns the client ID assigned by the server to which
  4259. // the client is currently connected to. Note that the value may change if
  4260. // the client reconnects.
  4261. // This function returns ErrClientIDNotSupported if the server is of a
  4262. // version prior to 1.2.0.
  4263. func (nc *Conn) GetClientID() (uint64, error) {
  4264. nc.mu.RLock()
  4265. defer nc.mu.RUnlock()
  4266. if nc.isClosed() {
  4267. return 0, ErrConnectionClosed
  4268. }
  4269. if nc.info.CID == 0 {
  4270. return 0, ErrClientIDNotSupported
  4271. }
  4272. return nc.info.CID, nil
  4273. }
  4274. // NkeyOptionFromSeed will load an nkey pair from a seed file.
  4275. // It will return the NKey Option and will handle
  4276. // signing of nonce challenges from the server. It will take
  4277. // care to not hold keys in memory and to wipe memory.
  4278. func NkeyOptionFromSeed(seedFile string) (Option, error) {
  4279. kp, err := nkeyPairFromSeedFile(seedFile)
  4280. if err != nil {
  4281. return nil, err
  4282. }
  4283. // Wipe our key on exit.
  4284. defer kp.Wipe()
  4285. pub, err := kp.PublicKey()
  4286. if err != nil {
  4287. return nil, err
  4288. }
  4289. if !nkeys.IsValidPublicUserKey(pub) {
  4290. return nil, fmt.Errorf("nats: Not a valid nkey user seed")
  4291. }
  4292. sigCB := func(nonce []byte) ([]byte, error) {
  4293. return sigHandler(nonce, seedFile)
  4294. }
  4295. return Nkey(string(pub), sigCB), nil
  4296. }
  4297. // Just wipe slice with 'x', for clearing contents of creds or nkey seed file.
  4298. func wipeSlice(buf []byte) {
  4299. for i := range buf {
  4300. buf[i] = 'x'
  4301. }
  4302. }
  4303. func userFromFile(userFile string) (string, error) {
  4304. path, err := expandPath(userFile)
  4305. if err != nil {
  4306. return _EMPTY_, fmt.Errorf("nats: %v", err)
  4307. }
  4308. contents, err := ioutil.ReadFile(path)
  4309. if err != nil {
  4310. return _EMPTY_, fmt.Errorf("nats: %v", err)
  4311. }
  4312. defer wipeSlice(contents)
  4313. return nkeys.ParseDecoratedJWT(contents)
  4314. }
  4315. func homeDir() (string, error) {
  4316. if runtime.GOOS == "windows" {
  4317. homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
  4318. userProfile := os.Getenv("USERPROFILE")
  4319. var home string
  4320. if homeDrive == "" || homePath == "" {
  4321. if userProfile == "" {
  4322. return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
  4323. }
  4324. home = userProfile
  4325. } else {
  4326. home = filepath.Join(homeDrive, homePath)
  4327. }
  4328. return home, nil
  4329. }
  4330. home := os.Getenv("HOME")
  4331. if home == "" {
  4332. return _EMPTY_, errors.New("nats: failed to get home dir, require $HOME")
  4333. }
  4334. return home, nil
  4335. }
  4336. func expandPath(p string) (string, error) {
  4337. p = os.ExpandEnv(p)
  4338. if !strings.HasPrefix(p, "~") {
  4339. return p, nil
  4340. }
  4341. home, err := homeDir()
  4342. if err != nil {
  4343. return _EMPTY_, err
  4344. }
  4345. return filepath.Join(home, p[1:]), nil
  4346. }
  4347. func nkeyPairFromSeedFile(seedFile string) (nkeys.KeyPair, error) {
  4348. contents, err := ioutil.ReadFile(seedFile)
  4349. if err != nil {
  4350. return nil, fmt.Errorf("nats: %v", err)
  4351. }
  4352. defer wipeSlice(contents)
  4353. return nkeys.ParseDecoratedNKey(contents)
  4354. }
  4355. // Sign authentication challenges from the server.
  4356. // Do not keep private seed in memory.
  4357. func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
  4358. kp, err := nkeyPairFromSeedFile(seedFile)
  4359. if err != nil {
  4360. return nil, err
  4361. }
  4362. // Wipe our key on exit.
  4363. defer kp.Wipe()
  4364. sig, _ := kp.Sign(nonce)
  4365. return sig, nil
  4366. }
  4367. type timeoutWriter struct {
  4368. timeout time.Duration
  4369. conn net.Conn
  4370. err error
  4371. }
  4372. // Write implements the io.Writer interface.
  4373. func (tw *timeoutWriter) Write(p []byte) (int, error) {
  4374. if tw.err != nil {
  4375. return 0, tw.err
  4376. }
  4377. var n int
  4378. tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout))
  4379. n, tw.err = tw.conn.Write(p)
  4380. tw.conn.SetWriteDeadline(time.Time{})
  4381. return n, tw.err
  4382. }